mercredi 31 août 2016

Calculate and print average gpa with C++

I have the following problem:

1) Declare a class name studentExample with private elements: id - integer gpa - float

I need to create a default constructor that initializes the id to 111222333 and the gpa to 0.0 and a void function getId that returns the id of an object.

2) Declare an array of 10 objects of the class studentExample named student.

3) Assuming the array is filled (10 sets of values have been entered into the array).

Print the id of each student

Calculate and print the average gpa of those 10 students.

I am very new to C++ and mostly programming. I started with the folowing code:

#include <iostream>
using namespace std; 

class studentType{
private:
    int id;
    float gpa;
public:
    id=111222333;
    gpa=0.0;
    void getID(int id);
}




Calling a method within my class states "incompatible types" even though it isn't?

I have no idea why my class method will not accept the matrix as an input despite it being an int[][].

Here's my main:

        public class Lab1 {
            public static void main(String[] args) {
                Matrix One = new Matrix(3, 3);

                Matrix.viewMatrix(One);  
            }
        }
/** 
Here's my class called "Matrix":
**/   
        public class Matrix {
            private int rows;
            private int columns;

            Matrix() { 
            }

            Matrix (int rows, int columns) {
                this.rows = rows;
                this.columns = columns; 
                int[][] matrix = new int[rows][columns];
            } // matrix constructor

            public void viewMatrix(int[][] a) {

            } // viewMatrix
        } // class




How do I unload a istance of a class in python

Ok I think it better to give an example on why I would want to do this. Say I had a game. There are some objects that are enemeys these enemeys have a class that is running (health, weapons, ect) If a player kills a enemy I want to unload that enemeys data from the game (removing the enemys instance of the class) How would I go about doing this?




If else statements in Java / calling other class

I need to create a driver program that says if I can fight a ticket or just pay it off. My problem is calling in another class called ticket to create an if else statement. I created an if else statement that will only say to fight the ticket on the last ticket...

(here is the problem im stuck on) **The problem: You are receiving speeding tickets which are automatically generated by a camera. You can FIGHT the ticket if any of the following are true:

• Your recorded speed is <= 11 mph over the limit

what am i doing wrong?

          import java.util.*; //scanner
           public class MinilabUsingClasses

         {
            public static void main (String [] args)
         {
    Scanner kb = new Scanner(System.in);  //creating new instance of scanner
    int numTickets;  //variable for number of tickets
    String name; //variable for name


    System.out.print("How many tickets do you have? " );         //ask user for numtickets
    numTickets = kb.nextInt();

    System.out.print("\nWhat is your name? " );         //ask user for name
    name = kb.next();
    System.out.println("\n");

    for (int i= 1; i <= numTickets; i++)  // use for loop to bring in random ticket info

        {
        Ticket currentTicket = new Ticket(name);
        System.out.println(currentTicket.toString());
        }

    int newSpeed = 0;

    if (newSpeed <= 11)
    {
        System.out.println ("Fight!");
    }
    else if (newSpeed > 11)
    {
        System.out.println("Pay :(");
    }






}

}

      //This class will describe a theoretical "speed camera ticket"

         import java.util.*;     //for random number generator

     public class Ticket
       {
//constant
private final int LIMIT = 55;

//data
private String name;
//private int limit;
private int speed;
private String cameraID;
private String location;

//default constructor - creates a ticket with the name "Bill Gates"
public Ticket()
{
    this("Bill Gates");     //just turns around and calls constructor with single arg
}

//parameterized constructor - this will set all values.  limit and location
//will be constant and the rest will have some randomness built in
public Ticket(String theName)
{
    //random number generator
    Random generator = new Random();

    //local variables
    int rand, len;
    char randomChar;

    //set the name data value
    name = theName;

    //name will have some randomness
    for (int i=0; i<name.length(); i++)
    {
        rand = generator.nextInt(10);     //random int from 0-9
        if (rand < 3)        //3/10 of the time change lowercase <-> uppercase
            if (name.charAt(i) >= 'a' && name.charAt(i) <= 'z')
            {
                //lowercase -> uppercase
                name = name.substring(0,i) + (char)(name.charAt(i)-32) + name.substring(i+1);
            }
            else if (name.charAt(i) >= 'a' && name.charAt(i) <= 'z')
            {
                //uppercase -> lowercase
                name = name.substring(0,i) + (char)(name.charAt(i)+32) + name.substring(i+1);
            }

        rand = generator.nextInt(21);     //random int from 0-20
        if (rand < 1 && name.charAt(i) != ' ')        //1/20 of the time put in a typo (but not for blanks)
        {
            randomChar = (char)(generator.nextInt(94)+33);          //get a randomChar in the ASCII table (33-126)
            name = name.substring(0,i) + randomChar + name.substring(i+1);  //put it in
        }
    }

    //it is programmed for constant location and speed limit
    location = "I-10 and 48th Street";

    //generate pseudorandom "cameraID"
    rand = generator.nextInt(10);     //int between 0-9
    if (rand < 2)
        cameraID = "A";       //starts with A 2/10 of the time
    else
        cameraID = "B";

    //middle digits of varying length
    len = generator.nextInt(4)+4;   //length this part of the ID (3-7 digits)
    for (int i=0; i<len; i++)
        cameraID = cameraID + (char)(generator.nextInt(10)+48);   //concatenate a random digit

    //ends with 35 2/10 of the time
    rand = generator.nextInt(10);
    if (rand < 2)
        cameraID = cameraID + "35";   //concatenate

    //speed is a random number between 6 - 20 mph over the limit
    rand = (int)(Math.random()*20);
    speed = LIMIT + 6 + rand;
}

//getLimit - returns the speed limit the camera was set at
public int getLimit()
{
    return LIMIT;
}

//getSpeed - returns the driver's speed
public int getSpeed()
{
    return speed;
}

//setSpeed - sets the speed to whatever is passed in
public void setSpeed(int newSpeed)
{
    speed = newSpeed;
}


//getName - returns the driver's name
public String getName()
{
    return name;
}

//get getCameraID - returns the cameraNumber
public String getCameraID()
{
    return cameraID;
}

//setCameraID - sets it to whatever is passed in
public void setCameraID(String newID)
{
    cameraID = newID;
}

//toString - returns its representation as a String
public String toString()
{
    String str = "\nName: " + name + "\nLimit: " + LIMIT;
    str += "\nSpeed: " + speed + "\nCamera: " + cameraID;
    str += "\nLocation: " + location;

    return str;
}

}




What is the optimal way to return a private value from inside a class?

I'm attempting to optimize my code for maximum readability and for that I need my code to be in-line through and through. I will present two snippets of code as an example. In my eyes the below one is more easier for the eyes. These snippets (one of them) would be stored in a class and setting width should only be possible inside the class while getting Width should always be possible.

A:

private int width;
public int Width
{
    get { return width; }
    private set { }
}

B:

private int width;
public int Width()
{
    return width;
}

As far as I am concerned these two ways of achieving the same end result are identical. Because I would like to be thoroughly in-line in all my classes I wouldn't want to use both ways mixed together. The B-approach seems cleaner in my eyes.

Are there any downsides/upsides to either approach. Should one approach be favored over the other? Are A and B approaches really completely identical?




Is it possible to get reference to 'this' pointer in class body without using the class name?

Here is what I tried:

class i_really_dont_wanna_to_use_this_class_name_for_reference_type_of_this
{
    //get this:
    auto get_this() -> decltype(this) {return this;}

    //now, somehow declare reference do value returned by get_this()
    //here is what I tried but failed
    auto * const & this_ref = get_this(); //error, invalid use of auto
    decltype(this)& this_ref = get_this() //error, invalid use of this     
}

Is it even possible?




Large class with dependant classes and shared properties

I am having trouble figuring out the best way to refactor a very large C# class and specifically how to pass shared properties/values from the large class into the extracted classes and have those modified values available in the main class.

At the start, this class was 1000 lines long and is very procedural – it involves calling methods and performing work in a specific sequence. Along the way things are persisted into the database. During the process there are multiple Lists of items that are worked on and shared in the methods. At the end of this process, there are a bunch of statistics that are presented to the user. These statistics are calculated in various methods as the processing is taking place. To give a rough outline – the process involves a bunch of random selection and at the end of the process the user sees how many random items, how many invalid records were picked, how many items came from this sub-list etc.

I have been reading Uncle Bob’s “Clean Code” and am trying to make sure as I refactor that each class does only 1 thing.

So I have been able to extract methods and classes in order to keep the file smaller (have it down to 450 lines now) but the problem I am having now is that these broken out classes require values from the main parent class to be passed to them and updated – these values will be used for other methods/class methods as well.

I am torn as to which is the cleanest approach:

1) Should I create a bunch of private member variables to store the statistical values and Lists in the main class and then after calling into the main class' dependnat class methods, receive back a complex result class and then extract these values out and populate / update the private member variables? ( lots of boiler plate code this way)

OR

2) Is it better to create a DTO or a some sort of container class that holds the Lists and statistical values and just pass it to the various class methods and child class methods by reference in order to build up the list of values? In other words I am just passing this container class and since it's an object the other classes and methods will be able to directly manipulate the values in there. Then at the end of the process, that values DTO/container/whatever you want to call it will have all of the final results in it and I can just extract them from the container class (and in that case there really is no need to extract them and populate the main class’ private member variables. )

The latter is the way I have it now but I am feeling that this is a code smell – it all works but it just seems “fragile”. I know large classes are not great but at least with everything in 1 large file it does seem clearer as to which properties I am updating etc.




Implement a constructor from c# to xaml

Can anyone please share your experience about how to put this piece of code into XAML?

In main function:

var connection = new Connection(source, sink);

Member function:

