jeudi 31 décembre 2015

C# - Array of a class that holds arrays of another class, readable/writable in XML

I know I'm probably jumping into the deep end with this as I'm kinda new to c#.

My main goal is to create a class (lets call it "test1") with variables, one of which is an array. Another class (we'll call this "test2") will hold other variables, some of which are arrays of the class "test1".

The size of the arrays are variable and not exactly fixed. I want to be able to increase/decrease the size of them during runtime. I also intend for it to be writable and readable to a file, such as XML. So, from what I understand, it has to be capable of being "serialized".

Would it look something like this?

public class test1
{
    public String test1_name;
    public String test1_id;
    public Single test1_value;
    public String[] test1_list;
}

public class test2
{
    public test1[] test2_list1;
    public test1[] test2_list2;
    public String[] test2_list;
}

I have managed to figure out how to use XML serialization to write the file. E.G.

System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(test_a)); //test_a being a simple class holding a simple variable

var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//tester.txt";
System.IO.FileStream file = System.IO.File.Create(path);
writer.Serialize(file, tester);
file.Close();

I want to ensure that I can write and read this data (either as XML or binary, I will decide later) and have it modifiable during runtime, along with the array sizes being adjustable.

Am I going about this the wrong way? How would I construct this and have it usable and saveable/readable?

Can somebody help put me on the right track for what I want to achieve? I know it may be a big ask, but some examples would be so greatly appreciated.

Sorry if this is a bit of a mess.

Thank you all very much in advance!




Beginner that is severely confused about variables and how to work with them across various areas of the code

I have copy pasted the entire code below. I understand that this question is asked elsewhere though I do think maybe my program has some unique qualities that could use a little more specific help if at all possible.

Let me explain my program a bit (there is a link below to a more comprehensive explanation of the idea).

So, I have a bunch of MIDI notes. Say, note A, B, and C.

In my last program I defined them all globally and it was a huge pain. But it did work. It just looked horrible. And every time I wanted to add more, it was really time consuming. When the program reached full size, it took me up to an hour to just add 4 new notes.

Here is a bigger explanation of the software I am working on and a picture to give you an idea of what I'm trying to do:

http://ift.tt/1JNom4Q

PROBLEMS:

  1. the first issue is that having two variables ap and aap means that every single pitch and its scale require two variables for the same thing.

  2. ap has to be defined as a=0 along with "global a"

  3. aap also requires "global aap"

  4. the lists of the 26 original globals and the 26 global copies that are made for the scales have to be copied into every area

  5. the individual variables have to be carefully plugged into complex functions elsewhere in the code: EX - the Pitch Mod scale sets a function that adds a number set by the user to every note after any given permutation - this function is actually rather complicated and it is time consuming adding the variable ap into every single part of the function

  6. I stopped adding new "note" objects after 26 for all the letters of the alphabet - this is not the question though, the question is how to just create a ton of variables and be able to plug them in across the entire program in a more sophisticated and flexible manner than simply having to define them all manually

TLDR:

Primary Question: I really just want answered is how to just not have to ever use global variables again like this and to simply be able to have common, simple variables across the entire program

Secondary Question: How to create variables and have a more sophisticated system that is able to bend and define things via perhaps complex dictionary/list structures and then fit them into the entire framework without having to be written out in such a systematic and "rigid" manner - in other words, perhaps a more fluid and advanced idea for how you might work with this concept?

I really appreciate it, and have also posted the image of a more simple possible version of the problem for you to look at:

Thanks and happy new years




Python deposit methods not working as expected for a small banking system

I am learning python and trying to make a small banking system. When I make a deposit the balance is supposed to increase, when I make a withdrawal the balance is supposed to decrease. This is working correctly up to here. But when I make another deposit, the balance does not increase, the withdraw function works correct. Here is the code saved as BankAccount.py:

class Account(object):
def __init__(self, holder, account_No, balance):
    self.Holder = holder
    self.Account_No = account_No
    self.Balance = balance

def deposit(self, amount):
    self.Balance += amount
    return self.Balance
def withdraw(self, amount):
    if (self.Balance < amount):
        #Print "Insufficient funds."
        return False
    else:
        self.Balance -= amount
        return self.Balance
def balance(self):
        return self.Balance

I run the code in Window Shell as follows:

from BankAccount import Account
jim = Account("Jim", 21894312, 0)
jim.deposit(5000)
jim.balance()
jim.withdraw(2000)
jim.balance() # balance is now 3000
jim.deposit(3000)
jim.balance() # balance reads 3000 instead of 6000 




Default constructor with normal constructors for calsses c++

I have been trying to understand the default constructor and i think i get it if it's the only constructor in the class. But what if i have more than one constructor defined in the class. What i am trying to do is to create a class "vector", which would store two dimensional vectors. I need one constructor to set the coordinates to the values given in the main function. I also need a default constructor, which when called, would set the coordinates to 0. I can't seem to figure out how to make both work in the same code

#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <algorithm>

using namespace std;

class Vector {
    double x_coord, y_coord;
public:
Vector(double x_coord=0, double y_coord=0); //default contructor???

Vector (double x, double y) //normal constructor
{
    set_values (x,y);
}
void set_values(double new_x, double new_y) //function to set values for the vectors
    {
        x_coord=new_x;
        y_coord=new_y;
    }
   double get_x()
    {
        return x_coord;
    }
   double get_y()
    {
        return y_coord;
    }

};




PHP __autoload() from lower directory

I a primary website and a site using a subdomain with the following directory structure

Primary website:

/home/mysite/public_html/

Subdomain:

/home/mysite/subdomain/

I would like my classes directory to be shared between the primary and subdomain. The classes reside here:

/home/mysite/public_html/classes/

I am trying to autoload the classes from a file in the subdomain's directory

/home/mysite/subdomain/includes/bootstrap.php

which contains this code:

$classdir = '/home/mysite/public_html/classes/';

function __autoload($class_name) {
    var_dump($class_name);
    require_once ($classdir.$class_name.'.php');
}

My issue is that the classes are not being loaded.

Please note this code works perfectly when used in a file located in the primary domain directory:

/home/mysite/public_html/includes/bootstrap.php

Including them individually works fine, such as:

require_once($classdir.'/class1.php');
require_once($classdir.'/class2.php');

However there are dozens of them and i would like to autoload them

Thank you for your time.




Sub class call parent class recursion java

Happy new year guys :-) I need your help to understand my mistake.

I created board class and cell class who extended the board class, and in the board class I also have an array of the cells. When I run my code I got java.lang.StackOverflowError exception.

board class:

Cell boardGame[][] = new Cell[8][8];

public Board() {
    /*
     * for (int i = 0; i < board.length; i++) { for (int j = 0; j <
     * board[i].length; j++) { board[i][j] = "-"; }
     */
    reorder();
    printBoard();
}

public void reorder() {
    for (int i = 0; i < 8; i++) {
        boardGame[1][i] = new Cell((new Pawn(ChessPiece.PAWN, Color.BLACK)), 1, i);
        boardGame[6][i] = new Cell((new Pawn(ChessPiece.PAWN, Color.WHITE)), 6, i);
    } 
{...}

Cell class:

public Cell(int xPosition, int yPosition) {
        position = new MoveSet(xPosition, yPosition);
        color = null;
        display = null;
    }

    public Cell(Soldier soldier, int xPosition, int yPosition) {
        this(xPosition, yPosition);
        this.soldier = soldier;
        setRoleMark();
    }

{...}

When I try to debug I notice that my Cell constructor go to the Board constructor and run reorder() again, then it create another Cell constructor that go to the Board constructor and run reorder again...

I realized it's a terrible design because my Cell class doesn't need anything from the Board class anyway, but I want to understand why it happened. I never called super, so why my cell class call the board constructor?

My guess is that every Cell try to create Cell boardGame[][] = new Cell[8][8] from it super class (because sub class got the super variable right?) so it basically trying to create itself.

But I am not sure, can you approve it to me?

Thanks, Or




Want to move GET method inside POST, Volley

I want to move GET method inside if that located inside onResponse of POST request without calling URL again because once client post edittext php file will echo json result that will show up inside listview in activity so if call URL again in other method nothing will show up, how can I do that please?

public class supportActivity extends AppCompatActivity implements View.OnClickListener{

private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://ift.tt/1NXzXA2";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_support);

     ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
     supportlist = (ListView)findViewById(R.id.supportlistview);
     adapter = new supportAdapter(this, con);
    supportlist.setAdapter(adapter);
     button = (Button)findViewById(R.id.buttonsupprt);

    button.setOnClickListener(this);


}

private void inquiry() {

         ticketinput = ticketsupport.getText().toString().trim();

    StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    if (response.trim().equals("responseticket")) {
                        showTicket();

                    } else {
                        Toast.makeText(supportActivity.this, "Check the number please", Toast.LENGTH_SHORT).show();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
        }
    }) {

        @Override
    protected Map<String,String> getParams() throws AuthFailureError{
            Map<String,String> map = new HashMap<String,String>();
            map.put("ticknumber", ticketinput);
            return map;
        }
    };

    RequestQueue requestQueue1 = Volley.newRequestQueue(getApplicationContext());
    requestQueue1.add(stringRequest1);

}
private void showTicket(){
        RequestQueue requestQueue2 = Volley.newRequestQueue(this);

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        JSONArray jsonArray = response.getJSONArray("responseticket");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject ticket = jsonArray.getJSONObject(i);
                            supportContent support = new supportContent();

                            support.setTicketnumber(ticket.getString("ticketnumber"));
                            support.setSubject(ticket.getString("subject"));
                            support.setResponse(ticket.getString("response"));

                            con.add(support);

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.e("error", "Volley");
        }
    }
    );
    requestQueue2.add(jsonObjectRequest);
}
@Override
public void onDestroy(){
    super.onDestroy();
}
 @Override
    public void onClick(View view){
        inquiry();
 }
}




Nested Classes and ADL

Here's the code:

namespace Namespace
{
    struct L0
    {
        enum SomeEnum
        {
            EnumVal
        };

        struct L1
        {
            friend void f(SomeEnum)
            {
                std::cout << "f()" << std::endl;
            }
        };

