mercredi 26 avril 2017

C# giving System.NullReferenceException even though im trying to assign a value [duplicate]

This question already has an answer here:

Even though i have initialised dataList1, it keeps throwing up

System.NullReferenceException

when i try to assign values to its variables.

Does anybody have any idea why this might be?

Thanks in advance.

        var dataList1 = new classX[600];
        int count = 0;

        foreach (string line in File.ReadLines("test1.txt"))
        {
            dataList1[count].setDay(line);
            count++;
        }




Virtual functions with different argument types

Trying to understand how virtual functions work and got stuck at a certain part. I have written a small programm:

class First
{
public:
virtual void f(int a) 
{
    cout << "First!" << endl;
    cout << a << endl;
}
};
class Second:public First
{
public:
void f(int a) {
    cout << "Second!" << endl;
    cout << a << endl;
}
};
void main() {
Second s;
First *p = &s;
p->f(5);
First n;
p = &n;
p->f(3);
_getch();
}

This code results in:

Second!

5

First!

3

However , once i change int at the f function of the Second class to a different type , like this:

class First
{
public:
virtual void f(int a) {
    cout << "First!" << endl;
    cout << a << endl;
}
};
class Second:public First
{
public:
void f(double a) { //double instead int here!
    cout << "Second!" << endl;
    cout << a << endl;
}
};
void main() {
Second s;
First *p = &s;
p->f(5);
First n;
p = &n;
p->f(3);
_getch();
}

My programm never uses f function from the second class and im getting this as a result:

First!

5

First!

3

Can someone explain me why this happens?




repeatedly remove items from list in class-object (Python)

How can I remove items from a list repeatedly in Python 3 ? For the first item my code works, but if I try to apply the method that removes items again it produces a TypeError. Here is the code that I am working with:

BlackJack Game

from random import choice




class Black_jack_deck(object):



def __init__(self,full_deck=(([str(i) for i in range(2,11)]+["A","J","Q","K"])*4*6)): #a deck of 312 cards containing 6* 52 french cards

    self.full_deck = full_deck


def draw(self,draw=True):

    self.draw = choice(self.full_deck)   #I use choice to simulate the dealer drawing a card from the top of a mixed card staple
    return self.draw
    self.full_deck = (self.full_deck).remove(self.draw)   


deck=Black_jack_deck() 

The error that is produced when I try to call deck.draw() for a second time looks like this:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    deck.draw()
TypeError: 'str' object is not callable

Note: even without the choice() function, for instance using pop() on a shuffled full_deck, the same error occurs.




Method Resolution Order for Classes in Python 3.5 Tkinter

I'm working on a little image manipulation program by using the Python 3.5 tkinter toolkit. This GUI uses classes, each class for one page/window, with Buttons to go from one page/class to another. My problem is, that I prompt the user to specify the image path in one page("path class") and than need this image to display in the canvas in another page ("canvas class"). Since both classes are pages, both inherit from the Tk.Frame class, but the canvas class also need to inherit the path from the path class. Here is the complete code (with IMPORTANT LINES), without any inheritances:

import tkinter as tk
from PIL import ImageTk

class MainClass(tk.Tk):
    # the MainClass class inherits from the Tk class in the tk module
    def __init__(self, *arg, **kwargs):
        tk.Tk.__init__(self, *arg, **kwargs)
        self.mainframe = tk.Frame(self)
        self.mainframe.pack(side="top", fill="both", expand=True)

        self.allframes = {}  # the allframes dictionary stores all frames

    for frame in (PathClass, CanvasClass):
        '''this for loop consists of all windows in the application'''
        self.specific_frame = frame(self.mainframe, self)

        self.allframes[frame] = self.specific_frame

        self.specific_frame.grid(row=0, column=0, sticky="nsew")
    self.show_frame(PathClass)

def show_frame(self, cont):
    self.specific_frame = self.allframes[cont]
    self.specific_frame.tkraise()

class PathClass(tk.Frame):  ###IMPORTANT LINE

def __init__(self, parent, controller): ###IMPORTANT LINE
    tk.Frame.__init__(self, parent)   ###IMPORTANT LINE

    self.input_frame = tk.Frame(self)
    self.input_frame.pack(side="top")

    global pic_path
    self.pic_path = tk.Entry(self.input_frame) ### here the PATH is pasted in
    self.pic_path.pack(side="left")

    self.uploadbutton = tk.Button(self.input_frame,
                                  command=lambda: controller.show_frame(CanvasClass()))
    self.uploadbutton["text"] = "Upload"
    self.uploadbutton.pack(side="right")

class CanvasClass(tk.Frame):   ###IMPORTANT LINE

def __init__(self, parent, controller):   ###IMPORTANT LINE
    tk.Frame.__init__(self, parent)   ###IMPORTANT LINE

    self.canvas_frame = tk.Frame(self)
    self.canvas_frame.config(width=1200)
    self.canvas_frame.pack(side="top")

    global imagex
    ### here the path is needed
    self.imagex = ImageTk.PhotoImage(file=self.pic_path.get())
    self.photocanvas = tk.Canvas(self.canvas_frame)
    self.photocanvas.create_image(self.imagex.width()/2, self.imagex.height()/2,
                                  anchor="center", image=self.imagex)
    self.photocanvas.config(width=500, height=500)
    self.photocanvas.pack(side="left")

application = MainClass()
application.mainloop()

ERROR CODE: 'CanvasClass' object has no attribute 'pic_path'

Here are the IMPORTANT LINES again with the inheritances:

class PathClass(tk.Frame):

   def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)

class CanvasClass(tk.Frame, PathClass):

   def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)

ERROR CODE: TypeError: Cannot create a consistent method resolution order (MRO) for bases PathClass, Frame

Again the IMPORTANT LINES with the super() function for multiple inheritance:

class PathClass(tk.Frame):

def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    super(PathClass, self).__init__()

class CanvasClass(tk.Frame, PathClass):

   def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    super(CanvasClass, self).__init__()

ERROR CODE: TypeError: Cannot create a consistent method resolution order (MRO) for bases PathClass, Frame

If the inheritance order is changed in the CanvasClass, I get a grid Error.

class PathClass(tk.Frame):

def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    super(PathClass, self).__init__()

class CanvasClass(PathClass, tk.Frame):

   def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    super(CanvasClass, self).__init__()

ERROR: tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack

When I change the grid to a pack(), I get a TypeError for super(CanvasClass, self).init() --> TypeError: init() missing 2 required positional arguments: 'parent' and 'controller'




List of classes in an assembly C# [on hold]

I want to get the list of classes in an assembly, as an output i want a List[Interface] not a List[string], as "Interface" is the interface from which inherits the classes of my assembly. I don't know if my question makes sense but if any one has the answer i would very much thankful. I already tried this solution: List of classes in an assembly, but it gives a list[string] containing the classes namesso it didn't help because i need the list of the classes that inherits from my interface. Thank you and have a nice day all :)

As an edit for my question, I used activator.createinstance(type t) to create instances of my classes so here is the code :

   Assembly assembly = typeof(Interface1<double, double>).Assembly;

   List<Interface> classes = new List<Interface>();

   foreach (Type type in assembly.GetExportedTypes())

   {
      var Attributes = type.GetCustomAttributes<FilterAttribute>();
      //select the classes with attribute [Filter]

      if (Attributes.Any())

      {
                TypeOfFilters.Add(type);

      }

      foreach (var i in TypeOfFilters)

      {
            var inst = Activator.CreateInstance(i);

            Classes.Add((Interface) inst);


      }

   }

i get the error "System.IO.FileNotFoundException : Could not load file or assembly"




multithreading class vs methods

I'm starting to write a program that uses threads but after searching how to start threads in Python I have found two methods that accomplish the same thing. There must be a difference or advantage one over the other. Confused which road I should go down.

My thread is going to be ran in the background continuously and never stop until the program is told to by the user. Also one or more arguments will be passed to the thread when started.

one way using classes:

from threading import Thread

