mardi 28 février 2017

Having Trouble with Inner Classes

I am having trouble getting my small program to work while using an inner class. When, I set a inside class member variable from the outside class, the value does not stick. Thanks.

Here is my source code:

class Erik:

    def __init__(self):

        self.__myData = self.Data()


    class Data:
        def __init__(self):

            self.__privateNumber = 0

        def getNumber(self):
            return self.__privateNumber

    def getData(self):
        return self.__myData


    def fun(self):

        self.__myData.__privateNumber = 64

        print 'Private Number Inside:', self.__myData.__privateNumber


myErik = Erik()

print 'Having fun...'
myErik.fun()

# This print statement should output '64'
print 'Private Number Outside:', myErik.getData().getNumber()

This is the output of my script:

C:\Users\Erik\Desktop\PYTHON_TINKER_DEALS>python erik.py
Having fun...
Private Number Inside: 64
Private Number Outside: 0

As you see, when I set the private number to 64, it does not reflect that when you get the data from the outer class. Thanks.




Passing an array of pointers to a Class Object

Hoping someone can help a beginner out here. I searched but some of the solutions were out of scope my knowledge. I'm trying to create a function which will take in a an array of pointers to a class object and output a getName() function for each object. But I keep getting a "no instance of overloaded function" I can't figure out what the problem is. Please below

#include <iostream>
#include "Student.hpp"
#include <string>
using namespace std; 

void getName(Student *studentArray[], int); //prototype 





int main()
{   

    //Creates class objects with Constructors Name and Score
    //Class object has a function getName() to return name 
    Student stud1("John", 100);
    Student stud2("Mary", 90);
    Student stud3 ("Jack", 85);

    //Create an array of student objects 
    Student myArray[3]= {stud1, stud2, stud3};

    //ERROR HERE NO INSTANCE OF OVERLOADED FUNCTON
    getName(myArray, 3) 

    return 0;


}



void getName(Student *studentsArray[], int arraySize)
{

    for(int index=0; index < arraySize; index++)
    {
        cout << studentsArray[index]->getName() << endl;  

    }
}




Recursive linear search for class list array python

Hi how would I do linear search using recursion instead of doing it iteratively? This is how I'm trying to do it currently. I get a TypeError: 'type' object is not subscriptable for l

@classmethod

def _linear_search_r(l,key, i=0):

    if l:  #Check if list is not empty
        if l[0] == key:
            return i 

        s = _linear_search_r(l[1:],key, (i + 1))
        if s is not False:
            i = s
            return i

    return False




Overriding len function in python

class foo:
    def __init__(self, data):
        self.data = data
    def __len__(self):
        return self.data

If I run this by passing a string in for data I get an error when calling len on an instance of this class. Specifically I get 'str' object cannot be interpreted as an integer.

So does the return statement in __len__ have to be an integer? I would think if I am overriding it, it should be able to output whatever I want, so why is this not possible?




React: Are classes without state still considered stateless/pure?

I've been refactoring my app to make more components stateless/pure components; i.e., they're just functions. However, I noticed that some components will need to connect with the redux store via mapStateToProps. Which causes me to do something like this:

const someComp = (props) => {
  const {
    funcFromReduxStore,
  } = props;

  return (
    ...
    <SomeComponent
      func={ funcFromReduxStore(myArgs) }
    ...
  );
};

This will not work because I am executing funcFromReduxStore. An easy solution is to wrap the prop in an arrow function. However, this causes many unnecessary re-renders b/c the function won't be bound.

The question then becomes: How do I bind a function in a stateless component?

Is it still stateless if I make it a class, without a constructor, and create a class instance field as so:

class someComp extends React.Component {
  const {
    funcFromReduxStore,
  } = this.props,

  wrapper = (x) => funcFromReduxStore(x) // equivalent way to bind w/ ES8+

  render() {
    ...
    <SomeCompnent
      func={ wrapper(myArgs) }/>
    ...
  }
}

I don't have a constructor, nor state. I want to keep the comopnent stateless, but I also want to bind the function to avoid unncessary re-renders. I also want to continue to keep it stateless b/c React has stated there will be performance benefits for stateless comopnents. Does this qualify as a workaround?




What is the proper way of dynamically constructing a pointer to a template class

Suppose my template class looks like this:

    template <class HashedObj, const int elementSize>
    class QuadraticHashTable { }

and I have a class called Word

class Word
{
     Word() { myTable = new QuadraticHashTable<//What do I put here?>();}
     private: 
     QuadraticHashTable<char*, 13> * myTable;
}

What is the proper way of dynamically allocating a table with element size 13?




Supplying a const variable to a class

Suppose that my hash table has words of different sizes and I want to keep track of words of different sizes in separate hash tables. Instead of creating 20 different hash table files for 20 different words sizes, is there a way to supply a const through a class?

Dynamic allocation is not an option, because it would cost 8 additional bytes for the pointer variable for each table entry.

template <//Is there a way to supply a const here to change the value of size?>
class HashTable
{
    static const int size = #;

    struct TableEntry
    {
        char words[size];
    }

}




Use class func on class parameter in Swift

I am trying to use a class func to set a title for a book, however it's not working. Please see my code below:

import Foundation

class Book: NSObject {

    var bookTitle: String = ""
    var bookPage: String = ""

    override init(){
        print("Book object has been created")
    }



    class func setPageTitle(title: String)
    {
        bookTitle = title //I get the error here
    }

}

I want to make it mandatory to set a pageTitle when a Book object is created.

Can someone please help me ?




Using PHP classes when adding users to database

Originally I used concatenated queries created by for loops to add large numbers of players/users to a mysql DB. Today, I wanted to experiment with classes because I didn't really understand their use case.

In the class below the new user(+data) is added to the DB and returns the unique ID number for the last inserted row.

I would have assumed that doing this insert as one query would be fastest way of doing it, rather than each time I instantiate a new player, but to be honest I'm still at the beginner phase so would welcome some advice, or suggestions on how best to optimise this.

Ideally as one query, Unless I'm wrong in assuming this is faster?

Is it possible to return the Unique ID's for multiple players as an array?

class player {
    var $player;
    var $PlayerID;
    var $email;
    function create_player($new_player, $email, $password, $db) {
        $this->player = $new_player;
        $this->email = $email;

        $salt = "xxx"; //simplified for this example            
        $passwordhash = $password; //simplified for this example
        $query = "INSERT INTO userstest (name, email, hash, salt ) values(:name, :email, :hash, :salt)";
        $params = array (':name' => $new_player, ':email' => $email, ':hash' => $passwordhash, ':salt' => $salt);

        $stmt = $db->prepare($query); 
        $stmt->execute($params); 
        $id = $db->lastInsertId();
        $this->PlayerID = $id;
    }
}




Get access to data of not declared class directly

We have a class Model inside which is a function which returns an instance of class Mesh with parameters. In a class Mesh has a constructor with parameters, and a few public fields:

class Model
{
public:
    Model(string path)
    {
        this->loadModel(path);
    }

    Mesh loadModel(string path)
    {
        vector<GLfloat> vertices;
        vector<GLuint> indices;
        ...
        return Mesh (vertices, indices);
    }
};
class Mesh 
{
public:
    vector<GLfloat> vertices;
    vector<GLuint> indices;

    Mesh(vector<GLfloat> vertices, vector<GLuint> indices)
    {
        this->vertices = vertices;
        this->indices = indices;
        this->loadMesh();
    }

    void loadMesh()
    { 
        //sending data to OpenGL
    }
};

int main()
{
   Model model("folder/...");
   return 0;
}

In main function we declare only Model class. Mesh class was created on the fly and sends data to OpenGL. How can we get access to fields of class Mesh (verticies, indicies) in main function? Or it is no longer there? Thank you!




Error by casting a class

I have created other class for global variables now I just want to cast it like that:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);
    class2 global;

    global = (class2)getApplicationContext();

I get error:

android.app.Application cannot be cast to eu.tools.test_training_home.class2

The class2:

public class class2 extends Application {

    private String name="name1";
    private int number =0;




a tag inside div-class

Can I place <a href="#">test</a> inside <div class="test">

I am well aware of <div class="test"> <a href="#">test</a> </div> my problem with that code is that the a tag leaves some styling for me to do in the css and i would be happy to shrink down my code as much as possible.




with configuration file, PHP classes dynamic extend

For example, I have 2 classes.

interface w
{
    public function test();
}

class a implements w{
    protected $path;
    public function test(){
        echo $this->path . PHP_EOL;
        echo "a class test method";
    }
}

class b  implements w{
    protected $path;
    public function test(){
        echo $this->path . PHP_EOL;
        echo "b class test method";
    }
}

I get these classes with the default value in the file.

conf.php // return "$conf = "

$conf = array(
    'default' => 'b',
    'class' => [

        'a' => [
            'path' => 'file/path1',
        ],

        'b' => [
            'path' => 'file/path2',
        ],
   ],
);

I want to use it dynamically, giving it a alias as follows.

//$conf = include('conf.php');

define('CONF', $conf); // array value, php7 or later

class_alias($conf['default'], 'd');

class c extends d {

  public function __construct(){
      $conf = CONF;
      $this->path = $conf['class'][$conf['default']]['path']; 
  }  
}


$c = new c();
$c->test();

Is this the right way to you?




How to access the Methods inside a class of a Project DLL in C#

I have been learning C# and was trying to create a particular Logic in a separate Solution.

In this scenario, I created a Project with a few classes and each class has particular methods for certain processes. I have created a DLL for this Project, let's call it "LogicLibrary.DLL"

Now, I have created another Project where I added a reference to the "LogicLibrary.DLL".

Now, my problem is that I am not sure how I should access the methods inside the classes of the DLL.

Suppose LogicLibrary.DLL has a class "Calculator.cs" which in turn has methods Add(int a, int b), Sub(int a, int b), Mul(int a, int b) and Div(int a, int b).

In the new project, how can I access any of the methods mentioned above. Is there any particular way of creating an object for the classes inside the DLL?

Would love your help!...Thank You!




Set string in class with a set-function.

I cant figure out why I can't change string className with the function player.setClassName(); . Can someone explain what I'm doing wrong?

//Functions.cpp

void classChoice(playerClass player) 
{
    int select = 0;
    string text = "Text";
    do {
        cin >> select;
        getchar();
        switch (select) {
        case 1:     
            player.setClassName(text);
            break;
        case 2:
            break;
        case 3: 
            break;
        default:
        }
    } while (select > 1 && select > 3);
}

the function im using to change className.

//PlayerClass.cpp

void playerClass::setClassName(string &className) {
    this->className = className;
}

playerclass

//PlayerClass.h

class playerClass : public playerCharacter, public Skills 
{
private:
   string className;
public:
   playerClass();
   playerClass(string className);
   virtual ~playerClass();

string getClassName();
void setClassName(string &className);
};




Connecting Adjacency Matrix to a Separate Class

I am working on a project where I am tracking the passes that occur between players in soccer and then building an Adjacency Matrix that I can analyze to obtain data about the team as a whole and about the players as individuals (e.g. The connectivity of the team during a certain game or the betweeness of a player with the goal). To implement this, I have written three different classes in C++: Team, Player, and AdjacencyMatrix.

