samedi 31 octobre 2015

Python : List in a class is not dumping to file

When i dump the list in the file and restart the program and try to retrieve it, it returns an empty list.

Am i doing something wrong?

import pickle
class student():
    s1marks=[]
    def getdata(self):
        for i in range(20):
            self.s1marks.append(i)
    def outdata(self):
        print self.s1marks

def einput():
    f=open('student1.dat','ab')
    e=student()
    e.getdata()
    pickle.dump(e,f)
    f.close()
def edisplay():
    f=open('student1.dat','rb')
    try:
        while True:
            e=pickle.load(f)
            e.outdata()
    except EOFError:
        pass
    f.close()




increment Class with javascript

How can I increment particular class? I'm using clone method, I have successfully cloned Id and increment it. But I want to increment my class within Div which I'm incrementing.

My class to increment : .emptybox

My js :

//duplicate Play Timer
    var i = 0;
    var original = document.getElementById('Play_Start');
    var count = 1;

    function duplicatePlay() {
        if (count < 20) {
            var clone = original.cloneNode(true); // "deep" clone
            clone.id = "Play_Start" + ++i; // there can only be one element with an ID
            original.parentNode.appendChild(clone);
            $(clone).effect( "highlight", {color:"#FEFFB9"}, 3000 );
            count++;
        } else {
        }

    }




C++ - Structure Methods Syntax

I get a weird error when I try and compile the following code: I need to use structs (I was taught classes with the struct keywor, and am trying to learn it that way. I also need to put the function definitions outside the struct block.

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

struct Box {
 int l;
 int w;
 int area();
 Box();
 Box(int a, int b);
 Box operator+(const Box a, const Box b);
};

Box::Box() {
 l = 0;
 w = 0;
}
Box::Box(int a, int b) {
 l = a;
 w = b;
}
Box Box::operator+(const Box a, const Box b) {
 Box box(a.l + b.l, a.w + b.w);
 return box;
}
int Box::area() {
 return l * w;
}
int main() {
 Box a(1, 2);
 Box b;
 b.l = 3;
 b.w = 4;
 Box c = a + b;
 cout << "Total area is: " << a.area() << " + " << (b.area) << " = " << (c.area) << endl;
}

Could someone help me out? Thanks




How to define this kind of php function?

I saw some sample php scripts can use a function after one another, but I can't find how to write script like that.

When I write the php script:

class apple {
  function banana() {
    echo 'Hi!';
  }
}

It looks like this when I want to call the function banana:

$apple = new apple;
$apple->banana();

What if I want to call a function right after the previous one, like this:

$apple->banana()->orange()

I've tried to put an function inside another, but it returns with error. How can I write the script like this?




LNK2019 in class declaration and definition

I know there are several questions on this. I have checked the MSDN page for LNK2019 error but I can not seem to specify why this error appeared.

This is my declaration file:

#ifndef _COLLEGE_H_
#define _COLLEGE_H_
#include"SVCQ.h"
#include"SVTT.h"
#include<vector>

class College
{
private:
    std::vector<SVCQ> listCQ;
    std::vector<SVTT> listTT;
protected:
    std::ostream& print(std::ostream & os) const;
    std::istream& input(std::istream& is, int size1, int size2);
public:
    College();
    ~College();

    //ouput, input
    friend std::ostream& operator<<(std::ostream& os, const Daihoc& obj);
    friend std::istream& operator>>(std::istream& is, Daihoc& obj);

        //some more functions

};

#endif

And this is my definition file:

#include "College.h"


College::College()
{
}


College::~College()
{
}

std::ostream& College::print(std::ostream & os) const
{
    for (size_t it = 0; it < listCQ.size(); ++it)
    {
        os << listCQ[it];
    }

    for (size_t it = 0; it < listTT.size(); ++it)
    {
        os << listTT[it];
    }

    return os;
}

std::istream& College::input(std::istream& is, int size1, int size2)
{
    listCQ.resize(size1);
    listTT.resize(size2);

    std::cout << "\n-----------------ENTER LIST CQ-----------------:\n";
    for (size_t it = 0; it < listCQ.size(); ++it)
    {
        std::cout << "#" << it + 1 << std::endl;
        is >> listCQ[it];
        std::cout << std::endl;
    }

    std::cout << "\n-----------------ENTER LIST TT-----------------:\n";
    for (size_t it = 0; it < listTT.size(); ++it)
    {
        std::cout << "# " << it + 1 << std::endl;
        is >> listTT[it];
        std::cout << std::endl;
    }

    return is;
}
std::ostream& operator<<(std::ostream& os, const College& obj)
{
    return obj.print(os);
}
std::istream& operator>>(std::istream& is, College& obj)
{
    int size1 = 0, size2 = 0;
    std::cout << "ENTER QUANTITY OF CQ: ";
    is >> size1;
    std::cout << "\nENTER QUANTITY OF TT: ";
    is >> size2;
    std::cout << std::endl;
    return obj.input(is, size1, size2);
}

The LNK2019 messages specify my flaws in the protected print and input method but I don't see anything wrong here. Can anyone help me?




Tic Tac Toe : Java

I'm really lost, I'm having trouble building this game. I need your guys help. Been struggling for days now to figure this out. I have three classes, Driver, Board, and Player. I have the driver, and I think the board class under control. I'm mainly struggling with the player class. The goal of this is to have a computer player be able to randomly input into the array, and then have the player be able to input their choice of where they want to play.

public class Driver
{
    public static void main(String[] args)
    {
        //new tic-tac-toe board
        Board board = new Board();

        //two new players (conputer and human)
        Player computer = new Player(board, "X");   //Give computer player access to board and assign as X.
        Player human = new Player(board, "O");      //Give human player access to board and assign as O.
        board.print();
        computer.computerMove();

        //while the game is not over
        while(!board.gameOver())
        {
            //let computer move first
            computer.computerMove();

            //print tic-tac-toe board
            board.print();

            //if the game is not over yet
            if (!board.gameOver())
            {
                //let the human make a move
                human.humanMove();

                //if the game is over
                if (board.gameOver())
                {
                    //print the board
                    board.print();
                }
            }
        } 

        //print out the winner (if there is one) of the game
        board.printWinner();
    }
}

Board class

public class Board
{
    private String player = "X";
    private String cpu = "O";
    int row = 3;
    int column = 3;
    private String[][] theBoard = new String[row][column] ;

    public Board()
    {
        theBoard = theBoard;
    }

    public boolean gameOver()
    { 
       if  (theBoard[0][0] == player && theBoard[0][1] == player && theBoard[0][2] == player || // 1st row
            theBoard[1][0] == player && theBoard[1][1] == player && theBoard[1][2] == player || // 2nd row
            theBoard[2][0] == player && theBoard[2][1] == player && theBoard[2][2] == player || // 3rd row
            theBoard[0][0] == player && theBoard[1][0] == player && theBoard[2][0] == player || // 1st col.
            theBoard[0][1] == player && theBoard[1][1] == player && theBoard[2][1] == player || // 2nd col.
            theBoard[0][2] == player && theBoard[1][2] == player && theBoard[2][2] == player || // 3rd col.
            theBoard[0][0] == player && theBoard[1][1] == player && theBoard[2][2] == player || // Diagonal          \ 
            theBoard[2][0] == player && theBoard[1][1] == player && theBoard[0][2] == player) //   Diagonal      /
            {
                return false;
            }
        else if (theBoard[0][0] == cpu && theBoard[0][1] == cpu && theBoard[0][2] == cpu || // 1st row
            theBoard[1][0] == cpu && theBoard[1][1] == cpu && theBoard[1][2] == cpu || // 2nd row
            theBoard[2][0] == cpu && theBoard[2][1] == cpu && theBoard[2][2] == cpu || // 3rd row
            theBoard[0][0] == cpu && theBoard[1][0] == cpu && theBoard[2][0] == cpu || // 1st col.
            theBoard[0][1] == cpu && theBoard[1][1] == cpu && theBoard[2][1] == cpu || // 2nd col.
            theBoard[0][2] == cpu && theBoard[1][2] == cpu && theBoard[2][2] == cpu || // 3rd col.
            theBoard[0][0] == cpu && theBoard[1][1] == cpu && theBoard[2][2] == cpu || // Diagonal          \ 
            theBoard[2][0] == cpu && theBoard[1][1] == cpu && theBoard[0][2] == cpu) //   Diagonal      /

            {
                return false;
            }
       else{

           return true;
        }
    }

    public void print()
    {

        System.out.println(theBoard[0][0] + " | " + theBoard[0][1]+ " | " + theBoard[0][2] + "\n----------");

        System.out.println(theBoard[1][0] + " | " + theBoard[1][1]+ " | " + theBoard[1][2] + "\n----------");

        System.out.println(theBoard[2][0] + " | " + theBoard[2][1]+ " | " + theBoard[2][2] + "\n");

    }

    public void printWinner()
    {
       if  (theBoard[0][0] == player && theBoard[0][1] == player && theBoard[0][2] == player || // 1st row
            theBoard[1][0] == player && theBoard[1][1] == player && theBoard[1][2] == player || // 2nd row
            theBoard[2][0] == player && theBoard[2][1] == player && theBoard[2][2] == player || // 3rd row
            theBoard[0][0] == player && theBoard[1][0] == player && theBoard[2][0] == player || // 1st col.
            theBoard[0][1] == player && theBoard[1][1] == player && theBoard[2][1] == player || // 2nd col.
            theBoard[0][2] == player && theBoard[1][2] == player && theBoard[2][2] == player || // 3rd col.
            theBoard[0][0] == player && theBoard[1][1] == player && theBoard[2][2] == player || // Diagonal          \ 
            theBoard[2][0] == player && theBoard[1][1] == player && theBoard[0][2] == player) //   Diagonal      /
            {
                System.out.println("X - won!");
            }
        else if (theBoard[0][0] == cpu && theBoard[0][1] == cpu && theBoard[0][2] == cpu || // 1st row
            theBoard[1][0] == cpu && theBoard[1][1] == cpu && theBoard[1][2] == cpu || // 2nd row
            theBoard[2][0] == cpu && theBoard[2][1] == cpu && theBoard[2][2] == cpu || // 3rd row
            theBoard[0][0] == cpu && theBoard[1][0] == cpu && theBoard[2][0] == cpu || // 1st col.
            theBoard[0][1] == cpu && theBoard[1][1] == cpu && theBoard[2][1] == cpu || // 2nd col.
            theBoard[0][2] == cpu && theBoard[1][2] == cpu && theBoard[2][2] == cpu || // 3rd col.
            theBoard[0][0] == cpu && theBoard[1][1] == cpu && theBoard[2][2] == cpu || // Diagonal          \ 
            theBoard[2][0] == cpu && theBoard[1][1] == cpu && theBoard[0][2] == cpu) //   Diagonal      /

            {
                System.out.println("O - won!");
            }


    }
}

And Player class, this is the one I'm struggling with the most.

import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;
public class Player

{
    String player = "X";
    String cpu = "O";

    int row = 3;
    int column = 3;

    private String[][] ticTac = new String[row][column];
    //Do I even need to build a new array? Not sure how to access 
    //the board from the board class.       

    public static Scanner scan = new Scanner(System.in);
    public Player(Board board, String inBoard )
    {
        //what do I do in this portion?
    }

    public void computerMove()
    {
        //what do I do in this portion?
    }        

    public void humanMove()
    {
        //what do I do in this portion?
    }
}




Javascript class events set for one instance fire for all subsequent instances

I have a class which creates mousedown listeners for each LI. However, a click to the LI of the first instance fires events for every LI instance which was created after it. If you create a 3rd instance, the click on the 1st fires for all 3 and a click on the 2nd fires for the 2nd and 3rd, etc.

To duplicate, run the jsfiddle and click on the two links (one after the other) which will create two UL elements each containing an LI element. Alerts() are set up to show each event firing.

I'm new to creating classes in javascript, so I've obviously missed something, but can't see why the events for the multiple instances are not separate. In case you're wondering, I've created my class the way I did to allow for static variables and methods. I am not using jQuery.

I've posted a jsfiddle of the below code

<div id="outer">
    <a href="#" onclick="edit('g123')">Click here first id=g123</a>
    <br> 
    <a href="#" onclick="edit('g234')">Click here second id=g234</a>
</div>    

<script>

listbox = (function (id) {
    var currentul = "";

    function listbox(id) {
        this.id = id;
    };

    // show or hide once all the properties are set
    listbox.prototype.go = function () {
        this.initlistbox();
        this.addlisteners();
    }

    // create the elements for drag and drop between two list boxes
    listbox.prototype.initlistbox = function () {
        var _this = this;
        var divlist = document.createElement('div');
        divlist.style.minHeight = '100px';
        divlist.style.width = '300px'
        divlist.style.outline = '1px solid blue'

        // the UL
        var ul = document.createElement('ul');
        ul.setAttribute('id', 'ulchosen-' + this.id);

        // track which UL is active for keystrokes
        ul.addEventListener('click', function (e) {
            if (e.stopPropagation) e.stopPropagation();
            currentul = this.id;
        }, false);

        // add the ul to the div
        divlist.appendChild(ul);

        divouter = document.getElementById("outer");
        // add the div to the body
        divouter.appendChild(divlist);

        // The LI
        // create LI elements
        var li = document.createElement('li');
        li.setAttribute('id', 'lb-li-chosen-1');
        li.innerHTML = "Hello " + this.id;
        ul.appendChild(li);

    };

    listbox.prototype.addlisteners = function () {
        var _this = this;

        var lis = document.querySelectorAll("[id^='lb-li-']");
        for (var i = 0; i < lis.length; i++) {
            this.setlilisteners(lis[i]);
        }
    };

    listbox.prototype.setlilisteners = function (el) {
        var _this = this;

        // click is for non drag, non shift / ctrl
        el.addEventListener('click', function (e) {
            alert("A: " + _this.id);
            e.preventDefault();
            return false;
        }, false);

        // mousedown is to select LI elements
        el.addEventListener('mousedown', function (e) {
            e.stopPropagation();
            e.preventDefault();
            alert("B: " + _this.id);
            return false;
        }, false);

    };

    return listbox;
})();

function edit(id) {
    var a = new listbox(id);
    a.go();
} 
</script>




How to Instantiate a class in a generic class in java

public class DictionaryBase<T extends IData> {
    protected Map<String, T> mdic = new HashMap<>();

    protected T Add(String Name) {
        T objNew = new T();

        objNew.Name(Name);
        mdic.put(Name, objNew);

        return objNew;
    }

On new T() I have the Error. What is the correct way to do this?




On how to properly use the following classes on graphs in C#

At the moment, I am trying to learn C# through implementing various algorithms. I asked this question on how to represent a graph in C#, and the user michaelb suggested to use classes. I tried to construct a graph with these classes in the following code.

I'm used to classes having a constructor, in which I can set the fields of the object I'm creating, but these classes only seem to have the default no-arguments constructors. I have three questions:

Are the "entities" in the classes even fields, e.g. does public Node From; constitute a field in the Edge class?

Isn't it weird that the classes Edge and Node refer to each other? It looks like a two-fold self-referential loop, in which they are defined in terms of each other.

When I try to run my code, I get the error at the step G.Nodes.Add(v1); that says System.NullReferenceException. What did I do wrong, and what would be the proper way of using these classes?

Thanks.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Graph G = new Graph();
        Node v1 = new Node();
        Node v2 = new Node();
        Node v3 = new Node();
        G.Nodes.Add(v1);
        G.Nodes.Add(v2);
        G.Nodes.Add(v3);
        Edge e1 = new Edge();
        Edge e2 = new Edge();
        e1.From = v1;
        e1.To = v2;
        e2.From = v2;
        e2.To = v3;
        v1.EdgesOut.Add(e1);
        v1.EdgesIn.Add(e1);
        v2.EdgesOut.Add(e2);
        v3.EdgesIn.Add(e2);

        Console.WriteLine(G);
        Console.ReadKey();

    }
}

