mercredi 30 septembre 2015

C++ How to print 2D array in a class function

So I am somewhat new to programming in classes, and I am unsure what I'm doing wrong with my code, as I am trying to print a 2 dimensional array but an error comes up when trying to build it. Here it is:

#include <iostream>

using namespace std;

class PlaneSeats
{
private:
    char seatAvailability[7][4];

public:
    PlaneSeats();
    void displayAvailability();
};

PlaneSeats::PlaneSeats()
{
    seatAvailability[7][4] = {{'A', 'B', 'C', 'D'},
                   {'A', 'B', 'C', 'D'},
                   {'A', 'B', 'C', 'D'},
                   {'A', 'B', 'C', 'D'},
                   {'A', 'B', 'C', 'D'},
                   {'A', 'B', 'C', 'D'}};
}

void PlaneSeats::displayAvailability()
{
    cout << row+1 << " ";
    for (int column = 0; column<4; column++)
    {
        cout << seatAvailability[row][column] << " ";
    }
    cout << endl;
}

int main()
{
    PlaneSeats plane;
    plane.displayAvailability();
    return 0;
}

The errors that come up when building are:

'row' was not declared in this scope    line 28

Symbol 'row' could not be resolved    line 28

Symbol 'row' could not be resolved    line 31

Multiple markers at this line    line 23
    - cannot convert '<brace-enclosed initializer list>' to 'char' in assignment
    - extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by
    default]

Been trying to figure out what's wrong and I'm about to punch my computer in xD thanks :)




In Observer Design pattern, are Subject and Observable the same thing?

In Observer design pattern, the observer observes the subject or the observable. It gets notified by their updates. I am confused whether those two things are the same things? Or there is a subtle difference between the two?




Combine two sketches in one project at Processing

First, I made two sketches each, Webcam and Motion Typo.

Then I combined those thing together, It doesn't work.

I can see just Webcam.

I want to make Webcam to be background and motion typo to be added like layers.

What's wrong? and What can I do?

    import processing.video.*;
    Capture cam;
    PImage preFrame;
    float threshold = 50;
    int fc, num = 8000;
    ArrayList ballCollection; 
    boolean save = false;
    float scal, theta;
    PGraphics letter;
    PFont font;
    String l = "福"; 
    void setup() {
      background(0);
      size(800, 600);
      letter = createGraphics(width, height);
      font = createFont("䡡湄楮札䍓ⵆ潮瑳", 700);
      ballCollection = new ArrayList();


       String[] cameras = Capture.list();

      cam = new Capture(this, width, height, 30);
      preFrame = createImage(cam.width, cam.height, RGB);

      cam.start();
    }
    void draw() {
      background(0);
      for (int i=0; i<ballCollection.size (); i++) {
        Ball mb = (Ball) ballCollection.get(i);
        mb.run();
      }  
      theta += .0523;
      if(cam.available() ==true){

        preFrame.copy(cam, 0, 0, cam.width, cam.height, 0, 0, cam.width, cam.height);
        preFrame.updatePixels();

        cam.read();
    }
    loadPixels();
      cam.loadPixels();
      preFrame.loadPixels();
      for(int x = 0; x< cam.width; x++){
        for(int y = 0; y < cam.height; y++){
          int loc = x + y * cam.width;
          color current = cam.pixels[loc];
          color previous = preFrame.pixels[loc];
          float r1 = red(current); float g1 = green(current); float b1 = blue(current);
          float r2 = red(previous); float g2 = green(previous); float b2 = blue(previous);

          float diff = dist(r1, g1, b1, r2, g2, b2);

          if(diff > threshold){
            pixels[loc] = color(198,47,27);
          } else {
            pixels[loc] = color(248,229,191);
          }
        }
      }
      updatePixels();
       createStuff();
    }
    void createStuff() {
      ballCollection.clear();

      letter.beginDraw();
      letter.noStroke();
      letter.background(255);
      letter.fill(0);
      letter.textFont(font, 700);
      letter.textAlign(CENTER);
      letter.text(l, 830, 720);
      letter.endDraw();
      letter.loadPixels();
      for (int i=0; i<num; i++) {
        int x = (int)random(width);
        int y = (int)random(height);
        //color c = letter.get(x, y);
        int c = letter.pixels[x+y*width];
        if (brightness(c)<255) {
          PVector org = new PVector(x, y);
          float radius = random(5, 10);
          PVector loc = new PVector(org.x+radius, org.y);
          float offSet = random(TWO_PI);
          int dir = 1;
          float r = random(1);
          if (r>.5) dir =-1;
          Ball myBall = new Ball(org, loc, radius, dir, offSet);
          ballCollection.add(myBall);
        }
      }
    }
    class Ball {
      PVector org, loc;
      float sz = 2;
      float radius, offSet, a;
      int s, dir, countC, d = 20;
      boolean[] connection = new boolean[num];
      Ball(PVector _org, PVector _loc, float _radius, int _dir, float _offSet) {
        org = _org;
        loc = _loc;
        radius = _radius;
        dir = _dir;
        offSet = _offSet;
      }
      void run() {
        display();
        move();
        lineBetween();
      }
      void move() {
        loc.x = org.x + sin(theta*dir+offSet)*radius;
        loc.y = org.y + cos(theta*dir+offSet)*radius;
      }
      void lineBetween() {
        countC = 1;
        for (int i=0; i<ballCollection.size(); i++) {
          Ball other = (Ball) ballCollection.get(i);
          float distance = loc.dist(other.loc);
          if (distance >0 && distance < d) {
            a = map(countC,0,10,10,255);
            stroke(255, a);
            line(loc.x, loc.y, other.loc.x, other.loc.y);
            connection[i] = true;
          } 
          else {
            connection[i] = false;
          }
        }
        for (int i=0; i<ballCollection.size(); i++) {
          if (connection[i]) countC++;
        }
      }
      void display() {
        noStroke();
        fill(255, 200);
        ellipse(loc.x, loc.y, sz, sz);
      }
    }




Creating an objective c global class

I'm sure I'm just missing something simple here, but can't find the answer though I looked in the other examples here, my code seems to be the same. I'm trying to define a global class with some methods that I can access from the other classes in my project. I can define it, but can not access the methods from my other classes, though I always import the global class header to the class where I want to use the method. Heres the code: 1st The Global class def:

#import <Foundation/Foundation.h>

@interface GlobalMethods : NSObject {}

- (unsigned long long)getMilliSeconds:(NSDate*)d;

- (NSDate *)getDateFromMs:(unsigned long long)ms;

@end

#import "GlobalMethods.h"

@implementation GlobalMethods

//SET DATE TO MILLISECONDS 1970 EPOCH

- (unsigned long long)getMilliSeconds:(NSDate*)d
{
    unsigned long long seconds = [d timeIntervalSince1970];

    unsigned long long milliSeconds = seconds * 1000;


    return milliSeconds;
}

// GET DATE FROM MILLISECONDS 1970 EPOCH

- (NSDate *)getDateFromMs:(unsigned long long)ms
{
    unsigned long long seconds = ms / 1000;
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970: seconds];

    return date;
}


@end

and then where I want to use my methods in another class:

#import "GlobalMethods.h"


// GET MILLISECONDS FROM 1970 FROM THE PICKER DATE
    NSDate *myDate = _requestDatePicker.date;

    milliSeconds = [self getMilliSeconds: myDate];

Error is : No visable interface for viewcontroller declares the selector getMilliSeconds.

Thanks for the help with this.




Need help calling methods in multiple classes

So I have 3 classes that are intertwined and I don't know where I am messing up at. Any advice or help would be appreciated.

First class that I am using is call Customer and has all the getters and setters for typical information for a customer first last name, street address, city, state, zip and phone number.

private String firstName;
private String lastName;
private String streetAddress;
private String city;
private String state;
private String zipCode;
private String phoneNumber;

public Customer() {

}

public Customer(String firstName, String lastName, String streetAddress,
        String city, String state, String zipCode, String phoneNumber) {

    this.firstName = firstName;
    this.lastName = lastName;
    this.streetAddress = streetAddress;
    this.city = city;
    this.state = state;
    this.zipCode = zipCode;
    this.phoneNumber = phoneNumber;

}

public String formatLabel() {

    return firstName + " " + lastName + "\n" + streetAddress + "\n" + city
            + ", " + state + " " + zipCode + "\n" + formatPhoneNumber();
}

public String formatPhoneNumber(){
    return String.valueOf(phoneNumber).replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1)-$2-$3");

}

public String getFirstName() {
    return firstName;
}

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

public String getLastName() {
    return lastName;
}

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

public String getStreetAddress() {
    return streetAddress;
}