        friend void g(SomeEnum)
        {
            std::cout << "g()" << std::endl;
        }
    };
}

int main()
{
    f(Namespace::L0::EnumVal); // error: f not defined
    g(Namespace::L0::EnumVal); // good
}

The idea here is to make the compiler find f() and g() through ADL.

However, this code fails to compile with gcc or clang. The similar code seemed to compile fine under MSVC though.

Maybe I miss something, but I don't really understand what is wrong with the code, and whether it is wrong at all. Would be nice if someone could shed some light on this one.

PS. Happy new year:)




Using a method for a null class

Say I have a class

class T
{
    int num;
    public T(int num)
    {
        this.num = num;
    }
    public void p()
    {
        Console.WriteLine(this.num);
    }
}

And I have a null object T t = null. Calling the method t.p() will cause a NullReferenceException no matter what.

Is it not possible to test if the object is null (by using this == null), so is there a way to set a default method that will work on a null object?




Create an interactive command loop using inheritance python34

I'm trying to see how I can structure a script in a way that I can use the inheritance method. I'm fairly new to python. And my problem is using variables in one class from another class-def. I just recently learned about the super function and I don't think I'm using it right because it keeps printing and recalculating everything that it's pulling from.

Let's say I have a bunch of messages coming in a text file delimited by commas that give me different information. I want to be able to take that text file and...

1. be able to read the content delimited by commas (done)
2. tell me how many of each type of message there are (done)
3. then create a class called messages that has defs for each type of message with its respective calculations and variables it creates in those instances (done)
4. create class to print and write those calculations and variables in the client and xls(partially done due to my issue)
5. create class to convert xls to csv and kml (somewhat done)


Here is a toy structure of what I'm working with


import bunch of stuff


data = []  #empty because we will store data into it


#Reads a CSV file and return it as a list of rows
def read_csv_file(filename):
    """Reads a CSV file and return it as a list of rows."""

    for row in csv.reader(open(filename)):
        data.append(row)
    return data

f = open(path_in + data_file)
read_it = read_csv_file(path_in + data_file)

with f as csvfile:
    readCSV = csv.reader(csvfile,delimiter=',')


#Counts the number of times a GPS command is observed
def list_msg_type_countdata):
    """Counts the number of times a GPS command is observed.

Returns a dictionary object."""

    msg_count = dict()
    for row in data:
        try:
            msg_count[row[0]] += 1 
        except KeyError:
            msg_count[row[0]] = 1

    return msg_count

print(list_msg_type_count(read_it))
print ("- - - - - - - - - - - - -")


class CreateWorkbook
    def openworkbook(data):
        output_filename = input('output filename:')
        workbook = xlsxwriter.Workbook(path_out + output_filename + '_' + command_type +'.xlsx')
        worksheet = workbook.add_worksheet()

    def closeworkbook_msg1(data):
        #sets up the header row
        worksheet.write('A1','item1',bold)
        worksheet.write('B1', 'item2',bold)
        worksheet.write('C1', 'item3',bold)
        worksheet.autofilter('A1:C1')   #dropdown menu created for filtering

        # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
        for r, row in enumerate(data, start=1):  #where you want to start printing results inside workbook
            for c, col in enumerate(data):
                worksheet.write_column(r,0, i1)
                worksheet.write_column(r,1, i2)
                worksheet.write_column(r,2, i3)
        workbook.close()
        f.close()
        print('XLSX file named ' + output_filename + '_' + command_type +' was created')

    def closeworkbook_msg2(data):
        #sets up the header row
        worksheet.write('A1','item1',bold)
        worksheet.write('B1', 'item2',bold)
        worksheet.write('C1', 'item3',bold)
        worksheet.write('C1', 'item4',bold)
        worksheet.autofilter('A1:C1')   #dropdown menu created for filtering

        # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
        for r, row in enumerate(data, start=1):  #where you want to start printing results inside workbook
            for c, col in enumerate(data):
                worksheet.write_column(r,0, i1)
                worksheet.write_column(r,1, i2)
                worksheet.write_column(r,2, i3)
                worksheet.write_column(r,3, i4)
        workbook.close()
        f.close()
        print('XLSX file named ' + output_filename + '_' + command_type + ' was created')      


class ConvertFile
    def convert2csv(data):
        # set path to folder containing xlsx files
        os.chdir(path_out)

        # find the file with extension .xlsx
        xlsx = glob.glob(output_filename + '_' + command_type + '.xlsx')

        # create output filenames with extension .csv
        csvs = [x.replace('.xlsx','.csv') for x in xlsx]

        # zip into a list of tuples
        in_out = zip(xlsx,csvs)

        # loop through each file, calling the in2csv utility from subprocess
        for xl,csv in in_out:
           out = open(csv,'w')
           command = 'c:/python34/scripts/in2csv %s\\%s' % (path_out,xl)
           proc = subprocess.Popen(command,stdout=out)
           proc.wait()
           out.close()
        print('CSV file named ' + output_filename + '_' + command_type + ' was created')

    def convert2kml(data):
        #Input the file name.
        h = open(path_out + output_filename + '_' + command_type + '.csv')
        with h as csvfile2:
            data2 = csv.reader(csvfile2,delimiter=',')
            next(data2)

            #Open the file to be written.
            g = open(output_filename + '_' + command_type +'.kml','w')
            g.write("<?xml version='1.0' encoding='UTF-8'?>\n")
            g.write("<kml xmlns='http://ift.tt/1b6BtQH'>\n")
            g.write("<Document>\n")
            g.write("   <name>" + output_filename + '_' + command_type + '.kml' +"</name>\n")
            for row in data2:
                g.write("   <Placemark>\n")
                g.write("<TimeStamp><when>" + str(row[0]) + "</when></TimeStamp>\n")
                g.write("       <Point>\n")
                g.write("           <coordinates>" + str(row[2]) + "," + str(row[1]) + "</coordinates>\n")
                g.write("       </Point>\n")
                g.write("   </Placemark>\n")


        g.write("</Document>\n")
        g.write("</kml>\n")
        g.close()
        h.close()
        print('and ' + output_filename + '_' + command_type +'.kml was created,too!')


class MessageType:
    def process_msg1(self,data)
        item1 = []
        item2 = []
        item3 = []

        print('printing stuff')

        for r in data:
            if row[0] == 'msg type1'
                item1.append('calculations')
                item2.append('calculations')
                item3.append('calculations')
        print('calculations done')
        return(array(item1),array(item2),array(item3))

    def process_msg2(self,data)
        item1 = []
        item2 = []
        item3 = []
        item4 = []

        print('printing stuff')

        for r in data:
            if row[0] == 'msg type1'
                item1.append('calculations')
                item2.append('calculations')
                item3.append('calculations')
                item4.append('calculations')
        print('calculations done')
        return(array(item1),array(item2),array(item3),array(item4))    

class PrintMSG(MessageType):
    def process_msg1(self, data):
        (i1, i2, i3) = super(PrintMSG, self).process_msg1(data)
        print('printing plus plotting using variables from class Message')

    def process_msg2(self, data):
        (i1, i2, i3,i4) = super(PrintMSG, self).process_msg2(data)
        print('printing plus plotting using variables from class Message') 


#processing piece
keep_asking = True
while keep_asking:
    command_type = input("What message type do you want to look at?")
    if command_type == 'msg type1':
        openworkbook(data)
        msg = MessageType()
        print_msg = PrintMSG()
        print_msg.process_msg1(data)
        closeworkbook_msg1(data) 
        convert2csv(data)
        convert2kml(data)
    elif command_type == 'msg type2':
        openworkbook(data)
        msg = MessageType()
        print_msg = PrintMSG()
        print_msg.process_msg2(data)
        closeworkbook_msg2(data) 
        convert2csv(data)
        convert2kml(data)
    else:
        print("Invalid type:", command_type)

    wannalook = input('Want to look at a message or no?')
    if wannalook == 'no' or 'n':
        keep_asking = False




Error : CoreData: warning: Unable to load class named '' for entity 'Receipt'. But the class is deleted

I've created a subclass of NSManagedObject for my entity, but after I've deleted it because I don't use it, I just have the entity specified in my xcdatamodeld file. And when I use this entity, I now get this message in my console : CoreData: warning: Unable to load class named '' for entity 'Receipt'. Class not found, using default NSManagedObject instead. !

How can I completely delete this class so that Core Data do not more research a class for my entity ?




How to get data from db and set to nested list

I have a nested list<object>:

public class ItemsOfQuestions { 
    public string item_title { get; set; } 
    public Byte item_type { get; set; } 
    public string item_image { get; set; } 
    public Int16 item_grade { get; set;}
} 
public class Questins_With_Items { 
    public string question_title { get; set; } 
    public List<ItemsOfQuestions> list_items { get; set; } 
}

I get data from db and set to list, but I get this error:

The best overloaded method match for 'System.Collections.Generic.List.Add(graph1.ViewModels.ItemsOfQuestions)' has some invalid arguments

Can anybody help?




Same Count Value is Returned for Different Queries [PHP]

I am writing a simple class and there is a public query function. Along with results and some other data, the function returns row count of returned results too. Everything works fine but the count returned is same for all queries.

Example:

$count1 = $db->query("SELECT * FROM users")->count(); // i.e. 10 records
$count2= $db->query("SELECT * FROM articles")->count(); // still 10 but they should not

As you can see in above queries that both are different and there are different record counts too, still the returned count is same for different queries. Any solution please? Here is my class snippet:

<?php
    class DB {
        private $_pdo, $_query, $_errors, $_results = false, $_count = 0;
        public function query($sql = NULL, $params = array()) {
            if($this->_query = $this->_pdo->prepare($sql)) {
                if(count($params)) {
                    $i = 1;
                    foreach($params AS $param) {
                        $this->_query->bindValue($i, $param);
                        $i++;
                    }
                }

                if($this->_query->execute()) {
                    $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                    $this->_count = $this->_query->rowCount(); // tried count() too
                } else {
                    $this->_errors = true;
                }
            }
            return $this;
        }

        public function count() {
            return $this->_count;
        }
    }
?>




Type mismatch error using custom class subroutine in Excel VBA

