vendredi 31 juillet 2015

Object that initalizes to itself C++

For example , I have the code:

class test{


void another(){


int main(){

test chk = chk;

Here i've done an initialization of newly created object of type "test" to itself, and my question is , does such initialization serve special purpose , does such initialization do anything otherwise than initalizing "test chk; " instead of "test chk = chk;" I understand that the constructor cannot be called if the object is initialized to itself , but why? , I would like to know more about such initialization of an object to itself.

Run Aother Class by Pressing Button in Kivy

I have written an app in kivy but It has total 3 classes one of them is application class second is exampleroot class and third is pscan calss which i want to run

Now when I press a button on screen .... So it should run pscan class....That's what I want...I have given my and example.kv file below

MAIN.PY file

from import App
import socket, sys, threading, os, time

################# LIBRARIES IMPORTED ##############

#####MY FIRST CLASS NAMED pscan ######

class pscan(object,threading.Thread):
        def __init__(self,ip, port):
                self.ip = ip
                self.port = port
        def run(self):
                        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        s.connect((socket.gethostbyname(self.ip), int(self.port)))
                        print "\n[+] OPEN:",self.ip, self.port
                        print "\n[!] CLOSE:",self.ip, self.port

target = ''
sport = 1
eport= 100

############ MY SECOND CLASS NAMED EampleRoot ########

class ExampleRoot(BoxLayout):
        def final(self,*args):

                while sport <= eport:
                        work=pscan(target,sport) #run pscan class from Exampleroot class
                        work.start()             #DID not working
class ExampleApp(App):
        return ExampleRoot()

if __name__ == "__main__":

.KV file


typescript class decorator: typing properties defined in decorator function

bar is a simple class decorator that adds a property to the class Foo.

function bar(target) {
    target.inDecorator = 'in decorator';

class Foo {
    constructor() {
        this.inClass = 'a string';

    getInClass() {
        return this.inClass;

const foo = new Foo();

All console logs work except for the first, Foo.inDecorator, the inclusion of which in ts 1.5.3 gives the error

Property 'inDecorator' does not exist on type 'typeof Foo'.

As far as I can tell inDecorator is defined on the prototype of Class Foo and should be available on Foo as if it were a static prop. Running the resulting js file works as expected. Took me longer than I care to admit to try just accessing the prototype, but any ideas on how to type/add a static prop or method accessible without the prototype?


Assigning Dynamic Cell Value to Variable

So as the title says, I am looking to assign Cell(x,y).value to a variable so that whenever I call it, the variable automatically sees what internal values(x and y in this case) the class is calling, so that I can use this variable in multiple places throughout my program.

To get a sense of what I'm trying to do, here is an example(I'm interfacing with excel).

while not Cell(l1,6).is_empty():
  if not Cell(l1,7).is_empty():
    for i in range(15,22):
      if i==15:


Array of classes 'undefined' C++

So, I have a array of monsters and a function to display their names. The problem is the debugger says Mons(the array) is undefined. I'd like to know what I'm doing wrong. Please help! The errors are mostly Mons is undefined.

#include <iostream> 
#include <fstream>
#include <windows.h>
#include <time.h>

RPG v0.1.6

//-- WinAPI stuff
void ClearScreen()
  HANDLE                     hStdOut;
  DWORD                      count;
  DWORD                      cellCount;
  COORD                      homeCoords = { 0, 0 };

  hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
  if (hStdOut == INVALID_HANDLE_VALUE) return;

  /* Get the number of cells in the current buffer */
  if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
  cellCount = csbi.dwSize.X *csbi.dwSize.Y;

  /* Fill the entire buffer with spaces */
  if (!FillConsoleOutputCharacter(
    (TCHAR) ' ',
    )) return;

  /* Fill the entire buffer with the current colors and attributes */
  if (!FillConsoleOutputAttribute(
    )) return;

  /* Move the cursor home */
  SetConsoleCursorPosition( hStdOut, homeCoords );

class Player {
    int HP;
    int MHP;
    int STR;
    int AGI;
    int RES;
    int XP;
    int LVL;
    Player() { HP = 8; MHP = 8; STR = 4; AGI = 3; RES = 2; XP = 0; LVL = 1; };

struct DT {

void save_to_file(std::string filename, const Player& P)
    std::ofstream f( filename.c_str() );
    f << P.HP << std::endl;
    f << P.MHP << std::endl;
    f << P.STR << std::endl;
    f << P.AGI << std::endl;
    f << P.RES << std::endl;
    f << P.XP << std::endl;
    f << P.LVL << std::endl;

bool load_from_file(std::string filename, Player& P) {
  std::ifstream f( filename.c_str() );
  f >> P.HP;
  f >> P.MHP;
  f >> P.STR;
  f >> P.AGI;
  f >> P.RES;
  f >> P.XP;
  f >> P.LVL;
    std::cout << "Success!" << std::endl;
  else {
    std::cout << "Failure" << std::endl;
  return f.good();


class Monster {
    int HP;
    int MHP;
    int STR;
    int AGI;
    int RES;
    int XP;
    std::string name;
    ///For Calling
    Monster() { };
    ///Set variables for new battle
    Monster(int A, int B, int C, int D, int E, int F, std::string G){
    this->HP = A;
    this->MHP = B;
    this->STR = C;
    this->AGI = D;
    this->RES = E;
    this->XP = F;
    this->name = G;
    void setStats(int A, int B, int C, int D, int E, int F, std::string G){
    this->HP = A;
    this->MHP = B;
    this->STR = C;
    this->AGI = D;
    this->RES = E;
    this->XP = F;
    this->name = G;

int monstersalive = 3;

// -- Call Functions
void BtlDisplay(Player& P, Mons M[]);
void Battle(Player& P, Mons M[]);

int main()
    // -- Call Classes
    Player p;
    DT d;

    Monster Mons[3];
    for(int j = 0; j < 3; j++){
        Mons[j].setStats(9,9,9,9 + j,9,9,"Noob");



    d.save_to_file("GameData1.txt", p);
    d.save_to_file("GameData2.txt", p);
    d.save_to_file("GameData3.txt", p);

    return 0;

void BtlDisplay(Player& P, Mons M[]) //-- Displays battle stats
    std::cout << "---------" << std::endl;
    std::cout << "L " << P.LVL << std::endl;
    std::cout << "HP " << P.HP << "/" << P.MHP << std::endl;
    std::cout << "---------\n\n" << std::endl;
    std::cout << "Monsters\n--------" << std::endl;
    for(int i = 0; i < 3; i++){
        if(M[i].HP > 0){


void Battle(Player& P, Mons M[])
    while(monstersalive > 0 && P.HP > 0){

PHP Class Variable Not Being Set

class MyClass {
private $total;

public function update() {
$this->total = 56.99;

public function print() {
echo $this->total;

The "print" method is returning "null" ... so the $total variable isn't being set?

Why doesn't double.class equal java.lang.Double.class?

Since the primitive double is represented with the java.lang.Double class, shoudln't double.class equal java.lang.Double.class? (This of course also happens on other primitive types too)

System.out.println(double.class == Double.class);


Result: false

Pass variable from one class to another Python

I have managed to have 2 classes in python that run independently. The goal that I try to make is to pass data variable received from class DataCom() to tkinter cf_label on the second class.

This is a correct way to start? I understand that I have to make public some variable in a way that I cannot figure it out. Maybe some help or suggestion. Self learner now in python pfff...

from Tkinter import * import socket import sys import time import datetime from threading import Thread

def timeStamped(fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
def get_constants(prefix):
    """Create a dictionary mapping socket module constants to their names."""
    return dict( (getattr(socket, n), n)
                 for n in dir(socket)
                 if n.startswith(prefix)

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.friend_check = IntVar()
        self.parent = parent

    def initUI(self):      

        self.cl_label=Label(text="data from socket")

    def friend_box(self):

        if self.friend_check.get() == 1:
            print '1'
            print '0'

class DataCom(Thread):
    def __init__(self, val):
        self.val = val
    def run(self):
        families = get_constants('AF_')
        types = get_constants('SOCK_')
        protocols = get_constants('IPPROTO_')

        # Create a TCP/IP socket
        sock = socket.create_connection(('localhost', 10000))

        while True:

                message = 'INFO'

                print >>sys.stderr, 'sending "%s" Length: %s' % (message,len(message))


                amount_received = 0
                amount_expected = len(message)

                while amount_received < amount_expected:
                    data = sock.recv(1024)
                    amount_received += len(data)
                    if len(data) != 0:
                        print >>sys.stderr, 'Server received %s %s:Length %s' % (timeStamped(), data, len(data))
                        print >>sys.stderr, 'No more data, closing socket'
                if not data:



def main():

    myThread1 = DataCom(4)
    myThread1.setName('Thread 1') 

    root = Tk()

    app = Example(root)

if __name__ == '__main__':

Declaring, updating and accessing a System::String within a class

I've been searching since yesterday about my question but I found nothing related to it so far. By the way, I am quite new to classes so please be kind.

I declared a System::String variable within a class, I created a method to update that variable and another one that returns it's value. However, updating the said variable throws an exception. What is the correct way of declaring a System::String within a class and how do you update and return it's value from a class?

The exception:

A first chance exception of type 'System.NullReferenceException' occurred in XXX.exe

Here is the simplified version of the class I made:

ref class clTimeStamp {
        strDatestamp = gcnew System::String("");
    System::String ^strDatestamp;
    void SetDateStamp(System::String ^a)
        strDatestamp = a->Substring( 6, 4 );    // yyyy
        strDatestamp = strDatestamp + "-" + a->Substring( 3, 2 );
        strDatestamp = strDatestamp + "-" + a->Substring( 0, 2 ) + "T";
    System::String ^GetDateTimeStamp()
        return strDatestamp;

And this is how I used it in the main program:

strBuffer = gcnew String(buffer.c_str());
fprintf(handle, "%s\n", clTimeStampHSCAN1->GetDateTimeStamp());

I am really confused with strings in C++-CLI, there's just too many ways to create them and it gets quite complicated.

Your help will be greatly appreciated.

Edit: Updated with Caninonos' suggestion (change initialization of String variable in the constructor) but the result is still the same.

Messages passed to success url of django Update View

Im trying to pass a success message on update using the generic CBV UpdateView..

class TribeUpdate(FormMessagesMixin, UpdateView):
    model = Tribe
    fields = ['name', 'description', 'cause']
    template_name_suffix = '_update_form'
    form_valid_message = 'success'

    def get_success_url(self):
        return reverse('tribe_detail', kwargs={'tribe_slug' : self.kwargs['slug']} )

    def get_object(self, *args, **kwargs):
        obj = super(TribeUpdate, self).get_object(*args, **kwargs)
        if not obj.creator == self.request.user:
            raise PermissionDenied
        return obj

    def form_valid(self, form):
        tribe = Tribe.objects.get(slug=self.kwargs['slug'])
        action.send(tribe.creator, verb='updated the tribe', target=tribe)
        return super(TribeUpdate, self).form_valid(form)

The success message doesnt apear on the success url page.. the tribe_detail view.. it just appears again when i click through to the UpdateView..?

Any help will be amazing, I need to override form_valid to save data to the form depending on the input..

creating many divs with content using javascript

I'm trying to learn javascript and would like do exactly as the code below using a loop whereas I can then change number of images/divs that's gonna be created on the page.

Thanks in advance / J

<div class="row">
        <div class="column">
            <img src="images/img1low.JPG">
        <div class="column">
            <img src="images/img2low.JPG">
        <div class="column">
            <img src="images/img3low.JPG">
        <div class="column">
            <img src="images/img4low.JPG">

Why is calling __init__() different to class variables? [duplicate]

This question already has an answer here:

I've noticed that, when you assign a value to a class variable directly, this value is shared by all instances of the class, whereas, when you assign a value in the __init__() method, it's unique for that instance.


  • All instances of Thing share the same properties
  • All instances of AnotherThing have individual properties

    class Thing()
        properties = {}
    class AnotherThing()
        properties = None
        def __init__(self):
            properties = {}

Why the difference? I haven't found anything in the documentation.

Is properties = None superfluous? I suspect it is.

Additional info: I tried to pickle Thing. Unpickling loses the properties. When pickling AnotherThing, everything worked as expected. The pickle file for Thing was only 30Kb. The pickle for AnotherThing is 1.3Mb

Class declared but not exist yet

I have few files in same folder:


function __autoload($class_name) {
    include $class_name . '.php';
$b = new B();
echo 'done' . PHP_EOL;


echo 'include A' . PHP_EOL;
abstract class A {
    function __construct() {
require_once ('A.php');
require_once ('B.php');
require_once ('C.php');

echo 'A exists - ' . (class_exists('A') ? 'yes' : 'no') . PHP_EOL;
echo 'B exists - ' . (class_exists('B') ? 'yes' : 'no') . PHP_EOL;
echo 'C exists - ' . (class_exists('C') ? 'yes' : 'no') . PHP_EOL;


echo 'include B' . PHP_EOL;
final class B extends A {


echo 'include C' . PHP_EOL;
final class C extends A {

Result if I run test.php:

include B
include A
include C
A exists - yes
B exists - no
C exists - yes

Why class B does not exists yet?

Is it because it's inside of declaration code?

It's easy to fix just add include 'A.php'; first line in test.php.

c++ friend class keyword within class definition

I was just wondering what is happening with the following code:

class SomeClass {

    void someMethod();
    bool _someValue;

class SomeOtherClass {

friend class SomeClass;

    void someOtherMethod();

    bool _someOtherValue;


I've been having a bit of a read of the following page in the 'Friend classes' and it seems that the friend class has access to the defining class?

If that is the case, what is the difference between using friend class SomeClass and just inheriting the classes such as class SomeOtherClass : SomeClass { }??

How do I get a sqlite Table attribute from a class?

I would like to get a Sqlite Table attribute from my class.

I have a method to check if a table exists from here:

var info = database.Connection.GetTableInfo(typeof(Customer).Name);
if (info.Any())
    //do stuff with table

where Customer is:

public class Customer
  //class stuff

Now my method will work fine as it is but I would like to link it to the Table attribute rather than the class name incase I change the table name in future.

How do I go about getting my Table attribute from my class?

Why is it not possible to access static fields of a class via Type.getClass()?

In haXe, it is possible to get the class of an object with the following function:


If the myObject is an instance of the class myClass contains a static field, I should be able to access this field:

class MyClass
    public static myStaticField:Int = 5;

public var myObject = new MyClass();

//expected trace: "5"
trace (Type.getClass(myObject).myStaticfield);

But the result is:

"Class <MyClass> has no field myStaticField."

Any idea why?

Cannot switch between classes every 1 second

I am trying to switch my div class using a timer, and I'm always switching between 2 classes.

Here is the beginning of the div code

<div id="this" class="photobanner">

You can check the JQuery function and timer I made below

function autoAddClass(){
    if( $( '#this' ).hasClass( 'first' ))
        setTimeout(autoAddClass, 1000);

This is not working

R write.table read.table change the format of some columns in dataframes

I am experienced a problem when saving data using write.table and reading data using read.table.

I wrote some code that collect data from thousands of files, does some calculations, and creates a data frame. In this data frame I have 8 columns and more then 11000 rows. The columns contain the 8 variables, 3 of which are ordered factors; the other variables are numeric.

When I look at the structure of my data before using the command write.table I got exactly what I expect which is:

'data.frame':   11424 obs. of  8 variables:
 $ a_KN      : num  8.56e-09 1.11e-08 1.45e-08 1.88e-08 2.45e-08 ...
 $ a_DTM     : num  5.05e-08 5.12e-08 5.19e-08 5.26e-08 5.33e-08 ...
 $ SF        : num  5.89 4.6 3.58 2.79 2.18 ...
 $ Energy    : Ord.factor w/ 6 levels "160"<"800"<"1.4"<..: 1 1 1 1 1 1 1 1 1 1 ...
 $ EnergyUnit: Ord.factor w/ 3 levels "MeV"<"GeV"<"TeV": 1 1 1 1 1 1 1 1 1 1 ...
 $ Location  : Ord.factor w/ 7 levels "BeamImpact"<"WithinBulky"<..: 5 5 5 5 5 5 5 5 5 5 ...
 $ Ti        : num  0.25 0.25 0.25 0.25 0.25 0.25 1 0.25 1 0.25 ...
 $ Tc        : num  30 28 26 24 22 20 30 18 28 16 ...

After that I use the usual write.table command to save my file:

write.table(data, file = "filename.txt")

Now, when I read again this file into R, and I look at the structure, I get this:

mydata <- read.table("filename.txt", header=TRUE)

> str(mydata)
'data.frame':   11424 obs. of  8 variables:
 $ a_KN      : num  8.56e-09 1.11e-08 1.45e-08 1.88e-08 2.45e-08 ...
 $ a_DTM     : num  5.05e-08 5.12e-08 5.19e-08 5.26e-08 5.33e-08 ...
 $ SF        : num  5.89 4.6 3.58 2.79 2.18 ...
 $ Energy    : num  160 160 160 160 160 160 160 160 160 160 ...
 $ EnergyUnit: Factor w/ 3 levels "GeV","MeV","TeV": 2 2 2 2 2 2 2 2 2 2 ...
 $ Location  : Factor w/ 7 levels "10cmTarget","AdjBulky",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ Ti        : num  0.25 0.25 0.25 0.25 0.25 0.25 1 0.25 1 0.25 ...
 $ Tc        : int  30 28 26 24 22 20 30 18 28 16 ...

Do you know how to solve this problem? THis bothers me also because I am creating a Shiny app and this changed class doesn't fit my purpose.


Incredibly huge and incredibly small numbers (not just integers) in C#

In C#, I need to work with very large (and very small) numbers, for which decimal and double are not accurate enough and BigInteger is not able to store a number's fractions.

I'd like to have numbers as big as memory will allow, and if possible hard drive space data

Does someone have a class or is there a system type for a really big number.

Infinity needn't be represented, but it would be a plus!

Python Tkinter: How do I avoid global variables in a changing class?

I'm doing a large project at the moment to help me learn my first programming language (Python) and I've run into some unknown territory. I am aware that it's generally bad to use global variables and there are better solutions, but I can't figure it out for my situation.

I've made the code below as a simple example of what I want to achieve. What's the best way to do this instead of using the global variable?

Also, are there any general errors I've made in my code below?

Thanks in advance

from tkinter import *

root = Tk()

display_number = 5

class NumberBox():
    def __init__(self):
        global display_number
        self.number_label = Label(root, text=display_number)

    def engine(self):
        root.after(10, self.engine)

def change_number(operation):
    global display_number
    if operation == "add":
        display_number += 1
    if operation == "subtract":
        display_number -= 1

Button(root, text="Add Class", command=lambda: NumberBox()).pack()
Button(root, text="Number UP", command=lambda: change_number("add")).pack()
Button(root, text="Number DOWN", command=lambda: change_number("subtract")).pack()

for _ in range(5):


Pass a php object through json

Problem statement:

I have to pass a php object from one php application to another using json. In my destination application, I am not able to access my member functions after json_decode.

Here is the sample script:

class TestScope{
        private $privateVar;
        function __construct(){
        function getPrivateVar(){
                return $this->privateVar;
$testScope = new TestScope();
$encode = json_encode($testScope);
$decode = json_decode($encode);

After executing the script, I am getting below error:

PHP Fatal error:  Call to undefined method stdClass::getPrivateVar()

What is the possible solution to prevent this error?

How I can access Class method variable in instance method OR Use a common variable for both?

I have this Class method to create a hero object.

    NSArray *heroWalkingFrames;
    //Setup the array to hold the walking frames
    NSMutableArray *walkFrames = [NSMutableArray array];
    //Load the TextureAtlas for the hero
    SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
    //Load the animation frames from the TextureAtlas
    int numImages = (int)heroAnimatedAtlas.textureNames.count;
    for (int i=1; i <= numImages/2; i++) {
        NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
        SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
        [walkFrames addObject:temp];
    heroWalkingFrames = walkFrames;
    //Create hero sprite, setup position in middle of the screen, and add to Scene
    SKTexture *temp = heroWalkingFrames[0];

    Hero *hero = [Hero spriteNodeWithTexture:temp]; =@"Hero";
    hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
    hero.physicsBody.categoryBitMask = heroCategory;
    hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;    
    return hero;

and I have another instance method to perform run animation for my hero.

        SKAction *incrementRight = [SKAction moveByX:10 y:0 duration:.05];
        SKAction *moveRight = [SKAction repeatActionForever:incrementRight];
        [self runAction:moveRight];     

now heroWalkingFrames variable in Start method so I can perform animation, I want to add this line in Start method

 [SKAction repeatActionForever:[SKAction animateWithTextures:heroWalkingFrames timePerFrame:0.1f resize:NO restore:YES]];

Is there any way I can use this variable for both ?

Wordpress ,enqueue scripts not bottom , top using constuctor?

I have just developed a plugin Ui Slider Filter by price, for wordpress and by no mean i am not a expert coder, learning. So the problem i have faced is , I only wanted to include necessary scripts in specific my plugin pages inside admin and only in the post where the shortcode is called. i had to do some tricky stuff in my classes and couple of script to insert manually using script tag. The function of the plugin is basically user can filter posts by price with dragging a jquery ui slider. You can see how it works here and please kindly give me your review.

The main problem was when i use constructor to enqueue script and call , script loads in bottom of page , I want my script to be loaded first then content. I searched so long didnt find any solution.

Just for example

Class Slider {
public function __construct (){
public function pluginScripts(){
     //register and enqueue all scripts here.

So my script loads but bottom of the page i want very beginning.

I know how to do this using static function outside of class but that doesn't solve it since i want to load script only when i create instance of this class.

Refactoring a data class in C++

So I have the following class which I find silly and would like to refactor.

class Data
    bool getVariableA();
    bool getVariableB();
    bool getVariableC();

    void setVariableA();
    void setVariableB();
    void setVariableC();

    bool A;
    bool B;
    bool C;

This goes on for like 100 variables and growing, most of which are boolean. If you were to refactor this class (while keeping all the data in it instead of spreading out), how would you go about it?

Issues with the current structure are at least that it's a) too much code b) pain to add stuff c) unit testing coverage always needs to be added manually when growing the class.

find out a class variable's defined scope (from within the class)


class myClass extends \Phalcon\Mvc\Model
    public $a;
    protected $b;
    private $c;

How can I test that $a is public, $b is protected, and $c is private from within myClass?

jeudi 30 juillet 2015

Difference between methods and member variables?

class Animal(object):
    """Makes cute animals."""
    is_alive = True
    health = 'good'
    def __init__(self, name, age): = name
        self.age = age
    # Add your method here!
    def description(self):
        print self.age

hippo = Animal('Tom', '20')
sloth = Animal('Randy', '18')
ocelot = Animal('Birdman','57')

The code above is from codecademy's python course. I am getting confused about some of the definitions surrounding OOP. If my understanding is correct, a function defined within a class is known as a method, which is why when it's called, for example like this: 'hippo.description()', the '()' are necessary because of the syntax involving functions.

However, I start to get confused with '' and 'self.age'. Are these also methods? I was wondering if they were perhaps member variables, but then wouldn't they be defined in the same way the variable 'health' was above? And if they aren't member variables, how come they can be accessed using dot notation in the same way as the member variables?


Convert 2D array into object array

I've got a 2D array and I need to convert each "line" of the array into a separate object array element that contains a String, an Int and multiple Doubles. Right now each 2D array element is stored as a String.

Here is my class object:

public Object() {
    String = "null";
    Double1 = -1.0;
    Double2 = -1.0;
    Double3 = -1.0;
    Integer = -1; 

Here is my method used to convert the 2D array to a class array:

 public static void objectConvert() {
        Object[] objArray = new Object[count];
        for (int i = 0; i<count; i++) {
            Object[i] = new Object(data[i][0], Double.parseDouble(data[i][1]), Double.parseDouble(data[i][2]), Double.parseDouble(data[i][3]), Integer.parseInt(data[i][4]));

Here are the errors that I get when compiling:

 javac error: cannot find symbol
                        Object[i] = new Object(data[i][0],
 Double.parseDouble(data[i][1]), Double.parseDouble(data[i][2]), Double.parseDouble(data[i][3]), Integer.parseInt(data[i][4]));
  symbol:   variable Object
  location: class Program error: constructor Object in class Object cannot be applied to given types;
                        Object[i] = new Object(data[i][0],
 Double.parseDouble(data[i][1]), Double.parseDouble(data[i][2]), Double.parseDouble(data[i][3]), Integer.parseInt(data[i][4]));
  required: no arguments
  found: String,double,double,double,int
  reason: actual and formal argument lists differ in length
2 errors

How to call an Action from a different class in Java

How would I call an Action from another class in Java? I got a CloseTabButton class online that allows a simple close tab button on each JTabbedPane, but when the tab is closed, I would like a dialog to pop up based on information (if file is not saved, ask to save it, etc.). This is the file:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CloseTabButton extends JPanel implements ActionListener {
    private JTabbedPane pane;
    public CloseTabButton(JTabbedPane pane, int index) {
        this.pane = pane;

        // CloseIcon class just had a button with an x painted on it
        Icon closeIcon = new CloseIcon();
        JButton close = new JButton(closeIcon);

        close.setPreferredSize(new Dimension(closeIcon.getIconWidth(), closeIcon.getIconHeight()));

        add(new JLabel(pane.getTitleAt(index), pane.getIconAt(index), JLabel.LEFT));

        pane.setTabComponentAt(index, this);

    public void actionPerformed(ActionEvent e) {
        int i = pane.indexOfTabComponent(this);

        String fileName = pane.getToolTipTextAt(i);

        // Where I want to ask if user wants to save, etc.
        if (fileName == "Untitled") {
            // Do stuff

        pane.remove(i); // Removes the tab

        // If tab count < 1, then disable the save and save as buttons on menu
        if (pane.getTabCount() < 1) {
            JFrame frame = (JFrame) pane.getParent().getParent().getParent().getParent().getParent(); // Yes, there is that many in my code to get the parent JFrame

            int menuCount = frame.getJMenuBar().getMenuCount();

            for (int a = 0; a < menuCount; a++) {
                int itemCount = frame.getJMenuBar().getMenu(a).getItemCount();

                for (int b = 0; b < itemCount; b++) {
                    Component component = frame.getJMenuBar().getMenu(a).getMenuComponent(b);

                    if (!(component instanceof JSeparator)) {
                        // Not a seperator
                        String itemName = frame.getJMenuBar().getMenu(a).getItem(b).getAccessibleContext().getAccessibleName();
                        if (itemName == "Save As..") {

In my main class I have actions listed like this:

static Action Close = new AbstractAction("Close") {
    public void actionPerformed(ActionEvent e) {
        closeCurrentWindow(); // function that will close tab

The other menu items are Actions as well, and as you can see, what I'm currently doing in the CloseTabButton class is quite frustrating, and most likely the wrong way to code it. Is there a much simpler way to do what I'm doing?

Call a method in initialization without overriding base class's __init__

I hope I make it clear in the title. I'm trying to inherit from list, and I want some of my own methods to be called when an instance of my class is created. However, I can't override list.__init__ since that would make me unable to use list's original methods. How can I accomplish this?

Javascript: Create a sub-class within a class [duplicate]

This question already has an answer here:

I know Javascript doesn't support classes, so I'm creating a Cube object, then declaring its prototype methods. Within Cube, I want to create a flip object with more methods within it:

// Create Cube class
var Cube = function(){
    this.x = 0;
    this.y = 0;

// Add methods to Cube prototype
Cube.prototype = {
    initialize: function(){

    // Adding sub-functions within flip
    flip: {
        start: function(){

        end: function(){
            console.log("Ending flip");

// Declare instance of Cube
var cubeInstance = new Cube();

However, I'm getting the wrong scope for this within flip.start(), because it outputs the flip object, instead of the Cube object I want:

Object { start: Cube.prototype.flip.start(), end: Cube.prototype.flip.end() }

What do you suggest I do so that cubeInstance.flip.start(); will trigger the start() method, but I can still access the Cube variables (namely, this.x and this.y)?

Chaging document.getElementById to getElementsByClassName

I have the following function that I would like to work with a class "pause" instead of an id. I did see a few topics about this however I didn't quite understand how would this work. Thanks!!!

       function onPlayerReady(event) {
            document.getElementById('pause').onclick = function() {

operator addition class deals with arrays addition C#

I'm a rookie of c#. I ran a simple test to get the sum of two arrays. Here is my example

       A                                B               Total
   date   Price                     date  Price       date  Price
   01/07  100                       01/07  50         01/07  150
   02/07  150                       02/07  30         02/07  180

I created two arrays:

string [,] A=new string[2,2]{{"01/07",100},{"02/07",150}};
string [,] B=new string[2,2]{{"01/07",50},{"02/07",30}};
string [,] c=new string [2,2];     
 for(int i=0;i<=A.GetUpperBound(0);i++)

Here is my question:

Is that possible to create a class or function called Addition who does the same computation and at each time I only need to declare these two parameters?

For example: class Addition(parameter1, parameter2)

Thanks for your help

Swift - NSDictionary multidimensional

currently i am working on a class which initializes an multidimensional array:

class Manager {

    let data: Dictionary<String, Array<String>>

    init(data: NSDictionary) {

        func getApiData() {

            getApiDataResourceA() { responseObject, error in

                let resourceA = responseObject!

      ["resources"] = resourceA // this line fails





The responseObject which is returned asyncronously has this structure:

    "data": [
            id: 1
            name: "Name1"
            id: 2
            name: "Name2"
    "count": 2,
    "success": true

The structure i want to get in my "data"-variable:

    "resources": [
                    "data": [
                            id: 1
                            name: "Name1"
                            id: 2
                            name: "Name2"
                    "count": 2,
                    "success": true
            "resourceB": // and so on ...

But when saving my responseObject into my "data"-variable:["resources"] = resourceA // this line fails

It prints:

Cannot assign to the result of this expression

Anybody could help me with this problem??

Thanks and Greetings!

Object created from a class to be used within a function prints unexpected 'new' (T_NEW)

Im trying to create a class that I can request to return a variable based on some mobile detection. Im trying to avoid defining anything with global. I'm getting the following error: Parse error: syntax error, unexpected 'new' (T_NEW)

require_once 'lib/Mobile_Detect.php';

class detectDevice {
  private static $detect = new Mobile_Detect;
  private static $deviceType;

  public static function returnDevice(){

    if ( $detect->isMobile() ) {
      $deviceType = "IS MOBILE";
    if( $detect->isTablet() ){
      $deviceType = "IS TABLET";

    print self::$deviceType;

echo detectDevice::returnDevice();

Any suggestions?

php class definition method

I'm new to PHP. I was just wondering why in the method "greet()" (see example). I mustn't add a parameter "$firstname" in the declaration of the function.

Wrong -->

public function greet($firstname){
  echo "Bonjour, mon nom est ". $this->firstname . "Ravi de vous rencontrer ! :-)";


Good -->

class Person {
public $isAlive = true;
public $firstname;

public function __construct($firstname,$lastname,$age){
    $this->firstname = $firstname;           

public function greet(){
    echo "Bonjour, mon nom est ". $this->firstname . "Ravi de vous rencontrer ! :-)";   


C++ - overloading operator >>

I realized string class MyString (we discussed it in my previous question). Here is code:

#include <iostream>
#include <cstring>

using std::cout;
using std::endl;

class MyString{
    char * content;
    int length;
    void copy(const MyString & source);
    MyString(const char * source);
    MyString(const MyString &source);
    void print(void);
    MyString & operator =(const MyString &source);
    friend std::ostream & operator<<(std::ostream & out, const MyString&   towrite);

    content = new char[1];
    content[0] = '\0';
    length = 0;

MyString::MyString(const char *source){
    length = strlen(source);
    content = new char[length + 1];
    strcpy(content, source);

    delete[] content;

void MyString::copy(const MyString & source){
    length = source.length;
    content = new char[length + 1];
    strcpy(content, source.content);

MyString::MyString(const MyString & source){

void MyString::print(void){
    cout << "" << content << endl;

MyString &MyString::operator=(const MyString &source){
    return *this;

std::ostream & operator<<(std::ostream & out,const MyString& towrite){
    out << towrite.content;
    return out;

int main(){
    MyString word0;
    MyString word1("stackoverflow");
    MyString word2;
    word2 = word1;
    MyString word3(word2);
    cout << word3 << endl;
    cout << word0 << endl;

I want to overload operator >> so I can have in main program something like:

MyString word;
cout<<"Enter some word: "<<endl;
cout<<"Your entered: "<<word<<endl;

I saw how operator >> is overloaded and tried to do it here but without success.

Any suggestion?

Generating MSDN documentation URLs

This question is on behalf of one of my team members: I am a developer in charge of writing the documentation for our product. I have written a tool in C# to output our assembly in markdown style files. In order to facilitate the ease of use for our classes, I wanted to implement a way of linking the class type and property constructs to any MSDN documentation available publicly. For the most part, this was accomplished simply by using the namespace of the class like so:

However, I ran into some problems when looking at classes with generic type arguments and properties. They seem to be generated in a special manner that looks like a hashed string, like so:

The “b682ts2x” part of the URL is the part that is different.

I would like to know if there is any way I can get in touch with someone who knows how these links are generated, and if there is a way to generate the same exact URL portion (that is, b682ts2x) for any class property using only reflection.

c++: vector of class instances, search by class member values failed

I have the following program where I defined a vector of class Point. I pushed into this vector five Point instances, with their Ids. Then I tried to search by Id but didn't get the expected result. The following program didn't return anything.

using namespace std;
class Point{
                int id;
                void setId(int k){id=k;}
                int GetId(){return id;}

int main()
        vector<Point> datasets;
        for(int i=0; i< 5; ++i){
        Point temp;
        for(int i=0;i<5;i++){
                if (datasets[i].GetId() ==4){
                        return i;

How to pass a string from Class 1 to Class 2 to Class 3?

I have 3 classes (UCourse, Student and Teacher) and each class has a unique string property.

Is there a simple way I can take the string property from the first class UCourse, pass it into a 2nd class Student, and then pass that string plus another string from the 2nd class into a 3rd class Teacher?

This is what I have so far for my 3 classes:

using System;

namespace EDXonline_AssignmentFour
    class Program
        class UCourse
            // Set the unique string for the 1st class
            private string course = "Computer Scienece";
            public string Course
                get { return course; }

        class Student
            // Get the string from the 1st class
            UCourse ucourse = new UCourse();
            public string coursef1
                get { return ucourse.Course; }

            // Set the unique string for the 2nd class
            private string name = "zach";
            public string Name
                get { return name; }

        class Teacher
            Student student = new Student();

            private string namet = "Sally";

            // Get the unique string from the 2nd class
            public string namef1
                get { return student.Name; }

            // Set the unique string for the 3rd class
            public string Namet
                get { return namet; }

Then, I need to create an instance of Teacher and by using only this instance of Teacher, I need to output all string properties from each of the 3 classes like this:

public static void Main (string [] args)
    Teacher teacher = new Teacher();
    Console.WriteLine("{0} and {1} are in {2}",
    teacher.namef1, teacher.Namet /*, UCourse string from the 1st class goes here*/);

So far that works to display the strings from the 2nd and 3rd classes, but how can I get the value of the UCourse string from the first class as well?

Get class of generic type in Java

Do you know, how to take class object of generic type in Java?

I mean there is notation like:


and I want something like:


I want to use robospice library and want to create class, that will keep results of query. It keeps query status and keeps object(that is the reason to make request as generic class) that is query resut.

Data modeling, how to model such a structure into classes?

I've a Book class

Class Book
    String name;
    String id;

which has some general properties and some other Libraries specific properties, so book id '111' in library "xyz" has title property and in library "abc" has numberOfPages and dimensions so, It will look like:

Class Book
    String name;
    String id;
    String xyzTitle;
    int abcNumberOfPages;
    float abcHeight;
    float abcWidth;

BUT this doesn't look good. why not create a separate classes for book info

Class XYZBookInfo
   String title;

Class ABCBookInfo
   int numberOfPages;
   float height;
   float width;

Class Book
   String name;
   String id;
   XYZBookInfo xyzInfo;
   ABCBookInfo abcInfo;

So good so far, But; what if a couple of libraries share some properties! if XYZ and ABC library are interested in Book's weight but another library ZZZ isn't?

Where to add weight property? even if we create a class WeightedBookInfo then create subclasses XYZBookInfo and ABCBookInfo from it, then we will have to duplicate weight value in both class' instances??!!

I'm trying to create a xcode core data model to represent this structure.

Calling multiple arguments in an array from a function [PHP]

I am trying to call multiple arguments from a function in php using an array.

Class useful {
    function callFunctionFromClass($className, $function, $args = array()) {
            return $className::$function($args);


    $u = new useful;

    $u::callFunctionFromClass(new useful, "text", "Test", "Test");

I have the function text() created aswell like so:

function text($msg, $msg2) {
    echo $msg;
    echo $msg2;

I am getting this error message:

Warning: Missing argument 2 for useful::text(), 
  called in htdocs\class\library\class.php on line 16 
  and defined in htdocs\class\library\class.php on line 11
Notice: Undefined variable: msg2 in htdocs\class\library\class.php on line 13

This works fine without $msg2 & a second argument. So how is multiple arguments pulled off?

Class level and Method level comments in eclipse java [on hold]

Can anyone clearly explain how to add class level and method level comments in eclipse java and how brief should we be while explaining about a class and methods

Python - accessing variable from function in class

I have a class as given below and I want to access some of variables located inside function of that class. The structure is as below:

class access_all_elements:

   def RefSelect_load_file(): 

       reffname = askopenfilename(filetypes=(("XML files", "*.xml"),
                                                 ("All files", "*.*") ))
       if reffname: 
          recovering_parser = etree.XMLParser(recover=True)
          AdasReference = etree.parse(reffname, parser=recovering_parser).getroot()
          AdasReferenceString = etree.fromstring(ToStringAdasReference)
          TimeReferenceTest = AdasReferenceString.findall("{")
      return TimeReferenceTest

  def CopySelect_load_file(): 
    #same code as above, but for loading another file in same GUI

Description of code

1). class access_all_elements: class to access all elements inside

2). def RefSelect_load_file(): function inside class that loads xml file

3). ReferenceXML.insert(END, insert filepath in text box inside gui

4). AdasReference: Parse xml file located in reffname

5). TimeReferenceTest: this extracts all the elements from xml having label car The output of this variable looks like: [<Element { at 0x279ff08>, <Element { at 0x279ffa8>.....]

5). return TimeReferenceTest I want to return the value of this variable when function is called

What I want:

There is another function outside this class namely callback which uses one of the variable which is located in access_all_elements class and that variable is TimeReferenceTest. I want to access the value of this variable in the below given function. The value is mentioned in 5th point above. The function outside class looks like below:

            def callback():

                toplevel = Tk()
                toplevel.title('Another window')

                for i,j in zip(TimeReferenceTest,TimeCopyTest): #TimeCopyTest is also like 
    TimeReferenceTest defined in above class under CopySelect_load_file() function, 
but not mentioned here

To put it simply, out of entire entity of RefSelect_load_file() function I only want to access the value of variable TimeReferenceTest in line for i,j in zip(TimeReferenceTest,TimeCopyTest) when callback is function is executed

What I tried and What this is all about

First all, I am making a GUI in Tkinter and trying to bind all the code I wrote with that gui. Callback is invoked when someone presses button to compare two xml files.

What I tried so far is the approach of encapsulating both functions into same class as shown above to access its variables. I call the class in following manner:

c = access_all_elements()

The problem here is I know this function is defined in a way to open file dialogue box, but I want to return value of only TimeReferenceTest when I call it in callback function. So is there any way you can suggest where i can access that variable without executing entire function?

Implementation of interfaces alongside the extensions of the implemented classes

I'm new to oop (php speficically). Please bear with me.

I have several classes that roughly correspond to the table names in the database. These classes, for example, are Party, Organization, Person. Organization and Person classes extend Party to have common methods, like accessors (getters+setters) and non-accessors.

In case I need different method implementations in Party, Organization, and Person, I create interfaces: PartyInterface, PersonInterface, OrganizationInterface. PersonInterface and OrganizationInterface extend PartyInterface.

Is it a good practice of having the same extension of interfaces along with extension of the implemented classes? What are the pros and cons of this approach?

Class implementation of C++ Enums

According to the answer of BitWhistler I've implemented a class for C++ enums. Hope this helps other people who looking for this thing.

some operators overloaded for convenience and now you can use enums in c++ as an Object of a class. It also supports following operators:

  • << ostream
  • >> istream
  • + string concat
  • == object and enum comparison
  • != object and enum comparison
  • = string and enum assignment

check the answer.

Can someone please explain in simple terms what a Python Class is

I'm new to Python programming and being 50 years old am having a tough time getting my head around a few things.

Can someone please explain in a simple way what a Class is please. I've done some research on Google and YouTube but I end up more confused!

Thanks Daz

Why isn't class initialized?

I have the following enum singleton:

public enum Container{
    //Methods, Fields

and the class it uses:

public class Client{
    private static final Container CONTAINER = Container.INSTANCE;


During the appliction i being started I got the class not found exception:

Client NoClassDefFoundException Cannot load and initialize the class

But If modify it as follows:

public class Client{
    //private static final Container CONTAINER = Container.INSTANCE;


The exception is no longer occured.

Django form fields dynamic subclassing

I'm trying to develop mechanism to dynamically create set of Django Form Fields.

While experimenting, I encounter strange behavior, and I'd like to know, if it worth to worry about.

Here the code:

In [139]: from django import forms

In [140]: MyFieldDynamic = type('MyFieldDynamic', (forms.CharField,), {})

In [141]:   1 class MyField(forms.CharField):
            2     pass

In [142]: MyFieldDynamic.mro()

In [143]: MyField.mro()

As you see if class created using type, its first superclass is django.utils.deprecation.MyFieldDynamic. What's wrong with this thing?

And a bit more broader question - is it possible at all, what I'm trying to do - create form fields at runtime? Maybe there are some resources, I skipped?

how can i concatenate multiple classes with css?

I have these bootstrap classes and I want concatenate each one with li, are there a best option than add li before each class? I mean, a way to group all bootstrap classes and concatenate with li.

.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12

In my case I want only these four: li .col-xs-4 li .col-sm-4 li .col-md-4 li .col-lg-4 but i prefer to do generally.

mercredi 29 juillet 2015

Why cannot I use a package-private (implicit) class as the top-level class of a java file?

I am new to Java. Maybe the question is a bit naive.

For example, I have a pkg1, in which there are 2 Java files: and

As the title, I feel it is reasonable to use a package-private-top-level class for f1, then use a public-top-level class for f2, then the outside of pkg1 can still access f1 via f2.

I can even have f3, f4... ..., which are all using package-private class as their top-level class. Then will become a package-interface file for the rest of files in pkg1.

So, why is the fact that a top-level class must be public? Just to prevent from unnecessary complexity?

python flask, keeping session in scope using another class

So my basic question. I have a flask application. Inside of this application I have built a simple login system that uses flask sessions. I want to break my code up into different classes to help separate my logic. But i am receiving the following error.

Traceback (most recent call last):
  File "", line 22, in <module>
    securty = Security()
  File "/Users/chrisburgin/Development/pigarage/", line 6, in __init__
NameError: global name 'session' is not defined

This error is receiving using the following.

My External Class

class Security:
    def __init__(self):
        print('Security Created')

    def loggedIn(self):
        if session.get('logged_in') != True:
            return False

And I am calling this from inside of my server file

securty = Security()

Just as summery. I understand that the 'Security' class doesn't have access to session because its not in scope but I could very much use assistance in understanding how to provide it access.

Please correct me on anything I have done wrong. Thanks!

css transition class remove steps

I am trying to create a button that opens a side panel. the button has two states: open and closed, and has animation keyframes to transition between the two. i've used the steps() easing function and a sprite sheet to achieve this. A class is added with jQuery and the button animates correctly, but when the class is removed it jumps to the closed state instead of animating.

@keyframes contactAnimate {
   100% { background-position: -210px; }
    height: 26px;
    width: 30px;
    position: fixed;
    top: 50px;
    right: 100px;
    image-rendering: pixelated;
    background-image: url("icons/mail-icon.png");
    transform: scale(2) translateX(-25%);
    z-index: 1;
    background-repeat: no-repeat;
    animation: contactAnimate 0.3s steps(7) 1 both;

I tried to add a different animation value to the original class but that just seemed to always break it by animating on page load then not at all when clicked. I've tried changing and adding a bunch of different things to the animation value but none of them effected the transition back to closed, and now i'm out of ideas... It's a pixel art button/ icon, so that explains the 'image-rendering: pixelated;' and why i've set the height and width so small then scaled it.

Declaring, updating and accessing a System::String within a class

I've been searching since yesterday about my question but I found nothing related to it so far. By the way, I am quite new to classes so please be kind.

I declared a System::String variable within a class, I created a method to update that variable and another one that returns it's value. However, updating the said variable creates an exception. What is the correct way of declaring a System::String within a class and how do you update and return it's value from a class?

Here is the simplified version of the class I made:

ref class clTimeStamp {
        strDatestamp = nullptr;
    System::String ^strDatestamp;
    void SetDateStamp(System::String ^a)
        strDatestamp = a->Substring( 6, 4 );    // yyyy
        strDatestamp = strDatestamp + "-" + a->Substring( 3, 2 );
        strDatestamp = strDatestamp + "-" + a->Substring( 0, 2 ) + "T";
    System::String ^GetDateTimeStamp()
        return strDatestamp;

And this is how I used it in the main program:

strBuffer = gcnew String(buffer.c_str());
fprintf(handle, "%s\n", clTimeStampHSCAN1->GetDateTimeStamp());

I am really confused with strings in C++, there's just too many ways to create them and it gets quite complicated.

Your help will be greatly appreciated.

In C# is it possible to assign the name of a class instance by string dynamically? [duplicate]

This question already has an answer here:

basically what I want to be able to do is

    public class MyClass
        public string name{ get; set; }

    Var newInstance = "test" ;
    MyClass newInstance = new MyClass();


returning object created in class function `warning C4172` [duplicate]

This question already has an answer here:

warning C4172: returning address of local variable or temporary

I get a bunch of these errors because I have a vector class that creates vectors and returns them after operations. I asked in another question how to properly return them.

I followed advice at this thread: How to "return an object" in C++?

I guess the vector object will be copied when returned, then why do I get this warning if it is handled? I just don't like a bunch of warnings when I compile.

#ifndef __VECTOR3F_H__
#define __VECTOR3F_H__

#include <cmath>

class Vector3f {

    float X;
    float Y;
    float Z;

    Vector3f() : X(0), Y(0), Z(0) {}
    Vector3f(int x,int y, int z) : X((float)x), Y((float)y), Z((float)z) {}
    Vector3f(float x, float y, float z) : X(x), Y(y), Z(z) {}

    ~Vector3f() {}

    float length() { return std::pow( float(X*X + Y*Y + Z*Z) , 0.5 ); }
    Vector3f unit() {
        float len = length();
        return Vector3f(X/len,Y/len,Z/len);
    Vector3f normalize() {
        float len = length();
        X /= len;
        Y /= len;

        return *this;

    Vector3f add( Vector3f vec) {
        return  Vector3f( X + vec.X , Y + vec.Y , Z + vec.Z);

    Vector3f add(float r) {
        return  Vector3f( X+r,Y+r,Z+r );    

    Vector3f cross(Vector3f vec) {
        float x = Y * vec.Z - Z * vec.Y;
        float y = Z * vec.X - X * vec.Z;
        float z = X * vec.Y - Y * vec.X;

        return Vector3f(x,y,z);

    Vector3f & operator+( Vector3f rhs) {
        return this->add(rhs);

    Vector3f & operator+(float r) {
        return this->add(r);

    Vector3f & operator*(float r) {
        return  Vector3f( X*r , Y*r , Z*r );

    Vector3f & operator-(float r) {
        return this->add(r*-1);

    Vector3f & operator/(float r) { 
        return  Vector3f( X/r, Y/r, Z/r );

    Vector3f & operator-( Vector3f rhs) {
        return this->add(rhs*-1);



Java inner and nested classes

I've started preparing myself for the OCJP7 exam and I found this chapter that seems to be very complicated.

Let's say I have this code:

class Outer1{
    interface InnerInterface{
        String x = "test";
    class InnerClass{
        String x = "test";
class Outer2{
    static interface NestedInterface{
        String x = "test";
    static class NestedClass{
        String x = "test";
class Main{
    public static void main(String [] args){
        String s1 = Outer1.InnerInterface.x;
        String s2 = new Outer1().new InnerClass().x;
        String s3 = Outer2.NestedInterface.x;
        String s4 = new Outer2.NestedClass().x;

Could you tell me why we can access Outer1.InnerInterface.x and Outer2.NestedInterface.x in the same manner? Inner interfaces are static by default? I'm trying to make some connections to make them more clearly.

Need help creating random explosions

I am creating a spaceship game where you go along and shoot down asteroids. I have created a couple of explosion classes, however no matter what I do I cannot get them show up randomly.

So what happens is I run my main program I shoot an asteroid and the first explosion is random, but for every explosion after that is the same as the first one. What is driving me crazy is that the sounds are playing randomly, but the visual explosion is not random. Both the sound and visual are in the same part of my "if, else" logic, but they don't match.

Here is the part of the code that I use that I am talking about:

for self.bullet_shot in self.bullet_list:
       bullet_hit_evil_space_ship = pygame.sprite.spritecollide(self.bullet_shot,self.enemy_list,True)
            self.explosion_pick = random.randint(0,1)
            for enemy in bullet_hit_evil_space_ship:

                if self.explosion_pick == 0:
                    explosion = explosions.Explosion_10()
                    explosion.rect.x = self.bullet_shot.rect.x - 10
                    explosion.rect.y = self.bullet_shot.rect.y - 60

                elif self.explosion_pick == 1:
                    explosion = explosions.Explosion_9()
                    explosion.rect.x = self.bullet_shot.rect.x - 10
                    explosion.rect.y = self.bullet_shot.rect.y - 60


So again, the sound plays randomly, but the explosion that appears is only random once (the first explosion) then they all are the same after that.

Any ideas on what is going on?

Performing function from a different class with Swift

Just about a month ago I started learning swift (mainly from books), with no prior programming experience whatsoever. I am still having trouble wrapping my head around several concepts, mainly value types and reference types, and things such as delegation. This is probably the reason why I can’t seem to find an answer for the following problem.

I have an Xcode project with 2 classes as in 2 swift files.

  1. A viewController class containing a collection view;
  2. A collectionViewCell class.

In the viewController class I have a method to disable and enable user interaction of the collectionView:

func collectionViewInteractionEnabled(boolean: Bool) {
   collectionView.userInteractionEnabled = boolean

When called from the viewController class, the method works. But when called from the collectionViewCell class, i get this:

"fatal error: unexpectedly found nil while unwrapping an Optional value”

Xcode highlights the contents of my function as the culprit. This makes me think that the collectionView is not there for the collectionViewCell class. But my infant programming brain really can’t follow the thought process needed to figure this out.

The only solution I found was using a notification to let the function perform. It works, but isn’t there another way that I should know about? Is it possible to call a function from a different class, and still have it perform as if it was being called from the class wherein the function is declared?

How to change array in class?

how do I assign char array 'startData'

int main()

Player plyr_1('X');
Player plyr_2('O');

char startData[8][8] = {{' ',' ',' ',' ',' ',' ',' ',' '},
                        {' ',' ',' ',' ',' ',' ',' ',' '},
                        {' ',' ',' ',' ',' ',' ',' ',' '},
                        {' ',' ',' ','O','X',' ',' ',' '},
                        {' ',' ',' ','X','O',' ',' ',' '},
                        {' ',' ',' ',' ',' ',' ',' ',' '},
                        {' ',' ',' ',' ',' ',' ',' ',' '},
                        {' ',' ',' ',' ',' ',' ',' ',' '}};

at the start of this loop

menu = false;

while(menu == false)
    int turnCounter = 1;

    Player currentPlyr('X');
    currentPlyr = plyr_1; = startData; = startData;

    plyr_1.score = 2;
    plyr_2.score = 2;

    selectMenu = currentPlyr.mainMenu();

inside array 'data' in created class 'plyr_1' and 'plyr_2'

'data' is a public char array from class 'Game'

class Game
        char data[8][8];

to reset the board everytime the loop starts?


c++ 2 Constructor 1 Object, How to?

I have to set up an object and, after an user chose, i have to change some param into the object but not every each.

example: {

class Champ 
       int hp;
       std::string class;
       Champ(std::string chose);

Champ::Champ() {hp=10; class="";}

Champ::Champ(std::string chose) {class = chose;}

     Champ Test;
     std::string chose;



return 0;


this code give me an error. i need hp equal for all "Champ" created but class can be changed.

The hp can't be "const" because this value may undergo changes...

how can i do this? :/

Function Pointer Array within a Class

I have a class say Method with multiple functions for solving PDE's with different methods similar to the add, subtract, multiply... functions below. Another function in the class (DoMath in this examples) calls the methods. The user can change the method type (add, subtract,...), so I would like to create a function pointer array (method_pointer), where the method is selected by choosing an integer "method_type". I have a version in C where everything is in one file without being members of a class, where this works fine; however, when the pointer is a member of the class I get "Reference to non-static function" or "Method_pointer is not a function or function pointer" errors. I can't get the syntax correct, any help would be greatly appreciated. Below is a sample program of what I'm trying to do.

Method.h Header

class Method{

void add(int, int, int);
void subtract(int, int, int);
void multiply(int, int, int);
void divide(int, int, int);

void DoMath(int, int, int);

void set_method( const int method_number);

   int method_type;
}; Source

#include "method.h"

typedef void (*method_function)(int, int,int);



void Method::set_method( int method_number){

void Method::add( int a, int b, int c){

void Method::subtract( int a, int b, int c){

void Method::multiply( int a, int b, int c){

void Method::divide( int a, int b, int c){

void Method::DoMath(int x, int y, int result){
   method_function method_pointer[4]={add,subtract, multiply,divide};

int main(int argc, const char * argv[]) {
    Method *method;
    int x=2;
    int y=3;
    int result=0;
    return 0;

c++ interfaces or other ways to maintain heterogeneous but similar types in a container

I am trying to understand c++ interfaces and having some difficulty with this abstract sketch:

class Space {
    virtual bool Open() = 0;
    virtual bool Blocked() = 0;

class EmptySpace : public Space {
    int number_;
    bool open_;
    bool blocked_;

    EmptySpace(int num)
        : number_(num), open_(true), blocked_(false){};
    bool Open();
    bool Blocked();

class Location;

typedef std::unordered_map<Location, Space*, HasherForThisMap> Grid;

So ideally, the way I see this is I can create a stack of Grid maps with varying types of Space types that all fulfill the space interface, without having to create a new map type. What I have isn't working because if I create a maps, and put in a Space type (EmptySpace to start), whenever I pull out a space by a Location key, its values are 0 (or I get some sort of error that dumps out of the compiled program).

Does this make sense and how is it really accomplished in c++? There seems to be a a lot of options, and I'm applying concepts I've learned elsewhere in an attempt to reach a solution. I think I need to understand templates & the c++ class inheritance, though admittedly I'd like to not have to worry through class inheritance issues.

in java, what's the visibility for class variables to its inner class [duplicate]

This question already has an answer here:

For example,

class A(){
  public a;
  protected b;
  private c;

  class innerB(){
   can I access a or b or c???

Thanks for your help.

this, slelf cause an error, Fatal error, Using $this when not in object context

I have a controller file called contactus which inherits from controller class. contactus uses method called loadModel, this method is defined in controller class.
Now, when use loadModel method an error message appears
Fatal error, Using $this when not in object context.

The controller class

class Controller {

    private $app = NULL;

    public function __construct() {
        // return an instance app object which has 'getInstance' method.
        $this->app = &Application::getAppInstance(); 

    protected function loadModel($fileName) {
        if (!file_exists(ROOTPATH . 'models' . DIRECTORY_SEPARATOR . $fileName . '.php')) {
            exit('Unable to locate the model you have specified $fileName');
        return $this->app->getInstance($fileName);

    public function test (){
        echo "Controller/Test.";


The Contactus class that uses loadModel method.

class Contactus extends Controller {
    function __construct() {}

    public function _default(){
        echo "Contactus/default";

Adding a class to an exceptions "data" property

I have a simple class called Coordinate that holds an X / Y Z value.

I am doing some processing and create an "Exception".

I am populating the ex.Data property with some custom values.

All is well until I try to add "new Coordinate(x/y/z)" into the data property.

The data property holds "objects".

An exception is thrown and it is telling me that I can't add objects that are not "serializable" or something like that.

I decided to add 3 entries to the data property (x/y/z respectively as double values) and all is well.

I don't quite understand what I need to add to my class so I could have added just an instance of the Coordinate variable instead.

Class implementation for C++ enum with a lot of feature [duplicate]

This question already has an answer here:

I have checked the suggested duplicated question but it just suggest using a code generator. Here I've discussed about a good alternative solution which its usage is very simple. Following answer supports converting enum to string and vice versa. It also supportsint initialization.

The goal of this post is to prepare good solution to solve C++ Enum problem. Any idea, critic or suggestion is more than welcome.

EDIT: a lot of things have been changed in the answer such as operator overloading and converting the enum type to object of a class that supports default value and a lot of data types conversion. It also supports iostream. please check it and let me know what you think about it.

Unity Null Refrence annoying exception

(Issue is open on GitHub Here)

I am building a health bar for a fighting game in Unity, and for some reason the Health bar text does not appear and all it gives me is a null refrence error, yet I've checked that everything it refrences to is not 'null'.

The code for the text is here:

function Update () {
    canvasText.text = brawlers[0].currentHealth + "/" + brawlers[0]; 
    canvasText2.text = brawlers[1].currentHealth + "/" + brawlers[1]; 

The Brawlers array refers to two classes, each of them like this:

#pragma strict

var className : String;
var health : int;
var Attack : int;
var Defense : int;
var Speed : int; 

I created a prefab with only the class attached and gave the health a value of 120. This prefab is attached to the fighters in the game, which are the brawlers array, as the 'myClass' varible. CurrentHealth is a varible initilized in the Brawler class.

My question is why is there a null refrence exception then?

changing HTML id to class messes up CSS styling

I am wanting to change some items that I have labeled using ids to one single class so that in my css document I can refer to them with .sortsubmenu rather than #sortsongmenu, #sortartistmenu, ...etc.

The problem is that when I change one of them from an id to a class, it messes up the formatting. In the picture below, everything about the songsubmenu and artistsubmenu are exactly the same, only songsubmenu is identified using an id and artistsubmenu is identified using a class. enter image description here

HTML Code:

<div id="topbar">
    <div id="topbar_wrapper">
        <ul id="mainmenu">
            <li><a href="#">Home</a></li><li>
            <a href="#">Search</a></li><li>
            <a href="#">Sort By &#9660</a>
                <ul id="sortmenu">
                    <li><a href='#'>Song</a>
                        <ul id="sortsongmenu">
                            <li><a href='#'>A to Z</a></li><li>
                            <a href='#'>Z to A</a></li>
                    <a href='#'>Artist</a>
                        <ul class="sortsubmenu">
                            <li><a href='#'>A to Z</a></li><li>
                            <a href='#'>Z to A</a></li>
                    <a href='#'>Album</a></li><li>  
                    <a href='#'>Genre</a></li><li>
                    <a href='#'>BPM</a></li><li>
                    <a href='#'>Release Date</a></li>
            <a href="#">Add Song</a></li><li>
            <a href="#">Contact Us</a></li>

CSS Code:

#topbar {
background-color: #222;
#topbar_wrapper {
width: 100%;
margin: 0 auto;
text-align: left;

#mainmenu {
list-style-type: none;
padding: 0px;
margin: 0px;
position: relative;
min-width: 200px;
#mainmenu li {
display: inline-block;
width: 200px;
#mainmenu li:hover {
background-color: #333;
#mainmenu li a{
color: #CCC;
display: block;
padding: 15px;
text-decoration: none;
#mainmenu li:hover > ul {
display: block;

#sortmenu {
display: none;
position: absolute;
background-color: #333;
border: 5px solid #222;
border-top: 0;
margin-left: -5px;
#sortmenu > li {
display: block;
position: relative;
#sortmenu li a:hover {
color: #699;
#sortmenu li: hover ul {
display: inline-block;

#sortsongmenu, .sortsubmenu {
display: none;
position: absolute;
background-color: #333;
border: 5px solid #222;
border-left: 0px;
text-align: right;
top: 0;
left: 100%;
width: 100px;

#sortsongmenu li, .sortsubmenu li{
display: inline;

#sortsongmenu li a:hover, .sortsubmenu li a:hover {
color: #DB7093;

Incredible huge numbers in C# [duplicate]

This question already has an answer here:

In C#, I need to work with very large (and very small) numbers, for which double is not accurate enough and int is not able to store a number big enough.

I'd like to have numbers as big as memory will allow, and if possible hard drive space too.

Does someone have a class or is there a system type for a really big number.

Infinity needn't be represented, but it would be a plus!

Call class using If as rule

I'm new on this Android thing and i dont know how to proceed from this point.

I would like to apply a rule to a button, the idea is simple. I got this button and when i press it, it has two options: it should check the code, if it matches then it start one Activity, if not, keep going as usual.

if it is the "same" as the data base, it goes to this new Activity

else it keep rooling the same class as it is.

I reach to this code, but i got no idea how to proceed from here.

That is my code :

public void Send(View view) throws IOException {
        BdLocal bd = new BdLocal(this);

        if (bd.getCodeCompany() == "0A0A0A0A0A0A0A") {     
            Intent intent = new Intent(NewCompanyCodeActivity.this, NewCompCodeSetup.class);
            startActivityForResult(intent, 0);

        } else {
        //i dont know how to put the cass SendHug here


    class SendHug extends AsyncTask<String, Void, String>{

... }

Separated this Activitys and class work fine


What is a good class structure for a GUI in python pyqt4

I'm new to python and OOP in general so I apologize in advance for my poor vocabulary. I am trying to create an app which generates a data set based on numbers input by a user. I am using PyQt4 to generate the GUI and I understand that an OOP approach is beneficial for this purpose.

My naive choice is to generate the GUI with one class and do the data calculation with another, is this a reasonable approach? I have read various tutorials on class structure and on PyQt but I can't quite put them together. My understanding is that I need to create an instance of my GUI class (inputs) within my calculation class. Since the input numbers change when a button is clicked I am a little lost in how to implement this, if indeed this is what I should be doing. I have tried to reduced my code to a minimal example,

import sys                
from PyQt4 import QtGui    

class UI(QtGui.QWidget):

    def __init__(self):
        super(UI, self).__init__()


    def initUI(self):        

        qbtn = QtGui.QPushButton('Calculate', self)

        qleA = QtGui.QLineEdit(self)
        qleA.move(0, 30)

    def onTextChangedA(self, text):
        B = float(text)
        self.C = B * 10

    def Vals(self):
        if self.C > 50:
            print str(self.C)
        F = [1, 2, 3]


    def Calc(self):
        #some calculations using UI.Vals.F and UI.Vals.C

    def MorCalc(self)
        #more calculations etc...
        #print the output of these calculations when the button is

def main():

    app = QtGui.QApplication(sys.argv)
    Window = UI()
    Calc = CALCULATION()

if __name__ == '__main__':

Notice that I have called both classes in def Main(), I do not know how to call them correctly or if my class definition should be CALCULATION(???):

hackerrank questions error in c++

Whats wrong with my code

plz specify the error where i getting wrong

the question by hackerrank is We can store details related to a student in a class consisting of his age (int), first_name (string), last_name (string) and standard (int).

You have to create a class, named Student, representing the student's details, as mentioned above, and store the data of a student. Create setter and getter functions for each element; that is, the class should at least have following functions:

get_age, set_age get_first_name, set_first_name get_last_name, set_last_name get_standard, set_standard Also, you have to create another method to_string() which returns the string consisting of the above elements, separated by a comma(,). You can refer to stringstream for this.

Input Format

Input will consist of four lines. The first line will contain an integer, representing the age. The second line will contain a string, consisting of lower-case Latin characters ('a'-'z'), representing the first_name of a student. The third line will contain another string, consisting of lower-case Latin characters ('a'-'z'), representing the last_name of a student. The fourth line will contain an integer, representing the standard of student.

Note: The number of characters in first_name and last_name will not exceed 50.

Output Format

The code provided by HackerRank will use your class members to set and then get the elements of the Student class.

Sample Input

15 john carmack 10 Sample Output

15 carmack, john 10


enter code here
#include "stdafx.h"
#include <iostream>
#include <sstream>

using namespace std;

Enter code for class Student here.
Read statement for specification.
class Student{
        int Age;
        string firstName;
        string lastName;
        int Standard;
        void set_age(int);
        void get_age();
        void set_first_name(string);
        void get_first_name();
        void set_last_name(string);
        void get_last_name();
        void set_standard(int);
        void get_standard();
        void to_string();

int main() {
    int age, standard;
    string first_name, last_name;
    cin >> age >> first_name >> last_name >> standard;

    Student st;

    cout << st.get_age() << endl;

    cout << ",";


    cout << endl;


    return 0;

void Student::set_age(int a)
    Age = a;

void Student::get_age()
    cout << Age ;

void Student::set_first_name(string name)
    firstName = name;

void Student::get_first_name()
    cout << firstName;

void Student::set_last_name(string name)
    lastName = name;

void Student::get_last_name()
    cout <<lastName;

void Student::set_standard(int element)
    Standard = element;

void Student::get_standard()
    cout << Standard;


void Student::to_string()
    cout << Age << "," <<lastName <<","
        << firstName <<","<< Standard;

I got the error

while trying to match the argument list '(std::ostream, void)'

Trying to balance my dataset through sample_weight

I'm using RandomForest for classification, and I got an unbalanced dataset, as: 5830-no, 1006-yes.

My code is:

X_train,X_test,y_train,y_test = train_test_split(arrX,y,test_size=0.25)
param_grid = { 'n_estimators': [10,50,100,200,300],'max_features': ['auto', 'sqrt', 'log2']}
sw = np.array([1 if i == 0 else 8 for i in y_train])
CV_clf = GridSearchCV(estimator=clf, param_grid=param_grid, cv= 10,fit_params={'sample_weight': sw})

But I don't get any improvement on my ratios TPR, FPR, ROC

Why? Am I doing anything wrong?

Nevertheless, if I use the function called balanced_subsample, my ratios obtain a great improvement:

def balanced_subsample(x,y,subsample_size):

    class_xs = []
    min_elems = None

    for yi in np.unique(y):
        elems = x[(y == yi)]
        class_xs.append((yi, elems))
        if min_elems == None or elems.shape[0] < min_elems:
            min_elems = elems.shape[0]

    use_elems = min_elems
    if subsample_size < 1:
        use_elems = int(min_elems*subsample_size)

    xs = []
    ys = []

    for ci,this_xs in class_xs:
        if len(this_xs) > use_elems:

        x_ = this_xs[:use_elems]
        y_ = np.empty(use_elems)


    xs = np.concatenate(xs)
    ys = np.concatenate(ys)

    return xs,ys 

My new code is:

X_train,X_test,y_train,y_test = train_test_split(X_train_subsampled,y_train_subsampled,test_size=0.25)
param_grid = { 'n_estimators': [10,50,100,200,300],'max_features': ['auto', 'sqrt', 'log2']}
sw = np.array([1 if i == 0 else 8 for i in y_train])
CV_clf = GridSearchCV(estimator=clf, param_grid=param_grid, cv= 10,fit_params={'sample_weight': sw})


VBA Excel: dynamically created button in a class module runs immediately and only once

I am trying to make class that would create a button. The button should have a macro assigned to it. The macro is a function of the class.

The code of the class module is the following:

'Class Module: btnClass
Option Explicit

Dim btn As Button

Function addButton()
    'Adding a button
    Set btn = ActiveSheet.Buttons.Add( _
        Range("A1").Left, _
        Range("A1").Top, _
        Range("A1").Width, _
    With btn
        'Assigning a function
        .OnAction = Me.onClickAction
        .Caption = "Button"
    End With
End Function

Function onClickAction()
    MsgBox ("Click")
End Function

The code of the main macro is the following:

Option Explicit
Sub main()
    Dim btnInstance As btnClass
    Set btnInstance = New btnClass

    'Calling a function of the instance that creates a button
    Call btnInstance.addButton
End Sub

The code above creates a button successfully. However, the function assigned to the button is run immediately (right after the button is created, not when I click on it), and only once (when you click on the button later, nothing happens).

Is there a way in VBA to implement the required functionality using class modules (want to create a class that does not rely on the outside functions)?

c++ passing a vectored class to another class

I am trying to write my code without using global variable as most people told me it was a bad habit, so I am changing how my program works.

I am having problem with passing multiple instance of a class to another class. I need to be able to modify the multiple instance of a class in the other class.

Here is what I am trying to do but failing miserably at it :

int main() {
Players *player[6];

//preparing 6 instances of Players() so I can loop through them in another class
for (int i = 0;i<6;i++){
player[i] = new Players();
player[0]->name = "fluffy";


#ifndef PLAYERS_H_
#define PLAYERS_H_
#include <string>
#include <vector>

class Players {
    virtual ~Players();
    std::string name;
    bool hand;
    int cif;
    int id;
    std::vector<int> autho;
    std::vector<int> collec;
    std::vector < std::vector <int> > puppet;
#endif /* PLAYERS_H_ */


#include "Players.h"
Players::Players() {
// TODO Auto-generated constructor stub
    name = "";
    hand = false;
    cif = -1;
    id = -1;

Players::~Players() {
    // TODO Auto-generated destructor stub

Now I want to call another class (doesn't matter which) and I want to pass the multi instanced class Players to it so it can read and do modification to the data within these instanced classes.

For example a class with a function that could read player[0]->name and modify it to "sandpaper"

How would you approach this without getting errors from the compiler?

I am open to suggestion for a completely different way to approach this ( I have tried to use struct variables and pass it but I got other problems as well)

thank you, Kaven

mardi 28 juillet 2015

A class that are got instance once by two different application

I created a class for authentication of my project.

I want to use it in my website and also in mobile application but why this class has a static constructor and should be get instance one time, it didn't work well, I mean I want to get instance for each application once.

I want to know how fix it?

Ways to find where an object is contained in Java?

I am having a class which is declared as.

public class StatusMessage {

    private Status status;
    private String message;
    private Throwable throwable;
    private List<StatusMessage> children;

    getters ; setters;

This enables me to have an endless tree like structure of StatusMessages by adding children.

Sample Code to add child.

StatusMessage parent =new StatusMessage(status,message);
parent.getChildren().add(new StatusMessage(status,message));
parent.getChildren().add(new StatusMessage(status,message));
parent.getChildren().add(new StatusMessage(status,message));
StatusMessage child1 =new StatusMessage(status,message);
StatusMessage child1_1 =new StatusMessage(status,message);

Is there any way i will be able to find out that child1 is the parent of child1_1 similarly travel from the lowest level to the root?

I want to achieve this by not adding a reference to parent in the child. Is there any way to do this in Java? Any suggestions?