dimanche 31 janvier 2016

" Instance of class has no attribute 'method name' " when it does absolutely does

I'm trying to write my own version of the game 2048. Here's the pastebin for it

I just implemented a new method in my TwentyFortyEight class called 'grid_merge'. I try to call it in my 'move' method on line 109 but get this error:

AttributeError: TwentyFortyEight instance has no attribute 'grid_merge'

You can clearly see the grid merge function above it though, could this just be a formatting error ?




How to create object of class from client project

When we create a Silverlight application, it creates two Projects. The client and the Web Project. I have a class in my SilverlightApplication1.Web namespace and I am trying to create an object of that class in my Client code behind Page class which is present in SilverlightApplication1 namespace. But seems like I can't create an object from client project. How can I do this? What's the concept?




Calling Python functions/methods with zero arguments

According to Clean Code, a function should take zero arguments when at all possible.

If we take a trivial example in Python with a function that does nothing more than add 2 to whatever is passed to it:

def add_two(x):
    return x + 2

>add_two(1)
3

The only way I can see that such a function can have zero arguments passed to it is by incorporating it into a class:

class Number(object):
    def __init__(self, x):
        self.x = x

    def add_two(self):
        return self.x + 2

>n = Number(1)
>n.add_two()
3

It hardly seems worth the effort. Is there another way of achieving the no-argument function in this example?




C# Interface vs Class vs Struct

im planning to create 5 Bots (i.e controlled by scripts) they will have a few properties (int,bool,and maybe 1 string) but none of the bots will have they're own method. Those properties will have the same values when initialized, i mean bot1.property1 = 1; bot2.property1 = 1; later on i will change the variables depending which bot is taking action , so this equality is just in the beginning. The properties will be mostly if not only - static's. What should i use ? An interface, Class or a Struct ? Please provide some basic example with just 1 property in it and some explanation.




How do you fix this PracticeIt Classes Inheritence rounding bug?

Practice It link (because I cannot post pictures and this is where I found the practice problem)

How do you fix this PracticeIt Classes Inheritence rounding bug? Apparently it only malfunctions in the getDiscountPercent() method.

public class DiscountBill extends GroceryBill{
    boolean p;
    double totalD;
    double total2;
    double total;
    int count;
    
    
    public DiscountBill(Employee clerk, boolean preferred){
        super(clerk);
        p = preferred;
    }
    
    public void add(Item i){
        super.add(i);
            total2 += i.getPrice();
        if(p){
            totalD+=i.getDiscount();
            total += (i.getPrice() - i.getDiscount());
            if(i.getDiscount() > 0.000){
                count++;
            }
            
        }else{
            total+= i.getPrice();
        }
    }
    public int getDiscountCount(){
       return count;
    }
    public double getDiscountAmount(){
        return totalD;
    }
    public double getDiscountPercent(){
         return 100.0 * (total2-total) /total2;
    }
    public double getTotal(){
        return (double)Math.round(total * 100d) / 100d;
    }
}

Instead of returning 16.6421928536466, it returns 16.64219285364659.

Practice It link (you can copy and paste this code and try to solve it here)




Declaring static method in an inner class

I have to implement a code inside a given class which looks like this:

package onz;
public class tester {
    public static void main(String[] args) {

    class MyClass{
    //------------------------------------------------------------
        // Here goes my code
    //------------------------------------------------------------
    };
}

Does that mean that I can't use static methods ? When I write my static methods, eclipse give an error saying:

"The method cannot be declared static; static method can only be declared in a static or top level type"

but I really need all my code to go right there




How to run tkinter class upon clicking a button

I have a function where you select a number which is in a database. When you click confirm (there is a button on my tkinter gui saying 'confirm') I want a class called 'ExampleApp' to run which will display the infomation of the selected number in a table. I have the table but I do not know how to make the class 'run'. How would I do this?

btn_ScheduleConfirm = Button(self.master)

btn_ScheduleConfirm.config(text = 'Confirm', borderwidth = 10)

btn_ScheduleConfirm.bind('<Button-1>') <---- Something has to go here to run the class but idk what

btn_ScheduleConfirm.grid(row = 1, column = 1)

This is the 'table' class.

class ExampleApp(tk.Tk):
 def __init__(self):

    tk.Tk.__init__(self)
    t = SimpleTable(self, 2,8)
    t.pack(side="top", fill="x")
    t.set(0,0,'Time')
    t.set(0,1,'Monday')
    t.set(0,2,'Tuesday')
    t.set(0,3,'Wednesday')
    t.set(0,4,'Thursday')
    t.set(0,5,'Friday')
    t.set(0,6,'Saturday')
    t.set(0,7,'Sunday')




How to use Matlab's abstract property and to declare its type in the concrete subclass

I am trying to describe that an abstract class AA has an abstract property X of type BB. This property BB differs for different concrete subclasses of AA. This BB is also an abstract class, and its concrete subclasses will be used as X for different concrete subclasses of AA. However, when I tried to do that as the following code, I got an error message.

So first, AA and AA concrete are

classdef (Abstract) AA
    properties (Abstract)
        X@BB;
    end
end

classdef AAconcrete < AA
    properties
        X@BBconcrete;
    end
end

and BB and BBconcrete are

classdef (Abstract) BB
end

classdef BBconcrete < BB
end

When I tried to initiate AAconcrete, I got the following error message.

>> a = AAconcrete
Error using AAconcrete
The property 'X' restriction defined in class 'AAconcrete' must match the
property definition in base class 'AA'.

I understand that the error message said type BBconcrete is not the same as BB, although isa(BBconcrete,'BB') returns true. Even though if I don't declare X as type BB in the abstract class AA, the same error message appears.

I wonder what's the right way to describe such relationship, and your help is greatly appreciated!




Ostream operator overloading? [on hold]

I am new to C++, and I am trying to write a class for rational/fraction numbers. I am not sure if my code is correct, but it is compiling, however, whenever I ran my test files... I get a completely different number? I am not sure where the error might be.I was wondering maybe my constructor is wrong?

Also, I have gcd(greatest common denominator) function I have not used yet since I am still trying to figure out how to fix the error within the numbers.

.H file

.Cpp file

And this is the result after I run my main file, which is way off.

Rational test(3,4); cout << test << endl;

459202640/32764




Vector operations on object-array with 'colon' indexing [MATLAB]

In my Matlab code I have an object-array of 'masses' which are an object of a class which describes the mass, speed, accerleration etc.

To speed up the simulation I want to reduce the usage of for-loops with using more vector operations. One of the operations is to get the distance of the current mass to all others.

I would like to solve it like that:

%position is a vector with x and y values e.g. [1 2]
%repeat the current mass as many times as there are other masses to compare with
currentMassPosition = repmat(obj(currentMass).position, length(obj), 2);      
distanceCurrentMassToOthersArray = obj(:).position - currentMassPosition;

I cannot use the colon-indexing operation on the object array. Currently i use a for-loop where I iterate through every single object. Do you have any tips to optimise that without using a for loop?

I hope my question was clear enough, otherwise I will optimise it ;).




Python 3.x - Run function before appending item to list

In Python 3.x, is it possible to run a function before an item gets appended to a list ?

I have a class which inherits from a list, with some additionnal custom functions. I would like a series of checks to be performed on the data of any element which gets added to this list. If an added element does not meet certain criteria, the list will raise an error.

class ListWithExtraFunctions(list):

   def __beforeappend__(self):

      ... run some code ...
      ... perform checks ...
      ... raise error if checks fail ...




Error: Could not find or load main class

I am new to java and I am currently trying to run a program for a class assignment and it compiles however, every time I run it I get this error "Error: Could not find or load main class sailboat.java" To make things worse I need to submit this in a different way from standard assignments logging onto the main server of my campus and transfer it from my directory to another yet every time I do it, it tells me it can't open the source file.

Would these two situations because by the same thing? Is this something caused by a mistake in my code, or is it something wrong with my Classpath?

here's the code I made, I used notepad++

import java.text.*;
import java.io.*;
import java.math.*;

