mercredi 30 novembre 2016

How do I get the correct output for my clock created with java?

My Teacher has given me this assignment. She gave us a ClockTester.java main program and we have to create a public class that declares the objects and methods to use in the Clock Tester. Below is the Tester, and below that is my clock.java code. I am having trouble getting it to format to 00:00:00 like she wants. I have also put her instructions guide.

If someone could please, please help me out here. Also I am getting a stack overflow error when I try to run the program.

Instructions from my teacher

//-------------------------------------------------------------------
//Program:      ClockTester
//Author:       D. Spence
//Date:         April 4, 2014
//Purpose:      Tests the features of the Clock class
//-------------------------------------------------------------------

import java.util.Scanner;

public class ClockTester
{
        public static void main (String[] args)
        {
                //Declare five objects in the Clock class
                Clock c1, c2, c3, c4, c5;

                //Initialize Clock objects using constructors
                c1 = new Clock();
                c2 = new Clock(15);
                c3 = new Clock(8,30);
                c4 = new Clock(12,5,45);

                //Show all four objects
                System.out.println("c1 is " + c1);
                System.out.println("c2 is " + c2);
                System.out.println("c3 is " + c3);
                System.out.println("c4 is " + c4);
                System.out.println();

                //Determine if clock times are past noon
                System.out.println(c1 + " is " + (c1.isPM() ? "after noon" : "at or before noon"));
                System.out.println(c2 + " is " + (c2.isPM() ? "after noon" : "at or before noon"));
                System.out.println(c3 + " is " + (c3.isPM() ? "after noon" : "at or before noon"));
                System.out.println(c4 + " is " + (c4.isPM() ? "after noon" : "at or before noon"));
                System.out.println();

                //Manually set a value
                c1.setTime(14,15,30);
                System.out.println("Changed c1 to " + c3);

                //Test for equality
                System.out.print (c1 + " is ");
                System.out.print ( (c1.equals(c3)) ? "equal" : "NOT equal");
                System.out.println (" to " + c3);
                System.out.println();

                c5 = new Clock(15,0,0);
                System.out.print (c5 + " is ");
                System.out.print ( (c5.equals(c2)) ? "equal" : "NOT equal");
                System.out.print (" to " + c2);
                System.out.println();


                //Demonstrate math operations
                System.out.println ("\n Some Clock Operations:");
                System.out.print (c1 + " + 10 hours is ");
                c1.addHours(10);
                System.out.println (c1);

                System.out.print (c3 + " + 45 minutes is ");
                c3.addMinutes(45);
                System.out.println (c3);

                System.out.print (c4 + " + 90 seconds is ");
                c4.addSeconds(90);
                System.out.println (c4);

                System.out.print (c4 + " + 12:59:55 is ");
                c4.addTime(12,59,55);
                System.out.println (c4);

                //TestBonus();

                System.out.println();
                System.out.println("This concludes the test of the Clock class.");
                System.out.println();

        }

/*
        public static void TestBonus()
        {
                System.out.println("\n ****TESTING BONUS FEATURE****\n");

                Clock c6 = new Clock(2,30,'p');
                System.out.println ("Non-military clock time: " + c6);
                c6.setMilitary (true);
                System.out.println ("Same clock in military: " + c6);
        }
*/

}










//-------------------------------------------------------------------
//Program:      Clock
//Author:       Taylor P.
//Date:         November 30, 2016
//Purpose:      Creates a clock class
//-------------------------------------------------------------------

public class Clock
{
        private int hours;
        private int minutes;
        private int seconds;
        private final int hours_Min = 0;
        private final int hours_Max = 23;
        private final int minutes_Min = 0;
        private final int minutes_Max = 59;
        private final int seconds_Min = 0;
        private final int seconds_Max = 59;


//Constructor sets default time to midnight (00:00:00)
        public Clock ()
        {
                this.hours = 00;
                this.minutes = 00;
                this.seconds = 00;
        }

//Constructor sets hours to input value
        public Clock (int h)
        {
                this.hours = h;
                this.minutes = 00;
                this.seconds = 00;
        }

//Constructor sets hours and minutes to input value
        public Clock (int h, int m)
        {
                this.hours = h;
                this.minutes = m;
                this.seconds = 00;
        }

//Constructor sets hours, minutes, seconds to input value
        public Clock (int h, int m, int s)
        {
                this.hours = h;
                this.minutes = m;
                this.seconds = s;
        }

//-------------------------------
//Method: getHours
//Return: int - hours
//Parameters: none
//Purpose: returns hours
//-------------------------------
        public int getHours()
        {
                return this.hours;
        }

//------------------------------
//Method: getMinutes
//Return: int
//Parameters: none
//Purpose: returns minutes
//------------------------------
        public int getMinutes()
        {
                return this.minutes;
        }

//------------------------------
//Method: getSeconds
//Return: int
//Parameters: none
//Purpose: returns seconds
//------------------------------
        public int getSeconds()
        {
                return this.seconds;
        }


//------------------------------
//Method: isPM
//Return: boolean
//Parameter: none
//Purpose: Determines if the time is past noon
//------------------------------
        public boolean isPM ()
        {
                if (this.hours < 12)
                        return false;
                else
                        return true;
        }

//------------------------------
//Method: setTime
//Return: void
//Parameter: 3 int types - hours, minutes, seconds
//Purpose: set time to (00:00:00) format
//-----------------------------
        public void setTime (int h, int m, int s)
        {
                this.hours = h;
                this.minutes = m;
                this.seconds = s;

        }

//-----------------------------
//Method: addHours
//Return: void
//Parameter: an int type of hours
//Purpose: to add hours together
//-----------------------------
        public void addHours (int h)
        {
                this.hours = this.hours + h;
        }

//-----------------------------
//Method: addMinutes
//Return: void
//Parameter: a int type of minutes
//Purpose: to add minutes together
//-----------------------------
        public void addMinutes (int m)
        {
                this.minutes = this.minutes + m;
        }

//----------------------------
//Method: addMinutes
//Return: void
//Parameter: an int type of seconds
//Purpose: to add seconds together
//----------------------------
        public void addSeconds (int s)
        {
                this.seconds = this.seconds + s;
        }

//-----------------------------
//Method: addTime
//Return: void
//Parameter: three int types of hours, minutes, seconds
//Purpose:
//-----------------------------
        public void addTime (int h, int m, int s)
        {
                this.hours = this.hours + h;
                this.minutes = this.minutes + m;
                this.seconds = this.seconds + s;
        }

//-----------------------------
//Method: equals
//Return:
//Parameter:
//Purpose:
//----------------------------
        public boolean equals (Clock c)
        {
                boolean equiv = c.equals(c);
                return equiv;
        }

//------------------------------
//Method: toString
//Returns:
//Parameters:
//Purpose:
//-----------------------------
        public String toString()
        {
                String string = "";
                                if (this.equals(this.hours) && this.equals(this.minutes) && this.equals (this.seconds))
                                {
                                string = "00:00:00";
                                }
                                else if (this.equals(this.hours))
                                {
                                                string = "00";
                                string = string + ":" + this.minutes + ":" + this.seconds;
                                }
                                else if (this.equals(this.minutes))
                                {
                                                string = "00";
                                                string = this.hours + ":" + string + ":" + this.seconds;
                                        }
                                        else if (this.equals(this.seconds))
                                        {
                                                string = "00";
                                        string = string + ":" + string + ":" + this.seconds;
                                        }
                                        else
                                                string = string + ":" + this.hours + ":" + this.minutes + ":" + this.seconds;
        return string;

        }

}



transferring arraylist from one class to another

I'm trying to move the data from the stations arraylist in the fileReader class into the another arraylist in the CTAStops class. Whenever I test this i get a null pointer exception. What would be the correct way to transfer the data over?

Any help at all would really be appreciated! :)

public class FileReader {

    public static ArrayList<CTAStops> stations = new ArrayList<CTAStops>();



    public static void main(String args[]){


     String csvFile = "CTAStops (2).csv";
     File file = new File(csvFile);

     try{

         Scanner inputStream = new Scanner(file);

         inputStream.nextLine();
         inputStream.nextLine();

         while(inputStream.hasNextLine()){


             String data = inputStream.nextLine();
             String var[] = data.split(",");


            stations.add(new CTAStops(var[0],Double.parseDouble(var[1]),Double.parseDouble(var[2]),var[3],Boolean.parseBoolean(var[4]),Integer.parseInt(var[5]),Integer.parseInt(var[6]),Integer.parseInt(var[7]),Integer.parseInt(var[8]),Integer.parseInt(var[9]),Integer.parseInt(var[10]),Integer.parseInt(var[11]),Integer.parseInt(var[12])));


         }

         inputStream.close();





     }catch (FileNotFoundException e){

         e.printStackTrace();
     }  

 }

    public static ArrayList<CTAStops> getList(){

        return stations;


    }


}   

import java.util.ArrayList;

public class CTAStops extends GeoLocation {

private String StationName; //instance variables that define a ctaStop
private double Latitude;
private double Longitude;
private String Location;
private boolean WheelChair;
private int RedLine;
private int GreenLine;
private int BlueLine;
private int BrownLine;
private int PurpleLine;
private int PinkLine;
private int OrangeLine;
private int YellowLine;

public static ArrayList<CTAStops> stations;

static FileReader read = new FileReader();




public CTAStops(){//default constructor


    StationName = "";
    Latitude = 0;
    Longitude = 0;
    Location = "elevated";
    WheelChair = true;
    RedLine = 0;
    GreenLine = 0;
    BlueLine = 0;
    BrownLine = 0;
    PurpleLine = 0;
    PinkLine = 0;
    OrangeLine = 0;
    YellowLine = 0;
    stations = FileReader.getList();
}

public static void main(String[] arg){
    System.out.println(stations.get(0).getStationName()); //for testing
}

}




Accessing class's properties after using List<>

I'm a beginner in C# and I have a particular question that is related in inheritance and polymorphism based on using classes. The assignment that I'm working is a bank account and that I have to use three classes-one is a base class while the other two are derived classes.

The base class is known as "BankAccount" and the two derived classes are"CheckingAccount" and "SavingsAccount". Furthermore, I have declared objects for "CheckingAccount" and "SavingAccount" and that they are stored in a List class. Afterwards, I'm trying to populate my assignment's GUI's labels accordingly based from the derived class's properties by using a combobox's "SelectedIndexChange" event.

The problem is that somehow the program doesn't check if the list class's stored elements are recognized as a particular type. Below of this contains my code for the program and the classes.

