samedi 31 décembre 2016

Collections of integers

I have a bunch of integers and I want to add them to a particular group. Lets say each group won't exceed 100 integers. I want to be able to add a new group, if necessary (max 100 groups). I want to be able to access all elements in any groups by index (i.e group[2].element[3]). I should also be able to sort the elements in every group. For storing the numbers, I can make a variable

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Element
{
    private int[] values;  
    public int[] Values    
    {
        get
        {
            return values;
        }
        set
        {
            values = value;
        }
    }
}

class Solution {
    static void Main(String[] args) {    
        Elements[] groups = new Elements[100];
        groups[0].SetValue([5,6,7], 0); // fill group 0 elements with values [5,6,7]
        int v = groups[0].GetValue(2);  // read value 6
    }
}

For groups, perhaps I could make a list of arrays. I suppose I can make a class called Elements, and for each new group, I instantiate a new element. Could you please help fix this code?




Python - Unusual IndentationError involving a class

When trying to develop a class, I get this error.

from __future__ import division
import numpy as np
import scipy as sp
import itertools as it
from scipy.integrate import quad
import astropy.cosmology
from astropy import units as u

class NFW:  

File "/Users/alexandres/Illustris/Scripts/NFWprofile2.py", line 10

               ^
IndentationError: expected an indented block
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "/Users/alexandres/Illustris/Scripts/NFWprofile2.py"]
[dir: /Users/alexandres/Illustris/Scripts]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

How on earth is this an indentation error?

regardless if i define the class as NFW() or NFW(object), this is occurring.

This is being edited through Sublime 3




How do I properly call setters on a return constant referenced class member

My problem is that I am trying to access none constant setter of a constant reference of a class member resulting in the error(C2662). If I make the values being set mutable, and the setter constant, then I am okay, but I have read that you should avoid doing this, but can't find another way to do it.

Definition of vector2D:

class vector2D {
    int _x;
    int _y;
public:
    vector2D() :
    _x(0),
    _y(0) {};

    // Getters
    int xGet() { return _x;};
    int yGet() { return _y;};

    // Setters
    void xSet(int x) {
        if (x > 100) {
            _x = 100;
            return;

        } else if (x < 0) {
            _x = 0;
            return;

        } else {
            _x = x;
            return;
        }
    };

    void ySet(int y) {
        if (y > 100) {
            _y = 100;
            return;

        } else if (y < 0) {
            _y = 0;
            return;

        } else {
            _y = y;
            return;
        }
    };
};

Definition of npc :

class npc {
    vector2D _position;
public:
    npc () {};
    const vector2D& positionGet() const{
        return _position;
    };
};

main.cpp :

main () { 
    vector2D myPos;
    myPos.xSet(2);    //Okay

    npc myGuy;
    myGuy.positionGet().xSet(2);    //C2662

    return 0;
}

What I have tried :

I tried to make xSet/ySet constant functions, but that then gives me an error(expresion must be a modifiable lvalue), which makes sense. I have been reading articles about this, but the correct way has never really been clear.

I tried making x/y mutable, and then that would let me make the setter functions constant, which does get rid of the error, but then I read that a lot of people say not to use mutable, which what other way should this be done?

I also tried to make the returned value of '_position' none constant, but isn't that not safe to do???

Note : I am also trying hard to make my questions better, and so please message/leave comment on how I could have asked this better :D




Why I am having error:

This question already has an answer here:

import java.util.regex.*;
import java.util.*;

abstract class Checking
{
    abstract void EmailChecking(String email);
    abstract void PhoneChecking(String phno);
    abstract void NameChecking(String name);
    abstract void PasswordChecking(String pass); 
}
class AllTypesChecking
{
    public static void main(String[] args)
    {
        int choice;
        char ans;
        String getid=new String();
        String phone=new String();
        String nam=new String();
        String pasd=new String();
        Scanner s=new Scanner(System.in);
        do
        {
            System.out.println("\n\n1 to Check Phone Number");
            System.out.println("2 to Check Email ID");
            System.out.println("3 to Check Password");
            System.out.println("4 to Check Name");
            System.out.print("\nEnter Option : ");
            choice=s.nextInt();
            switch(choice)
            {
                case 1:
                    System.out.print("\nPhone Number : ");
                    phone=s.next();
                    break;
                case 2:
                    System.out.print("\nEmail ID : ");
                    getid=s.next();
                    break;
                case 3:
                    System.out.print("\nPassword : ");
                    pasd=s.next();
                    break;
                case 4:
                    System.out.print("\nName : ");
                    nam=s.nextLine();
                    break;
                default :
                    System.out.println("Invalid Entry!!!");
            }
            switch(choice)
            {
                case 1:
                    Checking ch=new Checking()
                    {
                        void PhoneChecking(String phno)
                        {
                                if(Pattern.matches("^[0-9]{10,10}$",phno))
                                {
                                    System.out.println("\n"+phno+" is Valid Phone Phone Number");
                                }
                                else
                                {
                                    System.out.println("\n"+phno+" is Invalid Phone Phone Number");
                                }
                        }
                    };
                    ch.PhoneChecking(phone);
                    break;
                case 2:
                    Checking ch2=new Checking()
                    {
                        void EmailChecking(String email)
                        {
                            if(Pattern.matches("^[a-zA-Z0-9]+(!#$%&'*+-/=?^_`{|}~)+@[a-zA-Z]+.[a-zA-Z]{0,30}$",email))
                            {
                                System.out.println("\n"+email+" is Valid Email ID"); 
                            }
                            else
                            {
                                System.out.println("\n"+email+" is  Invalid Email ID");
                            }
                        }
                    };
                    ch2.EmailChecking(getid);
                    break;
                case 3:
                    Checking ch3=new Checking()
                    {
                        void PasswordChecking(String pass)
                        {
                            if(Pattern.matches("^[a-zA-Z0-9]+[!#$%&'*+-/=?^_`{|}~]$",pass))
                            {
                                System.out.println("\n"+pass+" is  Valid Password");
                            }
                            else
                            {
                                System.out.println("\n"+pass+" is Invalid Password");
                            }
                        }
                    };
                    ch3.PasswordChecking(pasd);
                    break;
                case 4:
                    Checking ch4=new Checking()
                    {
                        void NameChecking(String name)
                        {
                            if(Pattern.matches("^[a-zA-Z]{0,20}",name))
                            {
                                System.out.println("\n"+name+" is Valid Name");
                            }
                            else
                            {
                                System.out.println("\n"+name+" is Invalid Name");
                            }
                        }
                    };
                    ch4.NameChecking(nam);
                    break;
                default :
                    System.out.println("Invalid Entry!!!");

            }
            System.out.println("\n\nDo You Want to do Checking again ?");
            System.out.println("Enter Oprion : ");
            ans=s.next().charAt(0);
        }while(ans=='Y'||ans=='y'); 
    }
}

Please Help me to solve this error I am new to all this concepts of java.