public void setStreetAddress(String streetAddress) {
    this.streetAddress = streetAddress;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getZipCode() {
    return zipCode;
}

public void setZipCode(String zipCode) {
    this.zipCode = zipCode;
}

public String getPhoneNumber() {
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}

The second class is where I am calling the method and I am reading the user input. Its my VacationHomeInput class

public class VacationHomeInput {

Scanner scan = new Scanner(System.in);

public void readRentalOrder(){

    VacationHomeRental info = new VacationHomeRental();

    System.out.print("Enter start date in form mm/dd/yyyy: ");
    String rentalDate = scan.nextLine();
    info.setRentalDate(rentalDate);

    System.out.print("Enter number of rental homes: ");
    int numberOfVacationHomesRented = scan.nextInt();
    info.setNumberOfVacationHomesRented(numberOfVacationHomesRented);

    System.out.print("Enter number of days: ");
    int numberOfDaysRented = scan.nextInt();
    info.setNumberOfDaysRented(numberOfDaysRented);

}

public Customer readCustomer(){

    Customer customer = new Customer();

    System.out.print("Enter first Name: ");
    String firstName = scan.nextLine();
    customer.setFirstName(firstName);

    System.out.print("Enter last name: ");
    String lastName = scan.nextLine();
    customer.setLastName(lastName);

    System.out.print("Enter street address:");
    String streetAddress = scan.nextLine();
    customer.setStreetAddress(streetAddress);

    System.out.print("Enter city: ");
    String city = scan.nextLine();
    customer.setCity(city);

    System.out.print("Enter state: ");
    String state = scan.nextLine();
    customer.setState(state);

    System.out.print("Enter zip code: ");
    String zipCode = scan.nextLine();
    customer.setZipCode(zipCode);

    System.out.print("Enter phone number in form 999999999: ");
    String phoneNumber = scan.nextLine();
    customer.setPhoneNumber(phoneNumber);

    return customer = new Customer(firstName, lastName, streetAddress, city, state, zipCode, phoneNumber);

}

After that I have a class that is my main method that will call and create the customer object that will prompt the user to input and display its information below

public static void main(String[] args) {
    VacationHomeOutput output = new VacationHomeOutput();
    Customer hotelInfo = new Customer(null,
            "Holday Resort Vacation Home Rentals", "239 E. Hwy 98",
            "Cocoa Beach", "FL", "32540", "8507291000");

    Customer customer = new Customer();

    output.displayCustomer();
    customer.formatLabel();

    hotelInfo.formatLabel();

}

This is the output:

Customer:
Enter first Name: rem
Enter last name: reyes
Enter street address:123 main
Enter city: normla
Enter state: il
Enter zip code: 60108+
Enter phone number in form 999999999: 6305046204
null null
null
null, null null
null




Java Kryonet Error when sending object

I am using Kryonet for TCP sending of objects, particularly one called TransferMessage:

public static class TransferMessage{String text; String username; Color color = Color.black;}

Now, I know that I have to call kryo.register(TransferMessage.class) but when I attempt to connect to the server with all the classes registered, I get an error:

    Exception in thread "Server" com.esotericsoftware.kryo.KryoException: java.lang.IllegalArgumentException: Class is not registered: java.awt.Color
Note: To register this class use: kryo.register(java.awt.Color.class);
Serialization trace:
color (com.andrewlalisofficial.MessageTypes$TransferMessage)
    at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.write(FieldSerializer.java:585)
    at com.esotericsoftware.kryo.serializers.FieldSerializer.write(FieldSerializer.java:213)
    at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:571)
    at com.esotericsoftware.kryonet.KryoSerialization.write(KryoSerialization.java:50)
    at com.esotericsoftware.kryonet.TcpConnection.send(TcpConnection.java:192)
    at com.esotericsoftware.kryonet.Connection.sendTCP(Connection.java:59)
    at com.esotericsoftware.kryonet.Server.sendToAllTCP(Server.java:435)
    at com.andrewlalisofficial.ChatServer.sendMessage(ChatServer.java:204)
    at com.andrewlalisofficial.ChatServer.checkCommand(ChatServer.java:124)
    at com.andrewlalisofficial.ChatServer$1.received(ChatServer.java:72)
    at com.esotericsoftware.kryonet.Server$1.received(Server.java:61)
    at com.esotericsoftware.kryonet.Connection.notifyReceived(Connection.java:246)
    at com.esotericsoftware.kryonet.Server.update(Server.java:208)
    at com.esotericsoftware.kryonet.Server.run(Server.java:356)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Class is not registered: java.awt.Color

I don't understand because although my registered class uses the Color class, I never before had to register String objects, so I don't see what the difference here is, and how would I fix this error? Thank you in advance for your help.




CSS - Can someone explain what these other classes are?

I'm taking new class, I just started so I don't know much. its about a piece of code in this code that I don't really know what it means?

   table.postForm > tbody input[type="text"], 
input[type="password"], 
table.postForm > tbody textarea {
        color: #888 !important;
        background-color: #333 !important;
        border-color: #303030 !important;
}

td.replyhl{
    color: #555 !important;
    background-color: #333 !important;
    border-color: #303030 !important;
}

.reply, 
hr{
    border-color: #303030 !important;
}

.reply{
    color: #555 !important;
    background-color: #303030 !important;
}

.replytitle, 
.filetitle{
    color: #8B3A3A !important;
}

What I don't understand is what are these classes held together by comas doing??

table.postForm > tbody input[type="text"], 
input[type="password"], 
table.postForm > tbody textarea {
        color: #888 !important;
        background-color: #333 !important;
        border-color: #303030 !important;
}

and this part

.replytitle, 
.filetitle{
    color: #8B3A3A !important;
}




C# Use instantiated class in a different class/file

Am I able to use an instance of once class in another class and file without having to reinstantiate it?

class Start
{
    public static Log Log = new Log(...);
}

class Start1
{
    Log.Write("New instance!");
}

I have read about having to use a get/set block to do it, but I'm not exactly sure how I would go about that,




Assigning a class to a variable

class SimpleTestCase(object):

    def __init__(self, name):
        self.name = name
        self.SP = SP

    def __somemethod(self):
     # do something

class Test(object):
    def __init__(self, name ):
        self.name = name
        self.case = SimpleWidgetTestCase

Is there any reason to do

self.case = SimpleTestCase

instead of

simple_obj = SimpleTestCase("name")

By creating object one can access the class methods and variables. Is the former equivalent to latter?




I have a PHP table that calculates Fahrenheit into Celsius, I need to use Span Class to change color of the Celsius results based on certain criteria

How can I go about doing this? I know I have to use an if statement, but I have tried placing it everywhere and my code just gets messed up.

The criteria is if the value in C is less than or equal to 0, the result should be blue. If it is greater than or equal to 100 C, it's displayed in red. All other temperatures in C should be green.

This is my table code,

<tr>
        <td align="center"><strong>Fahrenheit</strong></td>
        <td align="center"><strong>Celsius</strong></td>
    </tr>

   <?php

   for ($tempFahrenheit = 0; $tempFahrenheit <= 250; $tempFahrenheit++){
   $tempCelsius = (5/9)*($tempFahrenheit-32);
   echo "<tr><td>$tempFahrenheit&degF.</td>";
   echo "<td>$tempCelsius&degC.</td></tr>";   

  }

  ?>




Accessing a PyQT widget outside it's class

a simple situation is proving fairly tricky.

My target is to get a window to update the status of a widget in another window. To explain:

I have window A with some "data" and I want it written into the textEdit widget of window B. The specifics of the main window and the widgets are

class MainWin(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1127, 880)

        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.textEdit = QtGui.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(20, 150, 1081, 661))
        self.textEdit.setObjectName(_fromUtf8("textEdit"))
        self.textEdit.isUndoRedoEnabled ()

What I am currently failing at obtaining is a simple method which called from another window (and another file) could change the content inside the textEdit. Not sure what I am doing wrong, but when I do try to import the class or a method from the class I always seem to have issue with the

TypeError: unbound method updEdit() must be called with MainWin instance as first argument (got nothing instead)

I am very much open to suggestions, and thanks in advance!




Best way of making a class for an object?

I'm trying to create a game. I need a kitten object with a image displayed. I need to use this object within multiple activities so I decided it's probably better using an outside class.

I used something like this. But the function findViewById(int) is not aviable from outside an activity. How to do this?

public class Kitten {
    Context parent;
    View parentView;
    ImageView imgBody, imgHead;

    Kitten(Context context, View view) {
        parent = context;
        parentView = view;

        //Create body & head
        imgBody = new ImageView(parent);
        imgBody.setImageResource(R.mipmap.img_kitty_body_white);
        addImage(imgBody);
        imgHead = new ImageView(parent);
        imgHead.setImageResource(R.mipmap.img_kitty_head_white);
        addImage(imgHead);
    }

    private void addImage(ImageView img) {
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.adoptView);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.BELOW, R.id.adoptView);
        lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        rl.addView(img, lp);
    }
}

The main problem I have, is within the addImage method...




Static Error: This class does not have a static void main method accepting String[].

My code compiles fine but when I go to run it, it gives me the error:

`Static Error: This class does not have a static void main method accepting String[]`

Here is my code:

class Employee{
  private String name; //name reference field
  private int idNumber; //integer variable holding employee's ID number
  private String department; //holds the name of the employees department
  private String position; //holds the name of the employee's position in the department
  //the following is the first required constructor
  //using the terms n,i,d, and p to assign values to the above fields
  public Employee(String n, int i, String d, String p){
    name=n;
    idNumber=i;
    department=d;
    position=p;
  }
  //the following is a constructor that sets the fields blank to be filled in
  public Employee(){
    name="";
    idNumber=0;
    department="";
    position="";
  }
  //writing appropriate accessor and mutator methods for all the fields
  public void setName(String n){ name=n; }
  public void setIdNumber(int i){ idNumber = i; }
  public void setDepartment(String d){ department = d; }
  public void setPosition(String p){ position = p; }
  public String getName(){ return name; }
  public int getIdNumber(){ return idNumber; }
  public String getDepartment(){ return department; }
  public String getPosition(){ return position; }
}
//new program creating employee objects
public class EmployeeInfo 
{
  public static void main(String[] args)
  {
    //create an Employee object
    Employee employee1 = new Employee("Susan Meyers", 47899, "Accounting", "Vice President");
    //test the accessor methods
    System.out.println("***employee1***");
    System.out.println("Name: " + employee1.getName());
    System.out.println("ID number: " + employee1.getIdNumber());
    System.out.println("Department: " + employee1.getDepartment());
    System.out.println("Position: " + employee1.getPosition());
    //create another Employee object
    Employee employee2 = new Employee();
    //test the mutator methods
    employee2.setName("Mark Jones");
    employee2.setIdNumber(39119);
    employee2.setDepartment("IT");
    employee2.setPosition("Programmer");
    System.out.println("\n***employee2***");
    System.out.println("Name: " + employee2.getName());
    System.out.println("ID number: " + employee2.getIdNumber());
    System.out.println("Department: " + employee2.getDepartment());
    System.out.println("Position: " + employee2.getPosition());
    //create another Employee object
    Employee employee3 = new Employee();
    //test the mutator methods
    employee2.setName("Joy Rogers");
    employee2.setIdNumber(81774);
    employee2.setDepartment("Manufacturing");
    employee2.setPosition("Engineer");
    System.out.println("\n***employee3***");
    System.out.println("Name: " + employee3.getName());
    System.out.println("ID number: " + employee3.getIdNumber());
    System.out.println("Department: " + employee3.getDepartment());
    System.out.println("Position: " + employee3.getPosition());
  }
}

I know I need to add the "public static void main(String[] args)" command somewhere but i'm not sure where! Thank you for any help you can give!




Constructor with unknown argument

I have recently started to do some programming in C#, after spending most of my life in PHP.

In PHP I could do this:

class User
{
    public __construct($UserId)
    {
        // Do stuff
    }
}

class Employee extends User
{
    public __construct($EmployeeId)
    {
        // Look up the UserId connected to $EmployeeId
        $UserId = hypothetical_get_user_id_func($EmployeeId);
        parent::__construct($UserId);
    }
}

But, in C# I don't seem to have that possibility, since it seems like I must know the $UserId before it enters the first constructor.

public class User
{
    public User(int UserId)
    {
        // Do stuff
    }
}