class Edge
{
    public Node From;
    public Node To;
}

class Node
{
    public List<Edge> EdgesIn;
    public List<Edge> EdgesOut;
}

class Graph
{
    public List<Node> Nodes;
}




Simultaneous CGAL calculations in multiple threads

I'm trying to run multiple geometric calculations with CGAL simultaneously in multiple threads. All threads are 100% "isolated" from each other. Nevertheless the app crashes with an access violation:

http://ift.tt/1Rkv8TQ

I've build a small example app to reproduce the error:

main.cpp

#include <fstream>
#include "windows.h"
#include "cTestClass.h"

int main ( int argc, char *argv[] ){

    cTestClass *eval0 = new cTestClass("d://.partion_2.stl", 0);
    cTestClass *eval1 = new cTestClass("d://.partion_2.stl", 1);

    eval0->start_eval();
    eval1->start_eval();

    return EXIT_SUCCESS;
}

cTestClass.h

#ifndef CTEST_CLASS_H
#define CTEST_CLASS_H

#include <atomic>
#include <thread>

class cTestClass
{
private:
    std::atomic<bool> flag_eval_finished;
    std::thread eval_thread;
    std::string stl_file_name;
    unsigned int thread_index;

    cTestClass(){ }
    void evaluate_partition();

public:
    cTestClass(std::string argStlFile, unsigned int argThread_index);
    void start_eval();
    bool eval_finished(); 
};

#endif

cTestClass.cpp

#include "cTestClass.h"

#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/Nef_polyhedron_3.h>
#include <CGAL/polygon_soup_to_polyhedron_3.h>
#include <CGAL/IO/Polyhedron_builder_from_STL.h>

#include <iostream>
#include <fstream>

//typedef CGAL::Cartesian<double> Kernel;
typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron_3;
typedef CGAL::Nef_polyhedron_3<Kernel>  Nef_polyhedron_3;
typedef CGAL::Point_3<Kernel> Point_3;

//typedef Polyhedron::Point_iterator Point_iterator;
typedef Polyhedron_3::Vertex_iterator Vertex_iterator;
typedef Polyhedron_3::Facet_iterator Facet_iterator;
typedef Polyhedron_3::Halfedge_around_facet_circulator Halfedge_facet_circulator;
typedef Nef_polyhedron_3::Volume_const_iterator Volume_const_iterator;
typedef Kernel::Iso_cuboid_3 Iso_cuboid;

//constructor
cTestClass::cTestClass(std::string argStlFile, unsigned int argThread_index)
{
    thread_index = argThread_index;
    stl_file_name = argStlFile;
    flag_eval_finished = false;
}

//===========================================================================================
// public member functions
void cTestClass::start_eval()
{
    std::cout << "Thread " << thread_index << ": start" << std::endl;
    eval_thread = std::thread(&cTestClass::evaluate_partition, this);
}

bool cTestClass::eval_finished()
{
    return flag_eval_finished;
}

//===========================================================================================
//private member functions
void cTestClass::evaluate_partition()
{

    //read stl file and create cgal polyhedron
    Polyhedron_3 poly_Partition; 
    std::ifstream stl_file(stl_file_name.c_str(), std::ifstream::in);
    std::vector<CGAL::cpp11::array<double, 3> > points;
    std::vector<CGAL::cpp11::array<int, 3> > triangles;
    CGAL::read_STL(stl_file, points, triangles);
    stl_file.close();

    //create polyhedron
    CGAL::polygon_soup_to_polyhedron_3(poly_Partition, points, triangles);


    //convert polyhedron to nef_poly representation
    std::cout << "Thread " << thread_index << ": " <<"Converting partition polyhedron to Nef representation" << std::endl;
    Nef_polyhedron_3 nefpoly_Partition(poly_Partition);

    flag_eval_finished = true;
}

Anyone got an idea what causes this crash?

Best regards

Monchi




How can I find out how many objects have been created from a class before in C++?

How can I find out how many objects have been created from a class before in C++?




Which implementation in JPA should be followed to optimize the login

A class diagram

Hey guys, I'm having a doubt about the implementation of class diagram above, confused between the Single_table strategy and the joined_table strategy, any help, any suggestion about the patterns followed in this case that are used to enhance the response time of the login process. Any help will be appreciated. Thank you guys in advance :).




Python Inheritance - Instance Has No Attribute

I'm new to python and just trying to test the syntax and get to know it. The code below works fine except for when I get to inheritance. The final command "toString" function is not working and I can't for the life of me figure out why.

I'm sure I'm not doing something the most efficient way, but even if there's a more efficient way I'd first like to understand why what I'm doing is wrong. thanks a lot. Please let me know if I need to clarify anything

#!/bin/python

