dimanche 31 juillet 2016

Overriding ParentModel class method in Child class

I have Parent Model class and viewModel class. Parent Model class has GetViewModel() method and I am trying to inherit Parent class and override the GetViewModel() in Child class.However, it throws an infinite exception.

Parent ViewModel Class:

public class ParentViewModel
{
    public IEnumerable<string> Choices { get; set; }
    public object Value { get; set; }
    public IMetaField MetaField { get; set; }
    public bool IsRequired { get; set; }
    public bool HasOtherChoice { get; set; }
    public string ValidationAttributes { get; set; }
    public string RequiredViolationMessage { get; set; }
    public string CssClass { get; set; }
}

Parent Model Class:

public class ChildModel : ParentModel
{
    public string CorticonEntityName { get; set; }
    public string CorticonFieldName { get; set; }

    public override object GetViewModel(object value, IMetaField metaField)
    {
        this.Value = value;
        return (object)new ChildViewModel()
        {
            Choices = this.DeserializeChoices(),
            Value = value,
            MetaField = this.MetaField,
            HasOtherChoice = this.HasOtherChoice,
            IsRequired = (this.ValidatorDefinition.Required.HasValue && this.ValidatorDefinition.Required.Value),
            ValidationAttributes = this.BuildValidationAttributesString(),
            RequiredViolationMessage = this.ValidatorDefinition.RequiredViolationMessage,
            CssClass = this.CssClass
        };
    }
}

I have created two child classes ChildModel class and ChildViewModel classs which are inheriting parent lasses.

I want to override the GetViewModel() of parent class so I have done as below and working perfectly.

ChildViewModel class:

public class ChildViewModel:ParentViewModel
{
    public string CorticonEntityName { get; set; }
    public string CorticonFieldName { get; set; }
}

ChildModel Class:

public class ChildModel : ParentModel
{
    public string CorticonEntityName { get; set; }
    public string CorticonFieldName { get; set; }

    public override object GetViewModel(object value, IMetaField metaField)
    {
        this.Value = value;
        return (object)new ChildViewModel()
        {
            Choices = this.DeserializeChoices(),
            Value = value,
            MetaField = this.MetaField,
            HasOtherChoice = this.HasOtherChoice,
            IsRequired = (this.ValidatorDefinition.Required.HasValue && this.ValidatorDefinition.Required.Value),
            ValidationAttributes = this.BuildValidationAttributesString(),
            RequiredViolationMessage = this.ValidatorDefinition.RequiredViolationMessage,
            CssClass = this.CssClass,
            CorticonEntityName=this.CorticonEntityName,
            CorticonFieldName=this.CorticonFieldName
        };
    }
}

But I don’t’ want set all the properties in child class GetViewModel() again as the parent GetViewModel() is doing. I wanted to reuse the Parent class method and set new properties in Child class so I tried as below but it is throwing infinite loop.

ChildViewModel class:

public class ChildViewModel:ParentViewModel
{
    public string CorticonEntityName { get; set; }
    public string CorticonFieldName { get; set; }
    CheckboxesFieldViewModel baseObject { get; set; }
}

ChildModel Class:

public class ChildModel : ParentModel
{
    public string CorticonEntityName { get; set; }
    public string CorticonFieldName { get; set; }
    CheckboxesFieldViewModel baseObject { get; set; }

    public override object GetViewModel(object value, IMetaField metaField)
    {
        object objBase=this.GetViewModel(value,metaField);
        return (object)new ChildViewModel ()
        {
            objParent=objBase,
            CorticonEntityName = this.CorticonEntityName,
            CorticonFieldName = this.CorticonFieldName
        };
    }
}

How can reuse the Parent class GetViewModel() without setting the properties again.




dart pub build class name minification

Running pub build --mode release applies minification to the generated javascript. The following piece of code illustrates that this may break code which relies on class names:

class ImageAsset {
    ...
}


Map<String, Type> map = new Map<String, Type>()..putIfAbsent("key", () => ImageAsset);


print("class name: ${map["key"]}"); // prints "class name: e4" or similar

What is the best way to deal with this?

  • Is it possible to preserve class names while not turning off minification completely?
  • Should I not rely on class names at all? I wanted to use Type instead of String for easier refactoring.



Why is this invalid syntax? (Class function)

The code I am trying to enter (python) looks like this:

class RainfallTable:
    def _init_ (self, njrainfall.txt):
        self.njrainfall.txt = open(njrainfall.txt, 'r')
    def close(self):
        if self.t:
            self.t.close()
            self.t = None

I am trying to get this class to simply open a file called njrainfall.txt, but I get the following error message when I do so:

  File "3Homework.py", line 2
def _init_ (self, njrainfall.txt):
                            ^

What am I doing wrong?




How to update a UILabel's text based on a instance's property

I'm attempting to update my "Lives Remaining: " UILabel, and I'm having trouble getting it to update based on a class's or instances current variable value- in this case lives. I'm using didSet to do so in my following code:

The Ship class:

class Ship:SKSpriteNode{

    ...

    var lives:Int = 0{
        didSet{
            shipLivesLabel?.text = self.lives.description

        }
    }

Instantiating the label in GameScene:

class GameScene: SKScene, SKPhysicsContactDelegate {

    private var shipLives = 0 {
        didSet{
            self.shipLivesLabel?.text = aShip.lives.description
        }
    }
    private var shipLivesLabel:SKLabelNode?

and where I'm adding it to the scene:

override func didMoveToView(view: SKView) {

    let shipLivesLabel = SKLabelNode(fontNamed: "Times New Roman")
    shipLivesLabel.text = shipLives.description
    shipLivesLabel.fontSize = 14
    shipLivesLabel.position = CGPoint(x:CGRectGetMidX(self.frame)*1.3,y:CGRectGetMidY(self.frame)*0.1)
    self.addChild(shipLivesLabel)
    self.shipLivesLabel = shipLivesLabel

I'm not sure if this is the proper way to go about this, and I'm also not sure how to reference the shipLivesLabel within the Ship class- I receive the error: Instance member shipLivesLabel cannot be used on type GameScene. Any help would be awesome.




How to copy a class object to another class object

Assume Fraction with properties int num and int denom and NSString *label. All through @property. Suppose we provide copy method (not through NSCopying protocol) so we can do

Fraction *g = [Fraction some initializer here];

Fraction *f = [g copy];

Show exactly what is needed in Fraction.h and Fraction.m to get this shallow.




Arduino: Class using multiple instance of another class

I want to learn how to use class object within class, especially how to pass an arguments between the objects. I'm trying to create an example object Calc which should provide two methods Calc.sum and Calc.sub. It should use another object Plus as a math engine. The Plus.add function compile and works well. But I don't know how to initiate multiple instance of plus in the calc. The code:

class Plus{                     // This class works well
    public:
        Plus(int);              // Structure
        int add(int);           // Public method (function)
        int myVar;              // Public property. Just to hold a value.
    private:
        int _init;              // Class-level private variable
};

Plus::Plus(int init){           // Constructor
    _init = init;
}

int Plus::add(int p){           // Method add
    return _init + p;
}

/***************************************************************************/

class Calc{
    public:
        Calc(int);              // Structure
        int sum(int);           // Method sum
        int sub(int);           // Method sub
        int myVar;              // Public property
    private:
        Plus positive(int);     // Class-level private object definition ?
        Plus negative(int);     // This is probably wrong ??
};

Calc::Calc(int init){           // Constructor (also wrong...)
    Plus positive(init);        // Create object "positive" and pass the initial value
    Plus negative(-init);       // Create object "negative" and pass the initial value
}

int Calc::sum(int n){
    return positive.add(n);
}

int Calc::sub(int n){
    return negative.add(n);
}

/***************************************************************************/

Plus two(2);        // Create class object two
Calc five(5);       // Create class object five

void setup(){
    Serial.begin(115200);

    Serial.print("two.add(3) = ");
    Serial.println(two.add(3));         // Calling instance of class Plus
    two.myVar = 100;
    Serial.println(two.myVar);

    Serial.print("five.sum(3) = ");
    Serial.println(five.sum(3));        // Calling instance of class Calc

    Serial.print("five.sub(3) = ");
    Serial.println(five.sub(3));        // Calling instance of class Calc
}

void loop(){}

My example is inspired by this article: http://ift.tt/2a9FXx1 but the code there is for one instance only

1) How to declare multiple instances of Plus within Calc

2) Is the terminology (comments) right?




Cant copy properities of one class to another using BeanUtils

I have a piece of code where I copy the similar properities of one class to another using BeanUtils.copyProperities(dest, orig). However. This does not work. I get the error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

I am using BeanUtils 1.9.2, Java 8, Windows 10, Eclipse.

import org.apache.commons.beanutils.*;

public class Main{
    public Main(){
        Entity entity = new Entity();
        AbstractGameObject aEntity = new AbstractGameObject();
        try {
            BeanUtils.copyProperties(aEntity, entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(aEntity.similar); // Should print out 10, No?;
    }
    public static void main(String[] args) {
        Main main = new Main();
    }
    private class Entity{
        int similar = 10;
        int differentE = 9;
        public Entity(){

        }
    }
    private class AbstractGameObject{
        int similar = 2;
        int differentA = 1;
        public AbstractGameObject(){

        }
    }
}




Creating separate class for listener

What is the advantage of creating separate class for listener OR is there any?Which of the below code is more efficient and why?When should i create separate class?

Separate class for TextWatcher

mEditText.addTextChangedListener(mNumberWatcher);
TextWatcher mNumberWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {


        }
    };

No Separate class

mEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });




Confusion with classes and global variables

I've come to a halt in the making of my first project. I'm trying to make a timecard program. I decided to use class object to handle the variables locally, but I can't figure out how to create a class object from user input.

import time
import datetime
import sqlite3