public class sailboat {
    public static void main (String argv []) throws IOException {
        BufferedReader stdin =
                new BufferedReader (new InputStreamReader (System.in));
        String inputValue;


        //Tartan 34C Title
        System.out.println("Sailboat: Tartan 34C");
        //Tartan 34C inputs
            double LOA = Double.parseDouble("34.50");
            double LWL = Double.parseDouble("24.00");
            double beam = Double.parseDouble("10.20");
            double displace = Double.parseDouble("11200.00");
            double displace_Ton = Double.parseDouble("5.60");
            double sail_Area = Double.parseDouble("483.00");


            //Hull Speed Formula
            double hull_Speed = Math.sqrt(LWL) * 1.34; 
                System.out.println("Hull Speed:" + hull_Speed);


            //Displacement to Waterline Length Formula
            double displace_Lng =  displace_Ton / 0.01 * Math.pow(LWL, 3.0);
                System.out.println("Displacement to water lenght:" + displace_Lng);


            //Sail Area to Displacement Formula
            double sail_Area_Displace = sail_Area / Math.pow((displace / 64), 0.67);
                System.out.println("Sail Area to displacement:" + sail_Area_Displace);


            //Capsize Screening Index Formula
            double Cap_I = beam / Math.pow((displace / 64), 0.33);
                System.out.println("Capsize Screening Index:" + Cap_I);


            //Comfort Index Formula
            double Comf_I = displace / (0.7 * LWL + 0.3 * LOA) * 0.65 * Math.pow(beam, 1.33);
                System.out.println("Comfort Index:" + Comf_I + "\n");

any input would be helpful.




Rounding numbers using the 4/5 rounding rule

I'm currently learning C++ and I have to write a simple Money class to perform calculations involving dollars and cents where arithmetic has to be accurate to the last cent using the 4/5 rounding rule. I have never dealt before with monetary amounts so I'm having some troubles in understanding how to get the best from my class.

I know that I shouldn't represent monetary amounts with float. So I use two data members for my class to store separately dollars and cents :

long int dollars
long int cents 

My problem is that I don't when and how I should round numbers. I asked myself this question while I was trying to implement an input operator for this class.

Suppose the user enters as input the values : 12.456, 45.999, 9.54.

  1. When should I round these numbers ?
  2. Should I first use them in arithmetic operations and then round the result or round them directly as they are entered into the program ?



Logical problems causing multiple instances of a note to be created

Here is the (without most of the functions) definition of a class called note.

   public class Note
    {
        private String text;
        String fileName = "";
        NoteManager noteManager = null;
        List<String> hyperlinks = new ArrayList<String>();

        public static final int BUFFER_SIZE = 512;

        public Note(NoteManager noteManager) {
            this.noteManager = noteManager;
            this.text = "";
        }

        public Note(NoteManager noteManager, String content) {
            this(noteManager);
            if (content == null)
                setText("");
            else
                setText(content);
        }

        public Note(NoteManager noteManager, CharSequence content) {
            this(noteManager, content.toString());
        }

        ....some functions....

        public static Note newFromFile(NoteManager noteManager, Context context,
            String filename) throws IOException
        {

        FileInputStream inputFileStream = context.openFileInput(filename);
        StringBuilder stringBuilder = new StringBuilder();
        byte[] buffer = new byte[BUFFER_SIZE];
        int len;
        while ((len = inputFileStream.read(buffer)) > 0)

         {
            String line = new String(buffer, 0, len);
            stringBuilder.append(line);

            buffer = new byte[Note.BUFFER_SIZE];
        }

        Note n = new Note(noteManager, stringBuilder.toString().trim());
        n.fileName = filename;

        inputFileStream.close();

        return n;
    }

       .... some functions attributed to this class

}

These notes are managed by a class called NoteManager.java, which I have abbreviated below:

public class NoteManager
{
    Context context=null;
    ArrayList<Note> notes = new ArrayList<Note>();

    ..... some functions...

    public void addNote(Note note)
    {
        if (note == null || note.noteManager != this ||   notes.contains(note)) return;
        note.noteManager = this;
        notes.add(note);    
        try
        {
            note.saveToFile(context);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }


    ....some functions....

    public void loadNotes()
    {
        String[] files = context.fileList();
        notes.clear();
        for (String fname:files)
        {
            try
            {
                notes.add(Note.newFromFile(this, context, fname));
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

    }
}

public void addNote(Note note)
    {
        if (note == null || notes.contains(note)) return;
        note.noteManager = this;
        notes.add(note);    
        try
        {
            note.saveToFile(context);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

I am trying to work out why this notepad app creates random new notes when the app is fully shutdown and then reopened, however I just cannot see what the problem is. I have cut out all the functions which didnt seem to relate to the problem, so the logical error must be here somewhere.

How does one go about finding what I am guessing to be some kind of circular reference or lack of checks?




access protected variable in derived class c++

I have a mother class and a derived daughter class. I am trying to access the protected variable 'familystuff' in the derived class. Both ways that I am trying to access it aren't working. When I compile and run it, I get the following output:

5 3 1

1

Familie 32768

FOO 32767

class Mother
 {
 private:
        int motherstuff;
 protected:
         int familystuff;
 public:
         int everyonesstuff;
         void SetStuff(int a, int b, int c){
            motherstuff = a;
            familystuff = b;
            everyonesstuff = c;
         }
         void Show(){
            cout << motherstuff << " " << familystuff << " " <<everyonesstuff << endl;
        }
};

class Daughter : public Mother
{
public:
    Daughter()
    {
            a = familystuff + 1;
    }
    void Show(){
            cout << "Familie " << a << endl;
    }
    int foo() { return familystuff;}
    private:
        int a;
 };

 int main(){

    Mother myMum;
    myMum.SetStuff(5,3,1);
    myMum.Show();
    cout << myMum.everyonesstuff << endl;

    Daughter myDaughter;
    myDaughter.Show();
    cout << "FOO " << myDaughter.foo() << endl;
}




Python 'str' object has no attribute 'name' when using a function variable to call a class instance

I'm just starting to learn programming with python. I'm trying to make a game similar to Pokemon, and I'm trying to apply OOP into agame.

I started by making a Pokemon class, and adding class-defined attributes such as name, HP, etype, attacks. "attacks" is a dictionary of lists.

My problem now is I'm trying to develop a simple battle engine where I can switch out pokemons. For this reason, I made a function/method name fight().

Inside that I have a variable named current_pokemon.name so whenever I switch out the pokemon, I can use the new pokemon's name, attacks, etc.

I used raw_input to return a string that replaces current_pokemon, which has a .name attribute to call on a pikachu instance. Instead, I get the 'str' object has no attribute. Why doesn't this work? It worked outside the function fight() when I explicitly wrote pikachu.attribute.

class Pokemon(object):
    def __init__(self, name, HP, etype, attacks):
        self.name = name
        self.HP = HP
        self.etype = etype
        self.attacks = attacks #2 attacks with name, dmg, type and power points

geodude = Pokemon("Geodude", 100, "Ground", 
                  attacks = 
                  {"Tackle":["Tackle",30,"Normal","35"], 
                   "Rollout":["Rollout",50,"Rock","20"]
                  })
                    #attacks = {attack:[attack_name, dmg, type, PP]}

pikachu = Pokemon("Pikachu", 100, "Lightning", 
                  attacks = 
                  {"Thunder Shock":["Thunder Shock",40,"Electric"],
                   "Quick Attack":["Quick Attack",40,"Normal"]
                  })

#selects pikachu's attack
print "Pokemon's name is", (pikachu.name)
print "Pikachu's %s attack damages %d" % ((pikachu.attacks["Thunder Shock"][0]),(pikachu.attacks["Thunder Shock"][1]))

pikachu.HP = pikachu.HP - geodude.attacks["Rollout"][1]
print "Pikachu's HP is", (pikachu.HP)
pikachu.HP = pikachu.HP - geodude.attacks["Tackle"][1]
print "Pikachu's HP is", (pikachu.HP)

#Pokemon Battle test with stored variable
#Value selector - replace all var attributes using an easy function
#Use Solution 2

def fight():
    current_pokemon = raw_input("pikachu or geodude? > ")
    print current_pokemon.name
    print current_pokemon.attacks


fight()

Output:

Pokemon's name is Pikachu
Pikachu's Thunder Shock attack damages 40
Pikachu's HP is 50
Pikachu's HP is 20
pikachu or geodude? > pikachu
Traceback (most recent call last):
  File "poke_game_stack.py", line 40, in <module>
    fight()
  File "poke_game_stack.py", line 36, in fight
    print current_pokemon.name
AttributeError: 'str' object has no attribute 'name'

Please help noob me with this simple problem! Thanks!




Showing the directory of the class in console when I am tying to print something in console

This is one class to return required Strings and char:

public class Author {

    private String name;
    private String email;
    private char gender;

    public Author(){}

    public Author (String name, String email, char gender){

            this.name = name;
            this.email = email;
            this.gender = gender;

    }

    public String getName(){        
        return name;
    }
    public String getEmail(){           
        return email;
    }

    public void setEmail(String email){         
        this.email = email;
    }

    public char getGender(){
        return gender;      
    }

    public String toStrnig(){   
        return "Name: "+ name + "\nEmail: "+ email + "\nGender: "+ gender;
    }

}

Here is main class to call the name, e-mail and gender.

   public class Book {

        public static void main(String[] args) {
            Author one = new Author("Shohurh", "ghostking@mail.mail", 'm');
            System.out.println(one);
            one.setEmail("nothing");
            System.out.println(one);
        }
}

This is the result in console: Library.Author@15db9742 Library.Author@15db9742

Would be thankful if you could highlight the wrong area of code:




Memory usage/ reference in java

I am going to ask a basic question about Java memory usage.

Imagine we have an array List and it is large enough and we don't like to use more memory. Now if I want to pass this array to another methods in this class, or other classes through their constructor or method, do I need additional memory/is there additional memory usage for this array?

If yes, could I just make this array package level, and therefore the other classes in this package could access it directly, without any memory need.

Thank you in advance.




How to correctly pass an image as an argument to a class in opencv python

I am a newbie to python and opencv and when I try to run this code I get an error in the colors method while converting BGR to HSV as

hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

cv2.error: C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\imgproc\src\color.cpp:7646: 
error: (-215) (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) in function cv::ipp_cvtColor

Even if I comment that part out and only run the part where it is simply returning the image as it is, it gives an error while displaying the image in cv2.imshow() as

cv2.imshow('image',res)

cv2.error: C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\highgui\src\window.cpp:281: 
error: (-215) size.width>0 && size.height>0 in function cv::imshow

Please help me figure out if I'm missing out on something.

class basicop:
@staticmethod
def colors(color, frame):
    if(color=='red'):
        lower = np.array([0, 100, 100])
        upper= np.array([10, 255, 255])
    elif(color=='green'):
        lower = np.array([86, 36, 99])
        upper= np.array([86, 255, 255])
    #CONVERT BGR TO HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(frame, lower, upper)
    res = cv2.bitwise_and(frame, frame, mask= mask)
    return frame

frame= cv2.imread('gree.jpg')
res=basicop.colors('green', frame)
cv2.imshow('image', res)
k = cv2.waitKey(0)
if k == 27:        
    cv2.destroyAllWindows()
elif k == ord('s'): 
    cv2.imwrite('sanj.jpg', res)
    cv2.destroyAllWindows()




samedi 30 janvier 2016

Why i'm having the methods of my subclass?

class MediaItem {
 var name: String
 init(name: String) {
     self.name = name
 } }



class Movie : MediaItem {
 var director: String
 init(name: String, director: String) {
     self.director = director
     super.init(name: name)
 } }

class Song : MediaItem {
 var artist: String
 init(name: String, artist: String) {
     self.artist = artist
     super.init(name: name)
 } 
}

var song : MediaItem = Song(name: "Mateo",artist: "Romeo")

Song i understand that is a MediaItem instance... right? But... i'm doing

= Song(name: "Mateo",artist: "Romeo")

Which methods should i have? The ": MediaItem" or the "= Song(name: "Mateo",artist: "Romeo")"




Can I set a layout from a class? (without an Activity)

I have a layout with a ImageView, which has no activity:

pieza.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView 
    xmlns:android="http://ift.tt/nIICcg"
    android:id="@+id/image"
    android:src="@drawable/arribin"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

and on the other hand, I have a class in which I try to modify the layout to inflate:

public void init(){
    res = this.getContext().getApplicationContext().getResources();
    lInf = (LayoutInflater)(getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE));
    lInf.inflate(R.layout.game, this, true);
}

private int getPieceId(){
    //trying to set the image
   ImageView image=(ImageView)findViewById(R.id.image);
    image.setImageResource(R.drawable.fast);
   return R.layout.pieza;
}
...
View newPiece = lInf.inflate(getPieceId(), null);

And LogCat:

ImageView.setImageResource(int)' on null object reference

Can I set the ImageView of a layout from a class without an Activity?




Python 3.4 - How to create a template property for many classes

In Python 3.x, is it possible to create a "template" property which can be reused by many classes ?

I have about 200 classes which correspond to products being sold in a shop. Each class uses properties specific to the product. The "get" and "let" function of each property perform sometimes elaborate sanity checks on the data when a property value is set.

Some of these properties are common throughout dozens of classes. A good example is the "Price" property. A simplified version of the "Price" property is shown below for class "Robot".

class Robot():


   def setPrice(self,Price):              # <--                        
                                          # <--
      if (Price < 1): Price = 1           # <--
                                          # <-- Common property
      self.__Price = Price                # <-- to many
                                          # <-- classes
   def getPrice(self):                    # <--  
                                          # <-- 
      return self.__Price                 # <-- 
                                          # <--
   Price = property(getPrice, setPrice)   # <-- 


   def setName(self,Name):

      if (type(Name) != type("a")): Name = "(no name)"

      self.__Name = Name

   def getName(self):

      return self.__Name

   Name = property(getName, setName)    

Would it be possible to isolate this property into some kind of external function of class, which could then be called by many of my classes ? In other words, could something like this be implemented ?

class_or_function PriceProperty():

   ... some code ...


class Robot():    

    Price = PriceProperty()            

    def setName(self,Name):

       if (type(Name) != type("a")): Name = "(no name)"

       self.__Name = Name

    def getName(self):

       return self.__Name

    Name = property(getName, setName)    


class Box():    

   Price = PriceProperty()       

   def setWeight(self,Weight):

      if (Weight < 25.0): Weight = 25.0

      self.__Weight = Weight             

   def getWeight(self):

      return self.__Weight

   Name = property(getWeight, setWeight) 




Python Subclasses Seemingly Editing Eachother

While working to create a basic text-adventure in the form of "Colossal Cave Adventure", "Zork", etc., I've encountered an issue with my Zombie and Skeleton classes seemingly editing each other.

class Entity(object):
    def __init__(self,name,hp,strength,defense,armor=False,weapon=Fist(),actions=["Attack","Block"]):
        self.name = name
        self.hp = self.maxhp = hp
        self.strength = strength
        self.default_defense = self.defense = defense
        self.armor = armor
        self.weapon = weapon
        self.initiative = 0
        self.actions = actions

    def attack(self,target):
        #An attack action
    def block(self):
        #A block action
    def update(self):
        #Updating the entity

class Zombie(Entity):
    def __init__(self):
        Entity.__init__(self,"Zombie",random.randint(13,20),4,5,Leather())
        print self.actions    #Printing the actions in order to try to fix this issue
        self.actions.remove("Block")
        print self.actions    #Printing the actions in order to try to fix this issue

class Skeleton(Entity):
    def __init__(self):
        Entity.__init__(self,"Skeleton",random.randint(16,23),6,5,False,Bow(999))
        print self.actions    #Printing the actions in order to try to fix this issue
        self.actions.remove("Block")
        print self.actions    #Printing the actions in order to try to fix this issue

monsters = [Zombie(),Skeleton()]

When the code is run, it returns

['Attack','Block']
['Attack']
['Attack']
#Error message

The error says that 'Block' isn't in the Skeleton's self.actions to remove, but as far as my understanding goes, 'Block' should be in there when Entity.__init__ is called. If I switch Zombie() and Skeleton() in monsters, the problem still happens, so the problem seems to be that the first subclass is removing the entry from both subclasses.

I'm new to subclasses, so it's very likely that the issue is in my limited understanding of how they work. Is this the intended behavior? If so, how would I get the behavior I'm looking for?




Copy (NSManaged)Object

My NSManagedObject class has a property holding an Int serving as some sort of tag. The default value is 0 and this object is the source of my table view. The property tag doesn't have to be an @NSManaged variable.

let data: [Items] = []

I have implemented a way to copy a cell by dragging it:

let newItem = data[indexPath.row]
newItem.tag++

let newPath = NSIndexPath(forRow: indexPath.row + 1, inSection: indexPath.section)

data.insert(newItem, atIndex: newPath.row)
tableView.insertRowsAtIndexPaths([newPath], withRowAnimation: .Fade)

This won't work obviously because tag will be changed in the original item as well. I can fix this by wrapping Items in a struct or using a tuple instead. But I was hoping I can avoid this and somehow find another (more elegant way) of doing this. Any ideas?




Why Am I getting my ArrayList empty if I call it from another class?

I am pretty new to Java, a small help will be highly appreciated.

Things to know about my code

I have two classes.

  1. First Class is called EvidenceBox.class
  2. Second Class called Police.class

In EvidenceBox class, I have a method called getParticularEvidence()

    public ArrayList <Evidence> getParticularEvidence(int caseNumber, String evidenceType) {
      EvidenceBox e = new EvidenceBox(caseNumber, evidenceType);
      return e.getEvidenceByType(caseNumber, evidenceType);
    }

What this method is doing doing is that it is taking caseNumber and evidenceType as parameter. Inside this method we are creating an Object instance of EvidenceBox class so that I can call another method called getEvidenceByType() which is in EvidenceBox Class. The whole point of this method is to take those two arguments above and pass it to another method in another class which has an if statement inside for loop that checks if the arguments is equal to something inside an ArrayList called evidenceBoxList, if it is equal then return the list of Evidences that were equal.

When I invoke this in the Main class:

System.out.println(crimeBoxOne.getEvidenceByType(2005000381, "S.Avery"));

What it does, is that it goes to the getEvidenceByType method, and then calls the other method which is in Evidence class:

    public ArrayList < Evidence > getEvidenceByType(int keyNumber, String keyName) {
      ArrayList < Evidence > setOfEvidence = new ArrayList < > (evidenceBoxList);
      for (Evidence e: setOfEvidence) {
        if (this.getCaseNumber() == keyNumber) {
          if (this.getCaseName().equals(keyName)) {
            System.out.println("Pieces of DNA Evidence in Evidence Box number " + this.getCaseNumber() + " found by " + this.getCaseName() + ": " + this.getEvidence());
            getEvidence().add(e);
          } else {
            System.out.println("Not found!");
          }
        } else {
          System.out.println("Not Found!");
        }
      }
      return getEvidence();
    }

The getCaseNumber is the number of the EvidenceBox, and the getCaseName is the name of the evidenceBox

My Problem

My problem is that The return of the list is always empty, even though it isn't because I added the EvidenceBox to the ArrayList. How can I resolve this problem?

getEvidence() is the getter method that returns the list of evidenceBox.




php call a class method from a callback parameter

From Class A I want to implement a callback that includes specific methods as parameters. Eg.

    call_user_func_array($callback, ['$this->get', '$this->post']);

However this doesn't work. What I am aiming for here is to do this:

index.php

    $API = new API();
    $API->state('/users', function ($get, $post) {
        $get('/', 'UserController.getAll');
    });

API.php

    public function state ($state, $callback) {
        call_user_func_array($callback, ['$this->get', '$this->post']);
    }

    public method get ($uri, $ctrl)  { echo 'getting'; }
    public method post ($uri, $ctrl) { echo 'posting'; }

Thanks for any input! I do realize using $this->method, won't work as $this-> will not exist within the callback scope.




Radial Gravity For A Planet Object In A Platformer Game And Its Class Structure

I am currently helping to make a game as a part of a Group Project at my University Games course using Action Script 3 within Flash Develop (we have the option to use other software such as Unity etc.).

The game we are developing will be a traditional platformer game, except instead of moving from left to right the complete each level, the player must reach the centre of the circular level, or planet.

I have two problems with this:

1) An actual solution for drawing in all objects towards the centre of the screen constantly (which stems from the problem of:)

2) The correct way to layout the classes and how each one is used.

We have been taught basic knowledge of different features of the program, such as using timers, input devices, listen events etc. but we have not been taught anything on basic class structure and I am having trouble starting off. (Classes for menu's, levels, NPC/enemies that spawn multiple instances etc.)

I am not asking for exact code to create something as such, I just need to know how to formulate the basic class structure for such a game for it to work correctly and perhaps the general idea of achieving radial gravity, as I it would be great if I could start this off with only a nudge in the right direction and figure the rest out on my own.




C++ - Upcasting & Downcasting

In my example :

At upcasting , the second "d.print()" call shouldn't print "base"?

Isn't it "d" derived object upcasted to a base class object ?

And at downcasting , what advantages does it have ?

Could you explain upcast and downcast in a practical way ?

#include <iostream>
using namespace std;

class Base {

public:

    void print() { cout << "base" << endl; }

};

class Derived :public Base{

public:
    void print() { cout << "derived" << endl; }

};

void main()
{
    //upcasting
    Base *pBase;
    Derived d; 
    d.print();
    pBase = &d;
    d.print();

    //downcasting
    Derived *pDerived;
    Base *b;
    pDerived = (Derived*)b;

}




Recursion in a function inside a class in python

I have difficulties in understanding the following python code:

class class1:

    def feed_forward(self, inputs):
        hidden_layer_outputs = self.hidden_layer.feed_forward(inputs)
        return self.output_layer.feed_forward(hidden_layer_outputs)

In particular I do not understand what the function feed forward does. Is it a recursive function? (I see that feed_forward() is called inside itself).




arbitrary unpackable functor class in python

Is there a way to implement a class so that it can be mapped over with the map-function and unpacked like a tuple? Something like that:

class T
...
t = T(1,[1,2,3])
a, b = t
a==1 #True
b==[1,2,3] #True
list(map(str,t))==['1','2','2'] #True

I tried using __iter__ but it turns out to be used for unpacking and map.




vendredi 29 janvier 2016

Call to a member function select() on a non-object

im trying to call select query through 'fund' class extended 'DB' class and select query is in DB class... i made fundinst() function and call select function by making fund class object... but it shows fatal error...

 function fundinst(){
    //echo "in fundinst()";exit;
    //echo $previous_month;exit;
    //echo $current_month;exit;
    //$funds = new funds;
    $probal = $funds->select($funds->table,'',"user_id = '".$_POST['user_id']."' and month = '".$previous_month."'");
    if(isset($probal[0]["crt_bal"]) && $probal[0]["crt_bal"]!=''){
    //print_r($probal);exit;
    $_POST["crt_bal"] = $probal[0]["crt_bal"] + $_POST["total"];
    //$inst = ($probal[0]["curInst"] * $probal[0][rateInst])/12 * 100;
    //echo $prograssive;
    }else{$_POST["crt_bal"] =$_POST["total"];}
    $_POST['created'] = date("Y-m-d h:i:sa");
    if($funds->save($funds->table,$_POST))
    {
        $_POST["curInst"] = ($_POST["balance"] * $rateInst)/ 12 * 100;
        $f_year->save($f_year->table,$_POST);
        echo "Save successfully";
    }
    else{echo "failed";}
}

this is fund class code

class funds extends DB
{
    var $table = "funds";   
}




what are the different types of classes available in programming languages?

class Test{

public static void main(String[] args){

    String s = new String("Hello,World");
    String h ="Hello";
}

}

//what are the different types of classes available in programming languages?




How do I know when to use a struct rather than a class in Swift 2.0?

How do I know when to use a struct rather than a class in Swift 2.0?

I know that classes allow people to exercise inheritance and sub classing and I see how classes are very beneficial this way. But if that's the case, when would we ever use structs? They just seem like a weaker version of a class.




Python: How to return a string with a certain formatting for a nested list

So I am trying to make a text-based adventure game, and it has a map system managed using a nested list, like so:

map_ = [
    ['O', 'O', 'O'],
    ['O', 'O', 'O'],
    ['O', 'O', 'O']
]

I have the map inside a class called Map() that has functions to create the map, add and change cells, and so on.

However, I am not sure how to print the map. I would like to create a __str__() function to print the map, but I am unsure of how to do so. I would like it to be printed out like this, with spaces separating the elements on the X axis and a line break separating the Y axis:

O O O
O O O
O O O

I have seen examples that look like this: for row in map_: print ' '.join(row) ...and this example prints the map in exactly the format I would like.

However, I want to turn this into a __str__() function, where it returns a combination of ' '.join(row) (printing a space between each row element) and '\n'.join(map_) (printing a newline between each row).

Of course, I would like the elements to be in the correct order (upper left on the printed view corresponds to map_[0][0] etc).

Is there a way I can do this with the __str__() function, or do I have to resort to using the printing function above?




Adding BOTH Mail and SMS/MMS delegates to class type

I have a simple app. It emails and SMS/MMS a screenshot.

Since I have two buttons that each execute two different functions - (1) screenshot then email; and (2) screenshot then SMS/MMS, I need to add these to my class in my code.

Currently ...

import UIKit
import MessageUI


class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

How can I add MFMessageComposeViewControllerDelegate to my above class statement?

I think I need to as I have functions that send Email and SMS/MMS.

Apologies for my language description, I'm very new :)




Overloading a C++ type to handle a custom class

Currently just messing around with overloading types and returning different things, but this one error has stumped me and I do not know how to google it.

The idea is, I have a "2dvector" class and I want to return the dot product to a single value and not vector form. Example: float dproduct = vec_a * vec_b;

I have successfully overloaded "*" to be dot product for my class. Though I'm stumped on how to take two classes, take the dot product as a single value, and return it into a different type.

My current thinking is this:

const float operator= (vec2& right);

const float vec2::operator= (vec2& right){
return (right.x + right.y);
}

Since the right side should evaluate properly since vec_a * vec_b will return a "vec_c" result.




c# to vb.net How to inherit more than one class? Can't convert it. SharpDevelop failed, too

I tried to convert this code from c# to vb.net but it always fails because vb.net does not allow to inherit more than one class into a class.

How can this be solved?

Here is the c# code:

 public class MyPromptService : PromptService, nsIAuthPrompt, nsIAuthPrompt2
{
   nsICancelable nsIAuthPrompt2.AsyncPromptAuth(nsIChannel aChannel, nsIAuthPromptCallback aCallback, nsISupports aContext, uint level, nsIAuthInformation authInfo)
    {
       throw new NotImplementedException();

    }

    bool nsIAuthPrompt2.PromptAuth(nsIChannel aChannel, uint level, nsIAuthInformation authInfo)
    {
        nsString.Set(authInfo.SetUsernameAttribute, "Username");
        nsString.Set(authInfo.SetPasswordAttribute, "Password");
        return true;
    }
}

Thanks so far for your help.




Can anyone help to explain this python code for the leetcode add two numbers?

I'm a 100% rookie for programing and 4 parts of this code doesn't make sense to me. However, it runs well and only takes 34ms upon submission.

  1. what is the type of l1 and l2? I tried to return type of them and it says listnode.ListNode. Not sure what that is. Does leetcode define a class without telling us? Then, how can we figure out what's hidden behind?

  2. In "s.next = ListNode(carry_out)", what I understand is that we define s.next as an object of class ListNode, am I right? Is this like a recursive thing? This is blowing my mind.

  3. To my understanding, the while sentence is saying as long as one of the three digit, the digit in l1,l2 and carry_out is not 0, the cycle will go on. But then, how can it calculate something like [2,0,0,5] and [3,0,0,1]? Why doesn't it stop by return [5]?

  4. digit_sum is also an obj of class ListNode, correct? Then, why return digit_sum is printing a list?

enter code here

#Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
def addTwoNumbers(self, l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    digit_sum = ListNode(0)
    carry_out = 0
    s = digit_sum
    while l1 or l2 or carry_out:
        if l1:
            s.val += l1.val
            l1 = l1.next
        if l2:
            s.val += l2.val
            l2 = l2.next
        carry_out = s.val / 10
        s.val = s.val % 10
        if l1 or l2 or carry_out:
            s.next = ListNode(carry_out)
            s = s.next
    return digit_sum




What is the difference between updating an object with a new object against updating its properties?

Say the follow Class:

public class MyClas
{
    public MyClass(uint a, string b, uint c, bool d)
    {
        A = a;
        B = b;
        C = c;
        D = d;
    }

    internal void Update(uint a, string b, uint c, bool d)
    {
        A = a;
        B = b;
        C = c;
        D = d;
    }

    public uint A { get; set; }
    public string B { get; set; }
    public uint C { get; set; }
    public bool D { get; set; }
}

We have MyClass as a static variable somewhere in the project making it accessible everywhere.

public static MyClass NamedItLikeThis { get; set; }

Then we have a method being called every X milliseconds and it updates NamedItLikeThis like this:

public void UpdateSeveralThings()
{
    NamedItLikeThis = new MyClass(1, "test", 2, true);
}

My question is:

  • What is the difference between updating NamedItLikeThis with a new object like the above example against instantiating it once with a new object and then using that object Update method to keep it up to date like the below example?

    public void UpdateSeveralThings()
    {
        if (NamedItLikeThis == null)
        {
            NamedItLikeThis = new MyClass(1, "test", 2, true);
        }
        else
        {
            NamedItLikeThis.Update(2, "update", 3, false);
        }
    }
    
    
  • What is the correct approach to update an object in this circumstances?




How to generate an arbitrary number of functions in a class in python? [duplicate]

This question already has an answer here:

To generate widgets that operate independently on a set of plots I need to generate a number of functions that all take different arguments inside a loop.

I'm trying to set up context with lambdas. However it seems like I keep overwriting the functions in the for loop. The relevant code is as follows:

  for attr_ind in attribute_ids:

        figure_obj = figure(plot_width = 1000, plot_height = 800, y_axis_type = "log", title = "this is a thing")
        setattr(self, attr_id + "_figure_obj" ,figure_obj)
                  ........................
        setattr(self, attr_id + "_radio_group", RadioGroup(labels = list_of_elements, active=0))
        setattr(self, attr_id + "_text_input", TextInput(value = "default", title="RSF for selected element: "))

        a = getattr(self, attr_id + "_text_input")
        a.on_change("value", lambda attr, old, new: self.update_data(attr_id, new))
        b = getattr(self, attr_id + "_radio_group")

and the function update_data looks like this

def update_data(self, attrname, new):
    radio = getattr(self, attrname + "_radio_group")
    figure = getattr(self, attrname +"_figure_obj")

    figure.title = new 

The end result is a set of plots that have a text-box that can be edited - but all change the last plot's title.




Is there a way to choose a random constructor to use in python?

Is there any way to choose a random one of my constructors to use? I have a pretty in depth code, but wrote up a silly one below just to make it as simple as possible.

class Engine(object):

    def __init__(self, scenario, fart, shart):
        self.scenario = scenario
        self.fart = fart
        self.shart = start   
        self.outcomes = [fart,shart]

    def giveScenario(self):
        print self.scenario

    def chooseOutcome(self):

        outcome = random.choice(self.outcomes)
        return outcome

dinner = Engine('You are at dinner','You fart','You shart')
home = Engine('You are at home','You fart','You shart')

Now let's say I was going to make a game where it chooses a random one of these two constructors (either the dinner or home one) to load into this bad boy, is there any way to do that?




Android Passing Class Object With Whatever Inside it to Other Activity

Short question: Class A implements Parcelable, Class B custom class contains many instances of other classes. Can i pass class B to other Activity as one object inside A and restore it again as one object with all data inside it?

The issue: I've read a lot of passing data between Activities using Serializable or Parcelable, i've read about passing data by Bundles, all are not suitable for my needs, i've a DataPackage class which is very simple class, going to store instances of classes, enums, arrays, getting some data by context..., i want to pass DataPackage from Activity to other one as one object, Serializable has easier implementation, but [context instanceof Serializable = false] so i can't receive context in my constructor if i'll implement Serializable, Parcelable has very complicated implementation and ugly writing/reading methods, i want just to pass my DataPackage object and getting it in other Activity with all data inside it

public class DataPackage {

    String name, hr_name;
    String mom_name, hr_mom_name;
    SimpleCalendarMan scman, hr_scman;
    String city;
    // =======================
    HoroscopeMan homan;
    K.Ruler ruler; // enum
    K.Type type;    // enum
    String[] compatibility_comparison_results;
    String[] chastity_results;
    String[] city_results;

    public DataPackage(Context ctx) throws Exception {
        if (ctx != null) {
            homan = new HoroscopeMan(ctx.getResources().getStringArray(
                    R.array.horoscopes), ctx.getResources().getStringArray(
                    R.array.horoscopes_natures));
            compatibility_comparison_results = ctx.getResources()
                    .getStringArray(R.array.compatible_or_not);
            chastity_results = ctx.getResources().getStringArray(
                    R.array.chastity);
            city_results = ctx.getResources().getStringArray(
                    R.array.city_pros_and_cons);
        }
    }

    protected void putType(K.Type type) throws Exception {
        this.type = type;
    }

    protected void putRule(K.Ruler ruler) throws Exception {
        this.ruler = ruler;
    }

    protected void putName(String name) throws Exception {
        this.name = name;
    }

    protected void putHrName(String hr_name) throws Exception {
        this.hr_name = hr_name;
    }

    protected void putMomName(String mom_name) throws Exception {
        this.mom_name = mom_name;
    }

    protected void putHrMomName(String hr_mom_name) throws Exception {
        this.hr_mom_name = hr_mom_name;
    }

    protected void putBirthdate(SimpleCalendarMan scman) throws Exception {
        this.scman = scman;
    }

    protected void putHrBirthdate(SimpleCalendarMan hr_scman) throws Exception {
        this.hr_scman = hr_scman;
    }

    protected void putCity(String city) throws Exception {
        this.city = city;
    }

}




Whats wrong with carrying these Variables in Java?

Currently learning Java right now, seems like a more difficult version of Python. Right now, we are learning about classes, and how to transfer Variables between classes. The project is simple, we are given two classes that have to do with taxes, and one class is the main, and the other sets the variables. While not adjusting the main class, how would you go through and debug these classes?

Main Class:

public class TaxFormTest {

    public static void main(String[] args)
    {
        TaxForm michiganStateTaxForm = new TaxForm();

        michiganStateTaxForm.setTaxRate(.07);
        System.out.println("Tax Form Rate: " + michiganStateTaxForm.getTaxRate());

        michiganStateTaxForm.setTaxRate(.09);
        System.out.println("Tax Form Rate: " + michiganStateTaxForm.getTaxRate());
    }
}

Secondary Class:

public class TaxForm{

    int taxRate;
    int rate;
    private double taxrate;

    public void setTaxRate()
    {
        taxRate = rate;
    }

    public double getTaxRate()
    {
        return taxrate;
    }

}

Thank you if you are able to assist me on this question.




Auto increment value in javascript class

I'm trying to auto increment a properties value each time I instantiate a new instance of the class. This is what my class constructor looks (I abstracted it down just a bit):

var Playlist = function(player, args){
    var that = this;
    this.id = ?; //Should auto increment
    this.tracks = [];
    this.ready = false;
    this.unloaded = args.length;
    this.callback = undefined;
    this.onready = function(c){
        that.callback = c;
    };
    this.add = function(tracks){
        for(var i = 0; i < tracks.length; i++){
            this.tracks.push(tracks[i]);
            this.resolve(i);
        }
    };
    this.resolve = function(i){
        SC.resolve(that.tracks[i]).then(function(data){
            that.tracks[i] = data;
            if(that.unloaded > 0){
                that.unloaded--;
                if(that.unloaded === 0){
                    that.ready = true;
                    that.callback();
                }
            }
        });
    };
    player.playlists.push(this);
    return this.add(args);
};

var playlist1 = new Playlist(player, [url1,url2...]); //Should be ID 0
var playlist2 = new Playlist(player, [url1,url2...]); //Should be ID 1

I'd like to not define an initial variable that I increment in the global scope. Could anyone hint me in the right direction? Cheers!




Modify the value of a property during PropertyChangedEventHandler

I am writing an application that reads information on the form and transforms that data in various ways based on a set of rules. Rather than get into the why's of the scenario, I will just lay out a basic example of what I am trying to do. Please note, this whole business of using PropertyChangedEventHandler and INotifyPropertyChanged is very new to me and I am still reading and learning about it.

Here is a sample class I use to capture the first name and a message to the user:

class Names : INotifyPropertyChanged
{

    private string _firstName;
    public string firstName { get { return _firstName; } set { SetField(ref _firstName, value, "firstName"); } }

    private string _nameMessage;
    public string nameMessage { get { return _nameMessage; } set { SetField(ref _nameMessage, value, "nameMessage"); } }

    #region handle property changes
    public event PropertyChangedEventHandler PropertyChanged;
    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        //if the value did not change, do nothing.
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        //the value did change, so make the modification.
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

Whenever the property for firstName changes, I want to automatically modify the value in the nameMessage property.

For example, the user types John, so the nameMessage property is set to Hello John.

This is a very simple example of what I am trying to accomplish but I am getting stuck because it is hard for me to understand how to get the pointer to that particular property for that index.

Here are my two questions: 1) What code should I write to get the changed value and modify it? 2) Does that business logic belong within the class, or should it be in a different class altogether?

Any pointers you can provide would be very helpful.

Thank you.




Public variable declaration not properly set outside class

I am doing a thing with C++ Qt, well, i have 2 headers and 3 src files (1 of these is main.cpp)

  • clientconnectwindow.h
  • tcpsocket.h

  • clientconnectwindow.cpp

  • tcpsocket.cpp

In tcpsocket.h I declared a class which contains public boolean property "isReadReady", which is set by a Qt "private slot" member function called "void isReadyRead()", the property "isReadReady" should be set to "true" when "isReadyRead()" is called, the problem is that isReadReady is not set inside clientconnectwindow.cpp, explaining better: If I check for "isReadReady" to be true in tcpsocket.cpp, it is "true", outside (clientconnectwindow.cpp), it is not true!

tcpsocket.h

 #ifndef TCPSOCKET_H
#define TCPSOCKET_H

#include <QTcpSocket>
#define JASM_SERVER_PORT 9734

class TcpSocket : public QObject
{

    Q_OBJECT

public:
    explicit TcpSocket(QString ipaddr,QObject *parent = 0);
    ~TcpSocket();
    int connectServer();
    QByteArray getMessage();
    void sendMessage(const char* message);
    bool isConnected;
    bool isDisconnected;
    bool isReadReady;
    QString getError;

private:
    QString plocal_ipaddr;
    QTcpSocket *plocal_tcpsocket;

private slots:
    void connected_success();
    void disconnected_server();
    void isReadyRead();

};

#endif // TCPSOCKET_H

clientconnectwindow.h

 #ifndef CLIENTCONNECTWINDOW_H
#define CLIENTCONNECTWINDOW_H

#include <QMainWindow>
#include "tcpsocket.h"

namespace Ui {
    class ClientConnectWindow;
}

class ClientConnectWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit ClientConnectWindow(QWidget *parent = 0);
    ~ClientConnectWindow();
    TcpSocket *jasm_tcp_socket;

private:
    Ui::ClientConnectWindow *ui;
    void setWindowStatus(const QString status);
    QString status;
    QString connect_ip;
    void launchTcpSocketConnection();

private slots:
    void getTextFromLineEdit();
};

#endif // CLIENTCONNECTWINDOW_H

clientconnectwindow.cpp

 #include "clientconnectwindow.h"
#include "ui_clientconnectwindow.h"
#include "tcpsocket.h"
#include <QRegExp>

ClientConnectWindow::ClientConnectWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ClientConnectWindow)
{
    ui->setupUi(this);
    this->status = "Not connected";
    ClientConnectWindow::setWindowStatus(this->status);

    connect(ui->btn_exit,SIGNAL(clicked()),this,SLOT(close()));
    connect(ui->btn_connect,SIGNAL(clicked()),this,SLOT(getTextFromLineEdit()));
}

ClientConnectWindow::~ClientConnectWindow()
{
    delete ui;
}

void ClientConnectWindow::setWindowStatus(const QString status)
{
    this->setWindowTitle(QString("[%1] JasmQt Client")
                         .arg(status));
}

void ClientConnectWindow::getTextFromLineEdit()
{
    QString textline = ui->ipaddr_linetext->text();
    this->connect_ip = textline;

    if(textline.isEmpty()) {
        this->connect_ip = "127.0.0.1";
    }

    if(this->connect_ip == "localhost" ||
       this->connect_ip == "127.0.0.1") {
        ui->iptype_label->setText("Connecting to localhost...");
    } else {
        ui->iptype_label->setText(QString("Connecting to %1")
                                  .arg(this->connect_ip));
    }

    QRegExp check("[0-9]*\\.[0-9]*\\.[0-9]*\\.[0-9]*");
    if(!check.exactMatch(this->connect_ip)) {
        this->status = "Error!";
        ui->iptype_label->setText("Error while parsing IP address!");
        ui->btn_connect->setEnabled(true);
        ClientConnectWindow::setWindowStatus(this->status);
        return;
    }else {
        this->status = "Connecting";
        ui->btn_connect->setDisabled(true);
        ClientConnectWindow::setWindowStatus(this->status);
    }

    //Socket connection
    launchTcpSocketConnection();
}

void ClientConnectWindow::launchTcpSocketConnection()
{
    jasm_tcp_socket = new TcpSocket(this->connect_ip);
    jasm_tcp_socket->connectServer();
    if(jasm_tcp_socket->isConnected)
    {
        qDebug() << "Connected";
        if(jasm_tcp_socket->isReadReady){
            qDebug() << "Ready";
            qDebug() << jasm_tcp_socket->getMessage();
        }
    }
}

tcpsocket.cpp

 #include "tcpsocket.h"
#include <QtDebug>

TcpSocket::TcpSocket(QString ipaddr, QObject *parent)
    : QObject(parent)
{
    this->plocal_ipaddr = ipaddr;
    this->isReadReady = false;
    this->isConnected = false;
    this->isDisconnected = true;

    this->plocal_tcpsocket = new QTcpSocket();
    qDebug() << "*** TcpSocket object constructor end ***";
}

TcpSocket::~TcpSocket()
{
    this->plocal_tcpsocket->close();
    delete this->plocal_tcpsocket;
}

int TcpSocket::connectServer()
{
    connect(this->plocal_tcpsocket,SIGNAL(connected()),this,SLOT(connected_success()));
    connect(this->plocal_tcpsocket,SIGNAL(disconnected()),this,SLOT(disconnected_server()));
    connect(this->plocal_tcpsocket,SIGNAL(readyRead()),this,SLOT(isReadyRead()));

    qDebug() << "** Connecting to: " << this->plocal_ipaddr << JASM_SERVER_PORT;

    this->plocal_tcpsocket->connectToHost(this->plocal_ipaddr,JASM_SERVER_PORT);

    qDebug() << "** Waiting for connection... **";
    if(!this->plocal_tcpsocket->waitForConnected(6000)) {
        getError = this->plocal_tcpsocket->errorString();
        qDebug() << "*** ERROR! ***" << getError;
        return -1;
    }

    return 0;
}

void TcpSocket::sendMessage(const char* message)
{
    this->plocal_tcpsocket->write(message,qstrlen(message));
}

QByteArray TcpSocket::getMessage()
{
    QByteArray readres = this->plocal_tcpsocket->readAll();
    return readres;
}

void TcpSocket::connected_success()
{
    qDebug() << "* Connected *";
    this->isConnected = true;
    this->isDisconnected = false;
}

void TcpSocket::disconnected_server()
{
    qDebug() << "* Disconnected *";
    this->isDisconnected = true;
    this->isConnected = false;
}

void TcpSocket::isReadyRead()
{
    qDebug() << "* Ready *";
    this->isReadReady = true;
}

Shortly, in TcpSocket::isReadyRead(), if I check the value of this->isReadyRead, it is true, if I do in clientconnectwindow.cpp, it appears to be false.

Thank you guys!




Can't access class object variable

I'm using Swift 2 to make a function that creates a bunch of objects from a class I wrote.

Now, the problem is that when I'm adding a new object I have no problem, I checked multiple times both from the function and from the init() function that it stores the data. (Printing self.myVariable from the init() function works).

However, when later I go to retrive my variable for example like

 if let dog: Animal? = Animal.init(id : "12345"){
print(dog?.legs)}

That prints nil, even though I checked in the Animal class and it successfully initialized the Animal object "dog".

If anybody has any idea why this is happening that would be really useful and appreciated.




Need help creating a summary for student activities, below:

I have both a public class and an app. Using a loop "for" statement, I have successfully created a list of 20 at random activities for new student user. Now, I need help creating a random percentage for each student activity.

public class student {
private String firstName;
private String lastName;
private int age;
String[] msg = {" working on crazy Java lab", "interacting with 
peers", "surfing the web"};

public student(String firstName, String lastName, int age){
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
}

public int getAge(){
return age;
}

public String whatsUp(){
double random = Math.random();
double rn_max5 = random * 3;
int ri_max5 = (int) rn_max5;
return firstName + " " + lastName + " is "+msg[ri_max5];

}
}




how to create a class in between php tags

I have 2 functions each containing a PDO object in a functions.php file that output html and are called in a different file. I am trying to organise my code and have put my database information outside of those functions and using them as globals.

I have read that using globals are bad practice so I though of having a class with the two functions inside, but as there is html inbetween the functions i'm finding it difficult to place them inside the class properly if it's even possible. best way I can demonstrate is with my code. How can I organise this in a class?

<?php 

    $hostname = 'host';
    $db = 'database';
    $user = 'username';
    $pass = 'password';

?>

<?php function connectDB () {

    global $hostname, $db, $user, $pass;

    $dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

    $sql = "query 1";

    $query = $dbh->prepare($sql);
    $query->execute(array(//'placeholder',//'placeholder')); 
    $query->setFetchMode(PDO::FETCH_ASSOC); 

        while ($r = $query->fetch()): 

            $variable1 = $r['column1']; 
            $variable2 = $r['column2'];
            $variable3 = $r['column3'];
            $variable4 = $r['column4'];
            $variable5 = $r['column5'];
            $variable6 = $r['column6'];
            $variable7 = $r['column7'];

?>

//html code

<?php endwhile; } ?>




<?php function connectDB2 () {

    global $hostname, $db, $user, $pass;

    $dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

    $sql = "query 2";

    $query = $dbh->prepare($sql);
    $query->execute(array(//'placeholder',//'placeholder')); 
    $query->setFetchMode(PDO::FETCH_ASSOC); 

        while ($r = $query->fetch()): 

            $variable1 = $r['column1']; 
            $variable2 = $r['column2'];
            $variable3 = $r['column3'];
            $variable4 = $r['column4'];
            $variable5 = $r['column5'];
            $variable6 = $r['column6'];
            $variable7 = $r['column7'];

?>

//html code

<?php endwhile; } ?>




How to include a file that defines constants in a class (and it's scope)

Say we have the following:

some.class.php

class
{
    public __construct()
    {
        fun_stuff();
    }

}

configuration.inc

const SOMECONST = 1;
const SOMEOTHERCONST = 2;

I am looking to do something like this:

some.class.php

class
{
    public __construct()
    {
        include_once(configuration.inc);
        fun_stuff();
    }

}

Now this works, but the constant is not defined within the scope of the class (echo some::SOMECONST;) but rather in the global scope (echo SOMECONST;)

I really really want to have the constants in another file as it makes a lot of sense in my case. Is there a way to declare the constants in the scope of the class? I know it's impossible to use includes or requires inside the class definition so i'm at a loss.




Returning variables vs assigning attributes

I never got formal OOP instruction, and just kinda stumbled my way through the basics in python, but am at a crossroads. When dealing with an instantiated class object, is it better to assign attributes via methods, or have the methods just return the values? I've read a lot about not letting the object's state get out of whack, but can't figure out the best way. Here's a simple example:

import magic
class Histogram():
    def __init__(self,directory):
        self.directory = directory

    # Data Option 1
    def read_data(self):
         data = []
         file_ref = open(self.directory,'r')
         line = file_ref.readline()
         while line:
             data.append(line)
             line = file_ref.readline()
         return data

    # Data Option 2
    def set_data(self):
         data = []
         file_ref = open(self.directory,'r')
         line = file_ref.readline()
         while line:
             data.append(line)
             line = file_ref.readline()
         self.data = data



    # Hist Option 1
    def build_histogram(self):
        data = self.read_data()

        # It's not important what magic.histogram does.
        self.histogram = magic.histogram(data)

    # Hist Option 2
    def get_histogram(self,data):
        return magic.histogram(data)

    # Hist Option 3 - this requires self.get_data() to have already run.
    def build_histogram_2(self):
        self.histogram = magic.histogram(self.data)

So Data Option 1 forces the user to either call that and store it somewhere to use in conjunction with Hist Option 2 or store it in self.data to use with Hist Option 3. Data Option 2 lets you use Hist Option 3, but you still have had to already run set_data.

So my real question is, for a class with methods to do different things, that often CAN but don't HAVE to be chained together, how should I write it? Implicitly setting attributes and risk getting the state messed up? Return variables and let the "User" set them? Have getters for the attributes that my methods use, and if the attributes don't exist handle that somehow?

Please let me know if you need better explanation, or another example or anything.




PHP - Return Class in JSON

I have a class:

class A {
   protected $nome;       

   public function getNome() {
       return $this->nome . " exemplo";
   }

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

When i use the code:

$r = new A();
$r->setNome("My");
json_encode($r);

the code not returns because of the protected property, if the property is public the code returns but does'nt returns correctly.




Trying to show the list of the hashmap keyset in the other method

Here is the code for converting the length. So, I want to call the hashmap keyset list from the main class and list them in console. I am trying to show the keyset before each printing:

import java.util.Scanner;
        public class Main {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);

    // The keyset can be set here to show the alternatives to convert to the user
            System.out.println("What length you want to confert from");
            String to = input.nextLine();

            System.out.println("What length you want to confert to");
            String from = input.nextLine();

            System.out.println("Input length");
            double value = input.nextDouble();

            int result = (int)Length.convert(value, from, to);
            System.out.println((int )value +  from + " = " +  result + to);
        }
        }

** Here is the second class for converting the length: **

  import java.util.HashMap;   
    public class Length {   
    public static double convert(double value, String from, String to ){

            HashMap<String, Double> table= new HashMap<>();

            table.put("mm", 0.001);
            table.put("cm", 0.01);
            table.put("dm", 0.1);
            table.put("m", 1.0);
            table.put("hm", 100.0);
            table.put("km", 1000.0);
            table.put("ft", 0.3034);
            table.put("yd", 0.9144);
            table.put("mi", 1609.34);

            double from_value = table.get(from);
            double to_value = table.get(to);
            double result = from_value/to_value*value;

            return result   
    }
    }




Invoking method of anonymous class

Java 7

First of all, I'm going to simplify the example to avoid posting unnecesary code. My specific concrete example a little bit complicated, but I' try to preserve the point.

public class Test {

    public static void main(String[] args){
        Test t = new Test(){ //<---------------------------------------------------------
            public void m(){ //                                                         |
                Test t = new Test(){//                                                  |
                    public void m(){//                                                  |
                        //Here I need to invoke the most inclosing class's m() method 
                    }
                    //other actions
                };
            }

            public void someMethod(){
                //action
            }
        };
    }

    public void m(){

    }
}

Is it possible to do in Java? I mean, to invoke the method of anonymous class that way?




Java Compile error when return Generic Class type

public interface Parent{
}

public class Child implements Parent{
}

public <T extends Parent> Class<T> getClass(){
  return Child.class;  // compile error, add cast to Class<T>
}

I expect there is no error about above code, however I get compile error when I return Child.class.




What purpose does empty exception class serve?

I have seen implementation for exceptions like:

<?php

class TestE extends Exception {}

class MyTest {

    public function __construct() {
        try{
            throw new TestE('This is an exception!');
        }catch(Exception $exc){
            var_dump($exc);
        }

        echo '2';
    }
}

$o = new MyTest();

where a custom exception class like TestE is defined but kept empty as above. What purpose does it achieve? I could have easily used:

throw new Exception('This is an exception')

instead of

throw new TestE('This is an exception')




jeudi 28 janvier 2016

Can a function argument be multiply typed?

I'm fairly sure the answer is no, but since it would be quite lovely, I'll ask the question anyway.

Example:

class Serializable
{
public:

  virtual void serialize() = 0;
};

class Unserializable
{
public:

  virtual void unserialize() = 0;
};

class A : public Serializable
{
public:

  virtual void serialize()
  {
  }
};

class B : public A, public Unserializable
{
public:

  virtual void unserialize()
  {
  }
};

Now, is there some way to create a function with one argument that is both an instance of Serializable and Unserializable such that an object of class B could be passed (without, of course, referencing the derived type B)? Something like:

void readAndWrite(Serializable_Unserializable& object);




is there better or correct way to use objects with vector in c++?

i have a class like this:

class Foo{
public:
   Foo(); 
   Foo(int, int, int)
  ~Foo();
private:    
   int a;
   int b;
   int c;
}

and int main function and like to save my elements(objects) in a vector:

int main()
{
   vector <Foo*> foo; // <------this line
   for(int i=0; i<=500; i++){
   foo.push_back(new Foo(i+1,i+2; i+3)); //<------ this line 
}

is there a better solution to do that and replace 2 line above?

tnx all;




Trying to set up a class thru .h and .cpp files -- why do I get these errors?

I'm using g++ on Debian 8.2 Jessie.

I'm learning about classes in C++. I think I understand the basics, but not fully how to instantiate class objects with header files.

Here's Movie.h:

#ifndef MOVIE_H
#define MOVIE_H

#include <string>

class Movie
{
private:
    std::string     m_title;
    int             m_releaseYear;
    std::string     m_description;
public:
    Movie(std::string &title, int releaseYear, std::string &description);
    ~Movie()
    {
        std::cout << "\nDestructor called\n";
    }

    void        setMovieInfo(std::string &title, int releaseYear, std::string &description);

    std::string getTitle();
    int         getReleaseYear();
    std::string getDescription();
    void        printInfo();
};

#endif

Then there's Movie.cpp:

#include "Movie.h"

// Movie constructor
Movie::Movie(std::string &title, int releaseYear, std::string &description)
{
    setMovieInfo(std::string &title, int releaseYear, std::string &description);
}

// Movie mem function
void Movie::setMovieInfo(const std::string &title, const int releaseYear, const std::string &description)
{
    m_title=            title;
    m_releaseYear=      releaseYear;
    m_description=      description;
}

std::string Movie::getTitle()
{
    return m_title;
}

int Movie::getReleaseYear()
{
    return m_releaseYear;
}

And main.cpp:

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

int main(){
    std::string     title;
    int             releaseYear;
    std::string     description;

    title=          "Blade Runner";
    releaseYear=    1982;
    description=    "Harrison Ford's character hunts a group of runaway four-year-olds.";

    Movie bladeRunner(&title, releaseYear, &description);
    bladeRunner.printInfo();

    return 0;
}

    std::string Movie::getDescription()
    {
        return m_description;
    }

    void Movie::printInfo()
    {
        std::cout << "Title: " << m_title << '\n';
        std::cout << "Year: " << m_releaseYear << '\n';
        std::cout << "Description" << m_description << '\n';
    }

But when I run g++ main.cpp -o main.sh && ./main.sh from the terminal, I get this error:

main.cpp: In function ‘int main()’:
main.cpp:13:53: error: no matching function for call to ‘Movie::Movie(std::string*, int&, std::string*)’
  Movie bladeRunner(&title, releaseYear, &description);
                                                     ^
main.cpp:13:53: note: candidates are:
In file included from main.cpp:2:0:
Movie.h:13:2: note: Movie::Movie(std::string&, int, std::string&)
  Movie(std::string &title, int releaseYear, std::string &description);
  ^
Movie.h:13:2: note:   no known conversion for argument 1 from ‘std::string* {aka std::basic_string<char>*}’ to ‘std::string& {aka std::basic_string<char>&}’
Movie.h:6:7: note: Movie::Movie(const Movie&)
 class Movie
       ^
Movie.h:6:7: note:   candidate expects 1 argument, 3 provided

Based on my almost-ignorant level of C++ knowledge, it looks like the compiler expected a pointers, but got references?

But I thought I explicitly told these member functions to accept references?

Should I even use references to pass the std::string variables? Or pointers? Or neither?




Understanding objects passed in a class and self calling function in Python

Can some help me understand the Python code below. I am trying to figure what "output = layer.ingredients(input_)" does?

class Lasagna(Layer): 

    def __init__(self, layers):
        self.layers = layers

    def ingredients(self, input_):
        # We remember the inputs for each layer so that we can use them
        self.inputs = []
        for layer in self.layers:
            self.inputs.append(input_)
            output = layer.ingredients(input_)
            input_ = output
        return output 
lasagna = Lasagna([Linear(784, 100), Function1(), Linear(100, 10), Function2()])

Thanks




Using the point class inside my robot class?

Basically my assignment is to create a class for a robot that can turn left/right, move, and then return the location/direction of the robot, all using the Point class.

I'm a little lost in what should go inside the actual methods.

public Robot(Point loc, int d)
 {
   currentLocation = loc;
   currentDirection = d;
 }

I have the constructor set up like this at the moment, but I still need to establish that north will be 0, east will be 1, south will be 2, and 3 will be west, where would I do this?

I also am lost on what to fill inside the methods. For example:

public void turnLeft()
 {

 }

For the turn left method I know I would have it get the current direction and then add 1 to it, so if it was facing south which is (2) it would become 3 which is west.

Can anyone throw me in the right direction to do this?

Thanks




Tkinter: Putting Code Into Class Breaks Python

I have this really simple and short few lines of code:

import Tkinter as tk

master = tk.Tk()

w = tk.Canvas(master, width=800, height=600)
w.pack(side="top", fill="both", expand=True)

master.mainloop()

For readibility, extended functionality, portability and other reasons I want to put the code into a class, like this:

class Example(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.create_window()
    def create_window(self):
        self.canvas = tk.Canvas(self, width=800, height=600)
        self.canvas.pack(side="top", fill="both", expand=True)


if __name__ == "__main__":
    app = Example()
    app.mainloop()

The code runs fine, exactly like the one above, but when I stop the program I get a "Python has stopped working" message. It doesn't affect the program itself but I want to know what's causing it and why it runs perfectly outside a class.




i need to compare an individual object to an array using a method in a separate class

    int blue = 1;
    int yellow = 2;
    int green = 3;
    int pink = 4;


    Triangle[ ] tri = new Triangle[21];
    Triangle [0] tri = new Triangle [blue,yellow,green];
    Triangle[1] tri= new Triangle [pink,blue,yellow];
    Triangle[2] tri= new Triangle [green,pink,yellow];

i have this array and i want to compare the objects in to each other using a method in a separate class public boolean compareColors(Triangle another) {

       if(colorRight == getRightColor() && colorLeft == getLeftColor() &&                   colorBottom == getBottomColor())
  return true;
  else
  return false;
}

i can't figure out the exact way to compare them or use the Triangle another input to compare the triangles one by one




How to properly compile a tostring method

I'm learning java as a beginner so if this question is incredibly trivial, bear with me- we all started from somewhere!

I'm learning about the tostring method and apparently my code below is meant to print out "Hello" however what it is printing out is Ape@6D06d9c which I just dont understand. Could someone please help in explaining where exactly I am wrong and how to remedy it

class Ape {

    public String tostring() {

    return "Hello";
    }
}


public class learningtostring1{
    public static void main(String[] args){
        Ape kermit = new Ape();
        System.out.println(kermit);
}


}




Calling a method error

I'm stuck with my code, I feel like I'm really overlooking something, but I'll ask anyway, because everything is learning! I'm trying to call this method, but I'm not really sure how to do it, I've a segment of my code that I'm working with.

public double Math2(double num1)
{
    return num1 * 1.5;            
}

public double Math3(double num2, double num1)
{
    return num2 * num1;
}

public override string ToString()
{
    return //num3 + " " + 

I tried calling Math2 like

return num3 + " " + Math2;

but it gave me an error. What exactly am I doing wrong? Thanks for helping a noob out!




About scope in Ruby local and instance/class variables?

I have a script for a simulation I'm working on:

  def winner_client
    clients = [@client1, @client2, @client3]
    @winner = clients.find { |drunkest| drunkest.drunk == 3 }.name
    puts "#{@winner} is too drunk!"
    Bouncer.kick(@winner)
  end
end

In the winner_client method, I want the clients array to work at the class level so I can use it in other methods. But if I do this:

class OpenBar
  @@clients = [@client1, @client2, @client3]

  def initialize
   #...

when I call the winner_client method it raises

KatzBar.rb:57:in block in winner_client': undefined method drunk' for nil:NilClass (NoMethodError)

How can I fix this?




More memory efficient way to define many objects of the same type

So, I'm foraying into the world of plasma simulation. Now, while I'm aware that top-level simulations are written in fortran and have ultra-memory efficient subroutines and specialized code, I'm hoping to just run some low-level simulations.

My problem is that, when simulating a large number of particles in a time-varying environment (well, time-stepped), keeping track of all that data is a trick. I've used multi-dimensional arrays before - using the column number for the particle, and the row number for the attribute, however this feels rather clumsy. It does, however, seem to be more quickly executed.

I recently tried defining my own class, however being a python newbie, I probably did it in a very inefficient way. For each particle in 3 dimensions, I needed to be able to store the particle's position, velocity and Force (with the potential to add more variables once the code becomes more complex). Using what I knew of classes, I defined a "particle" object (I think) that make my code much easier to read and follow:

# Define Particle as a class
class particle():
    def __init__(self, index=0, pos = np.array([0, 0, 0]), vel = np.array([0,0,0]), F = np.array([0, 0, 0])):
                self.index = index      # Particle index (identifier)
                self.pos = pos          # Position 3-vector
                self.vel = vel          # Velocity 3-vector
                self.F = F              # Net force 3-vector (at particle)

So, I can easily initialize an array containing lots of these objects, and modify each value in a reasonably straightforward way. However as I mentioned, this ran slower for simulations involving only a few particles. I will be playing with my code to compare it to a purely matrix-oriented method to see which one scales better with large simulations.

My question I suppose then is this: Is defining a "particle" in this way the most efficient? Or is there a more CPU/memory efficient way to define such an object. I would like to keep it's method ability (i.e. particle[i].pos = [1,2,3] or particle[2].vx[1] = 3) so I can set values for each particle, as well as pass them through functions. Keep in mind I'm a python newbie, so I probably won't have great success with large, complex code.




C++ class template specialization with pointers

I have a tree structure of the following format:

template <typename DataType>
class Tree {

    DataType *accessData() { return data; } 

    Tree *child1, *child2;
    DataType *data;
};

template <typename DataType>
class Root : public Tree<DataType> {
    // root provides storage of nodes; when it goes out of scope, the
    // entire tree becomes invalid
    MemoryPool<Tree> nodeStorage;
    MemoryPool<DataType> dataStorage; 
};

I use a variety of instantiations of this template in my program. It works quite well.

One instantiation, however, uses a DataType which is just an enum (so it's the same size as a pointer!) and because speed is essential (both when the tree is built, and when it is accessed), I'd much rather have this instantiation use the enum directly instead of a pointer. An example how I'd like the code to look (not strict):

Tree<BigClass> *foo = ...;
foo->accessData()->doBigClassThings();
Tree<int> *bar = ...;
int x = 4 + bar->accessInt();

Now of course I could just keep the current templates but I don't like this extra pointer access and especially the need to allocate ints in the root. Any ideas on how I can specialize the template to provide this functionality, or other approaches?

I've tried to specialize the template like this (and a bazillion other ways)

template <> Tree<int> { ... }

But I just keep getting compile errors. Any help would be greatly appreciated!




Understanding constructor and super in class

What exactly does the following code do?

class Hat extends React.Component {
    constructor(props) {
        super(props);
    }
}

It creates a ReactComponent, obviously, but I'm struggling to understand both constructor and super.




Subscript out of range on Class VBA

good morning, I have this issue, I create this class named "CInventory", this class generate an array of "valid data" and just to see this array on a range I try to "paste" the array to see the result, but I get an "subscript out of range", the error appears on line 6 (cinv.AllocateInventoryData) of the simple module, can somebody help me? thanks

This is the Class Module called CInventory:

Option Explicit
Private Path As String
Private TextFileNumber As Integer
Private InventoryData() As String

Public Property Get GetInventoryData() As String
    GetInventoryData = InventoryData
    End Property
    Public Property Let SPath(Text As String)
    Path = Text
End Property

Public Sub AllocateInventoryData()
    Dim ColumnArray() As String
    TextFileNumber = FreeFile
    Dim FileContent As String
    Dim i, j As Integer
    j = 0
    Open Path For Input As TextFileNumber
    FileContent = Input(LOF(TextFileNumber), TextFileNumber)
    Close TextFileNumber
    ColumnArray() = Split(FileContent, vbCrLf)
    For i = LBound(ColumnArray) To UBound(ColumnArray)
        If IsValidRow(ColumnArray(i)) Then
            ReDim Preserve InventoryData(j, 4)
            InventoryData(j, 0) = Left(ColumnArray(i), 8)
            InventoryData(j, 1) = Trim(Mid(ColumnArray(i), 10, 8))
            InventoryData(j, 2) = Trim(Mid(ColumnArray(i), 19, 18))
            InventoryData(j, 3) = Trim(Mid(ColumnArray(i), 57, 2))
            InventoryData(j, 4) = Trim(Mid(ColumnArray(i), 60, 12))
            j = j + 1
        End If
    Next i
End Sub

Private Function IsValidRow(Text As String) As Boolean
    If Left(Text, 6) = "iclorp" Or Left(Text, 5) = "Page:" Or Len(Trim(Text)) < 3 _
    Or Left(Text, 4) = "Site" Or Left(Text, 6) = "------" Then
        IsValidRow = False
    Else
        IsValidRow = True
    End If
End Function

And this is the Module from which I call the class CInventory (simple module)

Option Explicit
Sub example()
    Dim cinv As CInventory
    Set cinv = New CInventory
    cinv.SPath = "H:\Joel\invent_2.prn"
    cinv.AllocateInventoryData   '<-- here appears the error
    Worksheets(1).Cells(1, 1) = cinv.GetInventoryData
End Sub




"Intent" from Activity to Application

I know there is no option to Intent from Activity to Application. There is other way to trigger and move to extends Application class from extends Activity class?

I build a project on Android Studio that extends Application and then added extends Activity for the opening of the application. now, I can't find a way to move from the Activity class to the Application class.

There is a possible way?




Define an error class for C++

I've been trying to define an error class in C++. I have three files; main.cpp, my_class.h, my_class.cpp. If I tried to compile with the below code, all, of course, in three separate files, I would get a multiple definition error of my_exception.

Please note, if I move the entire definition and declaration of my_exception into my_class.cpp, everything compiles fine and works correctly. Why is this, and how should I write this so that I could put the definition of the exception into the .h file? Or should I even put an error class definition into a .h file?

main.cpp:

#include my_class.h
int main(){
    my_class m;
    /* stuff */
}

my_class.h:

#ifndef MY_CLASS_H
#define MY_CLASS_H

#include <iostream>  //irrelevant for this
#include <exception>
using namespace std;

//taken from http://ift.tt/1jdQ39R
class my_exception : public exception{
    virtual const char* what() throw() { return "message";}
} me_err;

class my_class{
    my_class() };
};

#endif // MY_CLASS_H

my_class.cpp:

#include my_class.h
my_class::my_class(){ 
    throw me_err; 
}




Class in ASP.NET Partial Class in App_Code

I created a class for connection and using with register.aspx without any problem. When i try to move codes from register.aspx.cs to regpartial.cs then i get an conflict error: "connection conn = new connection();"

I would like to move codes register.aspx.cs to mypartial.cs. I think it will be better but i'm not sure how can i solve conflict problem.

Register.aspx.cs (final)

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using test.App_Code;


namespace test
{   
    public partial class register: System.Web.UI.Page
    {
        private void Page_Load(object sender, EventArgs e)
        {

        }

Connection.cs (final try)

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace test.App_Code
{
    public class connection
    {

        public SqlConnection connect()
        {
            SqlConnection conn= new SqlConnection("Data Source=******;Initial Catalog=****;Integrated Security=False;User Id=****;Password=*****;MultipleActiveResultSets=True");
            baglanti.Open();
            return (conn);
        }
}

regpartial.cs (Final try)

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace test.App_Code.partials
{
    connection conn = new connection();
    public partial class regpartial : register
    {

    }
}




Can I pass attributes to an instance of selenium webdriver

I'm trying to create a class that can create wedriver instances and add proxies to them, this is only a dumbed down version of what i've already written, but I'm also trying to make a method that will wait for an element to be visible before clicking it, the attribute is isn't getting passed to the driver object.

I get the following traceback.

class Driver():

    proxy = ['213.136.79.124:80']

    def get_proxied_driver(self):
        for proxy in self.proxies:
            try:
                myproxy = self.proxies.pop()
                if self.test_proxy(myproxy):
                    proxy = Proxy({
                                'proxyType': ProxyType.MANUAL,
                                'httpProxy': myproxy,
                                'ftpProxy': myproxy,
                                'sslProxy': myproxy,
                                'noProxy': '' # set this value as desired
                                  })
                    driver     = webdriver.Firefox(proxy=proxy)
                    is_working = raw_input('Is your proxy working? [y/n]: ')
                    if is_working == 'y' or is_working == 'Y':
                        return driver
                    if is_working == 'n' or is_working == 'N':
                        driver.quit()
                        continue
                    if not is_working == 'y' or is_working == 'Y' or is_working == 'n' or is_working == 'N':
                        print 'Invallid'
            except:
                continue

    def click_elem(self, elem_type, elem):
        element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.elem_type, elem)))

        if elem_type == CLASS_NAME:
            find = find_element_by_class_name
        elem = driver.find(elem).click()

driver = Driver()
driver = driver.get_proxies_n_driver()
driver.get("http://ift.tt/1nB33z3")
driver.click_elem(CLASS_NAME, "submit_button")




No visible @interface for meal declares the selector calculatetip

i'm trying to call a method from another class and can't quite seem to get it to work. Trying suggestions from other threads, but even after seems to just throw the same error. Language is objective C Source for Meal.h

@interface Meal : NSObject
- (float)CalculateTip:(float)MealCost secondValue:(float)SelectedValue;

@end

Source for Meal.m

#import "Meal.h"

@implementation Meal
- (float) CalculateTip:(float)MealCost secondValue:(float)SelectedValue
{
float finalVal = 0;
float tipval = 0;
if (SelectedValue == 0)
{
    tipval = .1;
}
else if (SelectedValue == 1)
{
    tipval = .15;
}
else if (SelectedValue == 2)
{
    tipval = .2;
}
finalVal = MealCost*tipval;
return finalVal;
}

@end

Import statements in ViewController class

    #import "Meal.h";

Calling the method Meal *meal = [[Meal alloc] init];

This is where the error occurs "No visible @interface for meal declares the selector calculatetip"

float finalFloat =  [meal CalculateTip:MealCostFloat:select]; 




XCode Swift: Adding new class variables to existing Class

I am looking for a way to extend an existing class with new variables without creating my own new class, e.g. add an NSIndexPath to UITableViewCell to be able to access row or section without the use of tags.

I known i can add new functions with an extension

extension UITableViewCell {
    // i can do this
    func myExtendedFunction() {}
    // but this is not possible
    var indexPath:NSIndexPath
}

Is there a way to do this, or do i always have to build my own classes?




Error: uninitialized reference member in 'struct' [duplicate]

This question already has an answer here:

I am trying to compile a C++ code available at http://ift.tt/1nquXxc.

A particular file include/global_reg.h has a class named threaded_alignment which has a private member variable data defined as

  // This stuff really doesn't need to be in a struct, it
  // could just be member data.  But this leads to a marginally
  // less verbose initialization using memcpy.
  struct align_scan_struct {
    const opts_t &opts;
    const vector<char *> &mesh_names;
    const vector<corr_vector> &corrs;
    const vector<point> &targets;
    const vector<bool> &use_points;
    const vector<float> &confidence;
    TriMesh *points_mesh;
    const vector<TriMesh::Face> &all_faces;
    threaded_alignment *ta;
  } data;

and a constructor defined as

  threaded_alignment(const opts_t &opts, const vector<char *> &mesh_names,
                     const vector<corr_vector> &corrs, const vector<point> &targets,
                     const vector<bool> &use_points, const vector<float> &confidence,
                     TriMesh *points_mesh,  const vector<TriMesh::Face> &all_faces)
                      : counter(0) {
    pthread_mutex_init(&counter_mutex, NULL);
    pthread_mutex_init(&mesh_mutex, NULL);

    align_scan_struct d = { opts, mesh_names, corrs, targets, use_points,
             confidence, points_mesh, all_faces, this };
    memcpy(&data, &d, sizeof(align_scan_struct));

    threads.resize(opts.nthreads);
    for (int i = 0; i < opts.nthreads; i++) {
      pthread_create(&threads[i], NULL, alignment_thread, (void *) &data);
    }
  }

However, on compiling on GCC 5.1.0 on mingw32 gcc I get the following errors in this constructor:

include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|237|note: 'const opts_t& threaded_alignment::align_scan_struct::opts' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|238|note: 'const std::vector<char*>& threaded_alignment::align_scan_struct::mesh_names' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|239|note: 'const std::vector<std::vector<corr_t> >& threaded_alignment::align_scan_struct::corrs' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|240|note: 'const std::vector<trimesh::Vec<3u, float> >& threaded_alignment::align_scan_struct::targets' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|241|note: 'const std::vector<bool>& threaded_alignment::align_scan_struct::use_points' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|242|note: 'const std::vector<float>& threaded_alignment::align_scan_struct::confidence' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|244|note: 'const std::vector<trimesh::TriMesh::Face>& threaded_alignment::align_scan_struct::all_faces' should be initialized|

Any help or hint on the errors will be highly appreciated.