class Animal:


        __name = ""
        __height = 0
        __weight = 0
        __sound = 0

        def __init__(self, name, height, weight, sound):
                self.__name = name
                self.__height = height
                self.__weight = weight
                self.__sound = sound

        def set_name(self,name):
                self.__name = name

        def get_name(self):
                return self.__name


        def set_height(self,height):
                self.__height = height

        def get_height(self):
                return self.__heiight

        def set_weight(self,weight):
                self.__weight=weight

        def get_weight(self):
                return self.__weight

        def set_sound(self,sound):
                self.__sound = sound

        def get_sound(self):
                return self.__sound

        def get_type(self):
                print("Animal")

        def toString(self):
                return("{} is {} inches tall, {} lbs, and says {}".format(self.__name, self.__height,self.__weight,self.__sound))



objCat = Animal('Whiskers', 33, 10, 'Meow')
print (objCat.toString())


# Attempt Inheritance

class cDog(Animal):

        __owner=""

        def __init__(self,name,height,weight,sound,owner):
                self.__owner=owner
                Animal.__init__(self,name,height,weight,sound)

        def __str__(self):
                return ("{}".format(self.__height))

        def set_owner(self,owner):
                self.__owner=owner

        def get_owner(self):
                return self.__owner

        def get_type(self):
                print("Dog")

        def toString(self):
                return ("{} is {} inches tall, {} lbs, says {}, and is owned by, {}".format(self.__name,self.__height,self.__weight,self.__sound,self.__owner))


objDog = cDog('Brewsky', 20, 75, 'Ruff', 'Jared')
print (objDog.toString())




How Can I Use Comparators and Collections In Order To Sort A Text File In Different Ways? (Java)?

So I'm having an extremely hard time trying to use Comparators in order to sort and display a text file in different ways. I'm suppose to use 5 different comparators in order to sort the file by id number, salary (Smaller to larger), salaried (Salaried then non-salaried), alphabetized name (last and first), and also display the original. Here is the original text file

id  firstName   lastName    salaried    salary

200 Caroline    James   false   37654
2   Julian  James   false   46499
1   Conor   Habgren true    88767
10  Tillie  Donalan true    98456
15  Alice   Jeanu   true    72821
12  Fred    Habgren false   28767
103 Mary    Donalan false   28456
135 Ed  Jeanu   true    52821

I was able to use an ArrayList and get all the id numbers, first names, lastnames, and so on into the variable that it belongs to (I.E all the id numbers in the Id variable). My problem now is how do I go about sorting the text using Comparators and collections? So far I have three different classes, and EmployeeOrderingDemo class (the driver class), an ExployeeFX class, and an EmployeeOrdering class. Here is my driver class

import java.util.List;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class EmployeeOrderingDemo {

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

    List<EmployeeFX> list = new ArrayList<EmployeeFX>();


    try {
        File myFile = new File("P01_DATA.txt");
        Scanner inputFile = new Scanner(myFile);
        inputFile.nextLine();
        inputFile.nextLine();


        while (inputFile.hasNextLine()) {
            String line = inputFile.nextLine();

            String[] details = line.split("\\s+");
            int id = Integer.parseInt(details[0]);
            String firstName = details[1];
            String lastName = details[2];
            boolean salaried = Boolean.parseBoolean(details[3]);
            double salary = Double.parseDouble(details[4]);
            EmployeeFX p = new EmployeeFX(id, firstName, lastName,
                    salaried, salary);
            list.add(p);

        }   
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    outputData("Output in Salaried order.", list, EmployeeOrdering.SALARIED);
    outputData("Output in Salaried order.", list, EmployeeOrdering.EMPLOYEE_ID);
    outputData("Output in Salaried order.", list, EmployeeOrdering.NAME);
    outputData("Output in Salaried order.", list, EmployeeOrdering.SALARY);

    for (EmployeeFX p : list) {
        System.out.println(p);
    }



}

public static void outputData(String str, ArrayList<EmployeeFX> list, Comparator<EmployeeFX> specificComparator )
{
    String headerString = "Id  FirstName  LastName  Salaried  Salary";
    System.out.println("\n" + str + "\n\n" + headerString + "\n");
    Collections.sort(list, specificComparator);
}
}

Here is my Employee class

import java.util.ArrayList;

public class EmployeeFX {

private int id;
private String firstName;
private String lastName;
private boolean salaried;
private double salary;



public EmployeeFX(int id, String firstName, String lastName,
        boolean salaried, double salary) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.salaried = salaried;
    this.salary = salary;

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public boolean isSalaried() {
    return salaried;
}

public void setSalaried(boolean salaried) {
    this.salaried = salaried;
}

public double getSalary() {
    return salary;
}

public void setSalary(double salary) {
    this.salary = salary;
}

@Override
public String toString() {
    return this.id + " " + this.firstName + " " + this.lastName + " "
            + this.salaried + " " + this.salary;
}

}

And here is the class that I'm having the most problems with, the Employee Ordering class.

import java.util.Comparator;

public class EmployeeOrdering  {


class EMPLOYEE_ID implements Comparator<EmployeeFX>
{
@Override
public int compare(EmployeeFX arg0, EmployeeFX arg1) {
    if (arg0.getId() < arg1.getId()) {
        return 1;
    } else {
        return -1;
    }
}

}

class NAME implements Comparator<EmployeeFX>
{
    @Override
    public int compare(EmployeeFX arg0, EmployeeFX arg1) {
    if (arg0.getLastName().compareTo(arg1.getLastName()) < 0) {
        return 1;
    } else {
        return -1;
    }
}

}



    class SALARIED implements Comparator<EmployeeFX>
    {

@Override
public int compare(EmployeeFX arg0, EmployeeFX arg1) {
    if(arg0.isSalaried() == arg1.isSalaried()) {
        return 1;
    } else {
        return -1;
    }
}
    }


    class SALARY implements Comparator<EmployeeFX>
    {
        @Override
public int compare(EmployeeFX arg0, EmployeeFX arg1) {
    if (arg0.getSalary() < arg0.getSalary()) {
        return 1;
    } else {
        return -1;
    }
}
{

}
    }



}

I know I' am probably using Comparators wrong, what is the correct way to write these methods so they be referenced by the Driver class and produce correct results? Where does the "Collections.sort" come into play? How am I suppose to create those Comparators? The final goal is to print the text with only the ID numbers sorted, then only the last/first name sorted, weather they are salaried or not, and then printed sorted by salary.

Thanks! Any help would be greatly appreciated!




c# - Getting Window Name in Class exception

I have a class that will handle all exceptions, it has a method that will take in as a parameter a message, the exception, the window name, and the class name.

This method will obviously always be called in the catch code block as to take the exception and insert it into the appropriate table.

For the windows, I'm using the this.name property in order to get the window name in the method call and then leaving the class name null.

For the classes, I would like to include which window the exception came from and obviously the class name for the class name parameter.

How do I dynamically retrieve the window name which caused the class exception in the class as well as the class name itself. (All from within the class)

Thank you for taking the time to read this.




What is the purpose of the "class << Class" (angle brackets) syntax?

Question:

Why would I want to add anything to a class using class << Class syntax:

class Fun
    def much_fun
        # some code here
    end
end

class << Fun # the difference is here!
    def much_more_fun
        # some code here
    end
end

instead of using the monkey patching/duck punching method:

class Fun
    def much_fun
        # some code here
    end
end

class Fun # the difference is here!
    def much_more_fun
        # some code here
    end
end


Background:

While reading Why's Poignant Guide to Ruby I came across a really weird thing (which is nothing extraordinary in terms of this book).

Why defines a class LotteryDraw:

class LotteryDraw
    # some code here
    def LotteryDraw.buy( customer, *tickets )
        # some code here as well
    end
end

and after a while Why decides to add a method to the LotteryDraw class:

class << LotteryDraw
    def play
        # some code here
    end
end

saying that:

When you see class << obj, believe in your heart, I’m adding directly to the definition of obj.

What is the purpose of this syntax? Why did Why decide to do it this way and not using the monkey patching?


Research:

These are some related questions and websites:


‡: Why is the author's nickname.




example to create full association, aggregation and composition

is possible to create without new and point how ? without new how ? without point how ? how i create association,aggregation,and compostion with this class name and nick , how i replace fuction1() and fuction2() to association , aggregation , and compostion. how to get the results ?

>class name
>public:
>{ string a;
>  fuction1();
>}
>class nick
>public:
>{ string b;
>  fuction2();
>}
>>>>name.cpp
>fuction1()
>{
>   cout<<"what u name: ";
>   cin>>a;
>}
>>>>nick.cpp
>fuction2()
>{
>   cout<<"what u nick: ";
>   cin>>b;
>}
>>>int main()
>#include <name.h>
>#include <nick.h>
>{
>cout<<"u name is: "<<a<<"u nick is: "<<b;
>}




How to add bootstrap class to Django CreateView form fields in the template?

I am using Django CreateView and in the template I can individually set the label and fields. However, I cannot add the bootstrap classes that I need. Currently, I have the following form.

<form action="" method="post" class="form-horizontal">{% csrf_token %}
    <div class="form-group">
        <label class="control-label col-xs-1" for="name">{{ form.name.label }}:</label>
        <div class="col-xs-9">
            {{ form.name }}
        </div>

    </div>
    <div class="form-group">
        <label class="control-label col-xs-1" for="name">{{ form.code.label }}:</label>
        <div class="col-xs-9">
            {{ form.code }}
        </div>

    </div>
    <div class="form-group">
        <label class="control-label col-xs-1" for="name">{{ form.phone.label }}:</label>
        <div class="col-xs-9">
            {{ form.phone }}
        </div>

    </div>
    <input class="btn btn-primary col-xs-offset-1 col-xs-9" type="submit" value="Create" />
</form>

How can I add classes to the template variables name, code and phone?




swift 2.0 prepareForSegue not wokring

I'm trying to use prepareForSegue in an app I am making. prepare forSegue has to pass a class to a separate view controller. Here is the code in prepareForSegue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "createPieceSegue" {
        var svc = segue.destinationViewController as DestinationViewController!

        svc.pieceBaseClass = myClass
    }
}

These are the superclasses that the first view controller inherits from:

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITableViewDataSource, UITableViewDelegate, UINavigationBarDelegate

And the destination view controller is inheriting from UIViewController only. The error I keep getting is: UIViewController is not convertible to'DestinationViewController' Thus I can't pass data between the two. What does this error mean and how can I fix it?




Class with spars vectors Python

I have to implement a class which objects are sparse vectors using Python without spicy. How do I do that? I am new to Python.




Is name of a class an expression?

Just out of curiosity, Is name of a class considered as an expression?

Assume I have something like

public class Hello{}

I know Hello.class will return an object of type Class. So that is an expression. But, can we say Hello by itself is an expression? Is it considered as a single value?




Ruby: How should I access instance variables inside a class?

