samedi 30 avril 2016

Creating an instance of a minefield across .java files

I am trying to make a minefield game with JavaFX. I am having difficulty with creating an instance of the minefield (board) and populating it. After calling makeMinefield(); in the controller, the minefield object is still null. (The rest of the code I have not included because it is so long and have included only what should be relevant.)

Thank you for any advice.

in Minefield.java

package fxMinesweeper;
public class Minefield {

int minefieldWidth  = 10;           // starts at normal , default values
int minefieldHeight = 10;           // should change when choicebox changes

// grid amount of mines
int gridEasyNumMines = 5;
int gridNormalNumMines = 50;
int gridHardNumMines = 190;

int numMinesatStart;
int numMinesLeft;
int cellsUncovered;
boolean exploded;
Cell[][] minefield;

public Minefield(){
    numMinesLeft = 0;
    numMinesatStart = 0;
    cellsUncovered = 0;
    exploded = false;
}

public void makeMinefield(){
    minefield = new Cell[minefieldWidth][minefieldHeight];
    for (int i = 0; i < minefieldWidth; i++) {
        for (int j = 0; j < minefieldHeight ; j++ ){
            Cell Cell = new Cell();             // make Cell
            minefield[i][j] = Cell;          
            minefield[i][j].mined = false;
            minefield[i][j].flagged = false;
            minefield[i][j].x = i;
            minefield[i][j].y = j;
            System.out.println("Cell X = 
                  "+ minefield[i][j].x +": Y = "+ minefield[i][j].y +
                  ": Mined = "+ minefield[i][j].mined +": flagged : " +
                   minefield[i][j].flagged);
        }
    }
}
}

In Controller.java

package fxMinesweeper;

import javafx.beans.value.*;
import javafx.collections.FXCollections;
import javafx.event.*;       // in my code I do not have as many .* 's
import javafx.fxml.FXML;     // I used them here to lessen the imports
import javafx.scene.*;
import java.util.Timer;


public class MenuController implements EventHandler<ActionEvent>{
Minefield minefield;
    public void initialize() {
        System.out.println("Begin Setup");
        Minefield minefield = new Minefield();
        minefield.makeMinefield();
    }
}




How is my sub class?

THIS IS NOT A HOMEWORK QUESTION. I would like to thank you for taking your time helping me. Please help me improve my code like is there any unnecessary part or on which part could i make it better...

public class onlineCourseSubClass { //this is my class

 private int timeMeeting;
 private int numberOfStudent;
 private String professorName;
 private String className;

 public onlineCourseSubClass() { // is it needed to use 2 parameters b/c i had error when i used one.
   timeMeeting = 0;
   numberOfStudent = 0;
   professorName = "Here";
   className = "There";
 }
public onlineCourseSubClass(int timeMeeting, int numberOfStudent, String  professorName, String className) {
  this.timeMeeting = timeMeeting;
  this.numberOfStudent = numberOfStudent;
  this.professorName = professorName;
  this.className = className;
}

public void setTimeMeeting(int timeMeeting) {
  this.timeMeeting = timeMeeting;
}
public int getTimeMeeting() {
  return timeMeeting;
}

public void setNumberOfStudent(int numberOfStudent){
  this.numberOfStudent = numberOfStudent;
}
public int getNumberOfStudent() {
  return numberOfStudent;
}

public void setProfessorName(String professorName) {
   this.professorName = professorName;
}
public String getProfessorName() {
  return professorName;
}

public void setClassName(String className) {
  this.className = className;
}
public String getClassName() {
  return className;
}
public void displayClassInfo() {
  System.out.println("Class's Name: " + className +
                 "\nProfessor: " + professorName +
                 "\nTime Meeting: " + timeMeeting +
                 "\nStudent's Size: " + numberOfStudent);
  System.out.println();

}

}




 public class onlineCourse { // this is my main class
  public static void main (String[] args) {

  onlineCourseSubClass Course1 = new onlineCourseSubClass(9,10, "John", "Math");
  Course1.displayClassInfo();

  onlineCourseSubClass Course2 = new onlineCourseSubClass();
  Course2.setClassName("English");
  Course2.setProfessorName("Nathan");
  Course2.setTimeMeeting(12);
  Course2.setNumberOfStudent(40);
  Course2.displayClassInfo();
  }
}




Can't Properly "conect" a class with its objects

I wanted to make a class that would be the template of a "custom widget" for a "game" I'm trying to make. The problem is that I can only get it to work if when I call the class, I specify the Frame object that holds everything together. I've been searching my whole afternoon and couldn't find a concrete awnser...

The following code works but instead of just needing to write StatusButton().grid() I have to use StatusButton().frame.grid()

from tkinter import *
from tkinter.ttk import Progressbar

class StatusButton(Frame):
    def __init__(self, master):
        super(StatusButton, self).__init__()
        self.frame = Frame(master, padx = 10, pady = 10, bd= 5, relief = RAISED)
        self.label = Label(self.frame, text = "Hunger Bar")
        self.pgbar = Progressbar(self.frame)
        self.button = Button(self.frame, text = "Eat")
        self.label.pack()
        self.pgbar.pack()
        self.button.pack(pady = 5, ipadx = 15)
        return

root = Tk()   
buttonslist = [StatusButton(root) for x in range(16)]

for r in range(4):
    for c in range(4):
        StatusButton(root).frame.grid(row = r, column = c)
root.mainloop()

I'm guessing I'm not properly "conecting" the frame object to the class, even though the former is inside the latter, because when the previous code gets executed, but with StatusButton().grid() instead, the TKinter window pops up normally, but without any content, like if i was "gridding" an empty Frame object. How can I fix this, so that when StatusButton().grid() is run, my "custom widget thing" appears?

Sorry if this is a noob error, it's my first week in programming




Beginners code: HTML Styling ID within ID not working


I have just started learning HTML and I am having problems with IDs/classes within IDs/classes.

So, to my knowledge, an ID is specified by a #. That would mean that if I wanted to style an ID within and ID, wouldn't that be:

#ID1 #ID2 {
    ...
}

Which would mean that the styling will only apply for ID2 that is inside ID1? Please correct me if I'm wrong. When I used the same principle within my (very simple beginner) code, it didn't work. Here is my code:

<!DOCTYPE html>
<html>
    <head>
        <title>1 May 2016</title>
        <style>
            #name {
                color : blue;
                font-family : Tahoma;
            }
            #parafont #1 {
                font-family : Arial;
            }
            #parafont #2 {
                font-family : Times;
            }
            #parafont #3 {
                font-family : Courier;
            }
            parafont #4 {
                font-family : Lucida Grande;
            }
            #parafont #5 {
                font-family : Helvetica;
            }
            #test1 #6 {
                color : blue;
            }
    </style>
    </head>
    <body>
            <h3 id="name">Bob Bobbington</h3>
            <p>1 2 3 4 5 6 7 8 9 10</p>
            <p>When was this website created? Check the <b>title</b>.</p>
            <h3>All animals are quite interesting...</h3>
            <p id="parafont">
                <span id="1">This is a test paragraph.</span>
                <span id="2">Each sentence should have a different font.</span>
                <span id="3">This paragraph is going to use some styling.</span>
                <span id="4">Styling will change the font of each sentence.</span>
                <span id="5">Let's see whether it works!</span>
            </p><div id="test1"><p id="6">Test</p></div>
    </body>
</html>

All help is very much appreciated!




C++ : assign values to data members of an object within a class

I am trying to make a fight sequence. Right now I am just prototyping.

What I would like to do is define a function for the fight sequence in a class, and initialize different monsters to fight with. I have created a data structure in the .h file with the name 'monster'. I then initialize the monster tiger within the class. But when I go into my cpp to give its sound and picture, I run into errors.

What I ultimately want to do is:

#include <iostream>
#include "CombatSeq.h"
int main() {

    // Initiate Combat with a Tiger.

    CombatSeq c;
    c.fight(c.tiger); 
}

Here is my code :

The .h file :

#ifndef SOURCE2_COMBATSEQ_H_
#define SOURCE2_COMBATSEQ_H_

#include <iostream>

struct monster {
    std::string sound;
    std::string picture;
};

class CombatSeq {
public:
    void fight(monster t);

    monster tiger;

private:

};
#endif /* SOURCE2_COMBATSEQ_H_ */

The cpp file :

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


void CombatSeq::fight (monster t) {
    std::cout << t.picture;
    std::cout << t.sound;


}

// What would I put here to give tiger.sound & tiger.picture values?
// I have tried:

monster CombatSeq::tiger;
CombatSeq::tiger.sound = "tiger.ogg";

// But to no avail.

Thank you for your help!




How to increase the Player class Size Upon collision?

I am currently working on a square collecting game in which the User/Player will be a blue square that can only collect squares that are smaller than the player's square. These are represented by color, if the square is smaller than the player than it is green, if it is bigger it will be red.

I have run into a problem where I can not figure out how to INCREASE THE SIZE of the Player when the player collides with the green squares. I have tried a number of different things that don't seem to work and would appreciate some different options to try and accomplish this task.

Here is the code that I am currently using:

import pygame
import random

# Define some colors
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

class Block(pygame.sprite.Sprite):
    """
    This class represents the ball.
    It derives from the "Sprite" class in Pygame.
    """

    def __init__(self, color, width, height):
        """ Constructor. Pass in the color of the block,
        and its x and y position. """

        # Call the parent class (Sprite) constructor
        super().__init__()

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        self.image = pygame.Surface([width, height])
        self.image.fill(color)

        # Fetch the rectangle object that has the dimensions of the image
        # image.
        # Update the position of this object by setting the values
        # of rect.x and rect.y
        self.rect = self.image.get_rect()