class myClassA(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()
    def run(self):
        while True:
            print 'A'

myClassA()
while True:
    pass

Second way using methods:

from threading import Thread

def runA():
    while True:
        print 'A\n'

if __name__ == "__main__":
    t1 = Thread(target = runA)
    t1.setDaemon(True)
    t1.start()
    while True:
        pass




How do I add classes in C++?

**Below is my header file. In my main.cpp file I need to make three instances of Student and add them to the Course object. How is this done? I can't seem to find the answer in any textbook or online. Then I need to Instantiate at least one Teacher object. Then add that Teacher object to my Course object.

How might I do all these things? Thanks.**

  #pragma once


 class Student : Course{

private:
   std::string firstName;
   std::string lastName;
   int age;
   std::string address;
   std::string city;
    std::string phone;
public
  Student()=default;
    std::string getFirstName();
    void setFirstName(std::string name_two);
    std::string getLastName();
    void setLastName(std::string name_two);
    std::string getAddress();
    void setAddress(std::string address);
    int getAge();
    int setAge(age2);
    void getCity();
std::string setCity(city2);
void getPhone();
std::string setPhone();
void GradeStudent();
std::string SitInClass();
~Student();

};

     class Teacher : Course{


      private:
 std::string firstName;
std::string lastName;
int age;
std::string address;
std::string city;
std::string phone;
    public
Teacher()=default;
std::string getFirstName();
void setFirstName(std::string name_two);
std::string getLastName();
void setLastName(std::string name_two);
 std::string getAddress();
void setAddress(std::string address);
int getAge();
int setAge(age2);
void getCity();
std::string setCity(city2);
void getPhone();
std::string setPhone();
void GradeStudent();
std::string StInClass();
~Teacher();

};




C# pass a class as a parameter that allows for constructor of class to run

I am trying to create a method that is commonly used by multiple classes. I need to pass the class to the method and create a new instance of the class so the constructor of the class can be ran.

When I pass in the class to the below method I get this error:

Following exception occured No parameterless constructor defined for this object.

The method:

    public string GetCellTextByColumnHeaderAndRowIndex(string dataIndex, int rowIndex, IWebElement gridElement, Type yourPage)
    {

        object created = Activator.CreateInstance(yourPage);


        var element = driver.FindElements(By.XPath("//*[contains(text(),'Loading...')]"));
        foreach (IWebElement item in element)
        {
            WaitIWebElementNotVisible(item);
        }

        int colIndex = gridColumnIndex[dataIndex];

        RemoteWebElement currentEventItemCell =
            (RemoteWebElement)
            gridElement.FindElements(
                By.CssSelector("tr[data-recordindex=\"" + rowIndex + "\"] td:nth-child(" + colIndex + ")"))[0];
        var ScrollIt = currentEventItemCell.LocationOnScreenOnceScrolledIntoView;
        return currentEventItemCell.Text;
    }

I need the constructor of each class that is passed into this method to run so it will cache information that is later used in unit tests. I have seen quite a few different ways besides the above but they are partial answers and I'm just not proficient enough in C# to get it to work




why does 'getline' initialize the info?

while (!fin.eof())
{
    fin.getline(read, 49); subcnt++;    
    i_sequence = subcnt;                
    i_name = my_tok(read, "/");         
    i_price = atoi(my_tok(NULL, "/"));  
    i_quantity = atoi(my_tok(NULL, "/"));

    if (subcnt <= 10)
        loadlist[subcnt-1].setList(i_sequence, i_name, i_price, i_quantity);

}

my_tok is a function which I made to use instead of 'strtok'. loadlist is the class object which contains information of an item.

I want this codes to read information line by line from .txt file, and save written information to class object 'loadlist'. first loop is implemented as I want, but when it comes to the next loop and fin.getline(read,49) is called, all the info that previously saved is initialized. I have no idea why the information is continuously changing when fin.getline is called. Please help me..!




How call result of a function in another function in a class?

I have a code like this, in Python 2.7 :

class app(Object)
    def function1(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

    def function2(self):
        print(x, y)

app.function1("x", "y")
app.function2()

When function2 is calling I have a error message : global name x, y not define.

I try to put

x.get(); y.get()

in function2 but have the same error.

I try to put

return arg1, arg2

in function1 but have the same issue.

How call result of a function in another function in a class ?




Delphi paramter of type X must support interface Y

Howwwdy,

I have a setup like so :

IBuilder = interface(IInvokable)
end;

IBuilder<T; TOut> = interface(IInvokable)
end;

TBuilder<T: IBuilder; TOut> = class(TInterfacedObject, IBuilder, IBuilder<T, TOut>)
end;

TBuilder = class(TBuilder<TBuilder, TObject>)
end;

But in this case, I get a compilation error, saying that TBuilder must support interface IBuilder. This is probably due to the typed constraint T: IBuilder, even though TBuilder does support IBuilder (trough it's ancestor).

Can anyone please direct me on how to get around this?

Though, I cannot use TBuilder = class(TBuilder<IBuilder, TObject>)

This kind of structure allows me to build a sugar syntax like so :

TBuilder<T : IBuilder; TOut> = class(TInterfacedObject, IBuilder, IBuilder<T, TOut>)

  function Output : TOut;
  function Name(aName : string) : T;
  function Left(aLeft : Integer) : T;
  function Top(aTop : Integer) : T;

end;


// ... later

TBuilder.Create().Left(10).Top(5).Name('ABC'); // Nice one liner




How to send mail via java maven application

I'm using maven to devlop an application, I'm using Eclipse as an IDE, I'm running a Mapview Class as output, My problem is how I send the output ( which is on Mapview Form) by mail? Thank you




KeyError:

Hi this chemistry quiz has a series of pages where it will switch between those frames. I dont know why am i getting this error?(With my show frame of Stage 1 )

class STARTPAGE(tk.Frame):
def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)


    Instructions1 = tk.Label(self, text = ("You will obtain a Desired Product that is chosen randomly from a Starting Reactant."))                                                      
    Instructions2 = tk.Label(self, text = ("You get 3 Attempts to complete the question in which Points will be added to your score "))
    Instructions3 = tk.Label(self, text = ("After 3 attempts you will be moved onto next stage or question"))
    Instructions4 = tk.Label(self, text = ("You need to select one Reagent and 1 or 2 Conditions to complete stage"))
    Instructions5 = tk.Label(self, text = ("Your score will be ranked among others in your same class in a leaderboard"))

    Instructions1.grid(row = 0, column = 0)
    Instructions2.grid(row=1,column=0)
    Instructions3.grid(row=2,column=0)
    Instructions4.grid(row=3,column=0)
    Instructions5.grid(row=4,column=0)

    StartQuiz = tk.Button(self, text = "Start Quiz", command=lambda: controller.show_frame(STAGE1))
    StartQuiz.grid(row=8,column=1)

class STAGE1(tk.Frame):
 def __init__(self,parent, controller):
    tk.Frame.__init__(self, parent)
    self.controller = controller

    Stage1 = tk.Label(self, text = "STAGE 1")
    Stage1.grid(column=1,row=0)          

#Explain the Main class and tk frame constructor in each class from stack overflow
self.ButtonData = BUTTONDATA(self,tk.Frame)

    self.ButtonData.ReagentOption1.config(command=lambda: self.AllocatePointsStage(1))
    self.ButtonData.ReagentOption2.config(command=lambda: self.AllocatePointsStage(1))
    self.ButtonData.ReagentOption3.config(command=lambda: self.AllocatePointsStage(1))
    self.ButtonData.ReagentOption4.config(command=lambda: self.AllocatePointsStage(1))

    self.ButtonData.ConditionOption1.config(command=lambda: self.AllocatePointsStage(1))
    self.ButtonData.ConditionOption2.config(command=lambda: self.AllocatePointsStage(1))
    self.ButtonData.ConditionOption3.config(command=lambda: self.AllocatePointsStage(1))
    self.ButtonData.ConditionOption4.config(command=lambda: self.AllocatePointsStage(1))

    self.ButtonData.ReagentOption1.grid(column = 2,row = 5)
    self.ButtonData.ReagentOption2.grid(column = 2,row = 6)
    self.ButtonData.ReagentOption3.grid(column = 2,row = 7)
    self.ButtonData.ReagentOption4.grid(column = 2,row = 8) 

    self.ButtonData.ConditionOption1.grid(column = 10,row = 5)
    self.ButtonData.ConditionOption2.grid(column = 10,row = 6)
    self.ButtonData.ConditionOption3.grid(column = 10,row = 7)   
    self.ButtonData.ConditionOption4.grid(column = 10,row = 8)

    self.Continue = tk.Button(self, text = "Continue", command=lambda: controller.show_frame(Stage2))
    self.Continue.grid(column = 6)

    self.QuestionStarter = QUESTIONSTARTER(self,tk.Frame)
    self.QuestionStarter.PointsLabel.grid(row=0,column=6)
    self.QuestionStarter.AttemptsDisplayed.grid(row=1,column=7)
    self.QuestionStarter.WordedQuestion.grid(row=0,column=1)
    self.QuestionStarter.AttemptsDisplayedText.grid(row=1,column=8)
    DesiredProductLabel = tk.Label(self,command=lambda: ShowDesiredProduct(DesiredProduct))
    DesiredProductLabel.grid(row=5,column=0)

 def ShowDesiredProduct(self,DesiredProduct):
    DesiredProduct = GetDesiredProduct()
    return DesiredProduct
class Main(tk.Tk):
def __init__(self, *args, **kwargs):
    tk.Tk.__init__(self, *args, **kwargs)
    tk.Tk.wm_title(self, "Chemistry Quiz")
    container = tk.Frame(self)
    container.pack(side="top", fill="both", expand=True)
    container.grid_rowconfigure(0, weight=1)
    container.grid_columnconfigure(0, weight=1)
    self.frames = {}

    for F in (STUDENTLOGINPAGE,STAFFLOGINPAGE,STARTPAGE,ASSIGNMENTPAGE,STAGE1,STAGE2,STAGE3,STAGE4,STAGE5,LEADERBOARDPAGE):

        frame = F(container, self)

        self.frames[F] = frame

        frame.grid(row = 0, column = 0, sticky = "nsew")

        self.show_frame(STUDENTLOGINPAGE)
        if self.frames == []:
            print ("Error in loading program")

#This class inherits from Tk class within module of Tk Inter #This basically displays each page in turn from the List

def show_frame(self, cont):
    frame = self.frames[cont]
    frame.tkraise() 

def get_page(self,page_class):
    return self.frames[page_class]

Error -Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/init.py", line 1549, in call return self.func(*args) File "/Users/ammarhusain/Desktop/Computing Project/Ammar Chemistry Program FINAL.py", line 316, in StartQuiz = tk.Button(self, text = "Start Quiz", command=lambda: controller.show_frame(STAGE1)) File "/Users/ammarhusain/Desktop/Computing Project/Ammar Chemistry Program FINAL.py", line 3152, in show_frame frame = self.frames[cont] KeyError:




Matching class by enum

Hi I have an abstract class Item. Classes like Food, Weapon, etc inherit by this class. All informations about this items are stored in the database, work of C# Code is match the exact class and match it by Enum which is also stored in the database column as integer. My problem is this stupid code wherever I have to use methods of Food, Weapon etc classes

if ((ItemType)userItem.ItemType == ItemType.Food)
{
    Food food = new Food(userItem);
    food.UseItem(sender);
}
else if ((ItemType)userItem.ItemType == ItemType.Weapon)
{
    Weapon weapon = new Weapon(userItem);
    weapon.UseItem(sender);
}

In the parameter of constructor of Food, Weapon etc. classes is the the object from database to let know object about its fields.

Is some kind of stuff that will help me to match this types without this code? It really annoys me when I'm looking at it.




Counting created objects over 2 different classes leads to problems

I want to count created objects. If I do this with one class it is easy, but I want count objects from 2 different classes with 2 different counters interacting with each other. Simplified example:

template <class Obj>
class Counter1
{
    private: 
        static int total1;
    public:
        Counter1(){++total1;}
        .. destuctor, copy constructor ..
       static int getCounter1() {return total1;}
       static void setCounter1(int var) {total1 = var;}
};
template<class Obj> int Counter1<Obj>::total1(0);

template <class Obj>
class Counter2
{
    private: 
        static int total2;
    public:
        Counter2(){++total1;}
        .. destuctor, copy constructor ..
       static int getCounter2() {return total2;}
       static void setCounter2(int var) {total2 = var;}
};
template<class Obj> int Counter2<Obj>::total2(0);

class Test1 : private Counter1<Test1>
{
 .. some code ..
};
Test1::Test1() : Counter1()
{
   int tmp_var;
   tmp_var = Counter2<int>::getCounter2();
}

Sadly tmp_var never gets a valid number. What am I doing wrong?




ClassName::class vs 'ClassName' in PHP

In one of my projects we are having a function which validates objects like:

if( true == valObj( $someObj, 'SomeClass' ) ) {
    //Do some work;
}

While using this I thought this can be written like:

if( true == valObj( $someObj, SomeClass::class ) ) {
    //Do some work;
}

Now I just want to know which approach is better and why? Or are they same?




How to link multiple python classes in a separate main python file?

I'm creating a small Python-MySQL application using peewee (ORM). My code works perfectly in a single file, as follows:

import os

from peewee import *
from playhouse.db_url import connect

# Connect to the database URL defined in the environment, falling
# back to a local MySql database if no database URL is specified.
db = connect(os.environ.get('DATABASE') or 'mysql://testdb:testdb@127.0.0.1:3306/db')

db.connect()

class Users(Model):
    users_id = PrimaryKeyField()
    username = CharField()
    password = CharField()
    mobile_number = CharField()
    created_at = DateTimeField()
    updated_at = DateTimeField()

    class Meta:
        database = db

class User_profiles(Model):
    users_id = IntegerField()
    user_profiles_id = PrimaryKeyField()
    profile_name =  CharField()
    address = CharField()
    created_at = DateTimeField()
    updated_at = DateTimeField()    

    class Meta:
        database = db

Users.create(username = "Adam", password = "Dummy1", mobile_number = "1234567891")
User_profiles.create(users_id=4,profile_name="shop", address="Delhi")

Users & Userprofiles are models as defined using peewee. I'm able to create entries using these models in a single file.

Now I am trying to split it into 3 files: main.py, users.py,userprofiles.py main.py - main file which should call users.py and userprofiles.py

My main.py

import os

from peewee import *
from playhouse.db_url import connect

# Connect to the database URL defined in the environment, falling
# back to a local MySql database if no database URL is specified.
db = connect(os.environ.get('DATABASE') or 'mysql://testdb:testdb@127.0.0.1:3306/db')

db.connect()
Users.create(username = 'testname', password = '@88@@', mobile_number='1234567811'):

My users.py:

import os

from peewee import *
from playhouse.db_url import connect

# Connect to the database URL defined in the environment, falling
# back to a local MySql database if no database URL is specified.
# db = connect(os.environ.get('DATABASE') or 'mysql://testdb:testdb@127.0.0.1:3306/db')

db.connect()

class Users(Model):
    users_id = PrimaryKeyField()
    username = CharField()
    password = CharField()
    mobile_number = CharField()
    created_at = DateTimeField()
    updated_at = DateTimeField()

    class Meta:
        database = db

My userprofiles.py:

import os

from peewee import *
from playhouse.db_url import connect

# Connect to the database URL defined in the environment, falling
# back to a local MySql database if no database URL is specified.
# db = connect(os.environ.get('DATABASE') or 'mysql://testdb:testdb@127.0.0.1:3306/db')

db.connect()

class Users(Model):
    users_id = PrimaryKeyField()
    username = CharField()
    password = CharField()
    mobile_number = CharField()
    created_at = DateTimeField()
    updated_at = DateTimeField()

    class Meta:
        database = db

How do I import users.py and userprofiles.py in main.py to perform actions inside main.py using peewee?

I'm a newbie in coding. Getting started with Python




Angular 4/Ionic3 production build changes components classname

When running a production build of my app I noticed that the classes names changed. For example, a page component called "Search" changed to "t". This breaks my app because I need to identify the component by It's name in some place.

How could I retrieve the real name of the classes?




c++ How to get acces of function that is in parent class?

I have class Books and child class BookClient.

In class Books their is function that calculates age of book:

int age()
{return 2017 - getage();}

I want function that prints books that are >5 age.

I am using range-based for loop to access the vec.

vector <BookClient> vec;

void printageover5(string publisher)
{
    for (const auto& cs : vec)
    if (cs.age() > 5 && getpublisher()=publisher)
    {
        ..........
    }
}

int main()
{
printageover(Amazon);
}

getpublisher() is member of class

And their is the error:

the object has type qualifiers that are not compatible with the member function
 object type is: const  Books 




JavaFx Change main class to another main class (seperate class)

I'm new to JavaFx and have to create a small game. My JavaFx classes works fine but I can't figure out have to change between them. I created a package in eclipse where I have all the display classes (Menu screen class, lauding Screen class, Game display...). Every classes has their main and display fine. But now I can't change from one class to another class. Like from Start menu to game display. I tried initiating the game display class in the menu class and then setScene to game display's scene but it does not work. I'm also confused with either I have to change from stage, scenes or panes.

@Override
    public void start(Stage primaryStage) throws Exception {
        stage = primaryStage;
        scene = new Scene(createContent());
        primaryStage.setTitle("Menu Screen");
        primaryStage.setScene(scene);


        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

2nd Class:

@Override
    public void start(Stage primaryStage) throws Exception {

        primaryStage.setTitle("Bucanneer");

        // Setting up Stage, Scene and root
        // Group root = new Group();
        theScene = new Scene(createContent());
        primaryStage.setScene(theScene);
        primaryStage.setResizable(true);
primaryStage.show();

    }

Last try: I put this in the menu class when you press a button

private void backToMenu(){
        Test test = new Test();
        stage.setScene(test.getTheScene());
    }

Any advice plz, all I can find are with FXML.. Ps: Sorry for bad english. Not my native language.




No main class detected

The problem is that when I open "cmd.exe" and go to the directory called chesschallenge6 to enter "sbt" command and "run" afterwards it doesn't work. I get an error message saying there is no main class specified. I checked if the main class name is the same as its file name and even tried "object ChessChallenge6 extends App" but it still didn't work. The solution is simple but I just don't see it.

├── _chesschallenge6
├── _project
├── _target
└── _src      
    ├── _test
    └── _main
        ├── _algorithm
        ├── _model
        └── ChessChallenge6.scala




2D dynamic array class not working properly

main.cpp:

 Rectangle* rect= new Rectangle;
    rect->setInfo(attributes);
    figc.addEntry(rect);

FigureCollection.cpp

void FigureCollection::addEntry(Figure *figure){
/*figure->print()  working fine output: 

rectangle 1 1 1198 398 none bluedsada 2
. line (100,300) (300,100) green 5
. line (300,300) (500,100) green 10
. line (500,300) (700,100) green 15
. line (700,300) (900,100) green 20
. line (900,300) (1100,100) green 25
. rectangle 1 1 1198 398 none retard 2
. rectangle 10 15 1198 398 none purple 2
. rectangle 7 23 1198 398 none green 2
. rectangle 35 11 1198 398 none red 2
*/
            if (numberOfEntries == maxEntries){
                Figure** temp = new Figure*[maxEntries + 1];
                for (unsigned int i = 0; i < maxEntries; ++i){
                                temp[i] = collection[i];
                            }
                temp[numberOfEntries] = figure;
                for (unsigned int i = 0; i < maxEntries; ++i)
                                delete collection[i];
                delete[] collection;
                collection = temp;
                numberOfEntries++;
                return;
           }
            collection[numberOfEntries] = figure;
            numberOfEntries++;
}
void FigureCollection::printToConsole() const{
    for (unsigned int i = 0; i < numberOfEntries; ++i)
    {
        std::cout << i + 1;
      collection[i]->print();
    }
}

output:

1. rectangle 35 11 1198 398 none red 2
2. line (900,300) (1100,100) green 25
3. line (900,300) (1100,100) green 25
4. line (900,300) (1100,100) green 25
5. line (900,300) (1100,100) green 25
6. line (900,300) (1100,100) green 25
7. rectangle 35 11 1198 398 none red 2
8. rectangle 35 11 1198 398 none red 2
9. rectangle 35 11 1198 398 none red 2
10. rectangle 35 11 1198 398 none red 2

svg file:

    <rect x="1" y="1" width="1198" height="398"
        fill="none" stroke="bluedsada" stroke-width="2" />

  <g stroke="green" >
    <line x1="100" y1="300" x2="300" y2="100"
            stroke-width="5"  />
    <line x1="300" y1="300" x2="500" y2="100"
            stroke-width="10"  />
    <line x1="500" y1="300" x2="700" y2="100"
            stroke-width="15"  />
    <line x1="700" y1="300" x2="900" y2="100"
            stroke-width="20"  />
    <line x1="900" y1="300" x2="1100" y2="100"
            stroke-width="25"  />
  </g>
    <rect x="1" y="1" width="1198" height="398"
        fill="none" stroke="retard" stroke-width="2" />
         <rect x="10" y="15" width="1198" height="398"
        fill="none" stroke="purple" stroke-width="2" />
         <rect x="7" y="23" width="1198" height="398"
        fill="none" stroke="green" stroke-width="2" />
         <rect x="35" y="11" width="1198" height="398"
        fill="none" stroke="red" stroke-width="2" />

When I call a print function for each element it works properly, the data is stored correctly but when I put it in the 2D array it breaks somewhere and assigns the attributes of the last element found in the file.




Java - Changing a string to " * " in wheel of fortune game

I'm currently creating a wheel of fortune game and have created a class that selects a randomly selected phrase from a string array however I need this to string to change to an * character and just a space in between the words. I am also not sure the best class to add this new method too. I have copied and pasted the PhraseList, Phrase and Main classes below:

PhraseList Class

import java.util.Random;
/**
 * This is where the phrase list is stored and a random phrase is selected using random
 * @version 1.0
 */

public class PhraseList {

private String[] phraseList = {"a cut above","aged to perfection","chip off the old block","face the facts","hit the nail On the head"};
private String list;
/**
 *
 * @return the phrase from the phrase list
 */
public String pickPhrase (){

    int idx = new Random().nextInt(phraseList.length);
    list = (phraseList[idx]);
    return list;
}

}

Phrase Class

/**
 * This is where the phrase is stored and can be accessed using the     methods
 *
 * @version 2.0
  */
public class Phrase {

PhraseList newList = new PhraseList();
String gamePhrase = newList.pickPhrase();
String guessPhrase = "-";

int guessCount = 26;
/*
String gamePhrase = "knowledge is power"; //correct phrase
String guessPhrase = "--------- -- -----"; //place holders
int guessCount = 26; //guess count starts at 26 and is lowered 1 for a letter guess and 5 for an incorrect full guess
*/
/**
 * the game board is printed to the console below
 */
public void gameBoard(){
    System.out.println(guessPhrase);
}
    /**
     * takes the letter guessed from the game class and checks it against the
     * game phrase
     *
     * @param letter the letter guessed by the player
     * @return whether that letter appears in the phrase and how many times
     */
    public int makeGuess(char letter){
    guessCount --; //minus 1 per letter guess
    String guesses = "";
    int lettersFound = 0;

    for (int x = 0; x<gamePhrase.length(); x++){
        if (letter == gamePhrase.charAt(x)){

            guesses += letter;
            lettersFound++;
                        }
        else {
            guesses += guessPhrase.charAt(x);
        }
    }

    guessPhrase = guesses;
    System.out.println(guessPhrase);
    return lettersFound;

}

/**
 * takes the guess of the full phrase from the player and checks it
 * against the game phrase
 *
 * @param guess phrase guess input from player
 * @return the guessCount (lowered with each guess) times 200, providing the bonus points for a correct answer
 * or the feedback that the answer was incorrect and 5 points docked from the bonus
 */
public String fullGuess(String guess){
    String bonusTrans;
    if (guess.equals(gamePhrase)){
        guessPhrase = guess;
        bonusTrans = Integer.toString(guessCount * 200);

        return bonusTrans;
    }
else {
    guessCount -= 5; //minus 5 for incorrect guess
    return "incorrect";
    }
}

/**
 * checks the two phrases against each other and returns a true or false
 *
 * @return if the whole phrase has been guessed
 */
public boolean gameComplete(){
    if (guessPhrase.equals(gamePhrase)){
        return true;
    }
    else {
        return false;
    }
}

}

Main Class

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
/**
 * The main section of code.  Methods and classes are called in this section.
 * @version 2.0
  */

public class Game implements ActionListener {

public static void main(String[] args) {

    Game game = new Game();
    game.go();

}

public void go(){
    //GUI gui = new GUI(this);

    Scanner scan = new Scanner (System.in);

    String userInput;
    String wheelResult;

    char userGuess;

    int pointsAdded = 0; //the points totalled from the round
    int bonusTotal = 0; //bonus points relate to the speed in which a player solves the board
    Wheel newWheel = new Wheel();
    Phrase newPhrase = new Phrase();

    PhraseList newList = new PhraseList();
    String selectedPhrase = newList.pickPhrase();


    // The commented code below is a little attempt at finding the strings length
    /* String[] test = selectedPhrase.split(" ");

    for(int i=0; i<test.length;i++){
        System.out.println(test[i]);
        System.out.println(test[i].length());
        //repeat _ by test[i].length
    }
    */

    System.out.println("Welcome to the Wheel of Fortune!");
    System.out.println("I am Peter your host...");
    System.out.println("How many players are there?");
    System.out.println(selectedPhrase);

    int numberOfPlayers = scan.nextInt();
    int[] playerScores = new int[numberOfPlayers]; //this is where the players scores are stored
    int currentPlayer = 0;  //because arrays start at 0: +1 is added

    System.out.println("Are you ready Player 1? Type spin to start."); //asking the player to type spin to start the following loop
    //spinning the wheel and showing the results

    do {
        userInput = scan.nextLine();

        if (userInput.equals("spin")){

            wheelResult = newWheel.spinWheel();

            switch (wheelResult)
            {

            case "Free Spin":
                    System.out.println("You get to spin again");
                    break;

            case "Bankrupt":
                playerScores[currentPlayer] = 0;
                System.out.println("Oops... Player " +  (currentPlayer + 1) + ", is bankrupt!");
                currentPlayer = NextPlayer(currentPlayer, numberOfPlayers);
                System.out.println("Your turn to spin Player " + (currentPlayer + 1));

                break;

              case "Lose a Turn":
                System.out.println("Sorry Player " +  (currentPlayer + 1) + ", you lose a turn");
                currentPlayer = NextPlayer(currentPlayer, numberOfPlayers);
                System.out.println("Start your turn Player " + (currentPlayer + 1));

                break;


              default:
                System.out.println("Nice one! You landed on"+" £" + wheelResult + ". Which letter would you like to guess? Remember vowels cost £250");
                int wheelValue = Integer.parseInt(wheelResult);
                newPhrase.gameBoard();

                //Guess calculations
                int letterCount;
                userGuess = scan.next().charAt(0);

               //this is checking whether vowels were used in the guess and docks money accordingly
               if ((userGuess == 'a') || (userGuess == 'e') || (userGuess == 'i') || (userGuess == 'o') || (userGuess == 'u')){

                   playerScores[currentPlayer] -= 250;
                   System.out.println("£250 was removed from your score");
                }

                letterCount = newPhrase.makeGuess(userGuess);

                    if (letterCount >= 1)
                        {
                            pointsAdded = letterCount * wheelValue;
                                System.out.println("Well Done! The letter " + userGuess + " was found " + letterCount + " times(s)");
                                    System.out.println("£" + pointsAdded + " has been added to your score");
                                        playerScores[currentPlayer] += pointsAdded;
                                            System.out.println("Your new score is £" + playerScores[currentPlayer]);
                                            System.out.println("Type spin to continue or solve to try and complete the phrase");
                            }
                        else
                            {
                            currentPlayer = NextPlayer(currentPlayer, numberOfPlayers);
                            System.out.println("Sorry that letter doesn't feature in this Phrase. Start your turn Player " + (currentPlayer + 1));
                            }
            }
        }
        //solve code below

        if (userInput.equals("solve")){
            System.out.println("Enter your full phrase guess");
            String userFullGuess;
            String guessCheck;

            userFullGuess = userInput = scan.nextLine();
            guessCheck = newPhrase.fullGuess(userFullGuess);

            if (guessCheck.equals("incorrect")){
                currentPlayer = NextPlayer(currentPlayer, numberOfPlayers);
                System.out.println("Sorry that is inot right. Start your turn Player " + (currentPlayer + 1)); 
            }
            else {
            bonusTotal = Integer.parseInt(guessCheck);
            }
        }

//Game checks if whole phrase has been guessed and ends if true

    } while ((!newPhrase.gameComplete()) && (!userInput.equals("end")));
    if (userInput.equals("end")) {
        System.out.println("Game terminated");
    }

        else {
            System.out.println("Congratulations, Player " + (currentPlayer + 1) + ", you have completed the phrase");
            System.out.println("Score = £" + playerScores[currentPlayer]);
            System.out.println("Bonus Points = £" + bonusTotal);
            playerScores[currentPlayer] += bonusTotal;
            System.out.println("Final score = £" +playerScores[currentPlayer]);
            }
}


/**
 * this function moves the game on so the next player can spin.
 * if it is at the last player then 0 is returned to start from the beginning
 *
 * @param currentPlayer the player whose turn it currently is
 * @param numberOfPlayers the total number of people playing the game
 * @return 0 or +1 depending on whose turn it is
 */
private static int NextPlayer(int currentPlayer, int numberOfPlayers)
{
    if ((currentPlayer + 1) == numberOfPlayers)
        {
        return 0;
        }
        else
        {
        return currentPlayer + 1;
        }
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

    String s = e.getActionCommand();
    System.out.println(s);

}

}

Any help is much appreciated. I have tried a number of approaches but can't seen to crack this. Any other feedback on the project is also appreciated.




Meaning of Class count metrics

We are working on a bigger project with Ruby on Rails. As you might know, Rails works with MVC pattern and typically enforces the following class types for Domain objects:

  • Controllers (+ Helpers)
  • Models
  • Views (e.g. erb)
  • Serializers
  • Mailers

We experienced - like many other teams - that this is not feasible for bigger, long-running projects.

So in our current project, we added some layers, so we typically have

  • Controllers (+ Helpers)
  • Policies (access control per controller)
  • Presenters (a.k.a ViewModel)
  • Forms (containing all attributes available in an HTML form)
  • Views
  • Models
  • Queries (static ActiveRecord queries)
  • Serializers
  • Mailers
  • Services (Domain Service which extracts business code from controller)

It is much more testable, maintainable and understandable. However, our boss disagrees with "These are too many classes".

As he is typically a proficient architect (doing consulting), I don't want to simply reject this response. However, his time as active Java developer are gone and he often explains such sentences with his improved "gut feeling".

Of course, there are metrics that count classes - but is there a general approach to classify something like 'Classes per Domain object' or 'Class per Business case', which can be taken for an argument?




How variable a will exist without any object creation?

how varible int a is in existance without object creation, and it is not of static type also.

#include <iostream>

using namespace std;

class Data
{
 public:
 int a;
 void print() { cout << "a is "<< a <<endl; }
};

int main()
{
    Data *cp;
    int Data::*ptr=&Data::a;
    cp->*ptr=5;
    cp->print();

}




Void pointer to a class object: Initialization inside a function

I am trying to create a void pointer to a class object and have it be initialized inside a function. Unfortunately, the array member of the class cannot escape the function i.e. it cannot be accessed after initialization.

In the code below, the first call to print positions (inside the initialize function) works properly, however, the second call to print positions from outside the initialization function fails. I have a feeling that the array object created in the initialization function is destroyed and not passed along but I ma not sure and also don't know how to fix it.

Any help would be greatly appreciated.

#include <iostream>
#include <iomanip>
#include <string>


class Atoms
{
    double * positions;
    int nAtoms;

    public:
        // Standard constructor prividing a pre-existant array
        Atoms(int nAtoms, double * positionsArray)
        {
            this->nAtoms = nAtoms;
            this->positions = positionsArray;
        }

        // Print positions to screen
        void print_positions()
        {
            std::cout<< "nAtoms: " << this->nAtoms << std::endl;
            int nDim = 3;
            for (int i = 0; i < nAtoms; i++)
            {
                for (int j = 0; j < nDim; j++)
                {
                    std::cout << std::setw(6) << this->positions[i * nDim + j] << " ";
                }
                std::cout << std::endl;
            }
            std::cout << std::endl;
        }

};


void initialize_Atoms_void_pointer(void ** voidAtomsPointer)
{
    //Create a new instance of Atoms by a pointer
    int numAtoms = 5;
    int numDim = 3;
    int elemN = numAtoms * numDim;
    double data_array[elemN];

    for (int i = 0; i < numAtoms; i++)
    for (int j = 0; j < numDim; j++)
    {
        data_array[i * numDim + j] = i * numDim + j + 10;
    }
    Atoms *atoms = new Atoms(numAtoms, data_array);

    // Set the vPointer that the void pointer points to a pointer to Atoms object
    *voidAtomsPointer = static_cast<void *>(atoms);

    //Test call
    std::cout << std::endl << "Initializing atoms" << std::endl;
    static_cast<Atoms *>(*voidAtomsPointer)->print_positions();
}


void print_Atoms_pointer_positions(void * voidAtomsPointer)
{
    //Cast the pointer as an atoms pointer
    Atoms *atomsPointer = static_cast<Atoms *>(voidAtomsPointer);

    atomsPointer->print_positions();
}

int main()
{
    //Use the initializer function for getting a pointer
    void *testVoidAtomsPointer;

    initialize_Atoms_void_pointer(&testVoidAtomsPointer);
    print_Atoms_pointer_positions(testVoidAtomsPointer);
}




mardi 25 avril 2017

Parsing ES6 Class Objects From localStorage Doesn't Include Class Functions

I want to persist a class object in HTML5 localStorage. The class contains methods which I also need to persist, but parsing the localStorage object reveals that the object isn't the same.

class ExcitingMath {

    constructor(firstNumber, secondNumber) {

        this._firstNumber = firstNumber;
        this._secondNumber = secondNumber;
    }

    add() {

        return this._firstNumber + this._secondNumber;
    }

    subtract() {

        return this._firstNumber - this._secondNumber;
    }
}

const eMath = new ExcitingMath(2, 4);

Logging eMath in the console displays the class object with it's properties and methods:

enter image description here

However, when I localStorage.setItem("math", JSON.stringify(eMath)); and JSON.parse(localStorage.getItem("math")); the object to and from localStorage, it no longer includes the constructor or methods.

enter image description here

How can I persist the original class instance with localStorage?




How to add attributes and methods to an instance of a class

I am writing a class that needs to behave as if it were an instance of another class, but have additional methods and attributes. I've tried doing different things within __new__ but to no avail. As an example, here is a half-written class and the desired behavior:

class A(object):
    def __new__(self, a, b):
        value = 100 + a  # instances of A need to behave like integers
        ...   # bind A methods and attributes to value?
        return value

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

    def something(self):
        return 20 + self.b

Here is the desired behavior:

a = A(10, 5)
print(a + 10)         # 110
print(a * 2)          # 200
print(a.b)            # 5
print(a.something())  # 25

I know that when __new__ returns an instance of a class different than A, then __init__ and other methods are not bound to value. None of the other methods are either. Is this sort of thing possible? Am I thinking about this problem the wrong way?




I am trying to make a bunch of ascii characters move, but they only move together as one group. Why is that? (C#)

I've been trying to figure out as to why my ascii people won't move independently as one figure, as they've been moving as one group. My goal is to make a bunch of guys move in four random directions every frame. Every person is a class with it's own set of data, like the X and Y position of them. Here is a part of the code:

What the code does by the way, is it spawns 10 people in a rectangle of 10x2. This is when the problem arises.

public class Soldier
    {
        public int Health;
        public string Symbol;
        public int x, y;
        public int ID;

        public void SetHealth(int hp)
        {
            Health = hp;
        }

        public void SetSymbol(string sym)
        {
            Symbol = sym;
        }

        public void SetID(int id)
        {
            ID = id;
        }

        public void RandomStep()
        {
            Random rnd = new Random();

            int randNum = rnd.Next(1, 5);

            if (randNum == 1)
            {
                x += 1;
            }
            else if (randNum == 2)
            {
                x -= 1;
            }
            else if (randNum == 3)
            {
                y += 1;
            }
            else if (randNum == 4)
            {
                y -= 1;
            }
        }
    }

else if (battleMode == true)
                {
                    bool battleLoad = true;
                    int team1Size = 0;
                    int team1Max = 10;
                    int rowXstart = 40;
                    int rowYstart = 10;
                    int rowX = rowXstart;
                    int rowXmax = rowXstart + 5;
                    int rowY = rowYstart;
                    int rowYmax = 5;
                    int pickIDsol = 1;
                    int IDsoldier = 1;

                    int battleID = 1;

                    List<Soldier> soldierunlist = new List<Soldier>();
                    List<Soldier> soldierlist = new List<Soldier>();

                    for (; ; )
                    {
                        if (battleLoad == true)
                        {


                            for (; ; )
                            {
                                if (team1Size < team1Max)
                                {
                                    soldierunlist.Add(new Soldier());
                                    Soldier unpickSoldier = soldierunlist.First(x => x.ID == 0);
                                    unpickSoldier.ID = IDsoldier;
                                    IDsoldier += 1;
                                    team1Size += 1;
                                    Console.WriteLine("Loading1");
                                }
                                else
                                {
                                    break;
                                }
                            }

                            foreach (Soldier soldier in soldierunlist) {
                                soldier.Symbol = "☻";
                                Console.WriteLine("Loading Graphics");
                            }

                            for (; ; )
                            {
                                if (soldierunlist.Count != 0)
                                {
                                    if (rowX < rowXmax)
                                    {
                                        Soldier pickSoldier = soldierunlist.First(x => x.ID == pickIDsol);
                                        pickSoldier.x = rowX;
                                        pickSoldier.y = rowY;
                                        rowX += 1;
                                        pickIDsol += 1;

                                        soldierunlist.Remove(pickSoldier);
                                        soldierlist.Add(pickSoldier);
                                        Console.WriteLine("Creating Position values for soldiers");
                                    }
                                    else if (rowX >= rowXmax)
                                    {
                                        rowX = rowXstart;
                                        rowY += 1;
                                    }
                                }
                                else
                                {
                                    battleLoad = false;
                                    battleMode = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            for (; ; ){
                                Console.Clear();
                                int RefreshRate = 100; // 1000 = 1 second
                                /// [ START ]

                                //foreach (Soldier soldier in soldierlist)
                                //{
                                //    WriteAt(soldier.Symbol, soldier.x, soldier.y);
                                //    soldier.RandomStep();
                                //}

                                for (; ; )
                                {



                                    if (battleID != team1Max)
                                    {
                                        Soldier aSoldier = soldierlist.First(x => x.ID == battleID);
                                        aSoldier.RandomStep();
                                        battleID += 1;

                                    }
                                    else
                                    {
                                        break;
                                    }

                                }

                                foreach (Soldier soldier in soldierlist)
                                {
                                    WriteAt(soldier.Symbol, soldier.x, soldier.y);
                                }

                                battleID = 1;

                                /// [ END ] 
                                System.Threading.Thread.Sleep(RefreshRate); // Waits for (number) of time
                            }
                        }
                    }
                }




Can someone please expain the this keyword in java i think my understandings wong

class Rabbit {
private int row;
private int col;
private String direction ;

public Rabbit ( int row, int col, String dir ){
this.row = row;
this.col = col;
this.direction = dir 

i thought the this keyword meant that it would use the variable declared in the method not the one in the class




C++ program stops when entering input file

The following program basically asks for an input file then writes the results to an output file. Its showing no errors in VisualStudio when I compile it.

When the program runs and asks for an input file, I type in the input file and hit enter the program just sits there with a flashing cursor. It doesn't go any further. I can't figure out for the life of me whats going on.

I don't know if this is a coding issue or just something I'm doing wrong in VisualStudio?

Header file (sort.h):

#ifndef SORT_H
#define SORT_H
//A generic sorting function.

template<class T>
void sort(T a[], int number_used);
//Precondition: number_used <= declared size of the array a.
//The array elements a[0] through a[number_used - 1] have values.
//Postcondition: The values of a[0] through a[number_used - 1] have
//been rearranged so that a[0] <= a[1] <= ... <= a[number_used - 1].

template<class T>
void swap_values(T& variable1, T& variable2);
//Interchanges the values of variable1 and variable2.

template<class T>
int index_of_smallest(const T a[], int start_index, int number_used);
//Precondition: 0 <= start_index < number_used. Array elements have values.
//Returns the index i such that a[i] is the smallest of the values
//a[start_index], a[star_index + 1], ..., a[number_used - 1].

template<class T>
void sort(T a[], int number_used)
{
    int index_of_next_smallest;
    for (int index = 0; index < number_used - 1; index++)
    {//Place the correct value in a[index]:
        index_of_next_smallest =
            index_of_smallest(a, index, number_used);
        swap_values(a[index], a[index_of_next_smallest]);
        //a[0] <= a[1] <=...<= a[index] are the smallest of the original array
        //elements. The rest of the elements are in the remaining positions.
    }
}

template<class T>
void swap_values(T& variable1, T& variable2)
{
    T temp;

    temp = variable1;
    variable1 = variable2;
    variable2 = temp;
}

template<class T>
int index_of_smallest(const T a[], int start_index, int number_used)
{
    T min = a[start_index];
    int index_of_min = start_index;

    for (int index = start_index + 1; index < number_used; index++)
        if (a[index] < min)
        {
            min = a[index];
            index_of_min = index;
            //min is the smallest of a[start_index] through a[index]
        }

    return index_of_min;
}
#endif

Source file (source.cpp):

#include <iostream>
#include <fstream>        // For I/O   
#include <iomanip>        // For setw()
#include <cstdlib>         // For system()
#include <string>         // For stricmp()
#include "sort.h"           // Generic sort() function
using namespace std;

const int MAX_FILE_NAME = 35;  // Maximum file name length
const int MAX_ID_LEN = 10;  // Maximum length for items's id
const int MAX_NAME_LEN = 30;  // Maximum length for itemsloyee's name
const double DISCOUNT = 0.10;  // Quantity sold value at which commision rate changes
const double DISCOUNT_BREAK_POINT = 10;         // Regular commission per subscription sold 

class SalesRecord                      // Record definition for items's sales record
{
private:
    char   item_id[MAX_ID_LEN + 1];   // Items's id
    char   item_name[MAX_NAME_LEN + 1];// Items's name
    int    quantity_sold;            // Number of magazine subscriptions sold
    double regular_price;          // Commission on each subscription
    double discount_price;               // Salesperson's commission
    double total_price;  // Total price of items
public:
    // Functions that operate on an individual record
    void read(ifstream& in);         // Read record from input stream
    void calc_discount_price();          // Calculate commission fields in record
    void write(ostream & os) const;  // Write record to output stream
    int operator<(const SalesRecord& right) const;// Overloaded for use in sort
};

typedef SalesRecord * SalesRecord_Array; // Used to allocate 1-D sales record array

 // Utility functions - functions are not specific to this problem
void open_input(ifstream& input, char name[]);           // Get file name & Open file
void open_output(ofstream& output, char name[]);         // Get file name & Open file

                                                         // Funcions that operate on array (set) of records
SalesRecord_Array read_records(ifstream& in, int &n);    // Allocate space for records & read them
void calc_discounts(SalesRecord_Array records, int n);     // Calculate commission rate and commission
void write_records(SalesRecord_Array records, int n);    // Save records to file

int  main()
// Parameters: None
// Returns:    Zero
// Calls:      open_input(), read_records(), calc_commissions(), sort(), write_records().
{
    char again;                                  // Does user want to go through loop again?
    int  num_records;                            // # of records 
    char infilename[MAX_FILE_NAME + 1];          // Name of file for records to be processed
    ifstream  in;                                // Input file stream
    SalesRecord_Array records = NULL;            // Pointer to array of sales records

    do
    {
        open_input(in, infilename);               // Get file name & open file
        records = read_records(in, num_records);  // Read records & get number of records
        in.close();                               // Close file
        if (num_records > 0)
        {
            calc_discounts(records, num_records);    // Calculate commission values for each record
            sort(records, num_records);            // Sort records by item name
            write_records(records, num_records);   // Save records to new file
            delete[] records;                     // Free array of records  
        }
        else
        {
            cout << "\n\n\aNo data in file: " << infilename << endl;
        }

        cout << "\nDo you want to process another file (Y/N)? ";
        cin >> again;
        cin.ignore(256, '\n');  // Remove Enter key from keyboard buffer
    } while (again == 'y' || again == 'Y');

    cout << "\n\n***** END OF PROGRAM ******\n";// Print closing message.    
    return 0;
}  // End of main()                

   // Utility functions
void open_input(ifstream& input, char name[]) //Open file
// Parameters: Variables for input file reference nad input file name
// Returns:    None
// Calls:      None
{
    int count = 0;             // Count number of tries
    do // Continue until we get a valid file name and can open file
    {
        count++;
        if (count != 1)  // Issue error message if we are trying again.
        {
            cout << "\n\aInvalid file name or file does not exist. Please try again."
                << endl;
        }

        cout << "\nEnter the input file name (maximum of " << MAX_FILE_NAME
            << " characters please)\n:> ";
        cin.get(name, MAX_FILE_NAME + 1);// Gets at most MAX_FILE_NAME characters
        cin.ignore(256, '\n');           // Remove Enter key from keyboard buffer
        input.clear();                   // Clear all error flags, if any, from prev try
        input.open(name, ios_base::in); // Open only if file exists
    } while (input.fail());            // If can't open file, try again
} // End of open_input()

void open_output(ofstream& output, char name[]) //Open file
                                                // Parameters: Variables for output file reference and output file name
                                                // Returns:    None
                                                // Calls:      None
{
    int count = 0;             // Count number of tries
    do // Continue until we get a valid file name and can open file
    {
        count++;
        if (count != 1)  // Issue error message if we are trying again.
        {
            cout << "\n\aInvalid file name. Please try again."
                << endl;
        }

        cout << "\nEnter the output file name (maximum of " << MAX_FILE_NAME
            << " characters please)\n:> ";
        cin.get(name, MAX_FILE_NAME + 1);// Gets at most MAX_FILE_NAME characters
        cin.ignore(256, '\n');           // Remove Enter key from keyboard buffer
        output.clear();                  // Clear all error flags, if any, from prev try
        output.open(name);               // Open file for output
    } while (output.fail());           // If can't open file, try again
} // End of open_output()



void SalesRecord::read(ifstream& in)      // Read record from input stream, does not read commission values
// Parameters: Input stream
// Returns:    none
// Calls:      None
{
    in.get(item_id, MAX_ID_LEN + 1);         // Read id
    while (in.get() != '\n');              // Clear Enter after id

    in.get(item_name, MAX_NAME_LEN + 1);     // Read name: Last, First
    while (in.get() != '\n');              // Clear Enter after name

    in >> quantity_sold >> regular_price;                   // Read quantity sold value
    while (in.get() != '\n');              // Clear Enter at end of record
} // End of SalesRecord::read()

void SalesRecord::calc_discount_price()       // Calculate commission fields in record
// Parameters: None
// Returns:    None
// Calls:      None
{
    double discount_rate;
    if (quantity_sold < DISCOUNT_BREAK_POINT)
        discount_rate = 0.0;
    else
        discount_rate = DISCOUNT;
        discount_price = regular_price - (discount_rate * regular_price);
        total_price = quantity_sold * discount_price;
} // End of SalesRecord::calc_commission()

void SalesRecord::write(ostream & os) const// Write record to output stream
// Parameters: Output stream, record to be written      
// Returns   : None.                                                        
// Calls     : None.                                                        
{
    os.setf(ios::fixed);   os.setf(ios::showpoint);   os.precision(2);

    os << item_id << "\n" << item_name << "\n"
        << quantity_sold << " " << regular_price << " "
        << discount_price << " " << total_price << endl;
} // End of SalesRecord::write()              

int SalesRecord::operator<(const SalesRecord& right) const                          
{
    if (_stricmp(item_name, right.item_name) < 0)
        return 1;
    else
        return 0;
} // End of SalesRecord::operator<

  // Funcions that operate on array (set) of records
SalesRecord_Array read_records(ifstream& in, int &n)      // Allocate space for records & read them
                                                          // Parameters: Input stream, variable for number of records.      
                                                          // Returns   : Pointer to array of records allocated.                                                        
                                                          // Calls     : SalesRecord::read().                                                        
{
    in >> n;                       // Read number of records
    if (n < 1 || in.fail())
        return NULL;               // No records to read return

    while (in.get() != '\n');     // Clear enter after number of records in file
    SalesRecord_Array records;    // Pointer for array of records

    records = new SalesRecord[n]; // allocate space for records 
    if (records == NULL)
    {
        cout << "\aCan not allocate memory!";
        exit(1);
    }

    int i;
    for (i = 0; in.good() && !in.eof() && i < n; i++)
    {
        records[i].read(in);             // Read each record
    }

    return records;  // Return pointer to array 
} // End of read_records()

void calc_discounts(SalesRecord_Array records, int n) // Calculate commission rate and commission
// Parameters: Array of records, number of records.      
// Returns   : None.                                                        
// Calls     : SalesRecord::calc_commission().                                                        
{
    int i;
    for (i = 0; i < n; i++)
    {
        records[i].calc_discount_price();    // Process each record
    }
} // End of calc_records()

void write_records(SalesRecord_Array records, int n)   // Save records to file
// Parameters: Array of records, number of records.      
// Returns   : None.                                                        
// Calls     : SalesRecord::write().                                                        
{
    char      outfilename[MAX_FILE_NAME + 1];   // Name of file for output records
    ofstream  out;                              // Output file stream

    cout << "\n\nI need the output file name." << endl;
    open_output(out, outfilename);              // Get file name & open file

    if (out.good())
    {
        out << n << endl;          // Write number of records to file
        int i;
        for (i = 0; i < n; i++)
        {
            records[i].write(out);  // Write each record to file
        }
        out.close();
    }
    else
    {
        cout << "\a\nUnable to save data!" << endl;
    }
} // End of write_records()

Input file (order.txt)

5
0-8053-7442-6
Problem Solving with C++
1  45.50
7751158146
Looney Tunes Diskettes
12  8.50
88869809780
HP Laser Printer Paper
3   10.99
2429412454
No. 2 Pencil
24  0.10
4895469286
Note Pad
5  0.89




Checking Azure connected Database onClick for login

So Azure spit the following code for me to insert into an activity (Android Studio is what I'm using)

Add the following line to the top of the .java file containing your launcher activity:

import com.microsoft.windowsazure.mobileservices.*;

Inside your activity, add a private variable

private MobileServiceClient mClient;

Add the following code the onCreate method of the activity:

mClient = new MobileServiceClient("http://ift.tt/2qcPBCq", this);

Add a sample item class to your project::

public class ToDoItem{ public String id; public String Text;}

In the same activity where you defined mClient, add the following code:

ToDoItem item = new ToDoItem();
item.Text = "Don't text and drive";
mClient.getTable(ToDoItem.class).insert(item, new TableOperationCallback<item>(){
public void onCompleted(ToDoItem entity, Exception exception, ServiceFilter response)
{
if(exception == null){
//Insert Succeeded
} else {
//Insert Failed 
}
}});

My goal is to create a login page. I understand that the above was probably offered up more with a ToList in mind. I just want to get the syntax correct today. The problem I think, is my basic class structure. I have created an OnClick Listener within my on create that gets the ID from a button in my layout. I don't need it checking for anything in the database until the button has been actually clicked to either login or register.

public class LoginClass extends AppCompatActivity{  
       public void onCreate(Bundle savedInstanceState) {
          setContentView(R.layout.MyLoginLayout);
          MobileServiceClient mClient = null; 

          try {
              mClient = new MobileServiceClient ("myAzureWebsite", "AzureKey", this);
} catch (MalformedURLException e) {
e.printStackTrace();
}

Button Attempt = (Button) findViewById (R.id.mySubmitButton);
final MobileServiceClient finalMClient = mClient; // finalized so I can use it later. 

Attempt.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick (View v) {
         final View thisView = v;
         final MyToDoItemClass item = new MyToDoItemClass();

In MyToDoItemClass I have two variables (Both String) Just left over from
the example of a ToDoList (they are String ID and String Text)

         item.Text = "Filler"; 
         item.ID = "Fill";
finalMClient.getTable(MyToDoItemClass.class).insert(new Table OperationCallback<item>() { //<--- I'm getting an error that the variable, item
is from an unknown class...

public void onCompleted (Item entity, Exception exception, ServiceFilterResponse response){
if(exception == null) {
Intent i = new Intent (LoginClass.this, MainActivity.class);
startActivity(i);
}else{
Toast.makeText(thisView.getContext(), "Failed", Toast.LENGTH_LONG).show();
}}
});
}
});
}}

The problem is with that the TableOperationCallback is saying that the item from MyToDoItemClass class is from an unknown class. I'm brand new to java and Android studio. B**c slap gently, if can be helped.




Python Class Instance Memory

Why does an instance of the following class take up so much memory?

It takes about 10MiB of memory; though there is just one object with just an integer.

class myClass(object):
    __slots__ = ['n']
    @profile
    def __init__(self):
        self.n = 1
c = myClass()




Arduino IDE - Not allowing me to use MFRC library because of bug in a class

I'm making something to read RFID. When I go and compile the code, it sais

       exit status 1
  'class MFRC522' has no member named 'begin'

It's happening for everything else nfc.
I've checked the intitial code on (http://ift.tt/2pxyZcB) and have even redownloaded the libraries but it doesnt fix it. When i compile the exact code on that website, that error doesnt show up, so I'm thinking it's something I did when I changed the code..

Here's all my code, the parts im having trouble with will be 'boxed'

I tried looking for other answers, but they didnt really help because it's a problem with what I did to change the code

Thanks alot!

  #include <MFRC522.h>
#include <SPI.h>


#define SDAPIN 10 // RFID Module SDA Pin is connected to the UNO 10 Pin
#define RESETPIN 8 // RFID Module RST Pin is connected to the UNO 8 Pin
MFRC522 mfrc522(SDAPIN, RESETPIN);        // instatiate a MFRC522 reader 
object.
MFRC522::MIFARE_Key key;//create a MIFARE_Key struct named 'key', which will 
hold the card information



// VARIABLES 
byte j = 0;

//PINS

byte buzzerPin = 1;
byte ledRed = 2;
byte ledGreen = 3;
byte ledBlue = 4;



//RFID
byte byteblock = 2;
byte blockcontent[16] = {"MailMan!"};
byte FoundTag; // Variable used to check if Tag was found
byte ReadTag; // Variable used to store anti-collision value to read Tag 
information
byte TagData[MAX_LEN]; // Variable used to store Full Tag Data
byte TagSerialNumber[5]; // Variable used to store only Tag Serial Number
byte GoodTagSerialNumber[5] = {0x95, 0xEB, 0x17, 0x53}; // The Tag Serial 
number we are looking for
boolean rfYES = false;







MFRC522 nfc(SDAPIN, RESETPIN); // Init of the library using the UNO pins 
declared above


void setup(){



pinMode(buzzerPin, OUTPUT); // Set buzzer pin to an Output pin
 digitalWrite(buzzerPin, LOW); // Buzzer Off at startup
SPI.begin();

Serial.begin(9600);

for(byte i = 0; i < 6; i++){
  key.keyByte[i] = 0xFF;
} 

----------------------------------------------------------------------

Serial.println("Looking for RFID Reader");                                                                               //   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  nfc.begin();
byte version = nfc.getFirmwareVersion(); // Variable to store Firmware version of the Module

// If can't find an RFID Module 
if (! version) { 
Serial.print("Didn't find RC522 board.");                                                                                   //      <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
while(1); //Wait until a RFID Module is found
}

// If found, print the information about the RFID Module
Serial.print("Found chip RC522 ");                                                                         //       <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Serial.print("Firmware version: 0x");                                               //      <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Serial.println(version, HEX);                                                       //                  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Serial.println("--");                                                     //        <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<





}

-------------------------------------------------------------------



// END OF RFID//
void loop(){

RFID();                       //runs rfid code to set light,buzzer and der rfYes boolean

if(rfYES = true && readbackblock[18] = "MailMan!"){     //if tag was opened, go ahead

  pirsection:


PIR();

}
if(PIR = true){           //if there was movement, go on

 colorSensor;

  Serial.println(colorSensor());

  //send sms accoording to ColorSensor output;

  j ++;

  delay(1500);
  if(j < 3){

  goto pirSection;
  } else{
    rfYES = false;
    return;
  }




  }else{       //if there was no movement
  delay(2000);
  return;
}





}else if(readbackblock[18] != "MailMan!"){                // if tag was not opened, return
  delay(5000);
  return;          


 }else{
  delay(1500);
  return;
 }





}

              /////////////////////////////////////////   DECLARE FUNCTIONS ////////////////////////////////////





             // check pir for movement

             public boolean PIR(){

      if(digitalRead(pirPIN) = HIGH){
        Serial.println("PIR IS ");                                                          //    <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        Serial.println(pirPin);                                                              //   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<,
        return true;
      }else{
        return false;
      }
             }





        boolean RFID(){






String GoodTag="False"; // Variable used to confirm good Tag Detected

// Check to see if a Tag was detected
// If yes, then the variable FoundTag will contain "MI_OK"
FoundTag = nfc.requestTag(MF1_REQIDL, TagData);

if (FoundTag == MI_OK) {
delay(200);

// Get anti-collision value to properly read information from the Tag
ReadTag = nfc.antiCollision(TagData);
memcpy(TagSerialNumber, TagData, 4); // Write the Tag information in the TagSerialNumber variable

Serial.println("Tag detected.");                                                            //  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Serial.print("Serial Number: ");                                                 //   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
for (int i = 0; i < 4; i++) { // Loop to print serial number to serial monitor
Serial.print(TagSerialNumber[i], HEX);                                             //   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Serial.print(", ");                                  //       <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
Serial.println("");                                   //      <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Serial.println();                                      //                   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<,,,


// Check if detected Tag has the right Serial number we are looking for 
for(int i=0; i < 4; i++){
if (GoodTagSerialNumber[i] != TagSerialNumber[i]) {
break; // if not equal, then break out of the "for" loop
}
if (i == 3) { // if we made it to 4 loops then the Tag Serial numbers are matching
GoodTag="TRUE";
} 
}
if (GoodTag == "TRUE"){
  rfYES = true;                                                                                   
Serial.println("Success!!!!!!!");                                                      //           <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Serial.println();                                                                     //    <<<<<<<<<<<<<<<<<<<<<<<<<<<<<

//RGB led green

digitalWrite(buzzerPin, HIGH);
delay(2500);
digitalWrite(buzzerPin, LOW);


delay(1500);

}else {
   rfYES = false;
Serial.println("TAG NOT ACCEPTED...... :(");                   //               <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<,,
Serial.println();                                 //            <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

//RGB led red

digitalWrite(buzzerPin, HIGH);
delay(800);
digitalWrite(buzzerPin, LOW);
digitalWrite(buzzerPin, HIGH);
delay(800);
digitalWrite(buzzerPin, LOW);
delay(3000);
return;
}







}





String colorSensor(){





}




Python Classes Clarification - Python Crash Course Book

I'm currently working through Python Crash Course, I'm on chapter 9 - Classes. I am confused about some things and need clarification. There is a long setup to my questions, but I am trying to be thorough.

9-7: Admin

"An administrator is a special kind of user. Write a class called Admin that inherits from the User class you wrote in Exercise 9-3 (page 166) or Exercise 9-5 (page 171). Add an attribute, privileges, that stores a list of strings like "can add post", "can delete post", "can ban user", and so on. WRite a method called show_privileges() that lists the administrator’s set of privileges. Create an instance of Admin, and call your method."

I solved 9-7 with this code:

class Admin(User):
    def __init__ (self, first_name, last_name):
        super().__init__(first_name, last_name) 
        self.privileges = []
        #For 9-8 the above lines changes to
        #self.privileges = Privileges() 

    def show_privileges(self):
        if self.privileges:
            print("The admins privileges are")
            for privilege in self.privileges:
                print(privilege)
        else:
            print("There are no privileges set for this admin")

user1 = Admin("Foo", "Bar")

user1.show_privileges()
user1.privileges = [
    'can add users ',
    'can ban users ',
    'can delete users ',
    ]
user1.show_privileges()

Moving on...

9-8 Privileges

"Write a separate Privileges class. The class should have one attribute, privileges, that stores a list of strings as described in Exercise 9-7. Move the show_privileges() method to this class. Make a Privileges instance as an attribute in the Admin class. Create a new instance of Admin and use your method to show its privileges."

I solved 9-8 with this code:

Admittedly a little help from the authors solution on github.

class Privileges():
    #A seperate privileges class

Below, I had to set a privileges parameter equal to an empty list after self but in 9.7 this was done under init. Why the need for the change?

    def __init__(self, privileges=[]):
    #Initialize self and privileges
        self.privileges = privileges

Why the need for the change?

    def show_privileges(self):
    #A method to print the privileges of an admin
        if self.privileges:
            print("The admins privileges are")
            for privilege in self.privileges:
                print(privilege)
        else:
            print("There are no privileges set for this admin")


user1 = Admin('foo', 'bar')
user1.describe_user()

user1.privileges.show_privileges()

Below, I had to set the list equal to a variable, whereas in the 9-7 problem this wasn't necessary.

user1_privileges = [
    "I do it all",
    "Yes I do that that too"
    ]

Below, why is there a need for two .privileges here, when in 9-7 I only had to use one when setting it directly.

user1.privileges.privileges = user1_privileges
user1.privileges.show_privileges()

What exactly is init and what determines its parameters?

I figured I could approach this problem in a similar manor to 9-7 and I don't see the need for the changes described above. I appreciate it if you could clarify this for me.




spawning multiple classes without tedious task of naming variables (C#)

is there a way to make mulitple classes based on a number, say from a variable? For example:

public class Person
{
    //stuff
}

new Person(3);




Creating a pointer within a class to another object

May someone please help me correct the following. I'm trying to wrap my head around how to create a pointer to an existing object within a new object. I can't get the syntax correct and keep getting errors.

Here's my code:

class Country
{
    string name; 
public:
    Country (string name)
    {   name = name; 
        cout << "Country has been created" << endl;}

    ~Country()
    {cout << "Country destroyed \n";}

};

class Person
{
    //string name;
    //Date dateOfBirth;
    Country *pCountry; 

public:
    Person(Country *c):
      pCountry(c)
      {}

};




int main()
{
    Country US("United States");
    Person(&US)

    return 0;
}




kivy python widget instance or all widgets

Please help me with understanding classes/instances in python. I want to make a few buttons, and change color of the button, when it's clicked. I don't understand why on_touch_down changes the color of all the instances of the class, not the one that is touched. It's difficult for me to find answer because I don't know how to name it, I don't have much experience with objects. Please explain this. Thank you a million.

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.graphics import Color, Ellipse

class MemoWidget(Button):
    def on_touch_down(self, touch):
         self.background_color=[100,100,1,1]

class MyApp(App):
    def build(self):
        root = BoxLayout(orientation='vertical',spacing=4)
        m1 = MemoWidget()
        m2 = MemoWidget()
        m3 = MemoWidget()
        root.add_widget(m1)
        root.add_widget(m2)
        root.add_widget(m3)
        return root

if __name__ == '__main__':
MyApp().run()




how to use const array instead of const variable?

hi my current function is something like this... i want to know how can i use const apiKey as array. and how can i use 'key'=> self::apiKey as 'key'=> self::apiKey[rand(0,1)] etc. Please help me in it.

const apiKey = 'api_key_ods000doo123';
public function counter_params($video_ID, $part) {
$params = array(
'id' => $video_ID,
'key' => self::apiKey,
'part' => $part
);
$result = self::Connect($params);
//print_r($params);
return $result;
}




python program, Write a class to represent the geometric sphere,

I am working on a project in python, I can not figure out why I am getting an error on the project.

The project is as follows.

  1. Write a class to represent the geometric sphere. Your class should implement the following methods: init(self, radius) Creates a sphere having the giving radius. getRadius(self) Returns the radius of this sphere surfaceArea(self) Returns the surface area of the sphere. Formula for area is Surface Area = 4πr2 volume(self) Returns the volume of the sphere. Formula for volume is

  2. Write a main() method that prompts the user for the radius of the sphere and tells the user what the surface area and volume is for the given radius.

My current code is as follows.

import math 
class Spheres:
def __init__(self,radius):
    self.radius = radius
    self.area = 0
    self.volumeResult = 0   

def getRadius(self):
    return self.radius

def surfaceArea(self):
    r = self.radius         
    self.area = 4 * math.pi * (r * r)            
    return self.area

def volume(self):
    r = self.radius         
    self.volumeResult = (4/3) * math.pi * (r * r * r) 
    return self.volumeResult
def main():
r = input("enter radius of circle:") 
r = int(r)                 
radius = Spheres(r)
v = radius.volume()
a = radius.surfaceArea()             

print ("volume of circle :" , v () )
print ("Surface Area of circle:" , a () )

main()

When I run the code it looks like this

enter radius of circle:5   #### i enter 5 here to test it
Traceback (most recent call last):
File "C:\Users\Austin\Desktop\python bonus project\AustinBaker Python 
bonus.py", line 30, in <module>
main()
File "C:\Users\Austin\Desktop\python bonus project\AustinBaker Python 
bonus.py", line 27, in main
print ("volume of circle :" , v () )
TypeError: 'float' object is not callable
>>> 

I dont understand why the code is not working at all. Any help I could get to understand why it is not working would be appreciated.




connection with database with OOP mysqli extending class

I know must coding part of mysql bt new at mysqli. I am not able to execute these insert query to the database. I have searched a lot but couldn't find simple suggestion, or may be i didn't understand. Any help is appreciated.

       class connection{

       public $mysqli; 
       function connect(){

            $hostname = "localhost";
            $username = "root";
            $password = "";
            $database = "demodatabase";
            $mysqli = new mysqli($hostname, $username, $password, $database);
            /* check connection */
            if (mysqli_connect_errno()) {
                printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
            }
            return true;            
    }
}
class Index extends connection {

    function __construct(){
        parent::connect();
    }

    function insertdata($a, $b){

        //echo $a. ' ' .$b;
        //MySqli Insert Query
        $status = 0;
        $insert_row = $mysqli->mysqli_query("INSERT INTO tb_user (id, user, password, status) VALUES('','".$a."', '".$b."', '')");
        if($insert_row){
            print 'saved'; 
        }else{
            die('Error : ('. $mysqli->errno .') '. $mysqli->error);
        }
    }
}

 ?>




Avoid double delete while copying objects

With this simple code the compiler is throwing a "double free or corruption" error. I understand that the copying operation makes the constructor delete a pointer that has already been deleted, but I don't exactly understand how the object copy is made and what happens with the pointers inside them.

#include <iostream>
using namespace std;

class test {
  public:
      test(int a = 1) {*p = a;}
      ~test() {delete p;}
      int *p = new int; 
};

int main() {
    test uno;
    test dos = uno;
    cout << *uno.p << endl;
}




How to inject our package into java

I have some piece of code:

package bk;

import java.util.Vector;
import java.util.Scanner;

public class bk {
    private static int iAsLoopRunner=0;
    static Scanner takeInput=new Scanner(System.in);
    public static void print_int(int arr[])
    {
        for(iAsLoopRunner=0;iAsLoopRunner<arr.length;iAsLoopRunner++)
        {
            System.out.print(arr[iAsLoopRunner]+" "+"|"+" ");
        }
        System.out.println();
    }
    public static void print_float(float arr[])
    {
        for(iAsLoopRunner=0;iAsLoopRunner<arr.length;iAsLoopRunner++)
        {
            System.out.print(arr[iAsLoopRunner]+" "+"|"+" ");
        }
        System.out.println();
    }
    public static void print_string(String arr[])
    {
        for(iAsLoopRunner=0;iAsLoopRunner<arr.length;iAsLoopRunner++)
        {
            System.out.print(arr[iAsLoopRunner]+" "+"|"+" ");
        }
        System.out.println();
    }
    public static void print_double(double arr[])
    {
        for(iAsLoopRunner=0;iAsLoopRunner<arr.length;iAsLoopRunner++)
        {
            System.out.print(arr[iAsLoopRunner]+" "+"|"+" ");
        }
        System.out.println();
    }
    public static void print_long(long arr[])
    {
        for(iAsLoopRunner=0;iAsLoopRunner<arr.length;iAsLoopRunner++)
        {
            System.out.print(arr[iAsLoopRunner]+" "+"|"+" ");
        }
        System.out.println();
    }
    public static void print_vector(Vector arr)
    {
        for(iAsLoopRunner=0;iAsLoopRunner<arr.size();iAsLoopRunner++)
        {
            System.out.print(arr.get(iAsLoopRunner)+" "+"|"+" ");
        }
        System.out.println();
    }
    public static void sop(Object obj)
    {
        System.out.print(obj+" ");
    }
    public static void sopln(Object obj)
    {
        System.out.println(obj);
    }
    public static int[] getInt(int arraySize)
    {
        int arrayToReturn[]=new int[arraySize];
        for(iAsLoopRunner=0;iAsLoopRunner<arraySize;iAsLoopRunner++)
        {
            arrayToReturn[iAsLoopRunner]=takeInput.nextInt();
        }
        return arrayToReturn;
    }
    public static String[] getString(int arraySize)
    {
        String arrayToReturn[]=new String[arraySize];
        for(iAsLoopRunner=0;iAsLoopRunner<arraySize;iAsLoopRunner++)
        {
            arrayToReturn[iAsLoopRunner]=takeInput.next();
        }
        return arrayToReturn;
    }
    public static float[] getFloat(int arraySize)
    {
        float arrayToReturn[]=new float[arraySize];
        for(iAsLoopRunner=0;iAsLoopRunner<arraySize;iAsLoopRunner++)
        {
            arrayToReturn[iAsLoopRunner]=takeInput.nextFloat();
        }
        print_float(arrayToReturn);
        System.out.println("done ;)");
        return arrayToReturn;
    }
    public static long[] getLong(int arraySize)
    {
        long arrayToReturn[]=new long[arraySize];
        for(iAsLoopRunner=0;iAsLoopRunner<arraySize;iAsLoopRunner++)
        {
            arrayToReturn[iAsLoopRunner]=takeInput.nextLong();
        }
        print_long(arrayToReturn);
        System.out.println("done ;)");
        return arrayToReturn;
    }
    public static double[] getDouble(int arraySize)
    {
        double arrayToReturn[]=new double[arraySize];
        for(iAsLoopRunner=0;iAsLoopRunner<arraySize;iAsLoopRunner++)
        {
            arrayToReturn[iAsLoopRunner]=takeInput.nextDouble();
        }
        print_double(arrayToReturn);
        System.out.println("done ;)");
        return arrayToReturn;
    }
}

As one can see that this simplifies many lines of code like printing array just with one function.This can be greatly useful if we want to see how our array is changing while undergoing a sorting process.But for each project I have to create a new package and import this.It takes some time.Is there any way so that I can inject this package to java root packages like util package or whatever.I have tried a lot in google but every one finally shown creating a jar and importing that to project which is same as what I'm doing now.Thanks in advance :)




What is the difference between a private static function vs. a public static function in typescript?

In the context of an angular2 service; what is the difference between a private static function vs. a public static function in typescript?

  public static getUserStockList(): Stock[] {
    /* TODO: implement http call */
    return WATCHLIST;
  }

vs.

  private static getUserStockList(): Stock[] {
    /* TODO: implement http call */
    return WATCHLIST;
  }




What sort of function put in a Python class?

I try to improve my beginning's skills in Python (2.7) (and my english...).

I've wrote a code to compare 2 files in a graph. That's work ! So I try to make an interface for changing more easily the title, range, axis's name... that open and edit the script (it's for my coworkers, not fluente in Python !)

I use Tk library and ttk. I start by making a class for the frame and define function for repetitive task. "It's a good idea", I think. Ha ha ha. A bunch of error (variable in function aren't global so I can't use the result of the function and I didn't find how to resolve that, when a function is built into the class, an argument is always more, and the function run well out of the class...)

Finally, my code run... but it's very ugly.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from os import getcwd, path
import Tkinter as tk
from Tkinter import *
import tkFileDialog as filedialog
import shutil
import ttk
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

matplotlib.style.use('ggplot')
wd = getcwd() # working directory

class Application(ttk.Frame):
    def __init__(self, master=None):
        ttk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.quitButton = ttk.Button(self, text='Quitter', command=self.quit)
        self.quitButton.grid(column=2, row=3)


def champ(nom, defaut, col, ran, lab, collab, ranlab, largeur=7):
    nom = StringVar()
    nom = ttk.Entry(mainframe, width=largeur, textvariable=nom)
    nom.insert(0, defaut)
    if nom.bind('<FocusIn>'):
        nom.delete(0, "end")
    nom.grid(column=col, row=ran, sticky=W)
    ttk.Label(mainframe, text=lab).grid(column=collab, row=ranlab, sticky=E)

def champdouble(nom1, defaut1, nom2, defaut2, col, ran, lab, lab2, collab, ranlab, largeur=7):
    nom1 = StringVar()
    nom1 = ttk.Entry(mainframe, width=largeur, textvariable=nom1)
    nom1.insert(0, defaut1)
    nom1.grid(column=col, row=ran, sticky=W)
    ttk.Label(mainframe, text=lab).grid(column=collab, row=ranlab, sticky=E)
    nom2 = StringVar()
    nom2 = ttk.Entry(mainframe, width=largeur, textvariable=nom2)
    nom2.insert(0, defaut2)
    nom2.grid(column=col+2, row=ran, sticky=W)
    ttk.Label(mainframe, text=lab2).grid(column=collab+2, row=ranlab, sticky=E)

def on_entry_click(event):
    """function that gets called whenever entry is clicked"""
    global dirname
    if file1.get() == 'Choisissez un fichier...':
        file1.delete(0, "end") # delete all the text in the entry
        dirinit = r'C:/'
        dirname = filedialog.askopenfilename(parent=mainframe, initialdir=dirinit, title='Sélectionnez le fichier')
        file1.insert(0, dirname) #Insert blank for user input

def on_entry_click1(event):
    """function that gets called whenever entry is clicked"""
    global dirname2
    if file2.get() == 'Choisissez un fichier...':
       file2.delete(0, "end") # delete all the text in the entry
       dirinit = r'C:/'
       dirname2 = filedialog.askopenfilename(parent=mainframe, initialdir=dirinit, title='Sélectionnez le fichier')
       file2.insert(0, dirname2) #Insert blank for user input

def callback():
    def traitement(fichier, deb, fin):
        df = pd.read_csv(fichier, sep = '\t', engine = 'python', header = deb, skipfooter = fin)  # Lecture des fichiers
        df = df.rename(columns={'$Relations :NumZoneE': 'NumZoneE'})  # Renommage des entêtes de colonnes
        df = df[(df.NumZoneE != df.NumZoneA)]  # supression des intrazonaux
        df = df[(df.NumZoneE <= 1289)]  # supression des zones superieures a 1289
        df = df[(df.NumZoneA <= 1289)]
        df['OD_possible']=np.where(df['JRTA'] < 999999, 'oui', 'non')  # creation d'une colonne OD_possible
        df = pd.merge(df, dvol, on = ['NumZoneE', 'NumZoneA'])  # jointure des tables avec dvol
        dfg = df.groupby('OD_possible')  # groupage selon oui ou non
        return dfg

    titrel = titre.get()
    file1_debl = int(file1_deb.get())
    file1_finl = int(file1_fin.get())
    file2_debl = int(file2_deb.get())
    file2_finl = int(file2_fin.get())
    cettecolonnel = cettecolonne.get()
    range1l = int(range1.get())
    range2l = int(range2.get())
    binsl = int(bins.get())
    legend1l = legend1.get()
    legend2l = legend2.get()
    axeXl = axeX.get()
    axeYl = axeY.get()
    sortiel = sortie.get()

    # Chemin d'acces vers les fichiers à traiter
    dvol = r'\\C:\1704_Test_maj_horaire_RERD_Sc2012\090721_DVOL_km.txt'

    # Traitement de dvol
    dvol = pd.read_csv(dvol, sep = '\t')  # Lecture
    dvol = dvol.rename(columns = {'ZONEO': 'NumZoneE', 'ZONED': 'NumZoneA'})  # Renommage entete
    dvol = dvol[(dvol.DVOL != 0)]  # Suppression intrazonaux

    fig = plt.figure()
    gss_oui = traitement(dirname, file1_debl, file1_finl).get_group('oui')
    gss_non = traitement(dirname, file1_debl, file1_finl).get_group('non')
    gac_oui = traitement(dirname2, file2_debl, file2_finl).get_group('oui')
    gac_non = traitement(dirname2, file2_debl, file2_finl).get_group('non')

    plt.hist([gss_oui[cettecolonnel], gac_oui[cettecolonnel]], range = (range1l, range2l), bins = binsl, label = [legend1l, legend2l])
    plt.legend(loc = 'best')
    plt.title(titrel)
    plt.xlabel(axeXl, labelpad = 5)
    plt.ylabel(axeYl)
    plt.savefig(path.join(wd, sortiel))
    plt.show()
    plt.close()

if __name__ == '__main__':
    #app = Application()
    style = ttk.Style()
    style.configure("BW.TEntry", foreground="grey", background="white")
    style.configure("BW1.TEntry", foreground="black", background="white")
    #app.master.title('Comparaison de fichiers')

    mainframe = ttk.Frame(padding="3 3 12 12")
    mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
    mainframe.columnconfigure(0, weight=1)
    mainframe.rowconfigure(0, weight=1)

    # construction du champ file1
    file1 = StringVar()
    file1_deb = StringVar()
    file1_fin = StringVar()
    file1 = ttk.Entry(mainframe, width=20, style="BW.TEntry")
    file1.insert(0, 'Choisissez un fichier...')
    file1.grid(column=2, row=1, sticky=W)
    file1.bind('<FocusIn>', on_entry_click)
    ttk.Label(mainframe, text="Fichier n° 1 : ").grid(column=1, row=1, sticky=E)
    file1_deb = ttk.Entry(mainframe, width=5, textvariable=file1_deb)
    file1_deb.insert(0, "26")
    file1_deb.grid(column=4, row=1, sticky=W)
    ttk.Label(mainframe, text="ligne de début").grid(column=3, row=1, sticky=E)
    file1_fin = ttk.Entry(mainframe, width=5, textvariable=file1_fin)
    file1_fin.insert(0, "1307")
    file1_fin.grid(column=6, row=1, sticky=W)
    ttk.Label(mainframe, text="lignes de fin à supprimer").grid(column=5, row=1, sticky=E)

    # construction du champ file2
    file2 = StringVar()
    file2_deb = StringVar()
    file2_fin = StringVar()
    file2 = ttk.Entry(mainframe, width=20, style="BW.TEntry")
    file2.insert(0, 'Choisissez un fichier...')
    file2.grid(column=2, row=2, sticky=W)
    file2.bind('<FocusIn>', on_entry_click1)
    ttk.Label(mainframe, text="Fichier n° 2 : ").grid(column=1, row=2, sticky=E)
    file2_deb = ttk.Entry(mainframe, width=5, textvariable=file2_deb)
    file2_deb.insert(0, "26")
    file2_deb.grid(column=4, row=2, sticky=W)
    ttk.Label(mainframe, text="ligne de début").grid(column=3, row=2, sticky=E)
    file2_fin = ttk.Entry(mainframe, width=5, textvariable=file2_fin)
    file2_fin.insert(0, "1307")
    file2_fin.grid(column=6, row=2, sticky=W)
    ttk.Label(mainframe, text="lignes de fin à supprimer").grid(column=5, row=2, sticky=E)

    #champ("cettecolonne", "JRTA", 2, 3, "Champ à comparer :", 1, 3, 20)
    cettecolonne = StringVar()
    cettecolonne = ttk.Entry(mainframe, width=20, textvariable=cettecolonne)
    cettecolonne.insert(0, "JRTA")
    cettecolonne.grid(column=2, row=3, sticky=W)
    ttk.Label(mainframe, text="Champ à comparer :").grid(column=1, row=3, sticky=E)

    #champ("titre", "Titre du graphique", 2, 4, "Titre du graphique :", 1, 4, 20)
    titre = StringVar()
    titre = ttk.Entry(mainframe, width=20, textvariable=titre)
    titre.insert(0, "Titre du graphique")
    titre.grid(column=2, row=4, sticky=W)
    ttk.Label(mainframe, text="Titre du graphique").grid(column=1, row=4, sticky=E)

    #champdouble("range1", 0, "range2", 100, 2, 5, "Xmin :", "Xmax :", 1, 5)
    range1 = StringVar()
    range1 = ttk.Entry(mainframe, width=7, textvariable=range1)
    range1.insert(0, 0)
    range1.grid(column=2, row=5, sticky=W)
    ttk.Label(mainframe, text="Xmin :").grid(column=1, row=5, sticky=E)
    range2 = StringVar()
    range2 = ttk.Entry(mainframe, width=7, textvariable=range2)
    range2.insert(0, 100)
    range2.grid(column=4, row=5, sticky=W)
    ttk.Label(mainframe, text="Xmax :").grid(column=3, row=5, sticky=E)

    #champ("bins", 20, 2, 6, "Nombre d'intervalle :", 1, 6, 5)
    bins = StringVar()
    bins = ttk.Entry(mainframe, width=5, textvariable=bins)
    bins.insert(0, 20)
    bins.grid(column=2, row=6, sticky=W)
    ttk.Label(mainframe, text="Nombre d'intervalle :").grid(column=1, row=6, sticky=E)

    #champdouble("legend1", "file1", "legend2", "file2", 2, 7, "Légende du fichier n°1 :", "Légende du fichier n°2 :", 1, 7, 20)
    legend1 = StringVar()
    legend1 = ttk.Entry(mainframe, width=20, textvariable=legend1)
    legend1.insert(0, "fichier 1")
    legend1.grid(column=2, row=7, sticky=W)
    ttk.Label(mainframe, text="Légende du fichier n°1 :").grid(column=1, row=7, sticky=E)
    legend2 = StringVar()
    legend2 = ttk.Entry(mainframe, width=20, textvariable=legend2)
    legend2.insert(0, "fichier 2")
    legend2.grid(column=4, row=7, sticky=W)
    ttk.Label(mainframe, text="Légende du fichier n°2 :").grid(column=3, row=7, sticky=E)

    #champ("axeX", "Axe des X", 2, 8, "Nom de l'axe des x :", 1, 8, 20)
    axeX = StringVar()
    axeX = ttk.Entry(mainframe, width=20, textvariable=axeX)
    axeX.insert(0, "Axe des X")
    axeX.grid(column=2, row=8, sticky=W)
    ttk.Label(mainframe, text="Nom de l'axe des x :").grid(column=1, row=8, sticky=E)

    #champ("axeY", "Axe des Y", 2, 9, "Nom de l'axe des y :", 1, 9, 20)
    axeY = StringVar()
    axeY = ttk.Entry(mainframe, width=20, textvariable=axeY)
    axeY.insert(0, "Axe des Y")
    axeY.grid(column=2, row=9, sticky=W)
    ttk.Label(mainframe, text="Nom de l'axe des y :").grid(column=1, row=9, sticky=E)

    #champ("sortie", "image.png", 2, 10, "Nom du .png sauvegardé :", 1, 10, 20)
    sortie = StringVar()
    sortie = ttk.Entry(mainframe, width=20, textvariable=sortie)
    sortie.insert(0, "image.png")
    sortie.grid(column=2, row=10, sticky=W)
    ttk.Label(mainframe, text="Nom du .png sauvegardé :").grid(column=1, row=10, sticky=E)

    ttk.Button(mainframe, text="clic !", command=callback).grid(column=4, row=10, sticky=W)
    ttk.Button(mainframe, text='Quitter', command=quit).grid(column=5, row=10, sticky=W)

    for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
    mainloop()

Function champ et champdouble doesn't work. Class doesn't work. But code run !

What function put into the class ? How get the result of a function more easily ? Why function into a class and the same funtion out of a class haven't the same number of argument instead when they have visibly the same number of argument ? I begin in Python, it's hard but it's a lot of fun !