class Employee(object):
    def __init__(self, name, position, wage=0, totalpay=0, totalhours=0):
        self.name = name
        self.position = position
        self.wage = wage
        self.totalpay = totalpay
        self.totalhours = totalhours

    def HourlyPay(self):
        if self.position not in range(1, 4):
            return "%s is not a valid position" % self.position
        elif self.position == 1:
            self.wage = 105.00
        elif self.position == 2:
            self.wage = 112.50
        elif self.position == 3:
            self.wage = 118.50
        return "%s at position %i is making %i DKK per hour" % (self.name, self.position, self.wage)


    def Salary(self, hours):
        self.hours = hours
        self.totalpay += self.wage * self.hours
        self.totalhours += self.hours
        return "%s next salary will be %i DKK" % (self.name, self.totalpay)

# This is out Employee object
EmployeeObj = Employee('John Doe', 1) # Our Employee object
EmployeeObj.HourlyPay()
EmployeeObj.Salary(43) # Takes 'hours' as argument


# Temporary Database config and functions below
conn = sqlite3.connect('database.db')
c = conn.cursor()

# For setting up the database tables: name, position and total.
def Create_table():
    c.execute('CREATE TABLE IF NOT EXISTS EmployeeDb(name TEXT, position INTEGER, total REAL)')

# Run to update values given by our Employee object
def Data_entry():
    name = str(EmployeeObj.name)
    position = int(EmployeeObj.position)
    total = float(EmployeeObj.totalpay)
    c.execute('INSERT INTO EmployeeDb (name, position, total) VALUES (?, ?, ?)',
              (name, position, total))
    conn.commit()
    c.close()
    conn.close()
    return True

What I'm trying to achieve is to create this variable from user input:

EmployeeObj = Employee('John Doe', 1) # Our Employee object




define getter without setter ecma6 - react

React-ecma6 dosent seem to allow defining getters without setters Is there a way of defining a getter only method and changing a value through any other method?

import React from 'react';
export default class LoginRegister extends React.Component {
    constructor(props) {
        super(props);
        console.log("Login or Register page");
        this._is_on = false;
    }

    on() {
        this._is_on = true;
    }

    get is_on() {
        return this._is_on;
    }

    render() {

    }
}
var _getter = new GetterOnly()
_getter.on();

Uncaught TypeError: Cannot set property is_on of #GetterOnly which has only a getter




What does the new bootstrap uses private methods in es6 classes?

I was looking inside the source code of bootstrap 4, and I discovered they're using es6 classes coupled with some revealing module pattern of some sort.

Here is a simplified example of code taken from here

const Modal = (($) => {


  const NAME                         = 'modal'
  const VERSION                      = '4.0.0-alpha.3'
  ...

  const Default = {
    ...
  }


  class Modal {

    constructor(element, config) {
      this._config              = this._getConfig(config)
      this._element             = element
      ...
    }


    // public

    toggle(relatedTarget) {
      ...
    }

    show(relatedTarget) {
      ...
    }

    hide(event) {
      ...
    }

    dispose() {
      ...
    }


    // private

    _getConfig(config) {
      ...
    }

    _showElement(relatedTarget) {
      ...
    }

    _enforceFocus() {
      ...
    }

    _setEscapeEvent() {
      ...
    }

    _setResizeEvent() {
      ...
    }

  }

  return Modal

})(jQuery)

export default Modal

This would result in every method or property being exposed, also the private ones, however this does not happen in the final product, for esample something like $('#myModal').modal('_getConfig') will not work, what is happening?




Friend function of a class cannot be accessed by member function of that class [on hold]

I want to call a friend function of a class inside a member function of that class definition but it doesn't work when I put the friend function definition after the class definition. However if I put the friend function definition before the class definition it would work. Can anyone explain in details the rules that enforce this behavior?

The following doesn't work:Error: subtract was not declared in this scope

class Person
{
public:
    Person (int Height, int Weight);
    void output();
    friend int subtract(int a,int b);
private:
    int height;
    int weight;
};

int main()
{
    Person John(180,80);
    John.output();
}

Person::Person (int Height, int Weight):height(Height),weight(Weight)
{
}
void Person::output()
{
    cout<<height<<"and"<<weight<<endl;
    cout<<subtract(height,weight);
}
int subtract(int a,int b)
{
    return (a-b);
}

This works

#include<iostream>
using namespace std;
int subtract(int a,int b)
{
    return (a-b);
}
class Person
{
public:
    Person (int Height, int Weight);
    void output();
    friend int subtract(int a,int b);
private:
    int height;
    int weight;
};

int main()
{
    Person John(180,80);
    John.output();
}

Person::Person (int Height, int Weight):height(Height),weight(Weight)
{
}
void Person::output()
{
    cout<<height<<"and"<<weight<<endl;
    cout<<subtract(height,weight);
}




pascal dispose causes segmentation fault yet i cant see why

program Project1;

type
  ob = class
    num: integer;
    constructor init(id: integer);
    destructor done();
  end;

  constructor ob.init(id: integer);
  begin
    self.num := id;
  end;

  destructor ob.done();
  begin
  end;

type
  plist = ^list;

  list = record
    myob: ^ob;
    Next: plist;
  end;
var start:plist;
begin

  start:=nil;
  new(start);
  start^.myob^:=ob.init(1);
  new(start^.next);
  start^.Next^.myob^:=ob.init(2);
  start^.next^.myob^.done();
  dispose(start^.Next);
  start^.myob^.done();
  dispose(start);

end.

this code results in Error: Project project1 raised exception class 'External: SIGSEGV'. At address 405B32

when i try to run in debug i get the assembler screen popup and display

SYSTEM_$$_SYSGETMEM$LONGWORD$$POINTER(147)
00405B23 b890e44000               mov    $0x40e490,%eax
00405B28 e813080000               call   0x406340 <SYSTEM_$$_ENTERCRITICALSECTION$TRTLCRITICALSECTION>
00405B2D 89d8                     mov    %ebx,%eax
00405B2F 8b5004                   mov    0x4(%eax),%edx    <-error here
00405B32 8b92a0000000             mov    0xa0(%edx),%edx   <-or it might be here
00405B38 89500c                   mov    %edx,0xc(%eax)
00405B3B 8b5004                   mov    0x4(%eax),%edx
00405B3E 8982a0000000             mov    %eax,0xa0(%edx)
00405B44 b890e44000               mov    $0x40e490,%eax
00405B49 e802080000               call   0x406350 <SYSTEM_$$_LEAVECRITICALSECTION$TRTLCRITICALSECTION>

any help would be appreciated

how do i go about fixing this it seems to only happen when i try to use dispose thank you in advance




JOptionPane won't appear

i'm a beginner of java. and this is the very first time i encounter this problem. every time i run my program the JOptionPane.showInputDialog won't appear. here's my whole code can you see if there is something wrong:

import javax.swing.*;
public class StackTester {

public static void main(String[] args) {
    Stack st=new Stack();

    String [] menu={"Set Capacity", "Push", "Pop", "Search", "Clear", "Exit"};
    String message="Capacity: "+st.getCapacity()+"\nElements: "+st.display()+
            "\nEmpty: "+st.isEmpty()+"\nFull: "+st.isFull()+
            "\n# of Elements: "+st.count()+"\nFirst: "+st.first()+"\nLast: "+st.last()+"\n";


    String choice="";
    int data=0;

    do{
        choice=(String)JOptionPane.showInputDialog(null, message+"Input Choice:", "Menu", 1, null, menu, menu[0]);

        switch(choice){
        case "Set Capacity":
            st.setCapacity();
            st.getCapacity();
            break;
        case "Push":
            data=Integer.parseInt(JOptionPane.showInputDialog("Enter data: "));
            st.push(data);
            break;
        case "Pop":
            st.pop();
            JOptionPane.showMessageDialog(null, "Popped!");
            break;
        case "Search":
            data=Integer.parseInt(JOptionPane.showInputDialog("Enter data to search: "));
            JOptionPane.showMessageDialog(null, st.search(data));
            break;
        case "Clear":
            st.clear();
            JOptionPane.showMessageDialog(null, "Stack cleared");
            break;
        }
    }while(!choice.equals("Exit"));

}

}

i tried making another class and declared some showMessageDialog just to see if there is something wrong with the JOptionPane and not my code but it works. just here in this class nothing won't appear.




Why favor object.__setattr__(self, name, value) only in new style classes?

According to Python 2.7.12 documentation:

If __setattr__() wants to assign to an instance attribute, it should not simply execute self.name = value — this would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g., self.__dict__[name] = value. For new-style classes, rather than accessing the instance dictionary, it should call the base class method with the same name, for example, object.__setattr__(self, name, value).

However, the following code works as one would expect:

class Class(object):
    def __setattr__(self, name, val):
        self.__dict__[name] = val;

c = Class()
c.val = 42
print c.val

I know super(Class, obj).__setattr__(name, value) can ensure the __setattr__ methods of all base classes to be called, but classic class can also inherit from bases classes. So why is it only recommended for new style classes?

Or, on the other hand, why is doing so not recommended for classic classes?




PHP class declaration explanation needed

Okay so example 3 on this page http://ift.tt/1mWC21T

  1. What is Test $other in function baz(Test $other), i got that $other is argument for function however why Test and space is before it?
  2. whats the point of passing "test" and "other" arguments when initiating class they do anything?
  3. Whats the big deal about calling private method in this example?

    class Test { private $foo;

    public function __construct($foo) {
        $this->foo = $foo;
    }
    
    private function bar() {
        echo 'Accessed the private method.';
    }
    
    public function baz(Test $other) {
        // We can change the private property:
        $other->foo = 'hello';
        var_dump($other->foo);
    
        // We can also call the private method:
        $other->bar();
    }
    
    

    }

    $test = new Test('test');

    $test->baz(new Test('other'));




samedi 30 juillet 2016

what is wrong with the code above?

why I can't compile this code, I know is something wrong but I don't know what to do...


#include <iostream>
#include <string>


class A {
    public:
    int x;
    private:
    int y;
    protected:
    int z; 
    };

    class B : public A {
        // x is public
        // y is protected
        // z is not accessible from B 
    };

    class C : private A {
        // x is protected
        // y is protected
        // z is not accessible from C
        };

    class D : protected A {

    // x is private
    // y is private
    // z is not accessible from D
        };




How can I call a Subclass object from a Superclass and is there a better way to do this? (Python 3)

