dimanche 31 mai 2015

Class Not Updating when useing case in javascript

I don't know why the class does not be udpated in following script using the (case):

if (favorite !== null) {
  switch (favorite) {
    case 'cat' : 
    document.getElementById("one").className = "favBlue";

    //document.getElementById('one').className ='favRed';
    //document.createAttribute('class','favRed') 

                break;
    case 'dog' :    document.getElementsByName('dog').className = 'favBlue'; 
                break;
    case 'gerbil' : document.getElementsByName('gerbil').className = 'favYellow'; 
            break;
    case 'gopher' : document.getElementsByName('gopher').className = 'favWhite'; 
            break;
        }

Please click on this link in order to see the complete script http://ift.tt/1I3BXWj




Why can't i use struct nested in a struct as a type to declare variable in a class template? [duplicate]

This question already has an answer here:

You see, i like structs, so i put some structs inside structs and try to use these nested structs in a class template to declare some variables. The only problem is: it just doesn't seem to work as expected. This is my minimal example code:

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

struct T1{
    struct NESTED{
        int var1 = 12345;
    };
};

struct T2{
    struct NESTED{
        float var1 = 67890;
    };
};


template <typename T > class Proletarian{
public:
    T * t;                                       //works
  //T::NESTED * tn;                              //doesn't work!
    Proletarian<typename T>(){
        T::NESTED * tNested = new T::NESTED;     //works
        std::cout << tNested->var1;
    }

};


int _tmain(int argc, _TCHAR* argv[])
{
    Proletarian<T1> t1 = Proletarian<T1>();
    Proletarian<T2> t2 = Proletarian<T2>();
    return 0;
}

I use Visual Studio 2013, Intellisense is ok with my code, but it just won't compile with these two errors:

[Line 20 Column 1] error C2143: syntax error : missing ';' before '*'

[Line 20 Column 1] error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

I'm not that good at C++, so probably don't quite understand how templates work and why this actually happens.




gaussian class in java

I am making a class that simulates a Gaussian integer. I am using a constructor in my addition method to add two the two parts of the gInt and then return a new gInt that is the sum. But for some reason when I am trying to implement this method, Java says that a gInt is required when I initialize the new gInt and that it found a void. Why would this be? I have included the class below and indicated what line causes this error.

public class gInt {

    private int real;
    private int imag;



    public void gInt(int r)
    {
        imag=0;
        real=r;

    }

    public void gInt(int r, int i)
    {
        real=r;
        imag=i;

    }

    gInt add(gInt rhs)
    {
        gInt added;
        int nReal=this.real+rhs.real;
        int nImag=this.imag+rhs.real;

        added= gInt(nReal,nImag);   //--> Says it requires a gInt and found a void

        return added;
    }
}




One class instance used automatically throughout process

The python logging module once imported and instantiated will be so across the process, inside all modules and threads. How did they achieve that effect?

Example:

myapp.py

import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()

mylib.py

import logging

def do_something():
    logging.info('Doing something')

myapp.log

INFO:root:Started
INFO:root:Doing something
INFO:root:Finished




Why does my JFrame come up blank?

so I'm imitating WarioWare for a project but for some reason, in the code which calls the minigames as needed, the JFrame does not pop up with the panel. The screen is white. The weirdest thing is that the classes, when executed by themselves, work perfectly fine. In the upcoming code, all the variables are initialized and all of the classes are accessible. This is not a compiling but rather a run-time error.

Here's the code that integrates all of the minigames:


`import javax.swing.Timer.*;
import java.util.*;
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.event.*; 
import java.awt.geom.*;
import static java.lang.System.*;`


`public class TheFullGame extends JFrame 
{
    private SimonSays game;
    private spiderOrange gameThree;
    private GuessTheNumber gameFour;
    private LuckyerRPG gameTwo;
    private LickMe gameOne;
    private JButton ok, onne, twwo, thrree, foour;
    private JTextField numPlayers, playerName;
    private ArrayList<Player> AllPlayers = new ArrayList<Player>();
    private JPanel panel;
    private Player numbahOne, numbahTwo, numbahThree, numbahFour, thisPlayer;
    private int pointss, current, switchGame, numberOfPlayers;
    public static final Object monitor = new Object();
    public static boolean monitorState = false;
    private boolean zuchini = false, isDone = false, isOkay = false, isOne, isTwo, isThree, isFour, done = false, chosen = false, notYet, raddish, tooFour = false, tooTwo = false, tooThree = false;
    private Random r = new Random();`

    public static void main(String[] args)
    {
        new TheFullGame();
    }

    public TheFullGame()
    {
        JOptionPane.showMessageDialog(TheFullGame.this, "Please Select the number of players, then play the minigames, X-out after and finally, wait until we find out who is the best minigamer of all!", "Instructions", JOptionPane.INFORMATION_MESSAGE);
        letsStart();
    }

    public void letsStart()
    {
        greetings();
    }

    public void greetings()
    {
        this.setSize(1200, 250);
        this.setTitle("How many players?");
        this.setDefaultCloseOperation(HIDE_ON_CLOSE);

        JPanel panel = new JPanel();
        ButtonListener b1 = new ButtonListener();
        onne = new JButton("One Player");
        twwo = new JButton("Two Players");
        thrree = new JButton("Three Players");
        foour = new JButton("Four Players");


        onne.addActionListener(b1);
        twwo.addActionListener(b1);
        thrree.addActionListener(b1);
        foour.addActionListener(b1);


        panel.add(new JLabel("Welcome to Wario Ware inc. After declaring the number of players, each one will play a minigame. Whoever gets the highest score wins!"
        + "\nSelect the number of players."));
        panel.add(onne);
        panel.add(twwo);
        panel.add(thrree);
        panel.add(foour);
        this.add(panel);


        this.setVisible(true);
        this.setLocationRelativeTo(null);
    }

    public void thankYou()
    {
        isOkay = true;
        JOptionPane.showMessageDialog(TheFullGame.this, "Thank you for entering the game!", "Thank you.", JOptionPane.INFORMATION_MESSAGE);
    }

   `public void twoPlayers()
    {
        JOptionPane.showMessageDialog(TheFullGame.this, "Now, it's player One's minigame...", "Player up!", JOptionPane.INFORMATION_MESSAGE);
        switchGame = r.nextInt(3);
        oneGameOnePlayer(numbahOne);`

        while (raddish == false) {}
        if(isDone == true)
        {
            JOptionPane.showMessageDialog(TheFullGame.this, "Now, it's player Two's minigame...", "Next Player up!", JOptionPane.INFORMATION_MESSAGE);
            switchGame = r.nextInt(3);
            oneGameOnePlayer(numbahTwo); 
        }
        pickTheWinner();
    }
    ` 
 `public void onePlayer()
 {`        
    `JOptionPane.showMessageDialog(TheFullGame.this, "Now, it's player One's minigame...", "Player up!", JOptionPane.INFORMATION_MESSAGE);
    switchGame = r.nextInt(3);
    oneGameOnePlayer(numbahOne);`

    pickTheWinner();
 }`


 `public void threePlayers()
 {  `  
        `JOptionPane.showMessageDialog(TheFullGame.this, "Now, it's player One's minigame...", "Player up!", JOptionPane.INFORMATION_MESSAGE);
        switchGame = r.nextInt(3);
        oneGameOnePlayer(numbahOne);`

    `while (raddish == false) {}
    if (isDone == true)
    {`
       JOptionPane.showMessageDialog(TheFullGame.this, "Now, it's player Two's minigame...", "Next Player up!", JOptionPane.INFORMATION_MESSAGE);
       switchGame = r.nextInt(3);
       oneGameOnePlayer(numbahTwo);

       while (raddish == false) {}
       if(isDone == true)
       {
           JOptionPane.showMessageDialog(TheFullGame.this, "Now, it's player Three's minigame...", "Next Player up!", JOptionPane.INFORMATION_MESSAGE);
           switchGame = r.nextInt(3);
           oneGameOnePlayer(numbahThree); 
       }
    }

    pickTheWinner();
 `}`

 `public void fourPlayers()
 {``
        `JOptionPane.showMessageDialog(TheFullGame.this, "Now, it's player One's minigame...", "Player up!", JOptionPane.INFORMATION_MESSAGE);


