lundi 31 octobre 2016

Referencing a static variable with an event handler in c#

I am unsure how to reference a static variable using an event handler. I am trying to set Output = ""; each time the Execute button is clicked, so that it starts each Traverse method empty. This is what I have.

  public static String Output = "";

        public string Traverse(Node rootNode)
        {           

            if (rootNode != null)
            {
                Traverse(rootNode.left);
                Output += rootNode.data + "\r\n";
                Traverse(rootNode.right);
            }

            return Output;
        }

   public void btnExecute_Click(object sender, EventArgs e)
    {
        Output = "";
        txtOutput.Text += "\r\nInorder Traversal of Nodes";
        txtOutput.Text += "\r\nRoot Node: " + btree.root.data + "\r\n";
        txtOutput.Text += btree.Traverse(btree.root);
    }

but obviously the first line in the event handler is saying the name Output does not exist in the current context. How do I reference it?




How do I create a new instance of class using values from an existing class in Ruby?

I am trying to understand how to create a new instance of a class from within an existing class in Ruby. I found one example, on Stack Overflow, but it isn't clear how the values from the existing class get passed to the new instance. (If I am using the terminology right).

In the example below, I have two classes, RaceCar and RaceDriver. When initialized RaceDriver sets the name, experience=0, winnings=0 and makes sure there is no car assigned yet.

When initialized RaceCar sets the number of the car, the type, damage=0, racing_status :ready, and sets the driver.

What I want to do is create a method in the RaceDriver, set_driverscar, that creates a car for the driver, creating RaceCar.new but setting the driver to the name of the RaceDriver. It does not matter if it is in initialization or not, I am just trying to figure out.

How would I do this like in the example below?

I have been beating my head on this for a bit, and I must be missing something obvious but I just cannot figure it out OR find a good example that explains how to do this?

Can you help me with an answer so I can learn what I am missing here?

class RaceDriver

  attr_accessor :name, :experience, :winnings, :car

  def initialize(attrs = {})
    set_name(attrs [:name])
    @experience = 0
    @winnings = 0
    @car = nil
  end

  private

  def set_name(obj)
    obj == nil ? no_name : @name = :name
  end

  def no_name
    raise 'There is no name for this driver'
  end

end

class RaceCar

  attr_accessor :racing_number, :type, :damage, :racing_status, :driver

  def initialize(attrs = {})
    @racing_number = generate_number
    @type = "stock"
    @damage = 0
    @racing_status = :ready
    set_driver(attrs[:driver])
  end

  def disable
    @racing_status = :disabled
  end

  private

  def generate_number
    rand(20..99)
  end

  def set_driver(obj)
    obj == nil ? no_driver : @driver = obj
  end

  def no_driver
    raise "A car has to have a driver to compete!"
  end

end




Scala - Change Dataset type

case class ACase( name: String)
case class BCase( name: String, num: Int)

I have ACase's dataset and would like to change it as BCase type with adding column. Here is my try.

def makeBCase( aCase: ACase, num: Int) {
    BCase( aCase.name, num)
}
def change( aDS: Dataset[ACase]): Dataset[BCase] = {
    val bDS = aDS.map { a => 
        makeBCase( aDS, 123)
    }
    ....
    bDS // error - type mismatch; required : org.apache.spark.sql.Dataset[ACase]
}

How can I change Its type?




Scope of struct properties in C#

I was working on a simple Keyboard reading program, and I came across something that I found to be very odd. In the code, I have each Key stored in a struct, which stores properties on whether it was pressed and/or released. Internally, the properties for Pressed and Released change when updated, but externally, they are always false. It took some time to figure out, but if I change the struct declaration to class, the code works just fine. I was wondering if this was a scope issue, and if not, what is the issue. Here is the code for both Key and Keyboard

public struct Key
{
    public Keys KeyName { get; }

    public bool Presseed { get; private set; }
    private bool PreviouslyDown { get; set; }

    public bool Released { get; private set; }

    internal Key(Keys keyName)
    {
        KeyName = keyName;
        Presseed = PreviouslyDown = Released = false;
    }

    internal void Update(bool isDown)
    {
        PreviouslyDown = Presseed;
        Presseed = isDown;
        Released = PreviouslyDown && !Presseed;
    }
}

public static class Keyboard
{
    private static readonly List<Key> Keys = new List<Key>(
        Enumerable.Range(0, Enum.GetNames(typeof(Keys)).Length).Select(n => new Key((Keys) n)));

    public static void Update(KeyboardState keyboardState)
    {
        Keys.ForEach(key => key.Update(keyboardState.IsKeyDown(key.KeyName)));
    }

    public static Key GetKey(Keys keyName)
    {
        return Keys[(int) keyName];
    }
}




$app in Facade class laravel

I have problem with understand how abstract class Facade have access to global class $app(Application). It's protected static $app; when i call Facade::$app it's print me the object of Application. I don't understand how it's posible without constuctor. Please explain me it.




How to modify classes for global use

my problem is a bit tricky to explain. Let me show you an example. I have the following class definitions:

class Person(object):     
    def __init__(self, name):         
        self.name = name  

    def say(self, stuff):         
        return self.name + ' says: ' + stuff     
    def __str__(self):         
        return self.name  

class Lecturer(Person):     
    def lecture(self, stuff):         
        return 'I believe that ' + Person.say(self, stuff)  

class Professor(Lecturer): 
    def say(self, stuff): 
        return self.name + ' says: ' + self.lecture(stuff)

class ArrogantProfessor(Professor): 
    def say(self, stuff): 
        return self.name + ' says: It is obvious that ' + Lecturer.lecture(self, stuff)

    def lecture(self, stuff):
        return 'It is obvious that ' + Lecturer.lecture(self, stuff)

Now I want to modify the any class but the ArrogantProfessor class so that I get the following:

>>> pe.say('the sky is blue')
Prof. eric says: I believe that eric says: the sky is blue 

>>> ae.say('the sky is blue')
Prof. eric says: It is obvious that I believe that eric says: the sky is blue

I should probably add, that pe = Professor('eric') and ae = ArrogantProfessor('eric') The change is basically to add the Prof. title in the beginning so it is universal for all methods. Therefore I tried to add something like "title" to the self.name within the __init__ method in the Person(object) class - but without success. Does anybody have a better idea Thanks!




Create class like a folder and methods as files

I would like to know if is possible to break this class:

class Something:


   method1(self):
       pass


   method2(self):
       pass


   method3(self):
       pass


   __init__(self):
       self.x = 'x'

In files, like this:

/something
| something.py
| method1.py
| method2.py
| method3.py

I have obsessive compulsive disorder, and unfortunately this is the only way i could ever program in python...




How to access outer class from inner?

Let I have a variable n in Outer class and want to read it from Inner class:

class Outer {
    int n;
    class Inner {
        void f() {
            cout << n;
        }
    };
};

One way is to keep a reference to Outer as a field of Inner. It works well but I'll have many instances of Inner inside one Outer and it will take unnecessary space.

So can I do it without adding extra fields in Inner?