public class Employee : User
{
    public Employee(int EmployeeId) : base(***) // I don't know this value yet?
    {
        // This is where I would find the User Id, and would like to pass
        // it to the User class constructor.
    }
}

Is there any way to achieve what I am trying to do here in C#?

Basically passing a value to the constructor of the main object, which in its own body figures out what value to pass to the base class.




How to manage variables for multiple objects

I am trying to assign properties to each object. I cannot modify the FileSystemUsage class of Sigar library, so i had to make another class to manage the propoerties.

The function where i am generating the objects is the following

private String getDiskUsage() {
    try {
        List<FileSystem> result = new ArrayList<FileSystem>();
        org.hyperic.sigar.FileSystem[] fss = null;
        fss = sig.getFileSystemList();
        List<Integer> diskUsage = new ArrayList<Integer>();
        String ioStat = "";
        DiskMembers diskm = new DiskMembers();
        for (int i = 0; i<fss.length; i++) {
            FileSystem fs = fss[i];
            if (fs.getType()==2) {
                FileSystemUsage usage = sig.getFileSystemUsage(fs.getDirName());                    
                if (diskm.getlastDiskCheck(i - 1) != 0) {
                    long diff = (nanoTime() - diskm.getlastDiskCheck(i - 1)) / 1000000;
                    long diffRead = usage.getDiskReadBytes() - diskm.getLastDiskRead(i - 1);
                    long diffWrite = usage.getDiskWriteBytes() - diskm.getlastDiskWrite(i - 1);
                    ioStat = String.format("(%d/%d kB/s)", diffRead / diff, diffWrite / diff);
                }
                diskm.setLastDiskRead(i, usage.getDiskReadBytes());
                diskm.setlastDiskWrite(i, usage.getDiskWriteBytes());
                diskm.setlastDiskCheck(i, nanoTime());
                diskUsage.add((int) (usage.getUsePercent() * 100));
            }
        }
        return String.format("%d%% %s", (Collections.max(diskUsage)), ioStat);

    } catch (SigarException e) {
        e.printStackTrace();
    }
    return "n/a";
}

The class that i made for managing the properties for each object is the following

class DiskMembers{
private long[] lastDiskCheck = new long[5];
private long[] lastDiskRead = new long[5];
private long[] lastDiskWrite = new long[5];

public DiskMembers(){
    this.lastDiskCheck[0] = 0;
    this.lastDiskRead[0] = 0;
    this.lastDiskWrite[0] = 0;
}
public boolean setLastDiskRead(int i, long value){
    this.lastDiskRead[i] = value;
    return true;
}
public boolean setlastDiskCheck(int i,long value){
    this.lastDiskCheck[i] = value;
    return true;
}
public boolean setlastDiskWrite(int i,long value){
    this.lastDiskWrite[i] = value;
    return true;
}
public long getLastDiskRead(int i){
    if (i==-1)
        return this.lastDiskRead[0];
    return this.lastDiskRead[i];
}
public long getlastDiskCheck(int i){
    if (i==-1)
            return this.lastDiskCheck[0];
    return this.lastDiskCheck[i];
}
public long getlastDiskWrite(int i){
    if (i==-1)
        return this.lastDiskWrite[0];
    return this.lastDiskWrite[i];
}
}    

The problem is i can't manage to keep properties separate for each object. I mean when object usage is generated i check the lastDickCheck variable by calling diskm.getlastDiskCheck(i-1). The first time it won't execute this section of code because the return value is zero(0). But after that i will execute it every time even for the different object as long as they array is. I want to keep record of "lastdiskcheck" for each object "usage", for each (disk).

If i update lastDiskCheck variable for disk C: It picks it up for the disk D as well, which i don't what.

How can i do that?




Passing a Mongo collection as an argument

I am currently working on a Meteor application where I want to pass a Mongo collection to a ECMAScript 6 class. I want to do this to be able to write a model layer as a class. I know this example of Astronomy works:

Posts = new Mongo.Collection('posts');

Post = Astro.Class({
  name: 'Post',
  collection: Posts
});

An Astronomy class has access to it's collection to save and delete stuff. I want to do the same, but with ECMAScript 6 classes, like this:

var Animals = new Mongo.Collection("animals");

class Animal extends ScubaModel {
  constructor(name) {
    super();
    this.name = name;
  }
}
Animal.collection = Animals;

This, however, results in an error: RangeError: Maximum call stack size exceeded. I know this error is often encountered when trying to do recursive stuff, but I am not doing anything recursive here. It seems to be the size of the Mongo collection that is the problem.

What I tried:

I tried some other stuff, for example, using the prototype like this:

Animal.prototype.collection = Animals;

This results in the same error. I also tried setting the collection in the constructor like this:

class Animal extends ScubaModel {
  constructor(name) {
    super();
    this.collection = Animals;
    this.name = name;
  }
}

This also results in the same error. Then I tried passing it in an array like Astronomy does:

super({collection: Animals});

This also fails. I also tried to create a method in my parent class to set the collection.

class ScubaModel {
  set collection(collection){
    this.collection = collection;
  }
}

Off course, this also fails.

My questions:

  1. Why can Astro.Class() have a collection as an argument, where a 'normal' class fails?
  2. Is there a way to pass my collection to my parent class?
  3. Should I get this idea out of my mind and just keep track of a collection of my collection as a global variable so I can access it from my parent class?



r data frame columns as different classes

I have the following issue. I would like to know how I can assign rows containing information of different columns (the data in the columns is in different classes - factor, integer, logical) to a data frame without some of the fields being indexed, but to get the value of them. Now when I assign it to the data frame some of the columns contain the values that I need in char format, while the others are just indexes referring to values.

data[i,2:ncol(data)] <- listing[listing$ID == subset$ID[agrep(matchstring, subset$Street, max.distance = 3)], ]




Declaring type in array?

I'd like to create a class instance within an array declaration. How is that done?

Something similar to the following:

myclassA.myarray = [ClassB() {name="Cleaning", deptId=12}, ClassB() {name="Repairs", deptId=30]

Where the array type is:

class ClassB : NSObject {
  var name:String?
  var deptId:Int?
}




How to get a list of classes that are used in Jquery

In order for me to refactor the css I need to extract all classes used in the jQuery scripts in order to separate classes that are used for styling and classes used for events. Any advice would be much appreciated.




c++ Calling a different class method with a for loop

im trying to call a different class method using the [i].display(); function the error im getting i as follows: no operator "[]" matches these operands

Here is my relevant code: Main.cpp:

 for (int i = 0; i < n; i++){
    char date_description[7];
    double high = 0.0, low = 0.0;
    cout << "Enter Date :";
    cin.getline(date_description, 80, '\n');
    cout << "Enter High :";
    cin >> high;
    cout << "Enter Low :";
    cin >> low;
    cin.ignore();
    weather.set(date_description, low, high);

  }
  cout << endl;
  cout << "Weather report:\n";
  cout << "======================" << endl;

  for (int i = 0; i < n; i++){
      weather[i].display();
  }

Weather.cpp

void Weather::set(const char* date_description, double low , double high) {
        strcpy(date, date_description);
        highTemp = high;
        lowTemp = low;

    }

    void Weather::display() const {

    }

Any idea why my weather[i].display(); is throwing an error? I didnt code my disply() implementation yet.




Making two sqares with :before class

I'm trying to make two squares before my headings. I know how to make a single square with the before class, but I dont know how to make two that isn't the same width.

What I'm going for is something that looks like this:

What I'm going for

I hope somebody is able to help me!




Can't use string ("Server1") as a SCALAR ref while "strict refs" in use

#!/usr/bin/perl -w
use strict;
use warnings;

use Class::Struct;

struct System => {
  Name => '$',
};

my $system = new System;
$system->Name("Server1");

my $strout1 = qq{Server is ${$system->Name}\n};
my $strout2 = "Server is \"".$system->Name."\"\n";

print $strout1;
print $strout2;

results in: Can't use string ("Server1") as a SCALAR ref while "strict refs" in use at test.pl line 14.

I want to be able to use qq and deref $system->Name correctly can anyone explain where i am going wrong?




Implementing this Abstract Class using a declaration

I'm implementing the Automatak opendnp3 libraries for c++. I want to add a Master to a Channel.As you can see from this definition, a parameter for this action is:

...
opendnp3::IMasterApplication& appliction,
...

The IMasterApplication interface is described here. So I create masterApplication.cpp and masterApplication.h files and attempt to implement the class as follows:

masterApplication.cpp

 #include "masterApplication.h"

 #include <opendnp3/master/IMasterApplication.h>

 #include <iostream>
 #include <chrono>

 using namespace opendnp3;
 using namespace asiodnp3;
 using namespace std;

 masterApplication::masterApplication() {
    }

 masterApplication::~masterApplication() {
    }

masterApplication.h

#ifndef MASTERAPPLICATION_H_
#define MASTERAPPLICATION_H_

 #include <opendnp3/master/IMasterApplication.h>
 #include <opendnp3/link/ILinkListener.h>
 #include <openpal/executor/IUTCTimeSource.h>

 class masterApplication : public opendnp3::IMasterApplication
 {
 private:

 public:
    masterApplication();
    virtual ~masterApplication();
 };

 #endif

But, when I try to declare a masterApplication object in my main to use:

masterApplication iMaster;

And then place that within the AddMaster function, I get the error:

main.cpp:57:20: error: cannot declare variable ‘iMaster’ to be of abstract type ‘masterApplication’
   masterApplication iMaster;

What am I misunderstanding here?




Dynamic Gallery to show download and progress bar in as3

My flash project has specific task to show the dynamic gallery items based on the xml list and there is a download option is available for each gallery item.

For this i made a movieclip (imageTile) with Thumbnail,Title,Progressbar & ProgressText. See the image link

http://ift.tt/1QKW0vV

and two classes named Main.as and FileRef.as

Main.as codes

        var tileMap:Dictionary = new Dictionary();
        public var tile:ImageTile;

        addChild(wall);
        wallWidth = wall.width;
        wallHeight = wall.height;
        var columns:Number;
        var my_x:Number;
        var my_y:Number;
        var my_thumb_width:Number;
        var my_thumb_height:Number;
        var images:XMLList;
        var total:Number;
        var swipe:Number = 0;

        var myXMLLoader:URLLoader = new URLLoader();
        myXMLLoader.load(new URLRequest("gallery.xml"));
        myXMLLoader.addEventListener(Event.COMPLETE, processXML);

    function processXML(e:Event):void {
        myXML = new XML(e.target.data);

        images = myXML.IMAGE;
        total = images.length();


        myXMLLoader.removeEventListener(Event.COMPLETE, processXML);
        myXMLLoader = null;


        var loader:Loader;
        for (var i:uint = 0; i < total; i++) {
        tile = new ImageTile();
        wall.addChild(tile);

        tile.x = i % 3 * 400 + 180;
        tile.y = Math.floor(i / 3) * 650 + 250;

        var imageName:String = images[i].@FULL;
        path = images[i].@Path;
        var title:String = images[i].@Title;
        **var caption:TextField = tile.getChildByName("caption_tf") as TextField;**
        caption.text = title;
        tile.addEventListener(MouseEvent.CLICK, onTileClick(path));
        loader = new Loader();
        loader.load(new URLRequest("images/" + imageName));
        tileMap[loader] = tile;
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoad);
    }
//trace(myXML);
}


    var tileMap:Dictionary = new Dictionary();