switchGame = r.nextInt(3);
    oneGameOnePlayer(numbahOne);`

        while(raddish == false) {}
        if (isDone == true)
        {
            JOptionPane.showMessageDialog(TheFullGame.this, "Now, it's player Two's minigame...", "Next Player up!", JOptionPane.INFORMATION_MESSAGE);
            switchGame = r.nextInt(3);
            oneGameOnePlayer(numbahTwo);

            while (raddish == false) {}
            if (isDone == true)
            {
                JOptionPane.showMessageDialog(TheFullGame.this, "Now, it's player Three's minigame...", "Next Player up!", JOptionPane.INFORMATION_MESSAGE);
                switchGame = r.nextInt(3);
                oneGameOnePlayer(numbahThree);

                while (raddish == false) {}
                if(isDone == true)
                {
                    JOptionPane.showMessageDialog(TheFullGame.this, "Now, it's player Four's minigame...", "Next Player up!", JOptionPane.INFORMATION_MESSAGE);
                    switchGame = r.nextInt(3);
                    oneGameOnePlayer(numbahFour); 
                } 
            }
        }

    pickTheWinner();
    }


    public void oneGameOnePlayer(Player potatoPlayer)
    {
        thisPlayer = potatoPlayer;
        raddish = false;
        isDone = false;

        switch(switchGame)
        {
            case 0:
                game = new SimonSays();

                while (raddish == false)
                {
                   raddish = game.isPlayed();
                }

                pointss = game.getPoints();
                addPoints();
                while(zuchini == false) {}
                thisPlayer.newPoints(current);
                break;

            case 1:
                gameOne = new LickMe();

                while (raddish == false)
                {
                   raddish = gameOne.isPlayed();
                }

                pointss = gameOne.getPoints();
                addPoints();
                while(zuchini == false) {}
                thisPlayer.newPoints(current);

                break;

            case 2:
                gameTwo = new LuckyerRPG();

                while (raddish == false)
                {
                   raddish = gameTwo.isPlayed();
                }

                pointss = gameTwo.getPoints();
                addPoints();
                while(zuchini == false) {}
                thisPlayer.newPoints(current);

                break;

            case 3:
                gameThree = new spiderOrange();

                while (raddish == false)
                {
                   raddish = gameThree.isPlayed();
                }

                pointss = gameThree.getPoint();
                addPoints();
                while(zuchini == false) {}
                thisPlayer.newPoints(current);

                break;
            case 4:
                gameFour = new GuessTheNumber();

                while (raddish == false)
                {
                   raddish = gameFour.isPlayed();
                }

                pointss = gameFour.getPoints();
                addPoints();
                while(zuchini == false) {}
                thisPlayer.newPoints(current);

                break;

        }
    }

    public void pickTheWinner()
    {
        if(numbahOne.getPoints() > numbahTwo.getPoints() && numbahOne.getPoints() > numbahThree.getPoints() && numbahOne.getPoints() > numbahFour.getPoints())
        {
               JOptionPane.showMessageDialog(TheFullGame.this, 
                    "Player One Won!!.",
                    "Good Job.",
                    JOptionPane.INFORMATION_MESSAGE);
        }
        else if(numbahTwo.getPoints() > numbahOne.getPoints() && numbahTwo.getPoints() > numbahThree.getPoints() && numbahTwo.getPoints() > numbahFour.getPoints())
        {  
               JOptionPane.showMessageDialog(TheFullGame.this, 
                    "Player Two Won!!.",
                    "Good Job.",
                    JOptionPane.INFORMATION_MESSAGE);         
        }
        else if(numbahThree.getPoints() > numbahOne.getPoints() && numbahThree.getPoints() > numbahTwo.getPoints() && numbahThree.getPoints() > numbahFour.getPoints())
        {
               JOptionPane.showMessageDialog(TheFullGame.this, 
                    "Player Three Won!!.",
                    "Good Job.",
                    JOptionPane.INFORMATION_MESSAGE);
        }
        else if(numbahFour.getPoints() > numbahOne.getPoints() && numbahFour.getPoints() > numbahTwo.getPoints() && numbahFour.getPoints() > numbahThree.getPoints())
        {
               JOptionPane.showMessageDialog(TheFullGame.this, 
                    "Player Four Won!!.",
                    "Good Job.",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    `}`

    public int addPoints()
    {
        zuchini = false;

        if (thisPlayer == numbahOne)
        {
            current = thisPlayer.getPoints(); 
            current = current + pointss;
        }
        else if(thisPlayer == numbahTwo)
        {
            current = thisPlayer.getPoints(); 
            current = current + pointss;
        }
        else if(thisPlayer == numbahThree)
        {
            current = thisPlayer.getPoints(); 
            current = current + pointss;
        }
        else if(thisPlayer == numbahFour)
        {
            current = thisPlayer.getPoints(); 
            current = current + pointss;
        }

        zuchini = true;

        return current;
    }


 `private class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {`
            `JOptionPane.showMessageDialog(TheFullGame.this, "Thank you for entering the game!", "Thank you.", JOptionPane.INFORMATION_MESSAGE);`

                numbahOne = new Player("one", 0);
                AllPlayers.add(numbahOne);

                numbahTwo = new Player("two", 0);
                AllPlayers.add(numbahTwo);

                numbahThree = new Player("three", 0);
                AllPlayers.add(numbahThree);

                numbahFour = new Player("four", 0);
                AllPlayers.add(numbahFour);


            if (e.getSource() == onne)
            {
                numberOfPlayers = 1;
                isOne = true;
                isDone = true;
                onePlayer();
            }
            if (e.getSource() == twwo)
            {
                numberOfPlayers = 2;
                isTwo = true;
                isDone = true;
                twoPlayers();
            }
            if (e.getSource() == thrree)
            {
                numberOfPlayers = 3;
                isThree = true;
                isDone = true;
                threePlayers();
            }
            if (e.getSource() == foour)
            {
                numberOfPlayers = 4;
                isFour = true;
                isDone = true;
                fourPlayers();
            }
        }
    }


Am I calling the class wrong? Please help me....

Thank you




PHP use variable from global space inside class [answered]

Hi I'm writing some code in PHP. I need to use a variable from the global scope inside my class but it doesn't work. I don't know if I need to use namespace or not and how ? Thank you Sample :

<?PHP

$plantask_global_script = array("one", "two");
$plantask_global_config = array("three", "four");
$myvar = array_merge($plantask_global_script, $plantask_global_config);

class Env implements ArrayAccess
{
    static private $container = $myvar;

    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            self::$container[] = $value;
        } else {
            self::$container[$offset] = $value;
        }
    }

    public function offsetExists($offset)
    {
        return isset(self::$container[$offset]);
    }

    public function offsetUnset($offset)
    {
        unset(self::$container[$offset]);
    }

    public function offsetGet($offset)
    {
        return isset(self::$container[$offset]) ? self::$container[$offset] : null;
    }
}




How to structure one to many to many to many data structure Swift

I'm having a hard time figuring out how best to map out a data structure that takes a user, adds brands associated with that user, then adds items of clothing and the user's size (for that brand's item of closing, for that user).

class User {

     var name: String

     class Brands : User {

          var brandName: [String]

          class ItemAndSize : Brands {
               var itemAndSize: [String: Int]
          }

     }

}

Is there a better way to structure this in Swift? I want to be able to store and call user.brandName.itemAndSize.




How to return the value of a pointer in a list?

I've got a "Faction" class, and a vector of pointers which I want to turn into a list. This is the method for it. I assume I've managed to turn the vector of pointers into a list alright in the first part, so now I want to print the list out within my method. I know by using the '*', I'm printing out the memory location as opposed to the value, and that's exactly what this code is doing.

list<Faction*> Faction::linklistFactions() {
    list<Faction*> list_factions(factionptr_.begin(), factionptr_.end());
    cout << "printing linked list:" << endl;

   for (int a = 0; a < list_factions.size(); a++)
   {
      std::list<Faction*>::iterator i = list_factions.begin();
      advance(i, a);
      cout << *i;
      cout << ",";
   }

   return list_factions;
}

But I want to print out the value, not the memory location. So instead of

cout << *i;

I can do something like

cout << i->getFactionname();

I am already able to do this for my vector, it was simple enough:

string Faction::getFactionname() const
{
     return factionname_;
}

But I'm having trouble coming up with a similar method for my list. It doesn't work the same, and I'm not sure why. Perhaps there's another way?




how do I allocate a pointer to a class with multiple inheritance

Suppose I have:

class Human {
    string choice;
public:
    Human(string);
};

class Computer {
    string compChoice;
public:
    Computer(string);
};

class Refree : public Human, public Computer {
public:
    string FindWinner();
};

int main() {
    Human* H1 = new Human("name");
    Computer* C1 = new Computer("AI");
    Refree* R1 = new Refree();
}

This code fails to compile with:

 In function 'int main()':
error: use of deleted function 'Refree::Refree()'
note: 'Refree::Refree()' is implicitly deleted because the default definition  would be ill-formed:
error: no matching function for call to 'Human::Human()'
note: candidates are:
note: Human::Human(std::string)
note:   candidate expects 1 argument, 0 provided

Why does this fail, and how can I construct a pointer to Refree?




Python NameError The class of the name is not defined but it actually is

I was playing with classes and I thought to create a class called Container which is meant to group all things that can hold other things.

# -*- coding: utf-8 -*-

class Container(object):
    def __init__(self, name, volume):
        self.name = name
        self.max_volume = volume

hands = Container('HANDS', 2)

I started from this point and then I wanted to test if everything was ok but if in the python console I call hands.name it says that hands is not defined. This happens when I import it as a module too.

I don't get what I am doint wrong! Can you please explain me how to make it work?

I get from the python console:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'hands' is not defined




Too few template arguments error while trying to pass a list of pointers as a parameter?

I've made this "Socialite" class, and a separate "Faction" class. One of the arguments for the Socialite object is a vector of pointers to "Factions". I had used the Socialite class earlier without the 'factionlist' as a parameter, and it worked fine.

class Socialite
{
public:

 Socialite();
 Socialite(string lastName, string firstName, string userId, string picture, string website, string description, list<Faction*> factionlist);

 //other methods

 void newSocialite(string lastName, string firstName, string userId, string picture, string website, string description, list<Faction*> factionlist);
 void deleteSocialite(string lastName, string firstName, string userId, string picture, string website, string description, list<Faction*> factionlist);

 //other methods

private:

 string lastName_;
 string firstName_;
 string userId_;
 string picture_;
 string website_;
 string description_;

 vector<Socialite *> socialiteptr_;
 list<Faction*> factionlist_;



};

When I included it however, I get the errors:

 error C2976: 'std::list' : too few template arguments  

and

 error C2065: 'Faction' : undeclared identifier 

on the same line every time my method/constructor contains a factionlist. The solutions I looked up involved code using templates, and I'm not using any, so I don't understand what's wrong.

Extra info: My vector of pointers is stored in such a way:

 vector<Faction *> factionptr_;

And I make it into a list in such a way:

 list<Faction*> list_factions(factionptr_.begin(), factionptr_.end());

What am I doing wrong?




c# TypeConverter ConvertTo Value Always Null

I might be overlooking something, but its driving me crazy. This is not the first time using a TypeConverter, but its the first time its giving me this kind of problem.

I'm trying to save a custom class into the .properties, but the value of the class im saving ends up being null when I try to convert it to a string, even if there are suppose to be values present in the class.

Custom Class:

[TypeConverter(typeof(Da_AutoLogin_Converter))]
public class Auto_Login
{
    public string Username;
    public string Password;

    public Auto_Login(string Username, string Password)
    {
        this.Username = Username;
        this.Password = Password;
    }
}

And heres the code when i'm creating a new instance of the class, with default values;

Auto_Login AL;
AL = new Auto_Login(txt_User.Text, txt_Pass.GetPassword());
MessageBox.Show(AL.Username); //Works, Displays Correctly
Properties.Settings.Default.AutoLogin = AL; //Something Happens Here

And this is my ConvertTo Function located in the TypeConverter:DA_AutoLogin_Converter

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
    if (destinationType == typeof(string))
    {
        if (value is Auto_Login)
        {
            string RETURN = "";
            Auto_Login AL = (Auto_Login)value;
            RETURN += AL.Username + "█" + AL.Password; //Both Ends Up Being Null For Some Reason
            return RETURN;
        }
    }
    return base.ConvertTo(context, culture, value, destinationType);
}

The username and password ends up being null. I have 4 other custom classes I'm saving into the .Properties, and I never had a problem with anything being null. What am I doing wrong with this one?




Access properties of Class in melonJS

I'm using melon js (melon State) to make a game and am adding cutscenes. I'd like to access the draw property on my Cutscene object so I can change the text as needed.

    var myState = new game.CutsceneScreen();    
    me.state.set(me.state.USER, myState);

How do I access the draw method in a class such that I can update the text?


console.log(myState) outputs "Class {}"

And

console.log(myState.font) outputs "undefined" even though I'm setting the font property in the object: this.font = new me.BitmapFont("32x32_font", 32);

Class:

game.CutsceneScreen = me.ScreenObject.extend({ 
        onResetEvent : function() { 
                me.game.world.addChild( 
                        new me.Sprite ( 
                                0,0, 
                                me.loader.getImage('cutscene_screen') 
                        ), 
                        1 
                ); 
                me.game.world.addChild(new (me.Renderable.extend ({ 
                        init : function() { 
                                this._super(me.Renderable, 'init', [0, 0, me.game.viewport.width, me.game.viewport.height]); 
                                this.font = new me.BitmapFont("32x32_font", 32); 

                        }, 
                        update : function (dt) { 
                                return true; 
                        }, 
                        draw : function (context) { 
                                this.font.draw (context, json cutscene text, 20, 240); 
                        }, 
                        onDestroyEvent : function() {} 
                })), 2); 
                me.input.bindKey(me.input.KEY.ENTER, "enter", true); 
                me.input.bindPointer(me.input.mouse.LEFT, me.input.KEY.ENTER); 
                this.handler = me.event.subscribe(me.event.KEYDOWN, function (action, keyCode, edge) { 
                        if (action === "enter") { 
                                this.text = next json  
                                //if you get to end of cutscene json array... then load play screen... 
                                me.state.change(me.state.PLAY); 
                        } 
                }); 
        }, 

        onDestroyEvent : function() { 
                me.input.unbindKey(me.input.KEY.ENTER); 
                me.input.unbindPointer(me.input.mouse.LEFT); 
                me.event.unsubscribe(this.handler); 
        } 
}); 




Store class variable in dictionary

I am making a program that will have a box that receives two inputs, an event name and the time allocated for the event, and will later output a list of all the events that have been added. This is the class for the input boxes:

class agendaEvent:
    def __init__(self, master):
        self.frame = Frame(master, padx=10, pady=10)
        self.frame.grid()
        self.name = Entry(self.frame)
        self.name.grid(row=1, column=0)
        self.time = Entry(self.frame, width=10)
        self.time.grid(row=1, column=1, padx=5)

I am fairly new to programming, but I believe the correct way to store the name and time would be in a dictionary.

There could be multiple instances of the class running at the same time and more could run after these have already been stored. It would be preferable to have them all stored in the same dictionary.

However, I do not know how to store the self variables in a dictionary that I could later access outside of the class. Is this possible? If so, how? If not, how could I store the variables in a way that they could be accessed in a separate function?




When is my struct too large?

We're encouraged to use struct over class in Swift.

This is because

  1. The compiler can do a lot of optimizations
  2. Instances are created on the stack which is a lot more performant than malloc/free calls

The downside to struct variables is that they are copied each time when returning from or assigned to a function. Obviously, this can become a bottleneck too.

E.g. imagine a 4x4 matrix. 16 Float values would have to be copied on every assign/return which would be 1'024 bits on a 64 bit system.

One way you can avoid this is using inout when passing variables to functions, which is basically Swifts way of creating a pointer. But then we're also discouraged from using inout.

So to my question:
How should I handle large, immutable data structures in Swift?
Do I have to worry creating a large struct with many members?




Loop through array to get element class without using getElementsByClassName

I am not experienced with jQuery and am having some issues that I feel like are pretty basic problems that I am not understanding fully. My project requires me to create a function that gets passed an array of elements, and I need to loop through these elements to verify if they have a class identifier or not.

Also, if one of those elements is a parent element, and the child element has a class identifier, run the same function on that child, using a recursive function.

My understanding of how to implement a recursive function is fine, but my understanding of jQuery and how to find a class is not. Here is what i have so far, which is not that great but that's why I am here.

var argArray = [
    '<p class="foundClassName"></p>',
    '<p class="anotherClassName foundClassName"></p>',
    '<p><p class="foundClassName"></p></p>',
    '<p><p class="foundClassName"><p class="foundClassName"></p></p>   </p>',
    '<p><p></p><p><p class="foundClassName"></p></p></p>',
    '<p><p class="foundClassName"></p><p class="foundClassName"></p> </p>',
    '<p><div class="somediv"><div class="innerdiv"><span   class="foundClassName">yay</span></div></div></p>'
];

var findElementsByClassName = function(className){


    var elementArray = $(className).get();

    for(var i = 0; i < elementArray.length; i++) {
        if(elementArray[i].className === className) {
            console.log(elementArray[i]);
        }
    }
};

console.log(findElementsByClassName(argArray));

So my thought process was this:

  1. Loop through the passed array.
  2. If the array element is a parent, run .get() on that and call the function on this returned array to find class.
  3. If an array element does not have child elements, check for a class and return a boolean.

My above code is completely wrong, but I think my thought process is correct. I have zero experience with jQuery so far and would like some help in trying to put my idea into action. For example, running the above will show that $ is not defined, which is understandable but if the variable is not an actual page, how can I use this jQuery variable? I think I need to stick with jQuery because that is how I can use .get(), right? My apologies for the shambolic code but I wanted to at least give an idea of where my thought process was going. Thanks for any help.




difference between declaring an object on class level and in methods

A is another class outside of test

case 1

public class Test{



      A testObj;

      public static void main(String[] args){
         testObj=new A();
         testObj.methodInsideClassA();
      }
}

case 2

 public class Test{


      public static void main(String[]  args){
         A testObj = new A();
         testObj.methodInsideClassA();
      }
}

so whats the difference between them? and what should i use?




.NET - Importing class with connection to database

I want to import a class to another class so that I don't have to write the same code X times.

I have a file with the connection to the database called connectDB.vb.

Imports MySql.Data.MySqlClient

Namespace connectDB1
    Public Class connectDB
        Dim connection As New MySqlConnection("Server=localhost; UserId=root; 
                                Password=root; Database=something")

        Public Sub doConnection()
            Try
                connection.Open()
            Catch ex As Exception
                MsgBox("Error")
            End Try
        End Sub
    End Class
End Namespace

And I want to import connectDB.vb to File1.vb

Imports MySql.Data.MySqlClient
Imports MyApp.connectDB1

Public Class File1

    Dim connectDataBase As New connectDB
    Dim connection As New MySqlConnection("Server=localhost; UserId=root; Password=root; Database=something")

    Private Sub File1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'doConnection()
        connectDataBase.doConnexion()
    End Sub

    'Private Sub doConnection()
    '    Try
    '        connection.Open()
    '    Catch ex As Exception
    '        MsgBox("Error")
    '    End Try
    'End Sub

    Private Sub addProduct()
        Dim dbcomm As MySqlCommand
        Dim dbread As MySqlDataReader

        If txtBoxQuantity.Text <> "" And txtBoxPrice.Text <> "" And txtBoxProduct.Text <> "" Then
            dbcomm = New MySqlCommand("insert into products (price, stock, name) values(@price, @stock, @name)", connection)
            dbcomm.Parameters.AddWithValue("@price", txtBoxPrice.Text())
            dbcomm.Parameters.AddWithValue("@stock", txtBoxQuantity.Text())
            dbcomm.Parameters.AddWithValue("@name", txtBoxProduct.Text())
            dbread = dbcomm.ExecuteReader() ' GIVES ERROR
            dbread.Close()
        End If
    End Sub

    Private Sub add_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles agregarProducto.Click
        addProduct()
    End Sub
End Class

But when I run this code that it's suposed to save the data in the DB it gives me this error:

InvalidOperationException was unhandled. Connection must be valid and open.

connectDB.vb connects to the database since I debugged and it connects to the DB, but when I want to do some sql sentence in the File1.vb it gives that error.

Without trying to import the class the code works, but I'm just trying to improve my code, as you can see the commented code is the code I used to connect to the database.




Why can't extend DisplayObject then instantiate

The DisplayObject class can be extended but the extended class cannot be instantiated.

Class:

package{
  class Extended extends DisplayObject{

              import flash.display.DisplayObject;


   public function Extended(){
      super()

    }

  }
}

Main timeline:

var e:Extended=new Extended();

addChild(e);

Error:

ArgumentError: Error #2012: Extended$ class cannot be instantiated.




c++ exprected primary-expression before

Schönen guten Tag,

ich versuche derzeit mit c++ eine Klasse zu schreiben und stoße da gerade auf etwas das ich nicht verstehe. Neben bei angemerkt ich bin hier neu und in c++ auch wie man vermutlich gleich merken wird, also sorry, wenn ich etwas offensichtliches falsch mache.

#include <iostream>
#include <string>

using namespace std;


class homepage
{
   private:
      string user = "Andre267";
      string pw = "abc1234";
      string rechte = "Admin";

   public:
      void login(string, string);
      void logout();
      void status();
      bool stat = 0;

};

void homepage::login(string user, string pw)
{
    if(user == this->user && pw == this->pw)
    {
       this->stat = 1;
       cout << "Wilkommen ["<< this->rechte << "] " << this->user;
    }
    else
       cout << "Benutzername und oder Passwort sind falsch! \n";
}

void homepage::logout()
{
    if(this->stat == 1)
    {
       this->stat = 0;
       cout << "Sie wurden erfolgreich ausgelogt.";
    }
    else
       cout << "Sie sind nicht eingelogt!";
}

int main
{
    homepage seite;

    cout << "Benutzername: ";
    cin >> user;
    cout << "Passwort: ";
    cin >> pw;

    seite.login(user, pw);


    return 0;
}

Als Fehlermeldung bekomme ich das hier:

10 21 Z:\video\c++ projekte - material\homepage.cpp [Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default] 11 19 Z:\video\c++ projekte - material\homepage.cpp [Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default] 12 23 Z:\video\c++ projekte - material\homepage.cpp [Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default] 18 19 Z:\video\c++ projekte - material\homepage.cpp [Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default] 44 5 Z:\video\c++ projekte - material\homepage.cpp [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default] 46 11 Z:\video\c++ projekte - material\homepage.cpp [Error] expected primary-expression before 'seite' 46 11 Z:\video\c++ projekte - material\homepage.cpp [Error] expected '}' before 'seite' 46 11 Z:\video\c++ projekte - material\homepage.cpp [Error] expected ',' or ';' before 'seite' 48 2 Z:\video\c++ projekte - material\homepage.cpp [Error] 'cout' does not name a type 49 2 Z:\video\c++ projekte - material\homepage.cpp [Error] 'cin' does not name a type 50 2 Z:\video\c++ projekte - material\homepage.cpp [Error] 'cout' does not name a type 51 2 Z:\video\c++ projekte - material\homepage.cpp [Error] 'cin' does not name a type 53 2 Z:\video\c++ projekte - material\homepage.cpp [Error] 'seite' does not name a type 56 2 Z:\video\c++ projekte - material\homepage.cpp [Error] expected unqualified-id before 'return' 57 1 Z:\video\c++ projekte - material\homepage.cpp [Error] expected declaration before '}' token

Kann mir dabei jemand helfen?




Can you alter an ES6 class definition to attach new instance methods?

Is there any way to retroactively (i.e. after the class has already been defined) add instance methods to an ES6 class?

Consider the following class:

class Thing {}

I'd now like to attach a hello method to Thing, which would then be callable on its instances like so:

let thing = new Thing();
thing.hello();

Is it possible?

(Sure, I could make a subclass, but that's not what I'm asking here.)




Assignment is treated as initialization [duplicate]

This question already has an answer here:

I've written the following and expected a to be initilized with 4 rvalue. But it didn't:

struct A
{
    const int a;

    A() //ctor-initializer is not specified, therefore no initialization for a is performed
    {
        a = 4; //initialization
    }
};

A a;

What's wrong? Why does compiler complain?




Error message in classes

I have this code (Beginning stages)

program project1;

uses crt;

type
   Vehicle = class
   private
      reg_no : integer;
      engine_size : real;
   public
      constructor create();
      calculate_hire_fee;

   Car = class
   private
      hire_charge_per_day : integer;
      number_of_passengers : integer;
   public
      constructor create();
      calculate_hire_fee;

   Truck = class
   private
      hire_charge_per_hour : integer;
      maximum_payload : integer;
   public
      constructor create();
      calculate_hire_fee;
end;

I get this error message:

project1.lpr(12,7) Error: Fields cannot appear after a method or property definition, start a new visibility section first project1.lpr(12,25) Fatal: Syntax error, ":" expected but ";" found

What is wrong>




Creating a static class with no instances

All of the tutorials I see online show how to create classes with __init__ constructor methods so one can declare objects of that type, or instances of that class.

How do I create a class (static in Java) so that I can access all methods and attributes of that class without having to create new instances/objects?

For example:

class World:

    allElems = []

    def addElem(x):  

        allElems.append(x)

World.addElem(6)
print(World.allElems)


EDIT

class World(object):

    allAirports = []

    @staticmethod
    def initialize():

        f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
        file_reader = csv.reader(f)

        for col in file_reader:

            allAirports.append(Airport(col[0],col[2],col[3]))

error: name 'allAirports' is not defined




Best way to future proof software that opens files with default application interactively

I have created a VB .NET application that opens files in their default application - extracts information and returns it to a listview on a form.

All of the code is in my main form. The main form has in it

  • Imports Microsoft.Office.Core
  • Imports Microsoft.Office.Interop.Word
  • Imports Microsoft.Office.Interop.Excel

If in the future I want to modify my software to include another filetype not thought of in this release, am I better off for all of the filetypes I wish to open (including office) adding new classes for each filetype and including the 'Imports' in the individual classes?

So for example I would have:

  • OpenFileDWG.vb
  • Imports Autodesk.AutoCAD.Runtime

  • OpenFileDOC.vb

  • Imports Microsoft.Office.Interop.Word

etc. etc. Is this a standard approach? If I were to do this, could I use:

If exists LCase(My.Computer.FileSystem.GetFileInfo(Filepath).Extension) THEN strFileOpener = OpenFileDWG & Extension Private fileOpener As strFileOpener

Would this approach work, or would I still need to reference the .dll in the main application, making this approach unworthy?

If I were to use this approach, could I just give the .vb file as part of an update?

Any advice is much appreciated.




I want C++ learn, but i dont know, how write Class C++ in this exercise

I want to learn C++ and i have found this exerciese. I have written a class before but this is a bit harder!

#include <iostream>
#include <map>

using namespace std;

//My code! :-)
class calendar
{
    private:
        int year;
        int month;
        int day;
        int hour;
        string text;
    public:

    calendar() {}


    void insert(int y,int m, int d, int h, string s)
    {
        year=y;
        month=m;
        day=d;
        hour=h;
        text=s;
    };
};


//The exercise!
int main()
{
    calendar my_calendar;
    my_calendar.insert(1987,05,19,10,"C++");    //insert
    my_calendar.insert(1987,05,19,11,"C++");    //insert
    my_calendar.insert(1987,05,19,10,"C++");    //False!! - Not Insert!
    return 0;
}




Class and variable

I'm triying to create a game on java. The game is working and now I would like to create a class with the high score. The variable "score" already exists in one class, and I created a variable highscore in a another one.

In the second class I wrote :

if (highscore < score) {
highscore = score;}

But it doesn't recognize the variable "score" even if all the class are in the same package and the variables and the class are public... Does somebody can help me?




Access public variables of class in another class both are extending CI_Controller class codeigniter php

I want to access public variables of one class login without extending the other class check in codeigniter Here Variable is $fb_data in class login Here is my code of class login

class Login extends CI_Controller
{

  public $fb_data;
    public function __construct()
    {
        parent::__construct();
        $this->ci =& get_instance();
        $this->load->library(array('session', 'lib_login'));
        $this->load->model('users_model');
        if (!isset($this->fb_data['me']) ) {
          $this->fb_data = $this->lib_login->facebook();
        }                

    }
     public function facebook()
    {               
        if (isset($this->fb_data['me'])) {
            echo "<pre>";
             var_dump($this->fb_data);
            echo "</pre>";                 
            echo '<a href="'.site_url("login/destroy").'">logout</a>';
        } else {
            echo '<a href="' . $this->fb_data['loginUrl'] . '">Login</a>';
        }
    }
}

Here is my code of class check

class Check extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library(array('session', 'lib_login'));
        $this->load->model('users_model');                       
    }       
    public function index()
    {        
        if (isset($this->fb_data['me'])) {
            echo "<pre>";
             var_dump($this->fb_data);
            echo "</pre>";     
            echo '<a href="'.site_url("login/destroy").'">logout</a>';
        } else {
            echo '<a href="' . $this->fb_data['loginUrl'] . '">Login</a>';
        }
    }


}

but whenever i call check/index function it gives me this errore

Message: Undefined property: Check::$fb_da

Is their any way i can access the $fb_data Thanks in advance.




Intellisense not working on classes in ASP.NET (StyleCop installed)

I got a little trouble with ASP.NET. I installed StyleCop (this is a must from school). After the installment I created an empty web application. From here I added some classes. Within these classes I cannot use intellisense for some reason. This makes programming almost impossible. On the other hand the strange thing is, intellisense does work in a regular app like winforms. At the moment I tried the following:

  • Remove all addons
  • re-checked the intellisense in text editor in the options menu
  • reboot visual studio
  • reboot computer

Anyone got some experience with this?

Thanks in advance




Nested class in a namespace versus nested class in another class

When does one nest a class in another class and when does one nest it in a namespace. What are the advantages/disadvantages of both. Thanks.




samedi 30 mai 2015

Where C++ calls destructors?

Assuming Member and MyList are two user defined classes. In the following code:

void fillList(MyList &list1)
{
    Member m1("aaa");
    Member m2("bbb");
    list1.insert(m1);
    list1.insert(m2);   
}

void func1()
{
    MyList lst;
    fillList(lst);
    lst.printAll();
}

int main()
{
    func1();
    return 0;
}

At which point does C++ call destructor of each m1, m2 and lst?

Is it always safe to assume C++ does not remove an object which will be used again?




Do we have pool of Objects for Wrapper classes too?

I would like to clarify few of queries. As i know Wrapper classes are final too and immutable. So do they have pool of objects just like String class did? and also are there immutable versions for Wrapper classes? String class has Immutable versions like StringBuilder and StringBuffer.




Trying to remove vector pointer duplicates. Why can't I use .erase()?

I've got a vector of pointers for my "Faction" class, stored in such a way:

vector<Faction *> factionptr_;

At this point, I am already able to sort my vector in alphabetical order, so I figured I could use this code here to remove any duplicates that'd show up next to each other:

void Faction::deleteDuplicateFaction(vector<Faction *> &factionptr_){

 for (int i = 0; i < factionptr_.size()-1; i++){

      if (factionptr(i)->getFactionname() == factionptr(i + 1)->getFactionname()){
            cout << "it's the same" << endl;

            factionptr_.erase(factionptr(i));
      }

But I'm getting an error at .erase() and I don't understand:

    IntelliSense: no instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=Faction *, _Alloc=std::allocator<Faction *>]" matches the argument list
        argument types are: (Faction *)
        object type is: std::vector<Faction *, std::allocator<Faction *>>   

Now I understand that I could be using iterators for this, but I'm not too familiar with them yet. I am definitely not averse to a solution involving iterators though.

Perhaps there's another way?

factionptr is this:

Faction * Faction::factionptr(int k) const{
 if ((k < 0) or(k > numberOfFactions())) // elementary error checking
      return NULL;

 return factionptr_[k]; // returns a pointer to the k-th daughter

}




Defning a namespace class in a header file

I have a similar problem to this but not the exact.

Assuming we have 2 header files and a main.cpp. In the first header file we have :

  namespace Logic
  {
    class GameManager;
  }

In the second header:

#include "first_header.h"
class Logic::GameManager 
{
public : 
    void init();
    void run():
};

And in the main.cpp i have :

#include "first_header.h"
int main()
{
   Logic::GameManager::GameManager gm;
   gm.init();
   gm.run();
}

I get this error until i include the second header in main.cpp :

'gm' uses undefined class 'Logic::GameManager::GameManager'

-Is this way of using namespaces and classes correct ?

-Is there a better way to do this?

Thanks.




Trouble outputting vector to .txt file

I've been struggling with this for some time now and I'm finally reaching out for help. I'm reading in data from a text file via the readData function. Within that function I'm calling a function of the ELement Class to read in Element data to a vector of vectors. I'm then then trying to write the data to a text file via the writeData function, and this is where my problem is. When I compile and run, the outputfile contains all other data that I'm writing to it except the Element data. I also need to be able to access this Element data via other functions.

Any help, tips, or insight would be greatly appreciated. I've included what I believe is the pertinent code below. If more is necessary, just let me know.

Thanks!

readData Function:

void readData::readdata(ifstream &inp)
{
        
        Element r;

        r.addelementdata(inp);
                
};

addelementdata Function:

void Element::addelementdata(istream& inp) 
{
        int i,j,tmp;

        for (i = 0; i < d_numElems; i++)
        {
                vector<int>row;
                for (j = 0; j < 10; j++)
                {
                        inp >> tmp;
                        row.push_back(tmp);

                }
        elems_matrix.push_back(row);
        }
        
}

output matrix contents Function:

void Element::Elems_matrix_contents(ofstream& out)
{
        int i, j;
        
        for (i = 0; i < d_numElems; i++)
        {
                for (j = 0; j < 10; j++)
                {
                        out << elems_matrix[i][j] << '\t';
                }
        }
}

Element Class:

class Element: public readData
{
protected:
        std::vector< std::vector<int> > elems_matrix;
        
public:
        // Constructors
        Element();
        
        //Destructor
        ~Element(){};
        // Functions
        void addelementdata(istream&inp);
  
        std::vector<std::vector < int >> elems_matrix_copy;
  
        void Elems_matrix_contents(ofstream& out);
                
};

readData Class:

class readData 
{
public:
        
        readData();
  
        ~readData(){};
  
        void readdata(ifstream &inp);
        void writedata(ofstream &out);

};



Access variable within a nested class in Python

I'm having trouble with exactly what the title says. I have this code at one point:

class eventAdd:
    def __init__(self):
        class agendaEvent:
            def __init__(self, master):
                self.frame = Frame(master, padx=10, pady=10)

Later on, outside of the class eventAdd, but on the same level as eventAdd, I have:

def addEvent():
    instance = eventAdd()
    doneButton = Button([PROBLEM AREA], text="Done", command=done)

Where I have typed [PROBLEM AREA] is, quite obviously, the problem area. I want to create doneButton inside the frame inside agendaEvent inside eventAdd. Is it possible to reference a variable inside an init inside a class inside an init inside a class for use like this? If so, how?

I apologize for any programming sins I may have committed. I am fairly new to programming and I am not yet sure what the best way to go about things are. Any suggestions are welcome.

Thanks in advance.




Call a function passed inside a list which is inside a class

I am a novice in Python and I was trying to program a game like Adventure.

I created a class called Room. In this class there is a function called ask_something in which I can pass a question and as many list as I want for the possible answers. Lists contain the possible answer and the effect of that answer which is another function.

How can I call that function whithin the Room class without knowing what function is it?

this is the code:

class Room:
    def ask_question(self, *arg):
        self.question = arg[0]
        self.answer_options = arg[1:]

        for option in self.answer_options:
            print '[{}] {}'.format(self.answer_options.index(option), option[0])

        answer = raw_input('> ')

        do_something = self.answer_options[int(answer)][1]

        do_something()

def print_this(text):
    print text

Room.ask_question(
    'How are you?',
    ('Fine!', print_this('ok')),
    ('Not fine!', print_this('I\'m sorry'))
)

The Python console says TypeError: 'NoneType' object is not callable




When to use $this->$property

I am having trouble understanding when and why you need to use $this->$property. So adding the $ to both the the this keyword and the property. I have only seen this used within the magic methods __get() and __set(). Can anybody elaborate?




Reading a file into Ruby program

so I have the following contents within a csv file:

id,name,description,ingredients,directions

1,Kale Burger,Combining the taste of cow with the nutrition of kale!,"Kale, Cow","Preheat oven to 500 degrees, put in a cow. Wait 10 minutes. Put in some kale. Take out cow and kale. Put on bun. Serve HOT!"

2,Poodle Cake (For your puppy!),Poople cakes! Perfect for pet poodle!,"Kibble, Hot dogs",Mix kibble with hot dog. Bake at 500 degrees for 25 minutes. DO NOT ADD CHOCOLATE

3,Peanut Butter Coffee Brownie,Just looking has caused people to gain 10 pounds!,"Chocolate, Peanut Butter, Espresso, Cream Cheese","Chew the espresso beans to a pulp, spit them into the bowl. Now mix in the chocolate, cream cheese, and peanut butter. Bake at 450 for 45 minutes"

Each of them are on a new line, 4 lines in total. I have created a Recipe class so that each one of my recipe's can be a separate object. Here is my recipe class for starts:

class Recipe
  attr_reader :id, :name, :description, :ingredients, :directions

  def initialize(args)
    @id           = args[:id]
    @name         = args[:name]
    @description  = args[:description]
    @ingredients  = args[:ingredients]
    @directions   = args[:directions]
  end
end

I'm trying to find a way to link these. I have created a separate class to hopefully store all of my recipes, like in an array. I just cant figure out how I could read the file in and split it up appropriately through a method. Any ideas would be great.




Making a class remove itself

I am making a program using Tkinter that will create a list of events. I used a class to make an event. If I click the Add Event button (second script shown), it creates a new instance of the class, lengthening the list. However, I also want to be able to remove events from the list. I am trying to attach a remove button to each class that, when clicked, will delete the class. This is my code from the class script (classes.py):

from Tkinter import *

class agendaEvent:

    def __init__(self, master):
        self.frame = Frame(master, padx=10, pady=10)
        self.frame.pack(side=TOP)
        self.name = Entry(self.frame)
        self.name.grid(row=1, column=0)
        self.time = Entry(self.frame, width=10)
        self.time.grid(row=1, column=1, padx=5)
        self.label1 = Label(self.frame, text="Event Name")
        self.label1.grid(row=0, column=0)
        self.label2 = Label(self.frame, text="Minutes")
        self.label2.grid(row=0, column=1)
        self.remove = Button(self.frame, text="Remove", command=agendaEvent.remove)
        self.remove.grid(row=1, column=3)

    def remove(agendaEvent):
        del agendaEvent

When I press the remove button, I get the error

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
    return self.func(*args)
TypeError: unbound method remove() must be called with agendaEvent instance as first argument (got nothing instead)

How can I call the instance of agendaEvent? Or is there a better way of going about this? This is the code for the main script (main.py):

from Tkinter import *
import classes


def addEvent():
    classes.agendaEvent(root)

root = Tk()

addEventButton = Button(root, text="Add Event", command=addEvent)
addEventButton.pack(side=BOTTOM)

root.mainloop()




Class 'AuthorizeNetDPM' not found

I have followed the instructions from here: authorize.net

But I've got an error saying Class not found.

This is my index.php

<?php

    require_once __DIR__.'/vendor/autoload.php';
    include __DIR__.'/src/Handler/Handlers.php';

?>

This is my Handlers.php post:

class Handlers
{
   public function post()
        {
            $url = "http://ift.tt/1lV42pj";
            $api_login_id = 'YOUR_API_LOGIN_ID';
            $transaction_key = 'YOUR_TRANSACTION_KEY';
            $md5_setting = 'YOUR_API_LOGIN_ID'; // Your MD5 Setting
            $amount = "5.99";

            AuthorizeNetDPM::directPostDemo($url, $api_login_id, $transaction_key, $amount, $md5_setting);
        }}

How do I inherit the authorize vendor inside my handlers?




designing class diagram to my project i must include dialoge sand jframes as Classes?

I'am creating a project documentation the project is

Question management and generating system (whatever)

i'am designing now the Class Diagram

my question is :

i have a lot of dialogs and frames since i'm programming in java , should i include the gui's with the diagram and relate it with other control classes?

Thanks




Get PARENT CLASS NAME of UI element (button, label, textfield)

I am trying to get the class name of a UIViewController through one of its UI elements. When called in the following manner, the class method returns the correct name (eg: myViewController):

NSLog(@"Class name: %@", NSStringFromClass(self.class));

But when called like this, it only returns UIView:

UIButton *button = [[UIButton alloc] init];
[self.view addSubview:button];
NSLog(@"Class name: %@", NSStringFromClass(button.superview.class));

If I have reference to the button object, in another class for example, how could I get the actual name of its parent class?




It's me, again with the java graphs not appearing

based on my previous question I have learned that extending JFrame and JPanel is bad. So I have decided to ditch the idea and learnt how to code a frame, and its components ( I'm still learning by the way). But eventhough I have done the buttons, I cannot seem to display my graph, and I am at my wits end now.

Below here is my first class, which has all the panels established and declared ( forgive me if the term is incorrect)

package testCODE;

public class OurUI {

        static Color kaler;

       private JPanel mainpanel = new JPanel();
       private JButton colorbutton1 = new JButton("Green");
       private JButton colorbutton2 = new JButton("Red");
       private JButton colorbutton3 = new JButton("Blue");
       private JPanel graphpanel = new JPanel();
       private JComponent[] GUIcomponents = { colorbutton1, colorbutton2, colorbutton3 ,};






        public OurUI(){


          for (JComponent comp : GUIcomponents) {
         mainpanel.add(comp);
      }

      }


      public JComponent getmaincomponent(){
          return mainpanel;
      }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

         @Override
         public void run() {

            OurGUI();


                           }              
                                                  }               
                                );
                  }

These lines below is the method in which I create the JFrame ( without extending of course)

   private static void OurGUI(){

                    OurUI ourUI = new OurUI();

                    JFrame guiframe = new JFrame("FUNCTIONAL DEPENDENCY");
                    guiframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    guiframe.getContentPane().add(ourUI.getmaincomponent());
                    guiframe.pack();//this code is for resizing the components, automatically so that we don't have to set the size
                    guiframe.setLocationByPlatform(true);
                    guiframe.setSize(500,450);
                    guiframe.setVisible(true);



        guiframe.getContentPane().add(DrawGraph.paintComponent());
                     }

}   

Yes, this line is wrong, which proves that I am calling the class in a wrong sense, albeit I cannot figure it what it is.

'guiframe.getContentPane().add(DrawGraph.paintComponent());'

These lines below are my other class, "DrawGraph". I'm not really good at coding, but I'm sure I did not call the class properly, just don't know how

        class DrawGraph{
            DrawGraph drawgraph = new DrawGraph();
            static boolean lukis = true;   

            DrawGraph(){

            }



            int oldY = 0;
            double degToRad (int deg)
        {
            return ((2*Math.PI)/360.0) * deg;
        }

        int scale (int i, int width)
        {
            return (int) ((i/(double)width)*720.0);
        }


    public void paintGraph(Graphics g) {
        //super.paintGraph(g);


        g.drawLine(0, 100, 400, 100);//X-axis
        g.drawLine(200, 0, 200, 200);//Y-axis
        g.drawLine(400, 100, 390, 90);//arrow pointing rightwards
        g.drawLine(400, 100, 390, 110);//arrow pointing rightwards
        g.drawLine(200, 0, 190, 10);//arrow pointing upwards
        g.drawLine(200, 0, 210, 10);//arrow pointing upwards

        g.drawString("X", 400, 80);//draw 'X' label
        g.drawString("Y", 220, 10);//draw 'Y' label

        g.drawString("\u03C0/2", 240, 120);//draw ' 1/2 Pi' label
        g.drawString("\u03C0", 290, 120);//draw 'Pi' label
        g.drawString("2\u03C0", 400, 120);//draw ' 2 Pi' label
        g.drawString("3\u03C0/2", 340, 120);//draw ' 3/2 Pi' label


        g.drawString("-\u03C0/2", 140, 120);//draw 'negative 1/2 Pi' label
        g.drawString("-\u03C0", 87, 120);//draw 'negative Pi' label
        g.drawString("-2\u03C0", 0, 120);//draw 'negative 2 Pi' label
        g.drawString("-3\u03C0/2", 30, 120);//draw ' 3/2 Pi' label



        g.drawString("0", 205, 110);//draw '0' label
        g.drawString("0.77", 175, 50);//draw '0.77' label for half Pi
        g.drawString("1", 175, 10);//draw '1' label for a Pi
        g.drawString("-0.77", 170, 150);//draw '0.77' label for half Pi
        g.drawString("-1", 185, 200);//draw '1' label for a Pi


            int width = 400;
            int height = 200;

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

                int y = (int) Math.round((-Math.sin(degToRad(scale(i,width)))+1)*height/2.0);
                if (lukis && i>0)
                {

                    g.drawLine(i-1, oldY, i, y);


                } else {
                    g.drawLine(i, y, i, y);

                }
                oldY = y;
            }
    }
        }




python multiple nested classes

This is going to look like class inheritance but I think it is not and there must be an easy way of doing the following. Take a look at this simple code:

class Land:
    def __init__(self):
        print "a new Land"
        self.farms = []

    def addfarm(self):
        self.farms.append(Farm())


class Farm:
    def __init__(self):
        print "a new farm"
        self.animals = []

    def addanimal(self,name):
        self.animals.append(Animal(name))

class Animal:
    def __init__(self, name):
        print "hi, I am %s" % name
        self.name = name


USA = Land()
USA.addfarm()
USA.farms[0].addanimal('George')
USA.farms[0].addanimal('Martin')
USA.addfarm()
USA.farms[1].addanimal('Polly')
USA.farms[1].addanimal('Ralph')

Is there an easy way of getting all animals without doing?:

for eachfarm in USA.farms:
    for each in eachfarm.animals:
        print each.name

I am asking this because if for instance the user wants to add a new George to farm 0 I would like to quickly be able to say that name is taken. I would also be able to quickly run a function that gives me all animals in the land or all farms. Should I be writing functions for all that or Python got its own?

I am also interested on knowing if my nested class structure is not correct and could end up causing issues.

For instance, lets say I have a function that given an animal tells me the perfect food mix for it. I would like to be able to run that function on all my animals and write back into their object. If they are nested I am afraid the function may get confused!

Thanks!




Adding custom class object to an NSArray updates existing objects

I've got a UIView in a viewController:

myView = [[rhythmUIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[self.view addSubview:myView];

The UIView exposes an NSArray in its .h:

@interface rhythmUIView : UIView
@property () NSMutableArray* myHits;
@end

And instantiates and initializes it in the UIView's .m:

NSMutableArray* myHits;
myHits = [[NSMutableArray alloc] init];

To which I add objects of a custom class:

@interface hits : NSObject
@property () double hitTime;
@property () float xPosition;
@end

in the viewController.m using

hits *thisHit;
thisHit = [[hits alloc] init];
<set thisHit's properties>
[myView.myHits addObject:thisHit];

All of that works - no compile or runtime errors, but when I change the values of the thisHit object in preparation to add a new object to the myHit array, it updates the value of every object that was previously inserted using thisHit.

This seems like an attribute problem, so I added a property to the custom class:

@property (copy) NSNumber* test;

And set it with:

thisHit.test = [NSNumber numberWithFloat:arc4random()%100];

Before the addobject. But it also modifies every row when I touch thisHit.

I didn't expect adding "copy" to the array to work:

@property (copy) NSMutableArray* myHits;

And it didn't. Same results.

I even tried adding this to the ViewControoler.m:

@property (copy) hits* thisHit;

Same results.

Tried insertObject:atIndex: instead of addObject: Same results.

I messed around with strong and weak in desperation, but then it actually started crashing.

Finally, learning from my last post, I tried moving the instantiation of the array from the UIView.m to the UIView creation in the viewController.m:

myView.myHits = [NSMutableArray new];

I had high hopes for that one, but again, no compile or runtime errors, but it was worse. The addobject doesn't actually do anything - the nsarray.count remains at zero.

Help please? Thanks!




Python thread locking/class variable initialisation confusion

I have a class which behaves strangely if accessed by multiple threads. The threads are started during sklearn's GridSearch training (with jobs=3), so I don't know exactly how they are called.

My class itself looks roughly like this:

from sklearn.base import BaseEstimator, TransformerMixin
import threading

class FeatureExtractorBase(BaseEstimator, TransformerMixin):
    expensive_dependency = {}
    lock = threading.lock()
    is_loaded = False

    @staticmethod
    def load_dependencies():
        FeatureExtractorBase.lock.acquire()
        if not FeatureExtractorBase.is_loaded:
            print('first request, start loading..')
            # load dependencies, takes a while
            FeatureExtractorBase.is_loaded = True
            print('done')
        else:
            pass
        FeatureExtractorBase.lock.release()

class ActualExtractor(FeatureExtractorBase):
    def transform(self, data):
        FeatureExtractorBase.load_dependencies()
        # generate features from data using dependencies
        return features

This class uses what I hoped would be lazy initialization. Initializing it right away lead to problems, I can't do that any more. And since the class gets reinitialized a couple of times during one program call, initializing the data in the constructor each time would waste time. Now, problem is that this doesn't work the way I want it to, this is the output:

Starting training
Fitting 3 folds for each of 1 candidates, totalling 3 fits
first request, start loading..
first request, start loading..
first request, start loading..
done.
done.
done.
Done   1 jobs       | elapsed:   56.2s
Done   3 out of   3 | elapsed:  1.0min finished

Starting evaluation
first request, start loading..
done.

Not only enter three threads what I thought would be a locked region at the same time, one minute later during tests, the same region gets entered again -- despite that is_loaded should have been set to True at that point.

This is the first time I handle threads in Python, and I am still very clumsy with classes, so I am sure I am doing something wrong here. But I can't see what or where.




C++ Prompt User to continue or leave

Actually i was just trying my hands upon C++ and stopped at this particular problem where instead of program getting closed, it should ask the user whether he/she wants to continue or wants to exit. Now for what i understand, i wrote the do-while code in ending lines but its not working. Please gimme a solution to it. Thanks!!

#include<iostream>
#include<stdio.h>
#include<cstdlib>
#include<string>

using namespace std;

class Cal
{
    public:
    int Add(int a, int b)
    {
        int res;
        res=(a+b);
        cout << "Answer is " << a << "+" << b << "=" << res << endl;
    }
    int Sub(int a,int b)
    {
        int res;
        res=(a-b);
        cout << "Answer is " << a << "-" << b << "=" << res << endl;
    }
    int Mul(int a,int b)
    {
        int res;
        res=(a*b);
        cout << "Answer is " << a << "*" << b << "=" << res << endl;
    }
    int Div(int a,int b)
    {
        int res;
        res=(a/b);
        cout << "Answer is " << a << "/" << b << "=" << res << endl;
    }
};

int main()
{
    int first, second, res, operation;

    cout<<"**********************************"<<endl;
    cout<<"******* Simple Calculator ********"<<endl;
    cout<<"**********************************"<<endl;
    cout<<"Select the Operation: "<<endl;
    cout<<"1. Addition"<<endl;
    cout<<"2. Subtraction"<<endl;
    cout<<"3. Multiplication"<<endl;
    cout<<"4. Divison"<<endl;
    cout<<"Choosen Operation is: ";
    cin>>operation;
    cout << "Enter the 1st Number: ";
    cin>>first;
    cout << "Enter the 2nd Number: ";
    cin>>second;

    switch(operation){
    case 1:
        Cal a;
        a.Add(first,second);
        break;
    case 2:
        Cal b;
        b.Sub(first,second);
        break;
    case 3:
        Cal c;
        c.Mul(first,second);
        break;
    case 4:
        Cal d;
        d.Div(first,second);
        break;
    default:
        cout<< "Please Enter a Operation";
        break;
    }

    char ans;
    do
    {
       cout<< "Do you want to continue (Y/N)?\n";
       cout<< "You must type a 'Y' or an 'N' :";
       cin >> ans;
    }
    while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n'));
}




When I click select button after category button, why isn't the String being printed and null being printed instead?

    package simpleclass;

    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import javax.swing.JButton;
    import javax.swing.JFrame;


    public class SimpleClass extends BaseClass{

    JButton b1=new JButton("Category");
    JButton b2=new JButton("Select");
    JFrame f=new JFrame();

    SimpleClass(){
    f.add(b1);
    f.add(b2);
    f.setLayout(new GridLayout(1,2));
    f.setSize(200, 200);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

    b1.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    new SubClass();
                } catch (IOException ex) {

                }
               }
           });
    b2.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(astring);
               }
           });
         }

          public static void main(String[] args) {
          new SimpleClass();
          }
         }


         class BaseClass
         {

          String astring ;
          public void setString(String astring) 
          {
          this.astring = astring;
          } 

        }



          class SubClass extends BaseClass
        {
          SubClass() throws FileNotFoundException
          {

          super.setString("WHYnull");

          }

        }

In this code there is one base class "BaseClass" and two subclasses "SimpleClass" and "SubClass". There are two buttons. When the button "Category" is pressed, then the String "astring" is being set to "WHYnull". Now my question is that when I press "Select" Button after that, why is null being printed? Isn't the variable "astring" exclusive?




C++: Problems reading input from a binary file

I have a class AccountManagement in AccountManagement.cpp. I have another class called Account in Account.cpp. I have a template that Orders the given data inside the list using OrdereList class, which also has it's own iterator. The AccountManagement class outputs the Accounts list in a binary file as shown below:

void AccountManagement::saveData(const char * file) //saves data in the specified binary file
{
    ofstream out(file, ios::out | ios::binary);
    if(!out)
    {
        cerr<<"Problem opening output file!"<<endl;
    }   
    OrderedList<Account>::iterator it = this->account_manager.begin();
    for(int i = 0; i < this->total_accounts; i++)
    {
        Account temp = *it;
        out.write((char*)&temp, sizeof(Account));
        it++;
    }
    out.close();
}

I have defined a following function inside AccountManagement class that reads all the data from binary file and outputs it. This function works perfectly fine. It is shown here:

void AccountManagement::output()
{
    ifstream in("accounts.dat", ios::in | ios::binary);
    if(!in)
    {
        cerr<<"File doesn't exist!"<<endl;
        exit(1);
    }
    Account acc;
    while(in.read((char*)&acc, sizeof(Account)))
    {
        cout<<acc;
    }
    in.close();
}

However, when I use this same function (with different name) in another file, which has Account.h header file as well to retrieve data from the same "account.dat" file it gives me segmentation fault. What could be the problem? Following is the function:

void loadData()
{
    ifstream in("accounts.dat", ios::in | ios::binary);
    if(!in)
    {
        cerr<<"File doesn't exist!"<<endl;
        exit(1);
    }

    Account acc;
    while(in.read((char*)&acc, sizeof(Account)))
    {
        cout<<acc;
    }
    in.close();
}

Account's class declaration:

class Account 
{
    friend ostream& operator<<(ostream&,const Account&); //overloading << operator
    friend istream& operator>>(istream&,Account&); //overloading >> operator
    public:
        void operator=(const Account&); //overloading = operator
        bool operator<=(const Account&); //overloading <= operator
        bool operator<(const Account&); //overloading < operator

    private:
        string number; //Account Number
        char name[100]; //Account holder's name
        char sex; //M or F indicating the gender of account holder
        MYLIB::Date dob; //date of birth of account holder
        char address[100]; //address of account holder
        char balance[20]; //balance of account holder
};




How to best add multiple fields to a

This is more a question of "technique". I am trying to create a class in Python that will have a certain number of variables. What would be the best way to store them?

I would like some sort of structure that allows me to quickly retrieve the values without writing further functions:

a = myclass()
a.add('name','John')
a.add('age',30)
b = myclass()
b.add('a complete different attribute','value')

and then:

print a.name
John

or

print a.retrieve('name')
John

I know I can do that by having a two columns list on the class that gets populated when I do add and write a function that retrieves a certain value. But I was wondering if Python had something already built in so reading the code is simplified.

Thanks




Define VB Excel.Chart event that always works

I am not a pro and my question may be easy but I wasn't able to solve it even after a time of research. Is it possible to create a Excel Chart Event (it is Calculate) that works for the Charts even if the Excel file is saved, closed and re-opened ? I am using Visual Studio 2008. I think the proper way to do it would be in defining a class, but how do I match the Charts calculate event with the classes event? Your answers would be a great help.




When dynamically loading a class in java

Suppose in java I'm dynamically loading class A.
Class A uses both java standard library classes and
user defined classes.
I'm wondering what is the classloader that has to load all of the classes used by A ?

thanks




Error in creating a new type in c++

I just started to learn c++ and i have the following problem in this simple code:

enum class color_type {green,red,black};

color_type color(color_type::red);

I get the error "color_type is not a class or namespace". My goal is to create a variable of type color_type that can only take values red, black and green. Could you please help me? Thank you




vendredi 29 mai 2015

Get Elements by Class name without using document.getElementsByClassName

I need to create a function that will effectively do what getElementsByClassName does, but I have to implement this myself. The problem is I cannot find much other than the Mozilla site that show much about what this is and what it does, but nothing about how it does it. Can anyone help in pointing me in the right direction as I just need a resource to help me understand this, and I am fairly confident I can get to the finish point from there.




Instantiating all possible combinations of enums

I'm having trouble iterating over all possible combinations of enums. I'm not too familiar with them as I've just started C# and am coming in from low level languages like C and assembler.

public enum enumA { A1, A2, A3 }
public enum enumB { B1, B2, B3 }

public class foo
{
    private enumA enumAfoo;
    private enumB enumBfoo;

    public foo()
    {
    }
    public foo(enumA A, enumB B)
    {
        enumAfoo = A;
        enumBfoo = B;
    }
}

public class fooTwo
{
    private List<foo> allCombinations = new List<foo>();
    public fooTwo()
    {

    }
    public List<foo> GetList()
    {
        return allCombinations;
    }
    public fooTwo(bool check)
    {
        if (check)
        {
            foreach (enumA i in Enum.GetValues(typeof(enumA)))
            {
                foreach (enumB j in Enum.GetValues(typeof(enumB)))
                {
                    allCombinations.Add(new foo(i, j));
                }
            }
        }
    }
}

When I run this code in a simple check output, I don't get what I'm after. Sample Main below. The output I get is just "TestingGround.foo" repeated 6 times, testing ground being my overall namespace. I Don't know if there's a problem with my logic of instantiating the list, or with how I'm converting it to string and outputting but I'd very much like some help in what's the correct procedure for doing this.

class Program
{
    static void Main(string[] args)
    {
        fooTwo A = new fooTwo(true);
        List<foo> list = A.GetList();
        foreach (foo j in list)
        {
            Console.WriteLine(j.ToString());
        }
        Console.ReadKey();
    }
}




What's the difference between these three similar Python classes? They all do the same (?)

All these classes run, and their outward behavior is the same, but I'm not convinced that they are all the same thing (by this I mean indistinguishable except for their names). Unfortunately, I'm not getting any errors by running this code - anyone know what's going on?

--RandNum1--

class RandNum1:
    a = 2

#do stuff

b=RandNum1()
b.a

c=RandNum1
c.a

--RandNum2--

class RandNum2():
    a = 2

#do stuff

b=RandNum2()
b.a

c=RandNum2
c.a

--RandNum3--

class RandNum3(object):
    a = 2

#do stuff

b=RandNum3()
b.a

c=RandNum3
c.a




Java : Hangman Game

I have a project I'm working on for my Java-class and I think I've pretty much finished the game. However, when I tested it before I submitted it, I ran into a problem.

Whenever I test the game, and I guess a single letter correctly, it will say I've finished the game. Everything looks perfectly fine to me, perhaps a fresh pair of eyes would do me some good. I'm tired.

Here's my main class, followed by the constructor's class.

http://ift.tt/1HTj3Eb

http://ift.tt/1Rwxq2Z

I appreciate any help you guys can give me, I just don't see where I messed up.




Replacing an instance declaration

I would like to replace an instance declaration of a standard type of Haskell library. For example, replacing the Show instance for boolean by :

instance Show Bool where
  show True  = "Vrai"
  show False = "Faux"

But when I try to do it, I get this error :

Duplicate instance declarations:
  instance Show Bool -- Defined at Exemples01.hs:37:10
  instance Show Bool -- Defined in `GHC.Show'

Is it possible to replace an instance declaration with Haskell ?




Location of event components in a multi class situation

I am trying to understand how events should be properly constructed when you have more than one class. For instance if you have class that detects value and you want to update a text box in a form, where should the event components be placed. From what I read:

Event component - [Location]
1. Delegate - [Globally visible location]
2. Event pointer - [Inside the class that triggers the event]
3. Event method - [Inside the class that triggers the event]
4. (OnEvent) method wrapper - [Inside the class that triggers the event]
5. Code that wires the event - [Inside the form???]

Is this in the ball park? Can 3&4 be located in a class outside the one that triggers the event?
Thanks




No PHP Error shown but also no Output

First sorry for my bad English, it's late here ^^

I got the following test.php

<?php
include_once "classes/Page.class.php";
include_once "config/db_conn.php";
include_once "config/configuration.php";
echo "Hi";
echo LANGUAGE . "." . CHARSET;
var_dump($db);
$p = new Page($db);
$p->setTitle("Testpage");
echo $p;

My Problem is, that i don't see any errors when i trying this. it only works, if i comment all the Page stuff out. So the Error must be in the Page.class.php File. By the way, it's my first PHP class.

Here it is.

<?php

require_once "../config/configuration.php";

class Page
{
    private $title;
    private $content;
    private $pdo;
    private $language;
    private $charset;
    private $style;
    private $base;
    private $error_array;
    private $error_bool;
    private $success_array;
    private $success_bool;
    private $directory;
    private $locale_config;
    private $lang_coding_config;

    public function __construct(&$pdo, $language = "", $charset = "", $style = "style.css", $base = "/", $languagecode = "")
    {
        $this->directory = dirname(__FILE__).'/../locale';
        if(empty($languagecode)) {
            $this->locale_config = LANGUAGE . "." . CHARSET;
        }else{
            $this->locale_config = $languagecode;
        }
        $this->title = '';
        $this->content = [];
        $this->pdo = &$pdo;
        if (empty($language)) {
            $this->language = PAGE_LANGUAGE;
        }else{
            $this->language = $language;
        }
        if(empty($charset)) {
            $this->charset = CHARSET;
            $this->lang_coding_config = CHARSET;
        }else{
            $this->charset = $charset;
            $this->lang_coding_config=$charset;
        }
        $this->style = [];
        $this->base = $base;
        $this->addStyle($style);
        $this->error_array = array(
            error_message    => "",
            error_code  => ""
        );
        $this->success_array = array(
            success_message => "",
            success_code => ""
        );
        $this->error_bool = false;
        $this->success_bool = false;
        echo "Construct";
    }

    public function setError($error_message,$error_code){
        $this->error_bool = true;
        $this->error_array['error_message'] = $error_message;
        $this->error_array['error_code'] = $error_code;
    }

    public function setSuccess($success_message,$success_code){
        $this->success_bool = true;
        $this->success_array['success_message'] = $success_message;
        $this->success_array['success_code'] = $success_code;
    }
    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function setLanguage($language)
    {
        $this->language = $language;
    }

    public function setCharset($charset)
    {
        $this->charset = $charset;
    }

    public function addStyle($style)
    {
        $this->style [] = $style;
    }

    public function setBase($base)
    {
        $this->base = $base;
    }

    public function addContent($content){
        setlocale(LC_MESSAGES, $this->locale_config);
        bindtextdomain(LANG_FILE_NAME, $this->directory);
        textdomain(LANG_FILE_NAME);
        bind_textdomain_codeset(LANG_FILE_NAME, $this->lang_coding_config);
        $this->content[] = $content;

    }

    public function __toString()
    {
        $str = '
<!DOCTYPE html>
<html lang=' . $this->language . '>
  <head>
    <meta charset=' . $this->charset . ' />
    <title>' . $this->title . '</title>
    <base href=' . $this->base . ' />';
        foreach ($this->style as $s) {
            $str .= '<link rel="stylesheet" href=' . $s . ' />';
        }
        $str .= '</head>
  <body>
    <main>';
        if($this->error_bool) {
            $str .= '<div class="box error">';
            foreach ($this->error_array as $c) {
                $str .= 'Fehlermeldung: ';
                $str .= $c['error_message'];
                $str .= ' Fehlercode: ';
                $str .= $c['error_code'];
                $str .= '<br />';
            }
            $str .= '</div>';
        }
        if($this->success_bool){
            $str .= '<div class="box success">';
            foreach ($this->success_array as $c) {
                $str .= $c;
                $str .= '<br/>';
            }
            $str .= '</div>';
        }
        foreach ($this->content as $c) {
            $str .= $c;
        }
        $str .= '
    </main>
  </body>
</html>';

        return $str;
    }
}

and the configuration file contains these lines at the beginning.

<?php


error_reporting(E_ALL);
ini_set('display_errors', 1);

Any help is appreciated.




How to access an object from a different class in Swift

I'm scrambling my mind as to how I should correctly do it. I subclassed CollectionViewCell were I add different labels, animations and buttons.

I am trying to delete a cell and update the collectionView in one of my methods in this class(CollectionViewCell) but I'm unable to access collectionView from here.

My CollectionView Class:

class FirstViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

@IBOutlet weak var collectionView: UICollectionView!
required init(coder aDecoder: NSCoder)
{
    super.init(coder: aDecoder)
} 
}