UWP(c#) crashing when passing mainpage to second page

For a school project I'm currently working on a UWP app to control a robot. However, my application crashes when I navigate to this specific page

 public MainPage()
    {
        RobotControl cameraView = new RobotControl(this);
        InitializeComponent();
        extendstatusbar();
        currentView.Navigate(typeof(RobotControl));
    }

I need to use the RobotControl page to pass back data to the main page so I create a new object, then navigate to the RobotControl page.

namespace uwp_app
{
    public sealed partial class RobotControl : Page
    {
        public bool joystickDown = false;
        public bool streamEnabled = false;
        public bool joyStickVisible = true;

        public double joystickRefreshRate = 60;
        public double joystickRefreshTime;

        public const int maxSpeed = 1023;
        public MainPage localMainPage;
        public Point mousePos;


        public RobotControl(MainPage MainPageIn)
        {
            this.InitializeComponent();

            localMainPage = MainPageIn;

            joystickRefreshTime = (1 / joystickRefreshRate);

            Content.AddHandler(PointerMovedEvent, new PointerEventHandler(Joystick_PointerMoved), true);
        }

        private void Joystick_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            mousePos = e.GetCurrentPoint(this).Position;
        }


        public void JoystickDown(object sender, PointerRoutedEventArgs e)
        {
            joystickDown = true;
            joystickThread joystickThread = new joystickThread(this, localMainPage);
            joystickThread.Run();
        }
        public void JoystickUp(object sender, PointerRoutedEventArgs e)
        {
            if (joystickDown)
            {
                joystickDown = false;
                localMainPage.Send("forward,0;right,0");
                Joystick.Margin = new Thickness(0, 0, 65, 65);
                textBoxX.Text = "x : " + 0.ToString();
                textBoxY.Text = "y : " + 0.ToString();

            }

        }

the next bit is a thread for handling the joystick on the page.

    public class joystickThread
    {
        private RobotControl cameraViewThread;
        private MainPage localMainPage;

        public joystickThread(RobotControl input, MainPage mainpageinput)
        {
            cameraViewThread = input;
            localMainPage = mainpageinput;
        }

        public async void Run()
        {
            while (cameraViewThread.joystickDown)
            {
                Point mousePos = mousePos;
                Point mousePosRelativeToJoystickCenter = new Point(((Window.Current.Bounds.Width - localMainPage.HamburgerButton.Width) - (cameraViewThread.joystickGrid.Margin.Right + (cameraViewThread.JoystickBackground.Width / 2))) - mousePos.X, (Window.Current.Bounds.Height - (cameraViewThread.joystickGrid.Margin.Bottom + (cameraViewThread.JoystickBackground.Height / 2))) - mousePos.Y);
                double mouseDistanceFromJoystickCenter = Math.Sqrt((mousePosRelativeToJoystickCenter.Y * mousePosRelativeToJoystickCenter.Y) + (mousePosRelativeToJoystickCenter.X * mousePosRelativeToJoystickCenter.X));

                double joystickX;
                double joystickY;
                if (mouseDistanceFromJoystickCenter <= (cameraViewThread.JoystickBackground.Width / 2))
                {
                    joystickX = mousePosRelativeToJoystickCenter.X;
                    joystickY = mousePosRelativeToJoystickCenter.Y;
                }
                else
                {
                    double scale = (cameraViewThread.JoystickBackground.Width / 2) / mouseDistanceFromJoystickCenter;
                    joystickX = mousePosRelativeToJoystickCenter.X * scale;
                    joystickY = mousePosRelativeToJoystickCenter.Y * scale;
                }
                //Debug.WriteLine("val: " + mouseDistanceFromJoystickCenter);
                //Debug.WriteLine("x: " + joystickX + " y: " + joystickY + "mousex: " + mousePos.X + " mousey: " + mousePos.Y);
                cameraViewThread.Joystick.Margin = new Thickness(0, 0, joystickX + ((cameraViewThread.JoystickBackground.Width / 2) - (cameraViewThread.Joystick.Width / 2)), joystickY + ((cameraViewThread.JoystickBackground.Height / 2) - (cameraViewThread.Joystick.Height / 2)));

                joystickX = (joystickX / (cameraViewThread.JoystickBackground.Width / 2) * RobotControl.maxSpeed) * -1;
                joystickY = (joystickY / (cameraViewThread.JoystickBackground.Height / 2) * RobotControl.maxSpeed);
                cameraViewThread.textBoxX.Text = "x : " + Math.Round(joystickX).ToString();
                cameraViewThread.textBoxY.Text = "y : " + Math.Round(joystickY).ToString();
                /*if (localMainPage.isDisposed == false)
                {
                    SendData((int)(Math.Round(joystickX)), (int)(Math.Round(joystickY)));
                }
                await Task.Delay(TimeSpan.FromSeconds(cameraViewThread.joystickRefreshTime));
            */
            }
        }
        public void SendData(int xPos, int yPos)
        {
            Debug.WriteLine("senddata called");
            string xMovement = "";
            string yMovement = "";

            if (yPos >= 0 && yPos <= RobotControl.maxSpeed)
            {
                yMovement = ("forward," + yPos);
            }
            else
            {
                yMovement = ("backwards," + (~yPos));
            }
            if (xPos >= 0 && xPos <= RobotControl.maxSpeed)
            {
                xMovement = ("right," + xPos);
            }
            else
            {
                xMovement = ("left," + (~xPos));
            }

            //.Send(xMovement + ";" + yMovement);

        }
    }
}

so to summarize, i get a nullpointer exception every time i try to load this page, i tried disabling features one-by-one but to no avail,

any help would be much obliged




Create an instance of Python New Style class to embed in C++

I am working with PyObject to embed part of the python code inside C++. I found the solution that works well with python 2.7 using PyInstance_New to create python instance. But it doesn't work with new style python classes which look like this.

    class B(object): 
      def __init__(self, name): 
        self.name = name

      def print_name(lastName): 
        print self.name + " " + lastName

In my older code(python 2.7), class definition doesn't inherit from object class and I create my instance to call print_name method like this. P.S. file name is A.py.

    PyObject *import, *attr, *instance, *methodcall, *arg, *tuple;
    arg = PyString_FromString("hello"); 
    tuple = PyTuple_Pack(1, arg);  

    import = PyImport_ImportModule("A"); 
    attr = PyObject_GetAttrString(import, "B");
    instance = PyInstance_New(attr, arg, NULL); 

    methodcall = PyObject_CallMethod(instance, (char *) "print_name", (char *) "(s)", (char *) "Bill"); 

But the code above doesn't work anymore because, in the new python 3.x, type(class) returns object, instead of instance. Now, I am getting this error.

bad argument to internal function.

Any help is appreciated. Thank you.




Swapping elements in array defined in class python

I'm modelling a particle collision of two different species. I'm using a class to define each specie and a class for the arrays that hold the particle positions and speed.

When a collision occurs i have to swap the velocities of particle of specie A with the velocity of particle of specie B.

Classes are defined in a separate file as:

class Particle(object):
def __init__(self,num):
    self.x=numpy.zeros((num,1)) #Position
    self.v=numpy.zeros((num,3)) #Velocity

class Species(object):
def __init__(self):
    self.mass=[]
    self.spwt=[]

    self.np=[]
    self.np_alloc=[]
    self.part=[]

Species are created in the main file:

#variables to hold species
A = struct.Species()
B = struct.Species()

#set species data
A.mass = 1      
A.np = 0
A.spwt=spwt
A.np_alloc = num
A.part = struct.Particle(A.np_alloc)


B.mass = 1     
B.np = 0
B.spwt=spwt
B.np_alloc = int(cloud_den/spwt/cloud_len)
B.part = struct.Particle(B.np_alloc)

And when i try to swap velocities for particles

print A.part.v[p1]
print B.part.v[p2]

A.part.v[p1],B.part.v[p2]=B.part.v[p2],A.part.v[p1]

print A.part.v[p1]
print B.part.v[p2]

Output is:

[ 1000. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]




C# dll class "No suitable method found to override"

After looking around similar questions in "No suitable method found to override", and would like to ask for advice here. Why does my code give a error in Output not in Errorlist:

error CS0115: 'PgOdin.AmountRejected()': no suitable method found to override

my class:

class PgOdin : PgIngenicoController
{
    protected override void AmountRejected()
    {
        Console.WriteLine("test");
    }
}

The PgIngenicoController class looks like:

public abstract class PgIngenicoController
{
 ........
     protected abstract void AmountRejected();
 ........
}

My dll code, cccontrolCS.cs reads:

public class cccontrolCS
{
    PgOdin PgInstance = new PgOdin();
    public void PrepareDLL(IntPtr HWND)
    {
        bool ResultOpenTerm;
        string portNumber = "Com9";
        ResultOpenTerm = PgInstance.OpenTerm(portNumber);


    }
    .... ....
}




Change in classes for global use in Python

I have the following classes:

class Person(object):     
    def __init__(self, name):         
        self.name = name     
    def say(self, stuff):         
        return self.name + ' says: ' + stuff     
    def __str__(self):         
        return self.name  

class Lecturer(Person):     
    def lecture(self, stuff):         
        return 'I believe that ' + Person.say(self, stuff)  

class Professor(Lecturer): 
    def say(self, stuff): 
        return self.name + ' says: ' + self.lecture(stuff)

class ArrogantProfessor(Professor): 
    def say(self, stuff): 
        return self.name + ' says: It is obvious that ' + Lecturer.lecture(self, stuff)

    def lecture(self, stuff):
        return 'It is obvious that ' + Lecturer.lecture(self, stuff)

I want to change the Professor class (and probably something in an prior class) so that the

pe.say('the sky is blue')
Prof. eric says: I believe that eric says: the sky is blue 

ae.say('the sky is blue')
Prof. eric says: It is obvious that I believe that eric says: the sky is blue

I am not allowed to change the ArrogantProfessor(Professor) class, otherwise I would just add the string Prof. in the return statement. Is there a way to change something (probably in the Person(object) class, so it works universal? Maybe a change in self.name? Thanks!




CSS set divb color, when diva:hover

I want, when the first class hover, the second class's color is white.

<div class="diva">This is the first class</div>

<div class="divb">This is the second class</div>

<style>
.diva:hover .divb {
  color:#fff;
}
</style

but, this isn't work. How can I do this?




why return change variables while inside a class

I cannot understand this ruby behavior, the code explains better what I mean:

class DoNotUnderstand
    def initialize
        @tiny_array = [3,4]
        test
    end

    def messing(ary)
        return [ary[0]+=700, ary[1]+=999]
    end

    def test
        puts @tiny_array.join(",")  # before => 3,4
        messing(@tiny_array)
        puts @tiny_array.join(",")  # after  => 703,1003
    end
end

question = DoNotUnderstand.new

@tiny_array was [3,4] and became [703,1003]
if I don't use a class, that happens:

@tiny = [1,2]
def messing(ary)
    return [ary[0]+693,ary[1]+999]
end

puts @tiny.join(",")                        # before  => 1,2
messing(@tiny)
puts @tiny.join(",")                        # after   => 1,2

the array simply remains [1,2]
why?




Object not being destroyed until end of the script if it registers spl_autoload_register();

Object not being destroyed before script ends can someone explain why using spl_autoload_register() prevents object from destruction when unset().

The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

Does spl_autoload_register() have reference to the object that registered it or what happens?

class MyAutoLoader {

    public function registerAutoLoader() {

        spl_autoload_register(function ($class) {

        });

    }

    public function __destruct() {
        echo 'Destroying: ' . get_class($this) . "<br/>";
    }

}

$MyAutoLoader = new MyAutoLoader();

$MyAutoLoader->registerAutoLoader();

unset($MyAutoLoader);

echo 'End of script<br/>';

//End of script
//Destroying: MyAutoLoader




decorate a python function with a method from a class object

i'm looking to use a decorator on a function. the thing is the decorator function is defined inside a class and it has to be specific to an object of that class. for example:

class Foo:
    def __init__(self):
        self.a = 15

    def bar(func):
        def _args(*args, **kwargs):
            func(*args, **kwargs) + self.a
        return _args

if __name__ == "__main__":

    foo = Foo()

    @foo.bar
    def multip(a, b):
        return a * b




Pass function pointer as part of a hash, perl

The script runs such that THE USER defines some function:

sub userFunction
{
 # do things
}

This function, $func is passed with a specific message name, $msg, into my class to be stored as a $msg/$userFunc pair in {_Handles}:

sub new
{
  my ($class, ...) = @_;
  my $self = {};
  $self->{_Handles} = {};
  .
  . 
  .
}

Then I add a message handler:

$Class->AddMsgHandler($msgName1, \&userFunction);
sub AddMsgHandler
{ 
  my ($self, $msg, $func) = @ARG;
  my $funcPtr = $func->();
  $self->{_Handles}{'msg'} = $msg;
  $self->{_Handles}{$msg}{'funcPtr'} = $funcPtr;
}

The intention is to transfer my message wirelessly across a device; another device will receive this message. Assuming the device receives the message in another function, I'm trying to call the user defined function as follows:

sub Receive
{
 .
 .
 .
 my $funcPtr = $self->{_Handles}{'message'}{$msg}{'function'};
 $funcPtr->($msg, $self->{_devices}{$nid});
} 

somehow there's no response. Perhaps I have misused the function pointer?




Making a linked list without built in functions

I have a project to make a linked list in python.

My program needs to add to the list, remove from it and get elements. Sounds easy right? Wrong! We aren't allowed to use normal lists or built-in functions (other than the basic print, str...)

I have one problem with my code, I have to initialise a blank list then add the elements, 1 by 1. Everything else works fine.

My questions:

Is this how a normal python list works?

Is it possible to initialize a linked list with a loop?

Here's the code:

class Node: # the node class
    def __init__(self, cargo = None, next = None): # __init__ stands for initialize
        self.cargo = cargo # e.g. steve
        self.next = next # represents the next node or None if its the last

    def __str__(self): # __str__ is called when the node is printed or converted to a string
        return str(self.cargo) # return a string

class List: # the main list class
    def __init__(self): # default is to initialize an empty list
        self.first_node = None      
        self.last_node = None
        self.length = 0

    def get(self, position, length): # function for efficiency
        if position == "end":
            position = length - 1 # last
        if position > length - 1: # can't go beyond last
            raise ValueError("List index out of range")

        prv_node = self.first_node
        node = self.first_node # start at the first
        num = 0
        while num < position: # go up to position
            prv_node = node # remember the previous node
            node = node.next # next node!
            num = num + 1

        return prv_node, node, position

    def add_node(self, cargo, position = "end"): # adds a node
        prv_node, node, position = self.get(position, self.length + 1) # +1 because the length is being increased

        print("adding node at "+str(position)+": "+str(cargo))            
        if position == 0: # first
            self.first_node = Node(cargo, next = self.first_node) # the first node is the new node
            if self.length == 0: # first node to be added
                self.last_node = self.first_node # there is only one node
        elif position == self.length: # last
            self.last_node.next = Node(cargo, next = None) # last_node.next was None, it is now a new node
            self.last_node = self.last_node.next # last node is now the new last node
        else: # normal
            prv_node.next = Node(cargo, next = node) # stick it in between
        self.length = self.length + 1 # length is now + 1

    def get_node(self, position): # gets a node
        ...

    def remove_node(self, position): # removes a node 
        ...

    def __str__(self): # when the list is printed
        node = self.first_node # start from the first
        string = ""
        while node != self.last_node: # go to the end
            string = string + str(node) + ", "  # print each node
            node = node.next
        string = string + str(self.last_node) # last node hasn't been added yet
        return string

# initialize    
mylist = List()
mylist.add_node("steve")
mylist.add_node("james")
mylist.add_node("tom")
mylist.add_node("david")
mylist.add_node("hoe-yin")
mylist.add_node("daniel")
print(mylist)




How can I im port python custom class in Anaconda (jupyter notebook)

I don't manage to find how import custom class in Python with the Jupyter notebook in anaconda.

In my work folder I have a file 'user.ipynb' that contains a class name User. In an other file in the same folder, I try to import this class with : from user import User.

I get this error: ImportError: No module named user.

I tried to create a file ' _ _init__.py' and _ _init__.ipynb in this folder but it doesn't work.

Do you know how I could do this ?

Thank you in advance




Java class dependency

Hey guys just a quick question. For instance I have two Java files A.java and B.java and say B is dependable on A such as having a method that returns A. I realized that when I compile the code I have to compile them together if I do them separately that the compiler will complain "cannot find symbol" (A in this case) even when I compile A first. I thought B.java class is able to find its dependencies when it is compiled since A.class exist in the same directory as B? This might just be one of those fundamental understanding that I missed when I first start learning. Also, is there something that I can include, such as classpath parameter, so the same error wont result during compiling?




Apply function only if columns respect condition

I’m new to R and i’m trying to learn fundamentals. I’m facing a small problem for which i can’t find a solution online.

What i want to do: write a function to lower case for all the columns in my data.frame if they respect a condition (class = factor)

This code works, but for all my columns :

lower = function(x) {data.frame(tolower(as.matrix(x)))}

I need more something like this, but it doesn’t work:

lower = function (x) { for (i in 1:length(x)) {
 if (class(i)=="factor") {
   data.frame(tolower(as.matrix(x))) 
 }
}}

x is my data.frame

Thank you

Y.P




Getting uninitialized constant error when trying to instantiate a new class

I'm receiving an error:

lynda.rb:206:in `<main>': uninitialized constant Pig (NameError)

when I try to instantiate a new instance of the pig class. Does anyone know why I'm getting this error? I have searched online and I've been told it is commonly due to not requiring your parent class properly. However my parent class is within the same file.

class Animal
  attr_accessor :name
  attr_writer :colour
  attr_reader :legs, :arms

 def initialize(noise,legs=4,arms=0)
    @noise = noise
    @legs = legs
    @arms = arms

    puts "A new animal has been instantiated"
 end

 def noise=(noise)
    @noise = noise
 end

 def noise
    @noise
 end



  class Pig < Animal
   def noise
      parent_method = super
      puts "Hello and #{parent_method}"
   end
 end

  class Cow < Animal
  end
end

piggy = Pig.new("oink")
p piggy.noise




Where should I put convert time funtion to access it in several controllers?

I have a function like this to convert DateTime.

    private static string ToRelativeDate(DateTime dateTime)
    {
        var timeSpan = DateTime.Now - dateTime;

        if (timeSpan <= TimeSpan.FromSeconds(60))
            return timeSpan.Seconds > 5 ? string.Format("{0} sekunder sedan", timeSpan.Seconds) : "Precis nu";

        if (timeSpan <= TimeSpan.FromMinutes(60))
            return timeSpan.Minutes > 1 ? String.Format("{0} minuter sedan", timeSpan.Minutes) : "minut sedan";

        if (timeSpan <= TimeSpan.FromHours(24))
            return timeSpan.Hours > 1 ? String.Format("{0} timmar sedan", timeSpan.Hours) : "timme sedan";

        if (timeSpan <= TimeSpan.FromDays(30))
            return timeSpan.Days > 1 ? String.Format("{0} dagar sedan", timeSpan.Days) : "igår";

        if (timeSpan <= TimeSpan.FromDays(365))
            return timeSpan.Days > 30 ? String.Format("{0} månader sedan", timeSpan.Days / 30) : "månad sedan";

        return timeSpan.Days > 365 ? String.Format("{0} år sedan", timeSpan.Days / 365) : "år sedan";
    }

I have it in the controller where I use ut right now but I need to use it in multiple controllers. Where should I put it (don't want to duplicate my code) and how can I call it? Guessing it should be in a separated class, but where? My file structure is a standard asp.net MVC project.




Reducing fractions in a fraction class

I am currently making a fraction class program which will perform a series of operations on two given fractions. I believe I have started off correctly, but I am having troubling figuring out how to reduce the fractions. I can easily reduce fractions on paper, but I am having trouble understanding how to do it using Java given the current program. How can I reduce fractions using a method?

Here is the class with the main method:

public class FractionTester
{
    public static void main( String args[] )
    {
        // use the word Fraction as if were a Java data type
        Fraction f1 = new Fraction( 44,14 ); // reduces to 22/7
        System.out.println( "f1=" + f1 ); // should output 22/7

        Fraction f2 = new Fraction( 21,14 ); // reduces to 3/2
        System.out.println( "f2=" + f2 ); // should output 3/2
        System.out.println( f1.add( f2 ) ); // should output 65/14
        System.out.println( f1.subtract( f2 ) ); // should output 23/14
        System.out.println( f1.multiply( f2 ) ); // should output 33/7
        System.out.println( f1.divide( f2 ) ); // should output 44/21
        System.out.println( f1.reciprocal() ); // should output 7/22

    } // END main
} // EOF

Here is the class which contains the methods:

public class Fraction
{
    private int numer;
    private int denom;

    // ACCESSORS
    public int getNumer()
    {
        return numer;
    }
    public int getDenom()
    {
        return denom;
    }
    public String toString()
    {
        return numer + "/" + denom;
    }

    // MUTATORS
    public void setNumer( int n )
    {
        numer = n;
    }
    public void setDenom( int d )
    {
        if (d!=0)
            denom=d;
        else
        {
            // error msg OR exception OR exit etc.
        }
    }

    // DEFAULT CONSTRUCTOR - no args passed in
    public Fraction(  )
    {
        this( 0, 1 ); // "this" means call a fellow constructor
    }

    // 1 arg CONSTRUCTOR - 1 arg passed in
    // assume user wants whole number
    public Fraction( int n )
    {
        this( n, 1 ); // "this" means call a fellow constructor

    }

    // FULL CONSTRUCTOR - an arg for each class data member
    public Fraction( int n, int d )
    {
        setNumer(n);
        setDenom(d);
        reduce();
    }

    // COPY CONSTRUCTOR - takes ref to some already initialized Fraction object
    public Fraction( Fraction other )
    {
        this( other.numer, other.denom ); // call my full C'Tor with other Fraction's data
    }

    public Fraction add( Fraction other)
    {
        Fraction result = new Fraction(numer + other.numer, denom + other.denom);
        return result;
    }

    public Fraction subtract( Fraction other)
    {
        Fraction result = new Fraction((numer * other.denom) - (other.numer * denom)), denom * other.denom);
        return result;
    }

    public Fraction multiply( Fraction other)
    {
        Fraction result = new Fraction(numer * other.numer, denom * other.denom);
        return result;
    }

    public Fraction divide( Fraction other)
    {
        Fraction result = new Fraction(numer * other.denom, denom * other.numer);
        return result;
    }

    public Fraction reciprocal()
    {
        int temp = numer;
        numer = denom;
        denom = temp;
        return new Fraction(numer, denom);
    }

    private void reduce()
    {
        return ;// reduces this fraction to lowest form
    }

}// EOF




trouble with python classes, changing member variable of one instance of a class also changes that of another instance [duplicate]

This question already has an answer here:

class Element():
    def __init__(self, tag, childs = [], attributes = {}):
        self.childs = childs
        self.tag = tag
        self.attrib = attributes

    def get_childs(self):
        return self.childs

    def add_Child(self, child):
        self.childs.append(child)

class Html():
    def __init__(self):
        self.tag1 = Element("head")
        self.tag2 = Element("body")
        tag0 = Element("html", [self.tag1, self.tag2])

    def get_body(self):
        return self.tag2

    def get_head(self):
        return self.tag1

def main():
    html_object = Html()

   print html_object.get_body().get_childs()
   print html_object.get_head().get_childs()
   print "---------------"
   html_object.get_body().add_Child("new_child_added_to_body_ELEMENT")
   print "---------------"
   print html_object.get_body().get_childs()
   print html_object.get_head().get_childs()

if __name__ == "__main__":
   main()

when executing the above lines of code i get the following output:

[]
[]
---------------
---------------
['new_child_added_to_body_ELEMENT']
['new_child_added_to_body_ELEMENT']

while i wanted to insert the 'new_child_added_to_body_ELEMENT' only to the self.childs list of self.tag2 (the "body" Element"), what i end up getting is that the line is also added to the self.childs list of self.tag1 (the "head" Element) that is also declared inside of the Html class init.

there's obviously something about python classes that i'm missing so an explanation about what i'm doing wrong will be really appreciated.




C#: What is the default value of an uninstantiated object?

I have a quick question about default values in c#.

What us the default value of an object when not instantiated?

Here is an example:

public class Example
{
  public Example() { Console.WriteLine("Content!"); }
}

public class MainClass
{
  // obj = ???
  Example obj;
}




How to pass data between classes in python

I am using Python and jinja2 as a templater to build a web page that asks for some inputs (about 10). Then when the user presses the calculate button the def post() method for the class performs many steps to evaluate an answer and displays the answer in a new html page. The inputs have been saved using self.request.get() and then saved into a dictionary.

My problem starts now.

From this new html page I have a second button where I can do further mathematical analysis based on additional input using a seperate Python class however I cannot get the dictionary made in the first class to be readable/useable in the second class.

Is there a simple way to pass data between classes or is the best option to save the data in a database so that it can be accessed anywhere?




Eclipse cannot see genreated classes

I have a problem with seeing generated classes in eclipse. It is because generated classes in target folder which are generated during build, have the same package as existing package in the project where some java classes made by myself are . I want to keep generated class in target folder but eclipse cannot see the class as it does not find it in target because of the same package. Is there anything what I can do in settings to make eclipse see the class ?




Constructor cannot be applied

i was doing this tutorial on Android Studio Development Essentials 6th Edition, the tutorial was about SQLiteDatase so i wrote evrything but i kept on getting an error whenever i try calling the Product Constructor everything is correct on the book but i cant get it right, this is the find Product Constructor and my Product class.

Find product

  public Product findProduct(String productname) {
    String query = "Select * FROM " + TABLE_PRODUCTS + " WHERE " +
            COLUMN_PRODUCTNAME + " = " + productname + ";";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    Product product = new Product();// Cannot be applied
    if (cursor.moveToFirst()) {
        cursor.moveToFirst();
        product.setId(Integer.parseInt(cursor.getString(0)));
        product.setProductName(cursor.getString(1));
        product.setQuantity(Integer.parseInt(cursor.getString(2)));
        cursor.close();
    } else {
        product = null;
    }
    db.close();
    return product;
}

My Product Class

public class Product {
private int id;
private String ProductName;
private int Quantity;

public Product(int _id, String _productname, int _quantity) {
    this.id = _id;
    this.ProductName = _productname;
    this.Quantity = _quantity;
}

public int getId() {
    return id;
}

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

public String getProductName() {
    return ProductName;
}

public void setProductName(String productName) {
    this.ProductName = productName;
}

public int getQuantity() {
    return Quantity;
}

public void setQuantity(int quantity) {
    this.Quantity = quantity;
}

}

Thank you.




dimanche 30 octobre 2016

How to create user-specified number of objects?

I've just started learning about classes and objects and know the basics(creating objects,assigning variables and using functions)

I'm trying to create a To-Do-List script. For this I have a class,:

class Tasks:
name=""
priority=3
duration=1.5
due_date=3

def __init__(self):                     #inputs all the variables
#Defines new variable new_priority            

    self.name = input("Enter the name of ", self)
    self.priority = input("Enter its priority from 1 to 5.")

    while self.priority not in range(1, 5):
        print("Please try again.The value must be between 1 and 5 \n")
        self.priority = input("Enter its priority from 1 to 5")

    self.due_date = input("When is it due?1-Today,2- Tomorrow ")

    while self.due_date == 0:
        print("Please try again.The value must not be zero")
        self.due_date = input("When is it due?1-Today,2- Tomorrow ")

    self.new_priority=self.priority * (1/self.due_date)


def print(self):

    print(self.name, "   ", self.duration, "   ", self.due_date, 
                                           "   ",self.priority)            

In this ,each task is an object. What I'm having problem with is that the number of tasks will be according to the user's preference. We may have 1,we may have 12.How do I create objects as per the user's will?




Java arrays in user defined classes

My code is posted below. I'm generating random numerical grades and assigning them letter grades. Will then create a client class to test the program. My issue is towards the end of the program. I'm getting an error saying illegal start of expression. Maybe I just need a fresh set of eyes to look at this. I can't seem to figure it out. Thanks!

import java.util.Random;

public class Convertgrade { private int numberOfStudents;

 private int[] studentGrades = new int[100];


 public Convertgrade()
 {
        numberOfStudents = 0;
 }

  //one arg constructor, sets numberOfStudents = students
  public Convertgrade(int students)

  {
         numberOfStudents = students;
         setGrades(students);
  }

  //mutator
  public void setStudents(int students)
  {
        if(students < 0)
        {
                   numberOfStudents = 0;
         }
         else
        {
                   numberOfStudents = students;
                   setGrades(students);
          }
  }

    //accessor
   public int getStudents()

   {
   return numberOfStudents;
    }

   public void setGrades(int students)
   {
          Random randomNumber = new Random(); 
          for(int count = 0; count < students; count++)
          {
                studentGrades[count] = randomNumber.nextInt(101);
                }
           }

      public char[] getLetterGrades()
      {
               char[] letterGrades = new char[numberOfStudents];
               for(int count = 0; count < numberOfStudents; count++)
               {
                       if(studentGrades[count] <= 59)
                       letterGrades[count] = 'F';

                       else if(studentGrades[count] <= 69)
                       letterGrades[count] = 'D';

                       else if(studentGrades[count] <= 79)
                       letterGrades[count] = 'C';

                       else if(studentGrades[count] <= 89)
                       letterGrades[count] = 'B';

                       else if(studentGrades[count] <= 100)
                       letterGrades[count] = 'A';
                        }
                   return letterGrades;
                   }

       public int getAs()

       {

                  int numberOfAs = 0;

                  for(int count = 0; count < numberOfStudents; count++)

                  {

                            if(studentGrades[count] >= 90)

                            numberOfAs++;

                   }
              return numberOfAs;
         }

       public int[] getNumberOfEachGrade()

      {

             int[] numberOfGrades = new int[numberOfStudents];

             for(int count = 0; count < numberOfStudents; count++)

              {

                    if(studentGrades[count] <= 59)

                    numberOfGrades[count] ++;

                    else if(studentGrades[count] <= 69)

                    numberOfGrades[count] ++;

                    else if(studentGrades[count] <= 79)

                    numberOfGrades[count] ++;

                    else if(studentGrades[count] <= 89)

                    numberOfGrades[count] ++;



                    else if(studentGrades[count] <= 100)

                    numberOfGrades[count] ++;

             }

          return numberOfGrades;

         }



        public String toString()

        {

              System.out.format("The number of students = %d\n", numberOfStudents);

              for(int count = 0; count < numberOfStudents; count++)

              {

                       System.out.format("Grade %d is %d\n", count + 1, studentGrades[count]);

              }

        return String.format("\n");

         public void sort_array(int[] array); 
         //GETTING ERRORS HERE^: ILLEGAL START OF EXPRESSION

        {

                int intTemp;

                int count = 0;

                int index = 0;

                for(count = 0; count < (array.length - 1); count++)

                {

                     for(index = 0; index < (array.length - 1); index++)

                     {

                            if(array[index] > array[index +1])

                            {

                                    intTemp = array[index +1];

                                    array[index +1] = array[index];

                                    array[index] = intTemp;

                                }

                       }

                 }

           }

  }

}




Android Studio - Using methods from outside classes with views

I'm having some difficulty with getting views in a method called from another class to function properly.

My app contains an experience bar present in the main activity (named Overlay) that tracks user progression using a progress bar. What I would like to do is have a separate method in another class that handles any code related to the experience bar.

I have already created an instance for the class and the method is called upon correctly, but certain android/view related pieces result in a crass. System.out.println will display text into the debugger, however the use of Toast and other views do not. Here are the two class files and the associated error.


public class OverlayActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

NavigationView navigationView = null;
Toolbar toolbar = null;
int level = 0;
int addXP = 110;
ProgressBar experienceBar;
Button buttonXP;
TextView experienceLevel;
ExperienceManager exp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_overlay);

    //Set the Overlay Fragment

    OverlayFragment fragment = new OverlayFragment();
    android.support.v4.app.FragmentTransaction fragmentTransaction =
            getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment);
    fragmentTransaction.commit();

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Hay! Don't touch me!", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    experienceBar = (ProgressBar) findViewById(R.id.experienceBar);
    experienceBar.setProgress(12);

    experienceLevel = (TextView) findViewById(R.id.ds_appBar_level);

    buttonXP = (Button) findViewById(R.id.buttonXP);
    buttonXP.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View View) {
            exp = new ExperienceManager();
            exp.addExperience(level, addXP);
        }
    });
}


public class ExperienceManager extends AppCompatActivity {

ProgressBar experienceBar;

public int addExperience(int level, int addXP) {
    experienceBar = (ProgressBar) findViewById(R.id.experienceBar);

    int addLevel = 0;
    while (addXP >= experienceBar.getMax()) {
        addXP -= experienceBar.getMax();
        addLevel += 1;
    }
    if (addXP >= experienceBar.getMax()-experienceBar.getProgress()) {

        experienceBar.setProgress(experienceBar.getProgress() + addXP - experienceBar.getMax());
        addLevel += 1;
    } else {
        experienceBar.setProgress(experienceBar.getProgress() + addXP);
    }
    if (addLevel >= 1) {
        level += addLevel;
        Toast toast = Toast.makeText(getBaseContext(), "Level up!", Toast.LENGTH_SHORT);
        toast.show();
        //experienceLevel.setText("Level " + level);
    }
    return level;
}


E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.teamcirelios.deepstone, PID: 4138
              java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                  at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
                  at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
                  at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
                  at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
                  at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
                  at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:199)
                  at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
                  at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
                  at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                  at com.teamcirelios.deepstone.ExperienceManager.addExperience(ExperienceManager.java:15)
                  at com.teamcirelios.deepstone.OverlayActivity$2.onClick(OverlayActivity.java:77)
                  at android.view.View.performClick(View.java:5697)
                  at android.widget.TextView.performClick(TextView.java:10826)
                  at android.view.View$PerformClick.run(View.java:22526)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:158)
                  at android.app.ActivityThread.main(ActivityThread.java:7225)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)


Likewise, a similar error results when trying to register a button click in a fragment. The experience bar itself displays with the Overlay acitvity, however for the app to work as intended it would need to receive an input to call that class from a button (or to be more accurate, a checkbox) inside a fragment.

The only solution that I could see working would be to take experienceBar.getMax() and similar and include them as parameters. However, I would need to return both the level and current xp, which to my knowledge isn't possible.

To basically sum everything up, I have three main questions.

  • What's the non-technical explanation for this error?
  • What is the best (and relatively simple) way to fix the code to achieve the desired function?
  • How can I register events inside a fragment?

Thank you!




Swift 3: Inside a class, write an Instance Method that acceps a minutes parameter that can advance time

class ClockTime {
    var hour: Int = 0
    var minute: Int = 0
    var timeofDay: String = ""

func time(hour: Int, minute: Int, timeofDay: String) {
    return time(hour: 6, minute: 27, timeofDay: "AM")
}

func advance(mins: Int) {

    minute += mins

    while (mins >= 60) {
        minute -= 60
        hour += 1
        if hour == 12 {
            if timeofDay == "AM" {
                self.timeofDay = "PM"
            } else {
                self.timeofDay = "AM"
            }

            if hour > 12 {
                hour = 1
            }
        }

    }

}     
}
var time = ClockTime()
time.advance(minutes: 20)

An example output should be any time passed in (9, 30, "AM") and moveforward 20 minutes because of the instance method call. Another example output for setting a time of (6, 27, "PM") could be time.advance(minutes: 31); outputs 6:58 PM

I am so confused on how to set the time for the instance method call.

A ClockTime class is created and the instance method accepts a minutes parameter. The AM, PM aspect makes it so that whenever any non-negative number is passed into the method call, it can distinguish that moving it forward may change the timeofDay from AM to PM to AM and so on. There should be a way to pass in a time in order to use the method. Thats why I created a function that accepts hour, minute, and timeofDay. I know that is not correct but didn't know how I can make the class accept the parameters of setting a time before using the instance method called advance that accepts a minutes parameter.

I am new to Swift programming and trying to figure all of this out. Swift 3 upgrade has made it even more complicated. Need some help with my code and what I am missing? Please provide guidance. I wanna learn how to do this with the best approach.

The original question is: Write an instance method advance that will be placed inside the ClockTime class. The method accepts a number of minutes as its parameter and moves your object forward in time by that amount of minutes. The minutes passed could be any non-negative number, even a large number such as 500 or 1000000. If necessary, your object might wrap into the next hour or day, or it might wrap from the morning ("AM") to the evening ("PM") or vice versa. (A ClockTime object doesn't care about what day it is; if you advance by 1 minute from 11:59 PM, it becomes 12:00 AM.)

For example, the following calls would produce the following results:

ClockTime time = new ClockTime(6, 27, "PM");

time.advance(1); // 6:28 PM

time.advance(30); // 6:58 PM

time.advance(5); // 7:03 PM

time.advance(60); // 8:03 PM

time.advance(128); // 10:11 PM

time.advance(180); // 1:11 AM

time.advance(1440); // 1:11 AM (1 day later)

time.advance(21075); // 4:26 PM (2 weeks later)




Trouble understanding private variables in classes and class property method in Python 3

This class example was taken from here.

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    def get_temperature(self):
        print("Getting value")
        return self._temperature

    def set_temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value

    temperature = property(get_temperature, set_temperature)

The idea here is that when we create an instance of Celsius and set the temperature attribute (e.g. foo = Celsus (-1000) ), we want to make sure that the attribute is not less than -273 BEFORE setting the temperature attribute.

I don't understand how it seems to bypass self.temperature = temperature and go straight to the last line. It seems to me like there are three variables created here: the Class attribute, temperature; the Instance attribute, temperature; and the set_temperature function which sets the attribute _temperature.

What I DO understand is that the last line (the assignment statement) must run the code property(get_temperature, set_temperature) which runs the functions get_temperature and set_temperature and intern set the private variable _temperature.

What confuses me is how the 'get_temperature(self, value)' knows what the parameter value is? Moreover, if I run: foo = Celsius(100) and then foo.temperature, is the result of foo.temperature coming from self.temperature = temperature OR temperature = property(get_temperature, set_temperature)? I know it can't be from self.temperature = temperature and thus the source of my confusion...they both have the same name!

QUESTIONS ABOUND!

Why do we have to attributes with the same name (e.g.temperature)?

Why do we need private attributes/properties?

How does set_temperature(self, value) obtain the attribute for parameter value (e.g. the argument that replaces value)?




Initialization of user-defined array in C++ class?

I'm working on knight's tour problem, and want to define a class, but I am having trouble with initialize an array defined by user. So the user inputs from the command line argvs are the chessboard lengths mX and nY; and a starting position(x,y). So basically, how do I initialize an array that's defined by the user?

First question: In the public part, is it right to declare int ** tour?

Second question: How do I refer to the array tour in the following functions in the same class?

Third question: In main, I called K.knight to initialize an array of dimension specified by the user, but it wasn't initialized. How do I initialize an array in main using the function K.knigt(), and be able to use the array in the following function K.knightfunc()?

class Ktour{
public:
    int xSize;              //m 
    int ySize;              //n 
    int ** tour;            //array to be initialized
    int solutionsCount;     //tracking solutions
    int position;           //position count, from 0 to m * n -1

// initialize tour matrix
void knight(int M, int N) {

position = 1;
solutionsCount = 0;

xSize = M;
ySize = N;

tour = new int * [xSize];
for (int i = 0; i < xSize; i++) {
    for (int j = 0; j < ySize; j++) {
        tour[i][j] = 0;
        std::cout << tour[i][j] << std::endl;
        }
    }
}
....some other functions defined in between...
....
.... 
};
...
// main
int main(int argc, char *argv[])
{    
    Ktour K;

    //user inputs chessboard length mX and nY; and a starting position(x,y)

    int mX = atoi(argv[1]);
    int nY = atoi(argv[2]);
    int x = atoi(argv[3]);
    int y = atoi(argv[4]);

    //initialization
    K.knight(mX, nY);  

    //run the recursive function;
    K.knightFunc(x,y);

    return 0;
}




create list with variables containing classes

I am trying to create my own Nbody simulation from scratch. I have created a class (called Body) that contains functions to calculate the forces from the other bodies and move it accordingly. I have created another class, called System, that defines the number of bodies, controls the updates of the positions and updates a plot of the system. Both classes work fine if I define the number of variables individually like this:

d1 = Body(i)
d2 = Body(i)
....

and put them in a list list = [d1,d2, ...]. i is a string (a name that is used The problem with this method is that it is tiresome to do n individual variable definitions and then put them in a list. I have tried to do a loop:

self.liste = []
for i in range(n):
            self.liste.append(Body(str(i)))

but this returns a list containing Nonetypes ([None, None, None, ....]). It is important to my setup that I end up with a list n different classes (it is okay if they are defined by a variable name). Can anybody help me with this?




Is there a way to take an argument for a class that can call newInstance(args)?

I have a class called ExtenderClass that has newInstance(args) defined.

I want to make a function that basically does this:

public ExtenderClass callNewInstance(class extending ExtenderClass) {
    return (class extending ExtenderClass).newInstance(args);
}

Is this possible?




PHP - creating an instance of class

I have class Page and I need to create few pages that will be displayed in browser. So I create an instance $firstPage = new Page(); and calling the methods like $firstPage -> title("FIRST TITLE"), $firstPage -> content("content")etc. but when I open the page in browser there is nothing. Thanks!

<?php

define ('SITE_NAME', 'Your Website');
define ('BASE', str_replace($_SERVER['SERVER_NAME'], '', $_SERVER['DOCUMENT_ROOT'])); // The Base Root Directory Name
define ('BASE_URI', $_SERVER['DOCUMENT_ROOT'] . '/'); // The HTML Directory Name
define ('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/'); // Your Website's Full URL Address
define ('DOCTYPE', 'xhtml strict');

class Page {

  private $title = '';
  private $description = '';
  private $keywords = '';
  private $robots = true;
  private $doctype = '';
  private $xhtml = true;
  private $charset = 'utf-8';
  private $include = array();
  private $jquery = array();
  private $body = '';

  function __construct ($title='') {
    if (!empty($title)) {
      $this->title = $title;
    } elseif (defined('SITE_NAME')) {
      $this->title = SITE_NAME;
    }
    if (defined('DOCTYPE')) {
      list($type, $standard) = explode(' ', DOCTYPE);
      $this->doctype ($type, $standard);
    } else {
      $this->doctype ('xhtml', 'strict');
    }
  }

  public function doctype ($type='html', $standard='strict') {
    if (in_array($standard, array('strict', 'transitional', 'frameset'))) {
      if ($type == 'html') {
        $this->xhtml = '';
        switch ($standard) {
          case 'strict': $this->doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://ift.tt/nYkKzf">'; break;
          case 'transitional': $this->doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ift.tt/kTyqzh">'; break;
          case 'frameset': $this->doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://ift.tt/1bdsIWz">'; break;
        }
      } elseif ($type == 'xhtml') {
        $this->xhtml = ' /';
        switch ($standard) {
          case 'strict': $this->doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://ift.tt/mOIMeg">'; break;
          case 'transitional': $this->doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/kkyg93">'; break;
          case 'frameset': $this->doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://ift.tt/17m2GIt">'; break;
        }
      }
    }
  }

  public function access ($user, $level=1) { 
    switch ($user) {
      case 'users':
        if (!isset($_SESSION['user_id'])) $this->eject('sign_in/');
        break;
      case 'admin':
        if (!isset($_SESSION['admin']) || $_SESSION['admin'] == 0 || $_SESSION['admin'] > $level) $this->eject();
        break;
      case 'others':
        if (isset($_SESSION['user_id'])) $this->eject();
        break;
    }
  }

  public function eject ($where='', $msg='') {
    if (stristr($where, BASE_URL)) {
      $url = $where;
    } else {
      $url = BASE_URL . $where;
    }
    if (ob_get_length()) ob_end_clean();
    if (empty($msg)) {
      $url = str_replace('&amp;', '&', $url);
      header("Location: $url");
    } else {
      echo '<script type="text/javascript"> var msg = confirm("' . str_replace(array('<br />', '<br>'), "\\n", addslashes($msg)) . '"); if (msg == true) { window.location = "' . $url . '"; } else { window.location = "' . $url . '"; } </script>';
      echo $msg . '<br /><br /><a href="' . $url . '">Click here to continue.</a>';
    }
    exit; 
  }

  public function title ($title='') {
    if (!empty($title)) $this->title = $title;
    return $this->title;
  }

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

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

  public function robots ($robots) {
    if (is_bool($robots)) $this->robots = $robots;
  }

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

  public function link ($link, $prepend=false) {
    if (!is_array($link)) $link = array($link);
    if ($prepend) {
      $this->include = array_merge($link, $this->include);
    } else {
      foreach ($link as $value) $this->include[] = $value;
    }
  }

  public function jquery ($code, $oneliner=true) {
    if ($oneliner) $code = $this->oneliner($code);
    $this->jquery[] = $code;
  }

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

  public function url ($action='', $url='', $key='', $value=NULL) {
    $protocol = ($_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
    if (empty($url)) $url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    if ($action == 'ampify') return $this->ampify($url);
    $url = str_replace ('&amp;', '&', $url);
    if (empty($action) && empty($key)) { // clean the slate
      $url = explode('?', $url);
      return $url[0]; // no amps to convert
    }
    $fragment = parse_url ($url, PHP_URL_FRAGMENT);
    if (!empty($fragment)) {
      $fragment = '#' . $fragment; // to add on later
      $url = str_replace ($fragment, '', $url);
    }
    if ($key == '#') {
      if ($action == 'delete') $fragment = '';
      elseif ($action == 'add') $fragment = '#' . urlencode($value);
      return $this->ampify($url . $fragment);
    }
    $url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
    $url = substr($url, 0, -1);
    $value = urlencode($value);
    if ($action == 'delete') {
      return $this->ampify($url . $fragment);
    } elseif ($action == 'add') {
      if (strpos($url, '?') === false) {
        return ($url . '?' . $key . '=' . $value . $fragment); // no amps to convert
      } else {
        return $this->ampify($url . '&' . $key . '=' . $value . $fragment);
      }
    }
  }

  public function display ($content='') {
    $html = '';
    $type = ($this->xhtml) ? 'xhtml' : 'html';
    $frameset = false;
    if (strpos($content, '<frame ') !== false) { // Then this is a frameset ...
      $frameset = true;
      $this->doctype($type, 'frameset');
    } elseif (strpos($this->doctype, 'frameset') !== false) { // If we're here then it's not ...
      $this->doctype($type, 'transitional');
    }
    $html .= $this->doctype . "\n";
    $html .= '<html';
    if ($this->xhtml) $html .= ' lang="en-US" xml:lang="en-US" xmlns="http://ift.tt/lH0Osb"';
    $html .= '>' . "\n";
    $html .= '<head>' . "\n";
    $html .= $this->meta_tags();
    $html .= $this->include_scripts();
    $html .= '</head>' . "\n";
    $html .= ($frameset) ? '<frameset' : '<body';
    if (!empty($this->body)) $html .= ' ' . $this->body;
    $html .= '>';
    $html .= "\n  " . trim($content);
    $html .= ($frameset) ? "\n</frameset>" : "\n</body>";
    $html .= "\n</html>";
    if (!$this->xhtml) $html = str_replace(' />', '>', $html);
    return $html;
  }

  private function meta_tags () {
    $tags = '  <meta http-equiv="content-type" content="text/html; charset=' . $this->charset . '" />' . "\n";
    $tags .= '  <title>' . $this->title . '</title>' . "\n";
    $description = (!empty($this->description)) ? $this->description : $this->title;
    $keywords = (!empty($this->keywords)) ? $this->keywords : $this->title;
    $tags .= '  <meta name="description" content="' . $description . '" />' . "\n";
    $tags .= '  <meta name="keywords" content="' . $keywords . '" />' . "\n";
    if (!$this->robots) $tags .= '  <meta name="robots" content="noindex, nofollow" />' . "\n";
    return $tags;
  }

  private function include_scripts () {
    $scripts = $this->combine_scripts($this->sort_scripts($this->include));
    if (!empty($this->jquery)) {
      $this->jquery = array_unique($this->jquery);
      $scripts .= '  <script type="text/javascript">$(document).ready(function(){' . "\n  ";
      $scripts .= implode("\n  ", $this->jquery);
      $scripts .= "\n  })</script>\n";
    }
    return $scripts;
  }

  private function sort_scripts ($array) { // used in $this->include_scripts()
    $array = array_unique($array);
    $scripts = array();
    foreach ($array as $script) {
      $parts = explode('.', $script);
      $ext = array_pop($parts);
      $name = implode('.', $parts);
      switch ($ext) {
        case 'ico': $scripts['ico'] = $script; break;
        case 'css': $scripts['css'][] = $name; break;
        case 'js': $scripts['js'][] = $name; break;
        default: $scripts['other'][] = $script; break;
      }
    }
    return $scripts;
  }

  private function combine_scripts ($sorted) { // used in $this->include_scripts()
    if (empty($sorted)) return '';
    $scripts = array();
    if (isset($sorted['ico'])) {
      $scripts[] = '<link rel="shortcut icon" type="image/x-icon" href="' . $sorted['ico'] . '" />';
    }
    if (isset($sorted['css'])) {
      foreach ($sorted['css'] as $script) {
        $scripts[] = '<link rel="stylesheet" type="text/css" href="' . $script . '.css" />';
      }
    }
    if (isset($sorted['js'])) {
      foreach ($sorted['js'] as $script) {
        $scripts[] = '<script type="text/javascript" src="' . $script . '.js"></script>';
      }
    }
    if (isset($sorted['other'])) $scripts = array_merge($scripts, $sorted['other']);
    return '  ' . implode("\n  ", $scripts) . "\n";
  }

  private function oneliner ($code) {
    return preg_replace('/\s(?=\s)/', '', str_replace(array("\r\n", "\r", "\n"), ' ', $code));
  }

  private function ampify ($string) { // used in $this->url
    return str_replace(array('&amp;', '&'), array('&', '&amp;'), $string);
  }

}
$page1 = new Page();
$page1->__construct("PRVASTRANA");
$page1->url('#','prvastrana','nokey');
$page1->title('NASLOV2');
$page1->charset('UTF-8');
$page1 ->body('FIRST PARAGRAF');
$page1->display('DISPLAY CONTENT');
echo "THIS";
?>




VC++ Classes. Static variables error unresolved external symbol

I Have This error that keeps haunting me in all of my programs that is probobly just me overlooking something.

code snippet where this error appaice:

class myClass {
private:
    int x;
public:
    static int getX() {
        x = 10;
        return x;
    }
};

int main() {
    cout << myClass::getX() << endl;
    return 0;
}

the error i am getting says : error unresolved external symbol what is causeing this or what is wrong with my code?




class does not find varibale

I'm trying to create my first class. But, I got stuck.

class StrLineBreak():

    def __init__ (self, string, add_first):

        self.string = string
        self.lb_ls = []
        self.add_first = add_first

        for i in range(len(self.string)):
            if self.string.find("\n", i) == i:
                self.lb_ls.append(i)

        if add_first == True:
            self.lb_ls[0] = -1      


Import_Str_Raw = open('textfile.txt').read()

instance_1 = StrLineBreak(string = Import_Str_Raw, add_first = False)

print(instance_1.lb_ls)

I get an error when I'm trying to use the if statement. The error says "name add_first no defined". I don't understand this since I defined the variable in the beginning.




how to use function of protocol of class in other class

I have a class Bot. That class is used as the protocol for another class BotFactory. I want to use a function of Bot in yet another class FbHandler. I have no idea how I would do this.

The function I want to use is msg. I have a comment in the code where I want to use it.

from twisted.internet import reactor, protocol
from twisted.web import server, resource
from twisted.words.protocols import irc

from bot.fb import messaging_events  # messaging_event just extracts sender and message from json


class Bot(irc.IRCClient):

    def _get_nickname(self):
        return self.factory.nickname
    nickname = property(_get_nickname)

    def privmsg(self, user, channel, msg):
        self.msg('#trirpi', msg)  # this is how I can send a message


class BotFactory(protocol.ClientFactory):
    protocol = Bot

    def __init__(self, channel, nickname='no_nick_specified'):
        self.channel = channel
        self.nickname = nickname

    def clientConnectionLost(self, connector, reason):
        print "Connection lost. Reason: %s" % reason
        connector.connect()

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed. Reason: %s" % reason

    def hello(self):
        Bot.msg(protocol, 'trirpi', 'message')


class FbHandler(resource.Resource):
    isLeaf = True

    def render_POST(self, request):
        print "Handling Messages"
        payload = request.content.read()
        print(payload)  # print out the received json data
        for sender, message in messaging_events(payload):

            # here I want to send an message with the irc bot

            print "Incoming from %s: %s" % (sender, message)  # this would be the content
        return "ok"

if __name__ == "__main__":
    instance = BotFactory('#trirpi', 'fbbot123')
    reactor.connectTCP('chat.freenode.org', '6667', instance)
    site = server.Site(FbHandler())
    reactor.listenTCP(8080, site)
    reactor.run()




I am getting An error on my function call, can someone explain why?

I get an error when I try to call my member function to copy the array into another array. Im not sure if I am calling it wrong or what. I think I have the syntax right on most parts but I am also not sure if it matter if the member function is a void or int.

Main.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Class.h"

using namespace std;

int main()
{
// Max size of array
int MaxRange = 1000;

// Get System time
unsigned seed = time(0);

// seed random number generator
srand(seed);

// allocate memory for array
int * Array = new int[1000];
int * CopiedArray = new int[1000];

// Randomly generate numbers into array
for (int i = 0; i < 1000; i++)
{
    Array[i] = 1 + rand() % MaxRange;
}

//print array
for (int j = 0; j < 1000; j++)
{   
    cout << Array[j] << endl;
}   
CopiedArray = Sort.CopyArray(Array);


return 0;

}

Class.h
#include <iostream>

using namespace std;


class Sort
{

public:
void CopyArray(int * Array);



};

Class.cpp
#include <iostream>
#include "Class.h"

using namespace std;

void CopyArray::CopyArray(int * Array)
{
// Allocate memory for copied array
int * CopiedArray = new int[1000]

//copy date to array
for(int i = 0; i < 1000; i++)
{ 
    CopiedArray[i] = Array[i]
}

cout << " THIS IS THE COPIED ARRAY" << endl;

// print copied array 
for (int j = 0; i < 1000; i++)
{
    cout << CopiedArray[j] << endl;
}

} 




How to construct an object using a variable as the class name?

I am creating a game in C# Windows form and I will have 9 different characters inside the game for my player to choose from (using radio buttons). I have a variable called PlayerChar and Whenever the player chooses a character I will store the character's name inside that variable. Also I have 9 different classes for each characters. What I am trying to do is, to get the program to create an object from the class of the character chosen. but I don't know how to use variable PlayerChar as my class name.

PlayerChar obj = new PlayerChar();

This is basically what I am trying to do. Also I tried using Activator.CreateInstance:

PlayerChar myObj = Activator.CreateInstance(PlayerChar);




defining a class constructor

I'm dealing with my very first course on programming in C++ and that's the way in which I've been told to define a class constructor:

class_name(int x, int y){
    this->x=x;
    this->y=y;
  };

If I understood correctly, as I've found several times here, I could rewrite it this way:

field(int x, int y) : m_x(x), m_y(y){};

having however this protected variables:

protected:
    int m_x, m_y;

instead of

protected:
    int x, y;

Are there any differences between them or is it just different ways of writing?

And, if so, why the need of having different m_x and x variables?

I hope this is not such a silly questions, but I'd like to really understand it.

peace.




Passing a class and calling a method on it

Consider a class extending Fragment called MyFragmentClass which has newInstance(args) implemented.

What I want to do is make a getter for anything extending MyFragmentClass so I can make a new Fragment via newInstance(args). Something like:

<T extends MyFragmentClass> Class<T> getMyFragmentClass() {
    return SomeClassExtendingMyFragmentClass.class;
}

and then

public void makeNewFragment() {
    MyFragmentClass fragment = getMyFragmentClass().somehowCallNewInstance(args);
}

However I am having some difficulty, since I can't really pass it a new MyFragmentClass() as this defeats the purpose of using newInstance(args), and I can't call newInstance(args) early if the args I want are in the class invoking the get() call.

I tried passing back the .class but I was only able to call newInstance() on it (no args).

Is there a workaround?




Error in the class to create pipeline

I try to create a new variable 'age' from two variables 'date_birth' and 'date_survey'

import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn import linear_model, pipeline
from sklearn.pipeline import FeatureUnion
from sklearn.pipeline import Pipeline

my dataframe

df = pd.DataFrame({'a':[1,2,3], 
                   'date_survey': ['10.01.2013', '20.02.2014', '30.03.2015'],
                   'birth': ['1985', '1984', '1986'] })

The code for pipeline

X = df[['date_survey', 'birth']]
y = df['a']
class MultiColumn:
    def __init__(self,columns = None):
        self.columns = columns # array of column names to encode

    def fit(self,X,y=None):
        return self
    def transform(self, X):                                                           
        return X[self.columns]
class Age(TransformerMixin):

    def transform(self, X, y=None, **fit_params): 
        X['date_survey'] = pd.to_datetime(X['date_survey'])
        year = pd.DataFrame(X['date_survey'].apply(lambda x: x.year))
        age = X['birth'].convert_objects(convert_numeric=True) - year
        return age

    def fit(self, X, y=None, **fit_params):
        return self
regressor = linear_model.SGDRegressor()
pipeline = Pipeline([
          ('union', FeatureUnion(
        transformer_list=[    
             # age
            ('age', Pipeline([
                ('selector', MultiColumn(columns=['date_survey', 'birth'])),
                ('date', Age())

            ])),
        ])),
    # Use a regression
    ('model_fitting', regressor),
])
pipeline.fit(X, y)

and i get an error

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

I guess that the error in class Age, but i cann't understand how to improve it




Checking if class is of certain type

I'm trying to create a method inside a class that will take Class as a parameter and will check if the current object is of that type. The code i have:

public class MyEvent extends MyBPMNNode {

public boolean isKindOf(Class<?> node) {
    boolean b = MyEvent.this instanceof node;
    return b;
}

But i compile it it gives me:

Error:(9, 45) java: cannot find symbol
symbol:   class node

What am i doing wrong here? Maybe my understanding of the 'Class' class is not right.




Write an instance method advance the time by those minutes

i'm new to swift and am self teaching myself. I know its customary to have sample code but i'm extremely lost. I'm trying to write an instance method advance that will be placed inside the ClockTime class. The method accepts a number of minutes as its parameter and moves your object forward in time by that amount of minutes. The minutes passed could be any non-negative number, even a large number such as 500 or 1000000. If necessary, your object might wrap into the next hour or day, or it might wrap from the morning ("AM") to the evening ("PM") or vice versa. (A ClockTime object doesn't care about what day it is; if you advance by 1 minute from 11:59 PM, it becomes 12:00 AM.)

For example, the following calls would produce the following results:

ClockTime time = new ClockTime(6, 27, "PM");




PHP Project Composer autoload can't find the classes

I'm building an authentication system and I use Composer to manage dependencies. When I run my project it seems none of the classes can be found. I generated the files using cmd. I found similar threads here and here but it does not quite do it... Any idea?

The error

Fatal error: Class 'Bixxcom\User\User' not found in C:\xampp\htdocs\authentication\app\start.php on line 34

start.php

<?php
use Slim\Slim;
use Slim\Views\Twig;
use Slim\Views\TwigExtension;
use Noodlehaus\Config;
use Bixxcom\User\User;
use Bixxcom\Helpers\Hash;

session_cache_limiter(false);
session_start();

ini_set('display_errors', 'On');

define('INC_ROOT', dirname(__DIR__));

require INC_ROOT . '/vendor/autoload.php';

$app = new Slim([
    'mode' => file_get_contents(INC_ROOT . '/mode.php'),
    'view' => new Twig(),
      'templates.path' => INC_ROOT . '/app/views'
]);

$app->configureMode($app->config('mode'), function() use ($app){

    $app->config = Config::load(INC_ROOT .  "/app/config/{$app->mode}.php");

        });

        require 'database.php';
          require 'routes.php';

        $app->container->set('user', function(){
            return new User;
        }  );

                $app->container->singleton('hash', function() use ($app){
                    return new Hash ($app->config);
        });


        $view = $app->view();
        $view->parserOptions = [
            'debug'  => $app->config->get('twig.debug')
   ];

           $view->parserExtensions = [
               new TwigExtension
           ];

composer.json

{

    "autoload":{
        "psr-4":{
            "Equalcast\\":  "app/Equalcast"
        }
    },


    "require": {
        "monolog/monolog": "1.0.*",
        "slim/slim": "~2.0",
        "slim/views": "0.1.*",
        "twig/twig": "~1.0",
        "phpmailer/phpmailer": "~5.2",
        "hassankhan/config": "0.8.*",
        "illuminate/database": "~5.0",
        "ircmaxell/random-lib": "~1.1"
    }
}

enter image description here




Python: a fast way to instantiate thousands of objects

class Job(object):
    def __init__(self, obj):
        # does some instantiation

for i in range(5834):
    Job(i)

I've timed the function __init__()

cnt: 5834
dur: 145.81797123
avg: 0.0249945099811 per call

It takes more than 2min just to create the objects for the program to start and that's too slow for me

I see two approaches here,
1. find out which step in __init__() takes a long time and optimize OR
2. parallelize creation on job obj

I prefer (2)

Is there some pattern to make the creation of jobs faster or would threading work (I'm not sure if the overhead for creating threads would be worse)?




(C++) Accessing private data from multiple classes for odeint calculations?

I am building a short script to calculate the maximum pitch and bounce felt by passengers of a vehicle, depending upon the vehicle's speed and road conditions. Currently, I have 5 different vehicle classes (SAE1, SAE2, SAE3, SAE4, SAE5), which contain some of the values needed for the calculation as initial values. There are three road condition classes (rough, smooth, track), where the rest of the required values for the calculation are stored. The user selects a vehicle class, and a type of road, and the program is to output the desired values.

I am in the very early stages of planning roughly how the code should be structured, but I am wondering what is the best way to access the data I need for the calculation. Since it's stored between two classes, does it make sense to make one class the friend of the other, and just put all the required math calculations as a function in the friend class?

I really do not want to use structures for this, as I want the variable values to be private. I am in the very early stages of building the structure for this program, so I don't have any real code to post.




Java arrays in classes and methods

I'm new to Java and got totally stuck in arrays in classes. Have been trying to find out the answer to set and get method when working with arrays, unfortunately couldn't get my head around where the problem actually was. Would highly appreciate is someone please could help to get it figured out. Here is my code:

public class Animal {
    private String name;
        public Animal(String name) {
            this.name = name;
         } //end of constructor

        public String getName(int i) {
            return this.name[i];
         } //end of getName

        public void setName(String name[]) {
            this.name = new String[] {"Tom", "Jerry"};
        } //end of setName

} //end of class Animal

I'm working in NetBeans and it highlights two error messages: - under get method: "an array required, but String found" - under set method: "incompatible types: String[] cannot be converted to String"

Can someone please explain what the error is? Seems it's quite simple but slipping sneaking away from my mind.

Many thanks




class class_daugther : public calss_mother

I can't find any info about this type of code. I'm not sure if this is a container or a pointer to a class_another.

Thank for helping




Lazy loading not possible with DI?

does dependency injection make it impossible to lazy load dependencies?

because of the fact that you need to pass instances to the constructor, you cannot make the instances later




Why can't I reference the instance/object outside the function I created it in?

Why can't I reference the instance/object outside the function I created it in and how can I fix this.

Simplified Code:

class MyClass:

    def PrintThis(self):
        print ("Hello World")



def MyClassPrinter():
    x = MyClass()

    x.PrintThis() #This Works





MyClassPrinter()

x.PrintThis() #This "is not defined"

This comes out as:

Hello World
Traceback (most recent call last):
  File "C:\User\Desktop\test.py", line 19, in <module>
    x.PrintThis() #This "is not defined"
NameError: name 'x' is not defined

I apologise if this is a stupid question or already answered somewhere else.




How is this class's __call__ method working, when it's called without proper arguments?

I'm going through Daniel Nouri's tutorial on facial recognition using CNN's, and I've come across a bit of the code which I don't understand. Daniel is defining a Class to be called at the end of each iteration during the training of the network, that will decide whether or not the training should stop early:

class EarlyStopping(object):
    def __init__(self, patience=100):
        self.patience = patience
        self.best_valid = np.inf
        self.best_valid_epoch = 0
        self.best_weights = None

    def __call__(self, nn, train_history):
        current_valid = train_history[-1]['valid_loss']
        current_epoch = train_history[-1]['epoch']
        if current_valid < self.best_valid:
            self.best_valid = current_valid
            self.best_valid_epoch = current_epoch
            self.best_weights = nn.get_all_params_values()
        elif self.best_valid_epoch + self.patience < current_epoch:
            print("Early stopping.")
            print("Best valid loss was {:.6f} at epoch {}.".format(
                self.best_valid, self.best_valid_epoch))
            nn.load_params_from(self.best_weights)
            raise StopIteration()

This makes some sense, however the actual implementation in the code looks like:

net8 = NeuralNet(
# ...
on_epoch_finished=[
    AdjustVariable('update_learning_rate', start=0.03, stop=0.0001),
    AdjustVariable('update_momentum', start=0.9, stop=0.999),
    EarlyStopping(patience=200),
    ],
# ...
)

Clearly, Daniel is calling the class as a function. However, I don't understand how he is calling it without the arguments shown in __call__(args). Is this just how things are meant to be implemented in the source code of nolearn? I'm confused as to how the network knows to use nn and train_history without those being passed into the function.




How to get class from string class name in Symfony

I need to access a const like this:

dump (Accomodation::MAX_IMAGES);

but I only have the string class name but not the class itself. For example, I have this string 'AppBundle:Accomodation' but I don't have the class Accomodation to access its static properties.

Any idea for Symfony?




Bug or Feature in R's version 3.3 class constructing

Trying to build a new class on the base of an 'ordered' class, using R.version 3.3.1 tried also on new R-devel
R Under development (unstable) (2016-10-26 r71594) -- "Unsuffered Consequences"
I get an error:

> setClass('newFactor', representation = c(tempValue = 'character'), contains = c('ordered'))
Error in validObject(.Object) : 
  invalid class “classRepresentation” object: invalid object for slot "slots" in class "classRepresentation": got class "character", should be or extend class "list"
> 

The same thing works on the stable Version 3.2.5: enter image description here

Is this a new way of constructing a class or a bug in R's version?




samedi 29 octobre 2016

How to design two almost similar cluster of classes, one of them have some additional properties and methods.

Now I have a father class and some child classes. I need to add some properties and methods into the father class (new class named father*). Correspondingly, I would like all the child classes add these things. I'm using Python.

A sketch for what I'm saying is below. the only difference between clusters of classes at left and right (without and with *) is the additional properties and methods.

enter image description here fig.1 Sketch of class clusters




Reading server response in python

I am using BACpypes library. The working of the library is such that the client sends a request and code runs a run function. It gets responses from various servers in the network. Each response is shown on the indication function present in server class. Run function sends responses of each server serially to indication function.

As I am writing a python script, I want the client to get back the response from servers. The Only thing I can do is to send it in self.variable form, but since run function updates indication function completely after each response, I lose the first server responses in the self.variables and get back only last server response. SO I need to create something like self.list which has an index and updates the responses. Also, since no. of times run function updating indication function is dependent on the number of server devices in the network, I need to have a self.list with dynamic indexing. Anyone have any suggestion in how to implement self.list().

**I can't change response to bypass indication function because its in-built in the library. Thanks for help




Python homework assignment: Design with Classes

everyone. I need help with a Python homework assignment. I have no idea where to even start. The project is:

A simple software system for a library models a library as a collection of books and patrons. A patron can have at most three books out on loan at any given time. Each book has a title, an author, a patron to whom it has been checked out, and a list of patrons waiting for that book to be returned When a patron wants to borrow a book, that patron is automatically added to the book's wait list if the book is already checked out. When a patron returns a book, it is automatically loaned to the first patron on its wait list who can check out a book. Each patron has a name and the number of books that patron has currently checked out. Develop the classes Book and Patron to model these objects. Think first of the interface or set of methods to be used with each class, and then choose appropriate data structures for the state of the objects. Also write a short script to test these classes.

If someone could help me out with this, I would really appreciate it. Thanks!




python: Instantiate class only once and mantain global vars

First of all, I'm pretty new at coding world and all that I`ve learn in the past few years it is basic due to this fantastic site and others great tutorials on the internet. So, I apologize for my noobie question/terms:

I have python project with init.py and a name.py files. In the name.py I have a class A() within has one method named start that I want to call. On name.py I also have an global variabe that I`ve used to store data from methods inside A class. Later I use decorators timeout and, when the timeout is reached, it grab the global variables content and save it into database.

However, the way I used my code is not right for my purposes. I first instantiate the A class using some like this:

### __init__.py
import name; 
a = name.A(); 
a.start({some_stuff}).

### name.py
global_list = []
Class A():
    def m1(data):
        global_list.append(     

    @decorator(10.0)
    Def save_on_db(sData):
        db.save(sData)

But when I do this (my global variable at name.py is restarted). Since I want to use the content of this global var for later purposes (do some queue for performance purposes), is there any way to instantiate my A class only once, so every time I call m1 method, I can keep the values of my global var (global_list)?

Best Regards




How does typedef work in place of struct/class for Procedural c++?

I have to build a program(Procedural C++) that has two data types. One called Elem that is an element of a vector(single dimensional array). and One called Vector that contains an unsigned int for the size of the array and also the array of Elem's itself. I can't seem to figure out the correct way to structure these so that they work as I have never done anything with procedural c++ before.

This is what I have

typedef Elem {
    float Element;
}

typedef Vector {
    unsigned int size = 0;
    Elem* Array = new array[];
}

but I'm getting this error

C++ requires a type specifier for all declarations
typedef Elem {
~~~~~~~ ^

and also

error: expected ';' after top level declarator
typedef Elem {
            ^

I'm at a loss here, any help would be appreciated!




Scala - create class, inherit partial constructor parameter

In Scala, I want to create an abstract class, which accepts some "strategy" parameter (here myBase), and a value parameter (here myVal). I want to inherit from that class, providing the strategy parameter as part of the inheritance, and get a class (here Cls1) which accepts the value as a constructor parameter.

Here's the code I want to be able to run:

abstract class Base(myBase: Int)(val myVal: Int) {
  val divVal: Int = myBase / myVal
}

class Cls1 extends Base(10) // myBase = 10
val obj1 = new Cls1(5) // myVal = 5
assert(obj1.divVal == 10/5)

Unfortunately, I get the following errors:

Error: too many arguments for constructor Cls1: ()A$A58.this.Cls1 lazy val obj1 = new Cls1(5) Error: missing argument list for constructor Base in class Base class Cls1 extends Base(10)

Can you please explain how can I accomplish this without repeating the logic (here myBase / myVal)?

Thanks!




Why won't figure.area = ... not work? Swift 3.0

struct Shape{

    struct Rectangle {
        var length = 0
        var width = 0
        var area = 0

    }

    struct Square {
        var length = 0
        var width = 0
        var area = 0

    }

    func area(length: Float, width: Float) -> Float {
        return length * width
    }

}

var figure = Shape.Rectangle()
figure.width = 2; figure.length = 3

figure.area = Shape.area(figure.length,figure.width)

Why won't figure.area = ... not work? It allows me to write that in xCode but it doesn't run properly in the PlayGround. Can you declare a function inside of a class? If yes, how do I declare this (figure.area = Shape.area(figure.length,figure.width)) properly?




Dataframe Object is not callable

I am posting my codes here directly. When I run it, it keeps telling me the dataframe object is not callable. Still don't know why after one and half hours:

` class OptionDataWebGleaner():

def __init__(self):

    ticker = pd.read_csv('Yahoo_ticker_List.csv')['AUB.AX'].values
    stock = raw_input('Please give the ticker of your selected option?\n')

    if stock in ticker:

        self.stock = stock
    else:

        raise TypeError('Your option is not available here.')

    date_norm = raw_input('Please give your maturity date in the format of mm/dd/yyyy\n')

    maturity_date = datetime.strptime(date_norm, '%m/%d/%Y').date()

    self.maturity_date = maturity_date
    self.today = date.today()

    dates = ['1481846400', '1484870400', '1487289600']
    maturity_dates = [date(2016, 12, 16), date(2017, 1, 20), date(2017, 2, 17)]
    date_dict = {}

    for v in zip(dates, maturity_dates):
        date_dict[v[1]] = v[0]

    try:
        self.d = date_dict[self.maturity_date]
    except:
        print('Your maturuity date is not available')

    option = raw_input('Please give the type of your option, either call or put\n')

    self.option_type = option + 's'

@property
def crawl_data(self):  # self #option_type: calls or puts. str

    stock = self.stock
    option_type = self.option_type
    maturity_date = self.maturity_date
    d = self.d

    chromedriver = "/Users/Miya/Downloads/chromedriver.exe"
    os.environ["webdriver.chrome.driver"] = chromedriver
    driver = webdriver.Chrome(chromedriver)
    today = self.today

    ## Get the url
    url = 'http://ift.tt/2blrZr3' + stock + '/options?date=' + d
    ## Crawl data
    driver.get(url)
    html_source = driver.page_source
    ## Beautifulsoup
    soup = BeautifulSoup(html_source, 'html.parser')


    if soup.find('table', option_type) is not None:

        stock_price = [float(i.text) for i in soup.findAll('span', 'Fz(36px)')]
        title = [i.text for i in soup.find('table', option_type).find_all('th')]
        text = [i.text for i in soup.find('table', option_type).find_all('td')]
        rows = [row for row in soup.find('table', option_type).find_all("tr")]

        l_table = len(rows) - 1
        ## call/put data
        dictionary = {}
        dictionary['maturity_date'] = [maturity_date] * l_table
        dictionary['date'] = [today] * l_table
        dictionary['stock_price'] = stock_price * l_table

        for j in range(10):
            key = title[j]
            dictionary[key] = []
            for i in range(l_table):
                dictionary[key].append(text[10 * i + j])

        ## write into dataframe

        dataframe = pd.DataFrame(dictionary)


    return dataframe

def clean_data(self):

    dataframe = self.crawl_data()

    print('Remove unexpected symbols...')

    columns_to_set = ['Last Price', 'Open Interest', 'Strike', 'Volume', 'Implied Volatility']
    for i in columns_to_set:
        series = dataframe[i]
        series_new = []
        for j in series:
            j = str(j)
            j_new = ''.join(ch for ch in j if (ch != '%') and (ch != ','))
            series_new.append(j_new)
        dataframe[i] = series_new
    print('Change the data type...')

    ## change the dtype
    columns_to_change = ['Last Price', 'Open Interest', 'Strike', 'Volume', 'stock_price', 'Implied Volatility']

    for i in columns_to_change:
        dataframe_cleaned[i] = dataframe[i].astype(float)

    print("Remove missing values...")

    dataframe_cleaned = dataframe_cleaned.dropna()

    # print("Clean Outliers...")

    # dataframe = dataframe.loc[dataframe['Implied Volatility'] <= 2]

    return dataframe_cleaned

def save_file(self):

    save_file = raw_input("Do you want to save the file into csv? Type Y for yes, N or no\n ")
    d = self.d
    stock = self.stock
    df_option = self.clean_data()

    if save_file == 'Y':
        csv_name = stock + d + '.csv'
        df_option.to_csv(csv_name)
        print("File Saved!")

def viz(self):

    dataframe = self.clean_data()
    stock = self.stock
    time_to_maturity = []
    dataframe = dataframe.sort_values(by='Strike')
    ## grab dataframe, then relevant data
    for i, j in zip(dataframe.maturity_date, dataframe.date):
        time_to_maturity.append((i - j).days / 365)

    strike_price = dataframe['Strike']

    # generate pseudo-implied volatility by using strike price and time-to-maturity as parameters

    implied_vol = dataframe['Implied Volatility'].values

    strike_price, time_to_maturity = np.meshgrid(strike_price, time_to_maturity)

    fig = plot.figure(figsize=(10, 5))  ## a plot object
    ax = Axes3D(fig)  # create a 3D object/handle

    ##plot surface: array row/column stride(step size:2)
    ##plot surface: array row/column stride(step size:2)

    surf = ax.plot_surface(strike_price, time_to_maturity, implied_vol, rstride=2, cstride=2, cmap=cm.coolwarm,
                           linewidth=0.5, antialiased=False)

    # set x,y,a labels
    ax.set_xlabel('Strike Price')
    ax.set_ylabel('time to maturity')
    ax.set_zlabel('implied volatility%')
    plot.suptitle(stock)
    plot.show()

def summary(self):

    dataframe = self.clean_data

    print(dataframe.describe())

OptionDataWebGleaner().viz()