class Player(pygame.sprite.Sprite):
    """ The class is the player-controlled sprite. """

    # -- Methods
    def __init__(self, x, y):
        """Constructor function"""
        # Call the parent's constructor
        super().__init__()

        # Set height, width
        self.image = pygame.Surface([15, 15])
        self.image.fill(BLUE)

        # Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

        # -- Attributes
        # Set speed vector
        self.change_x = 0
        self.change_y = 0

    def changespeed(self, x, y):
        """ Change the speed of the player"""
        self.change_x += x
        self.change_y += y

    def update(self):
        """ Find a new position for the player"""
        # move left or right
        self.rect.x += self.change_x
        if self.rect.x <= 0:
            self.rect.x = 1
            wall_sound.play()
        if self.rect.x >= 680:
            self.rect.x = 679
            wall_sound.play()
        # move up or down
        self.rect.y += self.change_y
        if self.rect.y <= 0:
            self.rect.y = 1
            wall_sound.play()
        if self.rect.y >= 385:
            self.rect.y = 384
            wall_sound.play()


# Initialize Pygame
pygame.init()

# Set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])

# This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'Group.'
block_list = pygame.sprite.Group()

# This is a list of every sprite. 
# All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()

# Create a BLUE player block
p_width = 30
p_height = 25
p_size = (p_width, p_height)
player = Player(p_width, p_height)
all_sprites_list.add(player)

# BLOCK LIST 
for i in range(50):
    width = random.randrange(20, 50)
    height = width - 5
    b_size = (width, height)
    if b_size <= p_size:
        color = GREEN
    if b_size > p_size:
        color = RED
    # This represents a block
    block = Block(color, width, height)

    # Set a random location for the block
    block.rect.x = random.randrange(screen_width - width)
    block.rect.y = random.randrange(screen_height - height)

    # Add the block to the list of objects
    block_list.add(block)
    all_sprites_list.add(block)

# Loop until the user clicks the close button.
done = False

# Pygame sound effects

collect_good = pygame.mixer.Sound("SnowWalk.ogg")
collect_bad = pygame.mixer.Sound("icebreaks.ogg")
wall_sound = pygame.mixer.Sound("evillaugh.ogg")

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

font = pygame.font.Font(None, 25)

score = 0

# -------- Main Program Loop -----------
while not done:
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            done = True

     # Set the speed based on the key pressed
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.changespeed(-3, 0)
            elif event.key == pygame.K_RIGHT:
                player.changespeed(3, 0)
            elif event.key == pygame.K_UP:
                player.changespeed(0, -3)
            elif event.key == pygame.K_DOWN:
                player.changespeed(0, 3)

        # Reset speed when key goes up
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player.changespeed(3, 0)
            elif event.key == pygame.K_RIGHT:
                player.changespeed(-3, 0)
            eli
    # See if the player block has collided with anything.
        #good
    blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)

    # Check the list of collisions.
        #good
    for block in blocks_hit_list:
        score += 1
        collect_good.play()

    if score <= -1:
        done = True
    # Draw all the spites
    all_sprites_list.draw(screen)

    text = font.render("Score: " + str(score), True, BLACK)
    screen.blit(text, [20, 300])

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Limit to 60 frames per second
    clock.tick(60)

pygame.quit()f event.key == pygame.K_UP:
                player.changespeed(0, 3)
            elif event.key == pygame.K_DOWN:
                player.changespeed(0, -3)

     # This calls update on all the sprites
    all_sprites_list.update()

    # Clear the screen
    screen.fill(WHITE)

    # See if the player block has collided with anything.
        #good
    blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)

    # Check the list of collisions.
        #good
    for block in blocks_hit_list:
        score += 1
        collect_good.play()

    if score <= -1:
        done = True
    # Draw all the spites
    all_sprites_list.draw(screen)

    text = font.render("Score: " + str(score), True, BLACK)
    screen.blit(text, [20, 300])

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Limit to 60 frames per second
    clock.tick(60)

pygame.quit()




C++ printing contents of array that was declared in main

working on program where an array has to be declared in the main (in this case, distList[5]) and it has to be sent to one member where it has to be filled by user input (inputDist) and then sent to another member from there (printAndAdd) to be printed and added, as suggested by the name. I believe I've gotten the array filled, but I'm not sure how to go from there. any help is appreciated.

void CDistance::inputDist(CDistance distList[], int size)
{

    for (int i = 0; i < 1; i++)
    {
        cout << "Please enter 5 digits following each one with a space to place into the array: " << endl;
        int ui1;    cin >> ui1;
        int ui2;    cin >> ui2;
        int ui3;    cin >> ui3;
        int ui4;    cin >> ui4;
        int ui5;    cin >> ui5;
        distList[i] = CDistance(ui1, ui2, ui3, ui4, ui5);
        cout << distList;

    }
}

void CDistance::printAndAdd(const CDistance distList[], int size)
{
    //cout << distList;
}

int main()
{
    CDistance distList[5];

    CDistance d1, d2(0, 0, 0, 0, 0);

    d1.setDistt();
    d1.printDistt();
    d1.menu(d2);
    d1.inputDist(distList, 5);
    d1.printAndAdd(distList, 5);
    _getch();
    return 0;
}

Also, here is the class definition of CDistance:

class CDistance
{
private:
    int feet;
    int inches;
    int feet2;
    int inches2;
    int five;

public:
    CDistance();
    CDistance(int, int, int, int, int);
    ~CDistance();
    void setDistt();
    void printDistt() const;
    void add(const CDistance&) const;
    void subtract(const CDistance&) const;
    void menu(const CDistance&) const;
    void inputDist(CDistance distList[], int size);
    void printAndAdd(const CDistance distList[], int size);
};

CDistance::CDistance()
{
    feet = 0;
    inches = 0;
    feet2 = 0;
    inches2 = 0;
    five = 0;
}

CDistance::CDistance(int f, int i, int f2, int i2, int fi)
{
    feet = f;
    inches = i;
    feet2 = f2;
    inches2 = i2;
    five = fi;
}

CDistance::~CDistance()
{
}




Why am I having an undefined reference error using class Templates? [duplicate]

This question already has an answer here:

Both classes are in header file, that is not the problem. For some reason my program tells me that I have an undefined reference error. I am not totally sure why that might be.

I have one implementation file for 2 classes. Might that be where the error comes from?

This is one of my first class

#ifndef NODE_H
#define NODE_H
#include <iostream>
#include <string>

using namespace std;

// Node class
template <class T>
class Node 
{
    private:
        int ID;
        string name;
        T test1, test2, test3;
        static const int counter = 0;
        Node* next;
  public:
    Node() 
    {
        ID = NULL;
        name = NULL;
        test1 = NULL;
        test2 = NULL;
        test3 = NULL;
    }
    ~Node(){}
    void SetID(); //giving a value for employee number
    void SetName();   //giving a value for yearly salary
    void SetTests();
    void SetNext(Node*);
};
#endif

This is my second class

#include <iostream>
#include <string>
#ifndef LIST_H
#define LIST_H
#include "Node.h"

using namespace std;

template <class T>
class List 
{
    Node<T>* head; //creating the head
                // head is an object that stores the address of the first node
    string dash;
  public:
    // constructor that initializes every list to null
    List() 
    { 
        dash.assign(80,'-'); // variable used for aesthetics
        head = NULL;    
    }

    ~List(){}
    // prtototype of the list member functions
    void Add();
};
#endif

This is my implementation file

#include <iostream>
#include <fstream>
#include "Node.h"
#include "List.h"

using namespace std;

template <class T>
void List<T> :: Add ()
{
    // Create a new node
    Node<T>* newNode = new Node<T>();
    newNode->SetID(); //giving a value for employee number
    newNode->SetName();   //giving a value for yearly salary
    newNode->SetTests();
    newNode->SetNext(NULL);              //setting the next node equal to NULL

    /*If(!isEmpty())
    {*/

   // Adding values to the elements of the head when head is empty
    if(head == NULL)
      head = newNode;

    //Inserting Elements at the beginning of the list
    else
    {
       newNode->SetNext(head); //make newNode -> point to the head
       head = newNode;     //make the head newNode
     }

}

This is the Main file

#include "Node.h"
#include "List.h"
#include <iostream>
#include <cstdlib>

using namespace std;
////////////////////////////////////////////////////////////////////////////////
                                  /* Main*/
////////////////////////////////////////////////////////////////////////////////
template <class T>
void menu(List<T> &);


int main()
{
    // New list
    List<int> list;
    menu(list); //List function call
    return 0;
}

///////////////////////////////////////////////////////////////////////////////
                    /*This function dispalys a Menu for the user to
                      pick the desired action to the linked list.
                      It uses the member functions of the class List, 2 loops
                      and a switch statement to execute these actions */
///////////////////////////////////////////////////////////////////////////////
template <class T>
void menu(List<T> &list)
{   char choice;

    do{ 
        system("CLS"); // use #include <cstdlib> to be able to use this
        system("CLS") clears the window
        cout << "\t\t\tWelcome User\n";
        cout << "\t\t\tMain Menu\n\n";
        cout << "\t(A)dd\n";
        cout << "\t(L)ocation\n";
        cout << "\t(R)emoves\n";
        cout << "\t(C)lear\n";
        cout << "\t(P)eek\n";
        cout << "\t(A)verage\n";
        cout << "\t(G)rade\n";
        cout << "\t(E)xit\n";
        cout << "\t\tWhat would you like me to do? ";
        cin >>choice;
        choice = toupper(choice); // chaging the character to capital
        //validation of entered choice
        while (choice != 'A' && choice != 'L' && choice != 'R' && choice != 'C'
               && choice != 'P' && choice != 'G' && choice != 'E' )
        {
            cout << "\n\t\tSorry invalid input\n\t\tPlease enter one of the ";
            cout << "choices below : ";
            cin >> choice;
        }
        cin.ignore();
         while (choice != 'A' && choice != 'L' && choice != 'R' && choice != 'C'
               && choice != 'P' && choice != 'G' && choice != 'E' )
        //switch statement used 
        switch (choice)
        { case 'A': //To insert 
            list.Add();
            cout << endl; 
            cin.get();
            cin.ignore();
            break;} 
    }while (choice != 'E'); //Runing the program until E is entered
}

I do not understand why do I have a reference error because I make sure I have guards, and include all the header files.

What is giving me an undefined reference error?