C:\Users\Sam_000\Desktop>javac AllTypesChecking.java
AllTypesChecking.java:55: error: <anonymous AllTypesChecking$1> is not abstract
and does not override abstract method PasswordChecking(String) in Checking
                                        {
                                        ^
AllTypesChecking.java:72: error: <anonymous AllTypesChecking$2> is not abstract
and does not override abstract method PasswordChecking(String) in Checking
                                        {
                                        ^
AllTypesChecking.java:89: error: <anonymous AllTypesChecking$3> is not abstract
and does not override abstract method NameChecking(String) in Checking
                                        {
                                        ^
AllTypesChecking.java:106: error: <anonymous AllTypesChecking$4> is not abstract
 and does not override abstract method PasswordChecking(String) in Checking
                                        {
                                        ^
4 errors




Why can't I define a `delete` method?

I'm attempting to make a library with methods in a class that represent HTTP methods, such as GET, POST, and DELETE. I'm trying to do this with an abstract class that defines methods for each of these HTTP methods.

The problem comes in when I define a simple delete method for this class. This is what said method looks like:

/**
 * A generic responder to a DELETE request.
 */
Response delete(Request request)
{
    return new Response("Method not supported");
}

This should work fine in theory, but on compilation I get the error, no identifier for declarator Response.

Why is this error occurring? Removing the delete method makes the program compile, but having that one method in there makes it not compile at all.

Any help would be appreciated, thank you!




Having trouble with macros in C++

I'm trying to write a C++ macro to define a bunch of classes using a template and a color name like so:

#define DECLARE_SET_ELEMENT(color) class ##color##SetElement : public SetElement { public: ##color##SetElement(std::string name); int getValue() override; };

so that I can use it like:

DECLARE_SET_ELEMENT(Blue) // -> class BlueSetElement ...
DECLARE_SET_ELEMENT(Red)  // -> class RedSetElement ...
...

But the macro definition does not seem to be working correctly. How should it be in order for it to work as I am intending?




Reflection in Java

I am new to reflection in java and I thought that since I provided the arguments to the EnemyShip constructor that will be preserved. And After changing just the name of the ship, only that will be changed. However, I got wentworth is travelling at 0 instead of what I expected : wentworth is travelling at at 3242

Last line of code should in reflectionTest be main focus

I have 2 classes:

package com.reflectionapi.demo;

import java.lang.reflect.*;

public class reflectionTest {

public static void main(String[] args) {


    Class shipClass = EnemyShip.class;
    int shipMod= shipClass.getModifiers();
    String shipModStat="";

    switch(shipMod){
    case Modifier.PUBLIC: shipModStat="Public";
            break;
    case Modifier.PRIVATE: shipModStat="Private";

    }


    System.out.println(shipClass.getName()+" "+shipModStat
            );//prints class of ship




    Method[] methods = shipClass.getMethods();


    Class[] parameters;


    for (Method method: methods){
        String methodName = method.getName();
        parameters= method.getParameterTypes();// assign method parameters to paramters array

        if (methodName.startsWith("get"))
                    System.out.println(methodName+" is a Getter Method "+
                            "it returns "+ method.getReturnType()+"\n");    

        else 
            if (methodName.startsWith("set"))

                    for (Class param: parameters){
                System.out.println(methodName+" is a Setter Method and "+
                "takes parameters "+ param.getName()+"\n");
                    }

        }

    Class superClass = shipClass.getSuperclass();
    System.out.println(shipClass+" is a subclass of "+ superClass.getName()+"\n");


    Constructor[] constructors = shipClass.getConstructors();   
    //Constructor constructors = shipClass.getConstructor(new Class[] {EnemyShip.class} ); not iterable

    Object constructorItem =null;

    for (Constructor construct: constructors){
        System.out.println(construct);

    }


    try {
         constructorItem= shipClass.getConstructor(String.class , int.class ).newInstance("XT-1800", 5000);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
            | NoSuchMethodException | SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    EnemyShip ship = new EnemyShip("Carl", 3242);

    ship.setName("Wentworth");
    //ship.setSpeed(1230420);

    System.out.println(ship.getName()+
            " is travelling at "+
            ship.getSpeed());



    }

}

Second class

 package com.reflectionapi.demo;

 public class EnemyShip {



public EnemyShip (String s, int m){// s= name m= speed
    /*
    name =s;
    speed=m;
 try later */

    System.out.println(s+
             " is travelling at :"+ m);
}

public EnemyShip (String s, int m, double j){// s= name m= speed

    System.out.println(s+
             " is travelling at :"+ m);
}


public String getName (){   
    return name ;
}

public void setName(String s){

    name =s;
}

public void setSpeed(int s){

    speed =s;
}

public int getSpeed(){
    return speed;
}

    private String name =""; 
    private int speed=0;

}




Update class instance in Python console

I'm building some code, so it's convenient to have it live in the Python console for easy experimentation. 'cept that classes have state and I'm not sure what the best way is to update an existing instance of a class such that I can continue toying with it.

Say, for instance, I have this class:

class Cheese:
  def __init__(self):
    self.brand    = 'Kraft'
    self.quantity = 4

And I create an instance:

c = Cheese()

Now, I modify the class like so:

class Cheese:
  def __init__(self):
    self.brand    = 'Kraft'
    self.quantity = 4
  def munch():
    self.quantity = self.quantity-1
  #Possibly many other new methods or changes to existing methods
  #Possibly incrementally updating things many times

How can I update c such that it becomes an instance of the updated class while retaining its previous internal state? At the moment, I have to re-run a lot of somewhat expensive code.




Public Function

I get an error on my class [31-Dec-2016 20:05:53 Africa/Casablanca] PHP Parse error: syntax error, unexpected 'Private' (T_PRIVATE), expecting identifier (T_STRING) in /home/tspcco/public_html/PCNEW/user/model/addon/main.php on line 5 Haven't add anything to the class yet

    <?php

  class Modeladdonmain extends Hand {

  public function Private() {

  }

  public function Poke() {

  }

  public function Whisper() {

  }

  }
 ?>




Python: why does this local list variable in class method retain its value?

I searched around and found this article which gives me a lead on why this is happening -- it seems I've just come across a more complex and subtle case of it. But it's those subtleties that have me bewildered and looking for a clearer explanation. (I doubt it matters, but just in case: I'm using Python 2.7.x on Windows 7.)

The starting point is this bit of code, which I distilled from a much larger and more complex app where I first encountered the problem.

class MyClass():
    def printStuff(self,myList=[1,2,3],myInt=4):
        print '--------------------------------'
        print 'myList at start: '+str(myList)
        print 'myInt  at start: '+str(myInt)
        doNotCare = myList.pop()
        myInt = myInt - 1
        print 'myList at end:   '+str(myList)
        print 'myInt  at end:   '+str(myInt)

testMC = MyClass()
testMC.printStuff()
testMC.printStuff()
testMC.printStuff()

...which generates the following output:

--------------------------------
myList at start: [1, 2, 3]
myInt  at start: 4
myList at end:   [1, 2]
myInt  at end:   3
--------------------------------
myList at start: [1, 2]
myInt  at start: 4
myList at end:   [1]
myInt  at end:   3
--------------------------------
myList at start: [1]
myInt  at start: 4
myList at end:   []
myInt  at end:   3

Now, based on the various write-ups on how defaulted parameters are handled in functions, it seems like myInt should exhibit the same behavior as myList, i.e. it should decrement to 3, 2, 1. But obviously it doesn't.

The puzzle gets more complex if I modify the doNotCare = myList.pop() line, instead using a slice to update the list:

class MyClass():
    def printStuff(self,myList=[1,2,3],myInt=4):
        print '--------------------------------'
        print 'myList at start: '+str(myList)
        print 'myInt  at start: '+str(myInt)
        myList = myList[:-1]
        myInt = myInt - 1
        print 'myList at end:   '+str(myList)
        print 'myInt  at end:   '+str(myInt)

testMC = MyClass()
testMC.printStuff()
testMC.printStuff()
testMC.printStuff()

...which somehow defeats that unexpected retained value, yielding the output:

--------------------------------
myList at start: [1, 2, 3]
myInt  at start: 4
myList at end:   [1, 2]
myInt  at end:   3
--------------------------------
myList at start: [1, 2, 3]
myInt  at start: 4
myList at end:   [1, 2]
myInt  at end:   3
--------------------------------
myList at start: [1, 2, 3]
myInt  at start: 4
myList at end:   [1, 2]
myInt  at end:   3

So I suppose the first question would be, is this in fact just a more complex and subtle case of the default-parameter behavior described in the reference? If it is, then why doesn't the behavior apply to myInt -- or even to myList, when I manipulate it with slicing instead of pop?




Python class - attribute inheritance

I am trying to implement a project using class inheritance, where parent class is:

class radio:

    def __init__(self, artist=None, track=None, genre=None, mood=None):

        self.artist = artist 
        self.track = track
        self.genre = genre
        self.mood = mood

then I create methods for each attribute (non working examples):

    def seed_artist(self):
        results = api.search(q=self.artist, type='artist')
        return results 

    def seed_track(self):
        results = api.search(q=self.track, type='track')
        return results

    def seed_genre(self):
        results = api.search(q=self.genre, type='genre')
        return results

    def seed_mood(self):
        results = api.search(q=self.track, type='mood')
        return results

the user is going to pick a seed above (only one), being it either artist, track, genre or mood, and that's why I initialize all arguments with None, leaving the argument value to be inserted at inheritance level.

the inherited class is:

class playlist(radio):

    def __init__(self,user):
        radio.__init__(self, artist, track, genre, mood)

lets say user inputs at command line a track seed, and my script ends up starting with a global variable:

track = 'karma police'

this way, all other attributes (artist, genre and mood) remain None.

when I create an instance, say:

jeff = playlist('Jeff Smith')

It will throw an error saying that genre, artist and moodare not defined, and I would have to inherit only trackattribute, like so:

radio.__init__(self, track)

I know I could start the script with global variables defined:

track = None
genre = None
artist = None
mood = None

and this would allow me to have:

radio.__init__(self, artist, track, genre, mood)

but this seems to me rather redundant...

Is there a workaround this, with no need for initial values of global variables set to None, keeping all the code within class scope definitions?




Change to a class attr also applied to the other attr in a seperate class [duplicate]

This question already has an answer here:

I have defined two classes (lets say class A and class B) and I have assigned the value (a list) of an attribute in class A to an attribute in class B. Now when I modify that value in class B, the value in class A is also modified. The code looks like this:

class A:
    def __init__(self):
        self.attr_a = [x for x in range(10)]

class B:
    def __init__(self):
        self.attr_b = a_object.attr_a
        self.attr_b[5] = 2

a_object = A()
b_object = B()
print(a_object.attr_a)
print(b_object.attr_b)

I would expect that this would print two diffrent lists but instead it prints:

[0, 1, 2, 3, 4, 2, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 2, 6, 7, 8, 9]

I changed the

self.attr_b = a_object.attr.a

to

self.attr_b = a_object.attr.a[:]

So it would return a copy of the list. It worked. However when I work with lists within lists the problem arises one more time. The code:

class A:
    def __init__(self):
        self.attr_a = [[x, x**2] for x in range(5)]

class B:
    def __init__(self):
        self.attr_b = a_object.attr_a
        self.attr_b[3][1] = 3


a_object = A()
b_object = B()
print(a_object.attr_a)
print(b_object.attr_b)

It prints:

[[0, 0], [1, 1], [2, 4], [3, 3], [4, 16]]
[[0, 0], [1, 1], [2, 4], [3, 3], [4, 16]]

Now to fix this I thought I would create a method to append a copy of the each sublist:

def appendit(self):
    attr_b = []
    for i in a_object.attr_a:
        attr_b.append(i[:])
    return attr_b

That fixed the problem as expected but I still don't know what the problem was in the first place. I am pretty much a newbie in programming so I would like to understand the real mechanics going on.




Convert class to double

I have a custom class that combines a value with the derivatives in the following way:

>> Params.betah
value =
   0.978961862737933
Size: (1,2)
   1.000000000000000   1.000000000000000  -0.001934834924361

When I use this variable in a specific part of my code I get a'Conversion to double from deriv1 is not possible.' (deriv1 is the name of the class).

Therefore in this part of the code I would be interested in having the variable with only the value. For some reason, I cannot figure out how to do this.

The class is defined like this:

% Matlab file to implement class "deriv1",
% forward mode of automatic differentation, first derivatives, possibly ssparse
% Usage:
% 1) x = deriv1(val): val is column vector
%    x is vector of independent variables, Jacobian is the identity
% 2) x = deriv1(val,iIndep): val is column vector, iIndep index of variables
%    x is vector where iIndep are independent variables, rest are constants
% 3) x = deriv1(val,0,np): val any matrix, np positive integer
%    x has zero Jacobian, assuming np independent variables
% 4) x = deriv1(val,[],J): val any matrix, J the Jacobian
%    x is matrix of values with Jacobian J
function s= deriv1(val,iIndep,deriv)
  nSparse = 1;
  if(nargin==0 | nargin>3)
    error('usage: deriv1(Value,Derivative)');
  end
  s.v=val; 
  if nargin==3
    if(isscalar(iIndep) && iIndep==0)
      np = deriv;
      if(np>=nSparse)
    s.d = ssparse(prod(size(val)),np);
      else
    s.d = zeros(prod(size(val)),np);
      end
    else
      s.d=ssparse(deriv);
    end
  else % only one argument
    m=size(val);
    if(length(m)~=2 | m(2)~=1)
      error('single argument to deriv1 must be column vector (independent variables)');
    end
    if(nargin==1)
      iIndep = 1:m(1);
    end
    nIndep = length(iIndep);
    if(nIndep>=nSparse | issparse(val))
      s.d=ssparse(iIndep,1:nIndep,ones(nIndep,1),m(1),nIndep);
    else
      s.d=zeros(m(1),nIndep);
      s.d(iIndep,:)=eye(nIndep);
    end
  end

  s=class(s,'deriv1');

But if I try to access Params.betah.v i get this error:

Error using deriv1/subsref (line 11)
wrong index type for_ deriv1

Where the code looks like this:

function xout=subsref(x,s)
  nx = size(x);
  switch s.type
    case '()'
      % xout.v = x.v(s.subs{:});
      xout.v = subsref(x.v,s);
      Is = reshape(1:prod(size(x.v)),size(x.v));
      ii = subsref(Is,s);
      xout.d = x.d(ii(:),:);
    otherwise
      error('wrong index type for_ deriv1');
  end

  if(nnz(xout.d)==0)
    xout = xout.v;
  else
      xout = class(xout,'deriv1');

  end

I am fairly new to Matlab and have not written this part of the code myself. Can anybody tell me how I create a variable that only contains the value from the original variable that contains both value and derivative?




Attempt to invoke virtual method on a null object reference issue

I am developing an App which uses the following code. It is generating an unexpected error as "Attempt to invoke virtual method on a null object reference". I do not understand the reason why this is happening. The error is thrown as the line containing t[i].setTestname(getData(exams[i]));. Could someone please point out what I am doing wrong. Could use some help over here.

void processTestPerformance()
{
    String exams[],rawdata;
    rawdata=data.toString();
    int numberoftests=getNumbers("tabletitle03",rawdata);
    Tests[] t= new Tests[numberoftests];
    exams=new String[numberoftests];
    rawdata=rawdata+"tabletitle03";
    for(int i=0;i<numberoftests;i++)
    {
        int j=rawdata.indexOf("tabletitle03");
        int k=(rawdata.substring(j+1)).indexOf("tabletitle03");
        exams[i]=rawdata.substring(j,j+1+k);
        t[i].setTestname(getData(exams[i]));
        rawdata=rawdata.substring(k);
    }
}

The code for class Tests is as follows:

public class Tests
{
    public int numberofsubjects;
    public String testname;
    public Subject s[];
    public void setS(Subject[] s)
    {
        this.s = s;
    }
    public void setNumberofsubjects(int numberofsubjects)
    {
        this.numberofsubjects = numberofsubjects;
        s=new Subject[numberofsubjects];
    }
    public void setTestname(String testname)
    {
        this.testname = testname;
    }
}

Thanks in Advance.




How can I call Connection Class from another class?

how can I call DbConnect class and use it for another class like FormElement class ?

main.class.php

class DBCONNECT
{
   public $dbConnection;

   public function __construct($dbHost, $dbUsername, $dbPassword, $dbName){

       $this->dbConnection = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

       if($this->dbConnection->error){
           trigger_error("Sorry couldn't connect to database :("); // problem connect to database
       }else{
           return true; // connection successfully
       }
    }
}

and my another class was

element.class.php

class FormElement
{
   public function getCmbPovinsi(){
    $userSqlQuery   = "SELECT id,provinsi FROM aud_provinsi ORDER BY provinsi";
    $userSys        = $this->dbConnection->query($userSqlQuery) or die($this->dbConnection->error);

    if ($userSys) {
        /* checking for available users */
        if($userSys->num_rows > 0){
            echo'<div class="col_one_fourth">
                    <label for="provinsi">Provinsi<small>*</small></label>
                        <select id="provinsi" name="provinsi" class="sm-form-control required">
                            <option value="">-- Pilih Provinsi --</option>';

                    while ($userResult = $userSys->fetch_assoc()) {
                        echo '<option value="'.$userResult['id'].'">'.$userResult['provinsi'].'</option>';          
                    }
                    echo '</select>
                 </div>';
        }else{
            echo "Error Handling!!";
        }
    }else{
        echo "invalid query : ".$this->dbConnection->error."<br>";
        echo "whole query : ".$userQuery ."<br>";
    }               
  }
}

and how this code can work properly ?




vendredi 30 décembre 2016

Excel Vba Throwing While Setting Object Property Even When Using Set - Error 91

It is my first experience with class modules, and while I'm working, Error 91 occured when I'm setting the property. I searched for it, and learnt that I should use set. However, even while I'm using set, it throws "Object Variable Not Set" . And the last thing is, I'm not talking about commented lines.

My Module:

    Option Explicit
Public Static Sub VeriGetir()

    Sheets("Veri Sayfası").Activate

    Dim römorklar() As Römork
    Dim index As Integer
    index = -1
    Dim i

    For i = 2 To 100
        If Not Cells(1, i) = "" And Not Cells(12, i) = "" Then
            Dim vRömork As Römork
            Set vRömork = New Römork
            vRömork.ÜrünKodu = Cells(1, i)
            Dim öz As MetinÖzellik
            Set öz = New MetinÖzellik
            öz.Ayarla "asd", 12
            Set vRömork.DingilSayısı = öz
            'Set vRömork.Ton = Cells(3, i)
            'Set vRömork.En = Cells(4, i)
            'Set vRömork.Boy = Cells(5, i)
            'Set vRömork.KüçükYük = Cells(6, i)
            'Set vRömork.İlave1 = Cells(7, i)
            'Set vRömork.İlave2 = Cells(8, i)
            'Set vRömork.ÖnAks = Cells(9, i)
            'Set vRömork.ArkaAks = Cells(10, i)
            'Set vRömork.Jant = Cells(11, i)
            'Set vRömork.Lastik = Cells(12, i)
            'index = index + 1
            'ReDim römorklar(index)
            'römorklar(index) = vRömork
        End If
    Next i


End Sub
Public Function MetinOluştur(isim As String, fiyat As Double) As MetinÖzellik

    Dim özellik As MetinÖzellik
    Set özellik = New MetinÖzellik

    özellik.Ayarla isim, fiyat

    Set MetinOluştur = özellik

End Function
Public Static Function SayıOluştur(değer As Double, fiyat As Double) As SayıÖzellik

    Dim sayı_özellik As SayıÖzellik
    Set sayı_özellik = New SayıÖzellik

    sayı_özellik.Ayarla değer, fiyat

    Set SayıOluştur = sayı_özellik

End Function

Römork Class Module:

    Option Explicit
    Private pÜrünKodu As String
    Private pDingilSayısı As MetinÖzellik
    Private pTon As MetinÖzellik
    Private pEn As SayıÖzellik
    Private pBoy As SayıÖzellik
    Private pKüçükYük As SayıÖzellik
    Private pİlave1 As SayıÖzellik
    Private pİlave2 As SayıÖzellik
    Private pÖnAks As MetinÖzellik
    Private pArkaAks As MetinÖzellik
    Private pJant As MetinÖzellik
    Private pLastik As MetinÖzellik
    Public Property Get ÜrünKodu() As String
        ÜrünKodu = pÜrünKodu
    End Property
    Public Property Let ÜrünKodu(Value As String)
        pÜrünKodu = Value
    End Property
    Public Property Get DingilSayısı() As MetinÖzellik
        DingilSayısı = pDingilSayısı
    End Property
    Public Property Let DingilSayısı(Value As MetinÖzellik)
        pDingilSayısı = Value
    End Property
    Public Property Get Ton() As MetinÖzellik
        Ton = pTon
    End Property
    Public Property Let Ton(Value As MetinÖzellik)
        pTon = Value
    End Property
    Public Property Get ÖnAks() As MetinÖzellik
        ÖnAks = pÖnAks
    End Property
    Public Property Let ÖnAks(Value As MetinÖzellik)
        pÖnAks = Value
    End Property
    Public Property Get ArkaAks() As MetinÖzellik
        ArkaAks = pArkaAks
    End Property
    Public Property Let ArkaAks(Value As MetinÖzellik)
        pArkaAks = Value
    End Property
    Public Property Get Jant() As MetinÖzellik
        Jant = pJant
    End Property
    Public Property Let Jant(Value As MetinÖzellik)
        pJant = Value
    End Property
    Public Property Get Lastik() As MetinÖzellik
        Lastik = pLastik
    End Property
    Public Property Let Lastik(Value As MetinÖzellik)
        pLastik = Value
    End Property
    ' En  Boy K.Yük   İlave1  İlave2
    Public Property Get En() As SayıÖzellik
        En = pEn
    End Property
    Public Property Let En(Value As SayıÖzellik)
        pEn = Value
    End Property
    Public Property Get Boy() As SayıÖzellik
        Boy = pBoy
    End Property
    Public Property Let Boy(Value As SayıÖzellik)
        pBoy = Value
    End Property
    Public Property Get KüçükYük() As SayıÖzellik
        KüçükYük = pKüçükYük
    End Property
    Public Property Let KüçükYük(Value As SayıÖzellik)
        pKüçükYük = Value
    End Property
    Public Property Get İlave1() As SayıÖzellik
        İlave = pİlave1
    End Property
    Public Property Let İlave1(Value As SayıÖzellik)
        pİlave1 = Value
    End Property
    Public Property Get İlave2() As SayıÖzellik
        İlave2 = pİlave2
    End Property
    Public Property Let İlave2(Value As SayıÖzellik)
        İlave2 = Value
    End Property

MetinÖzellik Class Module:

Option Explicit
Private pİsim As String
Private pFiyat As Double
Public Property Get İsim() As String
    İsim = pİsim
End Property
Public Property Let İsim(Value As String)
    pİsim = Value
End Property
Public Property Get fiyat() As Double
    fiyat = pFiyat
End Property
Public Property Let fiyat(Value As Double)
    pFiyat = Value
End Property
Public Sub Ayarla(pİsim As String, pFiyat As Double)
    Me.İsim = pİsim
    Me.fiyat = pFiyat
End Sub

SayıÖzellik Class Module:

Option Explicit
Private pDeğer As Double
Private pFiyat As Double
Public Property Get değer() As String
    değer = pDeğer
End Property
Public Property Let değer(Value As String)
    pDeğer = Value
End Property
Private pFiyat As Double
Public Property Get fiyat() As Double
    fiyat = pFiyat
End Property
Public Property Let fiyat(Value As Double)
    pFiyat = Value
End Property
Public Sub Ayarla(pDeğer As Double, pFiyat As Double)
    Me.değer = pDeğer
    Me.fiyat = pFiyat
End Sub
Public Static Function Oluştur(değer As Double, fiyat As Double) As SayıÖzellik

    Dim sayı_özellik As SayıÖzellik
    Set sayı_özellik = New SayıÖzellik

    sayı_özellik.Ayarla değer, fiyat

    Set Oluştur = sayı_özellik

End Function




Object not inheretinting functions from super class?

So I keep getting the

error: " AttributeError: 'Dog' object has no attribute '_Dog__name'"

The thing is print(spot.get_name()) works fine. Also when I tried spot.multiple_sounds() that fails similarly. I think the issue is when I try to call object attributes from the super class in functions in object definition. I can't understand why though. I'm doing all this from a tutorial and the code is identical to his. I think it may be because he's using python2.x and I'm using spyder python3.x but I have no idea. Any help is greatly appreciated.

import random
import os
import sys

class Animal:
    __name = ""
    __height = 0
    __weight = 0
    __sound = 0

    def __init__(self,name,height,weight,sound):
        self.__name = name
        self.__height = height
        self.__weight = weight
        self.__sound = sound

    def set_name(self, name):
        self.__name = name

    def get_name(self):
        return(self.__name)

    def set_height(self, height):
        self.__height = height

    def get_height(self):
        return(self.__height)

    def set_weight(self, weight):
        self.__weight = weight

    def get_weight(self):
        return(self.__weight)

    def set_sound(self, sound):
        self.__sound = sound

    def get_sound(self):
        return(self.__sound)

    def get_type(self):
        print("animal")

    def toString(self):
        return("{} is {} cm tall and {} kilograms and says {}".format(self.__name,
                                                                        self.__height,
                                                                        self.__weight,
                                                                        self.__sound))


cat = Animal('Whiskers', 33, 10,'Meow')

print(cat.toString())

class Dog(Animal):

    __owner = ""

    def __init__(self, name, height, weight, sound, owner):
        self.__owner = owner
        super().__init__(name, height, weight, sound)

    def set_owner(self,owner):
        self.__owner = owner

    def get_owner(self):
        return self.__owner

    def get_type(self):
        print("Dog")

    def toString(self):
        return "{} is {} cm tall and {} kilograms says {} and his owner is {}".format(self.__name, self.__height, self.__weight, self.__sound, self.__owner)

    def multiple_sounds(self, how_many=None):
        if how_many is None:
            print(self.getsound())
        else:
            print(self.getsound()*how_many)

spot = Dog("Spot", 53, 27, "Ruff", "Some Guy")
print(spot.get_name())
print(spot.toString())




Issue with undefined "reference to [Class]::[Function]" (C++)

First off, I apologize for the beginner question... I've spent practically all day scrumming the web(StackOverflow / Reddit) for the answer my issue.

Whenever I run main.cpp, it returns the errors:

[path] undefined reference to `Map::Map(int, int, int)'
[path] undefined reference to `Map::show()'

I've read something about adding map.cpp to the source files, but when I add it in "CMakeLists.txt" in "set(SOURCE_FILES...", it makes all the values in map.cpp "undeclared" and not available.

I'm using the latest version of CLion (I was too frustrated while using Visual Studio).

Project: Test

main.cpp

#include <iostream>
#include <string>
#include <array>
//Customs
#include "map.h"

int main() {

    Map world = Map(8,8);
    world.show();

return 0;
}

map.h

#ifndef MAP_H
#define MAP_H

class Map {

public:
    Map(int width, int length, int seed = 6435);
    void m_generate(int seed);
    void show();
};

#endif

map.cpp

#include "map.h"
#include <isotream>
Map::Map(int width, int length, int seed = 6435) {
    //Assigns Values
    m_max_x = width;
    m_max_y = length;
    m_size = width * length;
    m_generate(seed);
}

void Map::m_generate(int seed) {
    //Map init
    int m_map[m_max_x][m_max_y];
    m_map.resize(m_max_x);
    for (int i = 0; i < m_max_x; ++i)
        m_map[i].resize(m_max_y);

    //Generates map
    std::mt19937 mt(seed);
    std::uniform_int_distribution<int> RANDOM_NUM(0, 2);
    for (int x = 0; x < m_max_x; ++x) {
        for (int y = 0; y < m_max_y; ++y) {
            m_map[x][y] = RANDOM_NUM(mt);
        }
    }
}

void Map::show() {
    for (int x = 0; x < m_max_x; ++x) {
        for (int y = 0; y < m_max_y; ++y) {
            if(Map::m_map[x][y]==1)
                std::cout << "X";
            else
                std::cout << " ";
        }
        std::cout << "\n";
    }
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.6)
project(Test)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(Test ${SOURCE_FILES})




Having trouble calling a method from another class

I'm a beginner to C#. I'm trying to call a method from another class but having an error message saying "Method is inaccessible due to it's protection level".

Here's my Calculate class

namespace Cal
{
    class Calculate
    {
        static void GetBiggest()
        {
            int num1, num2, num3;
            Console.WriteLine("First number");
            num1 = int.Parse(Console.ReadLine());
            Console.WriteLine("Second number");
            num2 = int.Parse(Console.ReadLine());
            Console.WriteLine("Third number");
            num3 = int.Parse(Console.ReadLine());

            if (num1 > num2 & num1 > num3)
            {
                Console.WriteLine("Biggest number is " + num1);
                Console.ReadLine();
            }

            else if (num2 > num1 & num2 > num3)
            {
                Console.WriteLine("Biggest number is " + num2);
                Console.ReadLine();
            }

            else
            {
                Console.WriteLine("Biggest number is " + num3);
                Console.ReadLine();
            }
        }
    }
}

And here's my main class where i'm trying to call the Calculate class

namespace Cal
{
    class Program
    {
        static void Main(string[] args)
        {
            Calculate a = new Calculate();
            a.GetBiggest();

        }
    }
}




Calling a function within a function within a class

So there's this website that posts something I want to buy at a random time of day for a limited amount of time and I want to write something to send a message to my phone when a new url is posted to that webpage.

I planned on doing this by counting the number of links on the page (since it's rarely updated) and checking it every 5 minutes against what it was 5 minutes before that, then 5 minutes later check it against what it was 10 minutes before that, 5 minutes later check what it was 15 minutes before that... and if it's greater than what it originally was, send a message to my phone. Here's what I have so far:

class url_alert:
    url = '' 

    def link_count(self):
        notifyy=True
        while notifyy:
            try:
                page = urllib.request.urlopen(self.url)
                soup = bs(page, "lxml") 
                links=[]
                for link in soup.findAll('a'):
                    links.append(link.get('href'))
                    notifyy=False
                print('found', int(len(links)), 'links')
            except:
                print('Stop making so many requests')
                time.sleep(60*5)
        return len(links)


    def __phone(self):
        self= phone
    phone.message = client.messages.create(to="", from_="",body="") 
        print('notified')


    def looper(self):
        first_count = self.link_count()
        print('outside while')

        noty = True
        while noty:
            try:
                second_count = self.link_count()
                print('before compare')

                if second_count == first_count:
                    self.phone()
                    noty = False
            except:
                print('not quite...')
                time.sleep(60)


alert = url_alert()
alert.looper()

As a test, I decided to set the if statement that determines whether or not to send a message as equal but the loop kept on running. Am I calling the functions within the looper function the right way?




Preventing deconstruction of anonymous variable defined in macro until end of scope

I'm trying to leverage class constructors and deconstructors to represent and format scope in my log files via the RAII idiom. Using a single #define, it prints "{" and increases the global indentation level so that the next logged line is printed at that indentation level.

LogScopeRAII is supposed to print the "}" and decrease the global indentation level naturally as it goes out of scope at the end of Foo(). However, the behavior I am seeing is that LogScopeRAII is deconstructed immediately after being constructed.

Hypothesis: I think the problem is that LogScopeRAII is being created on the RHS of the assignment (and thus anonymously?) and is being destroyed at the end of the line, but I'm not sure what to do about. I thought LOG_ANONYMOUS_VARIABLE in VSCOPE_F would have done the trick and caused it to stick around, but it isn't.

Question: How can I stop LogScopeRAII from being deconstructed until the calling function goes out of scope?

/* Header */
LogScopeRAII::LogScopeRAII(Verbosity verbosity, const char* file, unsigned line, const char* format, ...)
{
    // ...
    // print "{" and then increase an indentation global var
}

LogScopeRAII::~LogScopeRAII()
{
    // ...
    // print "}" and then decrease the indentation global var
}

#define LOG_ANOMYMOUS_VARIABLE(str) LOG_CONCAT(str, __LINE__)

#define VSCOPE_F(verbosity, ...) \
LogScopeRAII LOG_ANONYMOUS_VARIABLE(raii) = \
((verbosity) > verb_cutoff() ? LogScopeRAII() : LogScopeRAII{verbosity, __FILE__, __LINE__, __VA_ARGS__}

#define SCOPE_F(verbosity_name, ...) VSCOPE_F(Verbosity_ ## verbosity_name, __VA_ARGS__)

#define SCOPE_FUNCTION(INFO) SCOPE_F(verbosity_name, __FUNCTION__)

/* Implementation */
void Foo()
{
    SCOPE_FUNCTION(INFO) // print "{" and increase indentation
    for (size_t i = 0; i < 3; ++i)
    {
        // do work
        LOG(INFO, "Work logged");
    }
    // print "}" and decrease indentation
}

Desired output:

{ Foo()
    "Work Logged" // Note indentation
} 0.23 s: Foo()




How to correctly hide helpers classes inside a class in C#

I am having problems understanding how to correctly encapsulate my class. It is (or should be) an inmutable class.

If I use all my

namespace MyApp
{

    [Flags]
    public enum OctaveGroups
    {
        None = 0,
        oneOctave = 1
    }

    class Frequencies
    {
        // HelperClass
        public class Frequency
        {
            public string Name { get;  set; }
            public OctaveGroups Octave { get; set; }
        }

        public readonly static List<Frequency> All = new List<Frequency>
        {
        #region Complete Frequencies Data

                new Frequency { Name = "63", Hz = 63,
                    Octave = OctaveGroups.oneOctave | OctaveGroups.oneThird,
                    },

                new Frequency { Name = "80", Hz = 80,
                    Octave = OctaveGroups.oneThird,
                    }
           // And so on..
                //..

        #endregion
        };


        public readonly List<Frequency> OneOctave = All.Where(f => f.Octave.HasFlag(OctaveGroups.oneOctave)).ToList();

        public readonly List<Frequency> None = All.Where(f => f.Octave.HasFlag(OctaveGroups.None)).ToList();

    }
}

If I make my Frequency class protected I get this error:

Inconsistent accessibility: field type 'List' is less accesible than field 'Frequencies.All'

I get the same error if I make class Frequency and List<Frequency> Allprotected and try to make a method that returns a List<Frequency> like:

public List<Frequency> GetAll()
    {
        return All.Where(f => f.Octave.HasFlag(OctaveGroups.OneOctave)).ToList();
    } 

How will be the correct way to expose just .All .OneOctave and .None fields while keeping them read only?




Python object interaction

So, programming in Python 3, I've got a program with a problem whose essence I've distilled in this (non)functional piece of code:

class One:
    def __init__(self):
        self.var1 = 1

    def change(self):
        two.var2 = 5

class Two:
    def __init__(self):
        one = One()
        self.var2 = 2
        one.change()

two = Two()

The IDLE interpreter throws:

Traceback (most recent call last): File "C:/-", line 15, in two = Two() File "C:/-", line 12, in init one.change() File "C:/-", line 6, in change two.var2 = 5 NameError: name 'two' is not defined

Apparently, doing this instead:

class One:
    def __init__(self):
        self.var1 = 1

    def change(self):
        two.var2 = 5

class Two:
    def __init__(self):
        self.var2 = 2
        one.change()

one = One()
two = Two()

...doesn't help, as it gives me the exact same type of error. I really don't understand why this is happening... or how to structure it differently. I think the last time I had a problem like this I avoided it by nesting classes (rather messy and worked for only one level of nesting, as far as I can remember), but I'd really like to know how to make these two objects communicate with each other properly.




use of undefined 'Player' and 'player' uses undefined 'Player' errors

    class Skeleton {
    public:
        void attack(Player player) {
            if (canAttackSkeleton()) {
                player.setHealth(player.getHealth() - _attackDamage); //C2027 and C2228 for setHealth() and getHealth()
                return;
            }
        }
        void getAttacked(Player player) {
            _health -= player.getAttackDamage(); //C2027 and C2228 for getAttackDamage()
        }


    private:
        float _attackDamage = 100.0f;
    };

    class Player{
    public:
        void attack(Skeleton skeleton) {
            if (canAttackPlayer()) {
                skeleton.setHealth(skeleton.getHealth() - _attackDamage);
                return;
            }
        }
        void getAttacked(Skeleton skeleton) {
            _health -= skeleton.getAttackDamage();
        }


    private:
        float _attackDamage = 100.0f;
    };

This is my code. + the main function

Basically I get " use of undefined 'Player' " with the error code C2027 and .setHealth, .getHealth and .getAttackDamage "must have class/struct/union" with the error code C2228.

This is the first time I've heard of classes in c++ and it is very confusing for me. (I'm a beginner).




What happens when int.class is called? [duplicate]

This question already has an answer here:

If Class object describes a type which may or may not be class and int is not a class why does int.class return int. I mean what happens in the background ?




What is the difference between these two approaches?

class A
{
   int a = 100;
};

and

class A
{
    int a;
public :
   A()
   {
      a = 100;
   }
};

I know that there are two approaches because static variables are initialised outside the class and cant that cant be done inside the class. But what difference does it make if i initialise the variable a ( a normal int ) using the constructor or during the declaration itself.




Python iterating through list of lists of class objects, returns that object is not iterable?

I have an initial class:

class foo:

    def __init__(self, a, b):
        self.a = a
        self.b = b

And another class which uses the foo class:

class bar:

    def __init__(self, foos):
        self.foos = sorted(foos, key=attrgetter('a'))

where foos is a list of foo. I now want to take a list of list of foo, something that looks like

lofoos = [[foo1, foo2, foo3], [foo4, foo5, foo6] ...]

and I want to use the map function to do this:

list(map(lambda foos: bar(foos), lofoos))

But this returns the error: TypeError: iter() returned non-iterator of type 'foo'.
Is there an easy solution to this?




Enum rawvalue as AnyClass

I know you can give enum's the rawvalue of String or Int ect but is there a way to make its type like AnyClass for example

enum Name:AnyClass{
    case classOne = ClassOne
    case classTwo = ClassTwo
}

Where ClassOne and ClassTwo are classes. The error I get is:

Raw type 'AnyClass' is not convertable from any literal

So is there another way to achieve this?




saying class add not have any return value

saying class add not have any return value

using System;
namespace ConsoleApplication1
{
    class method
    {
       public int add(int x, int y)
        {
            int sample=addition(x, y);
            Console.WriteLine("{0}",sample);
        }
        public int addition(int m,int n)
        {
            return (m+n);
        }
    }

    class Program
    {
        public static void Main()
        {
            int c;
            Console.WriteLine("enter two no");
            int a = int.Parse(Console.ReadLine());
            int b = int.Parse(Console.ReadLine());
            method z = new method();
            c = z.add(a,b);

            Console.ReadLine();
        }
    }
}




Xcode - Name of AppDelegate class in new target

When I'm adding a target in my Xcode project, a new AppDelegate class named "AppDelegate" is created. What is best practice about naming these? Keep an AppDelegate class for every target or rename it to AppeDelegate_Target or something else. I've noticed some issues with Xcode when using AppDelegate as name in all targets so I was wondering if there is kind of "best practice" (Interface Builder component uses wrong AppDelegate and a few glitches more)

Thanks!




python __str__ and __repr__ example use in a class [duplicate]

This question already has an answer here:

I see lots of questions on SO about __str__ and __repr__ in python classes (not talking about str() and repr(). And I get that they are somewhat like ToString() in other languages. But I have yet to see a good example of these used in a class.

I see some examples of a class with __str__ overloaded, but no __repr__ overloaded. Then, I see some examples with __repr__ overloaded, but no __str__ overloaded. And in both examples, it just looks like a regular ToString() to me.

So far, what I have learned is that __repr__ is more for developers, and designed to be machine readable, while __str__ is designed to be used by end-users. Also, __repr__ gets called on each individual element in a collection. But I have no idea how it should be used, or how exactly the two functions can be different.

Can someone provide a good example of a class the implements both correctly, with each returning different things? Or should only one be overloaded at a time?




Why I am having error like class is not abstract and does not override abstract method on line 8?

import java.util.*;

abstract class Checking
{
    abstract void Process(String email);
}

class StringChecking extends Checking
{
    public static void main(String[] args)
    {
        String getid=new String();
        Scanner s=new Scanner(System.in);
        System.out.print("\n\nEmail ID : ");
        getid=s.next();
        Checking ch=new Checking()
        {
            void Process(String email)
            {
                int temp1,temp2;
                temp1=email.lastindexOf("@");
                temp2=email.lastindexOf(".");
                if(temp2-temp1==1)
                {
                    System.out.println("\nInvalid Email ID!!!");
                }
                else if(temp2-temp1!=1&&temp2+1=='c'&&temp2+2=='o'&&temp2=='m'&&temp2+1=='C'&&temp2+2=='O'&&temp2+2=='M')
                {
                    System.out.println("\nValid Email ID");
                }
            }
        };
        ch.Process(getid);
    }
}

Please Help Me out in this error.

Cmd:// javac StringChecking.java

StringChecking.java:8: error: StringChecking is not abstract and does not overri de abstract method Process(String) in Checking class StringChecking extends Checking ^ StringChecking.java:21: error: cannot find symbol temp1=email.lastindexOf("@"); ^ symbol: method lastindexOf(String) location: variable email of type String StringChecking.java:22: error: cannot find symbol temp2=email.lastindexOf("."); ^ symbol: method lastindexOf(String) location: variable email of type String 3 errors




Swift - Refer to current class type in a static / class function

I've static functions to instantiate view controllers that look like

class AController: UIViewController {
  static func instantiate() -> AController {
    let storyboard = UIStoryboard(name: "AController", bundle: nil)
    let controller = s.instantiateInitialViewController() as? AController
    return controller!
  }
}

class BController: UIViewController {
  static func instantiate() -> BController {
    let storyboard = UIStoryboard(name: "BController", bundle: nil)
    let controller = storyboard.instantiateInitialViewController() as? BController
    return controller!
  }
}

I've a bunch of them so I'd like to make that cleaner as:

class MYViewController: UIViewController {
  class func instantiate() -> self.type {
    let storyboard = UIStoryboard(name: "\(self.type)", bundle: nil)
    let controller = storyboard.instantiateInitialViewController() as? self.type
    return controller!
  }
}

class AController: MYViewController {
}

class BController: MYViewController {
}

But I don't know of to dynamically refer to the type of the object in a static / class function, and how to have this refer to the subclass when called from a subclass. It's easy to do once an object has been instantiated with type(of: object)




Python Object Oriented Behaviour [duplicate]

This question already has an answer here:

I was reading the Python documentation (http://ift.tt/2ilbtZP) when I came upon this snippet explaining the difference between class variables and instance variables.

class Dog:

    tricks = []             # mistaken use of a class variable

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

    def add_trick(self, trick):
        self.tricks.append(trick)

d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')
d.tricks                # unexpectedly shared by all dogs
['roll over', 'play dead']

I plugged this code in an IDE and tried it out. It behaves as described. However, I don't understand it very well.

When the add_trick method is invoked, how does self.tricks reference Dog.tricks?

Thank you.




TypeScript class decorator that modifies object instance

I'm making a plugin for Aurelia and need a class decorator that

  1. adds attributes to the new object instance, and
  2. calls an external function with the new object as an argument.

I've looked through examples, and so far I've put together ("pseudo-ish" code)

return function addAndCall(target: any): any {
    var original = target;

    var newConstructor = function (...args) {
        original.apply(this, args);
        this.newAttribute = "object instance value";
        ExternalModule.externalFunction(this);
    };

    newConstructor.prototype = Object.create(original.prototype);
    newConstructor.prototype.constructor = original;

    return <any>newConstructor;
}

but

  • I'm not entirely clear on the details here (or what is actually needed), and
  • it might not work properly since I'm getting Aurelia errors when using objects instantiated from classes with this decorator (and I suspect it's my decorator rather than the Aurelia framework that's buggy).

Any help and explanation would be greatly appreciated!




Resize image in QLabel with QPixmap in Qt

Beginner in Qt here.I am trying to add an .png image to QLabel object using QPixmap by adding it as a Resource (.Qrc). The following code Snippet doesn't show the output. I have tried to resize the image(icon) using QPixmap as well.The output is just "ADDRESS ICON" without the image. The code is as follows : .

   #include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QPixmap>
#include <QLabel>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    mylabel = new QLabel();
    font = new QFont("Courier New");
addresspic = new QPixmap(":/new/prefix1/address.png");
    addresspic->scaled(10,10,Qt::KeepAspectRatio, Qt::FastTransformation);
    mylabel->setPixmap(*addresspic);




    mylabel->setPixmap(*addresspic);
   mylabel->setTextFormat(Qt::RichText);
 mylabel->setGeometry(QRect(QPoint(100,100),QSize(150, 150)));
 mylabel->setText("  ADDRESS ICON ");


   font->setItalic(true);
   font->setPixelSize(20);
    mylabel->setFont(*font);

    mylabel->show();
}

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

Any idea why I cant access the image along with the Text label? TIA




Python - how to get this multiple inheritance to work?

I am working on a project involving PyQt5, and I am struggling with managing inheritance between widgets.

I have one QWidget screen that inherits off QtWidgets.QWidget and another class which is generated by QtDesigner. It reads something like this:

class a(QtWidgets.QWidget, Ui_a):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setupUi(self)

        <some attributes>

    <some functions

Here, I inherit off Ui_a, a separate class stored in a generated file, and I can call setupUi (a method of Ui_a) fine.

I now want to create another class b, which also is a QWidget that needs to be displayed. This class b requires the use of some of the functions and attributes from class a. I can easily just copy paste the required stuff in but that is bad practice so I am looking for a more neat solution. If I do the code:

class b(QtWidgets.QWidget, Ui_b, a):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init(self, parent)
        self.setupUi(self)

This then crashes with an error message saying that it cannot create a consistent method resolution order.

My first question is - I know I need to call the init method of class a since a's attributes are created there, but I don't know how.

My second question is - How do I fix this MRO error and succeed in creating the new class b which can use a's attributes and functions?




Python: Define list within a class

i can't find the answer, so i decided to post this question:

i am rewriting my code to make it OO, and i find some difficoulties: `

class Validation():
    def __init__(self, input=path_property, output=validation_output):
        self.input = input
        self.outpu = output
        self.groupList = []
    def __str__(self):
        return 'Input: %s\nOutput: %s\nGroup List: %s' % (self.input, self.outpu, self.groupList)

    def csvExtract(self, d, groupList, n):
        with open(self.input, 'r') as csv_input:
            reader = csv.reader(csv_input, delimiter=',')
            for d in reader:
                self.groupList.append(d[n])
        self.groupList.pop(0)

if __name__ == '__main__':
    validate = Validation()
    validate.csvExtract('col', groupList, 3)
    print(groupList)
    print(validate)

This code simply read csv file, and add elements of third column to a list - this worked fine, when it wasn't put into a class, and a list was defined at the star of the code. Now i get this:

Traceback (most recent call last):
  File "C:/path/validation.py", line 34, in <module>
    validate.csvExtract('col', groupList, 3)
NameError: name 'groupList' is not defined

I'm also planning to make arguments of csvExtract (d - indicates column, and n - indicate number of column) a poart of def __init__. I have tried few different appraoch, could you help me with that?




Why is the destructor not destryoing the class's member variables? [duplicate]

This question already has an answer here:

Isn't the destructor of the MyPointer class suppose to destroy the ptr object and all of its members? it seems like the destructor ran but for i don't understand why the 'number' of ptr still exists after the destructor ran.

#include <iostream>

using namespace std;

int* integerptr;

class MyPointer{
public:
    MyPointer(int arg);
    ~MyPointer();
    int number;
};

MyPointer::MyPointer(int arg):
    number(arg)
    {}

MyPointer::~MyPointer(){
    cout<<"Object Destroyed"<<endl;
}

int create_obj(){
    MyPointer ptr(3);
    integerptr=&ptr.number;
    cout<<integerptr<<"-->"<<*integerptr<<endl;
    return 0;
}
int main()
{
    create_obj();
    cout<<integerptr<<"-->"<<*integerptr<<endl;
    return 0;
}

Here is the output from the terminal:

0x61fefc-->3
Object Destroyed
0x61fefc-->3




jeudi 29 décembre 2016

I need to know if there is a c++ class for text documents

I have read the books; taken a c++ class for c programmers and written working c++ programs but knowing how long it took to become a good c programmer I am still a C++ newbie. I am trying to find out if there is already a c++ class for text documents. I would imagine it would be called PAGE consisting of N arrays of char lines M long. It may allow a page number at the bottom. The document would consist of L pages probably linked together as a linked list. There possibly would be a table of contents class etc. I tried searching on google but keep getting answers like "how to document c++ programs" or "file I/O in c++". C++ is so big I don't know where to start.




Ruby string comparison

I am developing an OOD based code where I am creating a class say myclass which defines a method gettype which returns different classes based on string comparison

def gettype(c)          

    if c.to_s.eql?"d"
        return D.new        
    end

    if c.to_s.eql?"m"
        return M.new            
    end

    if c.to_s.eql?"k"
        return K.new            
    end

    return nil              
end

Now I am creating an object of the class and using a csv file to read string and do processing line by line

my = myclass.new
    CSV.foreach(@filein, { encoding: "UTF-8", headers: true}) do |row|              
         @ct = (row[3].to_s.sub("[-+.^:,'']","")).strip
        #checking for what's being outputted 
            puts @ct say it gives 'k'for one run
            puts @ct.class gives String

Now when I am calling the method my.gettype(@ct) in one loop of the CSV loop its giving Nil class, I tested my.gettype('k') and it returned class type equal K

Please help me out with the debugging, where I am going wrong? Why my string comparison is not succeeding, I tested slice and chomp....yet nothing, its giving Nil class when using variable and then converting it to string using to_s:(




Python - class attributes, methods and parameters

I am starting to study class in python, and am trying to get my head around the concepts of attributes, methods and parameters in OOP.

I am working with 3 examples:


example 1

   class Clock(object):
        def __init__(self, time):
        self.time = time
        def print_time(self):
        time = '6:30'
        print self.time

with:

clock = Clock('5:30')
clock.print_time()

It prints 5:30


example 2

class Clock(object):
    def __init__(self, time):
    self.time = time
    def print_time(self, time):
    print time

with:

clock = Clock('5:30')
clock.print_time('10:30')

It prints 10:30.


example 3

  class Clock(object):
        def __init__(self, time):
        self.time = time
        def print_time(self):
        print self.time

finally, with:

boston_clock = Clock('5:30')
paris_clock = boston_clock
paris_clock.time = '10:30'
boston_clock.print_time()

It prints 10:30

could please someone explain me how attributes, methods and parameters are being bound to objects in these examples?




Class Objects to Represent Relational Data

I'm working on a project to gather data from an external system and bring it into our internal system. Most of our current system uses older technologies (classic ASP), and the project I'm working on requires some newer technology so I'm using VB.Net so I don't have much of an existing .Net foundation to build on.

I have some pretty simple custom classes that I created for this purpose (ex. a Supplier class, Location class, and Product class). These classes were made to temporarily store data from the external system but in a structure that better fits our data structure. Consequently, they are pretty minimal and have only what's needed (ex. they aren't full object representations of each table with all columns).

For the simple independent entities as mentioned above, this isn't a problem. However, where I'm running into problems is when I start trying to relate these independent entities. To accomplish this, I've been using additional classes for each class that inherit KeyedCollection. This keeps data access quick and efficient (ex. I can find things directly by key values without having to iterate through entire collections). For example, my Supplier class has a corresponding Products property of type ProductCollection (that inherits KeyedCollection). This way, Suppliers(150).Products(300) would refer to a supplier with a primary key of 150 and a product with a primary key of 300.

My first problem is this: I want one "copy" of the product with a primary key of 300, and everything else to reference that "copy". This way, when I match up the primary key of the external data with the primary key of our internal data, I can update the Product object once and any/all references will reflect that update.

My next problem is this: with some of the more complicated relations I'm getting to, I'm running into issues with not having the primary key of the link table's record. I need to have Suppliers(150).Locations(33).Products(300) to represent supplier 150 can go to location 33 to get product 300. In the database, this would mean there's a record in a Supplier table with a primary key of 150, and a record in the SupplierLocation table linking supplier 150 to location 33 (note this table has its own primary key, which is not available with the classes/structure I currently have in place - but let's say it's primary key is 1050), and a record in the SupplierLocationProduct table linking SupplierLocation 1050 to product 300 (again, this table has it's own primary key that is not currently known).

What is the best way to accomplish the different things I need, given the scenario? I've looked at ORMs (ex. Entity Framework) but that seems like overkill for the couple of simple classes I need (however maybe doing this all manually is really what's overkill).

Just to recap, I want one "copy" of each independent entity (Supplier, Location, Product), and anything using these entities would simply be a reference back to the original "copy". I also need the primary keys of link table records available. Performance is also an important factor here, but so is maintainability. I don't want to be wasteful (ex. using List.Contains() when I already have primary keys available) but at the same time, I'm not interested in a one-time savings of 100 milliseconds if it means writing my own core functionality (creating hashkeys, testing equality, etc.)




Pygame creating multiple objects instead of moving only one

I'm trying to move a single image around the screen in Pygame using methods controlled by the keyboard, but it appears to be creating duplicates in those positions instead of moving the original image. Why is this happening, given that the image is created before entering the main loop?

Here is my code:

import pygame, sys
from pygame.locals import *
pygame.init()

FPS = 30
fpsClock = pygame.time.Clock()



DISPLAYSURF = pygame.display.set_mode((600, 500), 0, 32)
pygame.display.set_caption('Animation')

posx = 10
posy = 10

class Hero():
    def __init__(self):
        self.x = posx
        self.y = posy

    def appearance(self):
        return pygame.image.load('C:\\Users\\admin\\Desktop\\right.png')

    def move_right(self):
        self.x += 25
        return self.x

    def move_left(self):
        self.x -= 25
        return self.x

    def move_up(self):
        self.y -= 25
        return self.y

    def move_down(self):
        self.y += 25
        return self.y

new_hero = Hero() #create a Hero
item = new_hero.appearance() #create one reference 



while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:

             if event.key == pygame.K_LEFT:
                posx = new_hero.move_left()

             elif event.key == pygame.K_RIGHT:
                posx = new_hero.move_right()

             elif event.key == pygame.K_UP:
                posy = new_hero.move_up()

             elif event.key == pygame.K_DOWN:
                posy = new_hero.move_down()

    DISPLAYSURF.blit(item, (posx, posy)) 



    pygame.display.update()
    fpsClock.tick(FPS)




class mutating data of other class

I have two classes called Data and A. class A is mainly a collection of functions that manipulate data in Data. Now I need a way for A to access all the data in Data. I know two ways of doing so.

  1. I can pass a reference of Data to A but then I always have to write the prefix "Data." which I think is really annoying and there is no ambiguity anyway.

  2. I can make A a superclass of Data. This is what I did so far but I don't really like it, because Data is not really a subset of A(as for example in class Square and class Rectangle), A is just a bunch of functions that mutate Data.

So my question is: Is there another way for A to access the data in Data that would be more suitable?




Class object creation in C++

I have a basic C++ question which I really should know the answer to.

Say we have some class A with constructor A(int a). What is the difference between:

A test_obj(4);

and

A test_obj = A(4);

?

I generally use the latter syntax, but after looking up something unrelated in my trusty C++ primer I realized that they generally use the former. The difference between these two is often discussed in the context of built-in types (e.g. int a(6) vs int a = 6), and my understanding is that in this case they are equivalent.

However, in the case of user-defined classes, are the two approaches to defining an object equivalent? Or is the latter option first default constructing test_obj, and then using the copy constructor of A to assign the return value of A(4) to test_obj? If it's this second possibility, I imagine there could be some performance differences between the two approaches for large classes.

I'm sure this question is answered somewhere on the internet, even here, but I couldn't search for it effectively without finding questions asking the difference between the first option and using new, which is unrelated.




Confused on the locations of class declaration and implementation in c++

I have not been able to find the specific answer to this -- I do know that .h files contain class declarations and .cpp files hold the implementation.

I am confused as to how this is done without repetition.

If I have a class Animal it might be called in several areas of the program. So it would seem I would have to re-write the implementation several times (which no doubt means I am misunderstood).

It seems a bit goofy to include a .h declaration and .cpp implentation with every use of the given class (evidence I am misunderstanding something as well).

Where have I gone wrong in the subject of separating declaration and implementation?

I've been doing PHP and Python all of this time, so it might be prior habits confusing me.




C++/STL public iterators for deeply nested private data

Consider the below class definition featuring deeply nested private data.

template <typename T, typename U, typename V>
class NestedData {
private:
  typedef std::vector<V> L3;
  typedef std::map<U, L3> L2;
  typedef std::map<T, L2> L1;
  L1 inner_data;
};

Suppose we wish to add a public interface to iterate over each of the three levels. That is, we want to allow the client to build three nested loops that iterate over each value of type V, knowing the associated values of types U and T. We could add the below methods:

L1::const_iterator begin() const { return inner_data.begin(); }
L1::const_iterator end() const { return inner_data.end(); }

In this case, the results from the iterator would be pairs, with the right side being referenced to type L2. Although the reference is const, it exposes the full API of the std::map type, which is underable for a public interface. A cleaner solution would offer only a wrapper to makes it possible to iterate over L2. However, I have not seen any standard idioms for this kind of encapsulation of STL containers, and even the best case, implementation of a solution seems to create a high degree of code bloat.

What would be a common solution to this issue that plays well with general C++ conventions?




Python returning from class

class Customer:  #at this part ı defined the class for the customers in the file

def __init__(self, Name, Surname, Age, Balance):

    self.name = Name;
    self.sname = Surname;
    self.age = Age;
    self.balance = Balance;

def __str__(self):

    return("Hello, "+str(self.name)+" "+str(self.sname)+" You have "+ str(self.balance)+" dollars in your account.");

hello you can see my class above

my aim is to ask users name and surname and get the str part in the class im getting informations about customers from csv file.

ans = input("name")
ans2 = input("surname")


a=Customer(ans,ans2)
print (a)

with this part i tried to do part that ı explained above but ı couldt make the code work.




Clearing a group in python

Is there anyway to delete all the contents of a group of sprites in python such as

spriteList = pygame.sprite.Group()




How can I return sentiment value from Tweepy class and Pass it to Giphy API

I'm using the tweepy API and want to return the data found and pass it to a simple Giphy API function.

class TweetStreamListener(StreamListener):
     # on success
    def on_data(self, data):
     # decode json
        dict_data = json.loads(data)
     # pass tweet into TextBlob
        tweet = TextBlob(dict_data["text"])
     # output sentiment polarity
        print (tweet.sentiment.polarity)
     # determine if sentiment is positive, negative, or neutral
        if tweet.sentiment.polarity < 0:
            sentiment = "negative"
        elif tweet.sentiment.polarity == 0:
            sentiment = "neutral"
        else:
            sentiment = "positive"
    # output sentiment
        print (sentiment)
        return(sentiment)

The sentiment value above is what I want to return from the class and pass to the GIPHY API Functions

# Giphy API Functions
def setup():
   url = api + apiKey + query
   print("Getting data with query 'sentiment'")
   json.loads(url, my_callback)
def my_callback(data):
  print("Data recieved!")
  print(data.data[0].images.original.url)

I was thinking of creating a new file for the giphy functions but can I add them to this one?

NOTE: I thought the following line would return the sentiment value

    query = "&q=" + str(TweetStreamListener.on_data)
    print(query)

NOTE: Instead I was given this,"&q=function TweetStreamListener.on_data at 0x1065c3268"




using NaiveBayesClassifier in Swift 3

I try to teach my app basic language skills. After some research I found out that using the NaiveBayesClassifier is probably the best way to do that.

My Question now is how I can refactor the code in a way that the NaiveBayesClassifier will categorize text on its own and later respond with the category.

For instance if the user says:

"Turn my car on"

the AI should come up with something like:

category: 'car on'

and respond

"Turning the car on"

This is the code momentarily // Train the classifier with some ham examples. classifier.trainWithText("nom nom ham", category: "ham") classifier.trainWithText("make sure to get the ham", category: "ham") classifier.trainWithText("please put the eggs in the fridge", category: "ham")

// Train the classifier with some spam examples.
classifier.trainWithText("spammy spam spam", category: "spam")
classifier.trainWithText("what does the fox say?", category: "spam")
classifier.trainWithText("and fish go blub", category: "spam")

// Classify some new text. Is it ham or spam?
let firstExample = "use the eggs in the fridge."
let secondExample = "what does the fish say?"

print("\(firstExample) => \(classifier.classify(firstExample))")
print("\(secondExample) => \(classifier.classify(secondExample))")


let filteredMessage = classifier.classify(msg)

print(filteredMessage!)

switch filteredMessage! {
case "ham":
    return "ham"
case "spam":
    return "spam"
default:
    return Error.error.rawValue
}

For some reason the switch statement isn't working properly.

msg represents the users input




TypeError: argument 1 must be pygame.Surface, not method

I'm brand new to pygame, and trying to create a simple program that allows me to move an image around the screen using the keyboard. I'm getting the error in title when trying to get the image on the screen using the appearance method. I have a working version that I wrote without using classes, but would like to understand classes so I can implement them in the future. Would appreciate some guidance as to how to work around this error, thanks.

Here is my code:

import pygame, sys
from pygame.locals import *
pygame.init()

FPS = 30
fpsClock = pygame.time.Clock()



DISPLAYSURF = pygame.display.set_mode((600, 500), 0, 32)
pygame.display.set_caption('Animation')



class Hero():
    def __init__(self):
        posx = 10
        posy = 10


    def appearance():
        return pygame.image.load('C:\\Users\\admin\\Desktop\\right.png')

    def move_right(x):
        posx += 10


    def move_left(x):
        posx -= 10


    def move_up(y):
        posy -= 10


    def move_down(y):
        posy += 10


new_hero = Hero() #create a Hero

while True:

    item = new_hero.appearance
    DISPLAYSURF.blit(item, (posx, posy)) #error
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    fpsClock.tick(FPS)




C++ what does the unary operator used on class mean ? (Class::Class)

I followed the youtube tutorial and i can create basic class but the tutorial doesn't explain how the Class::Class works, I search google but i only know that it is called unary operator and what it does but I dunno what it do with Class, please help me explain about this and thanks very much.

#include <iostream>
#include <string>

//Class
class Mother {

    public:
        void msg();

};

void Mother::msg(){ //This is where i don't undrstand
    std::cout << "Go home early sweetie" << std::endl;
}

class Daughter: public Mother {

    public:
        void getMsg();

};

void Daughter::getMsg(){ //Same as this
    std::cout << "Mom said ";
    msg();
}


//Main
int main() {

    Daughter lucy;
    lucy.getMsg();

    return 0;
}




Unit Test - Null Reference Exc

I get NullReferenceException when I try to test my class and I have no idea why? Exeption is connected to: o1.Products.Add. When I try to delete it, everything is ok.

public class Product
{
    public string Name { get; set; }
    public decimal Value { get; set; }
}

public class Order
{
    public List<Product> Products { get; set; }

    private decimal value { get; set; }
    public decimal Value
    {
        get { return value; }
        set
        {
            if (Products.Count == 0)
                value = 0;
            else
                value = Products.Sum(x => Convert.ToInt32(x));
        }
    }
}

[TestClass]
public class Tests
{
    [TestMethod]
    public void OrderTest()
    {
        //Arrange
        Product p1 = new Product();
        Order o1 = new Order();
        //Act
        p1.Value = 10;
        o1.Products.Add(p1);
        //Assert
        Assert.AreEqual(30, o1.Value);
    }
}




How to add an ImageView to a costum view class in Android Studio?

Basically I've created a costum class which extends View and what it does currently is drawing a horizontal line where the screen is being touched until it's released. What I want to achieve is adding an ImageView in the background, behind the line so that line is drawn in the foreground. Here's the problem as I've got no clue how to add an ImageView to this view despite all the researches.

From my understanding the overriden onDraw function needs to: #1 clear the screen -> #2 draw the image on ImageView -> #3 draw the line on each iteration. I will have to later on implement dynamically image changing on said ImageView if this info helps somehow.

public class RateView extends View{

float touchY = (getHeight() / 2);
boolean isPressed = false;
Paint paint=new Paint();

public RateView(Context context, AttributeSet attrs) {
    super(context);
    this.setBackgroundColor(Color.parseColor("#da5f02"));
    init(null);
}

private void init(AttributeSet attr){
    paint.setColor(Color.GREEN);
    paint.setStrokeWidth(10);
    paint.setAntiAlias(true);
}

@Override
public void onDraw(Canvas canvas)
{
    super.onDraw(canvas);
        if (isPressed){
            canvas.drawLine(5, touchY, (getWidth()-10), touchY,paint);
        }
}

@Override
public boolean onTouchEvent(MotionEvent motionEvent){

    switch (motionEvent.getAction()){
        case MotionEvent.ACTION_DOWN:
            isPressed = true;
            break;
        case MotionEvent.ACTION_MOVE:
            touchY = motionEvent.getY();
            break;
        case MotionEvent.ACTION_UP:
            isPressed = false;
            break;
    }
    invalidate();
    return true;
}}

This is my costum view class. My main class only extends AppCompatActivity and sets contentView to the above view. Thanks a lot for replys in advance!




List of a class c#

namespace ReeksamenJan
{
class Kamp
{
    private string hjemmehold_;
    private string udehold_;
    private string dommer_;
    private string spillested_;
    private int målhjem_;
    private int målUd_;
    private DateTime spilletid_;

    public Kamp(string hjem, string ud, string sted, DateTime tid)
    {
        this.hjemmehold_ = hjem;
        this.udehold_ = ud;
        this.spillested_ = sted;
        this.spilletid_ = tid;

        this.målhjem_ = 0;
        this.målUd_ = 0;
        this.dommer_ = "NN";

    }

    public string getHjemmehold()
    {
        return hjemmehold_;
    }

    public string getUdhold()
    {
        return udehold_;
    }


    public void setDommer(string dommer)
    {
        Console.WriteLine("Dommeren er: {0} " ,this.dommer_ = dommer);
    } 
    public void setResultat(int målhjem, int målUd)
    {
        this.målhjem_ = målhjem;
        this.målUd_ = målUd;
        Console.WriteLine("Vinderen af kampen er: " +vinderAfKamp()); 

    }




    public string vinderAfKamp()
    {
        if(målhjem_ < målUd_ )
        {
            return udehold_;
        }

        else if (målhjem_ > målUd_)
        {
            return hjemmehold_;
        }
           else 

        return " Ingen vinder. Uafgjort";
    }


    public  void udskrivKamp()
    {
        Console.WriteLine("Hjemmeholdet er: " + hjemmehold_ + " , " + " Udeholdet er: " + udehold_ + " , " + "SpilleSted: " + spillested_ + " , " + " Tid: " + spilletid_ );
    }

}
 }





namespace ReeksamenJan
{
class Turnering 
{
    private string liga_;

    public Turnering(string liga)

    {

        this.liga_ = liga;

    }






    List<Kamp> kampen = new List<Kamp>();
    public void addKamp(List<Kamp> k)
    {

          //How??

    }

    public void removeKamp(Kamp remKamp)
    {
        //kampp.Remove(remKamp);
    }


    public  void PrintKampPlan()
    {

        Console.WriteLine("Ligaen: " + liga_ );

    }



}
}




I am stuck with my Tower Defense code when I want to call the round again

Hello I have created a round (when a group of enemies spawn) which I want to call at the end of each round after an action e.g mouse click but when I do this it just does not work, I have been stuck on this issue for so long and I cannot find anything on the internet to help me, this is my code. I want the round to be called again when the user clicks start round on the second round but it does not work.

import pygame

def text():
    font = pygame.font.SysFont("monospace", 14)
    text = font.render("Start Round", True, black)
    textpos = text.get_rect()
    textpos.center = (790,675)
    Background.blit(text, textpos)

def life_text(screen, life, font):
    text = font.render("Lifes %s" % life, True, BLACK)
    text_rect = text.get_rect()
    text_rect.center = (50,20)
    screen.blit(text, text_rect)

def newRound():
    pos = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if 730 < pos[0] < 730+120 and 650 < pos[1] < 800:
        pygame.draw.rect(Background, (150,150,150), (730,650,120,50))
        if click[0] == 1:
            startGame()
    else:
        pygame.draw.rect(Background, (100,100,100), (730,650,120,50))

def startGame():
    global startRound, endRound
    startRound = True
    endRound = False

def life(self):
    global lifes, hit
    if self.rect.x > 960 and self.rect.x < 964:
        lifes = lifes - 1
        hit = hit + 1
    if hit == 6 and lifes > 0:
        endGame()

def endGame():
    global endRound, startRound
    endRound = True
    startRound = False

class RedEnemy(object):

    image1 = pygame.image.load("enemySpriteFullHealth.jpg")
    image2 = pygame.image.load("enemySpriteHalfHealth.jpg")
    image3 = pygame.image.load("enemySpriteDead.jpg")

    def __init__(self, x, y, Background):
        self.Background = Background
        self.Background_rect = Background.get_rect()
        self.rect = self.image1.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.health = 20
        self.dist_x = 2
        self.dist_y = 0

    def update(self):   
        self.rect.x += self.dist_x
        self.rect.y += self.dist_y

    def draw(self, Background):
        Background.blit(self.image1, self.rect)
        life(self)

pygame.init()

red   = (230,  0,  0)
black = (  0,  0,  0)
white = (255,255,255)

width = 960
height = 720

lifes = 30
hit = 0
intro = 1
enemies = []
FPS = 200
startRound = False
endRound = True
test2 = False

clock = pygame.time.Clock()
mapImg = pygame.image.load("mapimage.jpg")
Background = pygame.display.set_mode((width, height))
Background_rect = Background.get_rect()


x = -80
y = 210
for e in range(6):
    x = x - 80
    enemies.append(RedEnemy(x, y, Background))
    print(enemies)

while intro == 1:
    for event in pygame.event.get():
        if event.type == quit:
            pygame.quit()
            sys.exit()

    if endRound == True:
        Background.blit(mapImg, (0,0))
        newRound()
        text()

    if startRound == True:          
        for enemy in enemies:
            enemy.update()
        Background.blit(mapImg, (0,0))
        for enemy in enemies:
            enemy.draw(Background)
    pygame.display.update()
    clock.tick(FPS)




Why do i need to add final keyword before int empAge in 4th line?

import java.util.*;

class Employee
{
    public void evaluateStatus(String empID, int empAge)
    {
        final int age = 40;
        class Rank
        {
            public char getRank (String empID)
            {
                System.out.print("\n\tGetting rank of employee: "+empID);
                if (empAge >= 40 && empAge <= 60)
                    return 'B';
                else if (empAge >= 61)
                    return 'A';
                else
                    return 'C';
            }
        }
        if (empAge >= age)
        {
            Rank objRank = new Rank();
            char rank = objRank.getRank(empID);
            if (rank == 'A' || rank == 'B' || rank == 'C')
            {
                System.out.print("\n\tEmployee rank is: "+ rank);
                System.out.print("\n\tStatus: Eligible for upgrade.");
            }
            else 
            {
                System.out.print("\n\tStatus: not eligible for upgrade.");
            }
        }
        else
        {
            System.out.print("\n\tStatus: not eligible for upgrade.");
        }
    }
    public static void main(String[] args)
    {
        if (args.length == 2)
        {
            Employee objEmp1 = new Employee();
            objEmp1.evaluateStatus(args[0], Integer.parseInt(args[1]));
        }
        else
        {
            System.out.print("\n\tError!");
        }
    }
}

I get the following error:

Y:\student\Desktop\Atif>javac Employee.java

Employee.java:13: error: local variable empAge is accessed from within inner class; needs to be declared final if (empAge >= 40 && empAge <= 60) ^ Employee.java:13: error: local variable empAge is accessed from within inner class; needs to be declared final if (empAge >= 40 && empAge <= 60) ^ Employee.java:15: error: local variable empAge is accessed from within inner class; needs to be declared final else if (empAge >= 61) ^ 3 errors




Port Audio and Libsndfile no data?

Im probably doing something stupid but I am not getting any form of data from libsndfile when I'm using it in a sound system that I'm developing. sf_read_floatf returns greater than zero but looking at the buffer itself it's just zeroed out data. I'm also using libsamplerate but at the moment I have both samplerates of the audio file and port audio the same for testing.

Port Audio Constructor:

PortAudioSystem::PortAudioSystem(double sampleRate, PaDeviceIndex device, void * hostApiSpecificStreamInfo) {
    this->m_masterVol = this->m_musicVol = this->m_sfxVol = 1.0f;
    this->m_deltaTime = 0.0f;
    this->audioStream = nullptr;
    this->_hasPaError = false;

    this->m_sampleRate = sampleRate;

    PaStreamParameters streamParams;
    streamParams.device = device; //set device to use
    streamParams.hostApiSpecificStreamInfo = hostApiSpecificStreamInfo;
    streamParams.sampleFormat = paFloat32; // 32bit float format
    streamParams.suggestedLatency = 0.2; //200 ms ought to satisfy even the worst sound card
    streamParams.channelCount = 2; //number of channels (1: mono, 2: left/right, etc)

    int err = 0;

    err = Pa_OpenStream(
        &this->audioStream,
        0, // no input
        &streamParams,
        sampleRate,
        paFramesPerBufferUnspecified, // let portaudio choose the buffersize
        paNoFlag,/* no special modes (clip off, dither off) */
        PortAudioSystem::paCallbackCommon,
        this
    );

    if (err != paNoError) {
        pushPaError(err, Pa_GetErrorText(err));
        this->audioStream = nullptr;
    }

    int src_err;
    this->m_srcState = src_new(SRC_SINC_FASTEST,2,&src_err); //create a new sample rate converter

    if (this->m_srcState == NULL) {
        //src_error(this->m_srcState);
        this->pushPaError(src_err, src_strerror(src_err));
    }

    this->m_nextPlayID = 0;
}

Port Audio Callback:

int PortAudioSystem::paCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData) {
    this->m_deltaTime = (float)((double)framesPerBuffer / this->m_sampleRate); //get delta time based on sample rate and number of frames per buffer
    if (this->m_playingAudioFiles.size() == 0) return paContinue; //if we dont have any playing audio files, skip.

    AudioFrame::_2 *outFrame = (AudioFrame::_2*)outputBuffer; //convert the port audio buffer to an audio frame buffer.

    //zero out the output buffer.
    for (unsigned long zeroI = 0; zeroI < framesPerBuffer; zeroI++) {
        outFrame[zeroI].left = 0.0f;
        outFrame[zeroI].right = 0.0f;
    }

    //for (PlayingAudioFile playingfile : this->m_playingAudioFiles) playingfile.audioFile->Seek(playingfile.currentFrame); //seek to the current position of the file

    AudioFrame::_2 *framesOut = new AudioFrame::_2[framesPerBuffer]; //create a buffer for frames out.
    //float * fFramesOut = new float[framesPerBuffer * 2]; //create a float buffer for frames out (*2 for left and right channel)

    //prep common data for sample rate conversion.
    SRC_DATA src_data;
    src_data.output_frames = framesPerBuffer; //set output frames to be the max output frames to have.
    src_data.end_of_input = 0; //we are not at the end of the file (change for specific audio file system [function?]).
    src_data.data_out = (float *)framesOut; //set our output frames to be the buffer that we created.

    flow.lock(); //mutex lock
    for (std::pair<long, PlayingAudioFile> entry : this->m_playingAudioFiles){ //for each playing audio file
        if (entry.second.paused) continue; //if the audio file is paused, skip it.

        PlayingAudioFile& playingfile = entry.second;
        playingfile.audioFile->Seek(playingfile.currentFrame); //seek to the current position of the file

        src_data.src_ratio = this->m_sampleRate / playingfile.audioFile->GetSampleRate(); //get the ratio of the sample rate conversion

        if (src_data.src_ratio == 1) { //if we are 1 to 1, dont do sample rate conversion.
            src_data.input_frames_used = src_data.output_frames_gen = (long)playingfile.audioFile->GetFrames(framesPerBuffer, (float *)framesOut);
        } else { //otherwise convert to port audio system's sample rate.
            //adjust the number of frames to read based on ratio.
            long long framesToRead//;
            /*if (fmod((double)framesPerBuffer, src_data.src_ratio) == 0) framesToRead = framesPerBuffer;
            else framesToRead*/ = (framesPerBuffer / ((long long)src_data.src_ratio));// + 2;

            AudioFrame::_2* framesIn = new AudioFrame::_2[framesToRead]; //create a buffer for frames in.
            //float * fFramesIn = new float[framesToRead * 2]; //create a float buffer to read in frames. (*2 for left and right audio channel)
            src_data.data_in = (float *)framesIn; //set the frame in buffer

            src_data.input_frames = (long)playingfile.audioFile->GetFrames(framesToRead, (float *)framesIn); //read the frames; //set the number of frames that were read

            if (src_data.input_frames == 0) {
                delete[] framesIn; //free up the frame in buffer to prevent memory leaks.
                continue; //if we have no data, skip
            }

            src_reset(this->m_srcState); //reset the sample rate conversion state
            int src_err = src_process(this->m_srcState, &src_data); //convert the sample rate

            if (src_err != 0) this->pushPaError(src_err, src_strerror(src_err)); //if we have an error, push it back.

            delete[] framesIn; //free up the frame in buffer
        }

        //AudioFrame::_2* framesOut = (AudioFrame::_2*) fFramesOut; //convert the float buffer to an audio frame buffer for easier access to the channels

        for (unsigned long outFrameI = 0; outFrameI < src_data.output_frames_gen; outFrameI++) { //for each frame (based on how many frames were generated from conversion [possibly under framesPerBuffer])
            //individual frame data;
            AudioFrame::_2 frame = framesOut[outFrameI];

            //adjust volume from master volume
            frame.left *= this->m_masterVol;
            frame.right *= this->m_masterVol;

            //adjust volume
            switch (playingfile.channel) { //based on sound channel
            case eAT_Music: //if we are a music channel
                frame.left *= this->m_musicVol;
                frame.right *= this->m_musicVol;
                break;
            case eAT_SFX: //if we are a sfx channel
                frame.left *= this->m_sfxVol;
                frame.right *= this->m_sfxVol;
                break;
            }

            if (frame.left != 0.0f){ //make sure we have data.
                if (outFrame[outFrameI].left == 0.0f) { //if the output frame has no data
                    outFrame[outFrameI].left = frame.left; //set the audio
                } else { //if the output frame has data
                    outFrame[outFrameI].left += frame.left; //mix the channels
                    outFrame[outFrameI].left /= 2; //ghetto way of making sure we dont clip?
                }
            }
            if (frame.right != 0.0f){ //make sure we have data.
                if (outFrame[outFrameI].right == 0.0f) { //if the output frame has no data
                    outFrame[outFrameI].right = frame.right; //set the audio
                } else { //if the output frame has data 
                    outFrame[outFrameI].right += frame.right; //mix the channels
                    outFrame[outFrameI].right /= 2; //ghetto way of making sure we dont clip?
                }
            }
        }

        playingfile.currentFrame += src_data.input_frames_used; //update the current position time based on how many frames were converted;

        if (playingfile.currentFrame >= playingfile.endFrame && !playingfile.loop) { //if we are finnished playing.
            //mark for removal.
            m_stoppedAudioFiles.push_back(entry.first);
        } else {
            //loop the file
            playingfile.currentFrame = playingfile.startFrame;
        }
    }

    delete [] framesOut;

    //removed stopped audio files.
    while (m_stoppedAudioFiles.size() > 0) {
        this->m_playingAudioFiles.erase(m_stoppedAudioFiles.back());
        m_stoppedAudioFiles.pop_back();
    }

    flow.unlock(); //mutex unlock

    return paContinue; //continue playback
}

AudioFile_Libsnd:

bool AudioFile_Libsnd::Seek(long long position){
    if (!this->_hasSfError) {
        if (sf_seek(this->sndFile, position, SF_SEEK_SET) == -1) {
            int err = sf_error(this->sndFile);
            pushSfError(err, sf_error_number(err));
            return false;
        }
        return true;
    }
    return false;
}

long long AudioFile_Libsnd::GetFrames(long long framesToRead, float buff[]){
    if (this->_hasSfError) return 0;

    long long framesRead = sf_readf_float(this->sndFile, buff, framesToRead);

    return framesRead;
}

bool AudioFile_Libsnd::GetFrame(float* frame) {
    return sf_readf_float(this->sndFile, frame, 1) == 1;
}

AudioFrame::_2:

    struct _2 {
        float left;
        float right;

        _2() : left(0.0f), right(0.0f) {}
    };

PlayingAudioFile:

struct PlayingAudioFile {
    IAudioFile* audioFile;
    long long currentFrame;
    long long startFrame;
    long long endFrame;
    bool loop;
    bool paused;
    EAudioChannel channel;
};

I know the whole code is kind of long but I currently don't know what I'm doing wrong... I believe that I am constructing the buffers correctly but I have tried pure float pointers, both array defined and created with new and that didn't work. I have also tried going frame by frame with a for loop and saving it into a single float but that apparently threw me a stack around variable was corrupt error... Any help would be appreciated.