I am creating a game in python(3) and I have a main class with the game loop and a bunch of variables in it. I have a subclass of this to create "path" objects, and I need the variables from the main class. I also need to call the subclass from the main, superclass. Every time I call the subclass, it also calls the main classes init method to pass variables through. The problem is when this happens, it resets the values of all my variables in the main class.

class Main:
    def __init__(self):
        foo = 0 
        sub1 = Sub()

    def foo_edit(self):
        self.foo += 5

    def main(self):
        sub2 = Sub()


class Sub(Main):
    def __init__(self):
        super(Sub, self).__init__()
        self.bar = 0

    def foo_edit(self):
        self.foo += 10

I've looked at many other similar questions, but none have given me the answer I need. I tried sub1 in my code(in the init function of main) and this creates a recursion loop error because the init functions call eachother forever. When I call it in the gameloop(or main in this example) it re initializes Main each time it is called, wiping the variables needed in Sub. Before I only had one instance of the "path" so I had no need of class, and had a function. Now that I need multiple "path" objects I am using a subclass of main to get the variables I need.

A solution to this problem that does or does not answer my question(calling a subclass from a superclass might be a bad idea) would be appreciated. Thanks in advance.




JDK 8 made Interface to have non-abstract methods then why to use abstract class?

Why we have both Interface and abstract class, even we can achieve interface by making all methods of abstract class abstract. Please explain the usage difference between both.

List list = new ArrayList(); ArrayList arraylist = new ArrayList();

what difference the above two lines make, except dynamic method dispatch. Rather if we define with ArrayList reference we can have more methods to use.

Thanks in Advance. :)




Singleton classes in ruby and their utility

what is a singleton class ? why they have been created? and what is the impact of them on the consistency? .I am running into some confusions while doing meta-programming in Ruby




How to concatenate 3 of MyStrings?

I am working on creating my own string class. I have almost finished it, but my test fails when I try and run the code below. All of my tests work except when I try and concatenate using the statement below. I posted my code to pastebin below, along with the test file I'm trying to run and the line number of my failed attempt. Any help would be greatly appreciated. Thanks!

Line 35 always fails:

s2 = 'a' , s4 = 'b' , s16 = 'c'

assert(((s2+s4)+s16) == "abc");

string.hpp:

string.hpp

string.cpp:

string.cpp

test_concat.cpp:

test_concat




c++ array of the same class hierarchy problem77

According to my book, if I want to make an array of objects that are not in the same class but in the same class hierarchy, I need to use pointers:

class text
{
public:
void write(string text);
void show();
private:
string texte;
};

void text::write(string text)
{
texte = text;
}

void text::show()
{
cout << texte;
}


class text_with_stars : public text
{
public:
void show();
};

void text_with_stars::show()
{
cout << "*";
text::show();
cout << "*";
}

int main()
{
text* array[2];
array[0] = new text;
array[0]->write("Hello");
text_with_stars* pointer = new text_with_stars;
pointer->write("Hi");
array[1] = pointer;
for (int i=0;i<2;i++)
{
    array[i]->show();
}
return 0;
}

But when I do this, the output is "HelloHi" meaning that the second object used the show version that is from text and not from text_with_stars but I made it exactly the same way that the book described. What Is the problem??




The template definition could specify specific type?

In this class template definition, seems uses a specific type:

template <unsigned int nWords>
class BitField
{
   enum {
    NumWords = nWords,
    BPW_2 = 5, // Bits per word, log 2
   };
   ...
   Bool operator==( const BitField<nWords> &rhs ) const;
   BitField<nWords>  operator|  ( const BitField<nWords> &rhs ) const;

   private:
      unsigned int _aWords[NumWords];
}

The code seems to be right, but I do not understand using template like this.




How to use an array of data and a for loop to instantiate objects. JavaScript

I have two arrays one with data

var elements = [["1","a",1],["2","b",2],["3","c",3]];

And another one with names of the objects which I want to create using data above.

var names =["a1","a2","a3"];

This is the prototype class

var Video = function(title,uploader,seconds){
    this.title = title;
    this.uploader = uploader;
    this.seconds = seconds;
}

Or is maybe is there other way to complete this task ?

Use an array of data and a for loop to instantiate 5 Video objects.




Delphi: How can I reset all class fields to zero value?

I have a class with many numeric fields, number of fields will grow up with project development, so would be nice to have a way to reset all fields, no matter how many will be added in future.

 TParams = class
  public
    defined:  boolean;
    FirstValue:             byte; // reset from here
    A0:       single; 
    A1:       single; 
    H1:       TPoint;
       // ...............
    A100:     single; 
    LastValue:             byte; // to here
    procedure Reset;
  end;

The only idea comes to mind is to insert 2 fields: before and after block that should be reseted, and use FillMemory:

procedure TParams.Reset;
begin
  FillMemory(@FirstValue, Integer(@LastValue)-Integer(@FirstValue),0);
end;

Is there better way ? (Im using Delphi 7)




How to "promote" an instance to a subclass?

Suppose I have the following classes:

class Plain(object):
    def speak(self):
        print 'ho-hum'

class Fancy(Plain):
    def exult(self):
        print 'huzzah!'

plain = Plain()
plain.speak()
# ho-hum
plain.exult()
# ---------------------------------------------------------------------------
# AttributeError                            Traceback (most recent call last)
# <ipython-input-585-5f782c9ea88b> in <module>()
# ----> 1 plain.exult()
fancy = Fancy()
fancy.speak()
# ho-hum
fancy.exult()
# huzzah!

... and suppose that, for some reason, I want to "promote" an instance of Plain so that it becomes an instance of Fancy.

I know that I can always modify the instance's __class__ attribute:

plain.__class__ = Fancy
plain.exult()
# huzzah!

...but I gather from various SO posts (e.g., here, here) that this is not a good thing to do (at least not in production code).

Is there a more "production-code-worthy" way to promote an instance to a subclass?


FWIW, the real-world use-case that brings me to this problem is the following. I'm working with a 3rd-party library that implements a client for a web service. Among the things this client can do is return instances of various classes. These classes provide very few methods, and the few they provide are very weak. I can easily write subclasses for these classes with more, and more powerful, methods, but in order for them to be useful, I'd also need to write wrappers for those API functions that currently return instances of the API's original classes. Invariably, this wrappers would only have to promote the instances returned by the original ("wrappee") functions to instances of my enhanced subclasses.




Designing a BinarySearchTree - best design

When implementing a Binary Search Tree, some people write an implementation such as follows, where there is a Node class storing data and the left and right links, a BinarySearchTree class that implements all the methods such as insert, search and delete, and finally a driver class which has the main, to create an instance of the BinarySearchTree class and call the insert, search and delete methods.

class Node
{
 ..
}

class BinarySearchTree
{
 void insert()
 {

 }

 void search()
 {

 }

 void delete()
 {

 }
 ..
 ..
}

class BinarySearchTreeWorker
{
 main()
 {
  BinarySearchTree bst = new BinarySearchTree();
  bst.insert(20);
  bst.search(20);
  bst.delete(20);
 }
}

Whereas, some other implement it like follows, where the BinarySearchTree class along with the insert, search and delete methods, also contains the main method, to act as a driver.

class Node
{
 ..
}

class BinarySearchTree
{
 void insert()
 {

 }

 void search()
 {

 }

 void delete()
 {

 }

 main()
 {
  BinarySearchTree bst = new BinarySearchTree();
  bst.insert(20);
  bst.search(20);
  bst.delete(20);
 }
 ..
 ..
}

Of the two, which is a better design, and what are the drawbacks of each?




Do I need to put everything in a class in C++?

I've been told everything in C++ (even if it's not being instantiated, but is used in more than one place) must be put in a class. And although I know I don't have to, I don't know which is worse: making a bunch of classes that aren't going to be instantiated, or having a bunch of functions in the main.cpp.

Here's some sample code if I follow what I have been told:

#include <iostream>
using namespace std;

int main(){
// line of code to call class that acts as a calculator
}




I got an error about override method and class jsonresponse

I can't solve this problem in my new app. I am a beginner in Android Studio. My register.java class file is added here:

package com.agte.agtevivo;

import android.content.Intent;
import android.os.Bundle;
 import android.support.v7.app.AlertDialog;
 import android.support.v7.app.AppCompatActivity;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;


public class Register extends AppCompatActivity  {

Button button;
EditText editText3,editText4,editText5,editText6,editText7;

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

     editText3 =(EditText)findViewById(R.id.editText3);
     editText4=(EditText)findViewById(R.id.editText4);
     editText5 =(EditText)findViewById(R.id.editText5);
     editText6=(EditText)findViewById(R.id.editText6);
     editText7=(EditText)findViewById(R.id.editText7);

    button=(Button)findViewById(R.id.button);
    //button.setOnClickListener(this);

     button.setOnClickListener(new View.OnClickListener(){
       // @Override
         public void onClik(View v){

             final String name=editText3.getText().toString();
             final String username=editText4.getText().toString();
    final int      number=Integer.parseInt(editText7.getText().toString());
             final String shop=editText5.getText().toString();
             final String password=editText6.getText().toString();

Response.Listener<String> responceListener =new Response.Listener<String>(){
               //  @Override
                 public void onResponce (String responce){
                     try {
                         JSONObject jsonResponce =new JSONObject(responce);
             boolean success=new jsonResponce("Registerd Successfully");

                         if(success)
                         {
               Intent intent =new Intent(Register.this,Login.class);
                             Register.this.startActivity(intent);
                          }else{
        AlertDialog.Builder builder =new AlertDialog.Builder(Register.this);
                             builder.setMessage("Register Failed");
                             //.setNegativeButton("Retry",null);
                             //.create()
                             //.show();
                         }
                     } catch (JSONException e) {
                         e.printStackTrace();
                     }
                 };


             };
    RegisterRequest registerRequest =new RegisterRequest
   (name,username,number,shop,password,responceListener);
             RequestQueue queue = Volley.newRequestQueue(Register.this);
             queue.add(registerRequest);
         }
     });
     }

  /* @Override
   public void onClick(View v) {
    switch (v.getId())
    {
    case R.id.button:
    break;
   }

 }
*/
   }

I got an error I have listed on below:

Error:(38, 62) error: is not abstract and does not override abstract method onClick(View) in OnClickListener