public Connection(Connector source, Connector sink)

I've tired this :

<object ...>
  <x:Arguments>
     oneOrMoreObjectElements
  </x:Arguments>
</object>

But it doesn't work. I think that's because the tool I use has it's own namespace, and the item "Arguments" isn't a part of it.




initialization order of static const initialized with functions

In short, I need to initialize a const static member with some value obtained from a file and keep it thereby same for every object derived from it.

So let's say I've a program -

#include <fstream>
#include <iostream>
#include <string>

class A
{
public:
static const int VAL1;
static const int VAL2;
};

int F(const std::string);

const int A::VAL1 = F("1.txt");
const int A::VAL2 = F("2.txt");

int F(const std::string filename)
{
  std::ifstream file(filename);
  int result = 0;
  file >> result;
  return result;
}

int main () {
  std::cout << A::VAL1 << " " << A::VAL2 << "\n";
}

Is it guaranteed that static members will be always initialized before creation of objects, because that's what I want :/




Cannot access class object normally (i.e. without __dict__)? [duplicate]

This question already has an answer here:

I'm new to Python and have been reading the docs over here and here trying to get my head around classes.

What I don't get is why I cannot access a classes attribute (or object) using the following syntax:

MyClass.someVar

Below is the offending code:

class Cities(object):
    """A class containing all valid cities"""
    def __init__(self):
        self.Charlotte = 183
        self.Tampa = 220
        self.Pittsburgh = 222
        self.LosAngeles = 475

def plane_ride_cost(city):
    myCity = Cities()

    print myCity.city               "<-- Breaks everything"
    return myCity.__dict__[city]    "<-- Works"

plane_ride_cost('Charlotte')

Looking at all the documentation, it seems I should be able to access my classes attributes using the shorter method. And there is some discussion and discouragement of using __dict__ which seems genuine.

Sorry if this is absolutely basic... but I just don't get why the shorthand version doesn't work! Coming from JS (whoops!)




How to make instances of a class unique each time in a loop

I need help with a console application I'm making. I'm making a application to use for studying. I want to be able to start it up, enter how many questions I want to have, enter question and answer for each question, use a looping method that will forever loop and ask those same questions over and over. Thought this would be really useful. But I have meet a problem on the way. I use a class to create instances for the questions and their respective answers, but I don't know how to make the instance name different for each question. Here's the code below

namespace glosor
{
    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine("Hello, please enter how many questions you would like to have on this reapeting test");
            int numberofquestions = Convert.ToInt32(Console.ReadLine());
           while(numberofquestions > 0)
            {
                Console.WriteLine(" what do you want question number " + numberofquestions + " to be?");

                QuestionAndAnswer question = new QuestionAndAnswer(null,null);
                question.answer = Console.ReadLine();
                Console.WriteLine(" what do you want question number " + numberofquestions + "'s answer to be?");
                question.answer = Console.ReadLine();
                numberofquestions--;
                QuestionAndAnswer.numberofquestions++;
            }


        }


         class QuestionAndAnswer{
            public string question;
            public string answer;
            public static int numberofquestions;
            public QuestionAndAnswer(string _question,string _answer)
            {
                question = _question;
                answer = _answer;


            }
        }


    }
}




a Function that accepts both a class and a derived class as the argument

How to make a function F that accepts both a class A, and a class B derived from A, for its only argument?

The constructors and destructors for class A and class B are different.




How do I import and return values in my program with a class?

I've always been very bad at understanding how classes work in python, my program is almost done but I'm very unsure about the def init part. I have a file that is a cvs and a rows [1, 2, Pikachu, 34, ] etc etc, the "indata" import works just fine, and each attribute have a index, but how to I import it to my init part so I can create an object with the searched attributes? *I didn't translate to english everywhere

import csv

class Pokemon(object):

def __init__(self, indata):
    """Initierar namn och attribut"""
    self.namn = indata[2]
    self.Per = indata[0]
    self.Type1=indata[10]
    self.HP=indata[3]
    self.Atk=indata[4]
    self.Def=indata[5]

def __str__(self):#
    return self.__namn__
    return self.__Per__
    return self.__Type1__
    return self.__HP__  
    return self.__Atk__
    return self.__Def__

def visaStatus(self):#show status
    #när vald pokemon är skapad ska den visa status
    """Visar namn och attribut"""
    print("\n", self.namn, "är Nr",self.Per, "in Pokedex")
    print("its main type is" , self.Type1, " its maximala HP is", self.HP)
    print("its attack is" , self.Atk,"defensive power",self.Def)


def indata(self,namn):

    import csv        
    namn=namn[0].upper()+namn[1:]
    with open('pokedex.csv', encoding = "latin1") as f:
        reader = csv.reader(f)
        for row in reader:
            if str(namn) in row:
                temp.append(row)
    if IndexError:
        print("There is no such pokemon")
        main()

    t=str(temp[0])
    indata=t.split(",")
    return indata#indata is working line with ['1', '1',] etc