  • Player holds the identification information (number and last name) and the data that is already calculated for that player (betweenness, number of touches, etc)
  • AdjacencyMatrix is a class defined to make a square two dimensional array of ints that has member functions defined to find the connectivity, betweenness, etc..
  • Team holds an array of Players (the roster), the data on the whole team, and the AdjacencyMatrix storing all of the passes between the Players

I am wondering if you have any ideas on how to keep the indices stored in an AdjacencyMatrix connected with the Players in the roster of a Team. Currently, I assume that the index of Player A in the roster is the same as the index of Player A in the AdjacencyMatrix, but I feel like that is very flimsy, especially since I would like to be importing/exporting this data (the AdjacencyMatrix as well as all the calculated data) to and from files for storage.

Another idea that I had was to add a member variable in the Player class that stores that Player's index in the Team's AdjacencyMatrix. This idea would be more robust than my current solution (you would be able to mess with the order of the roster without losing information), but it seems very inelegant.

Do you have any more elegant solutions to this problem or should I just be satisfied with the slightly inelegant but more robust solution?

Thank you for your advice.




pls help error in makefile i think compilation probleme

i created a simple class but dev c++ cant compate it
**ERROR** : C:\...\Makefile.win recipe for target '"all' failed (line 25)

strong text main.cpp

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

using namespace std;


int main(int argc, char** argv) {

Compte c1;
Compte c2;
Compte c3;
cout<<c3.getCount();
return 0;
}

compte.h

#ifndef COMPTE_H
#define COMPTE_H

class Compte
{
public:
    Compte();
    int getCount();
private:
    static int counter;
};

int Compte::counter = 0;

#endif

Compte.cpp

#include "COMPTE.h"

Compte::Compte()
    {
        counter++;
    }

int Compte::getCount()
{
counter;
}




How do I access member variables from one class into other using friend functions in C++?

I am using fried functions for the very time and was assigned to complete an incomplete code using friend functions as below.

//CODE GIVEN IN THE QUESTION NOT MEANT TO BE EDITED
#include<iostream>
using namespace std;
class store_keeper;
class item
{
    char prod_name[30];
    char prod_code[10];
    float prod_price;
    int stock_In_Hand;
    public:
    void get();
    void print()const;
    friend class store_keeper;
};
class store
{
    int num_Of_Items;
    item items[20];
    public:
    void get_details();
    void print_details() const;
    friend class store_keeper;
};
class store_keeper
{
    char name[30];
    char id[10];
    public:
    void get();
    void print();
    void stock_mgmt(store &);
};
//MY CODE
void item::get()
{
cin>>prod_name>>prod_code>>prod_price>>stock_In_Hand;
}
void item::print() const
{
    cout<<prod_name<<prod_code<<prod_price<<stock_In_Hand;
}
void store::get_details()
{
    cin>>num_Of_Items;
    for(int i=0;i<num_Of_Items;i++)
    {
        items[i].get();
    }

}
void store::print_details() const
{
    for(int j=0;j<num_Of_Items;j++)
    {
        items[j].print();
    }

}
void store_keeper::stock_mgmt(store &)
{
    for(int k=0;k<store_keeper::num_Of_Items;k++)
    {
        if(items[k].stock_In_Hand<10)
        {
            items[k].print_details();
        }
    }
}
//CODE GIVEN IN THE QUESTION NOT MEANT TO BE EDITED
main()
{
    store s;
    store_keeper sk;
    s.get_details();
    sk.stock_mgmt(s);
}

I had to display the details of the item for which the stock in hand is less than 10.I am getting an error that num_Of_Items was not declared in this scope and suggest any edits if any required.Thanks.




Restart, reset WallpaperService | onCreateEngine

For Wallpaper i have a class WallpaperService that override onCreateEngine function in which i read background image and then preview it for wallpaper on main screen.

Now, if i start my app, the first time preview is fine. But if i set wallpaper and then select any other background and set it, it shows old value (means class is not restarted)

I start the preview with

Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(this, CustomWallpaper.class));
startActivity(intent);

Can any one guide me how to restart my wallpaperService?

I checked different links on SO, but they didn't help me. I need to understand this stuff in detail. Please help




Pester mock method for Powershell 5 class

I am having an issue trying to mock a powershell 5 class method, when executing the test, I get the error " CommandNotFoundException: Could not find Command FunctionToMock". I am trying to unit test the "OutputToOverwrite" method by mocking "FunctionToMock". I think I would have to mock ChocoClass itself first, but I am not sure how to do it. Thanks.

Class ChocoClass
{
    [string] OutputToOverwrite()
    {
        return $this.FunctionToMock()
    }

    [string] FunctionToMock()
    {
        return "This text will be replaced"
    }
}


Describe{
    it "Testing mocking"{
        Mock FunctionToMock -MockWith {return "mystring"}
        $package = New-Object ChocoClass
        $expected = $package.OutputToOverwrite()
        $expected | should BeExactly "mystring"
    }
}




Calculator with changing buttons/function? Tkinter

I'm currently working on a project in which I am making a calculator with many functions using Tkinter on Py 3.6, using a TI as my guide. Similarly, I am trying to make a function similar to the shift, or alpha function in which the text on the buttons change and the outputs on the buttons change as well. For example, if the mode is 1 button1 reads '1' and adds 1 to the display; when the mode is 2, button1 reads 'A' and adds A to the display. I've gone through a number of attempts, so I don't have all the code I have attempted, but my current code is below to give you all something to work with. I don't know much about them, but could classes be an option? if so, how does one do this?
I am also trying to make a button for calculus functions, where when pressed, the layout will change to a screen with a large display to edit the function and a couple buttons to select a function. How could this be achieved?

from tkinter import *
import parser

root = Tk()
root.title('Calculator')

# order C-A-B

displayc = Entry(root)
displayc.grid(row = 1, columnspan = 6)
displaya = Entry(root)
displaya.grid(row = 2, columnspan = 6)
displayb = Entry(root)
displayb.grid(row = 3, columnspan = 6)


mode = 0

i = 0

var1 = StringVar()

#former attempt: shft button had 'command = update'
'''def update():
    global mode
    if mode == 0:
        mode = 1
    else:
        mode = 0
    return'''
def display(e):
    global i
    displayb.insert(i,e)
    i = len(displayb.get())
    return
def equals():
    displayc.delete(0,END)
    a = displaya.get()
    displayc.insert(0, a)
    displaya.delete(0,END)
    b = displayb.get()
    displaya.insert(0, b)
    eq = eval(b)
    displayb.delete(0,END)
    displayb.insert(0, eq)
    return
def clear():
    displayb.delete(0, END)
    return

#Only tested on button 1 for simplicity- I want it to work for all eventually
txt1=StringVar
a = '1' if mode == 0 else 'A'
one = Button(root, variabletext = txt1, command = lambda : display(1))
txt1.set(a)
one.grid(row = 4, column = 0)
two = Button(root, text = '2', command = lambda : display(2))
two.grid(row = 4, column = 1)
three = Button(root, text = '3', command = lambda : display(3))
three.grid(row = 4, column = 2)
four = Button(root, text = '4', command = lambda : display(4))
four.grid(row = 5, column = 0)
five = Button(root, text = '5', command = lambda : display(5))
five.grid(row = 5, column = 1)
six = Button(root, text = '6', command = lambda : display(6))
six.grid(row = 5, column = 2)
seven = Button(root, text = '7', command = lambda : display(7))
seven.grid(row = 6, column = 0)
eight = Button(root, text = '8', command = lambda : display(8))
eight.grid(row = 6, column = 1)
nine = Button(root, text = '9', command = lambda : display(9))
nine.grid(row = 6, column = 2)
zero = Button(root, text = '0', command = lambda : display(0))
zero.grid(row = 7, column = 1)
plus = Button(root, text = '+', command = lambda : display('+'))
plus.grid(row = 4, column = 3)
minus = Button(root, text = '-', command = lambda : display('-'))
minus.grid(row = 5, column = 3)
times = Button(root, text = '*', command = lambda : display('*'))
times.grid(row = 6, column = 3)
div = Button(root, text = '/', command = lambda : display('/'))
div.grid(row = 7, column = 3)
result = Button(root, text = '=', command = lambda : equals())
result.grid(row = 7, column = 0)
ac = Button(root, text = 'AC', command = clear)
ac.grid(row = 7, column = 2)
 #former attempt to change mode
'''shift = Button(root, text = 'sft', command = lambda : mode = 1 if mode == 0 else 0)
shift.grid(row = 2, column = 1)'''

place = Button(root, text = 'Place', command = lambda : display(var1.get()))
place.grid(row = 4, column = 5)

option1 = ['**2','**3','**(1/2)','**(1/3)','**','(',')','(-1)*']

menu1 = OptionMenu(root, var1, *option1)
menu1.grid(row = 4, column = 4)

root.mainloop()




Symfony - Doctrine not a valid entity or mapped super class

I have got an inherited website. Throwing a critical error in prod mode.

[2017-02-28 13:11:17] request.CRITICAL: Uncaught PHP Exception Doctrine\ORM\Mapping\MappingException: "Class "TheZoo\Website\FrameworkBundle\Entity\Menu" is not a valid entity or mapped super class." at /var/www/html/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php line 216 {"exception":"[object] (Doctrine\\ORM\\Mapping\\MappingException: Class \"TheZoo\\Website\\FrameworkBundle\\Entity\\Menu\" is not a valid entity or mapped super class. at /var/www/html/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php:216)"} []
[2017-02-28 13:11:17] security.DEBUG: Write SecurityContext in the session [] []