Error:(48, 93) error: is not abstract and does not override abstract method onResponse(String) in Listener

Error:(53, 50) error: cannot find symbol class jsonResponce

Error:Execution failed for task ':app:compileFlavorDebugJavaWithJavac'. Compilation failed; see the compiler error output for details.

Currently I got an error:

Response.Listener<String> responseListener = new Response.Listener<String>()   {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);

                        boolean success = new jsonResponse.getBoolean("Success");
                        if (success) {
                            Intent intent = new Intent(Register.this, Login.class);
                            Register.this.startActivity(intent);
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                            builder.setMessage("Register Failed");
                            //.setNegativeButton("Retry",null);
                            //.create()
                            //.show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

Error is:

  Error:Execution failed for task ':app:compileFlavorDebugJavaWithJavac'.
  > Compilation failed; see the compiler error output for details.
  Error:(62, 47) error: incompatible types
  required: boolean
  found:    getBoolean




equals method not being used on object of defined class [duplicate]

This question already has an answer here:

Sorry, it is very late so I may not explain all the details, but I have been working on this and I cannot understand why the object Item object reference in the array does not use the equals method of the Item class that it was given. I checked the class type of both Item objects inside the function and they return class Item.

import java.util.Arrays;

class Item{
    private int data;

    Item(int data){
        this.data=data;
    }

    public boolean equals(Item item){
        return data==item.data;
    }
    public String toString(){
        return String.format("{data: %d}", data);
    }
}
public class Problem3{
    public static void main(String[] args){
        Object object=new Object(){ public String toString(){return String.format("{hash code: %d}", hashCode());} };
        String date="Friday, July 29";
        Item item=new Item(2);

        Object[] array={"Fri, Jul 29", new Item(2), object, new Integer[]{212, 220, 240, 313, 316, 320, 323, 331}, new Double[]{Math.E, Math.PI, 9.80665}, new Boolean[]{true, true, true, true}, new String[]{"Eckhart", "Eric", "Owen", "Chris", "David", "Mark"}};
        System.out.println(Arrays.deepToString(array));
        System.out.println();

        System.out.println("Searching array for entries . . .");
        System.out.printf("\"%s\":  %b\n", date, isMember(array, date));
        System.out.printf("%s:  %b\n", item, isMember(array, item));
        System.out.printf("%s:  %b\n", object, isMember(array, object));
        System.out.print("[\u0065, \u03c0, \u0047]:  "+isMember(array, new Double[]{Math.E, Math.PI, 9.80665})); //\ud835 \u0065
    }
    private static boolean isMember(Object[] array, Object value){
        if(array.length>0){
            Object member=array[array.length-1];
            if(member instanceof Object[] && value instanceof Object[]){
                if(Arrays.deepEquals((Object[])member, (Object[])value)){
                    return true;
                }
            }
            else if(member.getClass().equals(Item.class) && value.getClass().equals(Item.class)){
                if(member.equals(value)){
                    return true;
                }
            }
            else if(member.equals(value)){ //Object parameter does not have field "data" of Item equals method, so "instance of Item" applied above
                return true;
            }
            Object[] arrayNext=Arrays.copyOf(array, array.length-1);
            return isMember(arrayNext, value);
        }

        return false;
    }
}




Class instance's field is not showing the stored value of that field

I am developing a file sending application from one end system(Client Class) to another end system(Server Class), currently I am testing it on same pc.

I am able to transfer the file from client to server but the problem is with the extension of that file which is being received on server, Now to solve this problem I have used a string variable which store the type of extension in client class and by referencing the client class I am able to use that variable in server class.

Now the problem is,

When I use the variable(cl.extension) in server class then it returns no value.

Code of Client class

public partial class Clients : Form
{

    public string extension;
    //Create the instance of TcpClient Class so that we can use the methods and properties of that class
    TcpClient clientsocket = new TcpClient();
    public Clients()
    {
        InitializeComponent();


    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //It connect client to the specified server with the ip address and the port number
        //By here the server replies that the connection has been established after executing the next statement
        clientsocket.Connect("127.0.0.1", 8888);

        label2.Text = "From Server: Connected ";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Here GetStream method send the message to the server
        NetworkStream serverStream = clientsocket.GetStream();


        OpenFileDialog ofd = new OpenFileDialog();
        ofd.ShowDialog();
        ofd.AddExtension = true;

        string filename = ofd.FileName;
        byte[] outStream = File.ReadAllBytes(filename);

    //Variable that store the extension of file
        extension = Path.GetExtension(filename);

        serverStream.Write(outStream , 0, outStream.Length);
        textBox2.Text = "File has been sended to server";

        serverStream.Flush();

    }

}

Code of Server Class

public partial class Server : Form
{

    Clients cl = new Clients();


    TcpListener serverSocket = new TcpListener(8888);
    TcpClient clientSocket = new TcpClient();
    public Server()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {


            try
            {
                serverSocket.Start();
                clientSocket = serverSocket.AcceptTcpClient();

            NetworkStream serverStream = clientSocket.GetStream();
            byte[] inStream = new byte[69000];
            serverStream.Read(inStream, 0, clientSocket.ReceiveBufferSize);
     //After reading the stream, it give user ability to save that stream by creating a file
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.ShowDialog();
            DicrectoryBox.Text = sfd.FileName + cl.extension;//Here is problem
            MessageBox.Show(cl.extension);//It does not show the extension (of client file)

            File.WriteAllBytes(DicrectoryBox.Text, inStream);
            StatusBox.Text = "Writing Completed";
        }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }



        clientSocket.Close();
        serverSocket.Stop();
    }
}

Problem is with cl.extension in server class, MessageBox is not showing the extension of the file that has been sanded by client.




vendredi 29 juillet 2016

I'm making Swift framework but it doesn't have the class I made

I'm testing creating framework.

enter image description here

So, I made the test framework first.

enter image description here

And in another project, import the framework but I can't access the MyClass I made. What's the problem? I don't know weather if can't access the class or framework doesn't have the class I made.

I'm struggling with this problem about two days. help me please.




Multiple role-based classes inherited from User class - Rails 4

I have a class called User and a few classes for user roles (e.g. Admin, Contributor, Member) that inherit form the User class:

class Admin < User; end

Following the STI principle, roles are stored as jsonb on the users table like so:

  t.jsonb :roles, default: {
    'admin':       false,
    'contributor': false,
    'member':      true
  }

Is it possible to set the appropriate subclass to an instance of a User for the corresponding role. In other words, do something like:

u = User.create(...)
u.class #<= returns 'User'
u.grant_role(admin)
u.class #<= should return 'Admin'

I am thinking of using a before_save callback so that each time User instance is instantiated or updated, an appropriate class is selected. Am I on the right track?




Java toString for a Binomial Expansion class

I'm working on creating a binomial expansion class that will essentially expand a binomial equation.

For example if you have (3x+4y)^4; It will equal: 81x^4 + 432x^3 y + 864x^2 y^2 + 768x y^3 + 256y^4

So far in my code I can calculate all of my coefficients into a one dimensional array, so I can get (81, 432, 864, 768, 256) but I'm having trouble figuring out how to include the x^powerValue and y^powerValue to print next to the coefficients in my toString method.

What would be an easy solution for this? Is having a String array for a String of x^powerValue and another String array for String of y^powerValue ; then just have the coefficient array * String arrayX * string arrayY for myString?

Thanks for any suggestions!




Declare a class in a for loop in python

I want to know if I can have a class declaration in python in a for loop I am reading a csv file and it has 3 rows and 5 columns

for row in settings_file_parameters:

    if firstline == True:
        firstline = False
        continue
    L.append(row)

for row in L:

    # Populating the parameters from the file
    fb = row[0]
    tb = row[1]
    ff = row[2]
    tf = row[3]
    fc = row[4]
    tc = row[5]
    as = row[6]
    p = row[7]
    print row[0], row[1]

    class ABC(XYZ):
        #do something

The print output prints the first and second element of all the rows before entering the class




classification based on image features

I have around 1000 repository each one contain different number of images, i'm use 20 templates ,then model has been construct for all repositories such that :

each repository contain N number of images ( N is differ from on to other) then for each image it compare with predefined templates (20 templates) if found then 1 otherwise 0 some images my contain more than two template such in image1 where NBA log can be found with Pepsi log and so on for others .

my Question what is model can be used for classifying these repositories based on pre-defined set of classes with take into consideration my values is binary and each repository contain different number of images?

                                  Template-dataset 
repo-ID     image-id         NBA   Pepsi   Cisco-logo .. Spy-cam    class  
Rep1        image1             1    1        0              0        A
Rep1        image2             0    0        0              0        N
....        ......             0    0        0              1        B
Rep2        image1             0    1        0              0        C




c++ How to make changes to the same object across multiple classes?

Noobie here. I'm trying to make changes to the Player object mainCharacter across multiple classes. I currently have a Player object declared as seen below. The Player is able to teleport to various worlds and fight monsters.

All of that code works. Once the enemy of one world is defeated, they stay defeated. My problem is that when he teleports to another world, the Player's stats are all reset to their default values; he has full life points again even after sustaining damage from the enemy in the previous world.

How do I make changes to the same Player object across multiple classes, or worlds? I figure there's a problem in my declarations but I'm not sure. I appreciate any input. Thanks!

Where the mainCharacter object is declared:

class SpaceList
{
    protected:
        class SpaceNode
        {
            friend class SpaceList;
            Player mainCharacter;
            Space* thisSpace;
            SpaceNode* next;
            SpaceNode(int m, SpaceNode* next1 = NULL)
            {
                if(m == 0)
                {
                    thisSpace = new EntranceHall(&mainCharacter);
                }
                else if(m == 1)
                {
                    thisSpace = new WaterSpace(&mainCharacter);
                }

Part of Player.hpp:

class Player: public Interactable
{
    protected:
        Backpack myBackpack;
    public:
        Player();
        virtual interactableType getInteractableType();
        virtual int interact();
        virtual int attack();
        virtual void defend(int);

Part of Player.cpp:

Player::Player()
{
    healthPoints = 10;
    numberOfAttackDice = 1;
    sidesOfAttackDice = 6;
    numberOfDefendDice = 1;
    sidesOfDefendDice = 6;
}

mainCharacter starts off at Entrance (Entrance.cpp):

EntranceHall::EntranceHall(Interactable* mainCharacter)
{
    interactableGrid[6][3] = mainCharacter;
    interactableGrid[0][3] = new Portal(0);//entrance portal
    interactableGrid[3][3] = new InterestPoint(0);//stone mural
}

mainCharacter may later teleport to Water World, default values reset (Waterspace.cpp):

WaterSpace::WaterSpace(Interactable* mainCharacter)
{
    interactableGrid[3][0] = mainCharacter;
    interactableGrid[3][3] = new Boss(this->getSpaceType());




Using and passing language variables inside php class

I am in need of a little bit of help here, it is the only part missing on my website. I have a newsletter script and on the first page I am using a multilanguage function that I got from codecanyon (PHPMLC) that works perfectly.

This is the index.php with the form ( I have stripped the unnecessary html).

<?php
require_once("../PHPMLC/class/PHPMLC.php");
$ml = new PHPMLC();
$ml_languages = $ml->getLanguages();
$ml_selected_language_code = $ml->getCurrentLanguageCode();
$ml_strings = $ml->getTranslatedStringsForCurrentLanguage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $ml_strings['prereg_m_title']; ?></title>
<link href="/css/style.css" rel="stylesheet">
</head>
<body class="Site">
<form class="form-horizontal" id="newsletter" action="send.php" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-6">
  <input type="email" name="signup-email" class="form-control" id="signup-email" value="" pattern="[A-Z-a-z-0-9-_@.]+" autocomplete="off" required />
  <input type="hidden" name="signup-gender" id="signup-gender" value="female" />
 </div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label"><?php echo $ml_strings['prereg_country_label']; ?></label>
<div class="col-sm-6">
  <select class="form-control" name="signup-country" required />
<option value="" disabled selected><?php echo $ml_strings['prereg_please_select']; ?></option>
<option value="Albania">Albania</option>
<option value="Andorra">Andorra</option>
<option value="Austria">Austria</option>
<option value="Belarus">Belarus</option>
<option value="Belgium">Belgium</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
  <button type="submit" class="btn btn-info"><?php echo $ml_strings['prereg_submit_button']; ?></button>
</div>
</div>
</form>
</body>
</html>

The form send the inputs to a file "send.php" which has the following code :

<?php
require 'inc/Database.class.php';
class Newsletter
{
private static $email;
private static $gender;
private static $country;
private static $ip;
private static $datetime = null;

private static $valid = true;

public function __construct() {
    die('Init function is not allowed');
}

public static function register($email) {
    if (!empty($_POST)) {
        self::$email    = $_POST['signup-email'];
        self::$gender    = $_POST['signup-gender'];
        self::$country    = $_POST['signup-country'];

        //Test if it is a shared client
        if (!empty($_SERVER['HTTP_CLIENT_IP'])){
        self::$ip = $_SERVER['HTTP_CLIENT_IP'];
        //Is it a proxy address
        }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        self::$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }else{
        self::$ip = $_SERVER['REMOTE_ADDR'];
        }

        self::$datetime = date('Y-m-d H:i:s');

        if (empty(self::$email)) {
            $status  = "error";
            $message = "The email address field must not be blank";
            self::$valid = false;
        } else if (!filter_var(self::$email, FILTER_VALIDATE_EMAIL)) {
            $status  = "error";
            $message = "You must fill the field with a valid email address";
            self::$valid = false;
        }

        if (self::$valid) {
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $existingSignup = $pdo->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
            $existingSignup->execute();
            $data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;

            if (!$data_exists) {

                $sql = "INSERT INTO signups (signup_email_address, signup_category, signup_country, signup_ip, signup_date) VALUES (:email, :gender, :country, :ip, :datetime)";
                $q = $pdo->prepare($sql);

                $q->execute(
                    array(':email' => self::$email, ':gender' => self::$gender, ':country' => self::$country, ':ip' => self::$ip, ':datetime' => self::$datetime));

                if ($q) {
                    $status  = "success";
                    $message = "Your registration was successful";
                } else {
                    $status  = "error";
                    $message = "An error occurred, please try again";
                }
            } else {
                $status  = "error";
                $message = "This email is already registered";
            }
        }

        $data = array(
            'status'  => $status,
            'message' => $message
        );

        echo json_encode($data);

        Database::disconnect();
    }
}
}

if (!empty($_POST)) {
$email = $_POST['signup-email'];
$gender = $_POST['signup-gender'];
$country = $_POST['signup-country'];

Newsletter::register($email);
}
?>

My problem is, I cannot translate the error/alert messages in send.php. I mean I cannot use the key "$ml_strings['reg_successful'];" instead of "Your registration was successful". It's driving me crazy because I am an amateur.

Many thanks in advance for your help.




How to understand the relation between `matrix`, `vector`, `numeric`, etc when define signature

My basic confusion is the the relation between class matrix, vector and numeric when define the signature in setMethod. They are all base type, and if a method for class numeric is defined, and then the method for numeric vector is defined, and vice versa(of course, the method for character will be also defined if one for vector is already there). However, if you define setMethod for numeric, the method reports when applied to a matrix object, and vice versa.

So what root reason causes this problem? Besides class() returning different results for matrix and numeric objects, what is the deeper level reason?

Moreover, if define a method for numeric or vecotr, the method for factor also is defined, is that caused by inheritance?




Classes objects in c++ [on hold]

How do I write two different classes in two different files and relate each other? For eg. Write 2 classes in 2 different files  class BankAccount  class ATM (a proxy class)




Tring to understand classes in python [on hold]

I learned CPP and now i learn python. But i confused: In cpp when i making an intance of subclass with __init__, i must to insert the super class's __init__ in to the __init__ of the subclass.

In cpp i don't have to do that, because when i make an instance of some class in CPP, the order of the building is from the superclass to the subclass. and if i have constructor in sub class in CPP, its ok and i don't have to call the one of the superclass..

What is different between the two langs??




vba using class object by references (.xlam file)

I created a src_vba.xlam to use commun functions from any Excel files. It works well with functions and subs but not with class objects.

Firstly, I created a class object Cconfig in my Excel file. I use it without any problem with that statement to declare it : Dim myConfig As New Cconfig

After, I created a .xlam file with a Project called src and I included the Cconfig file by importing it in. Therefore, I modified the statement of the declaration by : Dim myConfig As New src.Cconfig

It raises an error message : the key work New is not used correctly

Could you please tell me how to use an extern class defined in a .xlam file?

Thank you for your help.




Python list of dictionaries in class not behaving as expected [duplicate]

This question already has an answer here:

The issue I appear to be having is that when I run a code that uses the plusMinusAverage class more than once (in my case a for loop), the new instance of the class keeps references to the previous list of pmaDicts created by the previous plustMinusAverage creation and adds to the end of it.

Meaning (Code that results this is further down below)

things = []
for i in range(2):
    thing[i] = plusMinusAverage(count3D=2)
    print thing[i]
    print thing[i].values3D 
>>> (plusMinusAverage at 0x00NSTUFF1)
>>> [{"x":(attr.connection at 0x1234),"y":(attr.connection at 0x2345), etc..},
     {"x":(attr.connection at 0x3456),"y":(attr.connection at 0x4567), etc..}]
>>> (plusMinusAverage at 0x00NSTUFF2)
>>> [{"x":(attr.connection at 0x1234),"y":(attr.connection at 0x2345), etc..},
     {"x":(attr.connection at 0x3456),"y":(attr.connection at 0x4567), etc..},
     {"x":(attr.connection at 0x5678),"y":(attr.connection at 0x6789), etc..},
     {"x":(attr.connection at 0x7890),"y":(attr.connection at 0x8901), etc..}]

What gets me about this is that it appears to print out the object, but then the list appears to point to the original but with more entries. I don't get why the list would not be a unique one.

Sorry for the massive posting of code below, but I figured this issue has enough nuances that trying to make a simpler version would likely invite solutions that wouldn't work for my circumstance, and since I'm not certain where the issue lies exactly, I'm going to include all the pertinent parts where it might be going wrong. ..plus maybe someone who works in maya can use this to build their own shaderNode tools.

class Tracker2(object):
    dag = ""
    obj = ""
    getTime = "current"

    def setPathing(self):
        if self.nodeName == None:
            self.nodeName = cmds.createNode('transform')
            cmds.addAttr(self.nodeName, sn="type", ln="type", dt="string")
            cmds.setAttr(self.nodeName + ".type", type="string", keyable=0)
        sel = om.MSelectionList()
        sel.add(self.nodeName)
        self.obj = om.MObject()
        self.dag = om.MDagPath()
        sel.getDependNode(0, self.obj)
        try:
            sel.getDagPath(0, self.dag)
        except:
            pass

    def __init__(self):
        if not self.dag and not self.obj:
            self.setPathing()

    def fullpath(self):
        if self.dag and self.dag.fullPathName():
            return self.dag.fullPathName()
        return om.MFnDependencyNode(self.obj).name()

class shaderNode(Tracker2):
    def __init__(self):
        self.nodeName = cmds.shadingNode(self.type,au=1)
        Tracker2.__init__(self)

class connection(object):
    def __init__(self, attr, *args):
        self.attr = attr
    def __set__(self, instance, value):
        if isinstance(value,basestring):
            try:
                cmds.connectAttr(value,instance.fullpath()+"."+self.attr,f=1)
            except Exception as inst:
                cmds.warning(inst)
        elif not value:
            temp = cmds.listConnections(instance.fullpath()+"."+self.attr,s=1,d=0)
            if temp:
                cmds.disconnectAttr(instance.fullpath()+"."+self.attr, temp[0])
        else:
            cmds.warning("Set Connection: Source attribute is non-string value | "+value)
    def __get__(self, instance, owner):
        tempIn = cmds.listConnections(instance.fullpath()+"."+self.attr,s=1,d=0)
        tempIn = tempIn if tempIn else []
        tempOut = cmds.listConnections(instance.fullpath()+"."+self.attr,s=0,d=1)
        tempOut = tempOut if tempOut else []
        #returns list of [[incoming] , [outgoing]]
        return [tempIn,tempOut]

In separate py file where class containing connection is loaded as attr

class pmaDict(dict):
    def __init__(self,instance,*args,**kwargs):
        self.instance = instance
        dict.__init__(self,*args,**kwargs)
    def __getitem__(self, key):
        thing = dict.__getitem__(self,key)
        if key in self and isinstance(dict.__getitem__(self, key),attr.Attribute):
            return thing.__get__(self.instance,None)
        if key in self and isinstance(dict.__getitem__(self,key),attr.connection):
            return thing.__get__(self.instance,None)
        else:
            return dict.__getitem__(self,key)

    def __setitem__(self, key, value):
        thing = dict.__getitem__(self,key)
        if key in self and isinstance(dict.__getitem__(self,key),attr.Attribute):
            thing.__set__(self.instance,value)
        elif key in self and isinstance(dict.__getitem__(self,key),attr.connection):
            thing.__set__(self.instance, value)
        else:
            dict.__setitem__(self,key,value)

class plusMinusAvg(attr.shaderNode):
    type = "plusMinusAverage"
    values1D = []
    values2D = []
    values3D = []

    def addInput1D(self):
        i = len(self.values1D)
        print self
        cmds.setAttr(self.fullpath() + ".input1D[" + str(i) + "]", 0)
        newInput = pmaDict(self,
                           {"x": attr.Attribute("input1D[" + str(i) + "]", "float"),
                            "x_con": attr.connection("input1D[" + str(i) + "]")})
        self.values1D.append(newInput)

    def addInput2D(self):
        i = len(self.values2D)
        print self
        cmds.setAttr(self.fullpath() + ".input2D[" + str(i) + "]", 0, 0, type="double2")
        newInput = pmaDict(self,
                           {"xy": attr.Attribute("input2D[" + str(i) + "]", "float"),
                            "x": attr.Attribute("input2D[" + str(i) + "].input2Dx", "float"),
                            "y": attr.Attribute("input2D[" + str(i) + "].input2Dy", "float"),
                            "xy_con": attr.connection("input2D[" + str(i) + "]"),
                            "x_con": attr.connection("input2D[" + str(i) + "].input2Dx"),
                            "y_con": attr.connection("input2D[" + str(i) + "].input2Dy")})
        self.values2D.append(newInput)

    def addInput3D(self):
        i = len(self.values3D)
        print self
        cmds.setAttr(self.fullpath()+".input3D["+str(i)+"]",0,0,0, type="double3")
        newInput = pmaDict(self,
                           {"xyz": attr.Attribute("input3D["+str(i)+"]","double3"),
                            "x": attr.Attribute("input3D["+str(i)+"].input3Dx","float"),
                            "y": attr.Attribute("input3D["+str(i)+"].input3Dy","float"),
                            "z": attr.Attribute("input3D["+str(i)+"].input3Dz","float"),
                            "xyz_con": attr.connection("input3D["+str(i)+"]"),
                            "x_con": attr.connection("input3D["+str(i)+"].input3Dx"),
                            "y_con": attr.connection("input3D["+str(i)+"].input3Dy"),
                            "z_con": attr.connection("input3D["+str(i)+"].input3Dz")})
        self.values3D.append(newInput)

    def __init__(self, count1D=0, count2D=0, count3D=0):
        attr.shaderNode.__init__(self)
        for i in range(count1D):
            self.addInput1D()
        for i in range(count2D):
            self.addInput2D()
        for i in range(count3D):
            self.addInput3D()




Class v/s module

I tried to understand what classes are and how they are different from modules . I found the below text appealing . Please explain it

class MyStuff(object):

    def __init__(self):
        self.tangerine = "And now a thousand years between"

    def apple(self):
        print "I AM CLASSY APPLES!"

Here's why classes are used instead of modules: You can take this MyStuff class and use it to craft many of them, millions at a time if you want, and each one won't interfere with each other. When you import a module there is only one for the entire program unless you do some monster hacks.

In case you can provide some good source where things are well explained regarding class and objects please provide it or write it here




C# List of different classes

I did not find the answer in searching for it.

I need a List that contains different classes, each of them inherent from a base class BaseA, but each of them will have properties others will not have, or some that uses the same class will.

public class BaseA
{
    public int ID = 0;
}

public class AA : BaseA
{
    public int AID = 0;
}

public class AB : BaseA
{
    public int BID = 1;
}

public class AC : BaseA
{
    public int CID = 0;
}

Now the question is how do I get a single List that may contain class AA,AB and AC and the editor will not think i'm only working with one of them.

I tried to made the List<BaseA>, but this will only expose the bassA properties, and what i need is like to be able to do List[0].AID where it will understand what AID means if i'm talking about the AA class.

I may be going it all wrong, can someone point me to the right direction?




Get specific Key Value in side a loop

I have a public method which return's collection of keys and values of an item and i would like to output specific key values. following is the method i am using

public List<string> GetAll(string itemSystemname) 
{
  return itemValues[itemSystemname].Select(x => x.Value).ToList();
}

All the values are printed out using foreach like this

foreach (var item in i.GetAll("FrontPageNewsLarge"))
{
  @item  
}

and my desire way to Out the value's is like this

foreach (var item in i.GetAll("FrontPageNewsLarge"))
{
  @item.getvalue("Id") // OR item["ID"]  
}

How can I achieve this functionality. Thanks in Advace




Best approach for designing a Java class?

I hope I am asking the right question. This is just out of my curiosity and since I am not an experienced developer, I just to wanted to hear from you guys that what is the good approach while designing a class. Is there any standard approach or either one can be implemented? I just to want to know what is the conventional way of creating a class or what is your way?

Option 1:

public class Student{
    private String name;
    private String address;

    public Student(String name, String address){
        this.name = name;
        this.address = address;
    }

    public void addStudent(){
        //add name and address to database.
    }
}

Option 2:

public class Student{

    public void addStudent(String name, String address){
        //add name and address to database.
    }

    public void addAllStudent(List Student){
        //loop and add each student
    }
}

Method call:

//option 1:
Student s = new Student("abc","xyz");
s.addStudent();
//for list,
for(int i=0;i<list.length;i++){
    Student s = new Student(list[i].name, list[i].address);
}

//option 2:
Student s = new Student();
s.addStudent("abc","xyz");
s.addAllStudent(list);




get already created mysqliDb connection from another class

I have MysqliDb http://ift.tt/1pyBr8v.

In my php class:

<?php 
require_once ('MysqliDb.php');

class Main{

protected $db;   


public function __construct()
{
    $this->db = new MysqliDb ('localhost', 'root', 'tuncay', 'db');
}

}

Class A extends Main{

public function __construct()
{   
    $this->db = MysqliDb::getInstance();
    echo $this->db->where("id", 5)->getOne('test')['text'];
}

}

$a = new A();

?>

Php error: Fatal error: Call to a member function where() on null in /.../db/index.php on line 21 where() function belongs MysqliDb.php

What is wrong? I got $this->db from Main class

I just want to keep DB connection in A class and use it.




ES6 access functions from child class.

Given the codes below, how do I access the bar() from an the Parent class?

class Parent{
    constructor(){

    }

    foo(){
        this.bar() // not defined
    }
}

class Child extends Parent{
    constructor(){
        super();
    }

    bar(){

    }
} 

var c = new Parent();
c.bar() // not defined




jeudi 28 juillet 2016

What is the concept of Interface in Java? Can you give some real world examples?

Currently I am working on a project, which is implemented in Java. There are many classes, extended classes and interfaces that implement other interfaces.

I know basic concepts but cannot track/debug what is really going on? I want real world examples, such as from embadded systems or information systems that really make it clear to understand.




want to know purpose of Encapsule Fileds while creating class in NEATBEANS

enter image description here

What will be the effect if we give ENCAPSULATE FIELDS and What will be the effect if we didnt give the ENCAPSULATE FILEDS




pointer to an object has no any value (or do not get a value)

i have a problem with output of 2 classes like below:

Foo.cpp

Foo::Foo(string n):foo(n){
}

Foo::Foo(const Foo &f):foo(f.foo){
}

string Foo::getFooName() const{
    return foo;
}

Foo::~Foo(){
}

and class Bar:

Bar.h

public:
    Bar();
    Bar(string, Foo&);
    Bar(const Bar&);
    Foo& getFoo() const;
    ~Bar();
private:
    string bar;
    Foo* foo;
};

Bar.cpp

Bar::Bar(string b, Foo &f):bar(b), foo(new Foo()){
}

Bar::Bar(const Bar &b):bar(b.bar), foo(new Foo(*b.foo)){
}

Foo &Bar::getFoo() const{
 return *foo;
}

Bar::~Bar()
{
delete foo;
}

and in main fuction, when i use this cout<<"Test:"<<b->getFoo().getFooName(); it only gets me in output only Test: instead of Test:TestFoo.

what is wrong in my code? (gcc5.4.0,cmake 3.5.1) tnx

and main.cpp

Foo* f;
Bar* b;
f=new Foo("TestFoo");
b=new Bar("TestBar",*f);  
cout<<"Test:"<<b->getFoo().getFooName(); // this line




Call a child variable in a mother class python

Hi I'm trying to access the "Table_Name variable" of the Children class to make the "Load_Data" method do different stuff depending on the children who cast the parent Class.
Otherwise, does exist a method to know the children who summoned the parent class?

class DataBaseClass(obj):
    ..
    def Load_Data():
        if Table_Name?? == Child1.Table_Name:
            load_Child1_Data
        if Table_Name == Child2.Table_Name:
            load_Child2_Data    
    ..

class Child1(DataBaseClass):
    ..
    Table_Name = TableName1
    ..

class Child2(DataBaseClass):
    ..
    Table_Name = TableName2
..

import * 
..
Child1.Load_Data()
Child2.Load_Data()




dlib mlp::kernel_1a_c member initialization inside a class

I'm using dlib with the neural network example. dlib neural network

I am trying to initialize the

"mlp::kernel_1a_c net(2,5);"

variable inside a class, but I get all kinds of errors. Here is the piece of code relevant to my issue:

#ifndef MYCLASS_H
#define MYCLASS_H
#include <dlib/mlp.h>
typedef dlib::mlp::kernel_1a_c mlp_trainer_type;
Class MyClass:
 public:
  MyClassConstructure()
  {
     /// After declaration, how do I initialize my_neural_network_ here?
     // my_neural_network_(5, 5);  ????
  }
 private:
  /* this part fails, even without using the typedef. */
  mlp_trainer_type mouth_neural_network_;
 #end

How do I solve this problem? I don't want a global variable.

Please, don't focus on naming conventions or shoulda-couda-wouldas things unless it's relevant to my problem. I assure you the program worked for a month until I included that neural private variable today.




How to find the default construstor methods for a class

Problems comes from experimenting a package and find using new(Class = 'ddmatrix', Data = X) and ddmatrix(Data = X) yields different results, in which X is a matrix(one can think class ddmatrix is a transformed Class matrix).

Document

In the package, a S4 class ddmatrix is defined. A generic constructor function by setGeneric(name = 'ddmatrix'). Further, the pacakge defines setMethod('ddmatrix', signature = 'matrix', ...) as below:

 setMethod("ddmatrix", signature(data="matrix"), 
              function(data, nrow=1, ncol=1, byrow=FALSE, ...
                       bldim=.pbd_env$BLDIM, ICTXT=.pbd_env$ICTXT)
    {
    dim(data) <- NULL
    ret <- ddmatrix(data=data, nrow=nrow, ncol=ncol, byrow=byrow, bldim=bldim, ICTXT=ICTXT)    
    return( ret )
}
)

I am confused how a method ddmatrix is used in the above setMethod('ddmatrix', signature = 'matrix') step. Is this ddmatrix method the default method for the generic ddmatrix?

Meanwhile, when call new('ddmatrix', Data = X), which method it will call to build a new ddmatrix object from a matrix object? new function is:

function (Class, ...) 
{
    ClassDef <- getClass(Class, where = topenv(parent.frame()))
    value <- .Call(C_new_object, ClassDef)
    initialize(value, ...)
}

Question

To answer the discrepancy between new('ddmatrix') and ddmatrix(), I think one way is to find the default constructor. Meanwhile, the package also defines setMethod('ddmatrix', signature = 'vector',...), is this the default one?




Swift, segue information passed won't show

I'm trying to get some information to pass to another view controller. I did the segue and nothing is showing. I'm using an external class to organize the information. But I'm not sure why it's not working.

first view controller:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "toLocationVC" {

        let lVC = segue.destinationViewController as! LocationViewController

        lVC.locationImage?.image = locations[locationSelection].image;
        lVC.nameLabel?.text = locations[locationSelection].name;
        lVC.descriptionTextView?.text = locations[locationSelection].desc;

    }

second view:

var selectedLocation : Location?;


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    locationImage.image = selectedLocation!.image
    nameLabel.text = selectedLocation!.name
    descriptionTextView.text = selectedLocation!.desc

}

and this is the class Location:

class Location {

var image : UIImage
var name : String
private var description : String

var desc : String {
    return description + "\n\n\nThis Description and Images Provided by http://ift.tt/2aAPjT8"
}

init(name : String, image : UIImage, description: String) {
    self.name = name;
    self.image = image;
    self.description = description;
   }
}

I've tried changing some of the code around, but nothing seems to work.




Java: instance really better than static?

So I have a few classes like MainWindow, MenuPanel, GamePanel, GameEngine, Player and so on...

My question is, although I've read much about static vs instance, which should be more recommended to use, according one of my lines looks like this: MainWindow.getGamePanel().getPlayer1().getName().toLowerCase().compareTo(...);

or MainWindow.getGamePanel().getLabels()[0].getIcon();

Do you think this is a good practice trying so hard not to use statics where every object has different properties and things are not generalized, instead of maybe declaring the labels or the players and namesstatic and having a much more easy to reuse and read code?

The idea is I used these long codes because surely it would be awkward to create a GamePanel(visual class) object in the Player(more like a logical) class for example. So I just created like one object of every class in MainWindow (not the main class, just the JFrame class) and created static getters for every one of them.




How do I loop through certain mappings of a dict?

So what I am trying to do is loop only through certain mappings of a dict. So for example, for any key that has a space in it, print("I have a space"). For any key that do not include a space in the name, print("I do not have a space").

To be more specific, the file I am trying to do this on can found here starting line 262

Absolutely any constructive critisism and/or suggestions are welcome. Thanks!




Class method calling another class' method that is stored as an argument

Sorry for the confusing title, I have no clue how to ask this. I have a question regarding classes and methods. I have a button that, when pressed, calls another object's function. For this example, it should log "100" to the console as f's "x", but instead, it logs "0": my button's "x". Help?

<script>
function fun(x){
    this.x = x;
}

fun.prototype = {
    s:function(){
        console.log(this.x);
    }
}

function Button(func){
    this.x = 0;
    this.y = 0;
    this.w = 1000;
    this.h = 1000;
    this.func = func;
}

Button.prototype = {
    check_if_click:function(x, y){
       if (x >= this.x && x <= this.x + this.w && y >= this.y && y <= this.y + this.h){
            this.func();
        }
    }
}

f = new fun(100);
b = new Button(f.s);
b.check_if_click(500, 500);
</script>




Python: class with double underscore

I'm following this link and trying to make a singleton class using Metaclass. But, I want to make some internal tweaks to this singleton class and want the users to use another class (let's call it MySingleton). So I decided to make it private but it gives the following error.

enter image description here

My sole purpose is to prevent __Singleton from being used outside. How can I achieve this?

On a separate note, is it a good practice to use double underscore with classes?




Does the Java/C#-like definiton of classes not work in Javascript?

I realize there are several questions related to this but I couldn't quite find an answer.

So, as a big C# fanboy I'm used to declaring classes with their variables and methods. When it comes to Javascript, it offers these weird function declarations as seen on W3schools and here. I kind of dislike these constructs as they don't fulfill my need for somewhat strict order and differentiation of classes and functions, plus I'd like to do it the way I'm used to for maintainability. According to this, I can in fact declare classes with a constructor method and all their functions inside the declaration, however I'm confused that other sources don't even mention that option. Plus it's not quite clear to me what these specific get methods (with blanks between get and the method name) mean. Can I only use these to even interact with the object and not just define my own methods with return values and parameters?

Here is a simple attempt of how I would have declared a class, but that doesn't work.

class Person {
   constructor(prename,surname) {
      this.prename = prename;
      this.surname = surname;
   }