In ruby you can internally access variables directly via @var_name or via private getters attr_reader :var_name.

Which solution is more (semantically?) correct? Any advantages/disadvantages of using either solution 1 or solution 2?

Solution 1:

class Point
 def initialize(x, y)
   @x = x
   @y = y
 end

 def distance
   Math.sqrt(@x ** 2 + @y ** 2)
 end
end

Solution 2:

class Point
 def initialize(x, y)
   @x = x
   @y = y
 end

 def distance
   Math.sqrt(x ** 2 + y ** 2)
 end
 private attr_reader :x, :y
end




New key word in abstract class declaration C# [duplicate]

This question already has an answer here:

Does anybody know what is "new" keyword mean in this code?

 public abstract class RepositoryBaseSingle<T,D> where T :class where D : DataContext, new()
    {

    }




C++ std::sort() - Unable to sort a vector of a class type that access member variables

    //Entry.h
    float sumOfNonMegaEntryPct(vector<Number>& arg1_Numbers); //returns the sum of all non mega entry percentages

    //Entry.cpp
    //returns the sum of all mega entry percentages
    float Entry::sumOfMegaEntryPct(vector<MegaNumber>& arg1_MegaNumbers)
    {
        float sumPct = 0.00f;
        for (MegaNumber c : megaEntry)
        {
            sumPct = sumPct + arg1_MegaNumbers[c.getID()].getOccurencePct();
        }

        return sumPct;
    }



    //Lotto.h
    public:
    bool compareEntry_sumPct_nonMega(Entry arg1, Entry arg2); //compares two entries, used for sorting algorithm, sorts by nonmega number

    protected:
    vector<Numbers> numbers;
    vector<MegaNumbers> megaNumbers;

    //Lotto.cpp
    #include "lotto.h"
    //sorts nonmega numbers by sum of their pct, used for sort algorithm
    bool Lotto::compareEntry_sumPct_nonMega(Entry arg1, Entry arg2)
    {
        bool b = arg1.sumOfNonMegaEntryPct(numbers) < arg2.sumOfNonMegaEntryPct(numbers);
        return b;
    }

    //Source.cpp
    vector<Entry> copyGameEntry = game.getPlayEntry();
    sort(copyGameEntry.begin(), copyGameEntry.end(), bind(&Lotto::compareEntry_sumPct_nonMega, game));

This is just a part of the code, but I think it's enough to make sense. When compiling, I get the error(s):

Severity Code Description Project File Line Error C2451 conditional expression of type 'std::_Unforced' is illegal Lottery Sort e:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm 3133

Severity Code Description Project File Line Error C2675 unary '!': 'std::_Unforced' does not define this operator or a conversion to a type acceptable to the predefined operator Lottery Sort e:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm 3118




vendredi 30 octobre 2015

how to write an entire list to a data structure in python

So the problem I am facing is that I want to create a datastructure which have like 46 items from my pandas dataframe. So I have the entire list of column name and have pandas dataframe in place.

So is there anyway that we can transform each row of pandas into an object of my datastructure.

So say:

I have an excel where

Col X Y
A 1 2
B 3 4
C 5 6

So i want to transform each row into an object

Is there some good method to do so considering I have 46 columns and like 100,000 of rows.




Calling classes and methods within the main class in Java

I'm a Java newbie and I was told to create a program with a menu showing 2 options. First one should ask user for two numbers then it returns each number multiplied by 5. Second option should ask user for a number and then return same quantity of elements from the Fibonacci sequence.

I already manage to code all the requirements by creating a switch structure for the menu and solving each case within the structure, however my instructor is telling me that I need to create a separate class for each case and then the switch menu will just call the right class depending on the selection

How can I rearrange my code to work with classes and method from within the switch menu? Any suggestion is welcomed, thank you in advance!

Here is my code:

import javax.swing.JOptionPane;

public class Classes {

public static void main(String[] args) {

    String opciones = JOptionPane.showInputDialog(null, "Elija una operación\n\n1. Números quintuplicados\n2. Serie Fibonacci\n ");
    if (opciones == null) {
        System.exit(0);
    }
    int opcionElegida = Integer.parseInt(opciones);

    // 
    switch (opcionElegida) {
        case 1: {

            String respuestaUsuario, respuestaUsuario2;
            int x1, x2, resultado, resultado2;

            respuestaUsuario = JOptionPane.showInputDialog(null, "Introduce el primer número: \n");
            x1 = Integer.parseInt(respuestaUsuario);

            respuestaUsuario2 = JOptionPane.showInputDialog(null, "Introduce el primer número: \n");
            x2 = Integer.parseInt(respuestaUsuario2);

            resultado = x1 * 5; // paso de parametros
            resultado2 = x2 * 5; // paso de parametrosm

            JOptionPane.showMessageDialog(null, "Cada número multiplicado por 5 es\n" + resultado + " y " + resultado2);
            break;
        }

        case 2: {
            String respuestaUsuario; // Variable para ser usada con JOPtionPane
            int numero; // Variable que recibira el valor convertido de respuestaUsuario
            String resultado = "";
            int a = 0, b = 1, fibonacci, i;

            do {
                respuestaUsuario = JOptionPane.showInputDialog("                    *** Suceción Fibonacci ***\n¿Cuántos números de la serie desea conocer?", "Escribe un número");
                numero = Integer.parseInt(respuestaUsuario);
            } while (numero <= 1);

            for (i = 2; i <= numero; i++) {
                fibonacci = a + b;
                a = b;
                b = fibonacci;
                resultado = resultado + " " + fibonacci;
            }

            JOptionPane.showMessageDialog(null, " Los números de la serie son:\n" + resultado);
            break;

        }
        default:
            JOptionPane.showMessageDialog(null, "Opción no valida");
            break;
    }
}

}




C++ Friend Functions in separate header and .cpp files

//A.h
friend bool compareEntry_sumPct_nonMega(Entry arg1, Entry arg2);

//A.cpp
bool A::compareEntry_sumPct_nonMega(Entry arg1, Entry arg2)
{
    bool b = arg1.sumOfNonMegaEntryPct(numbers) < arg2.sumOfNonMegaEntryPct(numbers);
    return b;
}

I get the error compareEntry_sum_Pct_nonMega is not a member of A.




Setting a Panel's background color from a class, Windows Forms - C#

I have relating to setting the panels background color from a class.

The class is not within the form of the panel, but as a side class.

The panel on the main form is called pnlCanvas.

I don't know what I am missing. If I have values or methods in the main form, then I can access those values from the class. But, the panel seems it acts different.


public Form1()
{
    InitializeComponent();
    ChangeColor changeColor = new ChangeColor(this);

    changeColor.RedPanel();
}


class ChangeColor 
{
    public Form1 form1 { get; set; }
    public ChangeColor(Form1 form1)
    {
        this.form1 = form1;
    }
    Public void RedPanel()
    {
        form1.pnlCanvas.BackColor = Color.Red;
    }
}




c++ How do I get variables from a class and put it into another class, and put it into a constructor?

I have 2 h and cpp files. I wanna know how to call variables from the Abe.h file or the Abe class to the Bob.h or the Bob class. Please help.

Abe.h

#include <iostream>
using namespace std;
#ifndef ABE
#define ABE

class Abe
{
    private:
    int num;

    public:
        Abe();
        Abe(int);
        void showNumber();

};
#endif // ABE

Abe.cpp

#include "Abe.h"
#include <iostream>

using namespace std;

Abe::Abe()
{
    num=45;
}

Abe::Abe(int n)
{
    num=n;
}

void Abe::showNumber()
{
    cout<<num;
}

BOB.h

#include "Abe.h"
#include <iostream>

using namespace std;
#ifndef BOB
#define BOB

class Bob
{
private:
    Abe a;

public:
    Bob(Abe);
};

#endif // BOB

BOB.cpp

#include "Abe.h"
#include "Bob.h"
#include <iostream>

using namespace std;

Bob::Bob(Abe a1)
{
    a=a1;
  //^not sure what a=a1 is doing but if you could explain in simple terms or in deatil that would help.
}

so how do I get "num" from abe and use it in the Bob class? please help. Thank You!




How to access a instanciated class from another function?

I don't even know how I could possibly call this. Lets say I'm trying to call a an instantiated class from a method other then one that instantiated this class. (Might be hard to understand)

In java I would just do this:

public class MyClass {

    ExampleClass classIwantToAccess; // This line here is the important part.

    public MyClass()
    {
        classIwantToAccess = new ExampleClass();
    }

    public ExampleClass getWanted()
    {
        return classIwantToAccess;
    }
}

So I tried that in c++, But it doesn't work like I expected...

#include "Test.h"

Test test;

void gen()
{
    test = Test::Test("hello");
}

int main()
{
    // How can I access my class from here?
    return 0;
}




c++ How do I get variables from a class and put it into another class, and put it into a constructor?

I'm having a bit of a problem here. Well I have an assignment in my class where we made 3 header files(.h files) and 3 .cpp files. The assignments were Person Date and Time.

I will display them for you to see.

person.h

#include <iostream>
using  namespace std;
#ifndef PERSON
#define PERSON

class Person
{
private:
    string firstName;
    string lastName;
public:
    Person();
    Person(string,string);
    void displayPerson();
};
#endif

person.cpp

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

Person::Person()
{
firstName=" ";
lastName=" ";
}
Person::Person(string fn, string ln)
{
firstName=fn;
lastName=ln;
}
void Person::displayPerson()
{
cout<<firstName<<", "<<lastName;
}

Date.h

#include <iostream>
using namespace std;

#ifndef DATE
#define DATE
class Date
{
private:
    string month;
    string day;
    string year;
public:
    Date();
    Date(string,string,string);
    void displayDate();
};
#endif // DATE

Date.cpp

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

Date::Date()
{
    month="01";
    day="01";
    year="2013";
}
Date::Date(string m,string d, string y)
{
    month=m;
    day=d;
    year=y;
}
void Date::displayDate()
{
    cout<<month<<"/"<<day<<"/"<<year;
}

Time.h

#include <iostream>
using namespace std;

#ifndef TIME
#define TIME
class Time
{
private:
    static const int MAXMIN=59;
    static const int MINMIN=0;
    static const int MAXHOUR=24;
    static const int MINHOUR=0;
    int militaryHours;
    int militaryMinutes;
    int standardHours;
    int standardMinutes;
    string AMPM;
public:
    Time(int);
    Time(int,int);
    void displayTime();
    void displayTime1();
};
#endif // TIME

Time.cpp

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