I am not a Symfony developer but it looks like it could be down to the location of the class. "TheZoo\Website\" was part of the path on the old site.

The site works fine in debug mode. Any idea what is causing this?




It posible to put an object into a stack? [on hold]

I create a class Book and my object contain author name, num. of pages and volume;

It is possible to count all the books into a stack ?




Static classes or instance pointers

Backstory:

Currently I have a series of three classes related to a game. I've previously made games using Unity where you access components such as the camera using functions accessible throughout all code. My current setup, however, relies on instances of each class being sent across the other classes. See the following outtake:

class World{
     *Game game;
     *Camera camera;
};
class Game{
     *Camera camera;
     *World world;
};
class Camera{
     *Game game;
     *World world;
};

Questions:

  • Is this a result of bad design or are there times when a setup like this is justified?

  • Should I rather use static classes over my current setup since it would clarify the code and no more than one instance of each class is ever used?

  • What are the possible downsides of using static classes over instances?




Scala: 'class needs to be abstract' when implementing higher order function

I am trying to ensure that classes (which represent some symbolic math expression) with trait Func possess a method that will return a numerical function (implementing the symbolic expression).

trait Func {
  def func[T](x: T): T=>Double
}

case class Const(d: Double) extends Func {
  def func[T]: (T=>Double) = (x: T)=>d
}

object Main extends App {
  val c = new Const(3.142)
  val cAt1 = c.func(1.0)
  println(s"c(1.0)=$cAt1") // expected: c(1.0)=3.142
}

This returns the following error:

[error] /projects/tutdiff/diff.scala:6: class Const needs to be abstract, since method func in trait Func of type [T](x: T)T => Double is not defined
[error] case class Const(d: Double) extends Func {
[error]            ^

I am interested in why the implementation of func in Const doesn't meet the requirements. But also what it is that means a class must be abstract or not (new to Scala).




AppleScript & Javascript : Getting all data from HTML row

I want to get all the number from a website , which are in the same row.

the all have the same Class :

<td class="sortable dsNumberId">

                                    10999694994

                            </td>

I would like to return this to the clipboard and have a result like this :

10999694994

10949644992

10959594991

109796976

The number of value to collect is random, it can from 2 to 100 and the first class="sortable dsNumberId" is actually invalid (just the title with a link)

I have this script here :

tell application "Google Chrome"
    tell tab 2 of window 1 to set DSIDsList to execute javascript "var outPut=[0]; var arr=document.getElementsByClassName('sortable dsPersonId');for (var i in arr) {outPut.push(arr[i].innerHTML)};outPut;"

end tell

The issue is at the end which give me a text " ", missing value, missing value, missing value}"

and at the beginning which give me the invalid title / URL which I don't need.




Indexing dynamic objects in elasticsearch nest

Elastic search generally works with pre-defined classes . How do I work with dynamic classes. eg: Suppose I want to search a particular field then

var result = clientConnection.Search<TicketData>(

s => s .Aggregations(

a => a .DateRange(

"L1", d => d .Field(p => p.timestamp) .Ranges( r => r.To("2016-10-09T15:01:06+00:00"), r => r.From("2016-09-27T02:09:17+00:00") ) ) ) );

Here the ticketdata class has to be defined beforehand. Can we have something like var result = clientConnection.Search<DYNAMICCLASS>(s => s

.Aggregations(a => a

.DateRange("L1", d => d

.Field(p => p.timestamp)

       .Ranges(
        r => r.To("2016-10-09T15:01:06+00:00"),
        r => r.From("2016-09-27T02:09:17+00:00")
    )
)

) ); Can a dynamic class/ dynamic object work with this ? please give an example how it can be done.




c# - Application structure when using a serial port to read data

I would like some advice on the structure of my windows form application. My application will allow the user to open a serial port in order to read data from a USB device.

Currently, the application will open into the main form, the user would then open another form in order to configure the port, this form would then be closed and the user would return to the main form. As it stands, all port configuration and data reading is done within the code contained in this form, the read data would then have to be sent back to the main form to be displayed which I don't think is most efficient method of achieving this.


My question is, what would be the best way to do this? Should I create another class to handle all port configuration and reading of data in the background? If so, how would I sent the data back to the main form?

Thanks




Return value from class function

I'm trying to build a class of custom alerts, based on Boostrap. Everything is still very young but I encountered a problem. How can I return a value according to the clicked button only when the click event happens? Here you can see how I set the value (very easy, for tests)

    $modal.on('click', '[data-alertify="cancel"]', function(){
        var value = 'no';
        $modal.modal('hide');
        return value;
    });
    $modal.on('click', '[data-alertify="confirm"]', function(){
        var value = 'yes';
        $modal.modal('hide');
        return value;
    });

Here is my class and test code JSFiddle

As you can see, the alert (obviously) appears before the modal is shown. How should I handle this? How can I wait for the correct value to be returned, and then alert it?




lundi 27 février 2017

Dependency Injection VS static class methods

I am trying to grasp the concept of dependency injection and realized that it just instantiates a class and provide that object to be used when injected in other classes.

Why can't I choose to create a simple class with static methods attached to it (let's ignore the testing pain for a moment)?

What advantages DI offers?




returning object from class function c++

suppose we have a function like below

Car buyCar();

My question is which method we must have in Car class for this function to work ? Is it default constructor ?




How to use arrays as class object name in Java?

I'm trying to create a simple code to list and create details of shampoos. I have a main and a class. What I want is to use an array to automate the creation of my class object. Is it possible in Java? And also, are there any other alternative on what I'm trying to achieve? Below is my main code:

package main;
import java.util.Scanner;

public class Products {


public static void main(String[] args) {

    int inpInt = 0;
    String inpStr;
    String shName;
    String shType;
    String shFrom;
    int shAmount;
    int sham[] = new int[256];
    int x = 0;
    Scanner scanInp = new Scanner(System.in);

    System.out.println("What do you want to do?");
    System.out.println(" 1. Insert a product (shampoo)");
    System.out.println(" 2. Consume the product (shampoo)");
    while( inpInt > 2 || inpInt < 1){
        inpInt = scanInp.nextInt();

    }
    if(inpInt == 1){

        while(sham[x] != 0){
            x++;
        }

            System.out.println("Please insert the name of the shampoo down below.");
            shName = scanInp.nextLine();
            System.out.println("Please insert the type of the shampoo down below.");
            shType = scanInp.nextLine();
            System.out.println("Please insert the origins (hotel, apartment, etc) of the shampoo down below.");
            shFrom = scanInp.nextLine();
            System.out.println("Please insert the amount of the shampoo down below.");
            shAmount = scanInp.nextInt();

            shampooDetails sham[x] = new shampooDetails(shName, shType, shFrom, shAmount);

        }else if(inpInt == 2){
            System.out.println("Please choose how you want to consume the product.");
        }

    } 
}