   getFullName() {
      return this.prename + " " + this.surname;
   }
}  




How can the program user choose the number and names of class objects at runtime?

I am building a program that has a class that needs to have several different objects. The problem is that I don't know exactly how many objects there will be at runtime. In short, the user will choose how many objects there are as well as their names. I have absolutely no idea how to do this, or even if it's possible. I've done a little digging and I can't find anything remotely useful. Is this a legal action? If so, how is it done?




I get a null reference on a property in one of my classes [duplicate]

This question already has an answer here:

Am using winforms in c# with visual studio 2015

This is my class

public class advmessage
{
    public string[] message;
}

so then in the load event of form1 I do this

   advmessage newadvmessage = new advmessage();
   newadvmessage[1]="Hello";

and for that assignment, it throws the exception for null reference and says object reference not set to an instance of an object.

So if I have a class that does not need to be an array, everything works find, but on the ones that use arrays, is where it has the exception.

Also, I do not have a get set or return for any of the classes, and that might b the problem but yet when I added the { get; set; } in there it still had a problem. I could understand a null reference, if I referenced a null string, but I am just trying to set the message property that will be shown in a text box to the user.

Any help would be greatly appreciated.




Multiplying Polynomials (Dynamic Arrays) C++

I'm fairly new to C++ and I'm currently taking my first programming course. I'm supposed to create a Polynomial class that is able to add, multiply, and subtract Polynomials. However, the code I wrote is only able to add and subtract. Can someone help me figure out how to multiply two polynomials?

Header file

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <iomanip>


using namespace std;


class Polynomial {

public:

Polynomial();
Polynomial(int size, double coeff[]);
Polynomial(const Polynomial& poly);
~Polynomial();


double PolynomialVal(double x) const;


const Polynomial operator + ( const Polynomial& RHS)const;
friend Polynomial operator + (const Polynomial& RHS, const double c);
friend Polynomial operator + (const double c, const Polynomial& RHS);


const Polynomial operator - (const Polynomial& RHS) const;
friend Polynomial operator - (const Polynomial& RHS, const double c);
friend Polynomial operator - (const double c, const Polynomial& RHS);


const Polynomial operator * (const Polynomial& RHS) const;
friend Polynomial operator * (const Polynomial& RHS, const double c);
friend Polynomial operator * (const double c, const Polynomial& RHS);


const Polynomial& operator = (const Polynomial& RHS) ;


double& operator [] (const int index);


friend ostream &operator <<(ostream& output, const Polynomial& poly);
bool operator > (const Polynomial& RHS) const;