(.text$_Z4menuIiEvR4ListIT_E[_Z4menuIiEvR4ListIT_E]+0x199): undefined reference to `List<int>::Add()'
C:\Users\Documents\collect2.exe [Error] ld returned 1 exit status
C:\Users\Documents\Makefile.win recipe for target '"Last' failed




Calling newInstance() when creating a child fragment extending a parent fragment

I have a parent DialogFragment called TheParent and a child Fragment called TheChild which extends TheParent.

However, I need to be able to initialize some variables in TheParent even though I am instantiating TheChild, so what I tried was:

In the parent

public static TheParent newInstance(int myInt) {
    Bundle args = new Bundle();
    TheParent fragment = new TheParent();
    args.putInt(ARGUMENT_MYINT, myInt);
    fragment.setArguments(args);
    return fragment;
}

and then in the child:

public static TheChild newInstance(int myInt) {
    return super.newInstance(myInt);
}

However it does not like me doing this because of the static context.

What is the correct way to call newInstance() on TheChild and have it invoke newInstance() of the parent?




Clarification on a circular dependancy

My previous post has already been tagged as a duplication - lots of unreasonable compiler errors c++

Ive tried the suggested solutions (and edited the code in my original post according to the suggestion provided). However when forward declaring "class course;", my compiler doesnt seem to recognize the class in the previous files, saying that course(the class) is an incomplete type in every place its mentioned in "student.cpp".

Did I miss the point? how do I resolve the circular dependancy in my code? (I can copy my code here from the previous post, but Id assume its better to keep this post as short as possible?).

Thanks in advance.




Python Multiprocessing Pool with class instance as argument

I would like to run my code in parallel by passing, however I am getting the following error: cPickle.PicklingError: Can't pickle : attribute lookup builtin.function failed

Below is the basic code structure. I would like to run the increment_ID's function in parallel. Thanks for helping.

class Firm():
    def __init__(self):
        self.ID = 0

    def print_ID(self):
        print self.ID

class simulations():
    def __init__(self):
        self.firms_list = [firm.Firm() for count in xrange(10)]

    def increment_IDs(self):
        for firm in self.firms_list:
               firm.ID += 1




Alphabetizing a list through class methods

I have been trying to print a list using a str method of a class, but before the list can be printed it has to be alphabetized through other methods coming before the str method in the class. The provided methods for this are

def returnName(self):
    '''return the name of the player first last'''

    return(self.first + self.last)

def returnReverseName(self):
    '''return the name of the player as last, first'''
    reverseName = (str(self.last), str(self.first))
    return(reverseName)

def __eq__ (self, other):
    '''determine if this persons name is the same as the other personsname'''

    if self.returnReverseName == other.returnReverseName:
        return True
    else:
        return False


def __lt__(self,other):
    '''determine if this persons name is less than the other persons name alphabetically'''

    if str(self.returnReverseName) < str(other.returnReverseName):
        return True
    else:
        return False

def __gt__ (self, other):
    '''determine if this persons name is greater than the other persons name alphabetically'''

    if self.returnReverseName > other.returnReverseName:
        return True
    else:
        return False

def __str__(self):
    '''return a string of the persons name and their rating in a nice format'''

    Name1 = str(self.first) + ' ' + str(self.last)
    return ('%-20s %10.2f' % (Name1, self.rating))

where the name needs to be sorted by last name, first name but printed in first name last name order. the methods lt and gt are what should be ordering them when printed. The code I have so far to compile the list is

basicList.sort()
for line in playerDict:
    print(playerDict[line])

but this doesn't utilize the list, and is only printing the dictionary line by line in an unordered manner, although it does refer to the methods it is just unable to alphabetize the names. How do I properly use the methods to get the dictionary printed in the right order, and if I need to use the list of player objects how do I get it to print using the str method that would be printed post-alphabetization? Thank you in advance for the help




Ruby: Disallow updating of an array that is a class variable

I am writing a simple Tic Tac Toe game, in which I have a class for the Board, the Player, the Computer, and the Game itself. In my Board class, I have set a class variable @board (which is an array) as attr_reader, which should disallow writing directly to it. Although the following will not work (as intended)

game_board = Board.new 
game_board.board = "some junk"

The following does work, which I don't want to happen

game_board = Board.new
game_board.board[0] = "some junk"

How do I stop the class array variable @board from being written to? Current class code below:

class Board
  attr_reader :board

  def initialize
    create_board
  end

  private
  def create_board
    @board = Array.new(3).map{Array.new(3)}
  end
end

game_board = Board.new 
game_board.board
 #=> [[nil,nil,nil],[nil,nil,nil],[nil,nil,nil]]
game_board.board = "junk"
 #=> undefined method 'board ='  

game_board.board[0] = "junk" 
game_board.board 
 #=> ["junk",[nil,nil,nil],[nil,nil,nil]] #I don't want to allow this!

I tried googling this, but to no avail, however I am a complete beginner, so I may not be using the correct search terms




Pure virtual function can't be defined in .cpp for derived class?

Consider the following code:

main.cpp:

#include "Test.h"
int main()
{
    B b = B();
    return 0;
}

Test.h:

class A {
public:
    virtual int foo() = 0;
};

class B {
public:
    int foo();
};

Test.cpp:

#include "Test.h"
int B::foo()
{
    return 1;
}

This produces the following error: error LNK2001: unresolved external symbol "public: virtual int __thiscall B::foo(void)"

This error does not accure if I implement the function inside the class, like this:

class B {
public:
    int foo()
    {
        return 1;
    }
};

(Test.cpp empty)

Why is it apparently not possible to implement the function in the .cpp file?




Transferring list from one class method to another

So in a class that I have, I create a list from information gathered in a different list line by line, and so far that has gone smoothly. My issue is that with this newly made list, I need to utilize a different method in the same class in order to print the list's information in a structured manner. I am unsure of exactly how to get the new list from one method to another so that I can begin the printing process. In my main program, that utilizes a dictionary (string value as key, class object as value) to refer to the class methods, I have the input of

playerDict[nameChoice].calc(basicList)

which takes me to the method for the given player, and then compiles the list. The two methods are as follows

    def calc(self, sublist):
    '''calculate a passer rating for one sub-list year in the info list'''

    ratingList = []
    count = 0
    for line in self.info:
        C = ((((int(line[3]) / int(line[4]))*100) - 30)/20)
        if C > 2.375:
            C = 2.375
        Y = (((int(line[5]) / int(line[4])) - 3) * .25)
        if Y > 2.375:
            Y = 2.375
        T = (((int(line[6])) / int(line[4])) * 20)
        if T > 2.375:
            T = 2.375
        I = 2.375 - ((int(line[7])/int(line[4])) * 25)
        ratingtop = (C + Y + T + I)
        ratingbot = 6
        yearRating = float((ratingtop / ratingbot) * 100)
        ratingList.append([self.info[count][0], self.info[count][2], yearRating])
        print(ratingList)
        count += 1
    ratingList.sort()
    print(ratingList)
    print_ratings = self.printInfo
    return ratingList

def printInfo(self):
    '''print individual year information about this player including each years passer rating. The list should be in year order. Use calc to assist.'''

So the list I need in the printInfo method is ratingList. In my main program, I have invoked the two separately, using playerDict[nameChoice].calc(basicList) and playerDict[nameChoice].printInfo(), but I need to find a way to get the ratingList into the printInfo method in order to print out the information in the list in the specified manner. How would I go about doing this? I dont have printInfo completed yet but that part will come easily once I am capable of utilizing the list in the method.




Creating a new instance of a class from another class

So I'm stuck on some homework trying to create an instance of the Employee class from my class called records.

public class Employee implements Comparable<Employee>

{
/* instance variables */
private String Name;
private String employeeNumber;


/**
 * Constructor for Employee
 */
public Employee(String employNum)
{
   super();
   this.employeeNumber = employNum;             
}

Next I need to create a Record class that will create a HashSet of Employees details, this is where I need help.

public class Records
  {
  Set<String> employeeSet = new HashSet<String>();

  public Records()
  {

  }

Then I want it to have a method for adding a new employee and then putting their records in the set.

public void newEmployee(String employNumber)
{
  Employee newEmp = new Employee(employNumber);
  employeeSet.add(//other methods);
}

I can't get that last bit to create a new employee.




Ruby wrong number of arguments in class instantitation

I am trying to make a battleship game in Ruby, but when I try to create an instance of the game board, I get "wrong number of arguments, 0 for 1". I dont see where I am going wrong as the initialize definition clearly accepts arguments.

class Board

  attr_reader :grid, :default_grid

  def intitalize(grid = self.class.default_grid, random = false)
    @grid = grid
    make_random_board if random
  end

  def self.default_grid
    grid = Array.new(10){Array.new(10)}
  end

  def count
    grid.flatten.count{|x| x == :s}
  end

  def self.random
    self.new(self.default_grid, true)
  end

  def empty?(position = nil)
    return true if position.nil?
    else
    false
  end

  def full?
    grid.flatten.none?(&:nil?)
  end

  def place_random_ship
      if full? 
        raise "error, board is full"
      end

      space = [rand(grid.length),rand(grid.length)] 
        until empty?(space)
          space = [rand(grid.length),rand(grid.length)]
        end
      self[space] = :s
  end

  def make_random_board(count = 10)
    count.times do
      place_random_ship
    end
  end

end

emptygrid = Array.new(2){Array.new(2)}
myGame = Board.new(emptygrid)




How to create a class that will store a tuple of (r,g,b)?

requirements:

Create a class called "Color" that will store a tuple of (r,g,b).

The tuple should be stored in a data member called color.

The components of the color tuple should be stored in data members: red, green, blue as well

Add a str method to print out the color class so it looks like: "(red: redVal, green: greenVal, blue: blueVal)"




Assign class labels to text documents

I have two text documents with words from different news feeds called sports.txt and politics.txt. These were gathered from rss feeds.

I want to assign class labels to the documents based on the type of news they contain - i.e. 'Sports' and 'Politics' target names, prior to creating a document term matrix.

How do I assign target names to my own data?

Seems so simple but I have been looking for the answer for days and can't find it... All examples involve loading data-sets like iris which already have assigned 'setosa', 'virginica' etc target names assigned...




Can the same Python objects vary in size since there is no formal initialization?

I'm trying to learn some basic Python object design. One thing I noticed is that python doesn't require you to list out all data members before you are able to use them within the class. Instead, I've noticed that you are able to introduce new data members throughout different method calls on a class.

Referring to the code below, notice how I use the constructor to declare a self.hello_world member. Because the constructor is called for every instance of that class, I am certain that every object will contain a hello_world member.

However, notice how I create a self.dog data member ONLY if I call the printTest method. This data member would not exist if I don't call this method.

So my question, unlike the programming language C++ in which all objects must have a certain object size, can python objects instantiated from the same class vary in size due to what I pointed out?

Thank you!

# Class test

class TestClass:


    def __init__(self):
        self.hello_world = 49

    def printTest(self):
        print("Trying to create new data member /n")
        self.dog = "Biscuit"




Variables in a Class that points to an object class

I am trying to make a simple ai soccer simulator in java,i have a Player class and a Ball class..how can i make 2 variables(CurrentPlayer and ExPlayer) in Ball class that points to object class Player that has the ball ,or to null if the ball is free?

Thanks! :D




What do parentheses do after a class is called?

I have been trying to make a simple player class that contains all of the important player functions in python. I was just getting into the pygame module, when I noticed a class used parentheses. I took the time to learn what a class does in python, but, couldn't find why parentheses are used after for a class. Here is my main code.

class plr(pygame.sprite.Sprite):
    def __init__(self):
        plr.__init__(self)
        self.image = pygame.Surface((20,20))
        self.image.fill(black) 

Any explanations?




curly braces php on class [duplicate]

This question already has an answer here:

I have a simple class... I need to update public $token if it is setted. My code is:

<?php
class Amazon {
    public $token = '';
    public function update($key = '', $value = '')
    {
        if(isset($this->"{$key}"))
        {
            $this->"{$key}" = $value;
        }
        return true;
    }
}

But I am getting this error: Parse error: syntax error, unexpected '"', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'




ClassCastException for no reason?

I'm getting a ClassCastException for seemingly no reason. Let me explain the structure of my code: AbilityModifier is an abstract class ProjectileModifier is an abstract class which extends AbilityModifier NoGravity is a class which extends ProjectileModifier

AbilityModifier has a custom ClassLoader that I use to find all ability modifiers. This way I don't have the register them manually. However, to register them automatically, I need to cast them and add them to a List. When I cast it, it throws a ClassCastException saying that redempt.divinity.ability.modifier.modifiers.NoGravity cannot be cast to redempt.divinity.ability. I've done a test, and everything works with no exceptions:

package redempt.test;

public class Main {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Class<?> clazz = C.class;
        Object o = clazz.newInstance();
        A a = A.class.cast(o);
        System.out.println("Finished!");
    }
}
class A {
    public A() {

    }
}
class B extends A {
    public B() {

    }
}
class C extends B {
    public C() {

    }
}

So that works, but for some reason, my other code does not. Let me give you all the classes involved:

AbilityModifier:

package redempt.divinity.ability.modifier;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import redempt.divinity.Main;
import redempt.divinity.ability.AbilityType;

public abstract class AbilityModifier {
    public static Set<AbilityModifier> modifiers = new HashSet<AbilityModifier>();
    public abstract void onUse(Player player);
    public abstract String getName();
    public abstract Material getRepresentation();
    public abstract AbilityType getType();
    public static void registerAll() throws IOException, ClassNotFoundException, URISyntaxException, InstantiationException, IllegalAccessException {
        File file = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
        JarFile jar = new JarFile(file);
        file.toURI().toURL();
        URL[] urls = {file.toURI().toURL()};
        List<String> names = new ArrayList<String>();
        URLClassLoader loader = URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName().replace("/", ".");
            if (name.endsWith(".class")) {
                try {
                    Class<?> clazz = loader.loadClass(name.replaceAll("\\.class$", ""));
                    System.out.println("Loading class: " + clazz.getSimpleName());
                    System.out.println(isSubclass(clazz));
                    if (isSubclass(clazz) && !Modifier.isAbstract(clazz.getModifiers())) {
                        names.add(clazz.getSimpleName());
                        AbilityModifier modifier = AbilityModifier.class.cast(clazz.newInstance());
                    }
                } catch (NoClassDefFoundError e) {
                    System.out.println("Unable to load class: " + name);
                }
            }
        }
        loader.close();
        jar.close();
        System.out.println(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().toURL().getPath());
        System.out.println("All ability modifiers found:");
        for (String name : names) {
            System.out.println(name);
        }
    }
    public static void register(Class<? extends AbilityModifier> clazz) {

    }
    private static boolean isSubclass(Class<?> clazz) {
        if (clazz.getSuperclass().equals(Object.class)) {
            return false;
        }
        return clazz.getSuperclass().getName().equals(AbilityModifier.class.getName()) ? true : isSubclass(clazz.getSuperclass());
    }
}

ProjectileModifier:

package redempt.divinity.ability.modifier;

import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import redempt.divinity.ability.Ability;

public abstract class ProjectileModifier extends AbilityModifier {
    public abstract void onUse(Player player, Entity projectile);
    @Override
    public void onUse(Player player) {
    }
    public abstract void onHit(Ability item, int level, EntityDamageByEntityEvent event);
    public abstract void onTick(Entity projectile);
}

NoGravity:

package redempt.divinity.ability.modifier.modifiers;

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.util.Vector;
import redempt.divinity.ability.Ability;
import redempt.divinity.ability.AbilityType;
import redempt.divinity.ability.modifier.ProjectileModifier;

public class NoGravity extends ProjectileModifier {
    Vector vector;
    Location lastpos;
    @Override
    public void onUse(Player player, Entity projectile) {
        vector = player.getLocation().getDirection().normalize();
        lastpos = projectile.getLocation().clone();
    }
    @Override
    public String getName() {
        return "No gravity";
    }
    @Override
    public Material getRepresentation() {
        return Material.FEATHER;
    }
    @Override
    public AbilityType getType() {
        return AbilityType.PROJECTILE;
    }
    @Override
    public void onHit(Ability item, int level, EntityDamageByEntityEvent event) {
    }
    @Override
    public void onTick(Entity entity) {
        lastpos.add(vector);
        if (lastpos.getBlock().getType().equals(Material.AIR)) {
            entity.setVelocity(vector);
        }
        lastpos = entity.getLocation().clone();
    }
    public NoGravity() {
    }
}

Exception:

java.lang.ClassCastException: redempt.divinity.ability.modifier.modifiers.NoGravity cannot be cast to redempt.divinity.ability.modifier.AbilityModifier
        at redempt.divinity.ability.modifier.AbilityModifier.registerAll(AbilityModifier.java:47) ~[?:?]
        at redempt.divinity.Main.onEnable(Main.java:30) ~[?:?]
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:292) ~[spigot-1.9.jar:git-Spigot-f04e043-52c7fc0]
        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340) [spigot-1.9.jar:git-Spigot-f04e043-52c7fc0]
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [spigot-1.9.jar:git-Spigot-f04e043-52c7fc0]
        at org.bukkit.craftbukkit.v1_9_R1.CraftServer.loadPlugin(CraftServer.java:361) [spigot-1.9.jar:git-Spigot-f04e043-52c7fc0]
        at org.bukkit.craftbukkit.v1_9_R1.CraftServer.enablePlugins(CraftServer.java:321) [spigot-1.9.jar:git-Spigot-f04e043-52c7fc0]
        at net.minecraft.server.v1_9_R1.MinecraftServer.t(MinecraftServer.java:411) [spigot-1.9.jar:git-Spigot-f04e043-52c7fc0]
        at net.minecraft.server.v1_9_R1.MinecraftServer.l(MinecraftServer.java:376) [spigot-1.9.jar:git-Spigot-f04e043-52c7fc0]
        at net.minecraft.server.v1_9_R1.MinecraftServer.a(MinecraftServer.java:331) [spigot-1.9.jar:git-Spigot-f04e043-52c7fc0]
        at net.minecraft.server.v1_9_R1.DedicatedServer.init(DedicatedServer.java:269) [spigot-1.9.jar:git-Spigot-f04e043-52c7fc0]
        at net.minecraft.server.v1_9_R1.MinecraftServer.run(MinecraftServer.java:527) [spigot-1.9.jar:git-Spigot-f04e043-52c7fc0]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_65]




For Swift language, what is the difference in initializing structs versus initializing classes? (I'm fairly new to programming)

I am using the Swift Programming language. Here is the code:

class CalculatorBrain9iOS{

    ***bunch of code***
    ***bunch of code***

    private var accumulator = 0.0
    private var pending: PendingBinaryOperationInfo?

    private struct PendingBinaryOperationInfo {
        var binaryFunction: (Double, Double) -> Double
        var firstOperand: Double
    }

    func ...(...) {
        if let operation = ... {
            switch operation {
            case ...
            case RandomFunction.ThisCase(let function):
                pending = PendingBinaryOperationInfo(binaryFunction:
                function,
                firstOperand: accumulator)

            }
        }
    }
    ***bunch of code***
}

I want to change the private struct (PendingBinaryOperationInfo) to a class. It doesn't need inheritance so I figured I could just replace "private struct" with "class". But I keep getting initializer error messages on that line. Is it strictly because that new class is a nested class? Or are there other factors involved?

I guess my other big question here is: Aside from inheritance and value/reference, what other differences exist between classes and structs that makes it so that I can't just replace a struct with a class and still have the program run perfectly fine?

*PS: Sorry, buts it's not letting me indent the lines for some reason.




How to store types in generic list in java?

In Java is it possible to store class types (derived from an interface) in collection like that?

public interface SampleInterface {
    List<Class<SampleInterface>> getDependencyList();
}

My dependent class 1 (without any dependency):

public class MySampleDependentClass1 implements SampleInterface {

    @Override
    public List<Class<SampleInterface>> getDependencyList() {

        List<Class<SampleInterface>> dependencies = new ArrayList<Class<SampleInterface>>();
        return dependencies;
    }

}

My dependent class 2 (what depends on the MySampleDependentClass1, so it wants to give MySampleDependentClass1 as it's dependency as a return value):

public class MySampleDependentClass2 implements SampleInterface {

    @Override
    public List<Class<SampleInterface>> getDependencyList() {

        List<Class<SampleInterface>> dependencies = new ArrayList<Class<SampleInterface>>();

        // NOT WORKING
        dependencies.add( MySampleDependentClass1.class );

        return dependencies;
    }
}

How could I add this class type to the collection? (without instantiating the class if possible) Is this collection "good" for storing the dependencies? Or should I use Type instead of Class? Or should I use wildcards like:

<? extends Class> 

or

<? extends SampleInterface>

instead?

I'am sure these questions are already answered somewhere, but after a longer googling I couldn't find the correct answer.




How do I call on a parent class in a subclass?

I need to create an UNBOUND method call to Plant to setup name and leaves and I don't know how. Any help is appreciated.

My code:

class Plant(object):
    def __init__(self, name : str, leaves : int):
        self.plant_name = name
        self.leaves = leaves
    def __str__(self):
        return "{} {}".format(self.plant_name, self.leaves)
    def __eq__(self, plant1):
        if self.leaves == plant1.leaves:
            return self.leaves
    def __It__(self, plant1):
        if self.leaves < plant1.leaves:
            print ("{} has more leaves than {}".format(plant1.plant_name, self.plant_name))
            return self.leaves < plant1.leaves
        elif self.leaves > plant1.leaves:
            print ("{} has more leaves than {}".format(self.plant_name, plant1.plant_name))
            return self.leaves < plant1.leaves

class Flower(Plant):
    def __init__(self, color : str, petals : int):
        self.color = color
        self.petals = petals

    def pick_petal(self.petals)
        self.petals += 1

Exact wording of the assignment:

Create a new class called Flower. Flower is subclassed from the Plant class; so besides name, and leaves, it adds 2 new attributes; color, petals. Color is a string that contains the color of the flower, and petal is an int that has the number of petals on the flower. You should be able to create an init method to setup the instance. With the init you should make an UNBOUND method call to plant to setup the name and leaves. In addition, create a method called pick_petal that decrements the number of petals on the flower.




declare class with if condition

I should initialise with if condition.

How to do this?

Class transport(bool two_wheel=true)
{

   string car,

   string bus,

   if ( two_wheel=true)

   {

     string bike,

     string cycle

   }

};




vendredi 29 avril 2016

python - Trouble calculating manhatan distance, TypeError

So I have a school project where we need to make a few classes for a GPS system. I'm having an issue figuring out the function dist(self,other): shown at the bottom of my code. Other definitions later in the project heavily rely on it, but i'm stumped at this point. The dist function calculates the Manhattan distance (x1-x2)+(y1-y2) of a location defined by instance variables x and y, and another location other which is given as a Tuple

class GPS_Location:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __str__(self):
        return '(%s,%s)' % (self.x,self.y)
    def __repr__(self):
        return 'GPS_Location(%s,%s)' % (self.x,self.y)
   def __eq__(self,other):
        self.other = other
        if (self.x,self.y) == other:
            return True
        else:
            return False
    def dist(self,other):
        self.other = other
        return abs(self.x - (other[0])) + abs(self.y - (other[1]))

When testing the code, I keep getting "TypeError: 'Location' object is not iterable". I have tried so many tweaks, and I just can't figure out what i'm doing wrong.

Any help would be greatly appreciated!




How to send variable in 2 class ?? why this id = nul?

null variable

my script 1.first class

public interface gg {

public static String id= as;

}

2.second class

import static penjualan.KategoriC.gg.id;

System.out.println("id = "+id);




Using Class name as variable name in Swift

I want to extend the UIView to export itself as a UIImage, by just calling:

let image = myView.UIImage

But when trying to create that UIView extension by doing:

extension UIView {
var UIImage:UIImage {
    get {
        let image = UIImage()

        // ..... my code ....//

        return image

    }
}

I get the following compilation error:

'UIImage' used within its own type

Anyone knows how to make it work?

PS: I know I can simply use a different name, but that is not what I am asking here.




GLFW fails to create a window due to memory issues, likely caused by poor use of pointers

I've been using Windows 10's code::blocks IDE to attempt to create the foundations of a graphics engine. Essentially I have run into problems with memory when trying to allow for future ability to create multiple windows if necessary.

To do this, I created a class 'windowClass' within a file called window.cpp. Here is the declaration:

class windowClass {
public:
    int Width, Height;
    GLFWwindow* mainWindow;
    bool fullscreen;  };

declaring an instance of the class called 'GameWindow':

windowClass GameWindow;

You can see that there are public values of Width, Height and a GLFW window called 'mainWindow'. Later in this 'window.cpp' file, I wanted to create a function that would allow me to define this GLFW window.

Function declaration:

void createWindow(windowClass* window)

and then window definition within the function:

window->mainWindow = glfwCreateWindow(860, 640, "gameWindow", NULL, NULL);
window->fullscreen = false;
window->Width = 860;
window->Height = 640;

Here, my goal was to use a pointer to a WindowClass so that any changes made within the function would be permanent for the rest of the program. Finally, before attempting to run the program, I called the function within 'main.cpp'

class windowClass *windowPointer = &GameWindow;
createWindow(windowPointer);

Again, the goal here was to make sure that any changes made to the classes within the createWindow function were passed to the TRUE GameWindow, not just an instance of it.

Despite these intentions, when I'm debugging, and once all of the changes to 'GameWindow' has been stepped through, 'GameWindow's various variables end up with the following values in the 'watch' window:

  • mainWindow: 0x35c
  • Width: 640
  • Height: 40776776
  • fullscreen: false

I would like to point out that 'Width' was passed what 'Height' was meant to recieve, and that mainWindow received a value of 0x35c, while, in working programs, GLFW windows get a value of something like: 0x8133b0

All of these errors in memory allocation result in a SIGSEGV fault when trying to run this while loop:

while (!glfwWindowShouldClose(GameWindow.mainWindow)) {
    glfwSwapBuffers(GameWindow.mainWindow);
    glfwPollEvents();
}

Here's my question: Is there something wrong with the pointers and memory management I'm writing, is my C++ code terrible, or am I taking a horrible approach to this entire problem?




How do I drop an item from a list when it doesn't have a specific name?

How do I remove an item from a list if the item doesn't have an actual name?

I have a class that includes a method called additem that adds an Item object that I constructed in another class. The Item object has two parameters: String name, String type, which are the name of the item and the type of the item. Here is the code for the additem method:

public void additem(String name, String type){
    if("Weapon".equals(type)){
        itemlistweapons.add(new Item(name, type).toString());
    }
    else if ("Apparel".equals(type)){
        itemlistapparel.add(new Item(name, type).toString());
    }
    else if ("Aid".equals(type)){
        itemlistaid.add(new Item(name, type).toString());
    }
    else if ("Misc.".equals(type)){
        itemlistmisc.add(new Item(name, type).toString());
    }
}

So, when I add an item to the list in the main class, I do it like so:

items list = new items();

list.additems("Itemname", "Itemtype");

So I never actually give the Object a name to call upon. How could I have a method that removes that specific item from the list if the item was never identified? Is there a way I could identify the item by giving the object a name somehow?




Java How do I create a unique object name?

So in regards to my code below, how would I go about creating a unique object every time a user wants to create a new account? For example if user makes an account I would like an object named acc1 then if a user makes another account i would like the object named acc2. Account ac = new Account(input.nextInt(),0,0); This is around where i need it to happen. I tried keeping the code as simplistic as possible and also note I'm rather new to java and this is a personal project just to learn. Help is appreciated thank you.

 System.out.println("Welcome to JAVA Bank");
    System.out.println("____________________");
    System.out.println("Plese Choose an Option: ");
    System.out.println("");
    System.out.println("(1) New Account");
    System.out.println("(2) Enter Existing Account");



    int choice = input.nextInt();


    switch(choice){

        case 1:
            System.out.println("Please choose an Account ID#");
            Account ac = new Account(input.nextInt(),0,0);
            break;




public class Account {

private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
private Date dateCreated;

public Account(int id, double balance, double annualInterestRate) {
    this.id = id;
    this.balance = balance;
    this.annualInterestRate = annualInterestRate;
    this.dateCreated = new Date();

}




Passing C++ vectors of template class by reference

I want to modify one of the functions of an open source C++ library. The function that I want to modify has an interface as the following:

PseudoEcgCalculator (AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>& rMesh,
                      const ChastePoint<SPACE_DIM>& rProbeElectrode,
                      std::string directory,
                      std::string hdf5File,
                      std::string variableName = "V",
                      bool makeAbsolute = true);

I want to overload the function in its second argument such that instead of taking:

const ChastePoint< SPACE_DIM >& rProbeElectrode

it takes vectors of ChastePoint:

std::vector< ChastePoint<SPACE_DIM> >& rProbeElectrodes

After changing it to this, the C++11 compiler in Ubuntu 14.04 LTS complains about this change. How can I correctly modify the function in order to accept vectors of template class ChastePoint<SPACE_DIM>? I tried:

const std::vector< ChastePoint<SPACE_DIM> >&
const std::vector< const ChastePoint<SPACE_DIM> >&

but still bothers the compiler. I pass the following variable, probe_electrodes, as the second argument of PseudoEcgCalculator:

std::vector< ChastePoint<3> > probe_electrodes;
ChastePoint<3> p1( 1.0, 1.2, 1.4 );
ChastePoint<3> p2( 2.0, 3.2, 1.8 );
probe_electrodes.push_back( p1 );
probe_electrodes.push_back( p2 );

Could the community help me on this? Thank you.




How do I enumerate this subclass without getting an Invalid Casting Exception error?

I've been trying to look into making classTwo enumerable but I'm getting an error I don't quite understand as most of the resources I'm looking at have this section of code in them...

public IEnumerator GetEnumerator() {
    return (IEnumerator)this;
}

But I'm getting an error on the return line. Here is the rest of my code...

class classOne {
    public float x;
    public float y;
    public float Z;

    public classOne() {
        x = 0;
        y = 0;
        z = 0;
    }

    public classOne(float X, float Y, float Z) {
        x = X;
        y = Y;
        z = Z;
    }
}
class classTwo {
    public classOne a;
    public classOne b;
    public classOne c;


    public Quantity() {
        a = new classOne();
        b = new classOne();
        c = new classOne();
    }

    public IEnumerator GetEnumerator() {
        return (IEnumerator)this; //Error: InvalidCastException: Cannot cast from source type to destination type.
    }
}




Will subclassing reduce my duplicate code?

My controller is calling my primary class Exercise to get values based on my data model. The data model contains a number of other classes that do calculations and contain data structure objects for the primary class. I feel like I have to do a lot of code duplication such as Exercise.getLastWorkout() which then calls my WorkoutDiary.getLastWorkout() to actually retrieve the workout.

Technically everything works fine, but I feel like I am missing a concept of abstraction. Could subclassing help me by providing inherited functions?

My code is here: http://ift.tt/24aW0QV

A good place to look is here for my controller that I request values from my model: http://ift.tt/1QG1ZQG

And this is the interface to my model: http://ift.tt/24aW0QX

The model calls on a number of other classes to create necessary data structures within it (WorkoutDiary) and perform calculations (PerformanceAnalyzer).

The WorkoutDiary class calls on other classes for relevant data structures as well (Workout, which calls on Set... so the abstraction continues)

Is this a proper design paradigm? I am building this app as a learning experience, so I recognize I am over-engineering such a simple app (tracking workouts). That is my intention. However, I want to get the design principles right.




How do I reference a class made up of classes from a Unity3D monobehaviour?

I have made a class to organize some data, and a class made up of several of those classes so I can use something like...

classA.classB.value = 1;

However I can't figure out how to reference my classes. If anybody knows how I should go about it that would be great!

using UnityEngine;
using System.Collections.Generic;
using System.Collections;

class Gene {
    public string name;
    public float value;
    public float complexity;
    public Gene(string Name, float Value, float Complexity) {
        name = Name;
        value = Value;
        complexity = Complexity;
    }
}

class Genome {
    public Gene agility;
    public Gene intelligence;
    public Gene strength;
    public Genome(Gene Agility, Gene Intelligence, Gene Strength) {
        agility = Agility;
        intelligence = Intelligence;
        strength = Strength;
    }
    public IEnumerator GetEnumerator() {
        return (IEnumerator)this;
    }
}

public class Life : MonoBehaviour {
    Genome genome;      //Warning Life.genome is never assigned to, and will always have its default value null
    Quantity quantity;  //Warning Life.quantity is never assigned to, and will always have its default value null

    void OnEnable() {
        genome = /*???*/;   //How do I add the reference?
        quantity = /*???*/; //How do I add the reference?

        if (!wasInstantiated) {
            genome.agility.name = "Agility"; //On Runtime: NullReferenceException: Object reference not set to an instance of an object
            genome.agility.complexity = 100;

            genome.intelligence.name = "Intelligence";
            genome.intelligence.complexity = 1000;

            genome.strength.name = "Strength";
            genome.strength.complexity = 100;
        }
    }
}




Using functions with blank arguments in JavaScript

I'm doing the code academy JS course, and sometimes I find it confusing to know when to pass arguments into a function, and when to leave it blank.

For example, when creating a new class, I'll use a function with arguments:

function Person (name, age, address, email) {
this.name = name;
this.age = age;
this.address = address;
this.email = email;
} 

var zach = new Person ('Zach', '30', 'Bla Bla', 'email@gmail.com);

but sometimes, I see classes created with blank arguments, such as this:

function StudentReport() {
this.grade1 = 4;
this.grade2 = 2;
this.grade3 = 1;
this.getGPA = function() {
    return (this.grade1 + this.grade2 + this.grade3) / 3;
};
}

How do you know when to use a function that takes arguments, and when to use one that doesn't? My initial thought is that you do this whenever you give a value to your properties (In this case each grade as a numeric value).

Am I right? Thanks




Fzaninotto Faker PHP Fatal Error

I keep getting this error when I am trying to test Faker PHP from github on my server:

Fatal error: Class 'Faker\Provider\en_US\Address' not found in /home/andrew/public_html/JeffWork/src/Faker/Provider/en_US/Address.php on line 6

Link: http://ift.tt/26C2c2Y

All of the package files have been installed and uploaded properly, and the code on line 5 & 6 looks like:

class Address extends \Faker\Provider\en_US\Address
{




When I run the view_inventory function after appending to the list, the appending item doesn't show

class Character(object):

    def __init__(self):
        self.name = ""
        self.inventory = []

    def add_inventory(self, item):
        self.inventory.append(item)

    def view_inventory(self):
        for i in range(len(self.inventory)):
            print "%r. %s" % (i+1, self.inventory[i])


class Hero(Character):

    def __init__(self):
        self.name = ""
        self.inventory = ["Torch", "Wrench", "Laser Cannon"]

Hero().view_inventory()
Hero().add_inventory("Key")
Hero().view_inventory()

I've tested the inventory instance after appending to it with the add_inventory function which shows "Key" as added to the end of the inventory list, however both Hero().view_inventory() print out the same results, without Key included.




Getting no initialisation error in swift class

Hi am new to swift i am string to store user credential in user default from the struct object in a LoginViewController. Below is my code,

class User: NSObject {

//MARK: Properties

var name: String

var email: String

var loginData: LoginData

//MARK: Initialization

init(name: String, email:String, loginData: LoginData) {

    self.name = name

    self.email = email

    self.loginData = loginData
}

}

Here LoginData is a structure

struct LoginData {

var username: String

var password: String

}

while submitting register data am assigning values as
let logindata = LoginData (username: username, password: password)

let v = User(name: nameval, email: emailval, loginData:logindata)

In LoginViewContoller I have a switch button to save user credential to NSUserdefaults I created a var logindataValue: LoginData

And storing in user defaults as follows

    let defaults = NSUserDefaults.standardUserDefaults()

    defaults.setObject(logindataValue.username, forKey: "username")

    defaults.setObject(logindataValue.password, forKey: "password")

    defaults.synchronize()

But in LoginViewController class showing an error as “LoginViewController has no initializers”

How to prevent this error? Is this the right approach to do in this scenario?




Python - Error when calling a class function to analyze an array

I'm using a class that allows me to analyze an array of data that I have and returns it as an array.

Here is the portion of the class that i'm using.

import numpy as np
from scipy.integrate import quad
import matplotlib.pyplot as plt
from scipy import interpolate

class MassFunction:

    def __init__(self, h=0.7, Omega_m=.27, sigma8=.809, n=0.95, rho_c=1.35972365653e11, delta_c=1.686):
        """
        @param h: hubble parameter.
        @param omega_m: current matter fraction of universe.
        @param sigma8: Value of variance of density field with spherical smoothing at 8 Mpc/h
        @param n: spectral scalar index for primordial power spectrum
        @param delta_c: amplitude of perturbation at collapse using linear theory.
        @param rho_c: critical density of universe in Msun/Mpc
        """
        self.h = h
        self.Omega_m = Omega_m
        self.n = n
        self.delta_c = delta_c
        self.rho_m = rho_c*Omega_m/self.h**2
        self.sigma8 = sigma8

    def NofM(self,masses, numbins, boxsize):
        """
        Produce mass function data for N(m). Fractional number density of halos in
        mass range (m,m+dm). Integrates to total number of halos/volume.
        @param masses: list of all masses in Msun/h
        @param numbins: number of bins to use in histogram
        @param boxsize: Size of box in MPc/h.
        @return: [x-axis in log10(mass), y-axis in log10(N(m)), xlabel, ylabel]
        """
        logmasses = np.log10(masses)
        hist, r_array = np.histogram(logmasses, numbins)
        dlogM = r_array[1]-r_array[0]
        x_array = r_array[1:] - .5*dlogM
        dM = 10.**r_array[1:]-10.**r_array[0:numbins] #Mass size of bins in non-log space.
        volume = np.float(boxsize**3) # in MPc^3
        return [x_array, np.log10(hist/volume/dM)]

The rest of the class is much longer, but using the other functions are not necessary in this case.

In my attempts of calling it, I imported it and tried to use it with the array of masses provided.

import matplotlib.pyplot as plt
import numpy as np
import MassFunction

# This is just the array of data 
halomass3 = halos3['GroupMass'] * 1e10 / 0.704 # in units of M_sol h^-1

MassFunction.MassFunction.NofM(halomass3,100, 75000 )

Im returned with this error unbound method NofM() must be called with MassFunction instance as first argument (got ndarray instance instead)

I'm not the most familiar with using classes, or calling classes, since this is my first time using them. Am I suppose to call the __init__ and set up parameters or am I missing something more?

If I have left out any necessary information. Please let me know!




chained class methods overwriting each other when only one is set

I have created chained methods across a set of classes, but when I set values for the last link in the chain, it is overwriting value in what I thought were separate instances within the class chain.

For example:

sub0.one.some.a.time_t.raw = 1

sub0.one.some.b.time_t.raw = 2

But:

print sub0.one.some.a.time_t.raw

returns 2 (not 1, as set above)

print sub0.one.some.b.time_t.raw

returns 2

Code is below. Sub0 is the top level in the chain, Sub4 is the lowest. I add instances of classes as methods within the class by using the type() method.

Why isn't sub0.one.some.a.time_t.raw returning 1, as I've set it? Isn't it a separate instance of all classes in the chain?

class Sub4(object):
    pass

class Sub3(object):
    pass

class Sub2(object):
    pass

class Sub1(object):
    def __init__(self, config):
        self.config_field = config['flag']

class Sub0(object):
    def __init__(self, config):
        self.config = config


sub4_methods = ['raw']
Sub4 = type("Sub4", (Sub4, ), { sub4:None for sub4 in sub4_methods})

sub3_methods = ['time_t']
Sub3 = type("Sub3", (Sub3, ), { sub3:Sub4() for sub3 in sub3_methods})

sub2_methods = ['a', 'b']
Sub2 = type("Sub2", (Sub2, ), { sub2:Sub3() for sub2 in sub2_methods})

sub1_methods = ['all', 'some']
Sub1 = type("Sub1", (Sub1,), { sub1:Sub2() for sub1 in sub1_methods})

configs = {
    "one": { "flag": True },
    "two": { "flag": False },
    }
Sub0 = type("Sub0", (Sub0,), { k:Sub1(v) for (k,v) in zip(configs.keys(), configs.values())})

#create class instance
sub0 = Sub0(configs)

#set values
sub0.one.some.a.time_t.raw = 1
sub0.one.some.b.time_t.raw = 2

#both of these return 1, even though they are set to 1 & 2 respectively
print sub0.one.some.a.time_t.raw
#returns 1

print sub0.one.some.b.time_t.raw
#returns 1

Thanks!




'Class' has no member named 'function'

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

class Stock{

public:
Stock();
void setStock(string, double);
string getSymbol();
double getSharePrice();
void displayStock();

private:
string symbol;
double shareprice;

};

class StockPurchase{

public:
StockPurchase();
void setShares(int);
double getCost();
void displayStockPurchase();
void setStockInfo(string, double, int);
private:
Stock s;
int shares;
double cost;


};

Stock::Stock(){

}

StockPurchase::StockPurchase(){

}

void StockPurchase::setStockInfo(string symb, double pric, int sha){
s.setStock(symb, pric);
s.setShares(sha);

}
void StockPurchase::setShares(int sa){

sa = shares;

}

void StockPurchase::displayStockPurchase(){

s.displayStock();

cout

<< ", the shares to purchase are " 

<< shares 

<< ", and the total cost will be " 

<< getCost() 

<< endl;

}

double StockPurchase::getCost(){

return shares * cost;

}

void Stock::setStock(string ss1, double ss2){

ss1 = symbol;
ss2 = shareprice;

}

string Stock::getSymbol(){

return symbol;

}

double Stock::getSharePrice(){

return shareprice;

}

void Stock::displayStock(){

cout << "The symbol of the stock is " << getSymbol() << ", and the price for                         that symbol is " << getSharePrice() << endl;

}

int main(){

StockPurchase a;
StockPurchase b;
StockPurchase c;

string symbol[3];
double price[3];
int shareamount[3];

for(int x = 0; x < 3; x++){

cout << "Enter the symbol for stock " << x << endl;
cin >> symbol[x];
cout << "Enter the price for stock  " << x << endl;
cin >> price[x];
cout << "Enter the amount of shares you would like for stock " << x << endl;
cin >> shareamount[x];
}

a.setStockInfo(symbol[1], price[1], shareamount[1]);
b.setStockInfo(symbol[2], price[2], shareamount[2]);
c.setStockInfo(symbol[3], price[3], shareamount[3]);


a.displayStockPurchase();
b.displayStockPurchase();
c.displayStockPurchase();

}

Hi, a couple of things, I'm still new to C++.

Firstly, I tried using a default constructor to define my objects in the int main but I got so many errors I made my own function instead. By default constructor I mean the StockPurchase::StockPurchase(), I had so many errors that I've never seen before so I made my own function that essentially did the same thing (this might be the issue?).

The new function I made was simply called setStockInfo, which takes the object Stock s and sets the information taken on by the objects in the main a, b, c.

So far I think its working although I'm sure I'm doing a ton wrong, the only thing that isn't working is trying to call s.setShares(sha).

It gives me this error:

 In member function 'void StockPurchase::setStockInfo(std::string, double,    int)':
 46:3: error: 'class Stock' has no member named 'setShares'

As far as I can tell its being instantiated and called just the same as setStock which is right above it. And I can't figure out what it is I'm doing wrong.




Accessing member function from another class without prior knowledge of the specific member function

I'm trying to call a member function from another class, for example:

class Test1(object): 

    def method1(self, a, b):
        a = a * 2
        print a
        return a + b

    @staticmethod
    def method2(a, b):
         a = a * 2
         print a
         return a + b

    @classmethod
    def method3(cls, a, b):
        return cls.method2(a, b)

Class Test2(object):

      self.result1=Test1.method3()
      self.result1 = self.result1 +1
      self.result2.after(1000,Test1.method3())
      print self.result1
      print self.result2       

Using decorators appears is the proper way, but I'm not sure, please advise me if this is a proper way.




Dynamicly creating a new instance of a class in python?

Do somebody know how to by dynamicly creating a new instance of a class?

For example I have the class User below.

I have just written a part of the methods here.

I would like to launch all the methods of that class in order that it create a new user with new attributes.

class User:
    def __init__(self,title,firstname,surname,age,income,rent,studentloan,
                 consumerloan,mortgageloan,food,debtreimbursement,cloting,hobby,
                 miscellaneous,child,contributionni):
        self.title = title
        self.firstname = firstname
        self.surname = surname
        self.age = age
        self.income = income
        self.rent = rent
        self.stufentloan = studentloan
        self.consumerloan = consumerloan
        self.mortgageloan = mortgageloan
        self.food = food
        self.debtreimbursement = debtreimbursement
        self.clothing = cloting
        self.hobby = hobby
        self.miscellaneous = miscellaneous
        self.child = child
        self.contributionni = contributionni

    def title(self):
        while AssertionError:
            self.title = input("What is your title? : Mr, Mrs, Ms")
            self.title = self.title.capitalize()
            if self.title == 'Mr' or self.title == 'Mrs' or self.title == 'Ms':
                return self.title
                break
        try:
            assert (self.title == 'Mr' or self.title == 'Mrs' or self.title == 'Ms')
        except AssertionError:
            print('You have to choose between Mr, Mrs and Ms.')

    def firstname(self):
        while AssertionError:
            try:
                self.firstname = input("What is your firstname?")
                self.firstname = self.firstname.capitalize()
                assert (self.firstname.isalpha())
                return self.firstname
            except AssertionError:
                print('You have to enter a proper firstname.')




iterating through array to generate instance variables

this is my first post and I'm quite new to programming/this site, so I apologise in advance if I'm doing something wrong/annoying.

I wanted to find a way to define objects without having to do so for each object. I came up with this

class Number
def initialize(name)
@name = name
end

def description
puts "I'm #{@name} "
end
end


a = ["zero", "one","two", "three", "four"]

for i in (0..5) do 
a[i] = Number.new(a[i])
end

a[3].description

I'm hoping someone can tell me what kind of Frankensteins monster I've created? It seems to work, a[3].description returns "I'm three" but does that mean three/a[3] exists as its own object and not an element of an array? furthermore if I try to do

puts a

I get

<Context::Number:0x000000009b7fd0 @name="three">, #

To clarify I just want to know whether I have actually managed to create objects here, and why on earth when I try and access elements of my array I get that weird feedback (kind of seems like its accessing memory or something, but that is alittle beyond me)

My thanks in advance for anyone who replies to this




How to move this code to class/method?

I am doing a web class in programming C#. I want to say right of the bat that I do not want you guys to do my work for me. Now to my specific/generic problem. I am used to writing sequential code. It is when I try to move my working code (s) to classes/methods I get in deep dodo.

The code example below is for a guessing game 1-100. I have tried for four hours straight do break code out in to a separate Class. I manage to get the user input or the RND in to a class. Then the logic in main breaks down. It seems like I get best result if the RND block is Static but user input is not Static etc., etc. In the end I went back to scratch with everything in Main and turn to you for generic guidelines.

I need to get this in my head so I can clean up my Main every time. Start at Class Program Ignore Screen that is working.

<--------Code Below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Uppgift3GissaTalet
{

    static class Screen
    {
        // Screen - Tools that I use every time ignore until end of screen======================================= >

        // Methods for screen handling:
        //
        // Clear Screen  ------------------------------------------
        static public void cls()
        {
            Console.Clear();
        }

        // Set Curser Posittion  ----------------------------------
        static public void cup(int column, int rad)
        {
            Console.SetCursorPosition(column, rad);
        }

        // Key Input --------------------------------------------
        static public ConsoleKeyInfo inKey()
        {
            ConsoleKeyInfo in_key; in_key = Console.ReadKey(); return in_key;
        }

        // String Input -----------------------------------------
        static public string inStr()
        {
            string in_string; in_string = Console.ReadLine(); return in_string;
        }

        // Int Input -------------------------------------------
        static public int inInt()
        {
            int int_in; try { int_in = Int32.Parse(Console.ReadLine()); }
            catch (FormatException) { Console.WriteLine("Input Error \b"); int_in = 0; }
            catch (OverflowException) { Console.WriteLine("Input Owerflow\b"); int_in = 0; }
            return int_in;
        }

        // Float Input -------------------------------------------
        static public float inFloat()
        {
            float float_in; try { float_in = Convert.ToSingle(Console.ReadLine()); }
            catch (FormatException) { Console.WriteLine("Input Error \b"); float_in = 0; }
            catch (OverflowException) { Console.WriteLine("Input Owerflow\b"); float_in = 0; }
            return float_in;
        }

        // Meny ------------------------------------------------
        static public int meny(string rubrik, string m_val1, string m_val2)
        {  // Meny med 2 val ---------------------
            int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menSvar = menyInm();
            return menSvar;
        }

        static public int meny(string rubrik, string m_val1, string m_val2, string m_val3)
        {  // Meny med 3 val ---------------------
            int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menSvar = menyInm();
            return menSvar;
        }

        static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4)
        {  // Meny med 4 val ---------------------
            int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menSvar = menyInm();
            return menSvar;
        }

        static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4, string m_val5)
        {  // Meny med 5 val ---------------------
            int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menyRad(m_val5); menSvar = menyInm();
            return menSvar;
        }

        static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4, string m_val5, string m_val6)
        {  // Meny med 6 val ---------------------
            int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menyRad(m_val5); ; menyRad(m_val6); menSvar = menyInm();
            return menSvar;
        }

        static void menyRubrik(string rubrik)
        {   // Meny rubrik --------
            cls(); Console.WriteLine("\n\t {0}\n----------------------------------------------------\n", rubrik);
        }

        static void menyRad(string menyVal)
        {   // Meny rad    --------
            Console.WriteLine("\t {0}", menyVal);
        }

        static int menyInm()
        { // Meny inmating ------
            int mVal; Console.Write("\n\t Menyval : "); mVal = inInt(); return mVal;
        }

        // Screen - End  <========================================
    } // screen <----

    class Program
    {
        static void Main(string[] args)
        {//Foreign bla bla.

            string rubrik = "\tGissa ett tal mellan 1 och 100: ";
            Random rnd = new Random();
            int slumpTal = rnd.Next(1, 101);
            int svar;
            int count = 0;

            Screen.cls();
            //Console.Write("\t\t" + slumpTal);     //Used for fixing logic.
            Console.WriteLine("\n\t {0}\n\t----------------------------------------------\n", rubrik);
            Console.Write("\tSkriv ditt tal: ");
            svar = Screen.inInt();
            count++;

            //Foreign yadda yadda.
            do
            {
                if (svar < 1 || svar > 100)  //Påminn användaren om att hålla sig inom ramarna.
                {
                    System.Console.Write("\tTalet du söker är inom intervallet 1-100!", svar);
                    Console.Write("\n\tSkriv ditt tal: ");
                    svar = Screen.inInt();
                }

                else if (slumpTal > svar && (slumpTal - svar < 6))  //Getting hotter.
                {
                    System.Console.Write("\tTalet du söker är större än {0} men du är nära nu!", svar);
                    Console.Write("\n\tSkriv ditt tal: ");
                    svar = Screen.inInt();
                    count++;
                }

                else if (slumpTal > svar)  //Ge ledtråd om att användaren måste skriva ett större tal.
                {
                    System.Console.Write("\tTalet du söker är större än {0}.", svar);
                    Console.Write("\n\tSkriv ditt tal: ");
                    svar = Screen.inInt();
                    count++;
                }

                else if (slumpTal < svar && (svar - slumpTal < 6))  //Getting hotter.
                {
                    System.Console.Write("\tTalet du söker är mindre än {0} men du är nära nu!", svar);
                    Console.Write("\n\tSkriv ditt tal: ");
                    svar = Screen.inInt();
                    count++;
                }

                else if (slumpTal < svar)  //Ge ledtråd om att användaren måste skriva ett lägre tal.
                {
                    System.Console.Write("\tTalet du söker är mindre än {0}.", svar);
                    Console.Write("\n\tSkriv ditt tal: ");
                    svar = Screen.inInt();
                    count++;
                }

            } while (svar != slumpTal);

            Screen.cls();
            Console.ForegroundColor = ConsoleColor.Green; //Changing colour(sic!) at win.
            Console.Write("\n\n\t\tBra jobbat, du löste problemet. Rätt svar är {0}!\n\t\tDu tog {1} försök på dig.", slumpTal, count);
            Screen.inKey();

        }//<------------Main
    }//<===========Program
}




Creating Person Class with Objective-C

I'm starting to learn Objective-C and I want to create a simple Person class with name, photo, address (house number, street name, postal code, city), phone.

I'm not sure if I have to use NSArray or NSDictionary for the address attribute. I already created a Person class and I placed my code in Person.h

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *photo;
@property (nonatomic, copy) NSString *address;
@property (nonatomic, copy) NSArray *phone;




LNK2019: Unresolved external symbol error - with member function of class template

I am trying to create a custom List in c++. I've defined it this way:

List.h:

#include "ListItem.h"

#pragma once
template<class T> class List
{
  private:
    ListItem<T>* first;
  public:
    T* GetAt(int);
    ListItem<T>* GetLastListItem();
    void Add(T*);
    void Clear();
};

List.cpp:

#include "stdafx.h"
#include "List.h"

template<class T> T* List<T>::GetAt(int index)
{
    if (!first)
        return 0;

    ListItem<T>* current = first;

    for (int i = 1; i < index; i++)
    {
        current = current->GetNext();
    }

    return current->GetItem();
}

template<class T> L...

main:

List<TestItem> liste;
TestItem ti; //just a int inside.
liste.Add(&ti);

I am getting the following errors:

1>ConsoleApplication1.obj : error LNK2019: unresolved external symbol ""public: void __thiscall List::Add(class TestItem *)" (?Add@?$List@VTestItem@@@@QAEXPAVTestItem@@@Z)" in function"_main".




Cant use class defined inside lib folder in rails app

I have created a class in my lib folder inside my rails app lib/pundit/current_context.rb :

class CurrentContext
  attr_reader :user, :account_asso

  def initialize(user, account_asso)
    @user = user
    @account_asso = account_asso
  end
end

This class is then called in my base_controller :

  def pundit_user
    CurrentContext.new(current_user, account_asso)
  end

I am always getting :

NameError - uninitialized constant Api::V1::BaseController::CurrentContext:

I thought it might be because I am not loading the files inside lib ? so I added config.autoload_paths << Rails.root.join('lib') inside my config/application.rb file :

require File.expand_path('../boot', __FILE__)

require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module QuickBedApi
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de
    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end
    # Do not swallow errors in after_commit/after_rollback callbacks.
    config.active_record.raise_in_transactional_callbacks = true
    config.autoload_paths << Rails.root.join('lib')
  end

end

Unfortunately I am still getting the error. How can I solve that ?




Php tree implementation versus assoc array

I'm trying to build a tree graph from dictionary. So, using the following dictionary 'and','anna','ape','apple', graph should look like this: graph I've tried 2 approaches: using associative array and using self-written tree/node classes.

Note: original dictionary is something about 8 MB and contains >600000 words.

Associative array aproach:

function letter_to_graph ($graph_path,$word,$letter_index) {
    $letter=$word[$letter_index];
    if (!isset($graph_path[$letter])) {
        $graph_path[$letter]=array();
    }
    if ($letter_index == strlen($word)-1) {
        $graph_path[$letter]['.']=array();
    } else {
        letter_to_graph(&$graph_path[$letter],$word,$letter_index+1);
    }
}

function push_word_into_graph ($graph,$word) {
    letter_to_graph(&$graph,$word,0);
}

$words_graph = array();
for ($i=0;$i<count($words);$i++) {
    push_word_into_graph(&$words_graph,strtolower($words[$i]));
    //if ($i % 300 == 0) {echo $i . "_<br/>";} //this is just for testing
}

It takes ~35 seconds to execute, eats up to ~350MB.

Node/tree approach:

class Node
{
    public $_children;

    public function __construct() {
        $this->_children = array();
    }

    public function add_child ($val) {
        if ($this->_children === null)
            $this->_children=array();
        $tmp = new Node();
        $this->_children[$val] = &$tmp;
        return $tmp;
    }
    public function has_child($val) {
        if (isset($this->_children[$val])) {
            return true;
        }
        return false;
    }
    public function get_child($val) {
        //if ($this->has_child($val))
            return $this->_children[$val];
        //else 
            //return false;
    }

}

class Tree
{
    protected $root; 

    public function __construct() {
        $this->root = new Node ();
    }
    public function insert_word ($word) {
        $this->insert_letter_node(&$this->root,$word,0);
    }

    protected function insert_letter_node($node,$word,$letter_index) {
        $letter=$word[$letter_index];
        if (!$node->has_child($letter)) {
            $new_node = $node->add_child ($letter);
        } else {
            $new_node = $node->get_child ($letter);
        }

        if ($letter_index < strlen($word)-1) {
            $this->insert_letter_node(&$new_node,$word,$letter_index+1);
        } else {
            $new_node->add_child('.');
        }
    }
}

$result_tree= new Tree();
for ($i=0;$i<(count($words));$i++) {
    $result_tree->insert_word(strtolower($words[$i]));
    //if ($i % 300 == 0) {echo $i . "_<br/>";}//this is just for testing
}

This one takes ~240 seconds to execute (estimated; actually it stops at half-path due to timeout limit) and eats up to ~550MB while working (so, if there were no timeout, it could've eaten much more).

They both are building correct graphs (second was tested on a part of dictionary), however 2nd approach is ~8 times slower and "eats" at least twice as much memory. Main question is "why the difference is so big?" - they both seem to have identical complexity. And the second question is "how to make it faster/less memory consuming?". Am I using pointers wrong somewhere?

UPD: I've "commented out" the unnecessary has_child check, however it doesn't increase speed significantly.




I have problems stdClass Object json

As I try to get [status] not working return nulled ...

$json_data = json_decode($json_data);

print_r($json_data); // return:
stdClass Object
(
    [status] => failed
    [version] => 0.0.5
)

not working get

    echo $json_data['status']; // return null
echo $json_data->status; // return null




How to generate UML diagram from a table

I have a (single) table that I want to produce UML diagram from. The structure is as follows:

ID|Class|Sub-Class|Sub-Sub-Class|Property1|Property2|Property3...

So is there a way to produce the class diagram from this table?




How to Create Class Attributes By Lopping Over __init__ Arguments?

I was wondering if there was a way to generate class attributes by looping over the arguments of the init method without explicitly referring to a list containing all the arguments of the init method?

In the example below could I loop over hp, image, speed, x, y to create the self arguments ?

class Character(pygame.sprite.Sprite):
    def __init__(self, hp, image, speed, x, y):

        # Call the parent class (Sprite) constructor
        super(Character, self).__init__()

        self.image = image
        self.rect = self.image.get_rect().move(x, y) #initial placement
        self.speed = speed
        self.hp = hp

For example with a loop that would look like that:

class Character(pygame.sprite.Sprite):
    def __init__(self, hp, image, speed, x, y):

        # Call the parent class (Sprite) constructor
        super(Character, self).__init__()

        for arg in arguments:
             self.arg = arg

I am not quite sure how to get the "arguments" to refer to hp, image, speed, x and y ? Or am I stuck with using a list like below ?

class Character(pygame.sprite.Sprite):
    def __init__(self, hp, image, speed, x, y):

        # Call the parent class (Sprite) constructor
        super(Character, self).__init__()

        for arg in [self, hp, image, speed, x, y]:
             self.arg = arg