and below is my class code (don't know if it helps):

public class shampooDetails {
private String sName;
private String sType;
private String sFrom;
private int sCAmount;
private int sTAmount;

public shampooDetails(){
    System.out.println("Creating a new shampoo...");
    sName = "Unknown";
    sType = "Unknown";
    sFrom = "Unknown";
    sCAmount = 0;
    sTAmount = 0;
}

public shampooDetails(String name, String type, String origins, int amount){
    System.out.println("Creating a new Shampoo with parameters...");
    sName = name;
    sType = type;
    sFrom = origins;
    sTAmount = amount;
    sCAmount = sTAmount;
}

I'm currently using NetBeans 8.1. My goal is to use sham[x] above as an automated way to create another shampooDetails. Thank you.




Simple Ruby Classes and Objects program

I am writing a script where I have to create an Orange Tree and every time I run through the specified method the tree's height goes up, tree's age goes up, and number of oranges on the tree also increases. But after a certain time (it's up to me) the tree is supposed to die. So in my program I decided that if the tree is 15 feet or more it should be dead. Now every time I run through the method the height, age, and number of oranges go up and once the height goes past 15 feet I get a message saying "Tree is dead" but the height keeps increasing. I want it to stop once the tree is dead. Also how can I add something different every time the user runs the method to go into the next year? For example right now every year the height goes up by 3, number of oranges goes up by 4 and age goes up by 1 as it should. How do I make the height and number of oranges go up by a random number every year? (not too large) here is my code.

class OrangeTree

def initialize
@tree_height = 0
@no_oranges = 0
@tree_age = 0
end

def firstYear

    if @tree_height >= 15 then
        puts "Tree is dead"
    end

    @tree_height = @tree_height + 3
    puts "Your orange tree is " + @tree_height.to_s + " feet tall!"

     @tree_age = @tree_age + 1
     puts "Your orange tree is " + @tree_age.to_s + " year old!"

    @no_oranges = @no_oranges + 4
    puts "Your orange tree has " + @no_oranges.to_s + " oranges!"

end

def pickOrange
    if @no_oranges == 0 then
        puts "You can't pick any oranges yet, you have to wait at least a year!" else

    puts "How many oranges do you want to taste?" + " Remember you only have " + @no_oranges.to_s + " oranges on your tree!"
    pick2 = gets.chomp.to_i
    puts "The oranges taste delicious and very refreshing!" 

    @no_oranges = @no_oranges - pick2

    end
    end

    def isDead
        if @tree_height >= 15 then
            return true else
            return false
        end
    end

        def countOranges
            puts "Current number of oranges: " + @no_oranges.to_s
        end
    end




Best solution for database connection in DAL

I would like to create a database abstraction layer for all database DDL and DML queries in python for postgresql database.

I can have each *DAO.py for each database table , all DAL methods can be in this scripts under class. As of now am creating a database connection in BaseDAO class. All other DAO classes are inherited this BaseDAO class for connection object. But its creating a database connection object each time I create/instantiate DAO classes. I want to avoid repeated database connection object. I would like to database connection objected created once and make use of that for others.

What would be the best solution to make use of database connection created in a BaseDAO class in BaseDAO.py for all DAO classes in different *DAO.py files ?




Python: How to make the the value of a variable an object

I am currently trying to create a program in python that randomly creates an object in a class when run. However, the problem I've run into is that when i attempt to create the object with code like this:

name = sword(name, rarity, dam)

I get an object with the reference being the variable name and not the actual name stored inside. How do create the object using the value inside the name variable as the reference?




PHP Class - disable index access

I have a php class, for example:

class myClass
{
    private $id;
    private $url;

    public function getId() { return $this->id; }
    public function getUrl(){ return $this->url; }

    public function setId($id)   { $this->id  = $id; }
    public function setUrl($url){ $this->url = $url; }
}

And I can use it like so:

function bla()
{
    $x = new myClass();
    $x['abc'] = 123;
}

My IDE does not highlight this as an error - this is not ideal behaviour. Clearly this is a class, not an associative array, it should not be accessed by index. Is there a way to make this a compiler warning at least? Thanks




How can I print the end result of this method in Swift?

Sorry for the admittedly rough title, but I am taking a course for Swift on teamtreehouse.com, and I did a "code challenge" recapping the Object-Oriented Swift course. Anyway, I was provided a couple of classes and my goal was to subclass the Machine class and override the method to actually do something, which I did. I passed the challenge but was curious if I could actually print the end result of this the function after passing in a parameter.

class Point {
    var x: Int
    var y: Int

    init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }
}

class Machine {
    var location: Point

    init() {
        self.location = Point(x: 0, y: 0)
    }

    func move(_ direction: String) {
        print("Do nothing! I'm a machine!")
    }
}

// Enter your code below

class Robot: Machine {
    override func move(_ direction: String) {
        switch direction {
        case "Up": location.y += 1
        case "Down": location.y -= 1
        case "Left": location.x -= 1
        case "Right": location.x += 1
        default: break
        }

    }
}

let aRobot = Robot()
aRobot.move("Up")
print(aRobot.location)

So, the final 3 lines are my attempt to actually manage this, but in the console, the line "Point" is printed and not the actual result of the method being enacted. I would like the result to be printed in the form of coordinates if possible. Sorry for the potentially bad code, I am only a beginner. Thanks in advance!




Where can I look at the Rails controller high-level superclasses?

I am trying to understand some of the higher level functioning of Rails, using the Rails console. I run controller.class.superclass.superclass which gives ActionController::Base, controller.class.superclass.superclass.superclass which gives ActionController::Metal and controller.class.superclass.superclass.superclass.superclass gives AbstractController::Base.

I have found these in the API documentation.

http://ift.tt/2m07t4Q http://ift.tt/1kmelDM

[can only post two links]

I can add to these simply by declaring the classes again in the console, but is there a way to find the original Ruby code for these and to inspect and edit it in its original file(s)? Just in case I need to know the full contents of these for future.




Access to not declared class in main function

We have a class A inside which is a function which returns an instance of class B with parameters. This required for constructor of class A. In a class B has a constructor with parameters, and a few public fields. In the main function, we declare A:

class A
{
public:
   B func()
   {
      return B(par1,par2,par3);
   }
};
class B
{
public:
   par1;
   par2;
   par3;
   B(par1,par2,par3)
   {
      this->par1 = par1;
      this->par2 = par2;
      this->par3 = par3;
   }
};

int main()
{
   A a();
   return 0;
}

How can we get access to public fields of class B in main function, if we have not declared it? Thank you!




Constructor, Member objects [duplicate]

This question already has an answer here:

class Person{

public:
   Person(const string &nm, const string &surnm)
   : name(nm), surname(surnm)
   {

      cout << "\ntimes";
   }

private:
   string name;
   string surname;

};

class Family{

public:

  Family(Person &dad, Person &mom, Person &chld )
  : father(dad), mother(mom), child(chld)
  {
  }

private:

   Person father;
   Person mother;
   Person child;

};


int main(void){

  Person father1("John", "Gun");
  Person mother1("Marry", "Gun");
  Person child1("Alex", "Gun");

  Family firstFamily(father, mother, child);


  return 0;

}

When I compile this code, no error occurs.However, when I define "firstFamily" object, the memory for member objects father, mother ,and child is allocated. If memory is allocated for these objects, then constructor of class Person must be executed three times and I define three objects by using class Person in main method. Thus, constructor of Person class must be executed 6 times.However, it is executed for three times. Why is it three times ?( can reason be that I initialized father mother and child member objects in constructor class Family ? and that constructor is not executed for member objects. )




PHP OOP extend class or pass it as parameter

i am confused a little, well for a long time, i've used PHP classess in this way:

class A {
   private $temp;

   public function __construct() {
       for($i=0; $i<=300000; $i++) { $this->temp[ $i ] = "Nedzad Alibasic"; }
   }
}

and then another class which contains parameter in construct where i would pass class A as declared model:

class B {
   private $a;
   public function __construct($a) { $this->a = $a; }
}

And everything was fine, i could easy refer to class A by $b->a->somefunction(); but always it seemed to me, when i allocate A class to B, i would charge extra memory, because i passed the whole class? But how do i see it, there's almost no difference between passing and extending class?

I mean, is there someone who can lead me why should i switch from this way to class B extends A { /** code **/ } when there's almost no difference in memory?

Or there's something else usefull i could use with extends, but can't use within passing class as parameter.

Best regards.




C++ programm with classes

Write a program in C++ with classes: We have these categories: Office , Equipment and Prints, which one of them has objects for example( Office has chairs ,table etc) , (Equipment has PC , laptops etc.) and each of these objects has name,surname,quantity.There are 100 articles and are input by the user.Create a function which counts quantities for each of the category and this function is created out of the class.These program ate the end should print for example:"The first category has 30 tables".




how I create xaml if i already have cs without xaml

I already have class C# .cswithout .xaml page. Now I want to use xaml style in it. Can I create new xaml page and assign this with my written .cs class? Or I can delete my class and create new xaml with empty cs? I use Visual Studio 15 C#.




C++ Printing out values from Array of objects of certain class

the point of my program is to take in values for student and then print out the values stored in the student object. I am having difficulty printing out past the 1st object and i can't understand why. Any help?

error in program sample output

//
//  main.cpp
//  homework4
//
//  Created by Brenda Gonzalez on 2/23/17.
//  Copyright © 2017 Brenda Gonzalez. All rights reserved.
//

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

class Student
{
public:

    Student(int courses = 0)
                :numCourses(courses)
    {}

    // initializes numCourses to 0
    static void studentInfo(int number, int count, Student* studentNum);
    //outputs the student name and prints all courses in schedule
    void resetInfo(int courses, char *schedule);
    //resets the number of courses to 0 and the schedule to an empty list
    void studentInput();

private:

    string name;
    int numCourses;
    char *courseList[50];
    long length;

};


int main() {

    int number = 0, count = 0;

    cout << "How many students would you like to input?" << endl;
    cin >> number;

    Student* studentNum = new Student[50];


    for (int i = 0; i < number; i++)
    {
        studentNum[i].studentInput();
        count++;
    }

    char answer;

    bool moreStudents = false;

    while (!moreStudents)
    {

        cout << "Would you like to input another student? (Y or N) " << endl;
        cin >> answer;

        if (answer == 'Y' || answer == 'y')
        {
            studentNum[number].studentInput();
            number++;
        }

        else if (answer == 'N' || answer == 'n')
        {
            moreStudents = true;
        }
    }

    Student::studentInfo(number, count, studentNum);
}

void Student::studentInput()
{

    string courseName;
    int i = 0, p = 0;

    cout << "Enter student name: " << endl;
    cin >> name;
    cout << endl;

    cout << "Enter number of courses: " << endl;
    cin >> numCourses;
    cout << endl;

    for (i = 0; i < numCourses; i++)
    {

        cout << "Enter name of course"<< ":" << endl;
        cin.ignore();
        getline(cin, courseName);

        length = courseName.length();

        courseList[i] = new char[length];

        for (p = 0 ; p < length; p++)
        {
            courseList[i][p] = courseName[p];
        }

        courseList[i][p] = '\0';
    }

    cout << endl;
}

void Student::studentInfo(int number, int count, Student* studentNum)
{
    cout << "Number of students entered: " << number << endl;

    for (int i = 0; i < number; i++)
    {
        cout << endl;
        cout << "Student " << (i + 1) << ": " << studentNum[i].name << endl;

        cout << "Courses: " << endl;
        for (int p = 0 ; p < 15; p++)
        {
            cout << studentNum[i].courseList[i][p];
        }
    }

}




dictionary is empty when called from another class

i have this 2 classes inside 1 file

this Character

public class Character{
    public static int Count = 0;
    public string username, charname;
    public int gender, level, money, playtime;

    public Character(string _username, string _charname, int _gender, int _level, int _money, int _playtime)
    {
        username = _username;
        charname = _charname;
        gender = _gender;
        level = _level;
        money = _money;
        playtime = _playtime;
        Count++;
    }
}

and this Player

public class Player : Script
{
    public Dictionary<string, Character> CharacterList = new Dictionary<string, Character>();
}

and i wanted to call CharacterList Dictionary from another class in another file like this

public class AmmuNation : Script
{
    Player Ply = new Player(Client sender);

    public void Test()
    {
        API.consoleOutput(Ply.CharacterList[sender.name].charname);
    }
}

but when the Test() executed it gives me this error even though the Key is in the dictionary

The given key was not present in the dictionary.

at System.Collections.Generic.Dictionary`2.get_Item(TKey key)

it worked when i call it from the class Player and will give me the value of charname

but when i call it from AmmuNation it will say that the Key is not found

even the Dictionary is empty when i tried this

foreach (KeyValuePair<string, Character> kvp in Ply.CharacterList)
{
    API.consoleOutput(kvp.Key);
}

but on Player it will print every Key inside the CharacterList




Variable resolved with 'this' vs without 'this' in java [duplicate]

This question already has an answer here:

This seems to be a general question about variable resolution in classes but I was unable to find any good answer on the internet so I am gonna ask here.

Consider the following classes,

class A {
    int x;
    public A() {
        this.x = 10;
    }
}

class B {
    int x;
    public B() {
        x = 10;
    }
}

Which of the following is gonna perform faster and why?

  1. Class A, Variable 'x' with 'this' resoltion
  2. Class B, Variable 'x' without 'this' resolution
  3. Both will have exactly same number of instructions and hence will take the same amount of time

I figured out 'this.x' takes lesser time. But what is the reason behind it? What extra instructions are generated in the latter case?




Using the Plantronics SDK with a Delphi application

and thank you in advance for any advice / insight / assistance that can be provided.

The Background:

We have a soft phone application that is written in Delphi (XE3) for Windows. The ability to answer an incoming call by activating the answer button an a Plantronics Wireless Headset was recently requested. The MSI files were downloaded and executed, and the Plantronics SDK was converted / altered into a Delphi Library File.

I then started to follow the "First Steps" section of the Plantronics Website. I knew that the "First Steps" code would have to be tweaked to fit the Delphi system.

The Problem:

In adjusting the code to work within Delphi, a few translation problems were encountered and resolved. One such error is proving to be stubborn - When an instance of one specific class is created, the error "Class not registered" is thrown.

"First Steps" code for reference -

//  Connect to the Plantronics COM API:
myAppName = "SDK .NET COM sample";
sessionManager = new COMSessionManager();
sessionManager.Register(myAppName, out session);

// Hook to SessionManager events:
sessionManagerEvents = sessionManager as ICOMSessionManagerEvents_Event;
if (sessionManagerEvents != null)
{
    sessionManagerEvents.onCallStateChanged += SessionManagerEvents_onCallStateChanged;
    sessionManagerEvents.onDeviceStateChanged += SessionManagerEvents_onDeviceStateChanged;
}

Delphi Code:

//Connect to the Plantronics COM API:
plugin_name: "Plugin Name";
the_session: CoCOMSession.Create;
session_manager = new COMSessionManager.Create;
session_manager.Register(plugin_name, the_session);

//Hook to Session Manager Events
state_device_event_args := CoCOMStateDeviceEventArgs.Create;
call_event_args := CoCOMCallEventArgs.Create;

The final line of Delphi Code is the issue. The other three "Create" calls go off without a hitch. The line "call_event_args := CoCOMCallEventArgs.Create;" throws the error "Class not registered", even through it is declared and implemented in the library file along with the other three.

Excerpts from the library file:

Class Declarations:

IID_ICOMStateDeviceEventArgs: TGUID = '{91542BEE-4931-4620-9E96-23AE4001E93F}';
CLASS_COMStateDeviceEventArgs: TGUID = '{335D08FD-8BB5-4EF5-964B-E8A8C010530F}';

IID_ICOMCallEventArgs: TGUID = '{0280956C-C644-4CD8-B124-C8A99E5D505E}';
CLASS_COMCallEventArgs: TGUID = '{705129C3-2265-4F10-9768-0FF8A20234C0}';

Class creation functions:

//Works
class function CoCOMStateDeviceEventArgs.Create: ICOMStateDeviceEventArgs;
begin
    Result := CreateComObject(CLASS_COMStateDeviceEventArgs) as ICOMStateDeviceEventArgs;
end;

// Doesn't Work
class function CoCOMCallEventArgs.Create: ICOMCallEventArgs;
begin
  Result := CreateComObject(CLASS_COMCallEventArgs) as ICOMCallEventArgs;
end;

Every tutorial / forum answer about resolving the "Class Not Registered" error that I have found has not resolved the issue.

Does anyone have any advice or insight as to what I have been doing wrong?

Thank you.




How to create a Java Array of Class? [on hold]

I have some class A,B,C, and these three class extends D so

A extends D
B extends D
C extends D

But I want to create an array which is Like D[3] = {A,B,C}; But I cannot.....Can anyone help..




Creating a "Screen" class that handles every print command for my program, getting a null pointer exception [duplicate]

This question already has an answer here:

I'm trying to use a class ("Screen") to handle all instances of System.out.print in my other classes. However I am getting a null pointer exception from my main method when I try to run my code to test it it.

I can't figure out what exactly is causing this error, any tips would be appreciated.

Main Class

public class AtmTest {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    //Screen.displayMessage(null);


    AtmTest test = new AtmTest();

}

public AtmTest(){
    //write way to start all processes
    new ATM();

}

}

This is the ATM class where I am first tyring to call the Screen class to display a message to the console, and where my code stops running.

public class ATM {

private boolean userAuthenticated;
private int currentAccountNumber;

private static final int BALANCE_INQUIRY = 1;
private static final int WITHDRAWAL = 2;
private static final int DEPOSIT = 3;
private static final int EXIT = 4;

private Keypad keypad;
private Screen screen;
private BankDatabase bankDatabase;

public ATM(){
//new Screen();
//screen.displayMessage("hey"); 
run();
}

public void run(){


    screen.displayMessageLine("Welcome!");

    authenticateUser();
    displayMainMenu();
    performTransactions();

}

This is the screen class that is supposed to control all outputs for the program.

public class Screen {



public Screen(){


}

public void displayMessage(String a){

    System.out.print(a);
}

public void displayMessageLine(String a){
    System.out.println(a);
}

public void displayDollarAmount(double a){
    System.out.println("$" + a); //make to two decimal places
}




Check the class of a variable

I have to use a method depending on a variable. I used Polymorphism to reference them in a Dictionnary, but for now, i have to use each of their property and to use them depending of which class is it. So i need to detec which class is used by a variable.

To deal with this, i tried to make a switch but as you can see in my spy, i always have error (check the blue one)

enter image description here

Do you know a way to call a method depending on which class a variable is instantiated in ?




Sprites do not move in SFML

I am working with my first small project in SFML. I made a ball (projectile) which is bouncing around on the screen and a player which is movable. The problem however, occurred when I tried to make an Objecthandler to my objects. After letting the handler taking control of the drawing and updating of the objects, the player and the ball just stopped and became unmovable. My question is why? The ball:

#ifndef PROJECTILE_H
#define PROJECTILE_H
#include <SFML\Graphics.hpp>
using namespace std;

class Projectile : public sf::Drawable {

private:
    sf::Texture texture;
    sf::Sprite sprite;
public:
    Projectile();
    virtual ~Projectile();
    sf::Sprite getSprite() const;
    virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
};

#endif //PROJECTILE_H

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

Projectile::Projectile() {

    if (!this->texture.loadFromFile("../Resources/projectile.png")) {
        cout << "Error! Projectile sprite could not be loaded!" << endl;
    }
    this->sprite.setPosition(sf::Vector2f(0.0f, 0.0f));
    this->sprite.setTexture(this->texture);
    sf::FloatRect boundingBoxProjectile = this->sprite.getGlobalBounds();
}

Projectile::~Projectile() {
}

sf::Sprite Projectile::getSprite() const{
    return this->sprite;
}

void Projectile::draw(sf::RenderTarget & target, sf::RenderStates states) const {
    target.draw(sprite, states);
}

The handler:

#ifndef OBJECTHANDLER_H
#define OBJECTHANDLER_H
#include "Block.h"
#include "Player.h"
#include "Projectile.h"
using namespace std;

class ObjectHandler : public sf::Drawable {

private:
    Player player;
    Block block;
    Projectile projectile;
    int hitX = 0;
    int hitY = 0;
    float checkX;
    float checkY;
    float keyFrameDuration = 0.0f;
    float speed = 500.0f;
public:
    ObjectHandler();
    virtual ~ObjectHandler();
    void updateProjectile(float dt);
    void updatePlayer(float dt);
    void updateBlock(float dt);
    virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
};

#endif OBJECTHANDLER_H

#include "ObjectHandler.h"

ObjectHandler::ObjectHandler() {
    this->projectile = projectile;
    this->block = block;
    this->player = player;
}

ObjectHandler::~ObjectHandler() {
}

void ObjectHandler::updateProjectile(float dt) {
    sf::Vector2f direction;

    if (hitX == 0) {
        direction = sf::Vector2f(0.5f, checkY);
        checkX = 0.5f;
        if (this->projectile.getSprite().getPosition().x >= 700) {
            hitX = 1;
        }
    }
    else if (hitX == 1) {
        direction = sf::Vector2f(-0.5f, checkY);
        checkX = -0.5f;
        if (this->projectile.getSprite().getPosition().x <= 0) {
            hitX = 0;
        }
    }

    if (hitY == 0) {
        direction = sf::Vector2f(checkX, 0.5f);
        checkY = 0.5f;
        if (this->projectile.getSprite().getPosition().y >= 460) {
            hitY = 1;
        }
    }
    else if (hitY == 1) {
        direction = sf::Vector2f(checkX, -0.5f);
        checkY = -0.5f;
        if (this->projectile.getSprite().getPosition().y <= 0) {
            hitY = 0;
        }
    }

    this->projectile.getSprite().move(direction * speed * dt);
 }

void ObjectHandler::draw(sf::RenderTarget & target, sf::RenderStates states)   const {
    this->block.draw(target, states);
    this->projectile.draw(target, states);
    this->player.draw(target, states);
}

And Game:

#ifndef GAME_H
#define GAME_H

#include <SFML\Graphics.hpp>
#include "ObjectHandler.h"

class Game : public sf::Drawable {
private:
    virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
    sf::Texture backgroundTexture;
    sf::Sprite backgroundSprite;
    ObjectHandler object;
public:
    Game();
    virtual ~Game();
    void update(float dt);
};

#endif // GAME_H

#include "Game.h"
#include <iostream>
using namespace std;

void Game::draw(sf::RenderTarget & target, sf::RenderStates states) const {
    target.draw(backgroundSprite, states);
    target.draw(this->object, states);
    }

Game::Game() {
    if (!backgroundTexture.loadFromFile("../Resources/levelOne.jpg")) {
        cout << "The background could not be loaded!" << endl;
    }
    backgroundSprite.setTexture(backgroundTexture);
}

Game::~Game() {
}

void Game::update(float dt) {
    this->object.updatePlayer(dt);
    this->object.updateProjectile(dt);
    this->object.updateBlock(dt);
}




is there a max for variables in a class? ES6 [on hold]

Hi in my last question I defined only the space button but in my library I am using all the letters and numbers.

In my library it doesn't work. (over the 60 array's which all have 2 items) and it works if I short the variables amount as in my last question.




Create a pickable Python class

I am trying to create some custom Python classes for my application. When I try to debug my code I can not pick the instances of my custom classes, I receive the error "Object XXX is not pickable". I found this page http://ift.tt/2d0nD9C but I don't understand how I should implement the methods that make my class pickable. For example how would you modify the following classes so that I can pick instances of them?

class Point3D:
def __init__ (self, x, y, z):
    self.x = x
    self.y = y
    self.z = z

def move(self, vector):
    self.x += vector.x
    self.y += vector.y
    self.z += vector.z
    return

def isValidPoint(self):
    isNotValid = False
    isNotValid = math.isnan(self.x) or math.isnan(self.y) or math.isnan(self.z)
    return not isNotValid

And

class PointCloud3D:
def __init__ (self):
    self.points = []    

def getNumberOfPoints(self):
    return len(self.points)

def addPoint(self, point):
    self.points.append(point)
    return

def addPointCloud3D(self, additionalPointCloud3D):
    for self.point in additionalPointCloud3D:
        self.addPoint(point)

def getCloudCenter(self):
    numberOfPoints = self.getNumberOfPoints()
    centersSumX = 0
    centersSumY = 0
    centersSumZ = 0
    for point in self.points:
        centersSumX = centersSumX + point.x
        centersSumY = centersSumY + point.y
        centersSumZ = centersSumZ + point.z
    centerX = centersSumX/numberOfPoints
    centerY = centersSumY/numberOfPoints
    centerZ = centersSumZ/numberOfPoints

    center = Point3D(float(centerX), float(centerY) , float(centerZ))

    return center




DrawRectangle doesn't work

I have a rectangle on a class created by me. The function "DrawRectangle" doesn't draw anything. I put the code below:

My own class (Unidad.cs):

class Unidad
{
    //Constructor
    public Unidad(string tipo, int movimiento)
    {
        tipoUnidad = tipo;
        movimientoUnidad = movimiento;
    }

    //Propiedades
    public string tipoUnidad {get; set;}
    public int movimientoUnidad { get; set; }

    //Método para dibujar unidad
    public void colocar(MouseEventArgs e)
    {            
        Form1 myf = new Form1();

        using (Graphics g = myf.picboxFondo.CreateGraphics())
        {
            Pen pen = new Pen(Color.Red, 2);

            g.DrawRectangle(pen, e.X, e.Y, 20, 20);

            pen.Dispose();
            g.Dispose();
        }
    }
}

Main class:

public partial class Form1 : Form
{
    //Prueba de clase
    Unidad prueba;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        picboxFondo.Size = ClientRectangle.Size;
        prueba = new Unidad("I", 20);
    }

    private void picboxFondo_MouseDown(object sender, MouseEventArgs e)
    {
        prueba.colocar(e);
    }
}

I have picboxFondo Modifiers public. All compile correctly and works perfect, but when I go to g.DrawRectangle I see all the values are OK but it doesn't draw anything.

Can you help me?

Thanks!




Classes with virtually common code

I have a number of custom collection classes. Each serves to provide a collection of various custom types - one custom type to one custom collection. The custom collections inherit List<T> [where T in this case is the specific custom type, rather then a generic] and provide some additional functionality.

I previously did away with the custom collections and had custom methods elsewhere, but I found as I extended the code that I needed the collections with their own methods.

It all works, everything is happy. But it irritates me, because I know I am not doing it properly. The issue is that each class uses pretty much the same code, varying only the type and a parameter, so I feel that it could be implemented as an abstract class, or generic, or extension to List, or ... but I'm not really understanding enough of the differences or how to go about it to be able to sort out what I need.

Here are two of my several collections, so that you get the idea:

    // JourneyPatterns
public class JourneyPatterns : List<JourneyPattern>
{
    private Dictionary<string, JourneyPattern> jpHashes;       // This is a hash table for quick lookup of a JP based on its values

    /* Add a journey pattern to the JourneyPatterns collection. Three methods for adding:
         1. "Insert Before" (=at) a particular point in the list. This is the method used by all three methods.
         2. "Insert After" a particular point in the list. This is "before" shifted by 1 e.g. "after 6" is "before 7"
         3. "Append" to the end of the list. This is "before" with a value equal to the list count, and is the same as inherited "Add", but with checks
    */
    public JourneyPattern InsertBefore(JourneyPattern JP, int before)
    {
        // check for a pre-existing JP with the same parameters (ignore ID). Do this by constructing a "key" based on the values to check against
        // and looking it up in the private hash dictionary
        JourneyPattern existingJP;
        if (jpHashes.TryGetValue(JP.hash, out existingJP)) { return existingJP; }
        else
        {
            // construct a new ID for this JP
            if (string.IsNullOrWhiteSpace(JP.id)) JP.id = "JP_" + (Count + 1).ToString();
            // next check that the ID specified isn't already being used by a different JPS
            if (Exists(a => a.id == JP.id)) JP.id = "JP_" + (Count + 1).ToString();
            // now do the add/insert
            if (before < 0) { Insert(0, JP); } else if (before >= Count) { Add(JP); } else { Insert(before, JP); }
            // finally add to the hash table for fast compare / lookup
            jpHashes.Add(JP.hash, JP);
            return JP;
        }
    }
    public JourneyPattern InsertAfter(JourneyPattern JP, int after) { return InsertBefore(JP, after + 1); }
    public JourneyPattern Append(JourneyPattern JP) { return InsertBefore(JP, Count); }
}

// JourneyPatternSections
public class JourneyPatternSections : List<JourneyPatternSection>
{
    private Dictionary<string, JourneyPatternSection> jpsHashes;       // This is a hash table for quick lookup of a JPS based on its values

    /* Add a journey pattern section to the journeyPatternSections collection. Three methods for adding:
         1. "Insert Before" (=at) a particular point in the list. This is the method used by all three methods.
         2. "Insert After" a particular point in the list. This is "before" shifted by 1 e.g. "after 6" is "before 7"
         3. "Append" to the end of the list. This is "before" with a value equal to the list count, and is the same as inherited "Add", but with checks
    */
    public JourneyPatternSection InsertBefore(JourneyPatternSection JPS, int before)
    {
        // check for a pre-existing JPS with the same parameters (ignore ID). Do this by constructing a "key" based on the values to check against
        // and looking it up in the private hash dictionary
        JourneyPatternSection existingJPS;
        if (jpsHashes.TryGetValue(JPS.hash, out existingJPS)) { return existingJPS; }
        else
        {
            // construct a new ID for this JPS
            if (string.IsNullOrWhiteSpace(JPS.id)) JPS.id = "JPS_" + (Count + 1).ToString();
            // next check that the ID specified isn't already being used by a different JPS
            if (Exists(a => a.id == JPS.id)) JPS.id = "JPS_" + (Count + 1).ToString();
            // now do the add/insert
            if (before < 0) { Insert(0, JPS); } else if (before >= Count) { Add(JPS); } else { Insert(before, JPS); }
            // finally add to the hash table for fast compare / lookup
            jpsHashes.Add(JPS.hash, JPS);
            return JPS;
        }
    }
    public JourneyPatternSection InsertAfter(JourneyPatternSection JPS, int after) { return InsertBefore(JPS, after + 1); }
    public JourneyPatternSection Append(JourneyPatternSection JPS) { return InsertBefore(JPS, Count); }
}

As you can see, what is differing is the type (JourneyPattern, or JourneyPatternSection), and the prefix that I am using for the "id" property of the type ("JP_" or "JPS_"). Everything else is common, since the method of determining "uniqueness" (the property "hash") is part of the custom type.

Some of my custom collections require more involved and different implementations of these methods, which is fine, but this is the most common one and I have implemented it about 6 times so far which seems a) pointless, and b) harder to maintain.

Your thoughts and help appreciated!




C++'s Class Problems

I am asking you a question from the C ++ class. When you look at the C + + course videos, why are they using the voids(functions) that people use outside of class. Can someone explain this to me?

example:

void example::example1()
{
// code stuff
}




Accessing a field of a class containing template

Consider a macro as:

#define mac<a,b> abc

I have a function that has the return type as of abc type.
Say xyz = func()
Now with the help of xyz, I want to access a and assign some value to a,say

a = 10;

How can access the variable 'a', and assign it the value using xyz.




VBA custom class, get all objects by property value

I have a Class - "Class1" with an attribute - "attribute1" as string. Possible vlaues of this attribute are {1, 2, 3}

In my main program, I need to retrieve all the objects with attribute1 value equal to {1}.

Wich is the most efficient way to do this?

Thank You in advance.




Accessing a member of an Object of template class

Consider the following macro:

#define hash<k1,v1> abc

Now by some how, I have the instance of abc with me and now I want to assign a value to v1 using abc, how can i do that.

I tried to do abc->v1 = 10;
I also tried abc.v1 = 10;
but both of them didn't work. Please provide a simple solution.




dimanche 26 février 2017

UML Class Diagrams for a game in C++

How would one go about constructing a complete overview Unified Modelling Language class diagram for a maze game in 3 Dimensional? What classes will I need to have?




Why it is OK to construct a new object while class has not been fully loaded?

public class Test{
    static Test test = new Test();
    static {
        System.out.println("Test class ...");
    }
    public static void main(String[] args){

    }
}

See code above , class Test will get loaded when main is called and a static instance called test will be constructed , has Test class been loaded already when static Test test = new Test(); is called ? If not , is it safe to do like this ?




OOP Fundamental - Refactoring?

(sorry if the title isn't appropriate, not sure how to properly word the question)

I am refactoring a project and have the following situation. I have a class called Property and a class called User.

Business Rule: A user has one or more properties.

So, what makes more sense:

User.GetProperties() or

Properties.Get(userId)

Currently I am accessing the properties via the User class. Not sure if this is the common way of handling this relationship. What do you guys/gals think?

I'm thinking forward here and the reason for the concern is because I will later have:

Property.Get(state)

Property.Get(zip)

Property.Get(city)

Property.Get(numberOfBedroom)

etc...

other ways to get properties and I know these will be accessible via the Property class. Right? (I'm firm on this) so given this, does this change how to access a User's Properties?




Does not contain a static 'Main' [BUT IT DOES?]

I'm following quill18creates C# tutorial series on youtube. I'm on video #3, where we start discussing classes and the main.cs script to execute code.

I've copied his example verbatum and started the project EXACTLY as he did in xamarin studio but no matter what, the compiler does not seem to want to accept the code.

Code:

using System; // We need the standard .NET library for many things

namespace DodgeGame
{
    class DodgeGameMain
    {
        static void Main()
        {

        }
    }

}

C:\Users\Aspen\Documents\Projects\DodgeGameSolution\DodgeGame\CSC: Error CS5001: Program does not contain a static 'Main' method suitable for an entry point (CS5001) (DodgeGame)

I've noticed that his Xamarin Studio is detecting a "document outline" while mine just says "an outline is not available for the current document". I've tried to save as. the file but that didn't change a thing. So what's going on?

You'll notice from this pic it's not displaying the class in green either:

enter image description here




Questions about Java upcasting/downcasting and inheritance pripority

Having trouble understanding the intricaies of upcasting/downcasting, and static binding and dynamic bidning in these cases. Please consider the following classes and interface example:

 public class Marsupial {   private String name;
         Marsupial(String name) {    
         this.name = name;    
         }
         void eats() {   
         System.out.println("Eats #1");   
         }
         String getName(){    return name;    
         }
         }


    abstract class Herbivore extends Marsupial {
         Herbivore(String name) {
         super(name);    
         }
         void eats() {
         System.out.println("Eats #2");    
         }
         abstract void chews(boolean b); 
         }


    interface Australian {   
    public void greets(Koala k); 
    }


    public class Koala extends Herbivore implements Australian {
         Koala(String name) {
         super(name);   
         }
         public void greets(Koala k) {
         System.out.println("G'day mate!");
         System.out.println(getName() + " " + k.getName() );   
         }
         void chews(boolean b) {

        System.out.println("Yum yum!");   
         }
         void chews(int i) {    System.out.println("Delicious!");    
         }
         void likes(Koala k) {
        greets(k);
        k.greets(this);   }    
        }

Now when I make a driver class to use all of the classes I notice some odd things happening that I am not sure why.

For example,

public class Driver {   
    public static void main(String[] args) {
    Marsupial m = new Marsupial("Kate");
    Marsupial m2 = new Koala("Kim");
    System.out.println(m.getClass() == m2.getClass());
               }    
}

This turns out to be false. They are not the same class. So what is happening here exactly. We have Marsupial on the left and something else on the right. So does what's on the right the only thing that matters when we are calling methods? When the compiler runs and looks at methods does is check the right side of the equals operator and say ok this is such and such class, therefore use the methods of the class defined on the right side when figuring out whose class to use.

Also,

if inside the main method I wrote:

Marsupial m = new Koala("jack");
m.eats();

This prints out Eats #2. Now is this because since Koala does not have a eats method is just goes back one level up the chain, so the next level up would be Herbivore and since that has an eats() method that is what gets called, is that the idea there?

Another example in the main method:

Herbivore h = new Koala("June");
((Marsupial)h).eats();

Here the thing that throws me off is that we can use abstract classes as a reference to actual objects, like here Herbivore is an abstract class therefore cannot be instaniated, but it can be assigned to a class that does instantiate an object. But what confuses me most is that now we are in the Koala class and we call the eats() method but then we UPCAST the variable to Marsupial. So does that automatically put us in the Marsupial class and therefore anytime we call a method even if its in other classes the Marsupial class method is the one that gets called since we typecasted it to Marsupial, therefore its Eats #1.

Another area of confusion is if we do this in main:

Australian a = new Koala("Khloe");
a.chews(true);

It's werid seeing an interface be assigned to a subclass instantiation. It confuses me what would get called with a.chews(true). So since it's been defined as a Koala object then we are IN the Koala class and must use Koala methods if they exist, and if not there we go one level up to check that they have that method and so on and so fourth. But here the method is invalid. So does it only work if Australian had a prototype method in there and Koala defined it? then it would work? Is that the idea behind setting interfaces as objects of their subclasses? Even though Koala has that method since Australian does not, it will not work.

And if we have the code in main like:

Herbivore h = new Koala("Stacy");
h.chews(true);

this will print out "Yum yum" only because Herbivore had that prototyped undefined method and Koala defined it. But if Herbivore didn't have that prototype method is wouldn't work.

The last question I have is if this were run in main:

Herbivore h = new Koala("Kali");
h.chews(4);

This won't work because despite the fact that Koala has this method in there, it's not defined in Herbivore, so it's invalid.

Please help, any corretions or information you could provide would be very helpful.

Thank you




variable or field 'name of var' declared void

When i run this program i get error: variable or field 'push green; declared void, i have 2 files a header file and a cpp file. Not sure of what is causing this error. I am new to OPP in c++. someone can help with this please????????????

/////thinker.h
#include <cstring>
#include <assert.h>
#include <string>

class thinking_cap
 {
   public:
      void slots(char new_green[], char new_red[]);
      void push_green() const;
      void push_red() const;

 private:
 char green_string[50];
 char red_string[50];
};



////////  thinker.cpp
  #include <iostream>
 #include <stdlib.h>
 #include "thinker.h"

 int main( ) 
  {
    thinking_cap student;
    thinking_cap fan;
    student.slots( "Hello",  "Goodbye");
    fan.slots( "Go Cougars!", "Boo!");
    student.push_green( );
    fan.push_green( );
   student.push_red( );
   return 0;
 }

 void thinking_cap::slots(char new_green[ ], char new_red[ ])
 {
   assert(strlen(new_green) < 50);
   assert(strlen(new_red) < 50);
   strcpy(green_string,  new_green);
   strcpy(red_string, new_red);
 }
void thinking_cap::push_green 
 {
   cout << green_string << endl;
 }
 void thinking_cap::push_red 
 {
   cout << red_string << endl;
 }




How to make it shorter till 25 in Swift 3

Pease, help me to make it shorter till the Person.inventory.itemsInBag[25] thank you very much

func drawInventory() {

    if Person.inventory.itemsInBag[0].Id > 0 {
        let itemButton1 = UIButton()
        itemButton1.setImage(Person.inventory.itemsInBag[0].Image, for: .normal)
        itemButton1.frame = CGRect(x: 300, y: 185, width: 30, height: 30)
        itemButton1.addTarget(self, action: #selector(tapItemInInventory), for: .touchUpInside)
        view.addSubview(itemButton1)
    }
    if Person.inventory.itemsInBag[1].Id > 0 {
        let itemButton1 = UIButton()
        itemButton1.setImage(Person.inventory.itemsInBag[1].Image, for: .normal)
        itemButton1.frame = CGRect(x: 300+40, y: 185, width: 30, height: 30)
        itemButton1.addTarget(self, action: #selector(tapItemInInventory2), for: .touchUpInside)
        view.addSubview(itemButton1)
    }


}

func tapItemInInventory() {
    print(self.Person.inventory.itemsInBag[0].Name + "Pressed")
}

func tapItemInInventory2() {
    print(self.Person.inventory.itemsInBag[1].Name + "Pressed")

}




Java programming real life examples Bank

I am totally disconnected. I am trying to write real life examples using extends, superclass using a real life example of a Bank.

I need help trying to create a program that imitates Bank, employee, account saving, account checking, account holder, that uses extends, overrides, overwrite and sets up the program to simulate real life. Can someone help me understand how to think like a programmer so that I can start the program code.

  public abstract class Bank{

   private String employeeType;
   private


}   
public class account extends Bank{
   private int accountID;
   private int savingsAccountAmount;
   private int chackingAccountAmount;

}

pulbic class automaticTeller{
   private int tellerCashAmount;

}




Java: setting a bool for all instances of a class

I searched some times but didn't get a clue.

I'm trying to set up a directed graph. Each node (instance of the class Node) should hold a bool visited to see if it was visited by a search function.

After the search is completed i want to reset the bool visited for all instances of the class without running through them again.

Is there some way i can go - or am I totally on the wrong track?

Thanks for help and cheers, Mike

// Cans.java
public class Cans {
    public static void main(String[] args) {
        int[] fillLevels = {2,15,3};
        int[] states = {8,0,0};

        node MyNode = new node(3,0);
        MyNode.setfillLevels(fillLevels);

        node MyLink = new node(3,1);

        MyNode.addLink(MyLink);

        MyNode.setStates(states);

        MyLink.printStates();

        System.out.println("Number of links: "+MyNode.getNumLinks());
    }

    boolean fillState(node nodeA, int stateA,node nodeB, int stateB){
        int value = nodeA.getState(stateA);
        nodeA.setState(stateA, value);
        return true;
    }

}

..

// node.java
    import java.util.*;

    public class node {
        private int[] states;
        private static int[] fillLevels;
        private int level;
        private int n_nodes;
        private static int id0 = 0;
        private int id;
        private boolean visited;

        List<node> next = new ArrayList<node>();

        node(int n_nodes,int level){
            id=id0;
            id0++;
            this.n_nodes = n_nodes;
            this.level = level;
            states = new int[n_nodes];
            visited = false;
            fillLevels = new int[n_nodes];
        }

        void setfillLevels(int[] fillLevels){
            this.fillLevels = fillLevels;
        }

        void setStates(int[] states){
            this.states = states;
        }   

        void setState(int state, int value){
            states[state] = value;
        }

        int getState(int state){
            return states[state];
        }

        void addLink(node linkedNode){
            next.add(linkedNode);
        }

        boolean isVisited(){
            return visited;
        }

        int getNumLinks(){
            return next.size();
        }

        void printStates(){
            System.out.println("States of node #"+id+" on level "+level+":");
            int cntr = 0;
            for(int i:states){
                System.out.println(cntr+": "+i);
                cntr++; 
            }
        }
    }




How do I refer to the object created by a class, the the class

I want to call a function in my list class in another function of that class, but in order to do that it seems i have to be able to refer to the list i am observing. How do I do that? should be simple but i cannot find an answer anywhere.

this is a sample of my code, i wrote the StuctList header file, and this is its cpp equivalent

#include "StructList.h"

StructList::StructList()
{
    length = 0;
    currentPos = 0;
} // Default Constructor

bool StructList::IsThere(int ID) const 
{
    int index = 0;
    while (index < length && ID != data[index].identifier)
        index++;
    return (index < length);
}


int find(int ID) const
{
    if (IsThere(ID)) return -1; //here lies the issue, i think i should do something.IsThere(ID), but I don't know what
}

I know there is unexplained elements in this code, but if we could look past that it shouldnt alter the answer




How to pass a dinamically created interface as argument?

I'm dealing with the paramiko ssh library and in the docs it tells how to create my own policy for rejecting or accepting keys

I just need to pass an interface like this:

ssh.set_missing_host_key_policy(MyPolicyInterface)

Which I created like this:

class MyPolicyInterface(paramiko.MissingHostKeyPolicy): 
    def missing_host_key(client, hostname, key):
        key64 = key.get_base64()
        fingerprint = to_base_64(to_sha_256(key64))
        if fingerprint in known_hosts:
            print('fingerprint accepted: ' + fingerprint)
            return
        else:
            raise ValueError('fingerprint REJECTED: ' + fingerprint)

as you can see, I need to give a value for known_hosts inside this interface before passing to set_missing_host_key_policy. However, for this I'd need to have a constructor, which would add a self in the missing_host_key method, which would break the requirement for an interface.

Resuming: I need to do something like:

set_missing_host_key_policy(MyPolicyInterface(['host1', 'host2', ...]))




How to create a data structure in a Python class

class CD(object):
        def __init__(self,id,name,singer):
                self._id = id
                self.n = name
                self.s = singer

        def get_info(self):
                info = 'self._id'+':'+ ' self.n' +' self.s'
                return info

class collection(object):
        def __init__(self):
                cdfile = read('CDs.txt','r')

I have a file 'CDs.txt' which has a list of tuples look like this:

[
("Shape of you", "Ed Sheeran"),
("Shape of you", "Ed Sheeran"),
("I don't wanna live forever", "Zayn/Taylor Swift"),
("Fake Love", "Drake"),
("Starboy", "The Weeknd"),

......
]

Now in my collection class, I want to create a CD object for each tuple in my list and save them in a data structure. I want each tuple to have a unique id number, it doesn't matter they are the same, they need to have different id....can anyone help me with this?




JavaScript getting and then changing class (with variable)

I need to update buttons to show the last state that the group was in i.e. judge 1 scored a 0. I have four groups of 6 buttons. After all scores are entered I am committing the scores. I want to show what the last scores where.
enter image description here

My problem is grabbing the class from inside two for loops. The console is telling me:

Uncaught TypeError: Cannot read property 'className' of null at updateJudgeLast (scripts.js:278)

here is my function:

function updateJudgeLast(){
    for(j=1;j<5;j++){
        for(i=0;i<6;i++){
            var judgeScore ="#btnJudge";
            judgeScore += j;
            judgeScore += "_";
            judgeScore += i;
            console.info(judgeScore);

            var testLast = document.getElementById(judgeScore).className.split(' ')[1];
            console.info(testLast);

            switch(testLast){
            case "btn-default": break;
            case "btn-last":  $(judgeScore).attr("class", "btn btn-default"); break;
            case "btn-primary": $(judgeScore).attr("class", "btn btn-last"); break; 
            }
        }
    }
}

judgeScore is the id of the element to get the class of inside the loop it will output: "#btnJudge1_0" then "#btnJudge1_1". When I check the console it prints correctly but can't get it to check the class as it is null. What did I miss?

Background: This is a score board I'm making that is running FastLED on an ESP8266 12e the code is using JSON and JS to update the page and the board as needed.




Reference object in two classes C#

Let's go straight to my probably fairly simple problem.

I have a LoginService class in my Services folder which makes a connection with the server. I have another UserModel where I want to receive information from the server. In order not to login again (which would be stupid), I need to maintain the client reference in both files having the same value. In other words, I need to be able to access the same object from a different class (make another reference).

I have tried and tried and searched but I am missing something. A fairly similar post that I found that still didn't solve mine is this.

The code in my LoginService:

namespace App_Name.Services
{
    class LoginService
    {
        public static Class_Name client;

        public async Task MakeConnectionAsync(string userToken)
        {
            client = new Class_Name();

            PasswordVault vault = new PasswordVault();

            await client.LoginAsync(TokenType.User, userToken);

            await client.StartAsync();
        }

So now I want to get the user avatar on my UserModel.cs:

namespace App_Name.Models
{
    class UserModel
    {
        public string GetAvatar()
        {
            return LoginService.client.CurrentUser.GetAvatarUrl();
        }

But it always gives an exception because it tries but there is no connection. I am sure that it was Connected because in order to load the UserModel it has to be a successful connection.

Any ideas ?




extract characters from a list of names and make it a numeric command

I have a list of objects: area$X1,area$X2,area$X3,area$X4, ...area$X100.The class of each object is numeric. These objects are extracted from the results of a SpatialPixelsDataFrame. I have calculated the buffer area for different animal tracks from 1 to 100.

Eg. area$X1 is 0,0,0,0,0,0,1,1,1,1,1,0,1,1,0,0,0,0,0 I want to count the number of 1 in area$X1, so I used command

table<-table(area$X1)
#extract the number of 1s 
table[[2]]

this would give the number of 1s, and thus give me the size of the buffer area.

However, I want to do the same for all the other objects, area$X2 until area$X100. And calculate the mean number of 1s overall. I want to automate this process. How can I do it?

Currently, what I did is to create a list of names

names<-paste("area$X",1:100,sep="")

While I get the list of names I wanted, the class of elements in "names" is character.

names: "area$X1" "area$X2" "area$X3" "area$X4" "area$X5" "area$X6" "area$X7" 
..."area$X99"  "area$X100"
class(names[1]): character 

"area$X1" is no longer the numeric I wanted. I tried to removed quotation marks but it didn't help.

Can anyone help me with this? Thanks!!!




Is it possible to call a function inside json body in java

I have an interface in java with a json body like given below.

package com.url;
public interface MyUrls {
public static final String urlString = "{\n"    +
"   \"points\": {\n"    +
"       \"x\": 1.5 ,\n" +
"       \"y\": 2.0 ,\n" +
"       \"url\": \"www.google.com\",\n" +
"       } \n"   +
"   }"
} 

In the code, instead of the url "www.google.com", i need to call a method processUrl("www.google.com") and get the result in-line. I have tried the below given way. But its not working. Someone please help.

package com.url;
import com.url.Demo;
public interface MyUrls {
Demo demo = new Demo();
public static final String urlString = "{\n"    +
"   \"points\": {\n"    +
"       \"x\": 1.5 ,\n" +
"       \"y\": 2.0 ,\n" +
"       \"url\": \" \"+ demo.processUrl("www.google.com")+ \",\n"   +
"       } \n"   +
"   }"
} 




Defining an Instance of a class in a function to be Global [duplicate]

This question already has an answer here:

I have looked around this site but have struggled to find an answer to my question, so apologies if it has already been asked - and if it has could you please direct me to it.

So basically I have written a module which contains a class definition (with its function and value attributes) and some functions. One of these functions purpose, given the names and data, is to create multiple instances of the class (with the respective names given) defined in the same module.

When I call this function it seems to work, but the class instances appear to only be local to the function itself, and so are undefined (after the function has been called) in the main document.

Thus is there anyway to make the class instance defined in the function global?

Note: I have tried using the global keyword, but maybe I am using it wrong (see code below). Also I am knew to OOP in python so don't know much lingo, thanks in advance people :)

A simplified version of the code is:

Module File:

class class1:
    def __init__(self, data):
        self.data = data
    def some_function(self):
        ### Code to edit data ###


def multiple_classes(list_of_names, list_of_data):
    for pos, name in enumerate(list_of_names):
        exec("global " + name)
        exec(name + " = class1(list_of_data[pos]))

Main document:

import module

list_of_names = ['foo', 'foob', 'foobby']
list_of_data = [56.3, 'hello world', [3,2]]

module.multiple_classes(list_of_names, list_of_data)

print(foo.data, foob.data, foobby.data)

Which gives as NameError that 'foo' ('foob' or 'fooby' depending which one is first) is not defined. Yet if the print statement is placed inside the multiple_classes function, it works fine!




UWP: DataPackageView Bug

the Docs for the Clipboard Class state, that the getContent() Method returns a DataPackageView object. So far so good.

The following works:

var containsString = Windows.ApplicationModel.DataTransfer.Clipboard.getContent().contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.text)

containsString equals true.

The following does not work:

var text = Windows.ApplicationModel.DataTransfer.Clipboard.getContent().getTextAsync();
var text = Windows.ApplicationModel.DataTransfer.Clipboard.getContent().getTextAsync(Windows.ApplicationModel.DataTransfer.StandardDataFormats.text);
var text = Windows.ApplicationModel.DataTransfer.Clipboard.getContent().getHtmlFormatAsync();
var text = Windows.ApplicationModel.DataTransfer.Clipboard.getContent().getDataAsync(Windows.ApplicationModel.DataTransfer.StandardDataFormats.text);

Each methods are listed in the above linked Doc for DataPackageView, all returning an empty object after checking contains(...).

This also does not work:

var results = Windows.ApplicationModel.DataTransfer.Clipboard.getContent().requestAccessAsync();
var results = Windows.ApplicationModel.DataTransfer.Clipboard.getContent().requestAccessAsync(Windows.ApplicationModel.DataTransfer.StandardDataFormats.text);
var results = Windows.ApplicationModel.DataTransfer.Clipboard.getContent().unlockAndAssumeEnterpriseIdentity();

... all returning nothing.

I've literally tried everything. What am I doing wrong, or is this this a bug with the getContent() method or the DataPackageView?




Crashing after using operator new[]

I have a class Vector with array and size fields. When each of two arrays v1 and v2 have more than one element there is a problem with allotment of memory for this arrys in operator of copying. How can I fix it ? Here is a code:

#include<iostream>
using namespace std;

class Vector 
{
private:
    unsigned size;
    double *arr;
public:
    Vector();
    Vector(double *arr, unsigned size); 
    Vector(const Vector &copy);
    Vector &operator= (const Vector &vector);
    friend Vector operator+ (const Vector &varLeft, const Vector &varRight);
    friend ostream & operator<< (ostream &output, const Vector &var);
    friend istream & operator>> (istream &input, Vector &var);
};

int unitTest();

int main()
{
    unitTest();

    system("pause");
    return 0;
}
int unitTest()
{
    Vector v1;
    cin >> v1;
    Vector v2;
    cin >> v2;
    Vector v3;

    cout << "Your Vector v1:" << endl;
    cout << v1 << endl;
    cout << "Your Vector v2:" << endl;
    cout << v2 << endl;

    cout << "Arrays +:" << endl;
    v3 = v1 + v2;
    cout << v3 << endl;

    return 0;
}
    Vector::Vector()
    {
        arr = new double[size];
    };

Vector::Vector(double *arr, unsigned size) : size(size)
{
    arr = new double[size];
    for (int i = 0; i < size; ++i)
    {
        this->arr[i] = arr[i];
    }
};

When operator+ returns value my program crashes after line 'arr = new double[size];' in operator of copying.

Vector::Vector(const Vector &copy)
{
    size = copy.size;
    arr = new double[size];
    for (int i = 0; i < size; ++i)
    {
        arr[i] = copy.arr[i];
    }
}
Vector operator+ (const Vector &varLeft, const Vector &varRight)
{
    Vector res;
    res.size = varLeft.size;

    if (varLeft.size == varRight.size)
    {
        for (int i = 0; i < res.size; ++i)
        {
            res.arr[i] = varLeft.arr[i] + varRight.arr[i];
        }
    }
    else
    {
        cout << "Error. Vectors have different size." << endl;
    }
    return res;
}