 private:

int size;
double *coeff;

};

//implementation file

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <iomanip>
#include "Polynomial.h"

using namespace std;

Polynomial::Polynomial() {

int size = 0;
coeff = new double[size + 1];
coeff[0] = 0;

  }

 Polynomial::Polynomial(int Psize, double Pcoeff[]){
//cout << "Calling the constructor..." << endl;
size = Psize;
coeff = new double[size];
for (int i = 0; i < size; i++){
    coeff[i] = Pcoeff[i];
}
 }

 Polynomial::Polynomial(const Polynomial& poly) {

coeff = new double[poly.size];
for (int i = 0; i < (int)poly.size; i++){
    coeff[i] = poly.coeff[i];
}
size = poly.size;
}

  Polynomial::~Polynomial() {

if (coeff) {

    delete[] coeff;
    coeff = NULL;
}

}

  double Polynomial::PolynomialVal(double x)const {

double sum = 0.0;
double xPow = 1.0;
if (coeff) {
    for (int i = 0; i < size; i++){
        sum += xPow * coeff[i];

        //sum = coeff[i] * pow(x, i);

        xPow *= x;
    }
}
return sum;
}


const Polynomial Polynomial :: operator + (const Polynomial& RHS) const {

Polynomial NewPoly;
if (RHS.size > size) {
    NewPoly.coeff = new double[RHS.size];
    NewPoly.size = RHS.size;
}
else {
    NewPoly.coeff = new double[size];
    NewPoly.size = size;
} for (int i = 0; i < NewPoly.size; i++){

    NewPoly.coeff[i] = coeff[i] + RHS.coeff[i];

}

return NewPoly;

}

Polynomial operator + (const Polynomial& RHS, const double c){

Polynomial NewPoly;
for (int size = 0; size < RHS.size; size++){

    NewPoly.size = c + RHS.size;
}

return NewPoly;


}

Polynomial operator + (const double c, const Polynomial& RHS){

Polynomial NewPoly;
for (int size = 0; size < RHS.size; size++){

    NewPoly.size = c + RHS.size;
}
return NewPoly;
  }