def avsked(self):
    #hejdå hälsning vid avslut
    print(""Bye! See you next time""")

##################MAIN

def main():

   namn=input("Which pokemon do you want to know more about")
   namn=namn[0].upper()+namn[1:]#tillåter sökning med små bokstäver också
   djur=Pokemon(namn)
   djur.indata(namn)
   djur.visaStatus()
   svar=input("Vill du veta mer om någon annan Pokemon? J/N")
   while svar:
          if svar == "J" or svar=="j":
                 main()
          elif svar=="N" or svar=="n":
                 djur.avsked()
          else:
                 print("Ej giltigt svar")
   djur.avsked()

main()




C++ - Incomplete class type? [duplicate]

This question already has an answer here:

I've been working with a lot of C and Java lately so I'm a bit confused coming back to C++ on why this is not allowed.

incomplete type is not allowed

#pragma once

class Expression
{
private:
    Expression power; // <--- incomplete type is not allowed
};

I believe the answer here is to change the line Expression power to Expression *power but I don't understand why that is. I can declare objects like vector<int> var without having to make them a pointer, but the second I have an object of the same type as the file it's being declared in, I need one? I've looked around but cannot find any tutorials/videos on a class making an object of itself.




Rearrange a class structure for better performance

I have a class relation ship like below,

public class CollegeInfo
{
    public int CollegeId { get; set; }

    public Dictionary<int, DepartementInfo> DepartementInfo { get; set; }
}

public class DepartementInfo
{
    public int CollegeId { get; set; }
    public int DepartementId { get; set; }

    public Dictionary<int, DataGridViewRowInfo> DataGridViewRowsInfo { get; set; }
}

public struct DataGridViewRowInfo
{
    public string Id { get; set; }

    public int CollegeId { get; set; }
    public int RowID;
    public int DepartementId ;

    public string SpecialString { get; set; }        
}

If I have a object of CollegeInfo, I will be having different DepartementInfo and in each frame will have a collection of DataGridViewRowInfo

You all can see that we have CollegeId in all class and DepartementId in two classes how can I rearange these classed to make a better relation, If I take a single object of DataGridViewRowInfo it should have corresponding CollegeId and DepartementId




Can not get the instance of a singleton class from other classes

The problem I am facing is somehow related to "loop inclusion" or "incompleted class"

I have 2 classes:

ControllerManager, this class is declared as Singleton, this class has a object of AuxController.

AuxController, this class has a function that needs to get the instance of ControllerManager

The problem is: when compiling source code, it fails with error "incomplete type" or "invalid type"

Is there any way to fix this problem? or is there any other way to redesign code structure?

Source code ControllerManager.h

#ifndef CONTROLLERMANAGER_H
#define CONTROLLERMANAGER_H
#include "auxcontroller.h"

class ControllerManager
{
/* This class is defined as Singleton class */
private:
    /* 1. define a private static instance */
    static ControllerManager *inst;

public:
    /* 2. define a public static accessor */
    static ControllerManager *getInstance(){
        /* 3. do lazy initialization */
        if(!inst){
            inst = new ControllerManager();
        }
        return inst;
    }

protected:
    /* 4. Define all accessors to be protected */
    ControllerManager();
    ~ControllerManager();

/* property */
private:
    int m_code;

public:
    int getCode()
    {
        return m_code;
    }

    void setCode(int _code)
    {
        m_code = _code;
    }

/* below code causes fail of compilation */
public:

    AuxController m_auxcontroller;

};

#endif // CONTROLLERMANAGER_H

ControllerManager.cpp

#include "controllermanager.h"

/* 5. initialize static variable */
ControllerManager *ControllerManager::inst = 0;
ControllerManager::ControllerManager()
{
    m_code = 15;
}

ControllerManager::~ControllerManager()
{
    delete inst;
}

AuxController.h

#ifndef AUXCONTROLLER_H
#define AUXCONTROLLER_H

/* if do NOT include controllermanager.h with below line,
 * and declare ControllerManager class as a forward declaration:
 *
 * class ControllerManager;
 *
 * compiler will stop due to "incomplete type"
 */
#include "controllermanager.h"



class AuxController
{
public:
    AuxController();
    void setControllerCode(int code);
};

#endif // AUXCONTROLLER_H

AuxController.cpp

#include "auxcontroller.h"

AuxController::AuxController()
{

}

void AuxController::setControllerCode(int code)
{
    /* if do NOT include controllermanager.h ,
     * and declare ControllerManager class as a forward declaration in the header file:
     *
     * class ControllerManager;
     *
     * compiler will stop due to "incomplete type" at this line
     *
     */
    ControllerManager::getInstance()->setCode(code);
}

main.cpp

#include "controllermanager.h"

int main(int argc, char *argv[])
{
    ControllerManager *ctlMng = ControllerManager::getInstance();
    ctlMng->setCode(10);
    return 0;
}




How do I sort/spread-apart classes?

I've only started in C# and a couple of tutorials back I learnt about classes, I get the picture of OO programming and I get how it works but my question is how do I know when to create a new class?

I was advised to for example, keep stuff to do with the GUI/program in the program class for example, then keep all the stuff like the game engine and what-not in another. Is there a specific way of categorizing classes? I've seen some example source code of a simple text based bank account online and they used like 4 classes in such a simple program.

Source: http://ift.tt/2bUTozW




JUnit - Test Class Instantiation with objects in parameters

I am very new to JUnit testing and I am trying to understand how to test the instantiation of an class.

Let us say that I have the following ToyBox class which needs an ArrayList of Toys in order to be instantiated. This list of toys is created on another part of the program, of course, but I do not understand very well where I should create it in order to unit test ToyBox,

ToyBox Class

public ToyBox(ArrayList<Toy> toyList){
    this.toys= toyList;

    for (Toy toy: toyList) {
        checkToy(toy);
    }
}

private void checkToy(Toy toy){
    if (toy.isRed()){
        this.numRed += 1;
    } else {
        this.numBlue += 1;
    }
}
public int getBlues(){
    return this.numBlue;
}

ToyBoxTest

public class ToyBoxTest {

    @Test
    public void getNumBlues() throws Exception {
        // assert that num blues corresponds
    }

Where should I instantiate the ToyBox class in order to perform the getNumBlues() method?

Should it be like this?

public class ToyBoxTest {
    ArrayList<Toy> toyList = new ArrayList<Toy>();
    Toy toy1 = new Toy("blue", "car");
    Toy toy2 = new Toy("red", "bike");
    toyList.add(toy1);
    toyList.add(toy2);

    @Test
    public void getNumBlues() throws Exception {
        // assert that num blues corresponds
        ToyBox box = new ToyBox(toyList);
        assertEquals(1, box.getBlues());
    }

Basically, my question is where and how should I create the arraylist of objects needed to test a class that depends on that created list.

I don't know anything about unit testing and I want to learn the best practices for doing it. Thank you in advance!




mardi 30 août 2016

Using Android MediaPlayer Class in other Classes

Please can someone tell me how can I create an Android MediaPlayer class (Player.class) and use it in other project classes like in MainActivity.class to be in simple usage like:

// to play a specific audio file

Player.PlayAudio("myaudio.mp3");

// to pause
Player.pause();

// to play
Player.play();

// to stop
Player.stop;

// to resume
Player.resume();

// to check if is already playing and return a boolean
Player.isplaying();

I just wanted something like this! Every answer is highly appreciated thank you guys :)




Python Plot Categories for a Variable in a Dataset

How can I plot the counts of each category (like 1, 2 and 3) for a column variable only with matplotlib and without using NumPy, Pandas, SciPy, SciKit-Learn, etc.?




Class that has the member Vector of its own members

sorry in advance for anything I do wrong, this is my first time posting here.

So I'm trying to write a Neural Network. I've done it before in other languages, and using matrices libraries, however I wanted to make it on my own, to better understand them. However I have run into a problem with my classes.

I am doing this in C++.

So I have a class called ANN. it has a vector, of layers. layers are a class called Node. however within node I want to access the previous layer of nodes, so I can calculate this nodes values.

I know if I have a class, and I want one of its members to be of itself it has to be a pointer. ex.

class Node{
public:
    // Public methods/members here
private:
    Node *previousNode;
}

however this is not what I want. I want *previousNode to be ancestor of nodes

here is an example of what I want

class Node{
public:
    //Public functions/members here
private:
    vector <Node*> previousLayer;
}

Now I've heard in this situation it would be better to use a smart pointer. I don't exactly know what that is, I know it is basically a wrapper for pointers that manage them. I also thought the main reason smart pointers were used is because some pointers get left NULL or not deleted after use, but I did not think that would really matter seeing as the scope of this class could only possible end when the program ends.

my question is how would I implement a vector of pointers to the class the vector is in.




Plot Counts of Categories for a Variable in Python

I have a dataset which has 14 columns (I had to only use 5 columns) that I have split into train and test data sets. I need to create a vertical bar chart from the train data set for the counts of each class (1, 2, and 3 are the classes) for a column (travelling_class) variable. I am not allowed to use NumPy, Pandas, SciPy, and SciKit-Learn.

This is my code

travelling_class = defaultdict(list)
for row in data:
    travelling_class[row[0]]

travelling_class = {key: len(val) for key, val in travelling_class.items()}

keys = travelling_class()
vals = [travelling_class[key] for key in keys]
ind  = range(min(travelling_class.keys()), max(travelling_class.keys()) + 1)
width = 0.6

plt.xticks([i + width/2 for i in ind], ind, ha='center')
plt.bar(keys, vals, width)
plt.show()

Any help would be greatly appreciated. Thank you in advance




creating a vector of structs inside a class with a private struct

just some quick information that might help things along. im creating a quiz that is read in from a file. with oop in mind, im getting the information from the file into a temp struct to then push back into a vector. my problem is, i get an error of vector is not naming a type. i was recommended by a fellow student to do it like this. any ideas? here is my code.

#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>
#include <cmath>
#include <vector>
using namespace std;
void programIntro();
void programOutro();
void Readfile();
void score();
int correct;
int wrong;


class quiz
{
private:
struct question
{
string question;
string a;
string b;
string c;
string answer;
};
public:
vector <question> container ;

//reads my questions in from the file.
void Readfile()
{

ifstream test("quiz.txt",ios::in);
if(test.is_open())
{

struct reader
{
string question;
string a;
string b;
string c;
string answer;
}read;


for(unsigned int i=0; i<3;i++)
{
getline(test,read.question);
getline(test,read.a);
getline(test,read.b);
getline(test,read.c);
getline(test,read.answer);

}
}
if(!test.is_open())
{
  cout<<"Lucky you there is no test!! :("<<endl;
   cout<<endl;
             }
 }


 };




Why instanceof sometimes doesn't compile and sometimes returns false?

In the following example

  • test instanceof java.util.Map returns false

  • test instanceof java.util.HashMap doesn't compile

Why? They look so similar to each other!

public class InstanceofTest {
    public static class Test {}
    public static void main(String[] args) {
        Test test = null;

        // 1. false
        System.out.println(test instanceof java.util.Map);

        // 2. compilation error
        System.out.println(test instanceof java.util.HashMap);
    }
}




Proper way to modify public interface

Let's assume we have a function that returns a list of apples in our warehouse:

List<Apple> getApples();

After some lifetime of the application we've found a bug - in rare cases clients of this function get intoxication because some of the apples returned are not ripe yet.

However another set of clients absolutely does not care about ripeness, they use this function simply to know about all available apples.

Naive way of solving this problem would be to add the 'ripeness' member to an apple and then find all places where ripeness can cause problems and put some checks.

const auto apples = getApples();
for (const auto& apple : apples)
    if (apple.isRipe())
        consume(apple)

However, if we correlate this new requirement of having ripe apples with the way class interfaces are usually designed, we might find out that we need new interface which is a subset of a more generic one:

List<Apple> getRipeApples();

which basically extends the getApples() interface by filtering the ones that are not ripe.

So the questions are:

  1. Is this correct way of thinking?
  2. Should the old interface (getApples) remain unchanged?
  3. How will it handle scaling if later on we figure out that some customers are allergic to red/green/yellow apples (getRipeNonRedApples)?
  4. Are there any other alternative ways of modifying the API?

One constraint, though: how do we minimize the probability of inexperienced/inattentive developer calling getApples instead of getRipeApples? Subclass the Apple with the RipeApple? Make a downcast in the getRipeApples?




explain java output for the given program [duplicate]

This question already has an answer here:

if line 2 is omitted,the output is 0. otherwise it is showing error,why? how is line 2 an error and why the output of line 1 is 0,even though given obj.i=1; kindly explain to me why the program is behaving in this manner

class Parent 
{
    int i;
    void display()
    {
        System.out.println(i);
    }
}

class Child extends Parent
{
    int j;
    void display()
    {
        System.out.println(j);
    }
}

public class inheritance_demo
{
    public static void main(String args[])
    {
        Parent obj = new Child();
        obj.i = 1; //line 1
        obj.j = 2; //this is line 2`,the error statement
        obj.display();
    }
}




how can I use an array with a class using a dot operator

using System;

I am using string[] talentSlots = new string[2]; and I want to do a agent.talentSlots = blah blah thing how do I do it?

namespace warhammerRPGCB
{
    public class classes
    {
        string className;
        int stanceRed;
        int standGreen;
        string carrerSkills;
        string primaryChar;
        string[] talentSlots = new string[2];
        int focusSlot;
        int reputationSlot;
        int tacticSlot;

        public classes()
        {
            classes agent = new classes();
            agent.className = "Agent";
            agent.carrerSkills = "Charm, Education, Folklore, Guile, Intution";
            agent.stanceRed = 2;
            agent.standGreen = 2;
            agent.primaryChar = "Intelligence, Felloship";
            agent.tacticSlot = focusTalent, reputationTalent;
        }
    }
}




Self referential class [duplicate]

This question already has an answer here:

Trying to write a class for a directory which can have a parent and a list of children.

Class definition:

class Directory {
    public string name;
    public Directory parentDir;
    public List<Directory> subDirs;

    public Directory(string name) {
        this.name = name;
    }

    public void addSubDir(Directory x) {
        subDirs.Add(x);
    }
}

Sample code trying to create two instances and set one as a child of the other:

Directory temp1 = new Directory("root");

Directory temp2 = new Directory("games");

temp1.addSubDir(temp2);

The error I get is:

System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.




c++ oop program doesn't give expected result

Consider the following piece of program:

class cls
{
   int vi;
public:
    cls(int v=37)
    {
        vi=v;
    } 
    friend int& f(cls);
};

int& f(cls c)
{
    return c.vi;
}

int main()
{
    const cls d(15);
    f(d)=8;
    cout<<f(d);
    return 0;
}

When I run it, the output is

15

but I don't understand why 15, because I thought it should've outputed 8.




Python class shared variables gives unexpected output

Based on the explanation on Shared Variables in Python Class here , I expected the following code to give output as :

123 123
200 200
300 300

But it is

123 123
200 123
200 300

Code:

class A:
    abc = 123
    def __init__(self, a,b,c):
        self._a = a
        self._b = b
        self._c = c


if __name__ == '__main__':
    a = A(2, 4, 6)
    b = A(3, 9, 27)

    print a.abc , b.abc
    a.abc = 200
    print a.abc , b.abc
    A.abc = 300
    print a.abc , b.abc

Can somebody please help understand this ? My impression is that shared variables are same as static variables in C++ classes. Any insights to bust that myth, if it is so, would be helpful too.




Maven build failing after adding classpath and dependencies in lib folder in pom.xml NoClassDefFoundError

I have an app I built in Java and successfully compiled in Maven. After building I go to the target folder and run java -jar *projectfilename*.jar and I get the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/jibble/pircbot/PircBot at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:763) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) at java.net.URLClassLoader.access$100(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:368) at java.net.URLClassLoader$1.run(URLClassLoader.java:362) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:361) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at io.github.bholagabbar.Main.setupIRCBot(Main.java:9) at io.github.bholagabbar.Main.main(Main.java:27) Caused by: java.lang.ClassNotFoundException: org.jibble.pircbot.PircBot at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Now org/jibble/pircbot/PircBot which was not found is actually one of my dependencies in my pom.xml.

<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU"
  xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
  <modelVersion>4.0.0</modelVersion>

  <groupId>io.github.pixrat</groupId>
  <artifactId>gallurdo</artifactId>
  <version>1.0</version>
  <packaging>jar</packaging>

  <name>gallurdo</name>
  <url>http://ift.tt/19pvvEY;

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <id>copy</id>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>
                ${project.build.directory}/lib
              </outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <classpathPrefix>lib/</classpathPrefix>
              <mainClass>io.github.pixrat.Main</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <repositories>
    <repository>
      <id>jitpack.io</id>
      <url>http://ift.tt/1UqccXp;
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>pircbot</groupId>
      <artifactId>pircbot</artifactId>
      <version>1.5.0</version>
      <type>jar</type>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.github.Ullink</groupId>
      <artifactId>simple-slack-api</artifactId>
      <version>0.5.1</version>
      <type>jar</type>
      <scope>provided</scope>
    </dependency>
  </dependencies>
</project>

I have referred to answer here Maven: NoClassDefFoundError in the main thread, Maven: NoClassDefFoundError in the main thread and many other places but in vain. I'd appreciate some help thanks




.Net framework class composition

I'm not sure how to start to phrase my question so I'm going to jot down my thoughts and hopefully something will come up :)

Using the .net library, or any library for that matter, how do you go about understanding the class composition structure or interaction of certain classes in order to use a certain feature or maybe mock them in a test.

This idea or question came up as I was trying to write some specs to test a controller with model validation. I found so many different answers online and on Stack that shows so many classes that need to be mocked just to validate a model passed to an action. At the end the solution was a lot more simpler and just required a new HttpConfiguration on the controller to validate a model.

I feel MSDN has 80% of useless information of classes and properties that were probably generated. I don't care what property a class has that's easy to find but what's more important is how that class fits within the framework, what interaction with other objects it has and so on.

Currently, I do use MSDN, a decompiler (dotPeek or ISpy), and google to at least have a starting point but it shouldn't really be this hard. Decompiling the code takes considerable time to go through to understand how a certain feature work. So I want to see how others tackle this challenge maybe I get a better idea. So:

  • How do you normally figure out the interaction/composition between classes?
  • Any specific tool you use other than a decompiler? maybe one that build a graphical representation of the classes and their public properties to make things more clear!
  • How do you eliminate a lot of the not needed information from the decompiled classes in order to understand what's truly available for you to consumer?

PS: if you have any reference/sites/books please share.

Thanks,




Why can't I define a class in main()?

I'm trying to define a class in my main() method but when I run the code the console states 'g' is not defined. If I put the definition of g anywhere else it seems to work fine. What is wrong?

class graph(object):
    def __init__(self):
        self.nodes = []
        self.edges = []
        self.graphDict = {}

    def addNodes(self):
        self.nodes.append(input("Enter the name for a new node: "))

def main():
    g = graph()

if __name__ == '__main__':
    main()

And in the console:

>>> g
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    g
NameError: name 'g' is not defined

Any ideas how to fix this?




Initializing by pointer in c++

So let's say I have a class MyClass. Now I want to use another class called Animals, I would probably do the following.

class MyClass
{
public:
    MyClass();
private:
    Animals animals;
};

However I can also do this:

class MyClass
{
public:
    MyClass();
private:
    Animals* animals;
};

and then initialize the class in the constructor with:

animals = new Animals();

What is the difference between the two different approaches, which is better and why? In my use Animals should only be used inside MyClass




Creating get/set accessors for a cli::array property

I am fairly new to c++/cli and I have created a custom class that has two 2d arrays as a properties. I am having trouble creating the get/set for these properties. I have tried a few different ways of defining the get/set, but haven't succeed yet. Any help would be appreciated. Thanks.

public ref class MyClass {
public:
    property cli::array<bool, 2>^ filled;
    property cli::array<System::String^,2> ^id;

    MyClass() {
        filled = gcnew cli::array<bool,2 > (8, 12);
        id = gcnew cli::array<System::String^, 2>(8, 12);
        for (size_t i = 0; i < 8; i++)
        {
            for (size_t z = 0; z < 12; i++)
            {
                filled[(int)i, (int)z] = false; // this line currently gives the error: no instance of function "cli::array<T,rank>::set[with T=bool, rank=2]" matches the argument list
            }
        }
    };
};




C++ const function error

I am quite new to oop in c++ and I came across the following piece of code while surfing the net:

#include<iostream>
using namespace std;

class cls
{int x;
public: 
    cls(int i=3) {x=i;}

    int &f() const{ return x;}
};
int main()
{
    const cls a(-3);
    int b=a.f();
    cout<<b;
    return 0;
}

And when I try to run the code, it crashes due to the f function. Now I am not quite sure what is going on there and why it crashes, so I would need someone to enlighten me a little bit on the subject.




How to Print the Head (First 10 Rows) and Tail (Last 10 Rows) of a Dataset in Python

In Python (Jupyter Notebook) I have a dataset which has 5 columns that I have split into train and test data sets. I have to list the head (first 10 rows) and tail (last 10 rows) of the dataset. I am not allowed to use NumPy, Pandas, SciPy, and SciKit-Learn. I have to list the formatted data as follows (column1, column2 and column3 are integers and column4 and column5 are floats):

column1  column 2  column3    column4   column5     
1         0         5.0        male      200.4578  
0         1         24.67      female    300.06    
1         0         0.2        female    120.43

This is the code used to get the train and test datasets:

random.seed(900001)

n = len(data['coumn1'])
train_flag = [random.random() < 2/3 for i in range(n)]

train = defaultdict(list)
test  = defaultdict(list)

for i, flag in enumerate(train_flag):
    if flag:
        train['column1'].append(data['column1'][i])
        train['column2'].append(data['column2'][i])
        train['column3'].append(data['column3'][i])
        train['column4'].append(data['column4'][i])
        train['column5'].append(data['column5'][i])

    else:
        test['column1'].append(data['column1'][i])
        test['column2'].append(data['column2'][i])
        test['column3'].append(data['column3'][i])
        test['column4'].append(data['column4'][i])
        test['column5'].append(data['column5'][i])

Any help would be greatly appreciated. Thank you in advanced




Inheriting from inner class

|\|\|\|\|\|\|\|\|\|\|\|\|\|\|\|\| Code:

public class A {
    public A() {
        System.out.println("A()");
    }

    public class B {
        public B() {
            System.out.println("B()");
        }
    }
}
class Caller extends A.B {
    Caller(A a){
        a.super();
    }
}


public class Main {
    public static void main(String[] args) {
        Caller as= new Caller(new A());
    }
}

The question is simple. Why a.super() calls A.B constructor?




When I use java.lang.instrument.Instrumentation#redefineClasses() , should I pass a array to the function?

I used java.lang.instrument.Instrumentation#redefineClasses() to redefine existing classes, sometimes, I need to redefine several classes.

If I redefine class one by one, I will know which is success, which is failed.

But is it better to put classes redefined in an array together to get more correctness?




ES6 + Angular Controller class, getting this is undefined in callback

Consider the following class

class LoginController{
    constructor(authService,$timeout,$state){
        let vm = this;
        this.loading = false;
        this._authService = authService;
        this._$timeout = $timeout;
        this._$state = $state;
        this.loading = false;
        this.statusMessage = null;
    }

    login(){
        this.loading = true;
        this.statusMessage = null;

        let loginModel = {
            UserName : this.username,
            Password : this.password,
            RememberMe : this.rememberMe
        };

        //Login User
        this._authService.login(loginModel).then(function(user){
            //Set User Login & send to Dashboard
            this._authService.setUser(user);
            this._$state.go("dashboard");

        }, function(error){
            const errorMessage = error ? error.Message : "Undefined Login Issue occurred !";
            this.loading = false;
        });
    }
}

Everything is working fine, except for then I hit the error callback function and it gets to this.loading = false; which for some reason this is undefinded.

How do I keep a reference to the Class "this" in the error callback ?




JavaScript Class Syntax: Static Data Members

I cannot find any information about how one defines static data members in JavaScript using the (relatively new) class syntax. Is it even possible? Please see the following example code:

class Foo {
  constructor() {
    this.name = 'Default Name for each Instance';
    // staticData1 = 'Static Data 1'; // syntax error
    let staticData2 = 'Static Data 2'; // undefined outside
  }

  doSthSpecial() {
    console.log('Executing a method from instance "' + this.name + '"');
  }

  static doSthStatic() {
    console.log('Executing a method that does the same for each instance of "Foo"');
  }
}

foo = new Foo();
console.log(foo.name);
foo.doSthSpecial();
Foo.doSthStatic();
// The problematic case:
console.log(Foo.staticData2);




Two modules, Same line of code, one code works but other does not

I have just started using dictionaries and Class collections. I wrote a code using both that worked fine (see code below).

For a = 2 To UBound(FullArray, 1)

        Set GEMclass = dict.Items(a) '<-------
        GEM = GEMclass.g

             'Do while loop
             Do

            'Check to see if Parent has an owner
             If (Not (dict.Exists(GEM))) Then

                     Nrow = 0
             Else

                      Nrow = dict(GEM).Num

                      Call Main
                      Call PartTwo
                      Call PartThree

             End If

             Loop Until (Nrow = 0) 'keep doing this unti no tree link

Next a

Call TurnOnFunctionality

End Sub

However, I tried to use the same line of code in another sub and it does not work (the line is in marked with an arrow).

Dim i As Integer

    If ((GemDict.Exists(GEM))) Then

    i = GemDict.Item(GEM)
    i = i - 2
    Set GEMclass = GemDict.Items(i) '<-------

            'Debug.Print GemDict.Item(GEM)

            'Debug.Print GemDict.Keys(i)

                If GEMclass.NumofP > 1 Then

                MsgBox "Greater 1"

                Else

                MsgBox "Only 1"

                End If

    End If

    GEM = GEMclass.P

I declared both GEMclasses in each code as so

Public GEMclass As Gclass

Any ideas? I am stumped.




C++ Constructor Oder [on hold]

Consider the following piece of code:

#include<iostream>
using namespace std;
class cls
{
public:
        cls(int i=0) {cout<<" c1 ";}
        ~cls() {cout<<" d 1 ";}
};
class cls2
{
 cls xx;
public:
        cls1(int i=0){cout<<" c2 ";}
        ~cls1(){cout<<" d2 ";}
}c;
class cls3
{
    cls2 xx; cls xxx;
public:
    cls2(int i=0) {cout<<" c3 ";}
    ~cls2(){ cout<<" d3 ";}
};
int main()
{
    cls3 s;
    return 0;
}

Now, when I run it, it outputs:

c1 c2 c1 c2 c1 c3 d3 d1 d2 d1 d2 d1

and I can't seem to figure out why, in my head, it should output:

c1 c2 c1 c3 d3 d1 d2 d1

because:

cls2 s -> cls1 xx -> cls xx => c1
                           => c2
                -> cls xxx => c1
                => c3

I know that somewhere, my logic is flawed, but I don't know where.




Setting an ImageIcon to a label in another class through validation from previous label

I have a program that requires selecting a character, in this case a gender. When the 'female' button is pressed, on the same JFrame,in class Genders, a female ImageIcon is displayed on the label 'Avatar'. The same with male. If it's clicked, a male ImageIcon is displayed on the JFrame. On another JFrame, I have the class StartGame, with my selected gender displaying in the label playerbattle. I don't know how to make it that the selected gender is displayed. Please help, here's my code:

Class Genders:

  import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import com.sun.prism.Image;

import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Genders extends JFrame {

    public JPanel contentPane;
    protected ImageIcon avtMale = new ImageIcon("male warrior.png");
    protected ImageIcon avtFemale = new ImageIcon("female warrior.png");

    /**
     * Launch the application.
     */
    public static void main(String[] args) throws IOException{
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Genders frame = new Genders();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    /*String[] imageList = 
            {
                    "female warrior.jpg", "male warrior.jpg"
            };
    */

    public Genders() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        ImageIcon maleicon = new ImageIcon("male warrior.png");

        JLabel Avatar = new JLabel();
        Avatar.setBounds(0, 0, 227, 261);
        contentPane.add(Avatar);

        ImageIcon femaleicon = new ImageIcon("female warrior.png");

        JButton btnFemale = new JButton("Female");
        btnFemale.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ex) {

                //play sound:
                try {
                     // Open an audio input stream.           
                      File soundFile = new File("C:/My Awesome Stuff/Personal/Carman/My Eclipse Programs/Game/btnclicksfx.wav"); //you could also get the sound file with a URL
                      AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);              
                     // Get a sound clip resource.
                     Clip clip = AudioSystem.getClip();
                     // Open audio clip and load samples from the audio input stream.
                     clip.open(audioIn);
                     clip.start();
                  } catch (UnsupportedAudioFileException e) {
                     e.printStackTrace();
                  } catch (IOException e) {
                     e.printStackTrace();
                  } catch (LineUnavailableException e) {
                     e.printStackTrace();
                  }

            Avatar.setIcon(avtFemale);

            }
        });
        btnFemale.setBounds(335, 11, 89, 23);
        contentPane.add(btnFemale);

            JButton btnMale = new JButton("Male");
            btnMale.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    //play sound:
                    try {
                         // Open an audio input stream.           
                          File soundFile = new File("C:/My Awesome Stuff/Personal/Carman/My Eclipse Programs/Game/btnclicksfx.wav"); //you could also get the sound file with a URL
                          AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);              
                         // Get a sound clip resource.
                         Clip clip = AudioSystem.getClip();
                         // Open audio clip and load samples from the audio input stream.
                         clip.open(audioIn);
                         clip.start();
                      } catch (UnsupportedAudioFileException ex) {
                         ex.printStackTrace();
                      } catch (IOException ex) {
                         ex.printStackTrace();
                      } catch (LineUnavailableException ex) {
                         ex.printStackTrace();
                      }

                    Avatar.setIcon(avtMale);

                }
            });
            btnMale.setBounds(335, 45, 89, 23);
            contentPane.add(btnMale);

            JButton btnOkay = new JButton("Okay");
            btnOkay.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    //play sound:
                    try {
                         // Open an audio input stream.           
                          File soundFile = new File("C:/My Awesome Stuff/Personal/Carman/My Eclipse Programs/Game/btnclicksfx.wav"); //you could also get the sound file with a URL
                          AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);              
                         // Get a sound clip resource.
                         Clip clip = AudioSystem.getClip();
                         // Open audio clip and load samples from the audio input stream.
                         clip.open(audioIn);
                         clip.start();
                      } catch (UnsupportedAudioFileException ex) {
                         ex.printStackTrace();
                      } catch (IOException ex) {
                         ex.printStackTrace();
                      } catch (LineUnavailableException ex) {
                         ex.printStackTrace();
                      }

                    {

                    }
                    // go to Start Game class:
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                           dispose();
                            new StartGame().setVisible(true);
                        }
                    });

                }
            });

            //set playericon:


            btnOkay.setBounds(335, 227, 89, 23);
            contentPane.add(btnOkay);

            JButton btngenderback = new JButton("<");
            btngenderback.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    //play sound:
                    try {
                         // Open an audio input stream.           
                          File soundFile = new File("C:/My Awesome Stuff/Personal/Carman/My Eclipse Programs/Game/btnclicksfx.wav"); //you could also get the sound file with a URL
                          AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);              
                         // Get a sound clip resource.
                         Clip clip = AudioSystem.getClip();
                         // Open audio clip and load samples from the audio input stream.
                         clip.open(audioIn);
                         clip.start();
                      } catch (UnsupportedAudioFileException ex) {
                         ex.printStackTrace();
                      } catch (IOException ex) {
                         ex.printStackTrace();
                      } catch (LineUnavailableException ex) {
                         ex.printStackTrace();
                      }

                    //go to ProfileHome class:
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            dispose();
                            new ProfileHome().setVisible(true);
                        }
                    });
                }
            });
            btngenderback.setBounds(0, 0, 41, 15);
            contentPane.add(btngenderback);

            JLabel Genderbg = new JLabel("");
            Genderbg.setIcon(new ImageIcon("C:\\Users\\WhiteFringe\\Pictures\\Wallpapers\\9gag\\Gifs\\llkokigiphy.gif"));
            Genderbg.setBounds(0, 0, 434, 261);
            contentPane.add(Genderbg);
    }
}

Class StartGame:

    import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.JLabel;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class StartGame extends JFrame {

    public JPanel contentPane;
    //protected ImageIcon playerMale = new ImageIcon("male warrior.png");
    //protected ImageIcon playerFemale = new ImageIcon("female warrior.png");

    protected ImageIcon playericon = new ImageIcon();


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    StartGame frame = new StartGame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public StartGame() {

        String[] gametext = new String[100];
        String t1, t2;


        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent Escape) {

            }
        });

        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        JMenuItem mntmPause = new JMenuItem("Pause");
        mntmPause.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                //play sound:
                try {
                     // Open an audio input stream.           
                      File soundFile = new File("C:/My Awesome Stuff/Personal/Carman/My Eclipse Programs/Game/pausesfx.wav"); //you could also get the sound file with a URL
                      AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);              
                     // Get a sound clip resource.
                     Clip clip = AudioSystem.getClip();
                     // Open audio clip and load samples from the audio input stream.
                     clip.open(audioIn);
                     clip.start();
                  } catch (UnsupportedAudioFileException e) {
                     e.printStackTrace();
                  } catch (IOException e) {
                     e.printStackTrace();
                  } catch (LineUnavailableException e) {
                     e.printStackTrace();
                  }

            //go to PauseMenu class:
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                       setVisible(false);
                        new PauseMenu().setVisible(true);
                    }
                });
            }
        });
        menuBar.add(mntmPause);
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel playerbattle = new JLabel();
        playerbattle.setIcon(playericon);
        playerbattle.setBounds(0, 0, 194, 250);
        contentPane.add(playerbattle);

        JButton btnNext = new JButton("Attack");
        btnNext.setFont(new Font("Tahoma", Font.PLAIN, 9));
        btnNext.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

            }
        });
        btnNext.setBounds(355, 219, 69, 18);
        contentPane.add(btnNext);

        ImageIcon enemyicon = new ImageIcon("enemy1.png");

        JLabel enemybattle = new JLabel(enemyicon);
        enemybattle.setBounds(309, 79, 94, 147);
        contentPane.add(enemybattle);

        JLabel battle1bg = new JLabel("");
        battle1bg.setIcon(new ImageIcon("C:\\My Awesome Stuff\\Personal\\Carman\\My Eclipse Programs\\Game\\battle1.jpg"));
        battle1bg.setBounds(0, 0, 434, 237);
        contentPane.add(battle1bg);


    }
}

If something's still unclear, here are screenshots of the JFrames: Genders: Image link:

StartGame: ImageLink: My playerbattle label should show on the left hand side (I've already inserted the label there)




Use a definition defined in another class in another file - python

I have a file called valueType.py

It contains the following:

class SInt8(ValueType):
    # Set _format as big endian signed char( 1 byte )
    _format = '>b'

class UInt8(ValueType): 
    # Set _format as big endian unsigned char( 1 byte )
    _format = '>B'

class SInt16(ValueType):
    # Set _format as big endian signed short( 2 bytes )
    _format = '>h'

class UInt16(ValueType): 
    # Set _format as big endian unsigned short( 2 bytes )
    _format = '>H'

class SInt32(ValueType): 
    # Set _format as big endian signed int( 4 bytes )
    _format = '>i'

class UInt32(ValueType): 
    # Set _format as big endian unsigned int( 4 bytes )
    _format = '>I'

class Real32(ValueType): 
    # Set _format as big endian float( 4 bytes )
    _format = '>f'

And I have another file, let's just call it parser.py. In parser.py I have defined an object called parameter this object has an attribute which is referred as parameter.values.

parameter.values contain raw hex values and i need convert them to decimal format and i'm going to use struct.unpack(fmt, string). My question is, how can I use the definition of _format in valueType.py inside parser.py?

valueType.py is imported into parser.py and they are both within the same directory




lundi 29 août 2016

i have tried to execute the c# class but i am getting the error saying namespace for pattern could not be found..

i am getting the error as Namespace for pattern could not be found..
//method// public static bool validateAadharNumber(String aadharNumber) { Pattern aadharPattern = Pattern.compile("\d{12}"); bool isValidAadhar = aadharPattern.matcher(aadharNumber).matches(); if (isValidAadhar) { isValidAadhar = aadharcard.validateVerhoeff(aadharNumber); } return isValidAadhar; }




Is the class loaded when there is created a reference to it

Does creating the reference to object of the class causes loading this class? Static variables are initialized when the class is loaded, so considering the folowing code the answer is no, am I right?

    class A{
        static int f(){
            System.out.println("initializing!");
            return 0;
        }
        static final int i = f();
    }
    public class Main {
        public static void main(String[] args) {
            A a;
        }
    }

The code gives no output.




Hr class double border

I'm requesting your help with a .css hr class

I'm trying to figure out how to make a double border like this:

Sample

Here's what i did:

hr.style15 {
border-top: 4px double black;
}
hr.style15:after {
content: 'SHIPPING INFO';
display: inline-block;
position: relative;
top: -15px;
left: 40px;
padding: 0 10px;
background: #f0f0f0;
color: #8c8b8b;
font-size: 18px;
}

My questions are:

1) How do i get rid of the inline-block below the 2 lines? I have tried by deleting the inline-block sentence but it doesn't work.

2) Can i add font-family and font size to this?

3) Is it possible to increase the space between the 2 lines without increasing the width?

Thanks in advance and sorry for my poor english.




How to refer to a class in a new window using Jquery

Let's say I open a new window and write the contents of an existing window div element into it...

var mywindow = window.open('', 'print_window', 'toolbar=no, resizable=no, width=1000);

var current_contents = $('#detail_div').html();

mywindow.document.write('<html><head><title>Print Window</title></head><body>');
mywindow.document.write('<div id="print_container">'+current_contents+'</div>');
mywindow.document.write('</body></html>');

Now suppose that there are elements with the class "print_hide" in from the existing window we want to hide in the new window.

I've tried

$('.print_hide').hide();

But that only references the original (parent?) window.

None of this worked either...

$(mywindow.document.body '> .print_hide').hide();
$mywindow.document('.print_hide').hide();

Any thoughts?




Why does this JQuery code work for Classes but not IDs? [on hold]

I am trying to achieve a certain animation that needs to be done with ID's. For some reason the code only works with Classes and not IDs, the part of the code where this is happening is the part under the comment. Why is this? And if this isn't supposed to happen, then what is going wrong?


WORKS:

var main = function() {
  $('.box').on('click', function() {
    $(this).toggleClass('clicked');
  });

  //Makes twitter logo vanish
  $('.box').on('click', function() {
    $('#twit').fadeToggle();
  });
} 
$(document).ready(main);


DOESN'T WORK:

var main = function() {
      $('.box').on('click', function() {
        $(this).toggleClass('clicked');
      });

      //Makes twitter logo vanish
      $('#bx1').on('click', function() {
        $('#twit').fadeToggle();
      });
    }
    $(document).ready(main);

(#bx1 is the id assigned to the same element ass .box)
Full code: http://ift.tt/2bwPZHF




Xcode, Swift; Call function from another class

I'm currently developing an iOS app with Xcode and Swift.

I have the following code in the ProfileEdit class (ProfileEdit.swift):

    func updateProfile(sender: AnyObject) {
//        do something
    }

There's also another class called ProfileMain (ProfileMain.swift). I have this code in ProfileMain:

    @IBAction func button(sender: AnyObject) {
//        run func updateProfile in ProfileEdit.swift
    }

How can I run func updateProfile from @IBAction func button?

I alredady googled. Solution should be:

@IBAction func titleButton(sender: AnyObject) {
    ProfileEdit.updateProfile()
}

But I'm getting this error message:

Use of instance member 'updateProfile' on type 'ProfileEdit'; did you mean to use a value of type 'ProfileEdit' instead?




ruby acessing method from parent class

I'm using this class /module: http://ift.tt/2bV6yOx

I'm getting: ``get_configurations': undefined method` errors when I attempt the below

#!/usr/bin/ruby
require './proteus-ruby-api/bluecat_api.rb'

class IPam < Bluecat::Api
  alias :p_get_configurations :get_configurations

  def initialize(subnet_list)
    @subnet_list = subnet_list

  end # end initialize

  def get_available
    print p_get_configurations[0]
    print @subnet_list
 end # end of get_available

end # end of class

a = IPam.new(["NEW-DEVELOPMENT"])
a.get_available




When calling different functions in the same class, only the first function is ever called(Python)

I'm having a bit of trouble with my class functions. On my class I have 3 different functions but whenever I call one of the functions outside of the class, it only ever calls the first one despite me typing in the correct function name.

This is the class below with the different functions, although I have only included two as I don't want you to have to search through lots of code.

class mage(baseclass):
    def __init__(self, name, level, attack, defence, hp):
        baseclass.__init__(self, name, level, hp)
        self.attack = attack
        self.defence = defence
    def __str__(self):
            return "You are now a Mage, your new stats are:\n Level: {0}\n Attack: {1}\n Defence: {2}\n HP: {3}".format(self.level, self.attack, self.defence, self.hp)
    def flamevortex(self, x, y, z):
        print("You used Flame Vortex")
        time.sleep(1.5)
        damageofmove = 3
        damagedone = damageofmove*y
        damagedoneafterdefence = damagedone - z   
        x = x - damagedoneafterdefence
        print("The monster's health is now " + str(x))
        time.sleep(1.5)
        return x
    def lightningbolt(self, x, y, z):
        print("You used Lightning Bolt")
        time.sleep(1.5)
        damageofmove = 3
        damagedone = damageofmove*y
        damagedoneafterdefence = damagedone - z   
        x = x - damagedoneafterdefence
        print("The monster's health is now " + str(x))
        time.sleep(1.5)
        return x

This is the place where I am calling the functions:

if Userattack.upper() == "FLAMEVORTEX" or "FLAME VORTEX":
                monster1.hp = p1.flamevortex(monster1.hp, p1.attack, monster1.defence)
                if chosenmove == monsterattacks[0]:
                    p1.hp = monsterlasersword(p1.hp)
                elif chosenmove == monsterattacks[1]:
                    p1.hp = monsterswipe(p1.hp)
                elif chosenmove == monsterattacks[2]:
                    monster1.hp = monsterregen(monster1.hp)
                time.sleep(1.5)
                print("After the monster's attacks, your hp is now " + str(p1.hp))
            elif Userattack.upper() == "LIGHTNINGBOLT" or "LIGHTNING BOLT":
                monster1.hp = p1.lightningbolt(monster1.hp, p1.attack, monster1.defence)
                if chosenmove == monsterattacks[0]:
                    p1.hp = monsterlasersword(p1.hp)
                elif chosenmove == monsterattacks[1]:
                    p1.hp = monsterswipe(p1.hp)
                elif chosenmove == monsterattacks[2]:
                    monster1.hp = monsterregen(monster1.hp)
                time.sleep(1.5)
                print("After the monster's attacks, your hp is now " + str(p1.hp))

No matter what the user inputs, it only ever calls the first function. I know this is a lot to process and appreciate any help. Thanks




c++ nested classes access

Following is a simplified header file detailing three Classes. I want to be able to keep the pointer in my "Game" class private, and allow Introduction to modify it. However, as is, this is not working. As Introduction is a derivative of GameState, I thought I would be able to modify this pointer? Examples had shown that this was possible. I don't really want to move this to the Public space within Game.

class Introduction;
class Game;
class GameState;

class GameState
{
    public:

    static Introduction intro;

    virtual ~GameState();
    virtual void handleinput(Game& game, int arbitary);
    virtual void update(Game& game);

};


class Introduction : public GameState
{
public:

    Introduction();

    virtual void handleinput(Game& game, int arbitary); 

    virtual void update(Game& game);

};


class Game
{
public:

    Game();

    ~Game();

    virtual void handleinput(int arbitary);

    virtual void update();

private:

    GameState* state_;

};

The example I was following was here...http://ift.tt/13DJuVL




Python classes: method has same name as property

I'm constructing a class Heating. Every instance of this class has the property 'temperature'. It's mandatory that Heating also supports the method temperature() that prints the property 'temperature' as an integer.

When I call the method temperature() I get the error 'int' object is not callable because self.temperature is already defined as an integer.

How do I solve this?

code:

class Heating: """

machine1 = Heating('radiator kitchen', temperature=20) machine2 = Heating('radiator living', minimum=15, temperature=18)
machine3 = Heating('radiator bathroom', temperature=22, minimum=18, maximum=28) print(machine1) radiator kitchen: current temperature: 20.0; allowed min: 0.0; allowed max: 100.0 machine2 Heating('radiator living', 18.0, 15.0, 100.0) machine2.changeTemperature(8) machine2.temperature() 26.0 machine3.changeTemperature(-5) machine3 Heating('radiator bathroom', 18.0, 18.0, 28.0) """ def init(self, name, temperature = 10, minimum = 0, maximum = 100): self.name = name self.temperature = temperature self.minimum = minimum self.maximum = maximum

def __str__(self):
    return '{0}: current temperature: {1:.1f}; allowed min: {2:.1f}; allowed max: {3:.1f}'.format(self.name, self.temperature, self.minimum, self.maximum)

def __repr__(self):
    return 'Heating(\'{0}\', {1:.1f}, {2:.1f}, {3:.1f})'.format(self.name, self.temperature, self.minimum, self.maximum)

def changeTemperature(self, increment):
    self.temperature += increment

    if self.temperature < self.minimum:
        self.temperature = self.minimum

    if self.temperature > self.maximum:
        self.temperature = self.maximum

def temperature(self):
    return self.temperature

testen van het programma

if name == 'main': import doctest doctest.testmod()




In Java, Are there other identifiers besides static to be used in a class? [on hold]

I only recently learned what static does when used in a class, but was wondering if there are any other ways to change how your variables are declared. If so, What are they?




User-provided Copy-constructor in CUDA

I have a problem with CUDA, actually i'm working on optimizing a program (that do a lot of calculation). I've got the following error code :

Error: cannot pass an argument with a user-provided copy-constructor to a device-side kernel launch

on the following line :

alphaAngle <<< 1, 1 >>> (positionEarthStation, positionSat, positionGeoSat, CUDA_result, CUDA_tid, AngleIteration);

The error occured 3 time on this line, i guess for the 1st, 2nd and 3rd parameters.

Their type are Cartesian which is describe as follow :

class                               Cartesian
{
public:
    double                          m_X;
    double                          m_Y;
    double                          m_Z;
    Global                          global;

private:
    double                          m_m;

public:
    __host__ __device__             Cartesian(void);
    __host__ __device__             Cartesian(const Cartesian &c);
    __host__ __device__             Cartesian(double x, double y, double z);
    /*__host__ __device__   Cartesian&  operator=(const Cartesian& c);*/
    __host__ __device__ void        set(double x, double y, double z);
    __host__ __device__ double      magnitude(void);
    __host__ __device__ LatLonAlt   ToLLA(void);
};

What i'm doing is call a kernel from another kernel and pass arguments received and/or modified as parameter of the function called. Function calling :

__global__ void SatPositionKernel(Cartesian positionEarthStation, Propagator *CUDA_sat, Cartesian positionGeoSat, int timeIndex, int AngleIteration)
{
    /* Calculer la position du satellite défilant */
    int         tid, CUDA_tid[BLOCKS_ANGLE], index;
    double      CUDA_result[BLOCKS_ANGLE];
    Cartesian   positionSat, output;
    Global      global;

    if ((tid = threadIdx.x + blockIdx.x * blockDim.x) < NB_SAT)
    {
        positionSat = CUDA_sat[tid].evaluate(timeIndex * STEP, SIMULATION_DURATION, 0, true);
        /* Pour chaque position sur l'orbite geostationnaire */
        alphaAngle <<< 1, 1 >>> (positionEarthStation, positionSat, positionGeoSat, CUDA_result, CUDA_tid, AngleIteration);
        cudaDeviceSynchronize();
        index = getIndex(CUDA_result);
        output.set(positionGeoSat.m_X * cos(STEP * index) + positionGeoSat.m_Y * -sin(STEP * index), positionGeoSat.m_X * sin(STEP * index) + positionGeoSat.m_Y * cos(STEP * index), positionGeoSat.m_Z);
        printf("The sat %s at Time %f is as position (%.3f, %.3f, %.3f)\nThe Base at position (%.3f, %.3f; %.3f)\nThe Geo-orbital position is (%.3f, %.3f, %.3f)\nThe angle formed is %.15f",
            CUDA_sat[tid].m_name, timeIndex * STEP, positionSat.m_X, positionSat.m_Y, positionSat.m_Z, positionEarthStation.m_X, positionEarthStation.m_Y, positionEarthStation.m_Z,
            output.m_X, output.m_Y, output.m_Z, global.radToDeg(CUDA_result[index]));
    }
}

Function called

__global__ void         alphaAngle(Cartesian EarthStation, Cartesian Sat, Cartesian GeoSat, double *CUDA_result, int *CUDA_tid, int iteration)
{
    __shared__ double   tmp[THREADS_ANGLE][2];
    Cartesian           new_pos, vecU, vecV;
    Global              global;
    int                 tid, idx, i;

    idx = threadIdx.x;
    if ((tid = threadIdx.x + blockIdx.x * blockDim.x) < iteration)
    {
        new_pos = global.rotationZAxis(GeoSat, STEP_ANGLE * tid);
        vecU.set(Sat.m_X - EarthStation.m_X, Sat.m_Y - EarthStation.m_Y, Sat.m_Z - EarthStation.m_Z);
        vecV.set(new_pos.m_X - EarthStation.m_X, new_pos.m_Y - EarthStation.m_Y, new_pos.m_Z - EarthStation.m_Z);
        tmp[idx][0] = global.dotProduct(vecU, vecV);
        tmp[idx][1] = (double)tid;
    }
    __syncthreads();
    i = THREADS_ANGLE / 2;
    while (i != 0)
    {
        (idx < i && tmp[idx][0] > tmp[idx + i][0]) ? (tmp[idx][0] = tmp[idx + i][0], tmp[idx][1] = tmp[idx + i][1]) : (0);
        __syncthreads();
        i /= 2;
    }
    (idx == 0) ? (CUDA_result[blockIdx.x] = tmp[0][0], CUDA_tid[blockIdx.x] = (int)tmp[0][1]) : (0);
}

PositionEarthStation defined as follow in previous function :

Cartesian       positionEarthStation(1597885.53777688, 1253552.16551859, 6046164.27311665);

position sat defined in function calling.

positionGeoSat defined as follow in previous function :

positionDebutArcGeo = findStartGeo(positionEarthStation);

I tried to do something with approximatly the same operation/affectation in another code. Here it is :

__global__ void kernel2(Cartesian *titi)
{
    printf("fils titi[0](%f, %f, %f)\n", titi->m_X, titi->m_Y, titi->m_Z);
}

__global__ void kernel(Cartesian *toto)
{
    printf("parent\n");
    printf("pere titi[0](%f, %f, %f)\n", toto->m_X, toto->m_Y, toto->m_Z);
    toto->set(3, 2, 1);
    kernel2 << < 1, 1 >> > (toto);
    cudaDeviceSynchronize();
}

__global__ void test2(Cartesian titi)
{
    printf("fils titi(%f, %f, %f)\n", titi.m_X, titi.m_Y, titi.m_Z);
}

__device__ Cartesian get_momo(void)
{
    return (Cartesian(1, 1, 1));
}

__global__ void test(Cartesian titi)
{
    Cartesian       momo(1, 2, 6);

    momo = get_momo();
    printf("pere titi(%f, %f, %f)\n", titi.m_X, titi.m_Y, titi.m_Z);
    titi.set(1, 2, 3);
    test2 << < 1, 1 >> > (momo);
    cudaDeviceSynchronize();
}

int     main(void)
{
    Cartesian   titi, *toto;
    titi.m_X = 1;
    titi.m_Y = 1;
    titi.m_Z = 2;
    cudaMalloc((void **)&toto, sizeof(Cartesian));
    cudaMemcpy(toto, &titi, sizeof(Cartesian), cudaMemcpyHostToDevice);
    test << < 1, 1 >> > (titi);
    cudaDeviceSynchronize();
    printf("fin\n");
}

Cartesian type : same definition.

For the constructor / set function :

__host__ __device__     Cartesian::Cartesian(void) : m_X(0), m_Y(0), m_Z(0) {}

__host__ __device__     Cartesian::Cartesian(double x, double y, double z) : m_X(x), m_Y(y), m_Z(z) {}

__host__ __device__ void    Cartesian::set(double x, double y, double z)
{
    m_X = x;
    m_Y = y;
    m_Z = z;
    m_m = -1;
}

But on that code it work perfectly, if someone have an idea, need mode information/code/something tell me !

Thanks for your help !




C++ Copy Constructor Error

Say I have the following piece of code:

class C1{
int x, y;

public:

    C1(int a, int b):x(a),y(b)
    {
        cout<<"const normal C1"<<endl;
    }
};

class C2 : protected C1
{
    int x, y;
    const int z;

public:
    C2(int u, int v, int w):C1(u,v),z(w)
    {
        cout<<"constr normal C2"<<endl;
    }
    C2(const C2 &a,int u, int v, int w):C1(u,v),z(w)
    {
        cout<<"cpy constr C2"<<endl;
    }
};

int main(){
C2 a(2,3,4);
C2 b=a;
}

When I create the object b, the copy constructor is supposed to be called instead of the normal constructor, but it is not. Now I know that a copy constructor should look like

C(C const& obj){...}

where C is a class, but in this case, I need the other parameters for C1's constructor. Now, my question is, what have I done wrong, or what can I do in order to make the copy constructor work properly?




How can i define same class name in php?

I was trying to define same class name in php for 3 time. Is it possible to define??




C# Datagridview and Oledb

I am not very familiar with Oledb but I do want to use it within my Windows form project to store records, in a table, from an access DB into a datagridview. However, I would want to use a class method where it would return some values of data where I can then fill it with a dataadapter. Can someone please help me? Any code suggested would be fine; I can study it.




state pattern C++

I'm trying to instigate a simple State pattern, after following some of the excellent tutorials here: http://ift.tt/13DJuVL

I am half way through this current tutorial, and I am trying to replicate the static instances of each state, by containing them within the base class. However, when it comes to switching states, g++ is throwing this error.

   state_test.cpp: In member function ‘virtual void Introduction::handleinput(Game&, int)’:
state_test.cpp:55:16: error: cannot convert ‘Playing*’ to ‘GameState*’ in assignment
    game.state_ = &GameState::play;
                ^

Now, I understand the error involves the conversion of the pointer, but I am really struggling to see how to fix it. As I was following this guys code, I kind of expected it to work, but because he is changing it as he goes along and trying to reinforce best practice, I don't have his complete source code to follow. However, I feel it is important for me to understand the code at this stage, before I move through the rest of the tutorial.

Following is the code I created, attempting to replicate his state system:

#include <iostream>

class Game;
class Introduction;
class Playing;

class GameState
{
public:

    static Introduction intro;
    static Playing play;

    virtual ~GameState() {std::cout << "an undefined GameState has been destroyed" << std::endl;}
    virtual void handleinput(Game& game, int arbitary) {}
    virtual void update(Game& game) {}

};

class Game
{
public:

    Game()
    {}
    ~Game()
    {}

    virtual void handleinput(int arbitary)
        {
            state_->handleinput(*this, arbitary);
        }

    virtual void update()
        {
            state_->update(*this);
        }

//private: 
    GameState* state_;
};

class Introduction : public GameState
{
public:

    Introduction()  
    {
        std::cout << "constructed Introduction state" << std::endl;
    }

    virtual void handleinput(Game& game, int arbitary) 
        {
            if (arbitary == 1)
            game.state_ = &GameState::play;
        }

    virtual void update(Game& game) {}
};

class Playing : public GameState
{
public:
    Playing()   {std::cout << "constructed Playing state" << std::endl;}

    virtual void handleinput(Game& game, int arbitary) 
        {
            if (arbitary == 0)
            game.state_ = &GameState::intro;
        }

    virtual void update(Game& game) {}
};

int main(int argc, char const *argv[])
{
    Game thisgame;

    return 0;
}

Any ideas why my implementation isn't compiling?




Finding out where my method is getting used?

I have a class and I don't know if there are any objects calling this class. Is there a way to list all objects which call a method of a specific class? What I need is the file name and maybe the line number.




For auto generation of payslip first i am running main class but i am getting this errors

*Mainclass.java *

package com.srishti.Generatepayslip.payroll;
import com.Service.GenearatePaySlipService;

public class MainClass
{
public static void main(String[] args)
{
      try {
          GenearatePaySlipService genearatePaySlipService=new GenearatePaySlipService();
          genearatePaySlipService.createpayslip();
        } 
      catch (Exception e) {
            System.err.println("Got an exception!");
            System.err.println(e.getMessage());
        }
}
}

Errors:

javax.naming.CommunicationException: Receive timed out [Root exception is java.net.SocketTimeoutException: Receive timed out]
at org.jnp.interfaces.NamingContext.discoverServer(NamingContext.java:1302)
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1417)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:579)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:572)
at javax.naming.InitialContext.lookup(Unknown Source)
at com.DAO.GeneratePayslipDAO.getEmployeesList(GeneratePayslipDAO.java:32)
at com.Service.GenearatePaySlipService.<init>(GenearatePaySlipService.java:31)
at com.srishti.Generatepayslip.payroll.MainClass.main(MainClass.java:8)

Caused by:

java.net.SocketTimeoutException: Receive timed out
at java.net.TwoStacksPlainDatagramSocketImpl.receive0(Native Method)
at java.net.TwoStacksPlainDatagramSocketImpl.receive(Unknown Source)
at java.net.DatagramSocket.receive(Unknown Source)
at org.jnp.interfaces.NamingContext.discoverServer(NamingContext.java:1272)
... 7 more

Hi I am trying to generate the auto genartion of payslip with out manual enter of data. For this i am not using any servlet and jsp. First i am running the class for this i added jboss-common-client-3.2.3.jar and jnp-client-4.0.2.jar.Please help me to resolve it.




Storing static values (tables, single values for calculations)

I am in the planning of architecture to the calculation program associated with the construction (to study). For the calculations I need to create a little table of numerical values and text, and other single constant values. And here the question of whether to create a class in which I retain only constants and nothing more and then will be taken from here to the object through the constructor, in another class that contains only specific data for calculation? Is there some other more interesting and better way?




Powershell Add-Type - Add member of type dictionary/hashtable

I am trying to add a custom type in powershell like this:

Add-Type @'
public class MyType {
    public string name;
    public string type;
    public hashtable data;
    public string category;
}
'@

However, the type hashtable, dictionary does not exist. I have looked around for examples regarding this but could not find any.

Might add, that I do not want to use Add-Member.

Any ideas?

/Patrik




Android studio: Builded jar file not generating some class files

  • Hi i downloaded the vector chat application from this link and i imported it as a superate project (By using java 1.7 sdk only it was working).

  • As a superate project it's working perfectly then i imported (by copying manually) this project to my personal project then i got some error, by spending some time i resolved almost all errors but now i'm getting the error as cannot resolve symbol RoomPreviewData.

  • This RoomPreviewData class file was generating in the jar file in vector project (inside of build folder) but in my personal project it's not generating the RoomPreviewData.

  • For understanding i'm attaching the images to this question. So, any one please help me to solve this

Vector project image enter image description here

Failure project image enter image description here




dimanche 28 août 2016

Using Android MediaPlayer Class in other Classes

Please How can I create an Android MediaPlayer class (Player.class) and use it in other project classes like in MainActivity.class to be in simple usage like: // to play a specific audio file Player.PlayAudio("myaudio.mp3");
// to pause
Player.pause();
// to play
Player.play();
// to stop
Player.stop;
// to resume
Player.resume();
// to check if is already playing and return a boolean
Player.isplaying();
I just wanted something like this! Every answer is highly appreciated thank you guys :)




Instance of an abstract class not working

I'm sure many of you would mark this as repeaed the second you see the title. Please bear with me..Facing a complicated issue. :)

Thanks for reading till here :D

So, I have a class called InfoClass, which is abstract-

public abstract class InfoClass
{
    public abstract string Brand { get; set; }
    public abstract string BrandCount { get; set; }
}

I have a service in which I'm making a list out of it..and down the line tryin to make an instance of the same. But not able to-

[WebMethod]
    public void GetInfoList()
    {
        List<InfoClass> listInformations = new List<InfoClass>();
        .
        .
        .      //Going ahead in the program I've created a reader
        .
        .
        .
        .
            while (rdr.Read())
            {
                //This is the block not working
                InfoClass Advertises = new InfoClass();
                Advertises.Brand = Convert.ToString(rdr["Brand"]);                    
            }

Please help me out with an alternative to the code. I'm sure the class is meant to be abstract, So we cant change it on the class level.




How to change which class variable is being called depending on user input?

I've created a class called Earthquake which stores relevant earthquake data (its magnitude, time it hit, etc.) in class variables. I want to ask the user which data they'd like to see, then print out that data for them like so:

earthquake1 = Earthquake()

answer = input("What data would you like to see?")
print(earthquake1.answer)

In the example above, if the user answers magnitude, I want to print out the class variable earthquake1.magnitude.

Is there some way of doing this?




Single responsibility principle of a class

I am using a library which provides me a callback everytime a message is received. But within this callback I cannot publish a message to whoever the object that sent the message. So what I've done is I created another class "ReceivedMessageHandler" and created a Queue in that class. Then from the callback method I call the insertToQueue method of ReceivedMessageHandler and process the messages there. Now there is a ScheduledExecutor in the ReceivedMessageHandler class that processes the queue. So according to single responsibility of a class, is what I've done correct or should I create another class which has the Queue object and has getters setters for it. Then process the items in that queue in the ReceivedMessageHandler. Is that how it should be done or is what I've done correct? Any advice would be much appreciated.