Working in Excel VBA, I have a class module where I define my class 'Marker'. One of the properties of my class is TextLine(), which is an array that holds up to 5 strings. I have defined the two methods below in my class module. In another (regular) module, I fill markerArr() with my custom Marker objects. Loading each object's properties with data at each array index is working fine... However, after loading data into the object at each index, I try to use markerArr(count).ProcessLines but receive a type mismatch error. Since ProcessLines is a public sub in my class module, and markerArr(count) contains a Marker object, I can't seem to understand why this error is occurring... Am I overlooking something obvious?

'Serial number replacement processing function
Public Sub ProcessLines()

    Dim strSerial As String
    Dim toggle As Boolean
    toggle = False

    Dim i As Integer
    For i = 0 To 4
        If Trim(m_TxtLines(i)) <> "" Then
            'Add linefeed char to non-empty text lines
            m_TxtLines(i) = m_TxtLines(i) & Chr(10)

            'Detect if it is a serialized line
            If InStr(1, m_TxtLines(i), "XXXXXX-YYY") > 0 Then
                m_Serial(i) = True
                toggle = True
            End If
        End If
    Next

    'When at least one line on the marker is serialized, create and replace serial text
    If toggle = True Then
        'Only prompt for input once
        If startSerNo < 1 And Num_Sers < 1 Then
            startSerNo = InputBox("Enter the serial number to start printing at." & Chr(10) & _
                "Entering 1 will result in -001, entering 12 will result in -012, etc.", "Starting Serial #", "1")

            Num_Sers = InputBox("Enter the amount of serializations to perform." & Chr(10) & _
                "This will control how many copies of the entire marker set are printed.", "Total Serializations", "1")
        End If

        strSerial = CreateSerial(startSerNo)

        Dim j As Integer
        For j = 0 To 4
            If m_Serial(j) Then
                m_TxtLines(j) = Replace(m_TxtLines(j), "XXXXXX-YYY", strSerial)
            End If
        Next
    End If

End Sub

'Creates the string to replace XXXXXX-YYY by concatenating the SFC# with the starting serial number
Private Function CreateSerial(ByVal startNum As Integer)
    Dim temp
    temp = SFC_Num

    Select Case Len(CStr(startNum))
        Case 1
            temp = temp & "-00" & startNum
        Case 2
            temp = temp & "-0" & startNum
        Case 3
            temp = temp & "-" & startNum
        Case Else
            temp = temp & "-001"
    End Select

    CreateSerial = temp
End Function




Polymorphism class not working C++

I'm trying to learn polymorphism from a interactive Ebook and copied the code example onto VSO but I made .h and .cpp class files instead of keeping it all in one file but keep getting errors

the main.cpp is called PolyMorphism.cpp

PolyMorphism.cpp

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include "GenericItem.h"
#include "ProduceItem.h"

using namespace std;

int main()
{


    GenericItem* genericItemPtr = 0;
    ProduceItem* produceItemPtr = 0;
    vector<GenericItem*> inventoryList;
    int i = 0;

    genericItemPtr = new GenericItem;
    genericItemPtr->setName("Smith Cereal");
    genericItemPtr->setQuantity(9);

    produceItemPtr = new ProduceItem;
    produceItemPtr->setName("Apple");
    produceItemPtr->setQuantity(40);
    produceItemPtr->SetExpiration("May 5, 2012");

    genericItemPtr->PrintItem();
    produceItemPtr->PrintItem();

    inventoryList.push_back(genericItemPtr);
    inventoryList.push_back(produceItemPtr);

    cout << endl << "Inventory:" << endl;

    for (i = 0; i < inventoryList.size(); ++i) {
        inventoryList.at(i)->PrintItem();
    }


    system("pause");
    return 0;
}

My base class GenericItem.h

#pragma once
#include <iostream>
#include <string>
class GenericItem
{
public:
    void setName(string newName);
    void setQuantity(int newQty);
    virtual void PrintItem();

protected:
    string itemName;
    int itemQuantity;
};

GenericItem.cpp

#include "stdafx.h"
#include "GenericItem.h"
#include <iostream>
#include <string>

using namespace std;

void GenericItem::setName(string newName)
{
    itemName = newName;
    return;
}


void GenericItem::setQuantity(int newQty)
{
    itemQuantity = newQty;
    return;
}


void GenericItem::PrintItem() 
{
    cout << itemName << " " << itemQuantity << endl;
    return;
}

Derived class ProduceItem.h

#pragma once
#include "GenericItem.h"
#include <iostream>
#include <string>
class ProduceItem :
    public GenericItem
{
public:
    void SetExpiration(string newdate);

    string GetExpiration();

    void PrintItem();

private:
    string expirationDate;
};

ProduceItem.cpp

#include "stdafx.h"
#include "ProduceItem.h"
#include <iostream>
#include <string>

using namespace std;

void ProduceItem::SetExpiration(string newDate) {
    expirationDate = newDate;
}

string ProduceItem::GetExpiration() {
    return expirationDate;
}

void ProduceItem::PrintItem() {
    cout << itemName << " " << itemQuantity
        << " (Expires: " << expirationDate << ")" << endl;

    return;
}

My Output should be

Smith Cereal 9 Apple 40 (Expires: May 5, 2012)

Inventory: Smith Cereal 9 Apple 40 (Expires: May 5, 2012)

But I get 33 errors some are

syntax error identifier 'string'

'itemName': unknown overrie specififer




How to get inheritance to work from parent to child class python34

I'm trying to get the concept of inheritance. I'm trying to get the work done in Parent (class gps) into Child (print_gps). I'm using xlsxwriter to save gps data into an excel.

For some reason I can't get the data from class gps to be used in class print_gps. Am I missing a step?

 #Function process_gps_data for GPS 

class gps:
    print ("- - - - - - - - - - - - -")
    print('We got class')
    print ("- - - - - - - - - - - - -")



    def process_gprmc_data(data):
        """Processes GPS data, NMEA 0183 format.
    Returns a tuple of arrays: latitude, longitude, velocity [km/h],
    time [sec] and number of satellites.
    See also: http://ift.tt/1iggiz0.
    """
        NMI = 1852.0
        latitude  = []
        longitude = []
        altitude  = []
        velocity  = []
        timestamp = []
        num_sats  = []

        print ("- - - - - - - - - - - - -")
        print('process_gprmc_data')
        print ("- - - - - - - - - - - - -")
        for row in data:

            if row[0] == '$GPRMC':     # Valid position/time sentence
                y = (float(row[3][0:2]) + float(row[3][2:])/60.0)
                if row[4] == "S":
                    y = -y
                latitude.append(y)
                x = (float(row[5][0:3]) + float(row[5][3:])/60.0)
                if row[6] == "W":
                    x = -x
                longitude.append(x)
                print('x,y:',x,y)
                velocity.append(float(row[7])*NMI/1000.0)
                gpstime = row[1][0:6]                     # hhmmss
                gdate = row[9]                            # ddmmyy
                gpsdate = gdate[4:6]+gdate[2:4]+gdate[0:2]  # yymmdd
                real_time =gpsdate + gpstime
                add_date_time = datetime.strptime(real_time, "%y%m%d%H%M%S")
                print(add_date_time)
                timestamp.append(add_date_time)
        print ("- - - - - - - - - - - - -")
        print('arrays in')
        print ("- - - - - - - - - - - - -")
        return (array(latitude), array(longitude), array(velocity), array(timestamp))

    #had to create another function to print results
class print_gps(gps):
    def __init__(self):
        self.gps = gps()        
        super(print_gps, self).__init__() 

    def process_gprmc_data(self):     
        self.gps.process_gprmc_data()
        # how to call process_gprmc_data()
        (lati, long, v, t_stamp) = self.gps.process_gprmc_data(data)
#    def print_gprmc(process_gprmc_data):
        print('got definitions in')
        print ("- - - - - - - - - - - - -")
        print('lati:',lati)
        print ("- - - - - - - - - - - - -")
        print('long:',long)
        print ("- - - - - - - - - - - - -")
        print('v:',v)
        print ("- - - - - - - - - - - - -")
        print('date:', t_stamp)
        print ("- - - - - - - - - - - - -")
        if rows > 200:
            print('Big file please wait...thinking')

        #sets up the header row
        worksheet.write('A1','TimeStamp',bold)
        worksheet.write('B1', 'Latitude',bold)
        worksheet.write('C1', 'Longitude',bold)
        worksheet.write('D1', 'Velocity',bold)
        worksheet.autofilter('A1:D1')   #dropdown menu created for filtering

        # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
        for r, row in enumerate(data, start=1):  #where you want to start printing results inside workbook
            for c, col in enumerate(data):
                worksheet.write_column(r,0, t_stamp, date_format)
                worksheet.write_column(r,1, lati)
                worksheet.write_column(r,2, long)
                worksheet.write_column(r,3, v)


        workbook.close()
        f.close()
        print('XLSX file named ' + output_filename + ' was created')


#processing piece

command = input("What type do you want to look at?")
if command == '$GPRMC':
#    nmea_defs.gps(data)
    gps.process_gprmc_data(data)
    print_gps.process_gprmc_data(data)


else:
    print("Invalid type:", command)

I get this as a result and error:

process_gprmc_data
- - - - - - - - - - - - -
x,y: 139.64428333333333 35.892158333333334
2001-07-18 00:24:54
x,y: 139.64430166666668 35.892201666666665
2002-07-18 00:24:56
x,y: 4.8333433333333335 45.00351833333333
2003-08-14 10:47:09
x,y: 5.00001 51.00351833333333
2004-08-14 10:47:15
- - - - - - - - - - - - -
arrays in
- - - - - - - - - - - - -
Traceback (most recent call last):
  File "C:\Python34\choose_nmea.py", line 222, in <module>
    print_gps.process_gprmc_data(data)
  File "C:\Python34\choose_nmea.py", line 171, in process_gprmc_data
    self.gps.process_gprmc_data()
AttributeError: 'list' object has no attribute 'gps'




Class Button needs Function Pointers

I have a class named Button.It holds 4 variables : x,y,width,height.In my program i have many buttons and for each button i would need a diferent function.Something like a vector of pointers to functions.I have no idea how to do that.Please guide me.