My CollectionViewCell Class:

class CollectionViewCell: UICollectionViewCell {

func handlePanGesture(recognizer: UIPanGestureRecognizer) {

 FirstViewController.collectionView.reloadData()//

  }




String Replace Java Function

  1. I tried to Replace in multiple classes an multiple Strings with a function
  2. Why does this example not Work?

    public static String symbole(String sym)
     {  
    sym = sym.replace("&" , "§");
    sym = sym.replace("[<3]" , "\u2764");
    return sym;
    }
    String test = "This Dont work... why [<3]";
    symbole(test);
    
    

how can i replace this... any Suggestion? Please help and sorry for my perfect english




Java - Pass Class as Parameter for Comparison

Essentially what I want to do is pass a class as a parameter so that I can preform an instanceof comparison.

public class MyClass
{
    Object o = something;

    public void myMethod(Class c)
    {
        if(o instanceof c)
        {
            do something
        }
    }
}

Where the parameter Class c is any class that I choose to pass in from else where. Essentially I want to be able to pass in any class and make a comparison.

Any help would be appreciated.

Thanks




Setting items from a list to another list (both containing class instances) in random groups in python

I have two lists containing instances from two classes. I want to assign groups of items from the first list to the second. I have the right method add_agent. I just don't know how to iterate and exhaust both lists in the right order.

For example: 20 Agents assigned to 5 Families in random groups of 0, 1, 2, 3 or 4.

My code so far:

def allocate_to_family(families, agents):
    for dummy_agent in agents:
        for dummy_family in families:
            num_members = numpy.random.choice(4)
            while num_members != 0:
                dummy_family.add_agent(dummy_agent)
                num_members -= 1

Thanks a bunch!




PHP - cannot define class function parameter which is instance of the same class

I'm using Laravel 5 and its User class.

I want to add addFriend() function which will accept parameter of the same class "User".

app/User.php

namespace App;

// Laravel defined use statements...

class User extends Model
implements AuthenticatableContract, CanResetPasswordContract {

  /** Way 1
  *
  * FatalErrorException in Model.php line 956:
  * Class 'User' not found
  */
  public function addFriend(User $user) {
    $this->friends()->attach($user->id);
  }

  /** Way 2
  *
  * FatalErrorException in Model.php line 956:
  * Class 'User' not found
  */
  public function addFriend(\App\User $user) {
    $this->friends()->attach($user->id);
  }

  /** Way 3
  *
  * ErrorException in User.php line 50:
  * Argument 1 passed to App\User::addFriend() must be an instance of User, 
  * instance of App\User given...
  */
  public function addFriend(\User $user) {
    $this->friends()->attach($user->id);
  }

}

Is there a way to accept the parameter only if it's instance of the User class in this function?
Can you explain to me where I am wrong?




Best way to include relative path with file array

I'm new to C# and need advice on how to proceed with a problem:

I'm writing code to sync folders. To determine if two files are the same file I need to compare their relative paths (subfolders from their base directory and filename). I've created a FileInfo array with the following code:

for (int y = 1; y <= nf; y++)
            {
                this.Title = "Folder Sync - Getting files from folder " + y;
                DirectoryInfo basedir = new DirectoryInfo(dirs[y]);
                dirf[y] = basedir.GetFiles("*", SearchOption.AllDirectories).OrderBy(item => item.FullName).ToArray();
            }

However, the FileInfo Class does not have a RelativePath property. Here are options I've considered: 1. Create a separate string array with just the relative path for each file as file.FullName.Substring(basedir.FullName.Length)