 const Polynomial Polynomial :: operator - (const Polynomial& RHS) const{

Polynomial NewPoly;
if (RHS.size > size) {
    NewPoly.coeff = new double[RHS.size];
    NewPoly.size = RHS.size;
}
else {
    NewPoly.coeff = new double[size];
    NewPoly.size = size;
} for (int i = 0; i < NewPoly.size; i++){

    NewPoly.coeff[i] = coeff[i] - RHS.coeff[i];

}


return NewPoly;

 }

Polynomial operator - (const Polynomial& RHS, const double c){

Polynomial NewPoly;
for (int size = 0; size < RHS.size; size++){

    NewPoly.size = RHS.size - c;
}
return NewPoly;
}

 Polynomial operator - (const double c, const Polynomial& RHS){

Polynomial NewPoly;
for (int size = 0; size < RHS.size; size++){

    NewPoly.size = c - RHS.size;
}
return NewPoly;
 }

 const Polynomial Polynomial :: operator * (const Polynomial& RHS) const{

Polynomial NewPoly;
if (RHS.size > size) {
    NewPoly.coeff = new double[RHS.size];
    NewPoly.size = RHS.size;
}
else {
    NewPoly.coeff = new double[size];
    NewPoly.size = size;
} for (int i = 0; i < NewPoly.size; i++){

    NewPoly.coeff[i] = coeff[i] * RHS.coeff[i];

}



return NewPoly;
}

Polynomial operator * (const Polynomial& RHS, const double c){

Polynomial NewPoly;
for (int size = 0; size < RHS.size; size++){

    NewPoly.size = RHS.size * c;
}
return NewPoly;
}


Polynomial operator * (const double c, const Polynomial& RHS){

Polynomial NewPoly;
for (int size = 0; size < RHS.size; size++){
    NewPoly.size = c * RHS.size;
}
return NewPoly;
}

const Polynomial& Polynomial :: operator = (const Polynomial& RHS) {

if (this == &RHS) {
    return *this;
}
else {
    delete[] coeff;
    coeff = new double[RHS.size];
    size = RHS.size;

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

        coeff[i] = RHS.coeff[i];
    }

}
return *this;
 }

 double& Polynomial :: operator [] (const int index) {

if (size >= 0 && size < index) {

    return coeff[index];
}

}

ostream &operator <<(ostream& output, const Polynomial& RHS){

int n = RHS.size;
double Polycoeff;
bool firstDigit = true;


for (int i = n - 1; i > 0; i--){
    Polycoeff = RHS.coeff[n - i - 1];
    if (firstDigit){
        output << Polycoeff << "x^" << i;
        firstDigit = false;
    }
    else if (Polycoeff > 0){
        output << " + " << Polycoeff << "x^" << i;
    }

    else {

        if (Polycoeff < 0) {

            output << " - " << -1 * Polycoeff << "x^" << i;
        }
    }
}
Polycoeff = RHS.coeff[n - 1];
if (Polycoeff >= 0){
    output << " + " << Polycoeff;
}
else {
    output << " - " << -1 * Polycoeff;

}

return output;
}

bool Polynomial :: operator > (const Polynomial& RHS) const {

return (this->size > RHS.size);

  }

//main.cpp

  #include <cstdlib>
  #include <cmath>
  #include <cstring>
  #include <string>
  #include <iomanip>
  #include "Polynomial.h"

using namespace std;


 int main() {


double Quad[] = { 3, 0, 2, 0, 1 };
double Cubic[] = { 1, -2, 0, 3 };
double Square[] = { 2, 3, 1 };

cout << "Creating Polynomial\n\n" << endl;
Polynomial Q(5, Quad);
Polynomial C(4, Cubic);
Polynomial S(3, Square);


cout << "Testing the Polynomial class.\n\n";
cout << " Q = " << Q << "\n\n";
cout << " C = " << C << "\n\n";
cout << " S = " << S << "\n\n";

 cout << " The Polynomial S value when x = 1 is :  " << S.PolynomialVal(1)
 << "\n\n" << endl;


    cout << " Testing sum operator:\n";

    cout << " Q + C :\n" << Q + C << "\n";

    cout << "Testing difference operator :\n\n";

    cout << " Q - C :\n\n " << Q - C << "\n\n" <<endl;

    cout << "Testing product operator:\n\n";

    cout << " Q * C :\n\n" << Q * C << "\n\n"<< endl;

system("pause");
return 0;
 }




Python: Can an exception class identify the object that raised it?

When a Python program raises an exception, is there a way the exception handler can identify the object in which the exception was raised?

If not, I believe I can find out by defining the exception class like this...

class FoobarException(Exception) :
    def __init__(self,message,context) :
        ...

...and using it like this:

    raise FoobarException("Something bad happened!", self)

I'd rather not have to pass "self" to every exception, though.




class not functioning methods properly

I defined a class to handle blocks of tweets so I could manage them a little easier

class twitter_block(object):

def __init__(self):
    self.tweets = []
    self.df = pd.DataFrame()

    self.tag = ''
def load(self, data):

    self.tweets = [x for x in data]

then defined a method as part of a pipeline:

 def clean(self):

    HTTP_PATTERN = '^https?:\/\/.*[\r\n]*'
    AT_PATTERN = '@\w+ ?'

    # tke away links
    self.tweets = [re.sub(HTTP_PATTERN, '', str(x), flags=re.MULTILINE) for x in self.tweets]
    # take away @ signs
    self.tweets = [re.sub(AT_PATTERN,'',str(x)) for x in self.tweets]

but when I call this:

tweet = load_data('The_Donald.json')
block = twitter_block(tag='donald')
block.load(data=tweet)
block.clean()
block.print()

it returns the 1504 tweets that I loaded into the block object same as before, no cleaning links or anything. Although, actually it does remove @ signs... but this method,

def smilecheck(self): #save a tweet if there is a smiley there smiley_pattern = '^(:(|:))+$' for tweet in self.tweets:

    if re.match(smiley_pattern, str(tweet)):
        pass
    else:
        self.tweets.remove(tweet)

does not remove the tweets without smileys, returns 1504 tweets, the same as I put in... any help guys? im sure this is a problem with the way I am approaching objects




laravel 5 and dynamic Inheritance

We have developped a SaaS software, without framework, and are considering using Laravel to make a new version.

In the actual code, a class could be inherited just for some customers (for specific code). For example we have a class named "myclass", il the class "myclass_123" exists (123 being the ID of the customer), our soft will automaticaly load myclass_123 extending myclass. So iheritence depends on who is connected.

How would you manage it in laravel 5, if this is possible (in a clean way !) ?

Thanks in advance for your experience !




Can metaclass be any callable?

To catch your eyes:

I think the documentation might be wrong!

According to Python 2.7.12 documentation, 3.4.3. Customizing class creation¶:

__metaclass__ This variable can be any callable accepting arguments for name, bases, and dict. Upon class creation, the callable is used instead of the built-in type().

New in version 2.2.

However, this article argues:

Q: Wow! Can I use any type object as the __metaclass__?

A: No. It must be a subclass of the type of the base object. ...

So I did an experiment on my own:

class metacls(list):    # <--- subclassing list, rather than type
    def __new__(mcs, name, bases, dict):
        dict['foo'] = 'metacls was here'
        return type.__new__(mcs, name, bases, dict)

class cls(object):
    __metaclass__ = metacls
    pass

This gives me:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    class cls(object):
  File "test.py", line 4, in __new__
    return type.__new__(mcs, name, bases, dict)
TypeError: Error when calling the metaclass bases
    type.__new__(metacls): metacls is not a subtype of type

So is the document really wrong?




Transferring information from text file to key/value pairs in a dictionary to be attributes set in a class object

Would it possible? I was having trouble trying to figure out how to do it exactly.

Where it would go from something like this:

Jim Bob

MAT 101-001, A, 2, Fall2009

CSC 204-0C1, B, 4, Spring2014

BIO 101-001, C, 4, Spring2014

Sally Jessie

MKT 201-001, A, 3, Fall2014

ENG 102-003, B, 4, Fall2014

MAT 251-001, C, 5, Spring2015

Bruce Willis

COL 101-001, C, 3, Fall2015

BUS 201-001, A, 3, Fall2015

EGL 102-004, B, 3, Fall2015

To key/value pairs like this: classes = {'COL 101-001': 'Fall2015'}

Which would output the info like this:

(name here)

GPA: (info here)

Total Credits taken: (info here)

Classes: (list of classes here)




How to make an abstract variable static to a sub class

<?php
abstract class A {
    public static $var = "A";
    public function setVar() {

    }
    public function test() {
        $this->setVar();
        echo static::$var;
    }

    public function returnVar() {
        return static::$var;
    }
}

class B extends A {
    public function setVar() {
        static::$var = 'B';
    }
}

class C extends A {
    public function setVar() {
        static::$var = 'C';
    }
}

$class = new B();
$class->test();

$class2 = new C();
$class2->test();

echo "</br>";
echo $class->returnVar();
echo $class2->returnVar();

?>

What I'm trying to do is make the variable $var static to the class that extends abstract class A without having to re-declare it else where.

So say perhaps I create multiple objects from class B that extends A, I want all objects made from class B to share the same $var value.

Say I then create objects based on class C, they should all share the same value of $var...

This is the result I'm currently getting:

BC
CC

However, what I'm looking for is:

BC
BC

Thanks