private void comboBoxAccountNumber_SelectedIndexChanged(object sender, EventArgs e) {

        if (selectedBankAccount[0] is CheckingAccount)
        {
            labelOwnerID.Text = selectedBankAccount[0].AccountNumber;
            labelBalance.Text = selectedBankAccount[0].Balance.ToString("c");

        }

        else if (selectedBankAccount[1] is CheckingAccount)
        {
            labelOwnerID.Text = selectedBankAccount[1].AccountNumber;
            labelBalance.Text = selectedBankAccount[1].Balance.ToString("c");

        }


    }

     List<BankAccount> selectedBankAccount = new List<BankAccount> ();

    SavingsAccount savs1_Account;
    CheckingAccount chek1_Account;
    SavingsAccount savs2_Account;
    CheckingAccount chek2_Account;


    private void FormBankOfYourSelf_Load(object sender, EventArgs e)
    {
        savs1_Account = new SavingsAccount("0001", "31-1000", 100m, 0.01);
        chek1_Account = new CheckingAccount("0001", "44-1000", 250m, true);
        savs2_Account = new SavingsAccount("0002", "31-1001", 1000m, 0.0125);
        chek2_Account = new CheckingAccount("0002", "44-1001", 500m, false);  
        selectedBankAccount.Add(chek1_Account);
        selectedBankAccount.Add(chek2_Account);

        comboBoxAccountNumber.Items.Add(selectedBankAccount[0].AccountNumber);
        comboBoxAccountNumber.Items.Add(selectedBankAccount[1].AccountNumber);


    }



 public abstract class BankAccount
{
    // Fields - The data we want to store
    // Naming convention for fields is to use underscore before the name
    protected string  _customerId;
    protected string  _accountNumber;
    protected decimal _balance;

    //Properties - Allow access to fields (Get/Set)
    // Get = read access
    // Set = write (modify) access
    public string CustomerId
    {
        get { return _customerId; }
        set { _customerId = value; }
    }

    public string AccountNumber
    {
        get { return _accountNumber; }
        set { _accountNumber = value; }
    }

    public decimal Balance
    {
        get { return _balance; }
    }

    // Methods - The action or behaviors the class can do
    // almost always, define the constructor and ToString methods
    // Constructor creates (instantiates a new object)
    public BankAccount(string customerId, string accountNumber, decimal initialBalance)
    {
        //fields are set = to the parameters(inputs from the form)
        _customerId = customerId;
        _accountNumber = accountNumber;
        _balance = initialBalance;
   }

    public abstract bool Deposit(decimal depositAmount);
    //{
    //    // If the depositAmount is less then 0 then RETURN false
    //    if (depositAmount <= 0)
    //    {
    //        return false;
    //    }

    //    // Otherwise, complete the deposit and RETURN true
    //    _balance += depositAmount;
    //    return true;
    //}

    public abstract bool Withdraw(decimal withdrawAmount);
    //{
    //    // If the withdrawAmount is greater than the balance or less then or equal to 0 
    //    // then RETURN false (don't allow withdrawal)
    //    if (withdrawAmount > _balance || withdrawAmount <= 0)
    //    {
    //        return false;
    //    }

    //    // Otherwise, complete the withdrawal and return true
    //    _balance -= withdrawAmount;
    //    return true;
    //}


   public class CheckingAccount : BankAccount
   {
    //private string _customerID;
    //private string _accountNum;
    //private decimal _initBalance;
    private bool _overdraftProtection;

    public CheckingAccount(string customerId, string accountNum, decimal initialBalance, bool overDraft)
        :base(customerId, accountNum, initialBalance)
    {
        //_customerID = customerId;
        //_accountNum = accountNum;
        //_initBalance = initialBalance;
        _overdraftProtection = overDraft;
    }

    public bool OverDraftProtection
    {
        get { return _overdraftProtection; }

        set { _overdraftProtection = value; }
    }

    public override bool Deposit(decimal depositAmount)
    {
        if(depositAmount > 0)
        {
            _balance += depositAmount;
            return true;
        }

        else
        {
            return false;
        }
    }

    public override bool Withdraw(decimal withdrawAmount)
    {
        if(withdrawAmount <= _balance || withdrawAmount > 0 )
        {
            _balance -= withdrawAmount;
            return true;
        }

        else
        {
            return false;
        }
    }




}




C++ error when putting typedef statements inside class for doubly linked list

I am implementing a doubly linked list.

I have 3 typedef statements in my class.

When compiled I get the error "'reference' does not name a type". If I move them under my include statements, this error disappears but new ones arise, such as 'Node' not being declared in my main scope. I am not sure where each of these typedef statements need to go in order to get my program functioning properly. I have included the default constructor as well.

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;


class linkedlist
{
public:

    typedef int element_type;
    typedef element_type& reference;
    typedef const element_type& const_reference;
    linkedlist();
    ~linkedlist();
    bool empty() const;
    void clear();
    reference back();
    const_reference back() const;
    reference front();
    const_reference front() const;
    linkedlist& operator=(const linkedlist& l);
    void pop_back();
    void pop_front();
    void push_back(const element_type& x);
    void push_front(const element_type& x);
    void sort();