  1. Calculate the relative path every time I need it.
  2. Put both the FileInfo Objects and the RelativePath strings in an Object array
  3. Extend FileInfo properties (apparently not available with current C#)
  4. Create a derived class myFile info with a Relative path field/property. Fill that in with the Relative path when making the myFileInfo array.

I just tried 5, but was running into the error "Cannot implicitly convert FileInfo[] to myFileInfo[]". After reading up on constructors to try to fix this, I decided to take a step back and ask if this is even the right approach.

So, general question: What is the best practice way of dealing with this? Specific question: How do I include RelativePath for each file?




Find an object within a list and replace its value

I have the following list and class:

List<MyClass> MyList

public class MyClass
{
    public int id { get; set; }
    public bool checked { get; set; }
}

I also have the two variables:

int idToFind = 1234;
bool newcheckedvalue = true;

What I need to do is search the list and find the MyClass object where the id equals that value of idToFind. Once I have the object in the list, I then want to change the value of the checked property in the class to that of the newcheckedvalue value.

LINQ seems to be the solution to this problem, I just can't get the expression right. Can I do this in a single LINQ expression?




VBA Class : Collection.item member is a collection . How to retrieve sub collection item elements

I have this template data

Header of file ((string1, string2...) group1 header (string1, string2...) group1/line1 (string1, string2...) group1/line2 (string1, string2...) group2 header (string1, string2...) group2/line1 (string1, string2...) group2/line2 (string1, string2...)

Note : The datas belonging to group header and group line are different type even if they are on the same 'coloumn' (raw data comes from text file)

I create my main class (populate collection) and data class (populate item : cData_Nomination), everything works individualy BUT I need to create :

-1 file collection (I have multiples files) which store -- fields (file header) and -- x sub collection (groups) wich store --- fields (group header) --- x sub collection which store ---- fields (line data)

In the folowing code on line 170 .oDpo is the group collection every data are store on a collection with property Let (....). Everything seem to be store !

Public Function NomCreate(m_sFilepath As String, m_objDataList() As String, m_clDpo As Collection) As cData_Nomination

10        On Error GoTo Err_Handler
          Dim Functions As New cFunctions
          Dim objResult As cData_Nomination
          Dim objDate() As String



      'Note : Init Var(s) /Object(s)
      '----------------------------

20        Set objResult = New cData_Nomination

30        With objResult
40            .FileName = Functions.String_NZ(m_sFilepath)
50            .DataSource = Functions.String_NZ(m_objDataList(1))
60            .DelRes = Functions.String_NZ(m_objDataList(2))
70            .DateTime = Functions.Date_NZ(m_objDataList(4) & " " & m_objDataList(5) & ":00")
80            objDate = Split(Replace(m_objDataList(6), " - ", "-"), "-")
90            .DateTimeRange_Start = Functions.Date_NZ(objDate(0))
100           .DateTimeRange_End = Functions.Date_NZ(objDate(1))
110           .Sender = Functions.String_NZ(m_objDataList(7))
120           .Receiver = Functions.String_NZ(m_objDataList(8))
130           .GasPointName = Functions.String_NZ(m_objDataList(9))
140           .GasPointNameExternal = Functions.String_NZ(m_objDataList(10))
150           .Description = Functions.String_NZ(m_objDataList(11))
160           .DataType = Functions.String_NZ(m_objDataList(12))
170           .oDpo = Dpo
180       End With

Err_Exit:
          'Note : Return Function value
190       Set NomCreate = objResult
          'Note : Delete object
200       Set objResult = Nothing
          'Note : Exit
210       Exit Function

Err_Handler:
          'Note : Exit Function
220       GoTo Err_Exit

When I try to read data i got a problem I can't access to the collection .oDo via property Get (see the following code)

'property belonging to class cData_Nomination
Public Property Let oDpo(ByVal oCollection As Collection)
    Dim m_oDpo As New Collection
    Set m_oDpo = oCollection
End Property

How can I pass collection to an existing item collection (I might have been wrong) and How can i retrieve my sub collection items from the main collection ?

I hope it's clear ...

Thanks in advance