How can I instantiate the constructor of the inner class for an object of the outer class?

I am trying to implement a class, that has another class as a member.

class Book
{
    class Author;
}

In a .cpp file I am implementing the class Author as follows:

class Author
{
    string firstName;
    string lastName;
public:
    // the constructor for the class
    Author(string _firstName, string _lastName)
    {
        firstName = _firstName;
        lastName = _lastName;
    }
}

I want to do the following: in main, when I declare an object of class Book, I want it to instantiate the constructor of the class Author, from the code above. I was thinking of doing so by passing the parameters to the constructor of the Book class, and then using them to instantiate the constructor of Author, like this:

Book::Book(string a, string b)
{
    Book::Author(a, b);
}

But if I do so, if I have another inner class, as a member of the class Book, that has, let's say - 4 members, I would have too many parameters for the constructor of Book.

So my question is: is there another way to instantiate the constructor of a class that is a member when I create an object of the main class?

And also, how do I print the members of that main class, if these members are classes? I tried to overload the << operator for the inner classes, but I get the error: "invalid use of nonstatic data member."




Difference between __getattribute__ and obj.__dict__['x'] in python?

I understand that in python, whenever you access a class/instance variable, it will call __getattribute__ method to get the result. However I can also use obj.__dict__['x'] directly, and get what I want.

I am a little confused about what is the difference? Also when I use getattr(obj, name), is it calling __getattribute__ or obj.__dict__[name] internally?

Thanks in advance.




Swift 2.1 not recognizing my class

I have clipsTableViewController.swift file which contain clipsTableViewController class in this class I called DataManager class from another swift file which I created in project using cmnd+N and selecting swift file. But I get this confusing error message : Use of Unresolved Identifier DataManager

you can see it in the picture below : enter image description here

DataManager class : enter image description here

Any suggestion?




mercredi 30 décembre 2015

Get the function result from a class

I have a function inside a class, and I would like to get the result of this function, something like:

Returned dangerous functions are: dl, system

Here is my code

public final function filterFile(){

$disabled_functions = ini_get('disable_functions');

$disFunctionsNoSpace = str_replace(' ', '', $disabled_functions);

$disFunctions = explode(',', $disFunctionsNoSpace);

$this->disFunctions = $disFunctions;

// get file content of the uploaded file (renamed NOT the temporary)
$cFile = file_get_contents($this->fileDestination, FILE_USE_INCLUDE_PATH);


$found = array();

foreach($this->disFunctions as $kkeys => $vvals)
{            
    if(preg_match('#'.$vvals.'#i', $cFile))
    {                  
        array_push($found, $vvals);

    } 
} // end foreach

} // end filterFile

// calling the class
$up = new uploadFiles($filename);

$fileterringFile    = $up->filterFile();

print_r($fileterringFile);
var_dump($fileterringFile);

Thanks in advance




c# Custom class for lists

I have built a custom calendar control (like google calendar and outlook calendar)

I want to add the functionality to handle events(Add, remove, etc). I already have it, but I want it to feel as generic as possible.

How my code currently looks:

myCalendar.Events.Add(myEvent);
myCalendar.Draw //this adds all the events to the calendar

Example of what I think looks more generic:

myCalendar.Events.Add(myEvent);
myCalendar.Events.Remove(unwantedEvent);
myCalendar.Events.Draw

My question. Is the second code-snippet best practice or should I just go with a separate class for handling drawing and such. (which I currently have)

If the second snippet is better, how do I go about doing so?

Rough Example of one of the methods I've tried (to give you an idea of what I want to accomplish)

public _Events Events = new _Events();

public class _Events
{
    public List<Event> Events = new List<Event>();

    void Add(...)
    {
        //Add event to Events
    }

    void Clear()
    {
        ...
    }
}

public class Event
{
    public String Title { get; set; }
}

The problem with the above code is that i want to be able to return a default value like so...

listOfEvents =  myCalendar.Events

Disclaimer: I have tried in vain to find a solution, but couldn't find the right keywords to find it




Dynamically read class names and pair / append matching divs

I've looked at many posts about doing vaguely the same tasks individually and I get the basic concepts, but I'm wondering how to put it all together into one clean script. I think the trickiest part is getting a certain classname from div, parsing that certain classname and matching it with another classname elsewhere that has a matching letter sequence.

The situation, simplified for clarity: Many dynamic divs with multiple classes / separate parents:

<!— visible - holds filterable portfolio grid of logos —>
<div id="portfolioGrid">
  <div class=“ portfolio_item project_tag-client_name ” > Logo </div>
  <div class=“ portfolio_item project_tag-diff_client_name ” > Logo </div>
  <div class=“ portfolio_item project_tag-other_client_name ” > Logo </div>
</div>

<!— invisible separate div, holds tooltip contents —>
<div id="tooltips" style=“display:none”>
  <div class=“ portfolio_tooltip info_client_name ” > Project Info </div>
  <div class=“ portfolio_tooltip info_diff_client_name ” > Project Info </div>
  <div class=“ portfolio_tooltip info_other_client_name ” > Project Info </div>
</div>

I'd like to:

1) Dynamically find whole class names of classes that contain “project_tag-...“. In other words, "Find divs with class "project_tag-anything". Only need that one class, particularly the anything variant - Wordpress adds "project_tag-" prefix.

2) Find div inside “portfolio_tooltip” with matching “info_anything”.

3) Append “info_client_name” divs inside the matching “project_tag-client_name” divs.

4) Do all that dynamically without knowing a client_name so that it happens automatically when a new portfolio item / tooltip is created. Preferably with jQuery/JS.

The reason for doing this is so that I can give my non-comp-saavy client an easy/clear editing environment in WP, allow easier CSS manipulation for me, plus make it nearly automatic as long as class client_names match. I already have a tooltip that loads each respective info_content and pops up on hover/tap a logo, but having them under separate parents complicates things for CSS.

Also, feel free to let me know of any better ways of doing this, maybe I'm over thinking it. I dig learning.




Returning a class object based on two variables C++

I need help with something pertaining to classes. I know how to solve it but I am wondering if there is a better solution.

Each of the Tile objects has an x and y position and so does the player. The Tile objects are not in an array. I wonder if there is a way to expedite things other than if-else statements for every single combination like this:

if(x==1)
{
    if(y==1)
    {        
    } 
    else if(y==2)
    {        
    } //ect
} 
else if(x==2)
{    
} //ect

I need a function that will return a Tile object.

Tile getTileBasedOnCoords(int x, int y)
{    
}




Create an object and print it out but turns out printing the reference. How to solve this?

Hi I was looking at another post on stackoverflow about objects, instances.

I tried out some code.

public class Puppy{

   public Puppy(String name){
      // This constructor has one parameter, name.
     System.out.println(name);
   }

   public static void main(String []args){
      // Following statement would create an object myPuppy
      Puppy myPuppy = new Puppy("Tommy");
      Puppy myPuppy2 = new Puppy ("Sally");
      System.out.println(myPuppy);
   }
 }

The output is

Tommy
Sally
Puppy@58886ad0

Question: when I try to print out the object myPuppy in the main method, it prints out its reference instead of the value? How should I solve this?

Thanks a lot!




Screenreader reading classnames?

I was wondering if screenreaders are reading classnames?

ex.: photo description price

<img src>    
<p class="description"> ....
<p class="price">....




Passing a pointer to one derived class to another

I'm still learning basics of c++, but I'm currently working on a project using derived classes and virtual methods. So the situation is: I have a ClassA

class ClassA
{
public:
    virtual void action();
};

And there are two derived classes B and C:

#include "ClassA.h" 

class ClassB: public ClassA
{
public:
    virtual void action();
    int valueB;
};

-

#include "ClassA.h"

class ClassC: public ClassA
{
public:
    virtual void action();
    int valueC;
};

I want to pass a pointer to an object of ClassB as a parameter of action() in ClassC, so I can do something like this:

void ClassC::action(ClassB * ptr)
{
cout << "The value is: " << ptr->valueB;
}

However I cannot find a working way to do it. All of the object pointers are stored in a

vector<ClassA *> objects

where

objects[0]=new ClassC();
objects[1]=new ClassB();

if I try something like

objects[0]->action(object[1])

then I need my virtual method in ClassA to have a parameter ClassB *. And then for a program to recognise the type I tried either including entire ClassB.h (bad idea, it creates a "loop" of includes or something) or using a forward declaration class ClassB; (I get an error about invalid use of incomplete type). And so I'm currently stuck. I hope that everything is clear, but I can of course provide more datails if needed.




PHP: Dynamically call default method

There's the following (example) class:

class klasse
{
    private $var = 'doit';

    function doit($param)
    {
        return md5($param);
    }
    function bla($param)
    {
        // HERES THE PROBLEM
        return $this->{$this->var}($param);
    }
}

// Create new instance
$klasse = new klasse;

// Start the "dynamical output"
echo $klasse->bla('test');

This works fine! But the problem is that I'd like to call the md5() function "directly dynamically". So I don't want to go the detour with "doit()". If I try

private $var = 'md5';

at the beginning of the class I get the following (absolutely senseful) error message:

Fatal error: Call to undefined method klasse::md5() in - on line 13

So I know that this error is senseful but I have no clue how to avoid it?

How can I handle this (to directly call md5())?

Thank you!




How can I dynamically initialize items from the class constructor?

In my class constructor I am initializing many List[DropDownItem] lists ..... I don't want to have to list all of them in the constructor anymore, I want them to be initialized auto-magically.

I have the following, which can identify the type I need to target, but I can't get it across the goal line yet. Can't figure out how to do the "obj = new List(); part.

private void initializeDropdownItemLists()
{
    var props = typeof(UserEditModel).GetProperties();

    foreach (var p in props)
    {
        var type = p.PropertyType;
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        {
            var itemType = type.GetGenericArguments()[0];

            if (itemType == typeof(DropdownItem))
            {
                //p = new List<DropdownItem>();
            }
        }

    }
}




Filter Student class based on enum

I have an abstract class Human and a derived class Student. The Human class has a first name and last name field. The Student class has a new field called 'type', which is an enumeration that has the options PRIMARY, SECONDARY and COLLEGE, and averageGrade field, which is the student's average grades for the year. I need help with defining the Student class with the enumeration. I tried with this:

public class Student extends Human{

private int averageGrade;

public enum TYPE {
    PRIMARY(1), SECONDARY(2), COLLEGE(3);

private int studentType;
TYPE(int stType){
    studentType = stType;
}
 public int GetStudentType()
    {
      return studentType;
    }
 public void SetStudentType(int value) {
     if(value!=1 || value!=2 || value!=3) {
         throw new IllegalArgumentException(" dsfss");
 }
 this.studentType = value;
  }


    public Student(String firstName, String lastName, int studentType, int averageGrade) {
        super(firstName, lastName); 

        this.setAverageGrade(averageGrade);
    }




    public int getAverageGrade() {
        return averageGrade;
    }
    public void setAverageGrade(int averageGrade) {
        if (averageGrade < 2 && averageGrade > 6) {
            throw new IllegalArgumentException ("Student grades are between 2 and 6 inclusive");
        }
    this.averageGrade = averageGrade;
    }

    }

Also I have to print the student with the highest grade from each student type (PRIMARY, SECONDARY and COLLEGE). I don't know what kind of Comperator to use for the enum, the averageGrade is easy, but first I need to sort them based on the 'type' enum. Please help! I will be greatful.




Getting "Error: Could not find or load main class " after copying JARs from one machine to another

I built and ran a JAR on machineA as follows:

java -cp /foo/lib/dep1.jar:/foo/lib/dep2.jar:/foo/export/myjar.jar foo.bar.baz.MyMainClass ... 

So myjar.jar is the JAR I built and the other two its dependencies. Ran without any issues.

I then wanted to do the same on machineB so I copied the 3 JAR files there, then tried:

/non/default/install/java -cp /bar/dep1.jar:/bar/dep2.jar:/bar/myjar.jar foo.bar.baz.MyMainClass ...

and got Error: Could not find or load main class. (NOTE: /non/default/install/java is a separate java install on machineB that I have to use instead of /usr/bin/java. Reason is "historical", i.e. I have no control over this)

On machineA, java -version gives

java version "1.7.0_91"
OpenJDK Runtime Environment (rhel-2.6.2.2.el6_7-x86_64 u91-b00)
OpenJDK 64-Bit Server VM (build 24.91-b01, mixed mode)

On machineB, /non/default/install/java -version gives

java version "1.7.0_65"
Java(TM) SE Runtime Environment (build 1.7.0_65-b17)
Java HotSpot(TM) 64-Bit Server VM (build 24.65-b04, mixed mode)

Both machines are running RedHat 6.

Why am I getting the error and how do I fix it?

Thx!




how can I create with Polymorphy 2D-Array of abstract class?

I want to have a 2D array of an abstract class called Piece. So I made a pointer to a 2D array of Piece in a class called Board that have private field of board -Piece** _board.

I tried to use vector or wrap the board field with class but apperently something went wrong..

class Piece
{
public:
Piece(bool, string);
Piece(){};
bool isChass(bool, Board*);
virtual int move(int x_src, int y_src, int x_dst, int y_dst, Board*   board)=0;
virtual ~Piece();
bool get_isWhite();
string get_type();
Piece(Piece & other);
Piece& operator= (const Piece & other);
bool inRange(int, int);

protected:
bool _isWhite;
string _type;
};


class Board
{
public:
Board();
Board(const Board& other);
~Board();
Board& operator=(const Board &other);
Piece& getPiece(int i, int j){ return _board[i][j]; }
void game();
void deletePiece(int x, int y) { delete &_board[x][y]; }
void allocateBlankPiece(int x, int y) { _board[x][y] = *new Blank(); }

private:
Piece** _board;
bool _isWhiteTurn;


friend class Piece;
friend class Rock;
friend class Bishop;
friend class Queen;
friend class Knight;
friend class King;
friend class Pawn;
};




C++ - Implementing template methods within a CPP file [duplicate]

This question already has an answer here:

I have a non-template class, and within it, some template methods. The methods declaration is in header file (normally), it looks like this:

//foo.h

class foo
{
public:
    foo(){ }
    ~foo(){ }

    template <typename T>
    void foobar(T arg);
};

And then i want to implement it in a separate CPP file, like every class is normally implemented:

//foo.cpp
#include "foo.h"

template <typename T>
void foo::foobar(T arg)
{
    //some awesome code
}

And then it throws an error - undefined reference to 'void foo::foobar<char>(char) !

How to solve this?




Adding class list to combobox

I'm making a list of groupnames which the user writes down in a textbox. After checking whether the groupname already exists, it adds it to the list. I'm trying to add the objects to this list:

List<Group> Groups = new List<Group>();  

The problem I'm having is that I keep getting the error:
An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll

This happens due to the line of code that is supposed to add the groupnames in the combobox:

cbxGroups.DataSource = Groups.ToString();

This is what the class that the list is based on looks like:

class Groep
{
    //Fields
    private string naamGroep;


    //Properties
    public string NaamGroep
    {
        get { return this.naamGroep; }
        set { naamGroep = NaamGroep; }
    }



    //Constructor
    public Groep(string naam)
    {
        this.naamGroep = naam;

    }
}

I'm not sure how to solve this and I was hoping I could find some answers here.




Making an array of pointer to classes

I am trying to make an Array which will contain pointer to a class. The size of the array will be given from keyboard , so i tried to create the array with the following way :

 class creature
 {
    protected:
      string crt_name ;
      int L ;   
    public:
       creature( int Life = -1 , string Name = "")
        : L(Life) , crt_name(Name){} 

       string get_crt_name ( void )
       { 
          return crt_name ;
       }
 }; 

 class creature_society
 {
    private:
       creature* *A ;
       int noc ;
    public:
       creature_society( int , int ) ;
       ~creature_society() ;
       creature** get_A ( void ){return A ;}
 };

The constructor of creature society will fill the array with creatures made randomly

creature_society::creature_society( int life , int number_of_creatures )
{
   noc =  number_of_creatures ;
   A = new creature*[noc] ;

   creature* temporary ;

   for( int  i = 0 ; i<= number_of_creatures -1 ; i++)
   {
     if ( rand()%100 <= 50) 
        {
            temporary = new good_creature( life , get_unique_name( 3 ) );
            A[i] = temporary ;
        }
        else
        {
            temporary = new bad_creature( life , get_unique_name( 3 ) );
            A[i] = temporary ;
        }
  }
}

Then I try to print the array

    cout << endl << "Printing Society:" << endl ;
    for ( j = 0 ; j <= N -1 ; j++)
    {
       temp = (*( cs1.get_A() + j ))->get_crt_name() ;
    }

The problem is that when i am getting segmentation faults when running on linux , while working fine on Dev C++ ( most of the time )! Any mistakes you pointed out ?




Is it possible to create an object in an object which has as constructor the object from which it was created in c++

I am learning to build programs in c++ and am stuck at something basic. I use SDL2 to get inputs from and to deal with screens etc. I have defined an object "Program" and an object "EventHandler". The "EventHandler" handles all events (sends the events to lower level objects), but the "EventHandler" should also be able to create a new window, thus to access "Program".

This means I guess that "EventHandler" should be on the same level as "Program" and they should both be able to communicate with each other. Can this be done in c++ and how? Maybe there is some other more logical way in doing this.

The code below does obviously not work because of the order in which the classes are defined, and my selfmade "&this" to send the address of "program" is wrong, but it gives a nice overview of what I am trying to do.

//handles all events, is in contact with and same level as Program
class EventHandler {
    private:
    Program *program = NULL;
    SDL_Event e;
    //inputarrays
    const Uint8 *currentKeyStates;
    int mouseX = 0;
    int mouseY = 0;
    bool mousemotion = false;
    int mouseButtons[4] = {0, 0, 0, 0};

    public:
    EventHandler(Program *p) {
        program = p;        
    }
    void handleEvents() {
        while(SDL_PollEvent(&e) != 0) {

        }
    }
};

class Program {
    private:
    EventHandler *eh = NULL;
    std::vector<Window> windows;
    public:
    bool running;
    Program() {
        //Here the most basic form of the program is written
        //For this program we will use SDL2
        //Initialize SDL
        SDL_Init(SDL_INIT_EVERYTHING);

        //This program uses 1 window
        Window window(200, 200, 1200, 1000, "");
        windows.push_back(window);
        //Adds an event handler
        eh = new EventHandler(&this);

        //now simply run the program
        run();

    }
    void run() {
        running = true;

        //while (running) {

        //}
        SDL_Delay(2000);

        delete eh;
        //Quit SDL subsystems 
        SDL_Quit();
    }
};

int main( int argc, char* args[]) {

    Program program;

    return 0;
}




Add children to list in loop

I have a listview that is grouped by whatever the user wants it to. It looks smilair to this.

The way the classes are structured (these are classes within a class that is called HourEntry, only for people who want a clear view of what the classes look like):

public class OrderNumber : ObservableCollection<HrEntry>
        {
            public OrderNumber(string P_orderNr){

                orderNr = P_orderNr;
            }

            public string orderNr{ get; set; }
        }


        public class Customer : ObservableCollection<HrEntry>
        {
            public Customer(string P_cName){

                cName = P_cName;
            }

            public string cName{ get; set; }
        }


        public class Week : ObservableCollection<HrEntry>
        {
            public Week(string P_weekNr){

                weekNr = P_weekNr;
            }

            public string weekNr{ get; set; }
        }