Time::Time(int mh)
{
    string zero="0";
    militaryHours=mh;

if (militaryHours>MAXHOUR || militaryHours<MINHOUR)
{
    militaryHours=MAXHOUR;
    standardHours=12;
}
else if(militaryHours>12 && militaryHours<MAXHOUR)
{
    standardHours=militaryHours-12;
    AMPM="P.M.";
}
else if(militaryHours<12 && militaryHours>=MINHOUR)
{
    standardHours=militaryHours;
    AMPM="A.M.";
}

cout<<"MILITARY TIME: "<<militaryHours<<":"<<zero<<zero<<" "<<AMPM;
cout<<"\nSTANDARD TIME: "<<standardHours<<":"<<zero<<zero<<" "<<AMPM;
}

Time::Time(int mh,int mm)
{
     string zero="0";
     militaryHours=mh;
     militaryMinutes=mm;

if (militaryHours>MAXHOUR || militaryHours<MINHOUR)
{
    militaryHours=MAXHOUR;
    standardHours=12;
}
else if(militaryHours>12 && militaryHours<=MAXHOUR)
{
    standardHours=militaryHours-12;
    AMPM="P.M.";
}
else if(militaryHours<12 && militaryHours>=MINHOUR)
{
    standardHours=militaryHours;
    AMPM="A.M.";
}
if(militaryMinutes>MAXMIN && militaryMinutes<MINMIN)
{
    militaryMinutes=MAXMIN;
}
else if(militaryMinutes<MAXMIN && militaryMinutes>MINMIN)
{
    standardMinutes=0;
    standardMinutes=militaryMinutes;
}
if(militaryMinutes<10 && militaryMinutes>=MINMIN)
{
    standardMinutes=0;
    standardMinutes=militaryMinutes;
    cout<<"MILITARY TIME: "<< militaryHours<<":"<<zero<<standardMinutes<<" "     <<AMPM;
    cout<<"\nSTANDARD TIME: "<<standardHours<<":"<<zero<<standardMinutes<<"     "<<AMPM;
}
else
{
    cout<<"MILITARY TIME: "<< militaryHours<<":"<<standardMinutes<<" "<<AMPM;
    cout<<"\nSTANDARD TIME: "<<standardHours<<":"<<standardMinutes<<" "<<AMPM;
}
}

ok so person was to get the first name and last name of a person Date was to get a date...month day year Time was to ask a user for a time and to output military and standard time.

Now our teacher wants us to make a fourth class... named DentalAppointment.

This is what the assignment says

"Create a class named DentalAppointment. Include fields for patient data(using the existing Person class), the date(using the existing class), the time(using the existing Time class), and the duration of the appointment in minutes. Also, include a field that contains the ending time for the appointment - this field will be calculated based on the start time and the duration using the Time class function that adds minutes to the time object. The DentalAppointment constructor requires a first and last name, a month,day, and year, and an hour and minute for the appointment. Allow a DentalApppointment to be constructed with or without and additional argument for duration and force the duration to 30 minutes when no argument is supplied. The constructor should not allow any appointment over 240 minutes. The constructor will calculate the appointment ending time base on the start time and duration. Create a display function for the DentalAppointment class. Write a main() function that loops at least three times prompting the user for DentalAppointment data and displaying the information. Use an initialization list for the constructor."

Ok here is where I am confused.

so basically I have to pass the values from Person,Date, Time to DentalAppointment.

so first I made a DentalAppointment class.

DentalAppointment.h

#include <iostream>
#include "person.h"
#include "Date.h"
#include "Time.h"
using  namespace std;

class DentalAppointment
{
private:

public:

};

I dont know what to put in the private and public parts. Do I do?

#include <iostream>
#include "person.h"
#include "Date.h"
#include "Time.h"
using  namespace std;

class DentalAppointment
{
private:
    Person pFirstName;
    Person pLastName;
    Date appointmentMonth;
    Date appointmentDay;
    Date appointmentYear;
    Time appointmentHour;
    Time appointmentMinutes;
    int duration;
public:
    DentalAppointment();
    DentalAppointment(Person,Person,Date,Date,Date,Time,Time);
    DentalAppointment(Person,Person,Date,Date,Date,Time,Time,int);
    void showDentalAppointment();
};

if so then what do I put in for my cpp file? should it be like this???

#include <iostream>
#include "person.h"
#include "Time.h"
#include "Date.h"
#include "DentalAppointment.h"
using namespace std;

DentalAppointment::DentalAppointment()
{
    pFirstName=Person.firstName;
    pLastName=Person.lastName;
    appointmentMonth=Date.month;
    appointmentDay=Date.day;
    appointmentYear=Date.year;
    appointmentHour=Time.standardHours;
    appointmentMinutes=Time.standardMinutes;
}
DentalAppointment::DentalAppointment(Person fn,Person ln ,Date month,Date day,Date year,Time h,Time m)
{
    pFirstName=fn;
    pLastName=ln;
    appointmentMonth=month;
    appointmentDay=day;
    appointmentYear=y;
    appointmentHour=h;
    appointmentMinutes=m;
}

DentalAppointment::DentalAppointment(Person fn,Person ln ,Date month,Date      day,Date year,Time hours,Time minutes,int d)
 {
    pFirstName=fn;
    pLastName=ln;
    appointmentMonth=month;
    appointmentDay=day;
    appointmentYear=year;
    appointmentHour=hours;
    appointmentMinutes=minutes;
    duration=d;
}

please tell me if I am way off, or if im close. because calling private and public variables from different classes and putting them into different classes is confusing me. and putting them in constructors is killen me.... please help me!!! Thank You!!!




way to include files central for classes in PHP

my class user tries to access the $db object.

The problem is that the class user can't find the $db object after including it in my central file loader.inc.php. If I include the connect.php in every function/method, it works, but I want a central way to include all my classes and files.

user.class.php

class user {

        public function login($username, $password) {
            $username = $db->real_escape_string($username);
            $password = hash('sha256', $password);
            $stmt = "SELECT username, activation FROM users WHERE username='$username' AND password='$password';";
            $result = $db->query($stmt);
            $count_row = $result->num_rows;
            if ($count_row ==  1) {
                    $userdata = $result->fetch_array(MYSQLI_ASSOC);
                    if ($userdata['activation'] == 0) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    return false;
                }
        }
}  

connect.php

require_once 'config.php';
require_once 'loader.inc.php';

$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno()) {
    print mysqli_connect_errno();
} else {
    $db->query("SET NAMES utf8");
}  

loader.inc.php

require_once 'connect.php';
require_once 'user.class.php'; 

I know that the include function like it's shown here isn't secure, but I use this script only for testing purposes.

Sincerely

Johannes




CSS Mobile Navigation Changes for Portrait and Landscape

I have a series of pages on my site that contain ".iframe1". The .iframe1 needs to be viewable in both portrait and landscape modes on mobile phones, but I needed to tweak 2 things to make it function properly.

1.) Landscape Mode: Block "#main-header" from appearing altogether.

2.) Portrait Mode: Pad the top of my content area. (#main-header covers the top of my content while in portrait.)

I have completed #1, but can't seem to figure out how to achieve #2. I have combined them into one task because I feel that there is a chance they'll conflict if written separately.

Both of the following entries acheive #1 but not #2:

@media only screen and ( min-width: 480px ) and ( max-width: 768px ) {
#main-header {
display: none !important;
}
.iframe1 {
padding-top: 30px !important;
}
}


@media only screen and (orientation:landscape) and (max-width: 768px) {
#main-header {
display: none !important;
}
.iframe1 {
padding-top: 30px !important;
}
}

Anyone have ideas about how I can get #2 to work?

Thanks in advance,

KV




Differences between class method and object method

In C#, why when we can define a class method and access to a method by class name directly, we should/some people define an object instead and then create an instance of that object?

Class1:

class Class1
{
    public static int PrintX(int x)
    {
        return x;
    }
    private int y;
    public int PrintY(int z)
    {
        return this.y = z;
    }
}

Main Method:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Class1.PrintX(9));

        Class1 newClass = new Class1();
        Console.WriteLine(newClass.PrintY(9));
    }
}

Both ways print out 9. Why should I use an object method and then create an instance of it?!




Hangman Game using Methods, no arrays

I am working on a hangman project and the code has to have all the following methods that i have implemented. We technically have not used/ learned arrays in class so is it possible to complete this without using arrays and just strictly use methods?

import java.util.ArrayList;
public class Hangman {
    private String secretWord;
    private String playedLetters;
    private int failedAttempts;
    private final int MAX_ATTEMPTS = 5; 



    //hangman constructor 
    public Hangman(String word){
        secretWord = word.toLowerCase();
        playedLetters = " ";
        failedAttempts = 0; 
    }


    //method playLetter
    /**
     * Method   playLetter: receives a  char and checks if  it exists in the    secretWord and  not in  the already played  letters 
    (playedLetters). If it  is  a   new letter  appearing   in  secretWord, it  is  concatenated to playedLetters.  If  not,    the 
    method increments   the failedAttempts propety  in  1.  The method  does    nothing if  failedAttempts is   already 
    MAX_ATTEMPTS or if  the letter  has been    played  before  (is in  playedLetters).
     * @param letter
     */
    public void  playLetter(char letter){

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

            if(secretWord.contains(letter)){
                letter = letter.concat(playedLetters);
            }
    }


    //method matchWord
    /**Method   matchWord:  in  case    the parameter   word is equal   to  the property    secretWord, concatenate word to 
    playedLetters and   return  true.   If  not,    increment   failedAttempts and  return  false.
     */
    public boolean matchWord(String word){

        if(word == secretWord){
            word = word.concat(playedLetters); 
            return true;
        }
        else{
            failedAttempts ++;
            return false;
        }


    }


    //method getWordStatus
    /**Method   getWordStatus:  returns a   representation  of  the word    that    has underscore (_)  for each    letter  that    has not 
    been    guess   and the corresponding   letter  if  it  exist   in  the playedLetters.
     */
    public String getWordStatus(String secretWord, StringBuffer dashes, char letter){
        for (int i = 0; i < secretWord.length(); i++){
            if(secretWord.charAt(i) == letter){
                dashes.setCharAt(i, letter);
            }
        }
        return underscore;

    }

    //method finished
    public boolean finished(){
        if(failedAttempts >= MAX_ATTEMPTS){
            return true;
        }
        else{
            return false; 
        }
    }

    //method completed
    public boolean completed(){
        if ( playedLetters == secretWord){
            return true;
        }
        else{
            return false;
        }
    }


    //getters
    public String getSecretWord() {
        return secretWord;
    }