function onImageLoad(e:Event):void {
    var loader:Loader = e.target.loader;
    var tile:ImageTile = tileMap[loader] as ImageTile;
    var image:Bitmap = loader.content as Bitmap;
    image.x = -100;
    image.y = -100;
    image.width=366;
    image.height=418;
    var textField:DisplayObject = tile.getChildByName("caption_tf");
    var textFieldDepth:int = tile.getChildIndex(textField);
    tile.addChildAt(image, textFieldDepth);
    tileMap[loader] = null;
    image.smoothing = true;
}


function onTileClick(url:String):Function {
     return function(me:MouseEvent):void {          

        path = url;
        var download:FileRef = new FileRef();
         download.downloadFile(path);
}

FileRef.as code

public var mc_loaded   : MovieClip = Main.gameInstance.tile.getChildByName("mc_loaded") as MovieClip,
           mc_progress : MovieClip = Main.gameInstance.tile.getChildByName("mc_progress") as MovieClip,
           txt_prog    : TextField = Main.gameInstance.tile.getChildByName("txt_prog") as TextField;

public function downloadFile(url:String) : void
        {
   /// Download the gallery item codes using url
}

public function progressHandler( event : ProgressEvent ) : void
        {       
            //mc_loaded.scaleX = (event.bytesLoaded / event.bytesTotal) ;
        }

        public function completeHandler( event : Event ) : void
        {
            //reset progress bar after download is finished
            mc_loaded.scaleX = 0;  // I want to use the imageTile element
            txt_prog.text = "download finished";
        }

        public function OnZipComplete(evt:flash.events.Event):void
        {
         txt_prog.text = "download finished";
        }

Download works fine, but i could not get the progress bar and progress text for every tile created.

Thanks in advance




How to use variables for each object

I have an array of elements. I am making object on the basis of each elements name and call some getter functions. The object of the class that i am making is actually a third party library, "Sigar".

The problem is i don't want to modify this third party library, because of which i am not able to keep variables values separate for each object. I need come up with some way to keep separate variable separate for each object.

I hope my description explains what i want. Following is my code

private long lastDiskCheck = 0;
private long lastDiskRead = 0;
private long lastDiskWrite = 0;
private String getDiskUsage() {
    try {
        List<FileSystem> result = new ArrayList<FileSystem>();
        org.hyperic.sigar.FileSystem[] fss = null;
        fss = sig.getFileSystemList();
        List<Integer> diskUsage = new ArrayList<Integer>();
        String ioStat = "";
        for (int i = 0; i<fss.length; i++) {
            FileSystem fs = fss[i];
            FileSystemUsage usage = sig.getFileSystemUsage(fs.getDirName());
            if (lastDiskCheck!=0) {
                long diff = (nanoTime() - lastDiskCheck)/1000000;
                long diffRead = usage.getDiskReadBytes() - lastDiskRead;
                long diffWrite = usage.getDiskWriteBytes() - lastDiskWrite;
                ioStat = String.format("(%d/%d kB/s)", diffRead/diff, diffWrite / diff);
            }
            lastDiskRead = usage.getDiskReadBytes();
            lastDiskWrite = usage.getDiskWriteBytes();
            lastDiskCheck = nanoTime();
            diskUsage.add((int)(usage.getUsePercent()*100));
        }
        return String.format("%d%% %s", (Collections.max(diskUsage)), ioStat);
    } catch (SigarException e) {
        e.printStackTrace();
    }
    return "n/a";
}

the three variables

private long lastDiskCheck = 0;
private long lastDiskRead = 0;
private long lastDiskWrite = 0;

updates for each object inside the loop which i don't want. How can i keep it different for each object?




Set new size of dynamic array from an external function/class?

My main code declares a pointer that needs to be resized from an external function. Ex:

double *vect =NULL;
classobj object;

object.func(vect);

//--- print the outcome
for(int j=0; j<4; ++j)
   cout << vect[j] << " .. " << endl;

where function func() is part of classobj defined in an another file (say classobj.h and .cpp) as

void classobj::func(double *_vect){

  _vect  = new double[4];

  for(int j=0; j<4; ++j)
    _vect[j] = 3.0*j +1 ;

};

The problem is that vect has not been resized. I get segmentation fault. Any idea please on how to use pointers in this case?




Better way to call Function multiple times

Sorry about this silly curiosity,

In OOP such as C# and Java if I create a class to do all string manipulation I know it is better to make all the function static, but when I need to call those functions multiple times which one is better (using less resource):

  1. Creating an object one time only and call the function using that object.

    StringManipulation sm = new StringManipulation(); 
    sm.reverse("something");
    sm.addPadding("something");
    sm.addPeriod("something");
    
    

or

  1. Calling the class directly everytime

    StringManipulation.reverse("something");
    StringManipulation.addPadding("something");
    StringManipulation.addPeriod("something");
    
    



Single Catch Block for Multiple Methods in a Class java

I have a class with static Methods for Handling MemCache Requests, it has different methods with different arguments.

Whenever Some method is called in that class,i want to increment totalRequest Counter and if Exception occur in any of the methods inside the class i want to increment a failed counter. Is there any way to do it ?

If being Static in Nature has some problems, let me know ? Also It should be a efficient.




Initializing private member variables of a class

I apologize in advance because some of my verbiage may not be 100% correct.

I will have a class like this:

class ClassName {
private:
    AnotherClass class2;
public:
  ClassName();
  ~ClassName();
...

In the constructor of this class, among other things, I put the line

ClassName::ClassName() {
    AnotherClass class2; 
}

Which is how I thought you were supposed to initialize objects in C++, however I was noticing (through GDB) that two AnotherClass objects were being created. Once on the Constructor definition then again on my initialization line. What is the reasoning behind this? What if I wanted to use a more complicated constructor like AnotherClass(int a, int b), would it create a temporary object then create the correct one shortly after?




Why is the System class declared as "final" in Java?

As per my understanding, a class is declared as final to prevent it from being extended/inherited. So I see there can be security and probably some performance gains in this regard.

But is there a very specific design decision behind this? Say for eg: to realize some kind of design pattern? I did go around a similar thread here! but the answer was not really what I was looking for




mardi 29 septembre 2015

Create a class diagram based on the following description:

Create a class diagram based on the following description: In the modern world, many retail stores and even residential properties install video monitoring systems. A customer, who has a unique address, can choose to have one or more video monitoring system. Each video monitoring consists of a set of components namely: video archive, video display, and video capture. Video archive stores video data according to a storage path either locally or through FTP. The video store operation will be different in each case. The video capture has a unique vendor with unique factory address and its main operation is to capture video. The video capture can be associated with any number of cameras. Any camera will have a status attribute to define if it online or offline and it should stream the video buffer to the video capture component. There are two types of cameras: IP camera or an analog camera. The stream video buffer operation will depend on the type of the camera. Moreover, if the camera is an analog camera then it will contain one encoder component inside it to encode raw video data from the camera sensor. Finally, the customer is able to retrieve the video data only from local archive in the current system through the date and time parameters using a retrieve video operation




Using 2 classes for a Comission Calculator in Java

I am doing an assignment for a beginning Java class. We have to write a commission calculator and use two classes in it. I am stuck on how to use variables from one class in a second class. The methods that i have found so far are not working for me. Any advice would be greatly helpful. Below is the code i have so far.

package calc;

/**
 *
 * @author Ethan
 */
import java.util.Scanner;

public class Calc {

    public static void main(String[] args) {
        
 Scanner calcu = new Scanner(System.in); //Creats the scanner used for Input
  //Sets all of the variables to be used
 double sal; //salary
  double com1; //Comission percentage
  double com2; // Find the ammount of comisssion from yearly sales
  double comp; //Yearly Sales
  double frac; //Decimal Comission form
  double total; // Total of Compensation of Yearly salary + Comission
          
    System.out.println("Enter the annual Salary here: ");
    sal = calcu.nextDouble();
    
    System.out.println("Enter the total Sales here: ");
    comp = calcu.nextDouble();
    
   Rate();
frac = com1/100; //converts the Sales Comission to a decimal
 com2 = frac * comp; // Find the total Comission based on the 
  total = sal + com2; //find the total compensation
  
  System.out.print("Your total compensation is " + total);
    
    }
private static void Rate(){
     // Rate of commission is determined below.
        if (comp < 10000)
           com1 = 20;            //20% commission rate
        else if (comp < 30000)
           com1 = 22;             // 22% commission rate
        else if (comp < 50000)
           com1 = 23;            // 23% commission rate
        else if (comp < 100000)
           com1 = 24;            // 24% commission rate
        else
           com1 = 25;            // 25% commission rate
    
}
    
}

The problem i have is the i can't pull the rates so they can be used in the calculations.




How to avoid library jquery conflicts [duplicate]

This question already has an answer here:

I.m using these script files in same page

jquery/1.10.2/jquery.min.js

js/jquery.js

to use colorbox popup 1.10.2/jquery.min.js is necessary for me. But it creates conflict. How to avoid these conflict. or any other solutions.




Loading information from file in different ways

My program currently has this working:

        Bank bank = new Bank();

        bank.openAccount(new CheckingAccount(10100, new Customer("First", "Last"),500.00,false));
        bank.openAccount(new CheckingAccount(10101, new Customer("First", "Last"),2000.00,true));
        bank.openAccount(new SavingsAccount(2010, new Customer("First", "Last"),5000.00,0.02));

Now I am trying to load this information from a file instead, but I ran into a bit of a wall. I want the new Customer information to include both the first and last name which are stored in separate index positions as separate variables, but while this will work:

        new Customer[FIRST_INDEX], 

I can't seem to get it to accept two index positions without creating a new Customer again. This is turn is causing issue with the method in Accounts where I'd like to keep the same format. How can I go about doing this?

    public CheckingAccount(int accountNumber, Customer owner, double currentBalance, boolean freeChecks) 
{
    super(accountNumber, owner, currentBalance);
    this.freeChecks = freeChecks;
}

Another problem I am running into is that the last index position can be one of two variables depending on if I am dealing with a checking account or a savings account:

private final static int FREE_CHECKS_INDEX = 4; // This loads a boolean
private final static int INTEREST_INDEX = 4;    // This loads a double

Given this, I'm not entirely sure if my above approach would even work at all. The program is supposed to load either a Checking Account or Savings Account object, but since both types of accounts are stored in the same file I am wondering if I could read the last index position of each line of the text file before creating the object, but I'm not really sure how to go about doing that.

To be clear, I have this problem working perfectly without loading the data from the file, I am just unsure about the best approach for adapting it without having to rewrite all my other classes. Here's the new thing I am trying to do which I know isn't right:

    protected static void loadAccountInformationFromFile() throws Exception 
    {
        try ( Scanner fin = new Scanner(new File(INPUT_CUSTOMER_FILE)) ) 
            {
                String record;
                String[] fields;


                while ( fin.hasNext() ) 
                    {
                        record = fin.nextLine();

                        fields = record.split(",");

                        Bank bank = new Bank();

                        bank.openAccount
                            (
                                new CheckingAccount(Integer.parseInt(accountNumber[ACCOUNT_NUMBER_INDEX]), 
                                new Customer[FIRST_INDEX, LAST_INDEX], 
                                currentBalance[BALANCE_INDEX], 
                                freeChecks[FREE_CHECKS_INDEX]
                                )
                            );
                    }
            } catch (Exception e) 
                {
                    throw e;    
                } // end try
        } 




Facebook PHP SDK 5: Extending classes

I created a .php file to use Graph API and after a lot of work I can get but access to protected data. When I try to manipulate the response is: Fatal error: Cannot access protected property Facebook\FacebookResponse::$body.

Code:

<?php
/* some code */
$datos = $facebook->get('/' . $idfanpage . '/albums?fields=name,id', $access_token);
/* code to manipulate */
?>

Response:

object(Facebook\GraphNodes\GraphNodeFactory)#10 (2) {
  ["response":protected]=>
  object(Facebook\FacebookResponse)#11 (6) {
    ["httpStatusCode":protected]=>
    int(200)
    ["headers":protected]=>
    array(14) {
      ...
    }
    ["body":protected]=>
    string(842) "{"data":[{"name":"Timeline Photos","id":"...

Tried several methods, tutorials, related questions without a result that works well for my purposes.

I found this answer that suggests to extend the class, this way:

class myClass extends FieldCollectionItemEntity {
  function accessParentProtectedVars($var){
    return $this->hostEntity->$var;
  }
  //other member functions
}

I'm newbie with classes (worse with namespaces, etc.) so I know must create the FacebookMyClass.php class where the main classes are (autoload.php, Facebook.php, FacebookApp.php, etc.), then my prototype:

<?php
// I guess
namespace Facebook;

// Do I must 'use' or extending other class(es)?
// use ;

class FacebookMyClass extends Facebook {

   // Do I have to "re-declare" parent's vars?
  private $my_private_var;
  public $my_public_var;
  private $access_token;

  // The main thing, I think, is how class is constructed

  // public function __construct(array $config = []) {
  public function __construct($id, $secret) {
    // This will work? Need parameters?
      parent::__construct();
  }

  public function accessParentProtectedVars($idfanpage) {
    // How can I call/link to Facebook object/request/response?
    $object = $this->get('/' . $idfanpage . '/albums?fields=name,id', $this->access_token);
  }

  private function getTokens($params = []) {
    // code...
    $this->access_token = '...';
  }

}
?>

The question is: How can I extend Facebook\Facebook class(es)?




Processing + ControlP5 Library - Constructor Not Updating

I have 3 Classes, each with a method to create either a Textfield, Button or Textlabel. I have set up my program so that a Textfield prompts you for a name, which is then stored in the name1 String variable. I also use a Textlabel that has it's setText(name1), but when I run it, it is saying NullPointer. I did LOTS of testing and found that the problem lies in the constructor, since I believe the constructor does its thing at the beginning, and even if the variable name1 changes, it does not "update" or re-construct. How would I go about this?

The class:

public class Textlabel {
  int x;
  int y;
  String name;
  String text;
  int txtColor;
  int txtSize;
  String group;

 Textlabel(int _x, int _y, String _name, String _text, int _txtColor, int _txtSize, String _group) {
    x = _x;
    y = _y;
   name = _name;
   text = _text;
   txtColor = _txtColor;
   txtSize = _txtSize;
   group = _group;
 }
}

Corresponding function to actually draw the Textlabel:

void createTextLabel(int num) {
  cp5.addTextlabel(tl[num].name)
   .setFont(createFont("TradeGothic-Bold", tl[num].txtSize))
    .setColor(tl[num].txtColor)
     .setText(tl[num].text)
      .setPosition(tl[num].x, tl[num].y)
        .setGroup(tl[num].group);
}

The constructor:

String name1;

Textlabel tl[] = {
new Textlabel(255, 271, "Contact 1 Text", name1, #ffffff, 37, "g4"), 

 };

Another part of the code is for the Textfield and then controlEvent to store the text from Textfield into name1. Problem is that the constructor does its thing, so even if I in setup() do createTextLabel(0); or I wait until once the user inputted text, and then create it, it still does not update, I tested it by when I declare name1, giving it a value too, and it always showed the value.

Any help is appreciated! Thanks!




Java program to display numbers between two ranges using command line arguement [duplicate]

This question already has an answer here:

//Program to display prime numbers between 2 range using command line argument

class prime
{
    public static void main(String args[])
{
    if(args.length!=2)
    {
        System.out.println("Enter both starting & ending limit, only 2");
        System.exit(0);
    }
int num=Integer.parseInt(args[0]);
int num1=Integer.parseInt(args[0]);
int count;
if (count<=1)
{
    System.out.println("Prime numbers starts from 2");
    System.exit(0);
}
for(int i=num; i<num1; i++)
{
    count=0;
    for(int j=2;j<=i/2;j++)
    {
        count++;
        break;
    }
if(count==0)
System.out.print(i);
}
}
}

This is the error:

javac prime.java
prime.java:15: error: variable count might not have been initialized
if (count<=1)

But I have initialised it already. Any help? I am new to SO




student detail for number f students in c++ using class

I want to create a class.In class itself, I want to define a method called read().
In that, I have to use name, age, ph.no as a local variable.In same class i want to create a another method disp().In that, i have to display the name,age,ph.no for all students.

In main class,There should be only object creation and function call.I want to do as simple as possible.

Main problem is:

  1. I have to use name,age,ph.no`` as a local variable in getdisplay and have to use same variable in disp().
  2. Where i have to use for loop for getting number of students.
`#include #include class stu { void read( ) { char name[20],add[20]; int age,phno; cout<<”Enter the student Name”; cin>>name; cout<<”Enter the age “; cin>>age; cout<<”Enter the ph.no”; cin>>phno; } void disp( ) { cout<<”Student Name :”<



Simple java student record program [duplicate]

This question already has an answer here:

Can anyone help me to solve me this error?

I am a java beginner.I was executing this code and I got the error:cannot find symbol id.input();

anyone please explain me how to fix this and why is it so.

==============================

import java.util.*; class Student { public static class Record { int reg_no; String name; }

public Record ob;

public Scanner in=new Scanner(System.in);

public void Input()
{
    System.out.println("Enter the details"+ "\n"+"\t"+"1.Register Number"+"\n"+"\t"+"2.Name");

    ob.reg_no=in.nextInt();
    ob.name=in.nextLine();

}

}

class StudentRecord {

public static void main(String args[])
{
    System.out.println("\t"+"---------Student record----------");
    System.out.println("-------------------------------------------------------");

    Student id=new Student();
    id.input();
}

}




Creating a custom class and using it as an object/list

I've created a custom class called Person. Now I want to use the person class the same way you can with a String or int class, by turning them into a table when I create a variable with the person class.

Person[] persons = new Person[3];

But when I do it like this, I get the error: NullPointerException. Is there any way to fix it, so I can use the person class as a list?

This is my person class:

class Person{
  //Definerer navn og posisjonen.
  String navn;
  String[] interesser = new String[4];

  //Funksjonen for aa sette navn.
  void settNavn(String navn){
    this.navn = navn;
  }

  //Funksjonen for aa sette interesser.
  void settInteresser(String interesser, int index){
    this.interesser[index] = interesser;
  }

  //Funksjonen for aa hente navnet.
  String hentNavn(){
    return navn;
  }

  //Funksjonen for aa hente interessene.
  String hentInteresser(int index){
    return interesser[index];
  }
}




C# How to Call static method from subclass

I have this code:

class Super{ 
   public static List<Super> methodA() { . . . }
}
class Sub:Super{ 
   public static List<Sub> methodA() { . . . }
}

Then I call :

 Sub.methodA();

But the executed is from super class. Anyway I can exec the subclass's static method? They has same static method name.

Update: enter image description here You can see that Product is my superclass and purchase is subclass. Both has same static getAll() but returned different type. In this case it returns the List




Standard method to image upload in php

Upload image:

how can i upload image in php in best effective manner eg say class or may be even better method than class. my requirements from module: upload the image to folder and saving its path to db must have image crop functionality for different sizes must delete image from folder after deleting image. something like that thanks




readonly class not really read only

I have my simple class definition as follow:

public class class1 { public int a; }

private class1 _myclass;
//define a public readonly class
public class1 myclass {
  get { return _myclass; }
  //set { _myclass = value; }
}

and in my code the following line is not accepted:

myclass = new myclass(); //class is read only

however I can still write the following:

myclass.a = 2; //i can edit readonly class element

I want to prevent this and make elements of my readonly class unavailable.




I am a beginner in java please help me to write the code of following program

Write class to represent patient and doctor , store information of three patient under each doctor and also display detail of patient under each doctor.




Getting the number of elements with .length is inaccurate?

I have a page on the admin side of a website I'm working on. This page is for adding images to a product listing. I use jQuery to count the number of thumnails on the page (which is equal to the number of pictures assigned to the product) and when there are 5, it removes the button to add more pictures. This should effectively limit the number of images allowed to be uploaded to 5.

The "add picture" menu has three categories. You can use an URL, use an image you've previously uploaded, or upload a new image.

The only time I'm leaving the page is to upload a new image. When a new image is uploaded a form is submitted and the page resets. For some reason, jQuery is not registering the new image on the reload.

This is located near the top of the script. This script is in an external JS file that is included just before the closing body tag:

var pictureCount = $(".thumbnail-container").length;
if (pictureCount == 5) {
    $("#add-picture").hide();
} else {
    $("#add-picture").show();
}

This is the function that is called anytime an previously uploaded image is added, or an image is added from an URL. (I also use this same function to reduce the picture count when a thumbnail is removed):

var removeAddButton = function(operator) {
    if (operator == "+") {
        pictureCount++;
    } else if (operator == "-") {
        pictureCount--;
    }
    if (pictureCount == 5) {
        $("#add-picture").hide();
    } else {
        $("#add-picture").show();
    }
};

Each thumbnail has a picture, and a button which removed the thumbnail located in a div with a class of thumbnail-container. By defining the variable as the number of elements with the class of thumbnail-container when the pages refreshed (When a picture is uploaded and the POST goes through) the page should load knowing how many pictures are there.

However, after I upload an image the count is still 0. If I upload another image, it is 1. I have confirmed this with an alert and a console log. Strangely, if I run the first snippet, but cage it in a window.onload anonymous function, the page knows the count on the reload. However, when I wrap the snippet in window.onload, the second snippet doesn't affect the count when the function is called.

Why is this? How can I fix the issue?

P.S.

When the new image is uploaded, PHP takes care of adding the new thumbnail to the page. Since PHP gets finished before the JS starts, it should know the count.




How to declare a TooN Vecor/Matrix of dynamic size as c++ class member?

Am using TooN c++ library. I tried something like

  TooN::Matrix<> mat

or

 TooN::Matrix<TooN::Dynamic> mat

But neither works... Any idea please?




WTForms-prepopulate a textarea field with a string value?

I'm trying to pepopulate a wtforms-textareafield with a value.

I defined a class:

class Contact(Form):
     description = TextAreaField('Description:', default="please add content")

In template i did this:

<div class="form-group">
      {{ contact.description.label(class_="control-label col-xs-3") }}
       <div class="col-xs-6">
           {{ contact.description(class_="form-control")}}  
       </div>
</div> 

But the default text is not displayed,it's blank. I also tried to add value on template:

{{ contact.description(class_="form-control" ,value="please type content")}}

But no result. Can somebody help me? Thanks in advance.




lundi 28 septembre 2015

Python: Dictionary: Based on the key provided return an initialized class object variable

I'm new to learning python.

I'm in a situation where I have many classes, e. g.:

class A:
    def __init__(self, entry):
        ...

    def printf(self)
        print "A"

class B:
    def __init__(self, entry):
        ...

    def printf(self)
        print "B"

class C:
    def __init__(self, entry):
        ...

    def printf(self)
        print "C"

Next, what I wish to do is to have a dictionary, like this:

OBJECT_LIBRARY = {'A': A(), 'B': B(), 'C': C()}

So, when I refer to the dictionary with a 'KEY' the dictionary should return an initialized object of that type.

How can I achieve this?




C#: is it possible to subset list of custom class objects based on a parameter of these objects? (without LINQ)

What I am trying to achieve in C# without using LINQ is to subset a list of custom-class objects based on the value of one of the parameters of these objects.

Let's say the declaration of my list is the following:

List<MyCustom> listofobj = new List<MyCustom>();

Also, assume that the custom-class object "MyCustom" can return two parameters: MyCustom.name and MyCustom.age

Is there a way trough which I can retrieve and save into a temporary new list (let's call it "templist") the subset of the original list (i.e. "listofobj") formed by all its MyCustom objects that have "age" parameter greater than 30? Thanks!




Changing Buttons From Different Panels

I need help figuring out how to change Button b2 in MyJPanel2. I cannot make any changes to MyJPanel2.

  • p1 (the variable representing myJPanel1) needs to manipulate a button located in p2 (the variable representing myJPanel2).
  • In order to do this, p1 (the variable representing myJPanel1) needs to receive p2 (the variable representing myJPanel2).
  • Which object/class can have access to both myJPanel1 and myJPanel2?
  • This will be the best place to send an object (information) to another is using the new statement and sending parameters in.

I have everything working except I do not know how to reach b2 within MyJPanel2 from MyJPanel1.

public class MyJFrame extends JFrame
{
    public MyJFrame ()
    {
        super ("Name - Assignment 05");

        MyJPanel mjp = new MyJPanel();

        getContentPane().add(mjp,"Center");


        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize (640, 480);
        setVisible(true);
    }
}
--------------
public class MyJPanel extends JPanel
{;

    public MyJPanel()
    {
        super();
        setBackground(Color.gray);

        setLayout(new GridLayout(2, 1));

        MyJPanel1 p1 = new MyJPanel1();
        MyJPanel2 p2 = new MyJPanel2();

        add(p1,"North");
        add(p2,"Center");
    }
}
----------------
public class MyJPanel1 extends JPanel implements ActionListener
{
    JButton jl1, j2, b2;
    Student st1;

    public MyJPanel1()
    {
        super();
        setBackground(Color.yellow);

        st1 = new Student("Bill","Gates",56);
        // the whatsUp of this student has to shown in the other panel

        jl1 = new JButton(st1.getInfo());
        jl1.addActionListener(this);
        add(jl1);

        b2 = new JButton(st1.whatsUp());
        add(b2);
    }
    //=====================================
    public void actionPerformed(ActionEvent event) {
        Object obj = event.getSource();
        //=====================================
        if (obj == jl1) {
            String b = st1.whatsUp();
            b2.setText("               " + b + "               ");
        }
    }
}
-----------------
public class MyJPanel2 extends JPanel
{
    //==================================================
    //no changes allowed in myJPanel2 for assignment 05
    //==================================================
    JButton b1,b2,b3,b4;

    public MyJPanel2()
    {
        super();
        setBackground(Color.pink);
        //setLayout(new GridLayout(5,1));
        b1 = new JButton("When the user clicks on the button in the UPPER panel" );
        add(b1);

        b2 = new JButton("Display here whatsUp from the student in UPPER Panel" );
        add(b2);

        b3 = new JButton("===>>>>You CANNOT create a student here <======" );
        add(b3);

        b4 = new JButton("It has to be the student from the UPPER Panel" );
        add(b4);
    }
}




Combine two sketches in one project at Processing

First, I made two sketches each, Webcam and Motion Typo.

Then I combined those thing together, It doesn't work.

I can see just Webcam.

I want to make Webcam to be background and motion typo to be added like layers.

What's wrong? and What can I do???

    import processing.video.*;
    Capture cam;
    PImage preFrame;
    float threshold = 50;
    int fc, num = 8000;
    ArrayList ballCollection; 
    boolean save = false;
    float scal, theta;
    PGraphics letter;
    PFont font;
    String l = "福"; 
    void setup() {
      background(0);
      size(800, 600);
      letter = createGraphics(width, height);
      font = createFont("䡡湄楮札䍓ⵆ潮瑳", 700);
      ballCollection = new ArrayList();


       String[] cameras = Capture.list();

      cam = new Capture(this, width, height, 30);
      preFrame = createImage(cam.width, cam.height, RGB);

      cam.start();
    }
    void draw() {
      background(0);
      for (int i=0; i<ballCollection.size (); i++) {
        Ball mb = (Ball) ballCollection.get(i);
        mb.run();
      }  
      theta += .0523;
      if(cam.available() ==true){

        preFrame.copy(cam, 0, 0, cam.width, cam.height, 0, 0, cam.width, cam.height);
        preFrame.updatePixels();

        cam.read();
    }
    loadPixels();
      cam.loadPixels();
      preFrame.loadPixels();
      for(int x = 0; x< cam.width; x++){
        for(int y = 0; y < cam.height; y++){
          int loc = x + y * cam.width;
          color current = cam.pixels[loc];
          color previous = preFrame.pixels[loc];
          float r1 = red(current); float g1 = green(current); float b1 = blue(current);
          float r2 = red(previous); float g2 = green(previous); float b2 = blue(previous);

          float diff = dist(r1, g1, b1, r2, g2, b2);

          if(diff > threshold){
            pixels[loc] = color(198,47,27);
          } else {
            pixels[loc] = color(248,229,191);
          }
        }
      }
      updatePixels();
       createStuff();
    }
    void createStuff() {
      ballCollection.clear();

      letter.beginDraw();
      letter.noStroke();
      letter.background(255);
      letter.fill(0);
      letter.textFont(font, 700);
      letter.textAlign(CENTER);
      letter.text(l, 830, 720);
      letter.endDraw();
      letter.loadPixels();
      for (int i=0; i<num; i++) {
        int x = (int)random(width);
        int y = (int)random(height);
        //color c = letter.get(x, y);
        int c = letter.pixels[x+y*width];
        if (brightness(c)<255) {
          PVector org = new PVector(x, y);
          float radius = random(5, 10);
          PVector loc = new PVector(org.x+radius, org.y);
          float offSet = random(TWO_PI);
          int dir = 1;
          float r = random(1);
          if (r>.5) dir =-1;
          Ball myBall = new Ball(org, loc, radius, dir, offSet);
          ballCollection.add(myBall);
        }
      }
    }
    class Ball {
      PVector org, loc;
      float sz = 2;
      float radius, offSet, a;
      int s, dir, countC, d = 20;
      boolean[] connection = new boolean[num];
      Ball(PVector _org, PVector _loc, float _radius, int _dir, float _offSet) {
        org = _org;
        loc = _loc;
        radius = _radius;
        dir = _dir;
        offSet = _offSet;
      }
      void run() {
        display();
        move();
        lineBetween();
      }
      void move() {
        loc.x = org.x + sin(theta*dir+offSet)*radius;
        loc.y = org.y + cos(theta*dir+offSet)*radius;
      }
      void lineBetween() {
        countC = 1;
        for (int i=0; i<ballCollection.size(); i++) {
          Ball other = (Ball) ballCollection.get(i);
          float distance = loc.dist(other.loc);
          if (distance >0 && distance < d) {
            a = map(countC,0,10,10,255);
            stroke(255, a);
            line(loc.x, loc.y, other.loc.x, other.loc.y);
            connection[i] = true;
          } 
          else {
            connection[i] = false;
          }
        }
        for (int i=0; i<ballCollection.size(); i++) {
          if (connection[i]) countC++;
        }
      }
      void display() {
        noStroke();
        fill(255, 200);
        ellipse(loc.x, loc.y, sz, sz);
      }
    }




How to declare two variables and run each separately through a method? (java)

So for an assignment I have to create an application whose main() method holds two variables. After declaring the variables and assigning an integer to each of them, I have to run both through the same 3 methods. I was thinking that I have to create a class for the variables, but honestly have no idea where to begin. So far, I have figured out how to run one of the integers through the methods, but I can't get both to pass through the same methods. Here is my work so far:

public class ArithmeticMethods{
    public class integer
    {
    int firstInteger = 10;
    int secondInteger = 20;
    }
    public static void main(String[] args) {
        displayNumberPlus10();
        displayNumberPlus100();
        displayNumberPlus1000();
        System.out.println(firstInteger + " +" + " 10" + " is " + displayNumberPlus10());
        System.out.println(firstInteger + " +" + " 100" + " is " + displayNumberPlus100());
        System.out.println(firstInteger + " +" + " 1000" + " is " + displayNumberPlus1000());
    }
     public static int displayNumberPlus10() {
        int numberPlus10;
        numberPlus10 = (firstInteger + 10);
        return numberPlus10;
    }
    public static int displayNumberPlus100() {
        int numberPlus100;
        numberPlus100 = (firstInteger + 100);
        return numberPlus100;
    }
    public static int displayNumberPlus1000() {
        int numberPlus1000;
        numberPlus1000 = (firstInteger + 1000);
        return numberPlus1000;
    }
}

Right now the methods are set to only run the first variable and with my ATTEMPT at creating a class, the program doesn't work at all. Any advice would be greatly appreciated. Also I apologize if the code looks ugly. I am very new to this.




static class members and switches

I got a little problem, I get an error "C2361: initialization of identifier is skipped by 'default' label" due to the following:

I use an intern class member to set the chosen approach used in my methods. The methods use this intern member (static int) with a switch to determine wich approach was set. The switch need an intial value when compiling, so I decided to use a static const int. However, VS is still unhappy, and I can't change the static const int aswell. I am pretty sure this ain't a big deal, but it's quite frustrating.

example:

class test{
    public:
    static int Val;
    static void setVal(int val);
    static int doStuff(void);
};

test::setVal(int val){
    Val=val;
}

test::doStuff(){
    switch(Val){
    case 1:
    // do stuff
    case 2:
    // do other stuff
    default:
    // do default
    }
}

Many thanks for any tipps or solutions




How to wrap another class (c++)

I'm trying to learn to c++ after programming in other OO languages for many years.

I'm trying to create a wrapper class for another class, but having a hard time figuring out how to set this up properly.

For instance, with the following...

main.cpp

#include "foo.cpp"
#include <iostream>

int main() {
  Foo foo(42);
  std::cout << foo.get_barx() << std::endl; 
  return 0;
}

foo.cpp

#include "bar.cpp"

class Foo {
  public:
    // I'm trying to declare the member variable `m_bar` here.  I
    //   don't want to be instantiating an instance of Bar yet,
    //   but I think that might be exactly what's happening.
    Bar m_bar;

    Foo(int y) {
      // Here's where I really want to instantiate an instance of Bar
      //   and assign it to m_bar.
      Bar m_bar(y*2);
    }   

    int get_barx() {
      return m_bar.getx();
    }   
};

bar.cpp

class Bar {
  public:
    int m_x;

    // I seem to need this default constructor for the declaration
    //   of `m_bar` above, but I don't think that line should be 
    //   calling any constructors.
    Bar() { m_x = 21; };

    Bar(int x) {
      m_x = x;
    }   

    int getx() {
      return m_x;
    }   
};

When I compile and run this, I get back 21, but I expect 84. I'm pretty sure I'm doing something fundamentally wrong, and I'm pretty sure it's got something to do with how I'm declaring the m_bar member variable in Foo, but I can't figure out what the right way is to accomplish this.




A class that accepts two different data types in Java?

I want to make a class that can accept two different data types for each parameter. How can this be accomplished?

I realize the code below doesn't work, but how can I make something like that work? Basically so that parameter can be an int or String or something similar?

Example:

public Combat(int attack || String attack, int defence || String defence) {
        //code to parse strings into ints

    }




Using an external object inside a class declaration - PHP

So let's say I have two PHP classes : User & Connection.

What they do is obvious from their names.

Now suppose I have this code:

User.php

<?php

class User {

    static function get_email( $user_id ) {
        $conn_object = new Connection();
        $connection  = $conn_object->connection;
        // do stuff with the connection object
    }

}

?>

Connection.php

<?php

class Connection {

    public $connection;

    public function __construct() {
        $this->connection = // connect to the database here
    }

}

?>

main.php

<?php

require "Connection.php";
require "User.php";

$email = User::get_email( 4 ); // this doesn't work

?>

When I do something like that in main.php, I get a bunch of errors. When I var_dump( $conn_object ); in the User.php file, I always get a null, like the file doesn't even "see" the Connection object, or know it exists.

However, when I use the Connection class in main.php directly, I don't get any errors and everything runs smoothly. This means my Connection object doesn't have any syntax errors or otherwise.

Is this kind of thing not allowed to be done in PHP? Does the language not allow the usage of a class in a class? This is super weird behavior.

Any help would be greatly appreciated.

Thank you!

P.S: Please ignore any syntax errors I made in this question, as I know that syntax is not a problem in my code. Thanks again.




Zend Framework 2 - Instantiating Class

Why do I have to provide the leading backslash when providing the path to a class? [\Zend\Validator\EmailAddress() and not just Zend\Validator\EmailAddress()]

$validator = new \Zend\Validator\EmailAddress();

$email = "example@example.com";

if ($validator->isValid($email)) { // email appears to be valid } else { // email is invalid; print the reasons foreach ($validator->getMessages() as $messageId => $message) { echo "Validation failure '$messageId': $message\n"; } }

Thanks!




allocating four object arrays with one 'new'

I have a class with four dynamic arrays like this:

CObjA * objAArray;
CObjB * objBArray;
CObjC * objCArray;
CObjD * objDArray;

and I initialize those like this:

objAArray = new CObjA[numObj];
objBArray = new CObjB[numObj];
objCArray = new CObjC[numObj];
objDArray = new CObjD[numObj];

The problem is that those four memory allocations take a long time - performance is very bad if I have to create 40'000 objects like this.

my question is: is there a way to allocate all four arrays with one new operation?

If I create a new struct:

struct _arrays
{
 CObjA objA;
 CObjB objB;
 CObjC objC;
 CObjD objD;
};

and use one array of that struct instead, I only have to use one new:

_arrays * arr = new _arrays[numObj];

But then the objects are not laid out in memory correctly. They're then in memory as CObjA1-CObjB1-CObjC1-CObjD1-CObjA2-CObjB2.... instead of first all CObjA objects, then all CObjB objects, ...

Is there a way to use one new but still get the correct memory layout of the objects?




How to include one java file into another java file both having the main functions in it?

I want to include one java file into another. Both have the main functions in it. One file looks similar to the following:

public class FileShow
{

 public static void main(String args[])
  {

        JFrame guiFrame = new JFrame();

        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);

        //make sure the program exits when the frame closes
        guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guiFrame.setTitle("RTL Parser GUI");
        guiFrame.setSize(500,500);

        //This will center the JFrame in the middle of the screen
        guiFrame.setLocationRelativeTo(null);

        JPanel comboPanel = new JPanel();
        JTextField handle = new JTextField(30);
        comboPanel.add(handle);

    guiFrame.add(comboPanel);
    guiFrame.setVisible(true);
  }
}

whereas my other java file is:

public class AnotherFile{

    public static void main(String[] args) {

        new AnotherFile();
    }

    public AnotherFile()
    {
        guiFrame = new JFrame();

        //make sure the program exits when the frame closes
        guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guiFrame.setTitle("Assertion-Based GUI");
        guiFrame.setSize(500,500);

        //This will center the JFrame in the middle of the screen
        guiFrame.setLocationRelativeTo(null);

    JPanel comboPanel = new JPanel();
        JTextField handle = new JTextField(30);
        comboPanel.add(handle);

    guiFrame.add(comboPanel);
    guiFrame.setVisible(true);
    }
}

Is there any way to combine both the files and run together, since both have the main functions in it? How do i combine both the files in same java file and run both of them together?

Please help!




Very simple Angular directive using restrict to 'C' not working

I'm doing a very simple directive, this is the app.js code

var myApp = angular.module('magnisWebApp', [])

myApp.directive('layoutTop', function() {
    return {
        restrict: 'C',
        templateUrl: 'templates/layout__top.template.html'
    }
})

This is the template to load:

<div class="layout__top">
    <div class="top__left">
        Some kind of content
    </div>
</div>

And thi, is the html code...

<!DOCTYPE html>
<html lang="en" ng-app="myApp" ng-strict-di>
    <head>
        <meta charset="UTF-8">
    </head>
    <body ng-controller="MainCtrl">
        <div class="layout__wrapper">
            <!-- TOPBAR GOES HERE -->
            <div class="layout"></div>
        </div>
        <script type="text/javascript" src="bower_components/angular/angular.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
    </body>
</html>

When I try using restric to A or E it works, but not with class. Why?




ruby - test calling methods in same class with explicit receiver

I am staring my journey with Ruby. Let's get straigth to the point. I am going throught "path to enlightenment" and I have a little problem. The code is:

 def my_method_in_the_same_class(a, b) #m1
    a * b
  end

  def test_calling_methods_in_same_class_with_explicit_receiver #m2
    assert_equal __, self.my_method_in_the_same_class(3,4)
  end

My job is to fill the "__" field (what is equality for self.my_method...). When I try to define those things in Ruby and call m2 by just putting "m2" in IRB I get "NoMethodError: private method `my_method_in_the_same_class' called for main:Object". That's strange, because the correct answer is 12 and I don't know why I get this error.

That's first time when I call for help and feel really ashamed. Still - I can just type 12 and go on, but I guess that's not the point of learning.

Regards.




Implementing concordance with a linked list

Im getting some build errors and it would be great if someone could help me out to try and fix these errors. This program take a text file and writes out the frequency of the words in the file. It will then list out the words and how many times they are used. The program is supposed to limit the number of characters to 8 when it checks the words. Thanks for taking a look at this.

the error im getting is: main.cpp|47|error: no matching function for call to 'List::ins(char*&, int&)'|

Main.cpp

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include "List.h"

using namespace std;

void wrd_list(ifstream&, char word_list[]);// Gathers the words from the text file and displays it.
//@param ifstream&: file stream to read input file
//@param char[]: stores the words from file stream

void read_input(ifstream&, char arr[]);// Processes all the characters from the text file. Removes any non alpha characters
//@param ifstream&: file stream to read input file
//@param char[]: stores the characters from file stream

int main()
{

    char file_name[30];
    Word arr;
    ifstream file_in;

    cout << "Enter a file to open: ";
    cin >> file_name;

    file_in.open(file_name);

    wrd_list(file_in, arr);

    file_in.close();




    return 0;
}

void wrd_list(ifstream& file_in, char (&word_list) [MAX + 1]){

    List l;
    int counter = 0;

    while(!file_in.eof()){

        read_input(file_in, word_list);
        l.ins(word_list, counter);
    }
cout << l;
}

void read_input(ifstream& file_in, char (&arr) [MAX + 1]){

    char chr;

    int i = 0;

    while(isalpha(chr) && !isspace(chr)){

        if( i > MAX - 1){
            while(!isspace(chr)){
                file_in.get(chr);
                break;
            }
        }

        chr = tolower(chr);
        arr[i] = chr;
        ++i;
        file_in.get(chr);
    }

    for( int j = 0; j < i; j++){

            cout << arr[j];
    }

    cout << endl;
}

List.h

#ifndef LIST_H
#define LIST_H
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstddef>

using namespace std;


const int MAX = 8;
typedef char Word[MAX+1];


class List {

private:

    //Node struct
    struct Node{
        Word wrd;
        Node* next;
        int freq;
    };

    Node *first;


    //Private function

    Node* get_node (Word& entry, int& freq, Node* link);

public:
    // type def
    typedef char Word[MAX + 1]; // What can go in a list



    // Constructor taking initial value:
    List() { first = NULL; } //In Line

    // DESTRUCTOR
    ~List();

    // Insert function. Adds a node to the list
    void ins( Word& wrd, int& n);


    // Remove function. Removes a node from the list.
    void remove ( const Word& target);


    // Calculate number of nodes in the list.
    int sizeOfList() const;


    //Returns the length of the invoking concordance
    int get_count(Word& word);


    // FRIEND FUNCTION

    friend ostream& operator << (ostream& out_s, const List& l);


};

#endif // LIST_H 

List.cpp

#include "List.h"
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
//Default constructor is in line.


//Destructor
List::~List(){

Node  *temp;
    while(first != NULL){
        temp = first;
        first = first -> next;
        delete temp;
    }
}

void List::ins( Word& entry, int& n){

    Node *prev;

    if (first == NULL || strcmp(first -> wrd, entry), entry > 0){
        first = get_node(entry, n, first);
    }else{

        prev = first;

        while (prev -> next != NULL && strcmp(prev -> next -> wrd, entry) > 0){
            prev = prev -> next;
        }
        prev -> next = get_node(entry, n, prev -> next);
    }
}

void List::remove (const Word& target){

    Node *temp;
    Node * prev;

    prev = first;

    if ( prev -> wrd == target ) {
        first = first -> next;
        delete prev;
    }else{

        while ( strcmp(prev -> next -> wrd, target) > 0){
            prev = prev -> next;
        }
        temp = prev -> next;
        prev -> next = temp -> next;
        delete temp;
    }
}

int List::sizeOfList() const {

    Node *cursor;
    int counter;

    counter = 0;

    for (cursor = first; cursor != NULL; cursor = cursor -> next){
        ++counter;
    }
    return counter;
}

int List::get_count(Word& word){

    while(strcmp(first -> wrd, word) != 0)
            first = first -> next;

        return first -> freq;
}

ostream& operator << (ostream& out_s, const List& l){

    List::Node *cursor;

    out_s << "Word" << setw(10) << " " << "Frequency" << endl;
    out_s << "--------------------" << endl;


    for ( cursor = l.first; cursor != NULL && cursor -> next != NULL; cursor = cursor -> next){
        out_s << cursor -> wrd << setw(10) << " " << cursor -> freq << endl;
    }

    if(cursor != NULL){
        out_s << cursor -> wrd << setw(10) << " " << cursor -> freq << endl;
    }

    out_s << "--------------------" << endl;

    return out_s;
}

List::Node* List::get_node(Word& entry, int& freq, Node* link){

    Node* temp;

    temp = new Node;
    strcpy(temp -> wrd, entry);
    temp -> next = link;
    temp -> freq = freq + 1;
    return temp;

}




whats wrong with this wrapper class with for loop

public static void main(String args[])
{
    Calculation C=new Calculation();
    int i;
    for(i=5;i>=0;i--)
    {
         C.m[i]=Integer.valueOf(args[i]);        
         //assignment of command line arguments with the array//        
    }
    C.display();
}

this gives error of "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5" with the input of command line arguments as 10 20 30 40 50 60 Please help me




about class GC, how many conditions they must meet

public class Test{
    public static void main(String... args){
        Test test = new Test();
        Class testClass = Test.class;
    }
}

As i know, if jvm want to GC Test class, it must meet below conditions:

  1. all instances of Test have already GC'ed.

  2. Test's class loader has GC'ed.

  3. Test cannot be reflected at anywhere(i am not sure about this condition)

so, my question are,

  1. does jvm need testClass object GC'ed or testClass GC after Test GC'ed?

  2. what situation class loader will be GC'ed

  3. explain more about condition 3

  4. does it enough of conditions which listed?




How to deriving generic class from base generic class?

I Have a base abstract generic class

public abstract class A<T> where T: Control
{
    protected T _t { get; set; }

    protected abstract void Method ();

    protected A(T t)
    {
        _t = t;
    }
}

B class derived from A with type TreeView

public class B<T>: A<TreeView>
{
    protected override void Method ()
    {
        _t.CallSomeTreeViewMethod (); // ok!
    }

    public B (TreeView tree): base (tree)
    {

    }
} 

How to derived from B class with type whose derived from TreeView?

public class C: B<ExtendedTreeView>
{
    protected override void Method ()
    {
        _t.CallSomeExtendedTreeViewMethod ();
    }

    public C (ExtendedTreeView tree): base (tree)
    {

    }
}




python - treating an int like a class and giving it properties

I want to give an int a function eg

def x.converttostring(): return str(self)

x = 1
print x.converttostring()
>>> '1'
print x
>>> 1

ideally i want to have it operating on select ints, not all ints eg

x.converttostring()
>>> '1'
y.converttostring()
<error - no such function>

is it possible? (please excuse psuedo code)




Share information between classes, Reference variables

I have a little problem with share/reference the same information between classes, without duplicating values. I don't know how to resolve this in a good approach.

Class TestA {
     List<Double> listDouble;
     Double double1;
     Double double2;
}

Class TestB {
     Double sumList;
     Double sumDouble;
     Double sumOtherCase;

     Double otherCase1;
     Double otherCase2;
}
...
Class TestX {
     Double sumList; //another instance of 'TestA' different of the instance in 'TestB'
}

I have the classes 'TestA' and 'TestB' with values for example:

TestA.listDouble= new ArrayList<>();
TestA.listDouble.add(10d);
TestA.listDouble.add(20d);
TestA.double1 = 10d;
TestA.double2 = 20d;
TestB.otherCase1 = 10d;
TestB.otherCase2 = 20d;

I want to refence this values with class 'TestB', for when I change the values in 'TestA' or 'TestB' the values sums in 'TestB' change too. For what when I get TestB.sumList, TestB.sumDouble or TestB.sumOtherCase the values are updated.

Someone could help me? Sorry my English. Thank you!!




Python AttributeError: class object has no attribute

When I try to run the code of a class I'm writing, I get an AttributeError and I'm not sure why. The specific error is as follows:

    self.marker = self.markers[marker[1:]]
AttributeError: 'TTYFigureData' object has no attribute 'markers'

Here is part of the class I'm writing:

class TTYFigureData(object):
    """
    data container of TTYFigure
    """
    def __init__(
        self,
        x,                      # x values
        y,                      # y values
        marker          = "_.", # datum marker
        plot_slope      = True
        ):
        self.x          = x
        self.y          = y
        self.plot_slope = plot_slope
        self.set_marker(marker)
        self.markers = {
            "-" : u"None" ,
            "," : u"\u2219"
        }

    def set_marker(
        self,
        marker
        ):
        if marker in [None, "None", u"None", ""]:
            self.plot_slope = True
            self.marker = ""
        elif marker[0] == "_":
            self.marker = self.markers[marker[1:]]
        else:
            self.marker = marker

Where am I going wrong?




Sending a class to the main class from a class

My code is currently set to have 3 class files, main and tradeShip. tradeShip has recieved another class file, playerShip. in the tradeShip code, I need to send playerShip back to main. The code is as follows:

public class tradeShip() {
  public void sell(playerShip player) {
    //unimportant code
    main.saveGame(player);
  }
}


public class main() {
  public void saveGame (playerShip player) throws IOException {
    //code that deals with writing to text files
  }
}

This however gives me an error at main.saveGame(player); where it says "unreported exception IOException; must be caught or declared to be thrown"

Im not sure exactly whats going on, any help would be greatly appreciated!




Using quicksort to sort an array of objects by one of their attributes' value

So, I'm declaring an array of objects

Player top[50];

Here is the class:

class Player
{
    string name, place, pc;
    int pp;


public:
    float acc;
    int playerno;
    void read();
    void print();
};

(all of this works fine btw)

Here is my quicksort procedure:

void sort(Player *arr, int p, int q)
{   
    float piv = arr[24].acc;
    int i, j;
    Player  x;
    i = p;
    j = q;
    do
    {
        while (arr[i].acc < piv) i++;
        while (arr[j].acc > piv) j--;
        if (i <= j)
        {
            x = arr[i];
            arr[i] = arr[j];
            arr[j] = x;
            i++; j--;
        }
    } while (i <= j);

    if (j > p) sort(arr, p, j);
    if (i < q) sort(arr, i, q);
}

and then the main function calls

for (int i = 0; i <= 49; i++)
{
    top[i].playerno = i + 1;
    top[i].read();
    sort(top, 0, 49);
    top[i].print();
}

I'm getting a stack overflow error, I'm assuming it's because the function repeats itself infinitely. I want to sort all the objects (players) in this array by the value of their 'acc' attribute, yet I can't quite figure out how am I supposed to modify this procedure so that it works on an array of objects (it was originally intended for simple integer only arrays). Any ideas what is going wrong?