        public class HrEntry
        {
            public int HourEntryID{get;set;}
            public string OrderNumber{get;set;}
            public string CompanyName{get;set;}
            public string HourTypeName{get;set;}
            public string Hours{get;set;}
            public string HourEntryDate{get;set;}
        }

Not really interesting, but to make it more clear I've added it anyways.

Now the part where I add items in the listview, in short terms will look in the database and group them.(Again, for the people who want it clear what I'm doing)

public List<HourEntry.OrderNumber> sortByOrderNr(List<HourEntry.OrderNumber> P_orderNrList){

            try {
                int count = 0;
                dbConnection.OpenAsync();
                using(dbCommand = dbConnection.CreateCommand()){
                    dbQuery = "SELECT Count(OrderID) as count from orders WHERE OrderID IS NOT 0;";

                    dbCommand.CommandText = dbQuery;

                    dbReader = dbCommand.ExecuteReader();

                    while(dbReader.Read()){
                        count = Convert.ToInt32(dbReader["count"]);
                    }
                    dbReader.Close();
                    string[] orderIDList;

                    orderIDList = new string[count];
                    count = 0;

                    dbQuery = "SELECT OrderID from orders WHERE OrderID IS NOT 0 ORDER BY OrderID DESC;";
                    dbCommand.CommandText = dbQuery;
                    dbReader = dbCommand.ExecuteReader();
                    while(dbReader.Read()){
                        orderIDList[count] = dbReader["OrderID"].ToString();
                        count++;
                    }
                    dbReader.Close();

                    foreach (string orderId in orderIDList) {

                        dbQuery = "SELECT HourEntryID, OrderNumber, CompanyName, HourTypeName, Hours, HourEntryDate, hour_entries.OrderID FROM hour_entries ";
                        dbQuery += "LEFT OUTER JOIN orders ON orders.OrderID = hour_entries.OrderID ";
                        dbQuery += "LEFT OUTER JOIN customers on customers.CustomerID = hour_entries.CustomerID ";
                        dbQuery += "LEFT OUTER JOIN hour_types on hour_types.HourTypeID = hour_entries.HourTypeID WHERE hour_entries.OrderID = " + orderId + ";";

                        dbCommand.CommandText = dbQuery;
                        dbReader = dbCommand.ExecuteReader();
                        while(dbReader.Read()){

                            P_orderNrList.Add(new HourEntry.OrderNumber(dbReader["OrderNumber"].ToString()){
                                new HourEntry.HrEntry{

                                    HourEntryID = Convert.ToInt32(dbReader["HourEntryID"]),
                                    OrderNumber = dbReader["OrderNumber"].ToString() + "\n",
                                    CompanyName = dbReader["CompanyName"].ToString(),
                                    HourTypeName = dbReader["HourTypeName"].ToString() + "\n",
                                    Hours = dbReader["Hours"].ToString(),
                                    HourEntryDate = dbReader["HourEntryDate"].ToString()
                                }
                            });
                        }
                        dbReader.Close();
                    }
                }

                dbConnection.Close();
                return P_orderNrList;
            } catch (Exception ex) {
                dbConnection.Close ();
                Console.WriteLine (ex);
                return P_orderNrList;
            }
        }//End sortByOrderNR()

LOOK AT THIS PART:

    //The part where a group header is created
        P_orderNrList.Add(new HourEntry.OrderNumber(dbReader["OrderNumber"].ToString()){
//The part where a child is added to the group header
                                        new HourEntry.HrEntry{

                                            HourEntryID = Convert.ToInt32(dbReader["HourEntryID"]),
                                            OrderNumber = dbReader["OrderNumber"].ToString() + "\n",
                                            CompanyName = dbReader["CompanyName"].ToString(),
                                            HourTypeName = dbReader["HourTypeName"].ToString() + "\n",
                                            Hours = dbReader["Hours"].ToString(),
                                            HourEntryDate = dbReader["HourEntryDate"].ToString()
                                        }
                                    });

Finally my question is: Is there a way to first add a group header, then go trough a loop to add the children?

I've been trough the documentation of xamarin.forms for listviews and having groups in them. But nothing answered my question.

If there is anything I didn't explain too well please let me know, thanks in advance.




im not getting the right output?

i dnt know why this is not working, wat im writing wrong?

  public class Testmain {

/**
 * @param args
 */
public static void main(String[] args) {


    Wat n1=new This("john","man");


System.out.println(((This)n1).toString());

    // TODO Auto-generated method stub

}

  }

why am i getting this as an output :

 This@68e26d2e

What i should get as an output is this :

  John man

and yes i know the class names are random.




Ruby, add class method

Assume I have a class :

class Foo
end

To add a method to this class I khow 2 options:

1- Reopening the class and implement the method :

class Foo
  def bar
  end
end

2- using class_eval to implement method :

Foo.class_eval { def bar; end}

What is the difference?

Which one is better?




PHP same namespace for several classes

I wanted a clarification on the use of namespaces.

If I have two classes like this:

namespace Test\Collection; 

class First{}

AND

namespace Test\Collection; 

class Second{}

In this case I can use them in this way?

use Test\Collection;

$first = new First();
$second = new Second();

Thanks




importing a class object from one file in to another file

I am trying to call a function in class A from One.py file in to Two.py file by using

 from one import A

in this class A :in init function i am assigning a variable name i.e; self._fname=name. Now i am trying to call a function funC() from class A which uses the self.fname varible like below in Two.py

 now=A()
 now.funC()

when call this function i am getting an Attribute Error :Class A has no attribute '_fname'

func():
if self.fname:
    print "found"

How can i resolve this problem.Is there any way that i can import Class A object from one.py to Two.py so by using that object i can access the 'fname' variable.




Pointers to elements of a C++ class

I have a C++ class c_image which contains a vector of pointers to elements of class c_pixel:

class c_image {

    public:
        vector<shared_ptr<c_pixel>> pixel;
    ...
};

Class c_pixel elements contain an element Z of type double:

class c_pixel {

    public:
        double Z;
    ...
};

However, they are extended with class c_pixel_pv, which contains pv, an array of three elements of type double:

class c_pixel_pv : public c_pixel {

    public:
        double pv[3];
    ...
};

Class c_image also has a function filter

vector<double> c_image::filter(???) {
        ...
    };

which will take as input a pointer to the elements Z or pv[0] or pv[1] or pv[2].

But I have no idea how to point to these elements. I don't even know if it is possible to point, for example, only to pv[0] elements. I have no clue how to begin with this problem. Can anybody help me?




mardi 29 décembre 2015

How do I reference a class without calling it?

I'm making a hangman game, but really all that is causing a problem is my method "PanDisp" and my class "LabelChangeListener". I want to add a KeyListener and and ActionListener to the repective classes (KeyInput and LabelChangeListener), but when I do I need to reference the classes they are in, when I run the program I get a "StackOverflowError" because when I call the class, I get stuck in an infinite loop constantly calling "LabelChangeListener" and then calling "PanDisp()".

My question is how can I reference these classes and add their respective listeners without calling them in a loop?

public class PanDisp extends JPanel {

JLabel lblOutput;
JLabel lblGuess;
JButton btnUpdateLabel;
Image imgPkmn;
FraImg fraImg;
String sSecret;

public PanDisp() {//Constructor
    KeyInput keyInput = new KeyInput();
    KeyInput.LabelChangeListener labelChange = keyInput.new LabelChangeListener();
    sSecret = "*******";
    lblGuess = new JLabel("Type will go here");
    lblOutput = new JLabel(sSecret);
    btnUpdateLabel = new JButton("Enter");
    add(lblOutput);
    add(btnUpdateLabel);
    addKeyListener(new KeyInput());
    setFocusable(true);
    btnUpdateLabel.addActionListener(labelChange);
    fraImg = new FraImg(imgPkmn);
    //fraImg.main();
}

public void GameOver() {

}

class KeyInput implements KeyListener {

    String sInput;
    String sWord = "pikachu";
    String sSecret = "*******";
    char chInput;

    /*keyPressed - when the key goes down
    keyReleased - when the key comes up
    keyTyped - when the unicode character represented by this key is sent by the keyboard to system input.*/
    @Override
    public void keyTyped(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyPressed(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        chInput = (char) e.getKeyChar();
        sInput = String.valueOf(chInput); // convert the char to a String
        lblOutput.setText(sInput);
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    class LabelChangeListener implements ActionListener {

        char cWord;
        int nCorrect, nIncorrect, nNum;
        PanDisp panDisp = new PanDisp();

        public void actionPerformed(ActionEvent event) {
            //for (int i = 0; i < sWord.length(); i++) {
            //if (sInput.charAt(0) == sWord.charAt(i)) {
            //lblOutput.setText("*******");
            //}
            if (sWord.contains(sInput)) {
                for (int i = 0; i < sWord.length(); i++) {
                    sSecret.replace(sSecret.charAt(i), sWord.charAt(i));
                    //if (sWord.charAt(i) == sInput.charAt(0)){
                    //nNum = i;
                    //}
                }
                /*nCorrect += 1;
                if(nNum == 0){
                    lblOutput.setText(sSecret);
                }
                if(nNum == 1){
                    lblOutput.setText("*i*****");
                }
                if(nNum == 2){
                    lblOutput.setText("**k****");
                }
                if(nNum == 3){
                    lblOutput.setText("***a***");
                }
                if(nNum == 4){
                    lblOutput.setText("****c*");
                }
                if(nNum == 5){
                    lblOutput.setText("*****h*");
                }
                if(nNum == 6){
                    lblOutput.setText("******u");
                }*/
            }
            /*else {
                nIncorrect += 1;
                if (nIncorrect == 7) {
                    panDisp.GameOver();
                }
            }*/
        }
    }
}

}




rails invoking methods controller vs model

I've got a rails app. I'm trying to finetune different models and controllers. I can make the things work, but I'm not sure if I'm doing the preferred way. So I have an event.rb for my own in-app fullcalendar where I can CRUD new events and have social.rb for omniauth authorization (google calendar in this case). I'm trying to display the gcal events in my fullcalendar, so based on the social.rb data (tokens, keys) I make an API call to google to get gcal event times and then display the data in events/index page (fullcalendar).

Here are two of my methods I don't know how/where to put in my app. My questions (I have 3 as they are closely connected):

  • Method types. As I see init_google_api_calendar_client should be a class method if I put it into the social.rb (I'm not even sure if I should place it there). For the get_busy_events I simply can't decide what type to use.
  • I guess I should put these method in a model/module, but which one (social/event/something else)?
  • How should I invoke the methods?

events_controller

  def index
    @user = current_user
    @google = @user.socials.where(provider: "google_oauth2").first
    @client = Social.init_google_api_calendar_client(@google) ### Is this the proper way to call this method?
    @get_busy_times = #####how to call the get_buys_events method?
    @event = Event.new
    @events = Event.allevents(current_user)
    respond_to do |format|
      format.html
      format.json { render json: @events }
      format.js
    end
  end

social.rb

  def self.init_google_api_calendar_client(google_account)
    #method only called if google_oauth2 social exists
    client = Google::APIClient.new
    client.authorization.access_token = google_account.token
    client.authorization.client_id = ENV['GOOGLE_API_KEY']
    client.authorization.client_secret = ENV['GOOGLE_API_SECRET']
    client.authorization.refresh_token = google_account.refresh_token
    return client
  end

Where to put this method? Should be class/instance? How should be invoked?

  def get_busy_events(client)
    service = client.discovered_api('calendar', 'v3')
    result = client.execute(
      api_method: service.freebusy.query,
      body_object: { timeMin: start_at,
                     timeMax: end_at,
                     items: items},
      headers: {'Content-Type' => 'application/json'})
  end




How to add List of object to property of type list?

I want to add List of object to property of type list.

public class Viewmodel
{
    property string a {get; set;}
    property string b {get; set;}
    property string c {get; set;}
    property list<pqrModel> aListProperty {get; set;}
}

public class Anotherclass
{
        property string p {get; set;}
        property string q {get; set;}
        property string r {get; set;}
}

Now in the Code

List<Viewmodel> listobj = new List<Viewmodel>();

foreach(var o in listobj )
{
........
........
List<Anotherclass> Anotherclassobj = new List<Anotherclass>();
foreach(var a in Anotherclassobj)
{
    Anotherclass Anotherclassobjnew = new Anotherclass();

   Anotherclassobjnew.p = //filled by database
   Anotherclassobjnew.q = //filled by database
   Anotherclassobjnew.r = //filled by database

Anotherclassobj.Add(Anotherclassobjnew );
}

Viewmodel obj = new Viewmodel();
obj.aListProperty.Add(Anotherclassobj)
.......
.......
}

I cannot do like this

obj.aListProperty = Anotherclassobj;

Because it will add only the last instance of object to list property and override the others as Viewmodel obj is also moving in foreach loop.




PathTransition in loop

I have 8x8 Board, where SIZE = 8 and moveHistory is ArrayList of javafx.geometry.Point2D. Here is code :

private class ChessBoard extends Pane {
    ImageView knightImageView = new ImageView("image/knight.jpg");

    ChessBoard() {
        this.setOnMouseClicked(e -> {
            startX = (int)(e.getX() / (getWidth() / SIZE));
            startY = (int)(e.getY() / (getHeight() / SIZE));
            resetMoveHistory();
            paint();
        });
    }

    protected void paint() {
        this.getChildren().clear();

        this.getChildren().add(knightImageView);
        knightImageView.setX(startX * getWidth() / SIZE);
        knightImageView.setY(startY * getHeight() / SIZE);
        knightImageView.setFitWidth(getWidth() / SIZE);
        knightImageView.setFitHeight(getHeight() / SIZE);

        for (int i = 1; i <= SIZE; i++) {
            this.getChildren().add(new Line(0, i * getHeight() / SIZE,
                    getWidth(), i * getHeight() / SIZE));
            this.getChildren().add(new Line(i * getWidth() / SIZE, 0,
                    i * getWidth() / SIZE, getHeight()));
        }

        if (moveHistory != null) {
            for (int i = 1; i < moveHistory.size(); i++) {
                Point2D p1 = moveHistory.get(i - 1);
                Point2D p2 = moveHistory.get(i);
                PathTransition ptMove = new PathTransition();
                Line line = (new Line(
                        p1.getX() * (getWidth() / SIZE) + getWidth() / SIZE / 2,
                        p1.getY() * (getHeight() / SIZE) + (getHeight() / SIZE / 2),
                        p2.getX() * (getWidth() / SIZE) + getWidth() / SIZE / 2,
                        p2.getY() * (getHeight() / SIZE) + getHeight() / SIZE / 2));
                ptMove.setPath(line);
                ptMove.setNode(knightImageView);
                ptMove.setCycleCount(1);
                ptMove.setDuration(Duration.seconds(2));
                ptMove.play();
            }
        }
    }
}

What I am trying to do is display the moves with list loop, but it only shows 1 incorrect move and keeps playing it over and over. Where am I going wrong? Any help would be greatly appriecated!




Pass vector by reference to constructor of class

I have a class called test with which I want to associate a large vector with in the order of million elements. I have tried doing this by passing a pointer to the constructor:

#include <iostream>
#include <vector>
using namespace std;

class test{
public:
    vector<double>* oneVector;
    test(vector<double>* v){
        oneVector = v;
    }
    int nElem(){return oneVector->size();}
};

int main(){
    vector<double>  v(1000000);
    cout << v.size() << endl;
    vector<double>* ptr;

    test t(ptr);
    cout << t.nElem()<< endl;

    return 0;
}

However, this results in a Segmentation Fault:11, precisely when I try to do t.nElem(). What could be the problem?




How to document class reference using jsdoc

I want to have a class/constructor reference in a variable. How to comment the following code using jsdoc to have working autocomplete in WebStorm?

var DateLink = getDateConstructor();
DateLink.pa //I want to have autocomplete for parse()




Adding things in a python Class

So basically, i need to find a way to add a number to the schoolmember class but everytime i try there is an error. Here is the code:

class SchoolMember:
    #Represents any school member.
    def __init__(self, name, age,number):
        self.name = name
        self.age = age
        self.number= number
        print ('(Initialized SchoolMember: {})'.format(self.name))
    def tell(self):
        '''Tell my details.'''
        print ('Name:"{}" Age:"{}" Number:"{}"'.format(self.name, self.age,self.number),)

class Teacher(SchoolMember):
    #Represents a teacher.
    def __init__(self, name, age, salary,number):
        SchoolMember.__init__(self, name, age)
        self.salary = salary
        print ('(Initialized Teacher: {})'.format(self.name))
    def tell(self):
        SchoolMember.tell(self)
        print ('Salary: "{:d}"'.format(self.salary))

class Student(SchoolMember):
    #Represents a student.
    def __init__(self, name, age, marks,number):
        SchoolMember.__init__(self, name, age)
        self.marks = marks
        print ('(Initialized Student: {})'.format(self.name))
    def tell(self):
        SchoolMember.tell(self)
        print ('Marks: "{:d}"'.format(self.marks))
t = Teacher('Mr. Smith', 32, 50000, 9056789056)
s = Student('Jagroop', 15, 82, 9056761212)
# prints a blank line
print()
members = [t, s]
for member in members:
    # Works for both Teachers and Students
    member.tell()

I even added the numbers down at the bottom but the program keeps telling me that it doesn't have the propsition or something.

I would really appreciate help as my knowledge on python classes is really low, Thank you!!




Vector inside a class. C2065 error

I have vector of my own objects inside a class. But when i want to do something with this vector, i have error :/
game.h

#include "renderSystem.h" //there only  #include "console_color.h"
#include "level.h" //there only #include "renderSystem.h"
#include "gameObject.h"
class Game {
    vector<GameObject> objects;
    //something
public:
    Game();
    //something
};

game.cpp

void Game::initialize() {
    GameObject playerObject(GameObjectType_Player);
    objects.insert(objects.end(), playerObject);
    //something
}

gameObject.h

#include "renderSystem.h"
#include "level.h"
class GameObject {
    //something
public:
    GameObject(GameObjectType _type);
    GameObject() : GameObject(GameObjectType_None) {};
    //something
};

And errors are (i cant give you logs, because they are on russian :/ )

C2065 at game.cpp "objects.insert"
C2143 at game.h "vector<GameObject> objects"
C2228 at game.cpp "objects.insert"
C2238 at game.h "vector<GameObject> objects"
C4430 at game.h "vector<GameObject> objects"

I checked #includes, but may be i'm stupid :/
And in every file i have #pragma once
In renderSystem and level i wrote only includes
Wtf?!
Visual studio 2015
//And i have 0:43 AM, so may be i just need to sleep :/




Swift: Call function from another class

So while I do see other examples of this online. None of them seem to work for me. I am trying to unhide my PinPadView class by calling it from the ViewController. Any suggestions would be greatly appreciated.

class ViewController: UIViewController, UIWebViewDelegate {

    func initPinLogin() {
        //Display the Pin Pad object in App
        PinPadView.loadPinPad()
    }

}

class PinPadView: UIView {

    class func loadPinPad() {
        let pinPad:PinPadView = PinPadView()
        pinPad.hidden = false
    }
}




C++ Trouble declaring function prototype within header file

I have been given the following code to work with within a MatrixTest.cpp function:

Matrix matrix = Matrix::Zeros(2,4)

The aim is to "create a 2x4 matrix of zeros with the static Zeros" and I need to be able to add something to the header file "Matrix.h" which allows "MatrixTest.cpp" to compile for the line of code above. This is the code in my header file so far:

#ifndef MATRIX_H_
#define MATRIX_H_

class Matrix {
protected:
    // These are the only member variables allowed!
    int noOfRows;
    int noOfColumns;
    double *data;

    int GetIndex (const int rowIdx, const int columnIdx) const;

public:
    Matrix (const int noOfRows, const int noOfCols);
    Matrix (const Matrix& input);
    Matrix& operator= (const Matrix& rhs);
    ~Matrix ();

    Matrix Zeros(const int noOfRows, const int noOfCols);
};

#endif /* MATRIX_H_ */

This gives the error in my .cpp file that I cannot call member function Matrix Matrix::Zeros(int, int) without object. But surely Zeros is my object and my Matrix class is my type?

If I change my code in the header file to the following:

static Zeros(const int noOfRows, const int noOfCols);

Then I get an error within my .h file saying "forbids declaration of 'Zeros' with no type and an error within my .cpp file saying "conversion from 'int' to non-scalar type 'Matrix' requested"

I'm confused since I would've thought that my type is Matrix as it appears underneath the class Matrix and that since Matrix::Zeros(2,4) follows the constructor Matrix(const int noOfRows, const int noOfCols) then there wouldn't be a conversion issue from 'int' to non-scalar type.

Can anybody help with this as I seem to be going back and forth between these errors?




Setting a generic parameter of a class through reflection?

So before I ask the question, I feel that I must explain my situation for the question to make any logical sense:

I have the generic nested class ThreadHierarchy<P,C extends ExtendedThreadHandler<T>> (where P represents the parent and C, the child) inside of the generic class ExtendedThreadHandler<T> (where T represents type), and I need to create an instance of the TheradHierarechy class in the main constructor of its superclass like so:

    //Thread State initializer
public ExtendedThreadHandler() {
    this.setThreadClass((T)this);
    this.setThreadName(getClassInstance().getClass().getSimpleName());
    ThreadHierarchy th = new ThreadHierarchy<Thread.currentThread().getClass(), T>(true);
}

The issue with this is that while instantiating classes, the generic input values only accept string literals such as the predefined generic type T from ExtendedTheadHandler<T>, and therefore, I cannot input a method call or variable into the instance parameters.

Is there a way to either:

A) Input return values, in this case a class, into a generic class or method by defining a new instance variable to pass in? (I couldn't figure out how to do this)

OR

B) Use reflection to create an instance of the class where the values of P and C can be assigned manually?




Accessing ES6 super properties

So I was messing around with ES6 classes when I saw something surprising:

class Animal {
    constructor(name) {
        this.name = name;
    }
    speak(sound) {
        console.log(sound);
    }
}

class Dog extends Animal {
    constructor(name, age) {
        super(name);
        this.age = age;
    }
    speak() {
        super.speak("Woof! I'm " + super.name + " and am " + this.age);
    }
}

Then, I created my dog:

var mydog = new Dog("mydog",3);
mydog.speak();

Now this prints

Woof! I'm undefined and am 3

So my question is, why is super.name undefined? I'm expecting it to be mydog in this case.




Integrating Two Classes [on hold]

Below is my following code and I am having trouble integrating the two together, as I keep getting parsing errors, and multiple other errors relating to class.

public class Account {

public String accountName;
public double accountBalance = 0;


public Account(String name, double start) {
    accountName = name;
    accountBalance += start;
}

public void changeName(String name){
    accountName = name;
}

public void deposit(double deposit){
    accountBalance += deposit;
}

public int withdrawal(double withdraw){
    if(withdraw > accountBalance){
        return 0;
    }
    else{
        accountBalance -= withdraw;
        return 1;
    }
}


import java.util.Scanner;

public class Program {
    public static void main (String[] args){


    Scanner input = new Scanner(System.in);


    System.out.println("Please input the name of the account owner." );
    String user = input.nextLine();
    System.out.println("");

    double initialDep;



    System.out.println("Please input initial deposit.");
    System.out.println("");
    initialDep = input.nextDouble();
    Account a1 = new Account(user, initialDep);

    System.out.println("Balance: " + initialDep);
    System.out.println("");

    System.out.println("Please input the name of the account owner." );
    String user2 = input.next();

    System.out.println("");


    Account a2 = new Account(user2, 0);
    initialDep = 0.00;


    System.out.println("Balance: " + initialDep);
    System.out.println("");


    for(int i=0; i<4; i++){
        char action;
        double amount = 0;

        if(i == 1 || i == 3){
            action = 'w';
        }
        else{
            action = 'd';
        }

        if(action == 'd'){
            if(i == 0 || i == 1){
                user = a1.accountName;
                System.out.println("What is the amount you would like to deposit into " + user + "'s account?");
                amount = input.nextDouble();
                a1.deposit(amount);
                amount = a1.accountBalance;
            }
            else{
                user = a2.accountName;
                System.out.println("What is the amount you would like to deposit into " + user + "'s account?");
                amount = input.nextDouble();
                a2.deposit(amount);
                amount = a2.accountBalance;
            }

        }
        if(action == 'w'){
            if(i == 0 || i == 1){
                user = a1.accountName;
                System.out.println("What is the amount you would like to withdraw from " + user + "'s account?");
                amount = input.nextDouble();
                while(a1.withdrawal(amount) == 0){
                    System.out.println("Please input a lower amount.");
                    amount = input.nextDouble();
                    System.out.println("");
                }
                amount = a1.accountBalance;
            }
            else{
                user = a2.accountName;
                System.out.println("What is the amount you would like to withdraw from " + user + "'s account?");
                amount = input.nextDouble();                    
                while(a2.withdrawal(amount) == 0){
                    System.out.println("Please input a lower amount.");
                    amount = input.nextDouble();
                    System.out.println("");
                }

                a1.withdrawal(amount);
                amount = a2.accountBalance;
            }
        }
        System.out.println("");
        System.out.println("Balance: " + amount );
        System.out.println("");



    }
}
}
}




Reference an anonymous class?

I am developing a plugin for an RCP-Application. Within the plugin.xml, I need to register certain classes at a given extension point. One of these classes is an anonymous (?) class defined like this:

package de.me.mypackage;

import org.something.AnotherClass;

public class ClassOne {
...
public static AnotherClass<ClassOne> getThat() {
        return new AnotherClass<ClassOne>() {
...
}
}

Is there any way to reference to 'AnotherClass<ClassOne>' within the plugin.xml?

I already tried something like 'de.me.mypackage.ClassOne$AnotherClass' but that does not work. Or do I have to declare that class within its own file to be able to reference it?




Multiple Class Inheritance In TypeScript

What are ways to get around the problem of only being allowed to extend at most one other class.

class Bar {

  doBarThings() {
    //...
  }

}

class Bazz {

  doBazzThings() {
    //...
  }

}

class Foo extends Bar, Bazz {

  doBarThings() {
    super.doBarThings();
    //...
  }

}

This is currently not possible, TypeScript will give an error. One can overcome this problem in other languages by using interfaces but solving the problem with those is not possible in TypeScript.

Suggestions are welcome!




how to get data from db and set to nested list

i have a nested list:

I get data from db and set to list: but I get error:

The best overloaded method match for 'System.Collections.Generic.List.Add(graph1.ViewModels.ItemsOfQuestions)' has some invalid arguments

any help you?




Calling methods and passing proper context in Coffeescript

This is the simplified version of class I have:

class Calculations
  constructor: (amount = 1000) ->
    @amount = amount

  rowOne: =>
    columnOne:   => @amount * 0.1
    columnTwo:   => @amount * 0.2
    columnThree: => @amount * 0.3
    total:       => @_total(context)

  _total: (context) ->
    context.columnOne() + context.columnTwo() + context.columnThree()

I want to call methods like this:

calc = new Calculations()

calc.rowOne().columnOne()    # And it should return 100
calc.rowOne().columnTwo()    # And it should return 200
calc.rowOne().columnThree()  # And it should return 300
calc.rowOne().total()        # And it should return 600

How can I implement this properly? Current implementation of _total method, of course, does not work, because I have no idea how can I pass needed context there. Is this possible at all?




How to load classes in php

I need to understand how to load classes in php. I want to access classes methods by instantiate the class only with its name, for example:

$foo = new Foo();
$foo->method();

And not like this:

$foo = new \Class\Bar\Foo();

I'm in a Symfony 2.7 environment. Thanks in advance!




lundi 28 décembre 2015

How to check how many times a class property was set with a specific value?

Is there any possible way in determining how many times a class property was set with a specific value ?




Special initialization of classes

I am trying to do something fairly specific, and have been unable to find a solution. This is not an implementation problem on my part but more of a design pattern question.

What I would like to do is have a abstract class, and several derived classes. I would like to make it so that the derived classes can only be initiated with shared pointers.

For a single class this would be done with something like making the constructor private, and then making a custom "constructor" that just returns a shared pointer. For example:

class a{
    public:
       std::shared<a> construct(){
           return std::make_shared<a>(new a);
       };
    private:
       a(){};
};

Is there a way do to something that has a "similar" effect with a abstract class on the base classes? Ideally without redefining a private constructor for every class. Thanks!

I cannot use the factory pattern because that would still allow non smart pointer construction. A friend could be used on a non abstract function, but friend is not heritable. For example this would not work: How to force only smart pointers instance for a class?

The Named constructor pattern: http://ift.tt/1OvL1Ka is demonstrated in the example I gave, and does not solve the problem.




PHP Cosntruct function [on hold]

<?php
namespace Project\Bitm\SEIP106611\Birthday;

        class Date{
            public $date = "";

            public function __construct($date = false){
                $this->date = $date;

            }

            public function index(){
                echo "This is index page";
            }

            public function store(){
                $conn = mysql_connect("localhost","root","") or die("Cannot connect database.");
                $lnk = mysql_select_db("home") or die("Cannot select database.");

                $query= "INSERT INTO `birthday` (`id`, `birth_day`) VALUES (NULL, '".$this->date=$date."')";
                $result = mysql_query($query);

                var_dump($result); die();
            }


        }

?>

Problem is " Notice: Undefined variable: date ". how can i solve it?




Why is array not added to PHP class' property?

I'm new to OOP PHP and have been following Laracasts OOP Bootcamp. I have reached a certain part of the tutorial where I'm having trouble. I have the following file (ignore that conventions were not followed, as it is the learning phase):

<?php
class Person
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

class Staff
{
    protected $members = [];

    public function __constructor($members = [])
    {
        $this->members = $members;
    }

    public function add(Person $person)
    {
        $this->members[] = $person;
    }

    public function members()
    {
        return $this->members;
    }
}

class Business
{
    protected $staff;

    public function __construct(Staff $staff)
    {
        $this->staff = $staff;
    }

    public function hire(Person $person)
    {
        $this->staff->add($person);
    }

    public function getStaffMembers()
    {
        return $this->staff->members();
    }
}

$jeffrey = new Person('Jeffrey Way');

$staff = new Staff([$jeffrey]);

$laracasts = new Business($staff);
$laracasts->hire(new Person('Jane Doe'));

var_dump($laracasts->getStaffMembers());

Unfortunately, the var_dump is only giving me one staff member:

array(1) {
  [0]=>
  object(Person)#4 (1) {
    ["name":protected]=>
    string(8) "Jane Doe"
  }
}

I have tried adding [] to the line $this->members = $members; under Staff class but it's still giving me the same output. I've also double checked the files, I should be expecting two members instead of one.

Can someone tell me where I went wrong?

Thanks for your time.