    public String getPlayedLetters() {
        return playedLetters;
    }

    public int getFailedAttempts() {
        return failedAttempts;
    }

}


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

import javax.swing.JOptionPane;
public class GameManager {
    private static final int Character = 0;
    private Player player;
    private Hangman hangman;
    private String words;
    private String currentWord;


    //game manager
    public GameManager(String words){
        this.words = words.toUpperCase();
        createPlayer();
    }

    //create player method
    public void createPlayer(){
        String playerName = JOptionPane.showInputDialog("What is your name?"); 
        Player P1 = new Player(playerName); 
    }



    /**
     * Method   setupANewGame:  pick the next   word    from    the property    words (first    time    it  has to pick the first   word)   and 
    initializes the hangman property    with    the selected    word    (see    Hangman constructor). Picking   the next    word    form    the 
    words   property    needs   to  locate  the currentWord in  it  and takes the   next    word    locating    spaces. Consider    that    last    
    word has    no space    at  the end,    and if  the currentWord is  the last    word,   then    picking the next    word    means   going   back    
    to  the beginning   and picking the first   word.
     */
    public void setupANewGame(){
        // complete this. At the end it has to initialize the currentWord and the hangman:

        for(int i =0; i < currentWord.size(); i++){
            currentWord.get(i).setEnabled(true);
        }


        hangman = new Hangman(currentWord);
    }



    /**
     * Method   playTurn:   it  asks    the user    to  input   the next    letter  to  try,    and at  the same    time    it  shows   the status  of  the 
    hangman     Along   with    asking  for the letter  to  play,   it  should  give    the user    the option  to  quit    by  inputting   "quit". In  this    
    case,   the method  will    return  false.  The letter  input   by  the user    is  used    to  call the    method  playLetter of   the 
    hangman.    Finally,    playTurn return true when   the user    can keep    playing and false otherwise.    In  other   words,  it  
    returns false when  the hangman is  finished (the   user    won or  lose),  or  if  the user enters "quit". 
     * @return
     * use play letter part of the class
     */
    public boolean playTurn(){
        //complete this
        String letter = JOptionPane.showInputDialog("Enter the next letter or enter quit to quit");
        if(letter == "quit"){
            return false;
        }
        if(letter == )
        return true;
    }

    //play game method
    public boolean playGame(){
        // This method is completed!!!
        boolean stillPlaying = true;
        while(!hangman.finished() && stillPlaying){
            stillPlaying = playTurn();
        }
        player.incrementGames(hangman.completed());
        String message = "Game ended";
        if(hangman.finished()) message += ".";
        else message += " incompleted!";
        if(hangman.completed()){
            message += "\nYou won!!!";
        }
        else{
            message += " \nYou lose :(";
        }
        message += "\n"+hangman.getWordStatus()+"\nPlay again? (y/n)";
        String input = JOptionPane.showInputDialog(message);
        if(input == null || input.length() == 0){
            return false;
        }
        else if(input.toLowerCase().charAt(0) == 'y'){
            return true;
        }else{
            return false;
        }
    }

    //show summary method 
    public void showSummary(){
        //complete this
    }
}

public class HangmanGameTest {
    public static void main(String[] args){
        GameManager game = new GameManager("hello wednesday festival electronics");
        boolean playing = false;
        do{
            game.setupANewGame();
            playing = game.playGame();
        }while(playing);
    }
}


public class Player {
    private String name;
    private int gamesCount;
    private int gamesWon;

    //player constructor
    public Player (String name){
        this.name = name;
        gamesCount = 0;
        gamesWon = 0;
    }

    //games method

    public void incrementGames(boolean won){
        gamesCount++;
        if(won == true){
            gamesWon++;
        }
    }

    //getter
    public String getName() {
        return name;
    }

    public int getGamesCount() {
        return gamesCount;
    }

    public int getGamesWon() {
        return gamesWon;
    }

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

}




Instance abstract class that is implemented elsewhere?

I'm making a plugin DLL for 3dsmax. The SDK includes one particular class full of pure virtual functions that the documentation says are implemented by max itself. I know these functions are implemented, because class instances are sometimes passed to my plugin through functions in my plugin that max calls from its core api.

However, if I try to instance that class within my code, I cannot since all of its functions are pure virtual in the 3dsmax SDK.

Is there any way to tell the c++ compiler that even though the functions it sees are pure virtual, they are implemented somewhere else (in another .dll visible to the program)? The declarations of the functions in question are not in any of the 3dsmax .libs or includes...so it's 100% certain that they're outside the scope of my code....but they are out there.

I'm new to c++ so I apologize if this is a dumb question.




WebApi Newtonsoft.Json.JsonConvert.DeserializeObject

I am doing a WebApi Method in Visual Studio 2013 and I want to Deserialize a Class Type. My Class is like this

[JsonObject]
    class JOTA
    {
        [JsonProperty("ProductId")]
        public int ProductId { get; set; }
        [JsonProperty("Name")]
        public string Name { get; set; }
    }

My call is like this.

 public void ReturnListProd(JOTA PP)
 {
 JOTA product = Newtonsoft.Json.JsonConvert.DeserializeObject<JOTA>(PP);
 }

I have a compile error

'Network.Json.Json.Converter[] has some invalid argument'

But, if a define an ArrayList

public void ReturnListProd(ArrayList PP)
{
JOTA product = Newtonsoft.Json.JsonConvert.DeserializeObject<JOTA>(PP[0].ToString());
}

I have no error. But in this case, it does not help on what I need.

What I am missing? Thanks




Merge two LinkedList without creating a new LinkedList

I am trying to take the two linkedlist that I have in my executable file and merge them into each other in alternating positions. Ex. ListOne 1,2,3 and ListTwo 4,5 the new ListOne should be 1,4,2,5,3.

LinkedList .h file:

class LinkedList
{
private:
struct ListNode
{
    string firstName;
    string lastName;
    long int phoneNumber;
    struct ListNode *next;
};
ListNode *head;

public:
LinkedList()
{
    head = nullptr;
}
~LinkedList();
void appendNode(string f, string l, long int p);
void displayList();
};

LinkedList .cpp file:

LinkedList::~LinkedList()
{
cout << "LinkList destructor" << endl;
}

void LinkedList::appendNode(string f, string l, long int p)
{
    ListNode *newNode;
    ListNode *nodePtr;
    newNode = new ListNode;

    newNode -> firstName = f;
    newNode -> lastName = l;
    newNode -> phoneNumber = p;
    newNode -> next = nullptr;

    if (!head)
        head = newNode;

    else
    {
        nodePtr = head;

        while (nodePtr -> next)
            //while nodePtr is pointing to another node
            nodePtr = nodePtr -> next;
            //move to that node

        nodePtr -> next = newNode;
        //inset the newNode at the end of the linked list
    }
 }

 void LinkedList::displayList()
{
    ListNode *nodePtr;
    nodePtr = head;

    while(nodePtr)
    //while nodePtr is true, meaning there is a node in the list
    {
        cout << nodePtr -> firstName << endl;
        cout << nodePtr -> lastName << endl;
        cout << nodePtr -> phoneNumber << endl;
        nodePtr = nodePtr -> next;
     }
}

Executable file:

LinkedList ListOne;
LinkedList ListTwo;

ListOne.appendNode("Cate", "Beckem", 7704563454);
ListOne.appendNode("Cabe","Tomas", 7703451523);

ListTwo.appendNode("Mary", "Smith", 4043456543);
ListTwo.appendNode("Mark", "Carter", 4045433454);

My programs runs perfectly including the displayList function. I am just very confused how to go about making a merge function.




How to call function in another class

how to call to a function in another class. I can't explain, but i hope you will understand my problem.

Notice: Undefined variable: db in class general.

http://ift.tt/1PUri6u




Undefined reference to object pointer in c++ [duplicate]

I created two classes, one inherit from the other. The parent class has a matrix of pointers to the parent class objects but I'm getting this error and I don't know why:

undefined reference to `parent::parent_matrix'

Here is my code:

#include <iostream>
#include <string>

using namespace std;

class parent{
    private:
        string str;
    public:
        static parent *parent_matrix[8][8];
        void set_str(string str){
            this->str = str;
        }
        string get_str(){
            return str;
        }
        parent();
        ~parent();
};

class child:public parent{
    public:
        child();
        ~child();
};

parent::parent(){
    //parent constructor
}

parent::~parent(){
    //parent destructor;
}

child::child(){
    //child constructor
}

child::~child(){
    //child destructor
}

int main(){
    string str;
    child obj1, obj2;
    cin >> str;
    obj1.parent_matrix[0][0] = &obj2;
    obj1.parent_matrix[0][0]->set_str(str);
    cout << obj1.parent_matrix[0][0]->get_str();
}

Can anyone help me with this?
Thank you in advance.




Call to undefined method mysqli::fetch_assoc()

im trying to make a simple mysqli class for my self, but there is a error, that i cant resolve. Call to undefined method mysqli::fetch_assoc() on line 20.

public function __construct() {
    $this->db = new mysqli('localhost','username','password','web');
    if (mysqli_connect_error()) {
        die('Connect Error (' . mysqli_connect_errno() . ') '
                . mysqli_connect_error());
    }
}

public function query($query) {
    $result = $this->db->query($query);
    return $result;
}

public function fetch($query) {
    if (!empty($query)) {
        while ($row = $this->db->fetch_assoc()) {  *//there are line 20*
            $data[] = $row;
        }
        return $data;
    } else {
        return false;
    }
}




Java: Why can't I use the print() or println() method in java.io.PrintStream as it is after importing the class?

Apologies for this silly question, but while I was learning java classes, I tried the following

javap -c java.lang.System | grep -i out
  public static final java.io.PrintStream out;

javap java.io.PrintStream | grep print
public void print(boolean);
public void print(char);
public void print(int);
public void print(long);
public void print(float);
public void print(double);
public void print(char[]);
public void print(java.lang.String);
public void print(java.lang.Object);
public void println();
public void println(boolean);
public void println(char);
public void println(int);
public void println(long);
public void println(float);
public void println(double);
public void println(char[]);
public void println(java.lang.String);
public void println(java.lang.Object);
public java.io.PrintStream printf(java.lang.String, java.lang.Object...);
public java.io.PrintStream printf(java.util.Locale, java.lang.String, java.lang.Object...);

And I tried to see if I can import java.io.PrintStream and use print() or println() as it is, instead of System.out.println().

import java.io.PrintStream;
println('a');

And it came out with a compile error saying

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method print(char) is undefined for the type array at array.main(array.java:16)

Why can't I use println() as it is after importing java.io.Printstream ?




how to access all object have same type/class in one project in C++?

I want to call all object exist in a project. how can i do that?

Class1 Abc;
Class1 Xyz;
Class1 asd[100];
for each (Class1 k in ???)
{
    k.dosomething();
}




jeudi 29 octobre 2015

Java: Collections.sort resulting in error - no suitable method found [duplicate]

This question already has an answer here:

I am trying to implement the interface of Comparable for class Bank Account, I overrided the compareTo method for Bank account but when trying to using Collections.sort I am getting the error:

BankAccountTester.java:40: error: no suitable method found for sort(ArrayList<BankAccount>)
  Collections.sort(list);

Why is this happening?

My code is below for bank account and tester:

    /**
  A class to test the BankAccount class.
*/
import java.util.ArrayList; 
import java.util.Collections;

public class BankAccountTester
{

   public static void main(String[] args)
   {

      BankAccount bank1 = new BankAccount(30); 

      BankAccount bank2 = new BankAccount(15); 

      BankAccount bank3 = new BankAccount(10);  
      BankAccount bank4 = new BankAccount(5);
      BankAccount bank5 = new BankAccount(20);


      // Put the rectangles into a list 


      ArrayList<BankAccount> list = new ArrayList<BankAccount>(); 


      list.add(bank1); 

      list.add(bank2); 

      list.add(bank3); 
      list.add(bank4);
      list.add(bank5);



      // Call the library sort method 

      Collections.sort(list);  



      // Print out the sorted list 

      for (int i = 0; i < list.size(); i++) 
      {

         BankAccount b = list.get(i); 

         System.out.println(b.getBalance()); 
      }

  }
}

And bank account class:

 /**
       A bank account has a balance that can be changed by 
       deposits and withdrawals.
    */
    public class BankAccount implements Comparable<BankAccount>
    {  
        private double balance;
       /**
          Constructs a bank account with a zero balance.
       */
       public BankAccount()
       {   
        // this.balance = 0;
         this(0);

       }

       /**
          Constructs a bank account with a given balance.
          @param initialBalance the initial balance
       */
       public BankAccount(double balance)
       {   
          this.balance = balance;
       }

       /**
          Deposits money into the bank account.
          @param amount to deposit
       */
       public void deposit(double amount)
       {  
          balance = balance + amount;

       }

       /**
          Withdraws money from the bank account.
          @param amount  to withdraw
       */
       public void withdraw(double amount)
       {   
          balance = balance - amount;

       }

       /**
          Gets the current balance of the bank account.
          @return the current balance
       */
       public double getBalance()
       {   
          return balance;
       }

       public int compareTo(BankAccount otherObject) {
          BankAccount other = (BankAccount) otherObject;

          if (this.balance < other.balance) { return -1; }

          if(this.balance > other.balance) { return 1; }

          return 0;
       }

    }




Why is the dynamically allocated array attribute of my class template only able to store one item?

I am trying to expand the functionality of a class template I created. Previously it allowed you to use key-value pairs of any type but only if you knew the size of the arrays at compile time. It looked like this:

template <typename K, typename V, int N>
class KVList {
    size_t arraySize;
    size_t numberOfElements;
    K keys[N];
    V values[N];
public:
    KVList() : arraySize(N), numberOfElements(0) { }
    // More member functions
}

I wanted to be able to use this for a dynamic number of elements decided at run-time, so I changed the code to this:

template <typename K, typename V>
class KVList {
    size_t arraySize;
    size_t numberOfElements;
    K* keys;
    V* values;
public:
    KVList(size_t size) : numberOfElements(0) {
        arraySize = size;
        keys = new K[size];
        values = new V[size];
    }
    ~KVList() {
        delete[] keys;
        keys = nullptr;
        delete[] values;
        values = nullptr;
    }
    // More member functions
}

The new constructor has one parameter which is the size that will be used for the KVList. It still starts the numberOfElements at 0 because both of these uses would start the KVList empty, but it does set arraySize to the value of the size parameter. Then it dynamically allocated memory for the arrays of keys and values. An added destructor deallocates the memory for these arrays and then sets them to nullptr.

This compiles and runs, but it only stores the first key and first value I try to add to it. There is a member function in both that adds a key-value pair to the arrays. I tested this with the Visual Studio 2015 debugger and noticed it storing the first key-value pair fine, and then it attempts to store the next key-value pair in the next index, but the data goes no where. And the debugger only shows one slot in each array. When I attempt to cout the data I thought I stored at that second index, I get a very small number (float data type was trying to be stored), not the data I was trying to store.

I understand it might be worth using the vectors to accomplish this. However, this is an expansion on an assignment I completed in my C++ class in school and my goal with doing this was to try to get it done, and understand what might cause issues doing it this way, since this is the obvious way to me with the knowledge I have so far.

EDIT: Code used to add a key-value pair:

// Adds a new element to the list if room exists and returns a reference to the current object, does nothing if no room exists
KVList& add(const K& key, const V& value) {
    if (numberOfElements < arraySize) {
        keys[numberOfElements] = key;
        values[numberOfElements] = value;
        numberOfElements++;
    }

    return *this;
}




Avoid unauthorized value assignment to a python class attribute

Assume a class like this, where attribute x has to be either an integer or a float:

class foo(object):
    def __init__(self,x):
        if not isinstance(x,float) and not isinstance(x,int):
            raise TypeError('x has to be a float or integer')
        else:
            self.x = x

Assigning a non-integer and non-float to x will return an error when instantiating the class:

>>> f = foo(x = 't')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
TypeError: x has to be a float or integer

But the direct assignment of x does not return any errors:

>>> f = foo(x = 3)
>>> f.x = 't'
>>> 

How can I make python raise an error in the latter case?




Unable to figure out how to delete the entire Linked List through a function using classes only

Being a beginner for C++, I was able to get to the point of making a linkedlist using classes and not templates or vectors, and reached to a point where i can ad a node to the end, delete a node from the end (by value) and print the node. However, I now want to know how to be able to clear the complete set of nodes thereby clearing the complete linkedlist, without using any specialized functions or special headers.
I went through the following resources of reference but could not set or align my understanding with them as the following sources have done using different methods:-

Can't figure out how to clear a linked list in c++?

Linked List Delete Method (yes i tried getting ideas from java even though i dont know java but just tried too)

C programming Linked Lists delete node at position N

How would I clear a linked list? (came closest to make me understand it but some confusion)

Book: Deitel and Deitel (surprisingly near to my thought only that they have shown using templates or vectors)

Book: Primer (a little bit hard for me to understand)

Any help would be highly appreciated. Please try and forgive some of my bad habbits of programming like using namespace std and etc, etc, as my aim is to get the DeleteAll function working(clearing the complete list), look at the block of code which is commented totally in the last function of the class LinkedList. Then look at the Case 4 where i am trying to call it in the main function.this my first time with the concept of linked list, and yes it seems very intimidating.

#include <iostream>
#include <cstdlib>
#include "ctype.h"                  //for enabling the recognition of data types for different illegal user inputs for main program
using namespace std;


// Node class
class Node
{
    int data;
    Node* next;


public:

    Node(){};
    void setData(int aData)
    {
        data = aData;
    }

    void setNext(Node* aNext)
    {
        next = aNext;
    }

    int Data()
    {
        return data;
    }

    Node* Next()
    {
        return next;
    }

};


// LinkedList Class

class LinkedList
{
    private:
        Node *head;

    public:
        List()
        {
            head = NULL;
        }

        // printing contents of list        
        void Print()
        {
            Node *tmp = head;

            // but if no Nodes then following
            if (tmp==NULL)
            {
                cout<<"\n \t\tcannot find any Nodes: List EMPTY\n";
                return;
            }

            //if one node is found
            else if (tmp->Next()==NULL)
            {
                cout<<tmp->Data();
                cout<<"-->";
                cout<<"NULL"<<endl;
            }

            //else more nodes then parse and print the list
            else
            {
                do
                {
                    cout<<tmp->Data();
                    cout<<"-->";
                    tmp = tmp->Next();
                }
                while(tmp!=NULL);

                cout<<"";
                cout<<"X"<<endl;
            }


        }

        //Append or add a node to the linked list
        void Append(int data)
        {
            //creates a new node;
            Node *newNode = new Node();
            newNode->setData(data);
            newNode->setNext(NULL);

            //create a temp pointer for further linking to be facilitated
            Node *tmp = head;

            //but before setting next link to point last node to new node
            //we need to check if we are at the end of the list and if not then traverse to the end of node
            if(tmp !=NULL)
            {
                while(tmp->Next() !=NULL)
                {
                    tmp = tmp->Next();
                }
            tmp->setNext(newNode);
            }

            else
            {
                head = newNode;
            }

        }

        //Delete a node from list BY VALUE
        void Delete(int data)
        {
            //again create a temp pointer.
            Node *tmp = head;


            //again if no nodes
            if (tmp==NULL)
            {
                cout<<"\n \t\tNo Nodes to delete\n";
                return;
            }

            //Last node in the list which is the same as only one node left in list then following
            else if(tmp->Next()==NULL)
            {
                delete tmp;
                head = NULL;
            }

            //again parse through the nodes again to delete the data related node.
            else
            {
                Node *prev;
                do
                {
                    if(tmp->Data()==data)
                    {
                        break;
                    }
                    else
                    {
                        prev = tmp;
                        tmp = tmp->Next();
                    }
                }
                while(tmp != NULL);

                //once the data is found and located then readjust the linkage of previous with next and 
                //delete the current node
                prev->setNext(tmp->Next());
                delete tmp;
            }
        }

//      
//      int Deleteall()
//      {
//          again create a temp pointer.
//          Node *tmp = head;
//          
//          
//          again if no nodes
//          if (tmp==NULL)
//          {
//              cout<<"\n \t\tNo Nodes to delete\n";
//              return 0;
//          }
//          
//          Last node in the list which is the same as only one node left in list then following
//          else if(tmp->Next()==NULL)
//          {
//              delete tmp;
//              head = NULL;
//          }
//          
//          again parse through the nodes again to delete the data related node.
//          else
//          {
//              Node *prev;
//              
//              while(tmp);
//              {
//              
//              once the data is found and located then readjust the linkage of previous with next and 
//              delete the current node
//              prev->setNext(tmp->Next());
//              delete tmp;
//              }
//          } return 0;
//      }   
};

//Now call through the main function

int main()
{
//New List

LinkedList list1;
int usrdata, choice;
while(choice)
{
cout<<"\n\nPlease choose an action to be performed on the LinkedList\n\ninput 1 for adding/appending a node\ninput 2 for printing the list\ninput 3 for deleting the node by value\ninput 4 to exit\n\n";
cin>>choice;
switch(choice)
{
    case 1 :
        cout<<"\nEnter your desired data for adding/appending\n";
        cin>>usrdata;
        list1.Append(usrdata);
        list1.Print();
        continue;

    case 2 :
        cout<<"\nPrinting\n";
        list1.Print();
        break;

    case 3 :
        cout<<"\nEnter your desired data for removal/deleting\n";
        cin>>usrdata;
        list1.Delete(usrdata);
        list1.Print();
        break;

    case 4 :
        cout<<"\n deleting n exiting...\n";
//      list1.Deleteall();
        list1.Print();
        goto end;

    default :
        cout<<"I think you should go home now you seem tired\n";    
}
}

end:
cout<<"\n\nThis statement was reached because either you chose to exit or entered a wrong/illegal value or operation\n\n";

system("pause");        
return 0;
}

How to get the last function (completely commented lines) DeleteAll working to clear the entire list without using any other specialized headers or special functions etc.




Add setter method to a scala class

I'm reading a book "Scala in action" to learn scala. On page 59, the author provide following code. But when I run it, it doesn't compile.

class Person(var firstName:String, var lastName:String, private var _age:Int) {
  def age = _age
  def age_ = (newAge: Int) = _age = newAge //Error
}

It reports:

<console>:3: ';' expected but '=' found. def age_ = (newAge: Int) = _age = newAge}

This book use scala 2.10. I'm using scala 2.11.

Does scala change the usage of setter method in 2.11?




Python error when implementing class

class DetailedScore(Score):
'''A subclass of Score adding level'''

    def __init__(self, points, initials, level):
        '''
        (Score, int, str, int) -> NoneType

        Create a score including number of points, initials, and level.
        '''

        super().__init__(points, initials)
        self.level = level

    def __str__(self):
        '''
        Return a string representation of DetailedScore formated:

        'The student with initials 'KTH' scored 100 points, the student is in level 10'
        '''

        score_str = super().__str__()

        return '{}, the student is in level {}'.format(score_str, self.level)

    def __repr__(self):
        '''
        Return a string representation of DetailedScore formated:

        'DetailedScore(100, 'KTH', 10)'
        '''

        return 'DetailedScore({}, {}, {})'.format(self.points, self.initials, self.level)

score5 = DetailedScore(1000, 'JQP', 100)
score6 = DetailedScore(999, 'ABC', 99)
score7 = DetailedScore(999, 'BBB', 15)
score8 = DetailedScore(1, 'KTH', 12)

I am trying to finish this class, and am not sure why I keep getting an error when trying to build.

This is the error:

Traceback (most recent call last):
  File "/Users/KoryHershock/Documents/Python/[Kory_Hershock]_final.py", line 187, in <module>
    score5 = DetailedScore(1000, 'JQP', 100)
  File "/Users/KoryHershock/Documents/Python/[Kory_Hershock]_final.py", line 162, in __init__
    super().__init__(points, initials)
TypeError: super() takes at least 1 argument (0 given)
[Finished in 0.1s with exit code 1]




Trying to generate executable .jar file

I know this has been asked before, but I can not find an answer and it is getting a bit tedious. I have tried using eclipse to export it, and also using cmd to generate it myself, but I always get an error when trying to run. "Invalid header field" or "could not find or load main class". What I am trying to do is link a Java program, and a separate file for the class. "ScreenRobotProgram.java" and "ScreenRobot.class". These are both in the package "ScreenRobot". So, how can I link these to an executable Java program? Help would be very much appreciated. Thanks.




Python .format() KeyError when using class.__dict__

Basically I have a class defined and I'm trying to display its attributes in a print statement EDIT:

class Player(object):
    """ Default Class for the player """
    def __init__(self, name):
        self.name = name
        self.class_type = '[CLASS]'
        self.level = 1
        self.health = 10
        self.maxhealth = self.level * 10
        self.attack = 0
        self.defence = 0
        self.experience = 0
        self.weapon = ''
        self.shield = ''
        self.player_y = 9
        self.player_x = 39

print('LV: {level} EXP: {exp} HP: {health}/' +
      '{maxhealth}'.format(**char))

Am I doing something wrong? I'm just trying to find a more efficient way to display attributes of a class rather than doing...

print(character.name + ': Weight: ' + character.weight + ' Age: ' +
      character.age + '...')

Any ideas?




Accessing attribute from parent class inside child class

When I access an attribute from the parent class via the child class like this all works fine:

class A():
    a=1
    b=2

class B(A):
    c=3

d=B.a+B.b+B.c
print d

But if I try to access an attribute from the parent class inside the child class like this, it doesn't work:

class A():
    a=1
    b=2

class B(A):
    c=3
    d=a+b+c
    print d

I receive the error: name 'a' is not defined

Let assume that I have many equation like d=a+b+c (but more complicated) and I can't edit them - I have to call in class B "a" as "a", not "self.a" or "something.a". But I can, before equations, do A.a=a. But it is not the smartest way to reload all variables manually. I want to bypass it using inheritance. Is it possible or i should do all manually? Or maybe it is 3th route in this code?




Python unbound method pit fall. Why new variable initialized with unbound method is not referring the target as expected

Please take a look at code, you will get whole message what I am trying to convey.

class Foo:
   def fun(self):
       pass

a = Foo.fun
print "a is Foo.fun: %s" % (a is Foo.fun)

b = a
c = Foo.fun

print "b is c", (b is c)
print "c is Foo.fun", (c is Foo.fun)

def barFun():
   pass

bar = barFun
print "bar is barFun", (bar is barFun)

OutPut:

a is Foo.fun: False
b is c False
c is Foo.fun False
bar is barFun True

Here, why the variable a is not referring Foo.fun. As I know variable assignment is like increasing reference count. i.e, new variable will start pointing the object unlike in language c. So, as we are assigning Foo.fun to var a, a and Foo.fun both should point same object in the memory. But results are unexpected. While this assignment works well with normal function.

Here is the code id's of objects are different for unbound method assignment.

class Foo:
   def fun(self):
       pass

a = Foo.fun
print "Id of a: %s. Id of Foo.fun: %s" % (id(a), id(Foo.fun))

b = a
c = Foo.fun

print "Id of b: %s. Id of c: %s" % (id(b), id(c))
print "Id of c: %s. Id of  Foo.fun: %s" % (id(c), id(Foo.fun))

def barFun():
   pass

bar = barFun
print "Id of bar: %s. Id of barFun: %s" % (id(bar), id(barFun))

OutPut:

Id of a: 10155824. Id of Foo.fun: 139916772374320
Id of b: 10155824. Id of c: 139916772374320
Id of c: 139916772374320. Id of  Foo.fun: 10156224
Id of bar: 10741352. Id of barFun: 10741352




Add class to end of div

I have a div tag labeled

<div id = "product-tabs" class="gen-tabs gen-tabs--style1"> 

I need to add accor to the end of the class section

gen-tabs gen-tabs--style1 accor

Using jQuery

$(window).load(function(){
    $(".product-2-square-furniture-leg").parent(".gen-tabs--style1").addClass(".accor");    
}) 

This will be on a specific page body is product-2-square-furniture-leg. Perhaps I have the wrong path?




Submit a contact form and write to a separate class Java

This is my first time to post so i will say i am learning java and struggling i have to create a program that ask for three pieces of information and writes it to a class. Every example i have referenced to try to get it to work has not worked. Here is my code any help would be appreciated.

 import java.awt.FlowLayout;
 import java.awt.event.ActionListener;
 import java.awt.event.ActionEvent;
 import javax.swing.JFrame;
 import javax.swing.JTextField;
 import javax.swing.JPasswordField;
 import javax.swing.JOptionPane;
 import java.awt.Color;
 import java.awt.Dimension;
 import javax.swing.JFrame;
 import javax.swing.SwingUtilities;

 public class Main{
    public static void main(String[] args) {
        interfath screen = new interfath();
        screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        screen.setSize(600,600);
        screen.setVisible(true);

    }


 import java.awt.FlowLayout;
 import java.awt.Font;
 import java.awt.event.ActionListener;
 import java.awt.event.ActionEvent;
 import javax.swing.JFrame;
 import javax.swing.JTextField;
 import javax.swing.JPasswordField;
 import javax.swing.JOptionPane;
 import javax.swing.JPanel;

 import java.awt.FlowLayout;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import java.awt.Color;
 import java.awt.Dimension;
 import javax.swing.JFrame;
 import javax.swing.SwingUtilities;
 import javax.swing.JButton;

 public class interfath extends JFrame{

    private JTextField item1; // 
    private JTextField item2; // 
    private JTextField item3; // Header
    private JTextField item4; // Instructions
    private JTextField item5; // First Name,
    private JTextField item6; // Text Box for First Name
    private JTextField item7; // Last Name
    private JTextField item8; // Text Box for Last Name
    private JTextField item9; // Phone Number
    private JTextField item10; // Text Box for Phone Number


    public interfath(){
    setLayout(new FlowLayout());

    item3 = new JTextField("Project ++ 2.0.5.10.20.34", 20);
    item3.setEditable(false);
    item3.setFont(new Font("Times New Roman", Font.BOLD, 20));
    item3.setBackground(Color.YELLOW);
    add(item3);

    item4 = new JTextField("Please fill out the following form and submit.", 60);
    item4.setEditable(false);
    item4.setFont(new Font("Times New Roman", Font.ITALIC, 12));
    item4.setBackground(Color.GRAY);
    add(item4);

    item5 = new JTextField("First Name.",40);
    item5.setEditable(false);
    item5.setFont(new Font("Times New Roman", Font.ITALIC, 12));
    item5.setBackground(Color.GRAY);
    add(item5);

    item6 = new JTextField("", 15);
    add(item6);

    item7 = new JTextField("Last Name.",40);
    item7.setEditable(false);
    item7.setFont(new Font("Times New Roman", Font.ITALIC, 12));
    item7.setBackground(Color.GRAY);
    add(item7);

    item8 = new JTextField("", 15);
    add(item8);

    item9 = new JTextField("Phone Number.",40);
    item9.setEditable(false);
    item9.setFont(new Font("Times New Roman", Font.ITALIC, 12));
    item9.setBackground(Color.GRAY);
    add(item9);

    item10 = new JTextField("", 15);
    add(item10);




    }


 }