    explicit linkedlist(unsigned int n);
    void check() const;
    void rcheck() const;


private:
    struct Node
    {
        element_type elem;
        Node* next;
        Node* prev;
    };
    Node* head;
    Node* tail;
    int size;
};

linkedlist::linkedlist()
{
    head = new Node;
    tail = new Node;
    head->next = tail;
    head->prev = NULL;
    tail->next = NULL;
    tail->prev = head;
    size = 0;
}

...




Python: programmatic class instance variable initialisation with locals()

I have a class with many instance variables with default values, which optionally can be overridden in instantiantion (note: no mutable default arguments).

Since it's quite redundant to write self.x = x etc. many times, I initialise the variables programmatically.

To illustrate, consider this example (which has, for the sake of brevity, only 5 instance variables and any methods omitted):

Example:

# The "painful" way
class A:
    def __init__(self, a, b=2, c=3, d=4.5, e=5):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e

# The "lazy" way
class B:
    def __init__(self, a, b=2, c=3, d=4.5, e=5):
        self.__dict__.update({k: v for k, v in locals().items() if k!='self'})


x = A(1, c=7)
y = B(1, c=7)

print(x.__dict__)  # {'d': 4.5, 'c': 7, 'a': 1, 'b': 2, 'e': 5}
print(y.__dict__)  # {'d': 4.5, 'c': 7, 'a': 1, 'b': 2, 'e': 5}

So to make my life easier, I use the idiom shown in class B, which yields the same result as A.

Is this bad practice? Are there any pitfalls?




How can I filter and count objects in DJANGO template?

Hello I justa want to ask this because Im new in django, my trouble is that i want to count how many comments have a post and put it in to the html template. But the thing is that im using for to gather all the events in the db, but i just want to show only the count of comments that have every event that the "for" are showing. this is my models, view, and template. Thank you so much.

MODELS

class Event(TimeStampModel):
    name = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(editable=False)
    summary = models.TextField(max_length=255)
    content = models.TextField()
    category = models.ForeignKey(Category)
    place = models.CharField(max_length=50)
    start = models.DateTimeField()
    finish = models.DateTimeField()
    image = models.ImageField(upload_to = 'eventos')
    is_free = models.BooleanField(default=True)
    amount = models.DecimalField(max_digits=6, decimal_places=0, default=0) 
    views = models.PositiveIntegerField(default=0)
    organizer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.name)
        super(Event, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name

class Comments(TimeStampModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    event = models.ForeignKey(Event)
    content = models.TextField()

    def __unicode__(self):
        return "%s %s" % (self.user.username, self.event.name)  

VIEW

class IndexView(TemplateView):
    template_name = 'eventos/index.html'
    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['events'] = Event.objects.all().order_by('-created')[:6]
        context['categories'] = Category.objects.all()
        context['comments'] = Comments.objects.all()
        return context

HTML TEMPLATE



I want to show it just in that part of the html where it says comments.. with a tag of course, but i just dont know wich tag or how to do it.




add styles In a Plugin (inside a PHP class)

I've created a plugin as a class and what I'm trying to do is call a register_hooks() function inside my __construct method. I have a admin_menu and a wp_enqueue_scripts add_actions within my register_hooks(). My menu works but not the styles.

here are the functions:

constructor

private function __construct() {

    $this->_register_hooks();
// $this->redirect();

}

register_hooks function

private function _register_hooks() {
// register plugin menu
    add_action( 'admin_menu', array( &$this, '_menu' ) );

    // register plugin styles
    add_action( 'wp_enqueue_scripts', array( &$this, '_styles' ) );

}

queue styles function

public function _styles() {

    wp_register_style( 'magic_styles', plugins_url( 'assets/css/magic-gallery.css', __FILE__ ) );
    wp_enqueue_style( 'magic_styles' );
}

I then import this file into another page and initiate the plugin. Let me know if you need any more information.




Array keeps returning [Ljava.lang.String; [duplicate]

This question already has an answer here:

I have a class file with the following class

public class Menu
{
    private String[] OptionList;                 //array as an instance variable
}  


In this class I've created a constructor

public Menu(String[] options)
{
    this.OptionList = options;
}


And a toString method

public String toString()
{   
    return OptionList;  
}



Now in my driver file

public class MenuDemo 
{

    public static void main(String[] args) 
    {
       String[] drink_options = {"Water", "Soda pop", "Beer"};        //create an array of strings
       Menu drinkMenu = new Menu(drink_options);                      //create a new object to test the constructor with an array of strings as a parameter
       System.out.print(drinkMenu);
    }

}


My output was

[Ljava.lang.String;@15db9742

How can I get an output that looks like this instead?

(1) Water
(2) Soda pop
(3) Beer

I think I have to use a for loop like this.

for (int i = 0; i < OptionList.length; i++)
    {
        System.out.println("(" + (i+1) + ")" + options[i]);
    }

My question now is where would I put such a loop in my class file?




printing output using object in python [duplicate]

This question already has an answer here:

class hive:
   def abc(str):
      name = str
      return name + ' welcome'

def main():
  obj = hive()
  print('enter name')
  string = input()
  print(obj.abc(string))

if __name__ == "__main__": main()

I want to print name with welcome string concatenated with it,but I can't be able to do so and I am getting the error below :

C:\Users\SHUBHAM TANDAN\Desktop\python>class.py 
enter name
shubham
Traceback (most recent call last):
File "C:\Users\SHUBHAM TANDAN\Desktop\python\class.py", line 12, in <module>
if __name__ == "__main__": main()
File "C:\Users\SHUBHAM TANDAN\Desktop\python\class.py", line 10, in main
print(obj.abc(string))
TypeError: abc() takes 1 positional argument but 2 were given

Can anyone please help me find the error in the above code ?




Issue with a class method

I have to create a class Color of this type

class Color:
    def __init__(self, r, g, b):
        self.r = r
        self.g = g
        self.b = b

and i have to create these methods:

-createatuple() that returns a tuple (r, g, b) of the object's color

-mixture(f) that returns a new instance of the color and its values are a mixture of the current instance with the color f

I tried this

>>>class Color:
       def __init__(self, r, g, b):
           self.r = r
           self.g = g
           self.b = b
       def createatuple(self):
           return (self.r, self.g, self.b)
       def mixture(self, f):
           self.r = int((self.r+f.r)/2)
           self.g = int((self.g+f.g)/2)
           self.b = int((self.b+f.b)/2)
           return self.r
           return self.g
           return self.b

>>>color1 = Color(10,15,10)
>>>color1.createatuple()
(10,15,10)
>>>color2 = Color(20,5,200)
>>>color2.createatuple()
(20,5,200)

If i wanna do:

>>>color1.mixture(color2).createatuple()
(15,10,105)

But i receive " 'str' object has no attribute 'createatuple()' "

What's wrong?




Python: Why can't @var.setter function access class variables?

I have a class where I want to validate the data whenever it's property is changed. I wish to store the valid options as a class variable that the setter can refer to, but I seem to have found that within the @var.setter option I'm unable to reference any class variables at all.

Why is that?

Code example:

class Standard():
    def __init__(self):
        self.variable1 = 1
        self.variable2 = 2

  @property
  def variable1(self):
      # This works
      print(self.variable2)
      return self.__variable1

  @variable1.setter
  def variable1(self, var):
      # This doesn't work
      print(self.variable2)
      self.__variable1 = var

x = Standard()
print(x.variable1)
x.variable1 = 4
print(x.variable1)

This outputs:

AttributeError: 'Standard' object has no attribute 'variable2'

When it clearly does.




python class static method and stand-alone method

I have a class A and another class B that inherits from A.

In one functions A.f(), I notice there is several lines of code that does not depend on self or the class itself, and these lines can be reused in the child class B. In this case, shall I move these lines into a static class method of A, or put them in a stand-alone method?




How should class fields be declared in C++?

I need to declare and initialize a vector as a field of a class named PixelOperator.

I am torn between these two declaration methods, the first is "on the heap", and the second "on the stack" (or at least, that is my interpretation).

  1. vector<int>* field = new vector<int>();
  2. vector<int> field = vector<int>();

If I choose to declare in style number 2, I need to call delete in the destructor of the class.

Which one should I choose, and why?

Also, if the class is initialized on the heap (ie. PixelOperator* op = new PixelOperator();), are fields initialized on the stack initialized on the heap?




Best practice to store global variables of a JS plugin which have multiple instances

I am working on a medium scaled JS library which has a lot of modules. I am using ES6 with webpack to take advantage of the class syntax. I have organized the files in small independent modules and those modules needs to interact with each other.

My namespace is Plugin and I think it is fine to store a global like Plugin.xyz

I have user options stored in a global object Plugin.config and I was using this fine until I came accross multiple instances of the plugin. When I instantiated the class with new keyword, it takes in correct options, but the last instance will obviously overwrite the global Plugin.config object. I did some workarounds, created a Base class and stored config object inside this base class's object. So, every plugin instance has different base.config.

Now, when different modules need to communicate with each other, I have to send base.config in constructor of each class. Is this the proper way of dealing globals in your plugin or is there a best practice to follow?

Thanks




How to add my own "help" information to a python function/class?

I know I can use "help()" to see existing help information from packages. But after I wrote my own function/class, how can I enable "help" to see help document? I know the first line of "comment" is a doc attribute, but that's not what I wanted.

I wish to have my own package compiled, and others could see from "help()". How to do that?




how to had conditionnal class in a method helper?

I'd like to had a conditionnal class in a method helper

product_helper.rb

def product_icon
  ...
  elsif product.sent?
    '<div class="green-text  <%= 'middle' if current_action?(controller: 'products', action: 'index')" %> ><i class="fa fa-envelope-o" aria-hidden="true"></i></div>'.html_safe
end

But I get this ERROR :

syntax error, unexpected keyword_class, expecting keyword_end 
 '<div <%= 'class="middle if current_acti...
                  ^

Any help please ? I can't find the solution




How to determine if a class is nested under a given module?

I have some modules:

module A end
module A::B end
module C end

And some classes:

class Foo end
class A::Bar end
class A::Baz end
class A::B::Qux end
class C::Quux end

And an array containing these classes:

 classes = [Foo, A::Bar, A::Baz, A::B::Qux, C::Quux]

I want to find all classes from the above array that are not nested under A. This would work:

classes.reject { |c| c.name.split('::').first == A.name }
#=> [Foo, C::Quux]

But it's merely a hack. It compares via the modules name attribute. It wouldn't work at all for anonymous modules created via Module.new (name returns nil in that case) and it would likely break if a class overrides the name method.

How do I solve this properly?




Scrape Div Class from VBA

i´m working on comparing price products to try to get mine at price. I have a code wich work fine to scrape some web but i have a couple that have the data i want to bring "price" inside the Div Class and my code doesn´t allow me to bring it. I was working on this but still i can´t figure out how. If someone of you can help me on this i will be thankfull. Here is the web of one of the product: http://ift.tt/2gFzFYr I need to pull the small price wich say: "###(price) por litro" wich looking at the code is:

$1025.33 por Lt

But is inside, mean have previus 16 other Div after

My code is : Dim IE As Object

Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = False

    IE.navigate "http://ift.tt/2gFzFYr"


Application.StatusBar = "Loading, Please wait..."


Do While IE.Busy
    Application.Wait DateAdd("s", 1, Now)
Loop

Application.StatusBar = "Searching for value. Please wait..."

Dim dda As String

dda = IE.document.getElementsByClassName("product-price-per-unit")(0).innerText

ActiveSheet.Range("b2").Value = dda




Error when creating a string in a function of class

I create a class named Employee, in private, I have a Name as a string . here is my class declaring:

class Employee
{
     string Name;
 public:
     Employee();
     void SetName(string);
     void StringToEmployee(string);
     ~Employee();
 }

this is definition of StringToEmployee(string) method:

void Employee::StringToEmployee(string s)
{
     char  *first = s, *end = s+strlen(s), *last = NULL;
     last = find(first, end, ',');
     string temp(first, last- first);
     SetName(temp);
}

The error occurs when I debug to the line *string temp(first, last- first)*, it's seem to the compiler does not allow me to construct a new string in method. cause I have also changed into *string temp;* then *temp.assign(first, last-first)*. the error still remain. How could I create a new string in a method?




Currently studying Python and need some assistance

Could someone experienced with Python please mail me as I'm having issues with something. Thank you in advance, much appreciated.




constant class instance in swift confsion

let myclassInstance1=myclass()
let myclassInstance2=myclassInstance1
myclassInstance1.prop1=2
myclassInstance2.prop1=3

the above code is supposed to throw error as I am altering the constant.

But its not happening

How come ?




Make classifications with number ranges on Tableau

I Have a deposits parameter. I want to classify population into 3 sections as follows: high, medium and low

Tried to create a calculated field.This does not work for me in the following way and gives different errors. Please advise?

if 1300<[deposit] then 'high' or
if 1150<[deposit]< 1300 then 'Medium'
 else 'Low' 
 END
 END




How to invoke a class in another package?

I'm on a starter project and I split it in two packages in Eclipse and one of them has the main method and another .java class and the other one has anothers .java class with secondary methods. I want to know how do I invoke a method present in the secondary package to use it in the .java class that doesn't have the main method in the primary. How do I import it and how do I access a method from that class? I'm new to java and need this to a project.




destructor implementation in templated class

If I have a class like this:

template <class T>                            
class Array {                                              
 private:                                        
  T *m_pData;                                   
  unsigned int m_nSize;                         
 public:                                         
 Array(unsigned int nSize) : m_nSize(nSize),m_pData(nullptr) {                                           
 if(m_nSize > 0)
  m_pData = new T[m_nSize];                
 }                                           

 ~Array() {                    
  if(m_pData != NULL) {
   delete [] m_pData;
  }
};

If now I create an object of my class like this:

Array<int> miArray(5);

Implementation of the destructor should be fine, but if I create an object like this:

Array<int*> miArray(5);

In the destructor I should delete every object stored in the array to avoid memory leaks.

How can I achieve that?

Thanks




mardi 29 novembre 2016

Calling attributes from classes in Python

So at the moment I`m playing around with classes and I want to do the following:

class Hi (object):
     def __init__(self, bloop):
          self.bloop ≈ bloop # ignore the ≈, I`m typing this on my phone and my phone doesn`t have an equal sign.
thing ≈ Hi(“bloop”)
name ≈ input(“Input a thing”) # Let`s assume you input thing
print(name.bloop)

What I want it to do is for it to print “bloop” because you entered thing and it get`s bloop from thing kinda like thing.bloop. Thanks




PHP: Extend authentication class by methods of childs

I'd like to declare a class auth that is extended by multiple child classes.

// Parent class that should be called
abstract class auth
{
    // Force child classes to implement this method
    abstract public function authUser($uid, $pw);
}

class configAuth1 extends auth
{
    public function authUser($uid, $pw)
    {
        // Do some authentication stuff
        return false;
    }
}

class configAuth2 extends auth
{
    public function authUser($uid, $pw)
    {
        // Do some authentication stuff
        return true;
    }
}

Now I'd like to call the parent class and try all child class methods authUser() until one returns true.

So I'd say it's not senseful to instantiate all childs manually. How can I handle this?




Inheriting private members from base class to derived classes c++

I'm trying to inherit the name,skeletonType, and numLegs from my base class to my derived class. I have a base class named Invertebrates and derived class named Spider. I want to be able to use the private variables with the derived class from my base class. I'm trying to get my output to look like this " Spider:Brown Recluse, number of legs = 8, skeleton type = EXOSKELETON. Could someone help me out and point me in the right direction please. Here is what I put together so far. VVVVVV

// invertebrates.h
// invertebrate specifications

#ifndef _INVERTEBRATE_H_
#define _INVERTEBRATE_H_

#include <iostream>

using namespace std;

enum Skeleton_Type { NONE, HYDROSTATIC, EXOSKELETON };

class Invertebrate {
  private:
    string name;
    Skeleton_Type skeletonType;
    int numLegs;
  protected:
    void setSkeletonType(Skeleton_Type skeletonType);
    void setNumLegs(int numLegs);
  public:
    Invertebrate();
    Invertebrate(string name, Skeleton_Type skeletonType, int numLegs);
    string getName();
    Skeleton_Type getSkeletonType();
    int getNumLegs();
    virtual void print() = 0;
};

class Spider : public Invertebrate {
  private:
    const string NAME_PREFIX = "Spider: ";
  public:
    Spider();
    Spider(string name);
    virtual void print();
};
#endif // _INVERTEBRATE_H_ 
**********************************************************************

//invertebrates.cpp

#include "invertebrate.h"

void Invertebrate::setSkeletonType(Skeleton_Type skeletonType)
{
     this->skeletonType = skeletonType;
}

void Invertebrate::setNumLegs(int numLegs)
{
    this->numLegs = numLegs;
}
Invertebrate::Invertebrate()
{
    name = "noName";
    skeletonType = NONE;
    numLegs = 0;
}

Invertebrate::Invertebrate(string name, Skeleton_Type skeletonType, int     numLegs)
{
    this->name = name;
    this->skeletonType = skeletonType;
    this->numLegs = numLegs;
}

string Invertebrate::getName()
{
    return this->name;
}

Skeleton_Type Invertebrate::getSkeletonType()
{
    return this->skeletonType;
}

int Invertebrate::getNumLegs()
{
    return this->numLegs;
}


Spider::Spider(string name):Invertebrate(name&,EXOSKELETON,8)
{
    name = NAME_PREFIX + Invertebrate::getName();
}

void Spider::print()
{
    cout << this->getName();
    cout << ", number of legs =" << this->getNumLegs() << ", skeleton  type = " << this->getSkeletonType()<< endl;
}


int main()
{
    Spider *sp = new Spider("Brown Recluse");
    sp->print();

    return 0;
}




Is it good Idea to have Angle & Distance struct or class

Is it good Idea to have Angle & Distance struct, instead of just pass float or double around?

For example in C#, I can make a Angle struct, it would have methods such as:

angle.Sin();
angle.Cos();

That way I don't have to think if I'm using Radians or 360 Deg.

And for Distance, Speed, ... etc. I can do the same

Is it good design to build such class and structs?




How to round up and round down and kick out while loop with Enter key [duplicate]

This question already has an answer here:

# Create a class called "Loan":
# Data fields in the Loan class include: Annual Interest Rate(Float),\
# Number of years of loan(Float), Loan Amount(Float), and Borrower's Name(string)
class Loan:
    # Create the initializer or constructor for the class with the above data fields.
    # Make the data fields private. 
    def __init__(self, annualInterestRate, numberOfYears, loanAmount, borrowerName):
        self.__annualInterestRate=annualInterestRate
        self.__numberOfYears=numberOfYears
        self.__loanAmount=loanAmount
        self.__borrowerName=borrowerName
        self.monthlyPayment__ = None
        self.totalPayment__ = None
    # Create accessors (getter) for all the data fields: 
    def getannualInterestRate(self):
        return self.__annualInterestRate
    def getnumberOfYears(self):
        return self.__numberOfYears
    def getloanAmount(self):
        return self.__loanAmount
    def getborrowerName(self):
        return self.__borrowerName
    # Create mutators (setters) for all the data fields:
    def setannualInterestRate(self):
        self.__annualInterestRate=annualInterestRate
    def setnumberOfYears(self):
        self.__numberOfYears=numberOfYears
    def setloanAmount(self):
        self.__loanAmount=loanAmount
    def setloanAmount(self,loan2):
        self.__loanAmount=loan2
    def setborrowerName(self):
        self.borrowerName=borrowerName
    # Create a class method: getMonthlyPayment - 
    def getMonthlyPayment(self,loanAmount, monthlyInterestRate, numberOfYears):
        monthlyPayment = loanAmount * monthlyInterestRate / (1- (1 / (1 + monthlyInterestRate) ** (numberOfYears * 12)))
        return monthlyPayment
    # Create a class method: getTotalPayment - 
    def getTotalPayment(self):
        monthlyPayment = self.getMonthlyPayment(float(self.getloanAmount()), 
        float(self.getannualInterestRate()) / 1200, 
        int(self.getnumberOfYears()))
        self.monthlyPayment__=(format(monthlyPayment, '10.2f'))
        totalPayment = float(self.monthlyPayment__) * 12 \
        * int(self.getnumberOfYears())
        self.totalPayment__=(format(totalPayment, '10.2f'))
        return self.totalPayment__

# Write a test program (main function) to allow the user to enter the following: 
def main():
    loan1=Loan(float(input(("Enter yearly interest rate, for exmaple, 7.25: "))),\
               float(input(("Enter number of years as an integer: "))),\
               float(input(("Enter loan amount, for example, 120000.95: "))),\
               input(("Enter a borrower's name: ")))
    print()
    print("The loan is for", loan1.getborrowerName())
    print("The monthly payment is", loan1.getMonthlyPayment(loan1.getloanAmount(), \
    (loan1.getannualInterestRate()/1200), loan1.getnumberOfYears()))
    print("The total payment is", loan1.getTotalPayment())
    print()
    loan_change=print(input("Do you want to change the loan amount? Y for Yes OR Enter to Quit: "))
    while loan_change!="":
            print()
            loan2=float(input("Enter a new loan amount: "))
            loan1.setloanAmount(loan2)
            print("The loan is for", loan1.getborrowerName())
            print("The monthly payment is", loan1.getMonthlyPayment(loan1.getloanAmount(), \
            (loan1.getannualInterestRate()/1200), loan1.getnumberOfYears()))
            print("The total payment is", loan1.getTotalPayment())
            print()
            loan_change=print(input("Do you want to change the loan amount? Y for Yes OR Enter to Quit: "))

main()

Here is a sample output which I will dissect in a moment:

Enter yearly interest rate, for exmaple, 7.25: 2.5
Enter number of years as an integer: 5
Enter loan amount, for example, 120000.95: 1000.00
Enter a borrower's name: Samson

The loan is for Samson
The monthly payment is 17.74736160547945
The total payment is    1065.00

Do you want to change the loan amount? Y for Yes OR Enter to Quit: 


Enter a new loan amount: 

I have 3 simple questions:

  1. How do I round 17.74736160547945 to 17.75?
  2. How do I prevent the total payment from rounding to 1065.00 when it should be 1064.84?
  3. How do I make it so the while loop kicks out of the program when I hit the "Enter" key? Right now, it just stays in the loop no matter what I press. I want to make it explicitly enter the loop when I press "Y" and explicitly exit the program when I press "Enter" key.

Any help would be appreciated.

NOTE: For those about to copy/paste rounding tutorials - I've already tried them. I've tried rounding with {}, % and "10.2f" and none of those worked. I'm not sure how to round down also per question no. 2. I have a lot of floats flying around and I'm not exactly sure how to reign this program in to 2 decimal places. Thank you.




Using sleep and usleep interchangeably by creating a class that decides which one to use

How would I implement sleep and usleep in a header file. This is what I've tried so far and it isn't working. I am not quite proficient in c++ yet. I know that it is possible to do something similar in HTML by commenting out and each browser uses the code specific to it.

This is the sample I'm practicing with:

help.cpp

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

using namespace std;


int main() {

pause p;    

cout << "Hello";

p.pause(5000)

cout << " World";

}

Someone in another thread suggested using #ifdef #else #endif to get it to work between windows and linux/unix

pause.h

#ifdef _WIN32
    #include <windows.h>


class pause
{
    public:
        void pause(unsigned milliseconds)
        {
            Sleep(milliseconds);
        }
};

#else
        #include <unistd.h>

class pause
{
    public:
        void pause(unsigned milliseconds)
        {
            usleep(milliseconds * 1000); // takes microseconds
        }
};

#endif

Somehow though, I must have written the class incorrectly because running my .cpp file it is not recognizing the class or object I tried creating.

Error

Running /home/ubuntu/workspace/help.cpp
In file included from /home/ubuntu/workspace/help.cpp:2:0:
/home/ubuntu/workspace/pause.h:20:41: error: return type specification for constructor invalid
         void pause(unsigned milliseconds)
                                         ^
/home/ubuntu/workspace/help.cpp: In function ‘int main()’:
/home/ubuntu/workspace/help.cpp:9:7: error: expected ‘;’ before ‘p’
 pause p;    
       ^
/home/ubuntu/workspace/help.cpp:13:1: error: ‘p’ was not declared in this scope
 p.pause(5000)
 ^
/home/ubuntu/workspace/help.cpp:15:1: error: expected ‘;’ before ‘cout’
 cout << " World";
 ^


Process exited with code: 1




Identifying a class object with its member integer Id in C++

Look at the three classes and its data members, given below.

node class

 class node
 {
     int node_id;
     double x,y,z;

 }

element class

 class element
 {
      int element_id;
      node node1,node2,node3;
 }

mesh class

 class mesh
 {
      /* I know that instead of pointer object we've to use smart pointer
         in the vector  but don't know how to use it.Any help is 
         appreciated. */

      std::vector<node*> nodes; // stores node objects.
      std::vector<element*> elements; //store element objects;
 }

So I can easily instantiate node objects and can be stored in nodes of std::vector data-type. But I need to precisely know which node objects are there in the element to instantiate an object of element. node objects are stored in the vector array. Identifying a node object like nodes[i] is error prone in my case. So I would like to identify an node object based on its id. Please give me suggestions.

I hope my question make sense. Since I'm a beginner in c++ any edit is also appreciated to make question understandable.




loan calculator using classes(OOP) in python causes numerous errors

# Create a class called "Loan":
# Data fields in the Loan class include: Annual Interest Rate(Float),\
# Number of years of loan(Float), Loan Amount(Float), and Borrower's Name(string)
class Loan:
    # Create the initializer or constructor for the class with the above data fields.
    # Make the data fields private. 
    def __init__(self, annualInterestRate, numberOfYears, loanAmount, borrowerName):
        self.__annualInterestRate=annualInterestRate
        self.__numberOfYears=numberOfYears
        self.__loanAmount=loanAmount
        self.__borrowerName=borrowerName
    # Create accessors (getter) for all the data fields: 
    def getannualInterestRate(self):
        return self.__annualInterestRate
    def getnumberOfYears(self):
        return self.__numberOfYears
    def getloanAmount(self):
        return self.__loanAmount
    def getborrowerName(self):
        return self.__borrowerName
    # Create mutators (setters) for all the data fields:
    def setannualInterestRate(self):
        self.__annualInterestRate=annualInterestRate
    def setnumberOfYears(self):
        self.__numberOfYears=numberOfYears
    def setloanAmount(self):
        self.__loanAmount=loanAmount
    def setborrowerName(self):
        self.borrowerName=borrowerName
    # Create a class method: getMonthlyPayment - 
    def getMonthlyPayment(self,loanAmount, monthlyInterestRate, numberOfYears):
        monthlyPayment = loanAmount * monthlyInterestRate / (1\
        - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
        return monthlyPayment
    # Create a class method: getTotalPayment - 
    def getTotalPayment(self):
        monthlyPayment = self.getMonthlyPayment(float(self.getloanAmount()), 
        float(self.getannualInterestRate()) / 1200, 
        int(self.getnumberOfYears()))
        self.monthlyPayment__=(format(monthlyPayment, '10.2f'))
        totalPayment = float(self.monthlyPayment__) * 12 \
        * int(self.getnumberOfYears())
        self.totalPayment__=(format(totalPayment, '10.2f'))

# Write a test program (main function) to allow the user to enter the following: 
def main():
    loan1=Loan(input(("Enter yearly interest rate, for exmaple, 7.25: ")),\
               input(("Enter number of years as an integer: ")) ,\
               input(("Enter loan amount, for example, 120000.95: ")),\
               input(("Enter a borrower's name: ")))
    print()
    print("The loan is for", loan1.getborrowerName())
    print("The monthly payment is", loan1.getMonthlyPayment(loan1.getloanAmount(), loan1.getannualInterestRate(), loan1.getnumberOfYears()))
    print("The total payment is", loan1.getTotalPayment())
    print()
    print(input("Do you want to change the loan amount? Y for Yes OR Enter to Quit"))
    #while input !='':
    #??? No idea how to run a while loop that's kicked out with the\
    #"Enter" keystroke (while activated by "Y")...
    print()
    print(input(float("Enter a new loan amount: ")))
    print("The loan is for", loan1.getborrowerName())
    print("The monthly payment is", loan1.getMonthlyPayment())
    print("The total payment is", loan1.getTotalPayment())
    #print(input("Do you want to change the loan amount? Y for Yes OR Enter to Quit"))

main()

Trying to make this program run as shown (with ample comments to guide you if you want to know what I'm doing...) however, it is not working. It is riddled with errors. And I'm not sure what I'm doing wrong. Yes, there are class tutorials on Python's website. No, I do not understand them. That's why I'm here. Theory can only get one so far. Currently, the error I am getting is:

TypeError: can't multiply sequence by non-int of type 'str'

But I know this is just the tip of the proverbial iceberg. Ideally, when the program runs, it should allow the user to change the loan amount and reprint the new loan information preferably in a while-loop of sorts after the initial information has been entered. You can see my progress so far (with the gracious help of SO denizens). But there is still a lot left for me to clean up. I believe I've made it quite a ways. But there is much left to do. That error I mentioned is one starting point. Thank you for any help or guidance.




size of a class object [duplicate]

This question already has an answer here:

I have wrritten the following class

class ClientData1
 {
 public:
int accountNumber;

 double balance;
 char lastName[15];
 char firstName[14];
 };
int main()
{
    ClientData1 c;  
cout<<"sizeof( ClientData )"<<sizeof( ClientData1 )<<endl;
cout<<"sizeof( accountNumber  )  =="<<sizeof( c.accountNumber )<<endl;;
cout<<"sizeof( lastName )  =="<<sizeof( c.lastName )<<endl;
cout<<"sizeof( firstName )  =="<<sizeof( c.firstName )<<endl;
cout<<"sizeof( balance )  =="<<sizeof(c.balance )<<endl;

    return 0;
}

the output is 
sizeof( ClientData )=48
sizeof( accountNumber)=4
sizeof( lastName ) =15
sizeof( firstName ) = 14  
sizeof( balance )= 8

But according the fact that size of a class object is the sum of the sizes of all of its data members, size of clientdata should be 41.. why size is 48...plz help




loan calculator using class(OOP) not running in python

# Create a class called "Loan":
# Data fields in the Loan class include: Annual Interest Rate(Float),\
# Number of years of loan(Float), Loan Amount(Float), and Borrower's Name(string)
class Loan:
    # Create the initializer or constructor for the class with the above data fields.
    # Make the data fields private. 
    def __init__(self, annualInterestRate, numberOfYears, loanAmount, borrowerName):
        self.__annualInterestRate=annualInterestRate
        self.__numberOfYears=numberOfYears
        self.__loanAmount=loanAmount
        self.__borrowerName
    # Create accessors (getter) for all the data fields: 
    def getannualInterestRate(self):
        return self.__annualInterestRate
    def getnumberOfYears(self):
        return self.__numberOfYears
    def getloanAmount(self):
        return self.__loanAmount
    def getborrowerName(self):
        return self.__borrowerName
    # Create mutators (setters) for all the data fields:
    def setannualInterestRate(self):
        self.__annualInterestRate=annualInterestRate
    def setnumberOfYears(self):
        self.__numberOfYears=numberOfYears
    def setloanAmount(self):
        self.__loanAmount=loanAmount
    def setborrowerName(self):
        self.borrowerName=borrowerName
    # Create a class method: getMonthlyPayment - 
    def getMonthlyPayment(self,loanAmount, monthlyInterestRate, numberOfYears):
        monthlyPayment = loanAmount * monthlyInterestRate / (1
        - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
        return monthlyPayment;
    # Create a class method: getTotalPayment - 
    def getTotalPayment(self):
        monthlyPayment = self.getMonthlyPayment(float(self.loanAmountVar.get()), 
        float(self.annualInterestRateVar.get()) / 1200, 
        int(self.numberOfYearsVar.get()))
        self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f'))
        totalPayment = float(self.monthlyPaymentVar.get()) * 12 \
        * int(self.numberOfYearsVar.get())
        self.totalPaymentVar.set(format(totalPayment, '10.2f'))

def main():
    loan1=Loan()
    print(input(float("Enter yearly interest rate, for exmaple, 7.25: ", loan1.annualInterestRate())))
    print(input(float("Enter number of years as an integer: ", loan1.getnumberOfYears())))
    print(input(float("Enter loan amount, for example, 120000.95: ", loan1.getloanAmount())))
    print(input(float("Enter a borrower's name: ", loan1.getborrowerName())))

    print("The loan is for", loan1.getborrowerName())
    print("The monthly payment is", loan1.getMonthlyPayment())
    print("The total payment is", loan1.getTotalPayment())

    print(input("Do you want to change the loan amount? Y for Yes OR Enter to Quit"))

    print(input(float("Enter a new loan amount: ")))
    print("The loan is for", loan1.getborrowerName())
    print("The monthly payment is", loan1.getMonthlyPayment())
    print("The total payment is", loan1.getTotalPayment())

main()

For some reason my program is not running. I'm trying to allow the user to change the loan amount and reprint the new loan information. I don't know what I'm doing wrong, and classes/OOP is new to me, so I'm struggling dearly as I've been doing procedural-only for the past year. I am aware that this is filled with numerous errors... but I have nowhere to begin. All the tutorials for classes online are extremely vague and theoretical, and do not broach specific examples/scenarios like the one I'm facing with.

Any help would be appreciated.




C# How does a child class member find out which index in a parent list it comes from?

Let's say I have a class

public class member{
   int Num;
}

public class C1
{
    List<member> Nums=new List<member>();
    public C1
    {
       Nums.Add(66);
       Nums.Add(24);
       Nums.Add(32);
       Nums.Add(34);
    } 
}

Let's say I have access to an object of type member and it is a child to C1. Let's say it's the one with Num=32. How can I, having that object find out that 32 is the 3rd member in list Nums? That is without having the actual variable Nums! All I have is an object of type member.

I have a workaround...I can add another int into class member and as I add members I can index it. For example...

public class member{
   int Num;
   int Order;
}

public class C1
{
    List<member> Nums=new List<member>();
    public C1
    {
       Nums.Add(66,1);
       Nums.Add(24,2);
       Nums.Add(32,3);
       Nums.Add(34,4);
    } 
}

Now if I have an object of type member I will know where in the Nums list it exists.

Anyhow...if there is a better way...

Thanks in advance.




Accessing PHP Class Method in Joomla

There is an example Hello Word component in Joomla.

In Models:

class HellowWorldModelHelloWorld extends JModel
{
Protected $message;

Public function getMsg()
{
if (!isset($this->message))
{
$this->message = 'Hello World';
}
return $this->message;
}
}

in Views:

class HelloWorldViewHelloWorld extends JViewLegacy
{

    function display($tpl = null)
    {
        $this->msg = $this->get('Msg');

        if (count($errors=$this->get('Errors')))
        {
            JLog::add(implode('<br/>',$errors),JLog::WARNING, 'jerror');

            return false;
        }

        parent::display($tpl);
    }
}

Now my question is how this works, as far as I have learned, I can't make it out the below code

$this->msg = $this->get('Msg');

First $this->msg - msg property is not defined anywhere in the class or in the parent class. So how msg is get defined or set by directly accessing $this->msg

Second the method in the model is defined as function getMsg() . So I think it should be accessible as $this-getMsg()(but it doesn't work) but it is being accessed as $this-get('Msg') and it is working fine.

A detailed answer with example will help me properly understand what I am missing.




python class inheritance code re-use

I have two classes that share a lot of common stuff except one function f(x).

class A(object):
    def __init__(self):
        // some stuff
    def g(self):
        // some other stuff
    def f(self, x):
        // many lines of computations
        q = ...
        y = ...
        return y

class B(A):
    def f(self, x):
        // same many lines as in A
        q = ...
        y = ...
        // a few extra lines
        z = ... # z needs both y and q
        return z

In this case, do I have to define f(x) from scratch in class B? Is there some trick to re-use the code in A.f(x)?

One way I can think of is to make q a class property self.q, then do the following

def f(self.x):
    y = A.f(self, x)
    // a few extra lines
    z = ... # using y and self.q
    return z

Is this the standard way to do it? Is there something nicer?




Change color of link inside span class

I have:

<span class="field-content highlight-front">
   <a href="/node/42" hreflang="en">This is an example</a>
</span>

in the css file i want to change the color of the link by using the span class.

.highlight-front{ 
   color: blue;
}

but that doesn't seem to work. Any suggestions or places to read about targeting a link through a span class?




In C++ language, how do you create a new object which is a pointer to an array?

I'm using a 3rd party library in which a method is declared this way:

void nexLoop(NexTouch *nex_listen_list[]);

In case of a single .cpp file, this is working:

NexButton b0 = NexButton(0, 1, "b0");
NexTouch *nex_listen_list[] = 
{
    &b0,
    NULL
};
...
nexLoop(nex_listen_list);

Full example code can be seen here: http://ift.tt/2fIRD7P

Now I'm incorporating this library in a class which has a separate header and c file, so that:

MyNextion.h

#include "Nextion.h"

class MyNextion {
   public:
       MyNextion();
       void loop();
   private: 
       NexButton *b0;
       NexTouch *nex_listen_list[];
}

MyNextion.cpp

#include "MyNextion.h"

MyNextion::MyNextion() {
    b0 = new NexButton(0, 1, "b0");
    nex_listen_list = new ???
}

MyNextion::loop() {
    nexLoop(nex_listen_list); // ???
}

I was messing around with pointers and address operators but I couldn't find the right combination to a successful compilation.

My question is: what would you put here: nex_listen_list = new ???;

Also, I'm not sure the title well defines my problem. Please correct it if you have a better idea for the title.

Thank you!




Changing div class with JS

Im trying to collapse a panel with a button id="collapsible" which works, and then i need to change the class of the panel below id="gamewindow" to fill the entire screen, so with bootstrap i need to change col-md-9 to col-md-12 and this is the part that isnt working.

My html :

<div class="collapse in" id="collapsible">
....
</div>
<div id="gamewindow" class="col-md-9">
....
</div>

My JS :

if( $("#xs-check").is(":visible") )
    $("#collapsible").removeClass("in");
    $("#gamewindow").removeClass("col-md-9");
    $("#gamewindow").addClass("col-md-12");

What am i doing wrong?




Python Class Pokemon Battle

Hey stackoverflow users,

I am trying to write a Python class for a pokemon battle. I followed the posts here, but I am trying to integrate the different pokemon typing. For instance, fire, grass, and water and allow them to function as they do in the game. For example, fire is super effective against grass. I am not sure if I should add in another function for type or define the typing within the constructor and write a series of nesting statements that determine effectiveness or ineffectiveness.

class Pokemon(object):
        def __init__(self, name, HP, Damage, type):
        self.name = name     #Sets the name of the Pokemon
        self.HP = HP         #The Hit Points or health of this pokemon
        self.Damage = Damage #The amount of Damage this pokemon does every     attack
        self.type = type #Determines the type of the pokmeon to factor in effectiveness

    def Battle(self, Opponent):
        if self.type == 'grass':
            self.Damage = self.Damage * 1.35

        if(self.HP > 0): #While your pokemon is alive it will coninute the Battle
            print("%s did %d Damage to %s"%(self.name, self.Damage, Opponent.name)) #Text-based combat descriptors
            print("%s has %d HP left"%(Opponent.name,Opponent.HP)) #Text-based descriptor for the opponent's health

        Opponent.HP -= self.Damage #The damage you inflict upon the opponent is subtracted here
        return Opponent.Battle(self)  #Now the Opponent pokemon attacks
    else:
        print("%s wins! (%d HP left)" %(Opponent.name, Opponent.HP)) #declares the winner of the Battle
        return Opponent, self  #return a tuple (Winner, Loser)

Squirtle = Pokemon('Squirtle', 100, 5, 'water')
Bulbasaur = Pokemon('Bulbasaur', 100, 10, 'grass')
Winner, Loser = Bulbasaur.Battle(Squirtle)




PHP won't echo two classes

Bad headline I know, not sure how to word it.

In PHP, I'm trying to add two classes to a td by echoing them out. All of them contain one class every time, but the other class can change. I hop into the function which just has all of the classes in an array as follows...

$StandClassArray = array('north stand', 'east stand', 'south stand', 'west stand');

Note that these SHOULD be two separate classes, one is called 'stand' and one is called 'north' or 'south' etc. So all td's need the 'stand' class and one of the 4 compass points.

When I add this to my td with the following....

$Side = 0 ; // This would have been passed to the function usually.
echo "<td class = $StandClassArray[$Side]>Text</td>";

What I get in the browser is ...

<td class = "north" stand = "">Text</td>

I've tried doing it other ways, such as ...

echo "<td class = $StandClassArray[$Side] stand>Text</td>"; // Just the compass point in the array for this.

But it gives the same result.

I'm pretty sure that I've had this problem before, ages ago, but can't remember how to fix it.




Creating a smart data structure in Java

So I'm trying to create a smart data structure based off AVL tree and Hash Table.

I'm making sure I need to check first which implementation the data type will have depending on the size the list given to it.

For example, if I have a list n of size 1000, it'll be implemented using a Hash table. For anything more than 1000, using an AVL tree.

Code for this:

public class SmartULS<K,V> {

protected TreeMap<K,V> tree = new TreeMap<>();
protected AbstractHashMap<K,V> hashMap = new AbstractHashMap<K,V>();

public void setSmartThresholdULS(size){
    int threshold = 1000;
    if (size >= threshold) {
         map = new AbtractMap<K,V>();
    }
    else
         map = new TreeMap<K,V>();

    }
}

Now after this, I should be writing the standard methods such as

get(SmartULS, Key), add(SmartULS, Key, Value), remove(SmartULS,Key), nextKey(Key), previousKey(Key), etc.

I'm really lost as to how to start this? I've thought about creating these methods like this(written in pseudo):

    Algorithm add(SmartULS, Key, Value):
i<- 0
If SmartULS instanceof AbstractHashMap then
For i to SmartULS.size do
        If Key equals to SmartULS[i] then
            SmartULS.get(Key).setValue(Value)
        Else
            SmartULS.add(Key, Value)
Else if SmartULS instanceof TreeMap then
    Entry newAdd equals new MapEntry(Key, Value)
    Position<Entry> p = treeSearch(root( ), Key)




Pointer to a child class method

So here's my code I'm working with:

#include <iostream>

class Node
{
public:
    void speak(){std::cout << "I'm a base node" << std::endl;}
};

class Child : public Node
{
public:
    void speak(){std::cout << "I'm a child node" << std::endl;}
};

int main()
{
    Node node;
    Child child;

    node.speak();
    child.speak();

    std::cout << "= Pointers..." << std::endl;
    Node* pnode = &node;
    Node* pchild = &child;

    pnode->speak();
    pchild->speak();
}

And here's the output:

I'm a base node
I'm a child node
= Pointers...
I'm a base node
I'm a base node

The pchild->speak(); calls the Node's method and not the Child's one.

Now my problem is that I may have many different types of nodes, with varying number of connections. Thus I cannot declare a member pointer with a ChildX class, but only with a generic Node class. But each node will have a certain method that I want called.

I've tried to have a pointer to that method itself instead of to the class (since it would always be int (*foo)() type), but the compiler complains about invalid use of non-static member function.

So both of my approaches don't work. Neither pointer to a class, nor pointer to classes member function.




css class calling using comma and dot

i've used the following line to change a background image size .entry-header.background-image but it didn't work

what worked was: .entry-header,background-image

can somebody explain? o_O




Application crashed when I try to get value from other activity, why?

So in one Activity I set an ArrayList in a class and in the other Activity I want to get the ArrayList, but when I try to get those information the application is crashing.

ERROR:

FATAL EXCEPTION: main Process: com.example.sander.onzeoptocht, PID: 3749 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sander.onzeoptocht/com.example.sander....t.deelnemer}: java.lang.ClassCastException: android.support.multidex.MultiDexApplication cannot be cast to com.example.sander....mDataObject.deelnemerInfo

Set Activity:

ArrayList<alleDeelnemers> deelnemers = new ArrayList<>();

//deelnemer is a class with ID and some strings.
deelnemers.add(deelnemer);

//set arraylist in class
deelnemerInfo info = new deelnemerInfo();
info.setDeelnemerGegevens(deelnemers);

Class:

public class deelnemerInfo extends Application {

ArrayList<alleDeelnemers> deelnemerGegevens;

public ArrayList<alleDeelnemers> getDeelnemerGegevens() {
    return deelnemerGegevens;
}
public void setDeelnemerGegevens(ArrayList<alleDeelnemers> deelnemerGegevens) {
    this.deelnemerGegevens = deelnemerGegevens;
}

Get Activity:

deelnemerInfo info = ((deelnemerInfo)getApplicationContext());

Log.e("test", String.valueOf(info.getDeelnemerGegevens().get(0).getAantalvolgnummer()));




C# Windows Form Application - How to Create New Array According to User Selection

I want to create a windows form application that get information from a web service using REST API and present the information to the user and allow him to select items from the list and POST a request to create file according to the selection.

I created a class with all the relevant properties, and I save all the information I received from the web in a List of the created class.

My question is how can I allow the user to select an items from a List or List view and create a new list or array with all the selected items information in order to create a new JSON to POST to the server.




Add a class to a grandparent's child img

I have some images with checkboxes. When I check one of them, image should change through the new class "change-img". Here is a code:

<ul>
    <li class="tech-vis"><img class="tech-img" src="..." alt="..."/></li>
    <li class="check-tech"><input id="const-tech" class="checkbox-form inside"  type="checkbox" name="tech[]" value="value1" /></li>                                                    
</ul>
<ul>
    <li class="tech-vis"><img class="tech-img" src="..." alt="..."/></li>
    <li class="check-tech"><input id="const-tech" class="checkbox-form inside"  type="checkbox" name="tech[]" value="value2" /></li>                                                    
</ul>
... and etc.

And a script:

$("ul input[type=checkbox].inside").click(function() {
    if($(this).is(":checked")) {
        $(this).parents("ul img.tech-img").addClass("change-img");
    }
    else {
        $("img.tech-img").removeClass("change-img")
    }
});

I know that I'm wrong in line, where I'm adding a class, but how can I call this element?




Having Error while recurssing though A list of Objects that contains another List

I have a class in Java which has an object

List<GroupNavigationItemSRO> children

Now Every GroupNaviagationItemSRO has the same List

List<GroupNavigationItemSRO> children

NOw i want to iterate through every GroupNavigationSRO and populate a List of String . Currently i am trying to do that like this

void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){
        System.out.println("PRINT");
        for(GroupNavigationItemSRO item : items) {
            nitems.add(item.getUrl());
            System.out.println(item.getUrl());
           // g.add(item.getUrl());
            System.out.println("PRINT");
            List<GroupNavigationItemSRO> nextItem = item.getChildren();
            if (nextItem  != null && nextItem.size()>0) {
                getNavItems(nextItem,nitems);
            }
        }

    }

When i only print the objects ,it doesn't give any errors But as soon as i try and add to the List the recurssion stops

nitems.add(item.getUrl())

Why is this happening . Here's the entire java file in case its helpful

@Service("labelSearchService")
public class LabelSearchServiceImpl extends AbstractSearchService {
private static final String                version = SearchVersion.VERSION_2.getValue();

private static final Logger                LOG     = LoggerFactory.getLogger(LabelSearchServiceImpl.class);

private static final String          EXPIRY_SET        = "expiry";
private static final String          DATA_SET          = "data";

@Autowired
@Qualifier("searchServiceFactory")
private ISearchServiceFactory searchServiceFactory;

@Autowired
IAerospikeTopSellingBrandsCacheService topSellingBrandsCacheService;

@Autowired
private LabelSearchCacheServiceImplFactory labelSearchCacheServiceImplFactory;

@Autowired
AerospikeGuidedResponse aerospikeGuidedResponse ;

List<String> g = null;


@Override
public SearchSRO getSolrResponse(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer productCategoryId, int start, int number, String sortBy,
    String userZone, String vertical, String clickSrc, boolean isSpellCheckEnabled, String categoryURL, boolean isNested) throws SearchException, ShardNotFoundException, IllegalAccessException {
    String originalKeyword = searchTerm;

    searchTerm = SearchUtils.modifySearchTerm(searchTerm);
    SearchSRO sro = new SearchSRO();
    boolean isPartialSearch = SearchUtils.isPartialSearchEnabled();
    keyGenerator.setPartialSearch(SearchUtils.isPartialSearchEnabled());
    LabelNodeSRO labelNode = SearchUtils.getLabelNodeByNodePath(categoryURL);
    // for 'ALL' categories labelNode would be null.
    LOG.info("categoryURL : " + categoryURL);
    if (ALL.equals(categoryURL)) {
        if (number == 0 && !CacheManager.getInstance().getCache(SearchConfigurationCache.class).getBooleanProperty(SearchProperty.ALLOW_ZERO_RESULT_REQUESTS)) {
            return new SearchSRO();
        }
        sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchBinResultsForAllLabels(keyGenerator, queryFromBrowser, searchTerm, labelNode, start, number, sortBy, userZone, vertical,
                isPartialSearch, isSpellCheckEnabled, originalKeyword, false, isNested);
    } else if (labelNode != null) {
        sro = getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, null, null, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled,
                originalKeyword, isNested, false,categoryURL);
    } else {
        throw new SearchException("Search was hit without selecting any category");
    }

    // this is the minimum number to results that should match for results to be shown on 'people who search this bought this widget'

    SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class);

    if ((ClickSourceType.PWSTBT_WIDGET.getValue()).equalsIgnoreCase(clickSrc) && sro.getNoOfMatches() < cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)) {

        LOG.info("The minimum number of results to match for PWSTBT widget are " + cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)
                + " but number of matched results are " + sro.getNoOfMatches());
        sro = new SearchSRO();

    }

    return sro;
}

@Override
public SearchSRO getSolrResponseForMobile(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer productCategoryId, int start, int number,
        String sortBy, String userZone, String vertical, String clickSrc, boolean isBinSearch, int noOfResultsPerBin, boolean isSpellCheckEnabled, boolean isPartialSearch,
        String categoryURL) throws SearchException, ShardNotFoundException, IllegalAccessException {
    String originalKeyword = searchTerm;
    searchTerm = SearchUtils.modifySearchTerm(searchTerm);
    SearchSRO sro = new SearchSRO();
    isPartialSearch = isPartialSearch && SearchUtils.isPartialSearchEnabled();

    // this is to disable partial search in case of PWSTBT
    if (ClickSourceType.PWSTBT_WIDGET.getValue().equalsIgnoreCase(clickSrc)) {

        isPartialSearch = false;

    }
    LabelNodeSRO labelNode = SearchUtils.getLabelNodeByNodePath(categoryURL);
    // for 'ALL' categories labelNode would be null
    if (ALL.equals(categoryURL)) {
        if (number == 0 && !CacheManager.getInstance().getCache(SearchConfigurationCache.class).getBooleanProperty(SearchProperty.ALLOW_ZERO_RESULT_REQUESTS)) {
            return new SearchSRO();
        }
        // Response for Search result page in mobile - same as web.
        sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchBinResultsForAllLabels(keyGenerator, queryFromBrowser, searchTerm, labelNode, start, number, sortBy, userZone, vertical,
                isPartialSearch, isSpellCheckEnabled, originalKeyword, true, false);
    } else if (labelNode != null) {
        sro = getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, null, null, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled,
                originalKeyword, false, true,categoryURL);
    } else {
        throw new SearchException("Search was hit without selecting any category");
    }

    // this is the minimum number to results that should match for results to be shown on 'people who search this bought this widget'

    SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class);

    if ((ClickSourceType.PWSTBT_WIDGET.getValue()).equalsIgnoreCase(clickSrc) && sro.getNoOfMatches() < cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)) {
        LOG.info("The minimum number of results to match for PWSTBT widget are " + cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)
                + " but number of matched results are " + sro.getNoOfMatches());
        sro = new SearchSRO();
    }

    return sro;

}

@Autowired
private IUserPersonaSegmentService           personaSegmentService;

@Autowired
private IContextHolder<SearchRequestContext> ctxProvider;

private boolean isClientPersonaEnabled(SearchRequestContext ctx) {
    SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class);
    String clientsEnabled = cache.getProperty(SearchProperty.PERSONA_CLIENTS_ENABLED);
    String client = ctx.req.getContextSRO().getAppIdent();

    return !StringUtils.isEmpty(client) && !StringUtils.isEmpty(clientsEnabled) && Pattern.matches("(?i).*\\b" + client + "\\b.*", clientsEnabled);
}

protected UserSegmentDTO setupPersonalizationContext(LabelNodeSRO labelNode, String searchTerm, String sortBy) {
    SearchRequestContext ctx = ctxProvider.getContext();

    if (ctx == null || ctx.req == null) {
        LOG.warn("No Request Context found");
        return null;
    }

    SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class);

    // check if Personalization is enabled
    if (labelNode == null || !cache.getBooleanProperty(SearchProperty.PERSONA_SEARCH_ENABLED) || StringUtils.isEmpty(searchTerm)
            || !SolrSortCategory.RELEVANCY.getValue().equalsIgnoreCase(sortBy) || !isClientPersonaEnabled(ctx)) {
        LOG.debug("Personalization not enabled");
        return null;
    }

    LOG.info("Trying to set up personalization context");

    // setup the context for later use
    ctx.personaSegments = personaSegmentService.getUserSegments(ctx.req.getUserTrackingId(), labelNode.getNodePath());

    return ctx.personaSegments;
}

@Override
public SearchSRO getSearchProducts(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer campaignId, ProductCategorySRO pc, LabelNodeSRO labelNode,
        int start, int number, String sortBy, String userZone, boolean isPartialSearch, boolean isSpellCheckEnabled, String originalKeyword, boolean isNested, boolean isMobile,String categoryURL)
 throws SearchException, ShardNotFoundException, IllegalAccessException {
    LOG.info("------------------Product category page---------------");
    // build cache key considering campaign id
    keyGenerator.setCampaignId(String.valueOf(campaignId));
    // Search results will vary based on isNested flag even for exact same keywords hence, when we cache
    // we cache both results with different key
    keyGenerator.setNested(isNested);

    SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class);

    LOG.info("sortBy : " + sortBy + ", personalization Enabled : " + cache.getBooleanProperty(SearchProperty.PERSONA_SEARCH_ENABLED) + ", labelNode : " + labelNode);

    // try to set persona context
    keyGenerator.setPersonaSegment(setupPersonalizationContext(labelNode, searchTerm, sortBy));

    SearchSRO searchSRO = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, campaignId, pc, labelNode, start, number, sortBy, userZone, isPartialSearch,
            isSpellCheckEnabled, originalKeyword, isNested, isMobile,categoryURL);

    /*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext();

    if (coreContext != null) {
       if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) {
           String cacheKey = keyGenerator.buildKey();
           try {
               final AerospikeClient aClient = AerospikeClientFactory.getInstance();
               LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey);
               aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey));
               aClient.delete(null, new Key("search", DATA_SET, cacheKey));
           } catch (AerospikeException e) {
               e.printStackTrace();
           }
       }
    }*/
    return searchSRO;
}

@Override
public FilterListSRO getFiltersForProducts(Integer categoryId, Integer campaignId, String q, String keyword, boolean partialSearch, boolean isBrand, String categoryUrl,
        String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes, GetFiltersRequest request) throws SearchException, ShardNotFoundException {
    String key = new KeyGenerator(String.valueOf(categoryId), String.valueOf(campaignId), q, keyword, partialSearch, null, categoryUrl, version, userZone, hyperlocalCriteria, pinCodes).buildFilterKey();
    if (campaignId != null) {
        LOG.info("Get Filters for Campaign Products wrt : " + key);
    }

    FilterListSRO filterListSRO =  labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFiltersForProducts(key, categoryId, campaignId, q, keyword, partialSearch, isBrand, categoryUrl, userZone, hyperlocalCriteria, pinCodes,request);
    return filterListSRO;
}

@Override
public FilterListSRO getFiltersForProducts(Integer categoryId, Integer campaignId, String q, String keyword,
        boolean partialSearch, boolean isBrand, String categoryUrl, String userZone,
        HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes)
                throws SearchException, ShardNotFoundException {
    return getFiltersForProducts(categoryId, campaignId, q, keyword, partialSearch, isBrand, categoryUrl, userZone, hyperlocalCriteria, pinCodes,null);
}

@Override
public FilterListSRO getFilterValuesForFilter(String categoryId, String campaignId, String q, String keyword, boolean partialSearch, String filterName, String fullQ,
        String categoryUrl, String[] filtersToFetch, String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes) throws SearchException, NumberFormatException, ShardNotFoundException {
    String uniqueFilterKey = new KeyGenerator(categoryId, campaignId, q, keyword, partialSearch, filterName, categoryUrl, version, userZone, hyperlocalCriteria, pinCodes).buildFilterKey();
    String[] filterNames = filterName.split(",");
    FilterListSRO filterListSRO =  labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFilterValuesForFilter(uniqueFilterKey, categoryId, campaignId, q, keyword, partialSearch, filterNames, categoryUrl, filtersToFetch,
            userZone, hyperlocalCriteria, pinCodes);
    /*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext();
    if (coreContext != null) {
        if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) {
            String cacheKey = uniqueFilterKey.concat(".FilterSRO");
            try {
                final AerospikeClient aClient = AerospikeClientFactory.getInstance();
                LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey);
                aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey));
                aClient.delete(null, new Key("search", DATA_SET, cacheKey));
            } catch (AerospikeException e) {
                e.printStackTrace();
            }
        }
    }*/
    return filterListSRO;
}

@Override
public GroupNavigationSRO getGroupNavigation(KeyGenerator keyGenerator, String keyword, String q, String categoryUrl, Integer campaignId, boolean isSpellCheck, String userZone) throws IllegalAccessException {
    GroupNavigationSRO sro = new GroupNavigationSRO();
    try {
        ProductCategoryCache categoryCache = CacheManager.getInstance().getCache(ProductCategoryCache.class);

        LabelNodeSRO labelNode = ALL.equals(categoryUrl) ? null : categoryCache.getLabelForLabelPath(categoryUrl);

        if (!ALL.equals(categoryUrl) && labelNode == null) {
            LOG.error("Invalid label : " + categoryUrl);
            return null;
        }

        // try to setup persona context - using sort to relevancy since group left nav doesn't change with sortBy
        keyGenerator.setPersonaSegment(setupPersonalizationContext(labelNode, keyword, SolrSortCategory.RELEVANCY.getValue()));

        sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getGroupNavigation(keyGenerator, keyword, q, categoryUrl, campaignId, isSpellCheck, userZone);

        /*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext();

        if (coreContext != null) {
            if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) {
                String cacheKey = keyGenerator.buildKey().concat(".GroupNavigationSRO");
                try {
                    final AerospikeClient aClient = AerospikeClientFactory.getInstance();
                    LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey);
                    aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey));
                    aClient.delete(null, new Key("search", DATA_SET, cacheKey));
                } catch (AerospikeException e) {
                    e.printStackTrace();
                }
            }
        }*/

    } catch (SearchException e) {
        LOG.error("Error in fetching GroupSRO: ", e);
    }
    return sro;
}

@Override
public QueryResponse setCategoryFilterQueryAndExecute(SearchCriteria sc, Integer id) throws SearchException {
    labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().setCategoryFilterQuery(sc, id);
    return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().executeQuery(sc.buildQuery(), id);
}

@Override
public Long getProductCategoryCount(Integer categoryId, String categoryUrl) {
    Long count = CacheManager.getInstance().getCache(ProductCategoryCache.class).getCategoryCountByUrl(categoryUrl);
    if (count == null) {
        count = new Long(0);
    }
    LOG.info("Product Category Counts for CategoryUrl: " + categoryUrl + " = " + count);
    return count;
}

@Override
public List<TopSellingProductCategorySRO> getTopSellingProductsforCategories(List<Integer> categoryIds, List<String> categoryUrls) {
    List<TopSellingProductCategorySRO> topSellingProductCategorySROs = new ArrayList<TopSellingProductCategorySRO>();
    for (String categoryUrl : categoryUrls) {
        try {
            TopSellingProductCategorySRO topSellingProductCategorySRO = null;
            Integer searchId = ShardResolverService.getSearchIdByLabel(categoryUrl);
            QueryResponse rsp = searchServiceFactory.getSearchService(SearchVersion.VERSION_2.getValue()).getTopProductsInfoById(searchId,
                    CacheManager.getInstance().getCache(SearchConfigurationCache.class).getIntegerProperty(SearchProperty.MAX_TOP_SELLING_PRODUCTS_PER_CATEGORY));
            List<Long> pogIds = SearchUtils.extractTopProductsByCategoryId(rsp);
            if (pogIds != null && !pogIds.isEmpty()) {
                topSellingProductCategorySRO = new TopSellingProductCategorySRO(categoryUrl, pogIds);
                topSellingProductCategorySROs.add(topSellingProductCategorySRO);
            }
        } catch (Exception e) {
            LOG.error("Unable to get Top Selling Products for categoryId: " + categoryUrl + ", Exception:" + e.getMessage());
        }
    }
    return topSellingProductCategorySROs;
}

@Override
public List<TopSellingBrandSRO> getTopSellingBrandsforCategories(List<Integer> categoryIds, List<String> categoryUrls) {
    List<TopSellingBrandSRO> topSellingBrandSROs = new ArrayList<TopSellingBrandSRO>();
    for (String categoryUrl : categoryUrls) {
        TopSellingBrandSRO topSellingBrandSRO = topSellingBrandsCacheService.getTopSellingBrandsByUrl(categoryUrl);
        if (topSellingBrandSRO != null) {
            topSellingBrandSROs.add(topSellingBrandSRO);
        }
    }
    return topSellingBrandSROs;
}

@Override
public List<TopSellingBrandSRO> getAllTopSellingProducts(){
    List<TopSellingBrandSRO> topSellingBrandSROs = topSellingBrandsCacheService.getAllTopSellingProducts();
    return topSellingBrandSROs;
}

@Override
public FacetSRO getFacets(String cachekey, String keyword, String queryFieldName, String[] facetFields, Map<String, List<String>> filterMap, int number) throws SearchException {

    // update values for mainCategoryXpath & categoryXpath fields
    /*if(SolrFields.CATEGORY_XPATH.equals(queryFieldName) || SolrFields.MAIN_CATEGORY_XPATH.equals(queryFieldName)) {
        String labelPath = SearchUtils.getLabelPathByUrl(keyword);
        keyword = String.valueOf(ShardResolverService.getSearchIdByLabel(labelPath));
    }*/
    for (String filterField : filterMap.keySet()) {
        if (SolrFields.CATEGORY_XPATH.equals(filterField) || SolrFields.MAIN_CATEGORY_XPATH.equals(filterField)) {
            List<String> searchIds = new ArrayList<String>();
            for (String val : filterMap.get(filterField)) {
                String labelPath = SearchUtils.getLabelPathByUrl(val);
                searchIds.add(String.valueOf(ShardResolverService.getSearchIdByLabel(labelPath)));
            }
            filterMap.put(filterField, searchIds);
        }
    }
    return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFacets(cachekey, keyword, queryFieldName, facetFields, filterMap, number);
}

@Override
public FilterListSRO getSRPFilters(KeyGenerator keyGenerator, String q, String keyword, boolean partialSearch, String categoryUrl, String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes) throws SearchException {
    if (StringUtils.isEmpty(keyword)) {
        LOG.error("Invalid parameters.");
        return null;
    }
    keyword = SearchUtils.modifySearchTerm(keyword);
    if (StringUtils.isEmpty(keyword)) {
        LOG.info(" Returning empty filters for empty keyword.");
        return new FilterListSRO();
    }
    return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSRPFilters(keyGenerator.buildKey(), q, keyword, partialSearch, categoryUrl, userZone, hyperlocalCriteria, pinCodes);
}

@Override
public SearchSRO getSearchProducts(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm,
        Integer campaignId, ProductCategorySRO pc, LabelNodeSRO labelNode, int start, int number, String sortBy,
        String userZone, boolean isPartialSearch, boolean isSpellCheckEnabled, String originalKeyword,
        boolean isNested, boolean isMobile) throws SearchException, ShardNotFoundException, IllegalAccessException {
    // TODO Auto-generated method stub
    return getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, campaignId, pc, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled, originalKeyword, isNested, isMobile, null);
}

@Override
public String getmodelSearch(String query, String type) throws SearchException {

    return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getmodelSearch(query, type);
}

@Override
public String classifierResponse(String query, String type) throws SearchException {
    try {
        return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getClassifierResponse(query, type);
    } catch (JsonGenerationException e) {
        return e.getMessage();
    } catch (JsonMappingException e) {
        return e.getMessage();
    } catch (IOException e) {
        return e.getMessage();
    }
}

public GetGuidedSearchResponse getGuides(String query, String url) {

    if(!StringUtils.isEmpty(query) && !StringUtils.isEmpty(url) && url.equalsIgnoreCase("ALL"))
    {
        KeyGenerator keyGenerator = new KeyGenerator();
        keyGenerator.setQ("sNapDeAl.sEarcH.getGuides=" +"##"+ query+ "##"+ url);
        return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getGuides(keyGenerator, query, url);
    }   
    return null;
}   

public GetGuidedSearchResponse getFilteredGuides(String query ,GetGroupLeftNavResponse leftNavBarResponse) {    
    g=null;
    GroupNavigationSRO groups = leftNavBarResponse.getGroups();
    List<GroupNavigationItemSRO> items = groups.getItems() ;
//  List<String> nitems = getNavItems(items);
    List<String> nitems = null;
    getNavItems(items,nitems);
    System.out.println("SIZE" + nitems.size());
    List<String> navItems = new ArrayList<String>();
    System.out.println("GETTING GUIDED FILE FROM AEROSPIKE");
    List<String> guideItems = aerospikeGuidedResponse.getGuides(query);
    //HashMap<String,String> nodeUrlMapping = new HashMap<String,String>();
    if(guideItems.isEmpty())
    {
        System.out.println("\n\n\n\n" + "EMPTY GUIDED" + " \n\n\n\n\n");
    }
    guideItems.set(0, guideItems.get(0).trim());
    System.out.println("GUIDED RESPONSE");
    for(int i=0 ; i < guideItems.size() ;i ++)
    {
        System.out.println(guideItems.get(i));

    }
    /*for (int i =0 ;i < items.size() ;i++) {
        List<GroupNavigationItemSRO> children_items = items.get(i).getChildren();
        String s = items.get(i).getNodePath();
        String m = items.get(i).getUrl();
        System.out.println(s + "    " +  m);
        navItems.add(m);
        //nodeUrlMapping.put(s,m);
        for (int j=0;j<children_items.size();j++) { 
            String r = children_items.get(j).getNodePath();
            String n = children_items.get(j).getUrl();
            System.out.println(r +"    " +  n);
        //  nodeUrlMapping.put(r,n);
            navItems.add(n);
        }


    }*/
    System.out.println("ITEM RESPONSE");
    //navItems = g ;
    for(int i=0 ; i < navItems.size() ;i ++)
    {
        System.out.println(navItems.get(i));

    }
    List<String> filteredGuides = new ArrayList<String>();

    for(int i=0 ; i < guideItems.size() ;i++)
    {
        if(navItems.contains(guideItems.get(i)))
            filteredGuides.add(guideItems.get(i));
        else {

        }

    }
    System.out.println("NAV ITEMS" + navItems.size() + navItems.toString());
    System.out.println("GUIDE ITEMS" + filteredGuides.size() + filteredGuides.toString());
    List<WidgetEntity> entities = new ArrayList<WidgetEntity>();
/*  Iterator it = nodeUrlMapping.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
    }*/
    for(int i=0;i<filteredGuides.size();i++)
    {
        String guide = filteredGuides.get(i);
        guide = guide.trim();
        System.out.println(guide);
        LabelNodeSRO labelSRO = getLableSRO(guide);
        System.out.println(labelSRO.toString() + guide);
        WidgetEntity entity = new WidgetEntity();
        entity.setId(labelSRO.getUrl());
        entity.setName(labelSRO.getDisplayName());
        entity.setType("category");
        entities.add(entity);

    }
    System.out.println("ENTITIES DEtails" );
    GetGuidedSearchResponse response = new GetGuidedSearchResponse();
    for(int i =0 ;i<entities.size();i++)
    {
        System.out.println(entities.get(i).getId() + entities.get(i).getName() + entities.get(i).getType());
    //  System.out.println(nodeUrlMapping.get(entities.get(i).getId()));
    }
    response.setEntities(entities);
    return response;

}
LabelNodeSRO getLableSRO(String guide)
{
    System.out.println(guide + "GET");
    LabelNodeSRO label =SearchUtils.getLabelNodeByNodePath(guide);
    return label;


}

void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){
    System.out.println("PRINT");
    for(GroupNavigationItemSRO item : items) {
        nitems.add(item.getUrl());
        System.out.println(item.getUrl());
       // g.add(item.getUrl());
        System.out.println("PRINT");
        List<GroupNavigationItemSRO> nextItem = item.getChildren();
        if (nextItem  != null && nextItem.size()>0) {
            getNavItems(nextItem,nitems);
        }
    }

}

}