mardi 31 mai 2016

Ruby beginner. Instance variable not showing

class Player

  def initialize (name, age, start_year)
    @name       = name.capitalize
    @age        = age
    @start_year = start_year
  end

  def playing_for
    current_year  = Time.new.strftime("%Y")
    num_of_years  = current_year - @start_year
    @num_of_years = num_of_years
  end

  def to_s
    "Hi, my name is #{@name}. I am #{@age} years old. I have been playing Ultimate for #{@num_of_years} years."
  end

end

jon = Player.new("jon", 41, 2009)
puts jon

When I run the following code in Terminal, it shows as:

"Hi my name is Jon. I am 41 years old. I have been playing Ultimate for years."

and doesn't show the #{@num_of_years}.

Clearly there's something wrong with the way I've defined @num_of_years, but I can't figure out what.

Thanks in advance!




Sheadawson Silverstripe Blocks: Blocks within blocks

I'm using Shea Dawson's silverstripe blocks module and I'm wondering if there's a way to have blocks within blocks?

For example: I'm trying to create a "Grid" Block, and within that grid block I'd like the user to be able to "Add a block". Essentially, this "Grid Block" will act like a "Block Area".

I'm on the most recent version of SS, and this module. Let me know if you need any further information...




Php validation Class for Name, Email, Password, Phone Number, Image etc

I want to create a php validation class for name,password,email,contact,landline,Image.

<form action="" method="post" class="registration-form"enctype="multipart/form-data"> 
  
  <input type="text" name="username">
  <input type="password" name="password">
  <input type="text" name="contact">
  <input type="text" name="Image">
  <input type="email" name="Email">
  
  
  <input type="submit" name="submit">



Null Reference Exception when writing to custom class

So I'm just starting to get into custom classes in VB and running into this error when I attempt to write. I tried to follow the teacher's example, but also wanted to get into some of the more advanced aspects of VB and tried to use an array within my classes, and well, things don't quite work.

Form1 class:

Dim mypt(7) As Point

Private Sub Create_Click(sender As Object, e As EventArgs) Handles Create.Click
    PtSelect = Input()  'Returns an int
    mypt(PtSelect).mC(0) = CDec(IX.Text) 'Error here!
    mypt(PtSelect).mC(1) = CDec(IY.Text)
    mypt(PtSelect).mC(2) = CDec(IZ.Text)
End Sub

Point Class:

Public Class Point
Private c(2) As Decimal

Public Sub New(ByVal X As Decimal, ByVal Y As Decimal, ByVal Z As Decimal)
    c(0) = X
    c(1) = Y
    c(2) = Z
End Sub

Public Property mC(Val As Integer) As Decimal
    Get
        Return c(Val)
    End Get
    Set(value As Decimal)
        c(Val) = value
    End Set
End Property
End Class

Really just unsure what to do past this point, I've fiddled with everything that I could think may be it, but am unsure. My teacher did say that is was possible to use arrays within classes before I ran into the error and I'd like to make it work.




Loop and Set through variable in a Class in C# that is used multiple times

I Have a class TrayDetails containing a bunch of variables.

public class TrayDetails
{
    public string ID { get; set;}
    //... some more string variables here
}

Then I declared it on my main form twice.

private TrayDetails Right;
private TrayDetails Left;

I would want to iterate through the specific Right or Left variables and set all of its variables to string.empty when a condition is met.

Code:

Action FillData = () =>
{
     if(Right != null)
     {
        this.label1.Text = Right.ID;
        //... somemore labels = Right.somevariables
     }
     else
     {
         //I would want to put the string.empty variables here using a loop.
         //I cant seem to get PropertyInfo to work
     }

     //similar as above
     if(Left != null)
     // you get the idea
}

How can I achieve the desired output?




PHP Class not found but it's in folder and it is also included

I'v a singular proble... if I include files in this manner:

<?php     
    session_start();
    session_regenerate_id();
    foreach (glob("../class/*.php") as $filename)
    {
        echo "$filename\n";
        include $filename;
    }
    foreach (glob("../utilities/*.php") as $filename) {
        echo "$filename\n";
        include $filename;
    }

class ECommerce {
    private $checker;
    private $errorManager;

    /**
     * ECommerce constructor.
     */
    function __construct() {
        $this->checker = new Checker();
        $this->errorManager = new ErrorManager();
    }

the website doesn't work and when I do

$ecommerce = new ECommerce();

it says that

Class 'ErrorManager' not found in path

I thought anything, when I'v thought to try this:

 <?php     
    session_start();
    session_regenerate_id();
    include "../class/Checker.php";
    include "../class/User.php";
    include "../utilities/ErrorManager.php";

class ECommerce {
    private $checker;
    private $errorManager;

    /**
     * ECommerce constructor.
     */
    function __construct() {
        $this->checker = new Checker();
        $this->errorManager = new ErrorManager();
    }

in this manner, it works and anything does what it has to do!
Inside me, the question "why", has made roots and I can't sleep (really).
Why first manner works for all classes except for ErrorManager?
Thank you before!

Here, there is ErrorManager class code (it has the blank construct like Checker class)

<?php
class ErrorManager
{
function __construct() {
}

function getErrorUserNameNotValid() {
    return "Nome inserito non valido";
}

function getErrorUserSurnameNotValid() {
    return "Cognome inserito non valido";
}

function getErrorUserEmailAlreadyExists() {
    return "Email inserita non valida!";
}

function getErrorUserEmailNotValid() {
    return "Email inserita non valida!";
}

function getErrorUserPasswordNotValid() {
    return "Password inserita non valida! Inserisci una password che sia lunga tra i 6 e i 50 caratteri!";
}

function getErrorUserAddressNotValid() {
    return "Indirizzo inserito non valido!";
}

function getErrorUserPhoneNumberNotValid() {
    return "Numero telefonico inserito non valido! Inserisci solo numeri, senza trattini o caratteri speciali!";
}
}




C++ Subclass method overriding

I feel like total dumb on this one. I want to create a subclass of my class Model:

class Model {
public:
    Model(const GLchar* path, const GLuint& amountLoaded);
protected:
    void loadModel();
};

It should look like this:

class AnimatedModel : public Model {
public:
    AnimatedModel(const GLchar * path, const GLuint & amountLoaded);
protected:
    /*Override!*/
    void loadModel();
};

Then, form the outside, I want to create a new AnimatedModel. The AnimatedModel contructor simply passes its arguments to the Model constructor. The Model constructor then calls the Method loadModel(). I hoped, that this call would then reach my overridden version of this method, but it doesn't seem to work like this... What am i missing here?




Roxygen2: "Error in loadNamespace(name) : there is no package called ‘testthat’"?

This is a follow up from a previous question.

How to integrate new R6Class functions stored in independent files into an existing R package?

In summary, in trying to load a function stored in a file. I managed to do it by altering manually the NAMESPACE and Collate in the DESCRIPTION and rebuilding the package. However, I am sure this is not standard practice since the package already has a man folder and .Rd files created with roxygen2. However, when I try to use roxygen2 to manage my NAMESPACE and Collate in the DESCRIPTION, the following error pops up.

==> devtools::document(roclets=c('rd', 'collate', 'namespace'))

Updating mypackage documentation
Loading mypackage
Error in loadNamespace(name) : there is no package called ‘testthat’
Calls: suppressPackageStartupMessages ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted

Exited with status 1.

The working directory contains a folder tests with a testhat.R file and a second folder full of functions.

Any hint of why roxygen2 is falling to produce the documentation and update the NAMESPACE and DESCRIPTION?




Java - static initializers in imported projects

So I have two projects A and B, and project B is imported in project A, and in project B I want to initialize some objects which have static initializers. The problem is, they aren't getting called (already tested with final keyword, does not help).

So I actually want to have a small system and it should go this way (every class decribed here are in project B):

  • class A is a main class in which you can call a method addClassToLoad()* to add other classes (which will be "loaded" when method start() in class A will be called);
  • classes B, C and D call method addClassToLoad() from its static initializer;
  • when some class from project A calls a method start(), class A lists all classes it has gotten and calls a method onLoad() (explained in *).

And every method is static, so it's meant to be only one (no "instancing").

Saddly, static initializers aren't getting called.

And the question is: do I do something wrong (or maybe it is not possible at all) or maybe there is another way to do this small system? (I just don't really want to write in class A about every class, which must be loaded at start() method)

*addClassToLoad() takes an interface which has one method onLoad(), so it is getting called when method start() is called in class A

In code version:

class A:

public class A {
    private static ArrayList<ClassToLoad> classesToLoad;

    public static void addClassToLoad(ClassToLoad c) {
        if (classesToLoad == null)
            classesToLoad = new ArrayList<ClassToLoad>();
        classesToLoad.add(c);
    }

    public static void start() {
        for (ClassToLoad c : classesToLoad) {
            c.onLoad();
        }
    }
}

class B (and others (C, D etc.) like this one):

public class B {

    static {
        A.addClassToLoad(new ClassToLoad() {
            public void onLoad() {
                load();
            }
        });
    }

    private static void load() {
        // do something here on load ...
    }
}

class ClassToLoad:

public interface ClassToLoad {
    public void onLoad();
}




How to draw association between servlet classes

Here is my database diagram
enter image description here

Question-1: Is that good idea to store all modules categories in one place? If this category module has problem then all department categories will be down whereas if I see with generalization point of view then it seems to me correct because creating category module for each class is repetition that comes as bad design concept

Here is the class diagram that I made

enter image description here

Question-2: I am trying to draw class diagram by extend javax.servlet in a 3 tier layer i.e. Controller, Formatter and DAO. Here I am confused to detect exact relationship between classes

Please advise and thanks in anticipation




Python Class Recompute __str__

I have a class which has an attribute that is a list of two values:

Class Lollipop:
   def __init__(self, licks=None):
      self.licks = [int(x) for x in licks.split(':')]

   def __str__(self):
      if self.licks:
          return (':').join([str(x) for x in self.licks])

Now when I initially create a class instance I set licks to be None:

L = Lollipop()

Then I change it later:

L.licks = [5,2]

Now when I try to print it:

print L

I get:

[5,2]

Not the expected:

5:2

Am I doing something wrong? It almost looks like the string is computed when the instance is created, but that can't be... right? Can somebody explain?




android individual onclick for every button of the same class

the Problem is the following... I made a class whith a button and some stuff around it. Now I can add this button to the screen by creating an object. Example:

FloatingButton button = new FloatingButton();

I did this 3 times in my main activity. Therefore I have 3 Buttons now. The Problem is that I want to add a different onclick function to each of the Buttons. So if I add an onclick function in the FloatingButton class every Button would do the same. So I need to set the onclick function from the main activity. Is that possible?




How to use TypeScript constructor to declare variables

I'm trying to use TypeScript constructor in an Angular2 project, and I got confused regarding how to use class constructor to initialize the variables:

function Auto () {
    this.move = function () {
        console.log('move');
    }
    this.stop = function () {
        console.log('stop');
    }
}

Now I will use it in the class:

class Car {
    constructor(private _auto: Auto) {
    }

    onMove() {
        this._auto.move();
    }
}

When I try to compile, I get this error Cannot find name Auto, so could anyone help me understanding what's going on?

And, why private _auto: Auto make _auto a new instance of Auto class?




Python: TypeError: __init__() takes exactly 5 arguments (6 given)

I've been having this issue with this code, and I'm not sure why I'm still getting this TypeError here. I have the following Animal class, which is the base class for the Dog class defined below it. I want to create a Dog object which inherits from this Animal class.

Here's the Animal class:

class Animal(object):
    __name = None
    __height = None
    __weight = None
    __sound = None

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

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

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

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

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

def get_name(self):
    return self.__name

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

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

def get_sound(self):
    return self.__sound

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

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

And then I have the following Dog class which inherits from the above Animal class:

class Dog(Animal):
    __owner = None

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

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

def get_owner(self):
    return self.__owner

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

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

When I try to create a Dog object with the following code:

spot = Dog('Spot', 22, 11, 'Bark', 'John')

I get the following TypeError:

TypeError: __init__() takes exactly 5 arguments (6 given)

Does anyone know why I'm getting this error? I'm not really understanding what's going on here.

Thanks in advance!




How to integrate an R6 class into an existing program?

I`m working in an existing program that uses a system of R6Class modules. An example function is stored in a file son.R and looks like:

#' @importFrom R6 R6Class
son_class <- R6Class("son", inherit = mother_class,
  private = list( ... Some private elements ... ),
  public = list(
     initialize = function(x, y, z) {
       ...Some code...
       super$initialize(x, y)
     },
     calculate = function(x,y,z) {
     ... More Code ...
     calc_son(x,y,z)
     }
  )
)

#' @inheritParams ...
#' @return ...
#' @template ...
#' @examples ...
#' @export
son  <- function(x = "son", y, z) {
        son_class$new(x, y, z)
}

The authors of the package say that the way to create new modules is by creating new R6Classes that inherit from mother_class. Thus I create a daughter.R file that looks almost the same, just change the son to daughter, but when I try to compile i get the following error:

==> R CMD INSTALL --no-multiarch --with-keep.source mypackage

Error in .install_package_code_files ( , instdir " . " ) :
missing files in 'path / to / mypackage / R' in the' Collate ' : daughter.R
ERROR: unable to collate and parse R files for package ‘mypackage’

Which may be the source of this error. I am following the authors instruction verbatim.




Bukkit Using Multiple Classes

I'm trying to learn Java & Bukkit at the same time ( I have learnt some basic Java previously a few months back and made a simple text game).

I know what I'm doing when I'm using 1 class but, as you may know, everything became messy so I'm re-coding everything but attempting to make it a lot cleaner but I've come across a problem, apart from the main class, no other classes work, here is my code.

MAIN CLASS:

package me.Camaloony.RoyalCosmetics;

import java.util.logging.Logger;

import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

import net.md_5.bungee.api.ChatColor;

public class Core extends JavaPlugin implements Listener {

Logger myPluginLogger = Bukkit.getLogger();

@Override
public void onEnable()
{
    PluginManager manager = getServer().getPluginManager();
        manager.registerEvents(this, this);
    Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.RED + "=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
    Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.AQUA + "Royal Cosmetics has been enabled!");
    Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.RED + "=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
}
@Override
public void onDisable()
{
    myPluginLogger.info("Test 1 has been disabled!");
    myPluginLogger.severe("Test 1 has an error and has not loaded.");   
    }
}

Here is my 2ND CLASS

package me.Camaloony.RoyalCosmetics;

import java.util.ArrayList;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class MainGUI implements Listener {

    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {

        Player player = (Player) sender;

        if (commandLabel.equalsIgnoreCase("Cosmetics")) {
            createMainMenu(player);
        }

        return false;
    }

    @EventHandler
    public void onInvClick(InventoryClickEvent event){
        if (event.getCurrentItem().getItemMeta().getDisplayName().contains("Particles GUI")) {
            event.setCancelled(true);
        }
    }

    public void createMainMenu(Player player) {
        Inventory inv = Bukkit.getServer().createInventory(null, 45, "Royal Cosmetics");

        ItemStack item1 = new ItemStack(Material.REDSTONE);

        ItemMeta item1Meta = item1.getItemMeta();

        ArrayList<String> item1Lore = new ArrayList<String>();

        item1Lore.add("Click here to go to the particles GUI");

        item1Meta.setDisplayName("Particles GUI");
        item1Meta.setLore(item1Lore);

        item1.setItemMeta(item1Meta);

        inv.setItem(0, item1);

        player.openInventory(inv);
    }

}

How would I make it so the 2nd class is actually 'read' ?

Thanks a lot!




Circularity when using base and derived class as arrays in both

I am trying so make a class which holds a arbitrary value as specified in NBT format. It is a kind of json, but more advanced.

So, I make a class which holds a ListValue(a value without a name) and another one which holds a Value(with name). In the derived class, I lift = operator from base

using ListValue::operator=;

In a third file I have two usings:

using CompoundData = std::vector<Value>;
using ListData = std::vector<ListValue>;

ListValue has a private member as:

union ValueHolder
{
    Byte vByte;
    Short vShort;
    Int vInt;
    Long vLong;
    Float vFloat;
    Double vDouble;
    String* pString;
    CompoundData* pCompound;
} mData;

(I'll add ListData* later)

The problem is I have absolutely no idea how how to include all these headers so it will work with the circularity. I tried several forward declarations and containers as vector or vector with smart pointers for breaking it, but nothing worked for me.

I would be very very grateful if you could help me to give me a(n) idea / solution for my code. Thank you very much.




Why is this Java code returning a IndexOutOfBoundsException error?

Does anyone know why this code is returning an IndexOutOfBoundsException. I'm assuming it has something to do with one of the for loops but I am not sure.

Thank you for the help!

import java.util.*; public class Computer {

public Computer(ArrayList<String> unameList, ArrayList<String> ucontentList){


 for (int n = 0; n<=nameList.size()-1;n++){

 nameList.set(n, unameList.get(n));
 contentList.set(n, ucontentList.get(n));

 }

}

public void addFile(String fileName, String Content){

nameList.add(fileName);
contentList.add(Content);

}

public void editFile(String toEdit){

//disgregard

}

public void removeFile(String fileName){

for (int i = 0; i<=nameList.size()-1;i++){

    if(nameList.get(i).equals(fileName)){

        nameList.remove(i);
        contentList.remove(i);

    }



}

}

public String displayFile(String fileName){

String c = "no value";

for (int t = 0; t<=nameList.size()-1;t++){



    if((nameList.get(t)).equals(fileName)){

        String a = nameList.get(t);
        String b = contentList.get(t);
        c = a + b;


    }

}
return c;

}

public ArrayList<String> nameList = new ArrayList<String>(7);
public ArrayList<String> contentList = new ArrayList<String>(7);

public static void main(String args[]) {

ArrayList<String> name = new ArrayList<String>(7); 
ArrayList<String> content = new ArrayList<String>(7); 
name.add("name1");
name.add("name2");
name.add("name3");
name.add("name4");
name.add("name5");
name.add("name6");

content.add("content1");
content.add("content2");
content.add("content3");
content.add("content4");
content.add("content5");
content.add("content6");

Computer desktop = new Computer(name, content);

String display = desktop.displayFile("name2");
System.out.println(display);

}

}




How to print '%d' & '%s' in a class in python

I'm writing a script which counts some specific words and gives me specific count of the words.

I'm currently stuck in printing data, from the class.

My next task would be put these values in a excel file using a data driven framework.

Here's what i have done uptil now:

a = driver.page_source
soup = BeautifulSoup(a, "html.parser")


class counter_class:
    def count(self, tittle, block_code):
        blockcode_passed = block_code.count("Passed")
        blockcode_blocked = block_code.count("Blocked")
        blockcode_fail = block_code.count("Failed")
        blockcode_retest = block_code.count("Retest")
        blockcode_cannot_test = block_code.count("Connot Test")
        blockcode_completed = block_code.count("Completed")
        blockcode_passwc = block_code.count("Pass With Concern")
        blockcode_untested = block_code.count("Untested")

        print '%s' + ' ' + '%d' %(tittle,blockcode_passed)
        print '%s' + ' ' + '%d' %(tittle,blockcode_fail)
        print "Apps Gateway(Untested)" + ' ' + '%d' %(blockcode_untested)
        print "Apps Gateway(Blocked)" + ' ' + '%d' %(blockcode_blocked)
        print "Apps Gateway(Retest)" + ' ' + '%d' %(blockcode_retest)
        print "Apps Gateway(Cannot Test)" + ' ' + '%d' %(blockcode_cannot_test)
        print "Apps Gateway(Completed)" + ' ' + '%d' %(blockcode_completed)
        print "Apps Gateway(Pass With Concern)" + ' ' + '%d' %(blockcode_passwc)




apps_gateway = soup.find_all("div", {"id":"group-3191427"})
apps_gateway_str = str(apps_gateway)
apps_gateway_obj=counter_class()
apps_gateway_obj.count("appsgateway",apps_gateway_str)

The second part of the code works but the 1st part of the code:

print '%s' + ' ' + '%d' %(tittle,blockcode_passed)
print '%s' + ' ' + '%d' %(tittle,blockcode_fail)

Gives me error:

print '%s' + ' ' + '%d' %(tittle,blockcode_passed)
TypeError: %d format: a number is required, not str




How do I inherit from a class that has both functions (that I want public) and variables (that I want private)

Say I have a class Base and another class Derived which inherits from Base.

Base includes variable int val and a virtual function void foo().

I want to implement the virtual functions inside the Derived class but as far as I understand it is not good practice to have the variables public as every member element should be private and have a get & set function due to encapsulation.

How do I go about achieving this? I thought about having a public function void foo2()which will act as a proxy that calls foo() from inside the class, but that seems a lot more messy than just inheriting the variables as public.

I'm preety sure that I either don't understand why or how encapsulation is useful or how it's supposed to be done.




class rand in c# use Midsquare method , Linear Congruential Method,Combined Linear Congruential Generators or Random-Number Streams and why [on hold]

class rand in c# use Midsquare method , Linear Congruential Method,Combined Linear Congruential Generators or Random-Number Streams and why




Issue with name of the class or namespace

Compiler say:students isn't the name of the class or of the namespace. And it say that "name" is undeclared .

students.cpp:

    #include "stdafx.h"
#include <string>
#include "students.h"
using namespace std;
    void students::set_name(string student_name)
    {
        name = student_name;
    }

students.h:

#pragma once
#include <string>
#include "students.cpp"
using namespace std;
class students
{   public:
            void set_name(string student_name); 
    private:
            string name;
};

Thanks.




How can I access Python instance variable of type set in the right way [duplicate]

This question already has an answer here:

Can anyone tell why, why the length of my instance variable( with type set) do not work the way as I though.

When I called a.addToSet("xx"), I thought the value of len(b.aSet) and len(ExampleClass.aSet) should return zero, so as a.aInt be 100 and rest be 0, while the console print the 1 for all the three instance.

Many thanks

==========================

Let's say, we have a class called ExampleClass with two variable: aSet and aInt.

class ExampleClass():
    aSet = set()
    aInt = 0
    def addToSet(self,aValue):
        self.aSet.add(aValue)

a=ExampleClass()
b=ExampleClass()
a.addToSet("xx")
a.aInt=100

print len(a.aSet)
print len(b.aSet)
print len(ExampleClass.aSet)
print a.aInt
print b.aInt
print ExampleClass.aInt

OUTPUT

1

1

1

100

0

0




How to save search path to .mat file upon loading Matlab class object?

I am working on an analysis tool where the results between sessions are saved in a class object. When the object is saved to disk, the search path to the .mat file is saved within the object (function save_to_mat_file below):

classdef SampleClass < handle
  properties
    mat_file_name
  end
methods
  function save_to_mat_file(obj, mat_file_name)
    obj.mat_file_name = mat_file_name;
    save(mat_file_name, 'obj');
  end
    function auto_save(obj)
      save(obj.mat_file_name, 'obj');
    end
  end
end

Then the same filename can be used for auto-saving later. However, if the object is saved to a mat-file, and the mat-file then is moved (for instance to another computer, or another directory on the same computer), the auto_save function will use an obsolete search path for the .mat file. Is there some way to update the mat_file_name variable when the object is loaded? For instance, can the mat file name be retrieved in the loadobj method:

methods (Static)
  function b = loadobj(a)
    b = a;
    **%Set b.mat_file_name to search path of .mat file**
  end
end

(My gut feeling says this won't work, but it's the best attempt I could think of)




Swift : Unexpectedly found nil

This code is causing my application to crash and I can't figure out a way to fix it. The error is : fatal error: unexpectedly found nil while unwrapping an Optional value

Any idea how I can fix it? The two lines I'm returning in my createCharacters() function is whats causing the crash:

class NACharacters {

var featuredImage : UIImage!

init(featuredImage: UIImage){

    self.featuredImage = featuredImage

}

static func createCharacters() -> [NACharacters]{

    return[
        //THE TWO LINES BELOW CAUSE THE CRASH
        NACharacters(featuredImage: UIImage(named: "Diplo Squad")!),
        NACharacters(featuredImage: UIImage(named: "StopIcon")!)
    ]
  }
}




How to return a list instead of string from a class by default?

class A:
    def __init__(self, message):
        self.message = message

    def __repr__(self):
        return self.message

print A("Hello")

The above code prints prints "Hello", as a string is returned. But I want to return a list by default. Like if I write :

class A:
    def __init__(self, message):
        self.message = message

    def __repr__(self):
        mylist = [self.message]
        return mylist

print A("Hello")

The above code gives an error TypeError: __str__ returned non-string (type list)

Is there any way to return a list ?




Set width of table - not afftected

I am trying to set a fixed width to a certain table with the class selector. But its not affected at all. What is missing/wrong with this syntax?

css

.delivoptions_table th {
  table-layout:fixed;
  overflow: hidden;
  width: 200px;
}

the table ..

<div class = "delivoptions_table">
    <table id="deliver_alt_table">

            <tr>
                <td> ... </td>
            </tr>

         ...

    </table>
 </div>




Create Java Classes via XSD File using Eclipse

I am new to Java and Eclipse. What I now need to do, is creating Java classes by using a XSD file. I found some solutions online, but they all did not work for me. It is important, that there is a code, that does the job. Clicking "generate" is not the way, I want to realize the challenge.

JRE: jdk1.8.0_92

Libraries: jaxb-api.jar, jaxb-core.jar, jaxb-impl.jar, jaxb-jxc.jar, jaxb-xjc.jar




Need Help in PHP OOP

I'm new in PHP OOP. I need some help for how to write the php oop class then can call the class like below.

Query->table('user')->column('id','name')->where('name LIKE ?', ["name"=> 'John'])->orderby('name', 'desc')->get();

but, I had try so many time, what I can get it something like below then stop.

Query->table('user')->column('id','name');

I'm running out of idea and I had google alot, but fail to find any solution.

Thanks for reading my post and sorry about my poor english. :)




lundi 30 mai 2016

python generator in class

I am learning generator from this thread. This is really a good example for generator. But I am confused by one of the example code.

>>> class Bank(): # let's create a bank, building ATMs
...    crisis = False
...    def create_atm(self):
...        while not self.crisis:
...            yield "$100"
>>> hsbc = Bank() # when everything's ok the ATM gives you as much as you want
>>> corner_street_atm = hsbc.create_atm()
>>> print(corner_street_atm.next())  
$100  
>>> print(corner_street_atm.next())  
$100  
>>> print([corner_street_atm.next() for cash in range(5)])  
['$100', '$100', '$100', '$100', '$100']  
>>> hsbc.crisis = True # crisis is coming, no more money!  
>>> print(corner_street_atm.next())  
<type 'exceptions.StopIteration'>   
>>> wall_street_atm = hsbc.create_atm() # it's even true for new ATMs  
>>> print(wall_street_atm.next())  
<type 'exceptions.StopIteration'>  

>>> hsbc.crisis = False # trouble is, even post-crisis the ATM remains empty
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>

>>> brand_new_atm = hsbc.create_atm() # build a new one to get back in business
>>> for cash in brand_new_atm:
...    print cash
$100
$100
$100
$100
$100
$100
$100
$100
$100
...

When hsbc.crisis is reset to False, the corner_steet_atm can not yield anything but StopIteration. Why does this happen. I think the corner_street_atm is not empty after crisis.




How to access to a list of a class globally

i've got

namespace Example
{
    class TechCollection : List<Tech>
    {
    }
}

and then i've got this

TechCollection Tee = new TechCollection();

in one form but if I insert data I can't access it in other form Im not sure what's the problem, anyone can help?




JavaScript classes vs prototype-based inheritance

According to the Mozilla Developer Network, JavaScript classes are introduced in ECMAScript 6 and are syntactical sugar over JavaScript's existing prototype-based inheritance.

Considering I am just starting to use Javascript for OOP, I have the following questions.

How is the new formalism for classes, explained here:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

different from the previous syntax for instantiating classes, as described here?

var Polygon = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

How does this change (if so) the interpretation of classes in JavaScript?

Useful links on this topic:




Can i have a method in my implementation class which is not in its interface?

Say I have an interface class A ad class B implements Class A.

Class A

public interface classA {
       public static String getUserName(String userID);
}

Class B

public classB implements ClassA {
     public static String getUserName(String userID) {
         //some code here
     }

     //Is it right to have an additional method like this which is not in the interface
     public static String getFullName(String userID) {
         //some code here
     }   
}

1.Is it right to have a method in class B which is not declared in Class A ?




Read class objects from file c++

I need to read class objects from file, but I don't know how.

Here I have a class "People"

class People{
public:

string name;
string surname;
int years;
private:

People(string a, string b, int c):
name(a),surname(b),years(c){}
};

Now I would like to read peoples from .txt file and store them to objects of a class People.

For instance, this is how my .txt file looks like:

John Snow 32
Arya Stark 19
Hodor Hodor 55
Ned Stark 00

I think the best way to do this would be to create array of 4 objects. I need to read word by word and line after line, if I assume correctly but I don't know how...




Private value can still be accessed from outside

I am still bit confused about the scope, I think the variables can only be accessed within its scope, that's what I've understand in a general way

class Car {
    let manufacturer: String

    private(set) var color: String

    init() {
        manufacturer = "Ford"
        color = "Black"
    }

    func changeColor(color: String){
        self.color = color
    }
}

var carOfTim = Car()

carOfTim.changeColor("Red") // only "changeColor" fun can update the color
print(carOfTim.color)


//why I can do this?
carOfTim.color = "Green"
print(carOfTim.color) // it prints the "Green"!

Question: I think the private variable color can only be accessed by thechangeColor function, because changeColor has the same scope with color. But carOfTim.color = "Green" can still update the color variable, why?

Guess: Since I used the Xcode playground, everything is inputted into the same plain "terminal", therefore all of them might have the same scope, if I put the Car class into a different folder, carOfTim.color = "Green" may not working anymore.

Please correct me if I'm wrong. Thanks a lot for your time and help.




PHP - can't find Azure class createcontaineroptions

I am following this tutorial on using globs in Azure storage with PHP:

http://ift.tt/1K6nGwz

I used composer to get all the necessary dependencies. Here is my composer.json:

{
    "repositories": [
        {
            "type": "pear",
            "url": "https://pear.php.net"
        }
    ],
    "require": {
        "http://ift.tt/QkixGk" : "*",
        "pear-pear.php.net/http_request2" : "*",
        "http://ift.tt/QkixGm" : "*",
        "microsoft/windowsazure": "*"
    }
}

I do "composer update" and it appears to get everything needed.

In PHP I do:

<?php
require_once 'vendor\autoload.php';


use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Blob\Models\CreateContainerOptions;
use WindowsAzure\Blob\Models\PublicAccessType;
use WindowsAzure\Common\ServiceException;

$createContainerOptions = new CreateContainerOptions();

And that gives an error:

Fatal error: Class 'WindowsAzure\Blob\Models\CreateContainerOptions' not found in C:\myproject\azure.php on line 18.

I did print_r(get_declared_classes()); and sure enough, CreateContainerOptions is not in the list.

Can you please tell me what is wrong with my require or use statements that it doesn't pull in the CreateContainerOptions class?

Thank you!




Constructors not allowed a return type

I wrote this code for a Dynamic vector representation, however I get an error for constructors and deconstructors regarding their return-type.

This is the namespace Containers having the class DynamicVector and another class in in, Iterator, if you need code for the AbstractList or for the AbstractListIterator just ask and I will append the data.

namespace Containers
{
    template <typename Object>
    class DynamicVector : public AbstractList<Object>
    {
    private:
        int capacity;
        Object *array;

        void increaseCapacity(const int& increaseValue);
        void shiftLeftAtIndex(const int& index);
        void shiftRightAtIndex(const int& index);

    public:
        class Iterator : public AbstractListIterator
        {
        private:
            friend class DynamicVector<Object>;
            void setCurrent(Object *Element);

        public:
            Iterator();
            ~Iterator();

            /* Is iterator valid (NULL != this->current_) */
            bool isValid();
            bool hasNext();
            /* Iterator operators */
            void operator++();
            void operator++(int);
            bool operator==(const Iterator& Other);
            bool operator!=(const Iterator& Other);
            Iterator& operator=(const Iterator& Other);
            Object& operator*() const;
        };
        DynamicVector();
        DynamicVector(const DynamicVector& other);
        ~DynamicVector();

        void createList();
        void insert(const Object& data, const int& index);
        void add(const Object& data);
        void remove(const int& index);
        int isEmpty();
        Object get(const int& index);
        int size();
        Iterator begin();
        Iterator end();
    };

    template <typename Object>
    void DynamicVector<Object>::DynamicVector()
    {
        this->length = 0;
        this->capacity = 10;
        this->array = new Object[this->capacity];
    }

    template <typename Object>
    void DynamicVector<Object>::DynamicVector(const DynamicVector& other)
    {
        this->length = other.length;
        this->capacity = other.capacity;
        this->array = new Object[other.capacity];
        for (int index = 0; index < other.length; index++)
            this->array[index] = other.array[index];
    }

    template <typename Object>
    void DynamicVector<Object>::~DynamicVector()
    {
        ;
    }

... + other methods then I close the namespace with }




Load from more 2 class in 1 swift UISPLITVIEWCONTROLLER

I try to find information how to load this data from another class I have a UISPLITVIEWCONTROLLER and a lot of information inside I try to load Theta from 2 different classes in the 1 class can somebody help me please ?

searchController.searchBar.scopeButtonTitles = ["All", "Chocolate", "Hard", "Other"]
tableView.tableHeaderView = searchController.searchBar

candies = [

//i want to load the first2 candy from another class SWIFT

Candy(category:"go", name:"slow"),
Candy(category:"run", name:"feast"),

and the least 2 candy to load from another class SWIFT

Candy(category:"deanc", name:"good"),
Candy(category:"fly", name:"whery feast"),




C++ virtual templated method

I know this question has been answered in many different forms again and again, and is perhaps one of the most confusing points in C++'s design, but I'm trying to learn the language after many years doing many things in pure C that would be considered quite illegal in the C++ world (think function pointers juggling). I want to try educating myself to the C++ mindset before giving up and going to another language.

I just started a project in which the most fundamental component is a streaming class, and for that I wanted it to be generic: what kind of data it would stream would be up to its subclasses.

template <typename T>
class BasicStream {
protected:
    T *buffer;
    unsigned int bufferSize;
    unsigned int bufferPos;
    bool streamEnd=false;
public:
    virtual T read();
};

My idea was to chain objects together, as in the output of one object of certain class being directly read by another object of another class. But for this to work, all objects must be able to accept a generic read() function and return its desired type. For instance, I have a class to splice bits which accepts bytes (unsigned char) as inputs:

class BitExtractor : public BasicStream<bool> {
private:
    unsigned char bitMask;
    unsigned char byte;
    BasicStream<unsigned char> &byteSource;

public:
    BitExtractor(BasicStream<unsigned char> &source);
    virtual bool read();
};

It returns a bool type and needs any class which derives from BasicStream and has an <unsigned char> return type as input. My idea was to make the input completely agnostic from the data source; be it a file, an internet stream, or even some position in memory; all wrapped around classes derived from BasicStream<unsigned char>.

An example would be a FileReader class, to handle a/synchronous file loading:

class FileReader : public BasicStream<unsigned char> {
protected:
    FILE *file;
    bool asyncFlag;
    bool asyncOpReady;
    bool fileEnded;
    pthread_t asyncThread;
    unsigned int lastRead;
public:
    FileReader(char *fileName,int bufferSize=1024,bool asyncRead=false);
    ~FileReader();

    virtual unsigned char read();

private:
    typedef struct {
        unsigned int amount;
        unsigned int *read;
        unsigned char *buffer;
        FILE *file;
        bool *flag;
        bool *flagStreamEnd;
    } TData;
    static void AsyncRead(void *data);
};

Now, let's suppose I want to create a BitExtractor using a FileReader as data source.

BitExtractor bx=BitExtractor(FileReader("SomeFile.abc"));
bool firstBit = bx.read();

Internally, BitExtractor is calling the FileReader read() method. My assumption was that since FileReader is a class derived from BasicStream<unsigned char>, it should recognize the templated function.

BitExtractor::BitExtractor(BasicStream<UInt8> &source):bitMask(128),byteSource(source){}

bool BitExtractor::read(){
    bool bit=byte&bitMask;
    if(streamEnd==false){
        bitMask>>=1;
        if(bitMask==0){
            try {
                byte=byteSource.read();
                bitMask=128;
            } catch (...) {
                streamEnd=true;
            }
        }
    }
    else{
        throw "Bytesource has ended!\n";
    }

    return bit;
}

Even though it does compile, it fails to link due to vtable errors. I've already learnt though other StackOverflow questions that my code is impossible in C++, given its lack of runtime polymorphism. My question is, given my data streaming/chaining pattern, is there any other more "C++ish" alternative to implementing my design, like using or subclassing something from the STL (of which I know almost nothing)?

Or is it simply unimplementable in C++?




Container of class

I have a class Object, with some standard variables, functions, constructor and destructor. I use it to store info about every element (block) of my game. I want to:

  • Make it the most efficient way
  • Still have access to const. and dest.
  • Use it with a range-based for loop

I'm currently using std::vector <Object> v, but I think there might be a better solution.




Dice Roll game not working the way I need to JAVA

Alright so to quickly begin, I (and Uni mates) have created a code to run a Dice Rolling Game

  • Click Button to roll dice
  • PvP
  • Winner is first to get 1-6

public class Die {

int currentRoll, sides;

public Die() {
    this.sides = 6;
}

public Die(int sides) {
    this.sides = sides;
}

public int rollDice() {
    return new Random().nextInt(sides) + 1;
}}

public class SixNumbersPanel extends JFrame {

//**********************************************************************//
//                                                                      //
//These private Strings are added to create objects needed in the panel //
//                                                                      // 
//**********************************************************************//

private final String PlayerOne = "", 
                     PlayerTwo = "";
private final JButton PlayTwoRoll;
private final JButton PlayOneRoll;
private final JButton bEdit;
private final JButton bExit;
private final JButton bNew;

private final JScrollPane ScrollPane;
private final JTextArea GameArea;

private final JLabel header;
private final JLabel lblPlayOne;
private final JLabel lblPlayTwo;

private final JTextField PlayOneRollNum;    
private final JTextField PlayTwoRollNum;
private final JTextField playOneCount;
private final JTextField playOne_1;
private final JTextField playOne_2;
private final JTextField playOne_3;
private final JTextField playOne_4;
private final JTextField playOne_5;
private final JTextField playOne_6;
private final JTextField playTwoCount;
private final JTextField playTwo_1;
private final JTextField playTwo_2;
private final JTextField playTwo_3;
private final JTextField playTwo_4;
private final JTextField playTwo_5;
private final JTextField playTwo_6;

boolean[] playOneRolls = new boolean[6];
boolean[] playTwoRolls = new boolean[6];
private int clicker1 = 0, clicker2 = 0;

private Container SixNumbersPanel;


public SixNumbersPanel() {



//**********************************************************************//
//                                                                      //
//           These are the strings being created and given              //
//                 appropriate texts for the object.                    //
//           Each of these objects have been created in order           //
//              to organise them better later in this code              //
//                                                                      // 
//**********************************************************************//


    header = new JLabel ("Six Numbers Game");


    playOne_1 = new JTextField("");

    playOne_2 = new JTextField("");
    // add (playOne_2);

    playOne_3 = new JTextField("");
    // add (playOne_3);

    playOne_4 = new JTextField("");
    // add (playOne_4);

    playOne_5 = new JTextField("");
   //  add (playOne_5);

    playOne_6 = new JTextField("");
   //  add (playOne_6);

    ScrollPane = new JScrollPane();
   //  add (ScrollPane);

    GameArea = new JTextArea("");
   //  add (GameArea);

    playTwo_1 = new JTextField("");
    // add (playTwo_1);

    playTwo_2 = new JTextField("");
    // add (playTwo_2);

    playTwo_3 = new JTextField("");
   //  add (playTwo_3);

    playTwo_4 = new JTextField("");
    // add (playTwo_4);

    playTwo_5 = new JTextField("");
   //  add (playTwo_5);

    playTwo_6 = new JTextField("");
    // add (playTwo_6);

    PlayOneRoll = new JButton("Roll");
   //  add (PlayOneRoll);

    PlayOneRollNum = new JTextField("");
    // add (PlayOneRollNum);

    PlayTwoRollNum = new JTextField("");
   //  add (PlayTwoRollNum);

    PlayTwoRoll = new JButton("Roll");
   //  add (PlayTwoRoll);             

    playOneCount = new JTextField("");
   //  add (playOneCount);

    lblPlayOne = new JLabel("Roll Count");
   //  add (lblPlayOne);

    lblPlayTwo = new JLabel("Roll Count");
   //  add (lblPlayTwo);        

    playTwoCount = new JTextField("");
   //  add (playTwoCount);        

    bNew = new JButton("New Game");
   //  add (bNew);

    bEdit = new JButton("Edit Name");
    // add (bEdit);

   // bRule = new JButton("Rules");
   //  add (bRule);

    bExit = new JButton("Exit");
  //   add (bExit);

  JButton bYes = new JButton ("Yes");
   JButton bNo = new JButton ("No");
   JLabel lblQuestion = new JLabel ("Are you sure you want to exit?");


//**********************************************************************//
//                                                                      //
//               Let's customise the object attributes                  //
//                                                                      // 
//**********************************************************************//
    Font fontType = new Font("Tahoma", 1, 12);        
    Color cRed = new Color (255,0,0);
    Color cBlue = new Color (0,0,255);
    Dimension d = new Dimension (30, 30);
    Dimension buttonD = new Dimension (100, 25);


    header.setFont(new java.awt.Font("Tahoma", 1, 14));

    //player One
    playOne_1.setEditable(false);
    playOne_1.setFont (fontType);
    playOne_1.setBorder(createLineBorder(cRed));
    playOne_1.setPreferredSize (d);
    playOne_1.setHorizontalAlignment(JTextField.CENTER);

    playOne_2.setEditable(false);
    playOne_2.setFont (fontType);
    playOne_2.setBorder(createLineBorder(cRed));
    playOne_2.setPreferredSize (d);
    playOne_2.setHorizontalAlignment(JTextField.CENTER);        

    playOne_3.setEditable(false);
    playOne_3.setFont (fontType);
    playOne_3.setBorder(createLineBorder(cRed));
    playOne_3.setPreferredSize (d);
    playOne_3.setHorizontalAlignment(JTextField.CENTER);

    playOne_4.setEditable(false);
    playOne_4.setFont (fontType);
    playOne_4.setBorder(createLineBorder(cRed));
    playOne_4.setPreferredSize (d);
    playOne_4.setHorizontalAlignment(JTextField.CENTER);

    playOne_5.setEditable(false);
    playOne_5.setFont (fontType);
    playOne_5.setBorder(createLineBorder(cRed));
    playOne_5.setPreferredSize (d);
    playOne_5.setHorizontalAlignment(JTextField.CENTER);

    playOne_6.setEditable(false);
    playOne_6.setFont (fontType);
    playOne_6.setBorder(createLineBorder(cRed));
    playOne_6.setPreferredSize (d);
    playOne_6.setHorizontalAlignment(JTextField.CENTER);

    //player two
    playTwo_1.setEditable(false);
    playTwo_1.setFont (fontType);
    playTwo_1.setBorder(createLineBorder(cBlue));
    playTwo_1.setPreferredSize (d);
    playTwo_1.setHorizontalAlignment(JTextField.CENTER);

    playTwo_2.setEditable(false);
    playTwo_2.setFont (fontType);
    playTwo_2.setBorder(createLineBorder(cBlue));
    playTwo_2.setPreferredSize (d);
    playTwo_2.setHorizontalAlignment(JTextField.CENTER);

    playTwo_3.setEditable(false);
    playTwo_3.setFont (fontType);
    playTwo_3.setBorder(createLineBorder(cBlue));
    playTwo_3.setPreferredSize (d);
    playTwo_3.setHorizontalAlignment(JTextField.CENTER);

    playTwo_4.setEditable(false);
    playTwo_4.setFont (fontType);
    playTwo_4.setBorder(createLineBorder(cBlue));
    playTwo_4.setPreferredSize (d);
    playTwo_4.setHorizontalAlignment(JTextField.CENTER);

    playTwo_5.setEditable(false);
    playTwo_5.setFont (fontType);
    playTwo_5.setBorder(createLineBorder(cBlue));
    playTwo_5.setPreferredSize (d);
    playTwo_5.setHorizontalAlignment(JTextField.CENTER);

    playTwo_6.setEditable(false);
    playTwo_6.setFont (fontType);
    playTwo_6.setBorder(createLineBorder(cBlue));
    playTwo_6.setPreferredSize (d);
    playTwo_6.setHorizontalAlignment(JTextField.CENTER);

//      Roll count boxes
    PlayOneRollNum.setEditable(false);
    PlayOneRollNum.setFont (fontType);
    PlayOneRollNum.setBorder(createLineBorder(cRed));
    PlayOneRollNum.setPreferredSize (d);
    PlayOneRollNum.setHorizontalAlignment(JTextField.CENTER);

    PlayTwoRollNum.setEditable(false);
    PlayTwoRollNum.setFont (fontType);
    PlayTwoRollNum.setBorder(createLineBorder(cBlue));
    PlayTwoRollNum.setPreferredSize (d);
    PlayTwoRollNum.setHorizontalAlignment(JTextField.CENTER);

//     Display area for the game
    GameArea.setEditable (false);
    GameArea.setBackground (new Color(240,240,240));
    GameArea.setColumns(20);
    GameArea.setRows(5);
    GameArea.setBorder(createEtchedBorder(Color.lightGray, Color.white));
    ScrollPane.setViewportView(GameArea);

//     Buttons
    PlayOneRoll.setPreferredSize(buttonD);
    PlayTwoRoll.setPreferredSize(buttonD);
    bExit.setPreferredSize(buttonD);
    bNew.setPreferredSize(buttonD);
    bEdit.setPreferredSize(buttonD);

// Roll Count labels
    lblPlayOne.setForeground(cRed);
    lblPlayTwo.setForeground (cBlue);

// Roll Count Text Fields
    playOneCount.setEditable (false);
    playOneCount.setBorder(createLineBorder(cRed));
    playOneCount.setPreferredSize (d);

    playTwoCount.setEditable (false);
    playTwoCount.setBorder(createLineBorder(cBlue));
    playTwoCount.setPreferredSize (d);

//Organise the objects
    setTitle ("Six Numbers Game");
    setResizable(false);

    JPanel Toppanel = new JPanel();         

    JPanel GamePanelOne = new JPanel();   
        JPanel GamePanelOne1 = new JPanel();
        JPanel GamePanelOne2 = new JPanel();
        JPanel GamePanelOne3 = new JPanel();

    JPanel GamePanelTwo = new JPanel();
        JPanel GamePanelTwo1 = new JPanel();
        JPanel GamePanelTwo2 = new JPanel();
        JPanel GamePanelTwo3 = new JPanel();

    JPanel GamePanel = new JPanel();

    JPanel Rolling = new JPanel();        
    JPanel Counting = new JPanel();
    JPanel Btn = new JPanel();
    JPanel Game = new JPanel();


    Toppanel.add(header);

    Rolling.add (PlayOneRoll);
    Rolling.add(PlayOneRollNum);
    Rolling.add(Box.createHorizontalStrut(10));
    Rolling.add(PlayTwoRollNum);
    Rolling.add(PlayTwoRoll);

    Counting.add(playOneCount);
    Counting.add(lblPlayOne);
    Counting.add(Box.createHorizontalStrut(10));
    Counting.add(lblPlayTwo);
    Counting.add(playTwoCount);

    GamePanelOne1.add(playOne_1);

    GamePanelOne1.add(playOne_2);


    GamePanelOne.add(GamePanelOne1);
    GamePanelOne.add(GamePanelOne2);
    GamePanelOne.add(GamePanelOne3);


    GamePanel.add(ScrollPane);
    GamePanel.add(GameArea);

    GamePanelTwo1.add(playTwo_1);
    GamePanelTwo1.add(playTwo_2);
    GamePanelOne2.add(playOne_3);
    GamePanelOne2.add(playOne_4);
    GamePanelOne3.add(playOne_5);
    GamePanelOne3.add(playOne_6);
    GamePanelTwo2.add(playTwo_3);
    GamePanelTwo2.add(playTwo_4);
    GamePanelTwo3.add(playTwo_5);
    GamePanelTwo3.add(playTwo_6);


    GamePanelTwo.add(GamePanelTwo1);
    GamePanelTwo.add(GamePanelTwo2);
    GamePanelTwo.add(GamePanelTwo3);

    Btn.add(bNew);
    Btn.add(bExit);


   Game.add(Toppanel);
   Game.add(GamePanelOne);
   Game.add(GamePanel);
   Game.add(GamePanelTwo);
   Game.add(Rolling);
   Game.add(Counting);
   Game.add(Btn);

   add(Game);      

   JPanel OptionPanel = new JPanel();

   OptionPanel.add(lblQuestion);
   OptionPanel.add(bYes);
   OptionPanel.add(bNo);




   //Call instance of handler class
    theHandler handler = new theHandler();
    //Add an action listened to required items and pass handler as executable code
    PlayOneRoll.addActionListener(handler);
    PlayTwoRoll.addActionListener(handler);
    bNew.addActionListener(handler);
    bExit.addActionListener(handler);
    bYes.addActionListener(handler);
    bNo.addActionListener(handler);


   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} 
public void SixNumberGUI() {
    //Setting up the JFrame

    SixNumbersPanel myPanel = new SixNumbersPanel( ) ;
    myPanel.setSize(350, 500);
    myPanel.setVisible(true);

}


 private class theHandler implements ActionListener {
    //Code to be executed
    public void actionPerformed(ActionEvent event) {
        Die roll = new Die();
        int currentRoll = 0;

        Color cRed = new Color (255,0,0);
        Color cBlue = new Color (0,0,255);

        if(event.getSource() == PlayOneRoll) {
         clicker1++;
            playOneCount.setText(Integer.toString(clicker1));
            currentRoll = roll.rollDice();
            PlayOneRoll.setEnabled(false);
            PlayTwoRoll.setEnabled(true);
            PlayOneRollNum.setText(Integer.toString(currentRoll));
            GameArea.setText("Player Two - Your Turn");
                GameArea.setForeground(cBlue);

            switch(currentRoll) {
                case 1: playOne_1.setText(currentRoll + "");
                        playOneRolls[0] = true;
                        break;
                case 2: playOne_2.setText(Integer.toString(currentRoll));
                        playOneRolls[1] = true;
                        break;
                case 3: playOne_3.setText(Integer.toString(currentRoll));
                        playOneRolls[2] = true;
                        break;
                case 4: playOne_4.setText(Integer.toString(currentRoll));
                        playOneRolls[3] = true;
                        break;
                case 5: playOne_5.setText(Integer.toString(currentRoll));
                        playOneRolls[4] = true;
                        break;
                case 6: playOne_6.setText(Integer.toString(currentRoll));
                        playOneRolls[5] = true;
                        break;
            }
            //end the game loop that I want in Player.java
            ////////////////////////////////////////////////
            if(playOneRolls[0] == true && playOneRolls[1] == true && playOneRolls[2] == true&& playOneRolls[3] == true && playOneRolls[4] == true && playOneRolls[5] == true){
                GameArea.setText("PLAYER ONE WINS!");
                GameArea.setForeground(cRed);
            JOptionPane.showMessageDialog(null, "Player one wins!" + '\n' + "It took " + clicker1 + " clicks to beat the game!");

        }

        }
        else if(event.getSource() == PlayTwoRoll) {
         clicker2++;
            playTwoCount.setText(Integer.toString(clicker1));
            currentRoll = roll.rollDice();
            PlayTwoRoll.setEnabled(false);
            PlayOneRoll.setEnabled(true);
            PlayTwoRollNum.setText(Integer.toString(currentRoll));
            GameArea.setText("Player One - Your Turn");
                GameArea.setForeground(cRed);


            switch(currentRoll) {
                case 1: playTwo_1.setText(Integer.toString(currentRoll));
                        playTwoRolls[0] = true;
                        break;
                case 2: playTwo_2.setText(Integer.toString(currentRoll));
                        playTwoRolls[1] = true;
                        break;
                case 3: playTwo_3.setText(Integer.toString(currentRoll));
                        playTwoRolls[2] = true;
                        break;
                case 4: playTwo_4.setText(Integer.toString(currentRoll));
                        playTwoRolls[3] = true;
                        break;
                case 5: playTwo_5.setText(Integer.toString(currentRoll));
                        playTwoRolls[4] = true;
                        break;
                case 6: playTwo_6.setText(Integer.toString(currentRoll));
                        playTwoRolls[5] = true;
                        break;
            }
            //end the game loop that I want in Player.java
            ////////////////////////////////////////////////
            if(playTwoRolls[0] == true && playTwoRolls[1] == true && playTwoRolls[2] == true&& playTwoRolls[3] == true && playTwoRolls[4] == true && playTwoRolls[5] == true) {
                GameArea.setText("PLAYER TWO WINS!");
                GameArea.setForeground(cBlue);
            JOptionPane.showMessageDialog(null, "Player two wins!" + '\n' + "It took " + clicker2 + " clicks to beat the game!");

        }

        }
        else if(event.getSource() == bNew) {
            playOne_1.setText(null);
            playOne_2.setText(null);
            playOne_3.setText(null);
            playOne_4.setText(null);
            playOne_5.setText(null);
            playOne_6.setText(null);

            playTwo_1.setText(null);
            playTwo_2.setText(null);
            playTwo_3.setText(null);
            playTwo_4.setText(null);
            playTwo_5.setText(null);
            playTwo_6.setText(null);

            GameArea.setText("Current roll: ");

            PlayOneRoll.setEnabled(true);
            PlayTwoRoll.setEnabled(true);
        }

        else if (event.getSource() == bExit){


              System.exit(0); }

              }




    }
}

This code works with one issue, it won't restart the game when [New Game] button is clicked.

My other issue is I have tried for many house to split the logic within the [Roll] buttons into a separate class called "Player".

We are out of options and asking for any assistance to help us with our issue.

Thank you.




Return class type and have class type as parameter

I have function

private Class readObject (ObjectInput in, Class objectclass){
    try {
        Object o = in.readObject ();

        if (o instanceof objectclass) {
            return (objectclass)o;
        }

    } catch (Exception e) {

} 

In my class I am calling this function with:

ObjectInput in = (..)
Type1 type = readObject (in, Type1.class);
(do something with type)
while(true){
    Type2 type2 = readObject (in, Type2.class);
    (do something with type2)

Basically, readObject is supposed to return the class that I have as a parameter, if that is the correct type of Object o. You can think of this as, I have Type1, Type2 and Type3 objects that I am reading, but if I come across Type3 I do nothing.

This code that I have written does not work properly. For example,

Type1 type = readObject (in, Type1.class);

gives me the warning "cannot convert from Class to Type1".




Inheritance-Need Guidance

I am a novice programmer, so sorry if this is a really stupid question. I need to pass a value from one class to another. If I am not mistaken, this would be done through inheritance, but there seems to be something I am missing. Any help would be welcome. I am writing in C# within Unity.

    public class baseStats{
    private int STAMINA;

    public static int Stamina{
       get{return STAMINA;}
       set{STAMINA = value;}   
   }
}

The above is a sample of my parent class. Here is my child class:

    public class baseProfile:baseStats{
    private static int PROFILE_STAMINA;

    private static void profileStats(){
           Stamina = 10;
           PROFILE_STAMINA = Stamina;
    }
    public static int profileStamina(){
        get{return PROFILE_STAMINA;}
    }
}

In a third script I created for the purposes of debugging, I wrote:

 public class debug:MonoDevelop{
      void Start(){
           Debug.Log(profileStamina.ToString());
   }
}

It says I need an object reference for the non-static field, method, or property 'Profile.Profile.Stamina'. Easy fix: make everything static (I believe I need to make constructors or something like that to avoid having to use static all the time. A little help with that would be great!). Once error-free, I ran the program and the console outputs 0 for my profile stamina. I am really confused as to what is going on. Sorry this is such a long post, and thanks for any help I get.




how to use GUI class in another pakage with my program [duplicate]

This question already has an answer here:

so, ive already made my program, i have several classes, but i have to create a gui for my program and the gui has to be a class in a separate package, how do i assign the buttons and other components to their methods in my other package that contains my program.

like lets say i have:

package-a

{

CLASS-A

CLASS-B

CLASS-C

}

and

package-b

{

CLASS-GUI

}

how can i use methods in classes A, B or C in my GUI? I'm very confused, please help by explaining how i can import, i could not find a good example. also, I'm trying to create buttons and text boxes in my GUI, and i don't have a clue how i can connect a method from a separate class in another package to my GUI.




Selenium Webdriver C# Pages with Similar Elements

I have 4 pages with very similar elements and functionalities. However, the elements all have different Ids depending on which page you're on. Currently, I have them constructed as follows (example Class A & Class B). I'd like to refactor this since all of the methods are the same between the 2 classes, but I don't know how to do it since the elements have different Ids (I'm using Page Factory, but I'm open to not using it as well).

Any insight is greatly appreciated!

public class A : BaseClass
{
    [FindsBy(How = How.Id, Using = "ALoginId"]
    public IWebElement Login {get; set;}

    [FindsBy(How = How.Id, Using = "APassword"]
    public IWebElement Password {get; set;}

    [FindsBy(How = How.Id, Using = "ALoginBtn"]
    public IWebElement LoginBtn {get; set;}

    public void Login()
    {
        Login.SendKeys("username");
        Password.SendKeys("password");
        LoginBtn.Click();
    }
}

public class B : BaseClass
{
    [FindsBy(How = How.Id, Using = "BLoginId"]
    public IWebElement Login {get; set;}

    [FindsBy(How = How.Id, Using = "BPassword"]
    public IWebElement Password {get; set;}

    [FindsBy(How = How.Id, Using = "BLoginBtn"]
    public IWebElement LoginBtn {get; set;}

    public void Login()
    {
        Login.SendKeys("username");
        Password.SendKeys("password");
        LoginBtn.Click();
    }
}




Overwrite several methods of a class with a loop

I would like to know if there is an easy way to do some identical edits on several methods of a class. An example :

class Dog():
    def __init__(self):
        self.name = 'abc'
        self.age = 1

    def setName(self, newValue):
        self.name = newValue

    def setAge(self, newValue):
        self.age = newValue

class TalkingDog(Dog):

    def __init__(self):
        super().__init__()
        # The end is in pseudo code : 
        for method in TalkingDog.allMethods :
            method = method + 'print('I have been edited !')'

I know that I can also overwrite each method but in a situation with tens of methods, that will be a little boring...

So I tried this :

class TalkingDog(Dog):

    def __init__(self):
        super().__init__()
        for method in self.__dir__():
            if method.startswith('set'):
                oldMethod = getattr(self, method)
                def _newMethod(newValue):
                    oldMethod(newValue)
                    print('I have been edited !')
                setattr(self, method, _newMethod)


a = TalkingDog()
print(a.setName) >>> <function TalkingDog.__init__.<locals>._newMethod at 0x0000000002C350D0>

That almost works but setName is not anymore a method. It's an attribute which contains a function. I completely understand why but I'm trying to get a cleaner result. With that result, I risk of having problems later. For example I can't use the library pickle with that object (got the error _pickle.PicklingError: Can't pickle <function TalkingDog.__init__.<locals>._newMethod at 0x00000000003DCBF8>: attribute lookup _newMethod on __main__ failed).




How to use object that created locally in a function without copying it in memory?

For example I have a class that call a function in its consturctor that returns local object. I'm trying to use rvalue references to get access to this object to avoid expensive move of it in memory.

   class MyClass
    {
        BigObject&& C;
        MyClass() : C(f())
        {
        };
    };
   BigObject f()
   {
       return BigObject();
   }

But compiller tells me that reference member is initialized to a temporary that doesn't persist after the construction exits.

I don't get it. I understand that local objects, created in a scope of a function, exists only in a scope of function. Reaching the end of the scope - destructors of local objects are called. And here I initialize rvalue reference with local object , and I have access to it, while I'm in the body of constuctor.

Can someone explain, what is going on here? And is there a way to return a local object and use it as any ligetable class member, without moving it in memory?




How to set the value of a slot(S4) using <- in R

I have an object ob of class markovchain.

> ob
An object of class "markovchain"
Slot "states":
[1] "a" "b" "c" "d" "e"

Slot "byrow":
[1] TRUE

Slot "transitionMatrix":
   a  b  c  d  e
a  1  2  3  4  5
b  6  7  8  9 10
c 11 12 13 14 15
d 16 17 18 19 20
e 21 22 23 24 25

Slot "name":
[1] "deepak"

My task is to create a method to get and set the data of name slot.

Below is the method to get the data in the name slot.

> setGeneric("name", function(object) standardGeneric("name"))
[1] "name"
> setMethod("name", "markovchain", 
+           function(object) {
+             out <- object@name
+             return(out)
+           }
+ )
[1] "name"

It is working properly. See

> name(ob)
[1] "deepak"

Now my task is to set the data in the name slot. I have tried this

setGeneric("name<-", function(object, ob_name) standardGeneric("name<-"))
setMethod("name<-", "markovchain", 
          function(object, ob_name) {
            object@name <- ob_name
            object
          }
)

While setting the name I am getting an error.

> name(ob) <- "apple"
Error in `name<-`(`*tmp*`, value = "apple") : 
  unused argument (value = "apple")

I am not getting what I am doing wrong? Any help.




how to use a nested class of a template base class in a drive class?

I want to have access to private attributes of base class and make objects from the nested class both in the drive class.

The nested class is defined public in the base class and it's constructor is private. however, it is defined friend with the base class. So, why do I get these errors for: "List :: Iterator it(_last);":

"[Error] need 'typename' before 'List::Iterator' because 'List' is a dependent scope"

and also this:

"[Error] expected ';' before 'it' "

here is my code:

template<typename T>
class List {
private:
    class Node {
    public:
        Node(T d, Node *n = NULL, Node *p = NULL) 
            : data(d), next(n), prev(p) {}

        T data;
        Node *next;
        Node *prev;
    };

public:
    class Iterator {
    public:
        T next_element() { 
            T to_be_returned = current->data;
            current = current->next;
            return to_be_returned;
        }
        bool has_more_elements() {
            return current != NULL;
        }
    private:
        Node *current;

        Iterator(Node* n) { current = n; }
        friend class List;
    };

public:
    List();
    ~List();
    Iterator get_iterator() {
        return Iterator(_head);
    }
private:
    Node* _head;
    Node* _last;
};

template<typename T>
List<T>::List() {
    _head = NULL;
    _last = NULL;
}

template<typename T>
class MyList: public List<T> {
    public:
        void remove_last();
};

template<typename T>
void MyList<T> :: remove_last() {
     List<T> :: Iterator it(_last); 

}




Singleton to factory in PHP

There are many topics about this already, but I have not a clear picture of why factory patterns are better practice than Singleton.

An example

class MySingleton {
 public static function numberByWhat( $number ) {
   return $number + 100;
 }
 public static function someCharacters( $string ) {
   return $string + 'abc';
 }
}

class MyOtherSingleton {
  public static function getImage( $url ) {
    return '<img src="' . $url . MySingleton::numberByWhat( $50 ) . '">';
  }
  public static function getTextById( $id ) {
    if( $id == 3 ) {
      return 'this is my text' . MySingleton::someCharacters( 'Yeah' );
    }
  }
}

function run() {
  echo MyOtherSingleton::getImage( 'http://ift.tt/1pqWBWd' );
  echo MyOtherSingleton::getTextById( 3 );
}

run();

So there we have 2 classes and a function. When I run() I start a function in the second class. Inside the functions in the second class there are calls to the first class.

  • How would this look like as a factory pattern?
  • Why is it better as a factory pattern?



dimanche 29 mai 2016

Python Tkinter - How can you use a value from one function to another?

I am learning Python and Tkinter on my own and I have some questions regarding this code that I am writing. I am trying to get the program to execute two functions that are part of a class. So when I try to execute the below code tkinter executes the first function but does not execute function 2 and I don't understand why. Can someone please help me with this. Thank you.

from tkinter import *
myapp=Tk()
myapp.geometry('1100x700+100+50')
myapp.title('List Generator')

input1=IntVar()
input2=IntVar()

class Myclass:
    def __init__(self):
        text1=input1.get()
        text2=input2.get()
        ex1=float(text1)
        ex2=float(text2)
        totbtu=float(ex1*ex2)
        realbtu=totbtu+(totbtu*0.15)
        j= float(totbtu + 100)
        Label(myapp, text=totbtu).place(x=600,y=20)
        Label(myapp, text=realbtu).place(x=600,y=60)
        Label(myapp, text=j).place(x=600,y=100)

    def function2(self):
        h=j+33
        Label(myapp, text=h).place(x=600,y=140)

label1 = Label(myapp, text='Enter Area').place(x=10,y=10)
area_entry=Entry(myapp,textvariable=input1 ).place(x=140,y=10)
label11 = Label(myapp,text='SQ FT',).place(x=270,y=10)

label2 = Label(myapp, text='Enter Load').place(x=10,y=35)
area_entry=Entry(myapp,textvariable=input2 ).place(x=140,y=35)
label22 = Label(myapp,text="BTU's/SQ FT",).place(x=270,y=35)

button1 = Button(myapp, text = 'Generate',padx=5,pady=5,command=Myclass).place(x=10,y=70)

myapp.mainloop()




Access static variable from another class in React-Native app?

in my react-native app I currently have a User class in which I define a current user as below:

class User {
    static currentUser = null;

    //other relevant code here

    static getCurrentUser() {
        return currentUser;
    }
}

export default User;

In a different class, I am trying to access the set value of this currentUser. I cannot figure out how to correctly call this function; I am getting the error User.getCurrentUser is not a function. Should I be calling this function in a different way?

var User = require('./User');

getInitialState: function() {

    var user = User.getCurrentUser();

    return {
        user: user
    };


},




How to set Hashmap value using model class

I want to set Hashmap value using data from database and set it in model class, it doesn't work yet and shows empty data. Here is my code, get Data from database

private ArrayList<Kategori> categories;
private ArrayList<ChatRoom> chatroom_list;
private HashMap<Integer, ArrayList<ChatRoom>> chatrooms;

void getDataList(){
    categories = new ArrayList<>();
    chatrooms = new HashMap<>();
    chatroom_list = new ArrayList<>();
    try{
        categories.clear();
        cursor = db.rawQuery("SELECT * FROM kategori ORDER BY id ASC", null);
        //cursor2 = db.rawQuery("SELECT * FROM chatroom ORDER BY id ASC LIMIT ", null);
        Kategori kategori;
        while (cursor.moveToNext()){
            kategori = new Kategori();
            kategori.setId(cursor.getInt(cursor.getColumnIndex("id")));
            kategori.setNama(cursor.getString(cursor.getColumnIndex("nama")));
            categories.add(kategori);
        }
        listAdapter.notifyDataSetChanged();
    }catch(Exception e){
        e.printStackTrace();
    }
    try{
        chatroom_list.clear();
        chatrooms.clear();
        ChatRoom chatRoom;
        for (int i=0;i<categories.size();i++){
            cursor2 = db.rawQuery("SELECT * FROM chatroom WHERE status = '0' ORDER BY id ASC", null);
            while (cursor2.moveToNext()){
                chatRoom = new ChatRoom();
                chatRoom.setId(cursor2.getInt(cursor2.getColumnIndex("id")));
                chatRoom.setNama(cursor2.getString(cursor.getColumnIndex("nama")));
                chatRoom.setDosen(cursor2.getString(cursor2.getColumnIndex("dosen")));
                chatRoom.setInfo(cursor2.getString(cursor2.getColumnIndex("info")));
                chatRoom.setId_kategori(cursor2.getInt(cursor2.getColumnIndex("id_kategori")));
                if(categories.get(i).getId()==chatRoom.getId_kategori())
                    chatroom_list.add(chatRoom);
            }
            chatrooms.put(categories.get(i).getId(), chatroom_list);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

when I check it, Hashmap just shows empty data, Thank you!




Using a constructor outside of the defining file [duplicate]

This question already has an answer here:

I have the following file as class.hpp:

template <class T>
class MyClass{
    public:
    int n;
    MyClass(int N);
};

The following file as class.cpp:

#include "class.hpp"
template <class T>
MyClass<T>::MyClass(int N){
n = N;
}

And the following as test.cpp:

#include "class.hpp"
int main()
{
    MyClass<int> c(14);
}

When I try to link the files, it complains of an undefined reference to MyClass::MyClass(int). Where am I going wrong?




methods outside of constructor in c#

I am working on some study materials and came across some code I don't understand.

class Program
{
    static void Main(string[] args)
    {
        var warrior = new Samurai();
        warrior.Attack("the evildoers");
        Console.ReadLine();
    }

    class Sword
    {
        public void Hit(string target)
        {
            Console.WriteLine("Chopped {0} clean in half", target);
        }
    }

    class Samurai
    {
        readonly Sword sword;
        public Samurai()
        {
            this.sword = new Sword();
        }

        public void Attack(string target)
        {
            this.sword.Hit(target);
        }
    }
}

As far as I am concerned, when I instantiated Samurai, I run the method public Samurai(). How is the method warrior.Attack called if the Attack method was outside of the constructor public Samurai()?




redefinition in h files

i solved couple of my redefinition problems but still have one:

Error 2 error LNK2005: "class ConsoleCommandHandler commandHandler" (?commandHandler@@3VConsoleCommandHandler@@A) already defined in IRC.obj C:\Users\Łukasz\Desktop\IRCClient-master\Magic.obj

Here are the .h files

magic.h

#ifndef Magic_h
#define Magic_h
#include <iostream>
#include <signal.h>
#include <cstdlib>
#include <map>
#include <algorithm>
#include "src\Thread.h"
#include "src\IRCClient.h"



void signalHandler(int signal);

class ConsoleCommandHandler
{
public:
    bool AddCommand(std::string name, int argCount, void(*handler)(std::string /*params*/, IRCClient* /*client*/));
    void ParseCommand(std::string command, IRCClient* client);
private:
    struct CommandEntry
    {
        int argCount;
        void(*handler)(std::string /*arguments*/, IRCClient* /*client*/);
    };

    std::map<std::string, CommandEntry> _commands;
};

ConsoleCommandHandler commandHandler;

void msgCommand(std::string arguments, IRCClient* client);
void joinCommand(std::string channel, IRCClient* client);
void partCommand(std::string channel, IRCClient* client);


void ctcpCommand(std::string arguments, IRCClient* client);

ThreadReturn inputThread(void* client);

#endif

magic.cpp

#include "Magic.h"



void signalHandler(int signal)
{
    volatile bool running;
    running = false;
};


bool ConsoleCommandHandler::AddCommand(std::string name, int argCount, void(*handler)(std::string /*params*/, IRCClient* /*client*/))
    {
        CommandEntry entry;
        entry.argCount = argCount;
        entry.handler = handler;
        std::transform(name.begin(), name.end(), name.begin(), towlower);
        _commands.insert(std::pair<std::string, CommandEntry>(name, entry));
        return true;
    }

void ConsoleCommandHandler::ParseCommand(std::string command, IRCClient* client)
    {
        if (_commands.empty())
        {
            std::cout << "No commands available." << std::endl;
            return;
        }

        if (command[0] == '/')
            command = command.substr(1); // Remove the slash

        std::string name = command.substr(0, command.find(" "));
        std::string args = command.substr(command.find(" ") + 1);
        int argCount = std::count(args.begin(), args.end(), ' ');

        std::transform(name.begin(), name.end(), name.begin(), towlower);

        std::map<std::string, CommandEntry>::const_iterator itr = _commands.find(name);
        if (itr == _commands.end())
        {
            std::cout << "Command not found." << std::endl;
            return;
        }

        if (++argCount < itr->second.argCount)
        {
            std::cout << "Insuficient arguments." << std::endl;
            return;
        }

        (*(itr->second.handler))(args, client);
    }

    struct CommandEntry
    {
        int argCount;
        void(*handler)(std::string /*arguments*/, IRCClient* /*client*/);
    };

    std::map<std::string, CommandEntry> _commands;


void msgCommand(std::string arguments, IRCClient* client)
{
    std::string to = arguments.substr(0, arguments.find(" "));
    std::string text = arguments.substr(arguments.find(" ") + 1);

    std::cout << "To " + to + ": " + text << std::endl;
    client->SendIRC("PRIVMSG " + to + " :" + text);
};

void joinCommand(std::string channel, IRCClient* client)
{
    if (channel[0] != '#')
        channel = "#" + channel;

    client->SendIRC("JOIN " + channel);
}

void partCommand(std::string channel, IRCClient* client)
{
    if (channel[0] != '#')
        channel = "#" + channel;

    client->SendIRC("PART " + channel);
}

void ctcpCommand(std::string arguments, IRCClient* client)
{
    std::string to = arguments.substr(0, arguments.find(" "));
    std::string text = arguments.substr(arguments.find(" ") + 1);

    std::transform(text.begin(), text.end(), text.begin(), towupper);

    client->SendIRC("PRIVMSG " + to + " :\001" + text + "\001");
}

ThreadReturn inputThread(void* client)
{
    std::string command;

    commandHandler.AddCommand("msg", 2, &msgCommand);
    commandHandler.AddCommand("join", 1, &joinCommand);
    commandHandler.AddCommand("part", 1, &partCommand);
    commandHandler.AddCommand("ctcp", 2, &ctcpCommand);

    while (true)
    {
        getline(std::cin, command);
        if (command == "")
            continue;

        if (command[0] == '/')
            commandHandler.ParseCommand(command, (IRCClient*)client);
        else
            ((IRCClient*)client)->SendIRC(command);

        if (command == "quit")
            break;
    }

#ifdef _WIN32
    _endthread();
#else
    pthread_exit(NULL);
#endif
}

irc.h

#pragma once
#include <iostream>
#include <signal.h>
#include <cstdlib>
#include <map>
#include <algorithm>
#include "Magic.h"
#include <msclr/marshal.h>
#include <msclr/marshal_cppstd.h>
#using <mscorlib.dll>


namespace IRCclient {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
    using namespace System::IO;
    using namespace System::Runtime::InteropServices;
    using namespace msclr::interop;


    /// <summary>
    /// Summary for MyForm
    /// </summary>


    private: System::Void connect_button_Click(System::Object^  sender, System::EventArgs^  e)
    {
        if ((server_box->Text == "") || (port_box->Text == "") || (username_box->Text == "") || (channel_box->Text == ""))
        {
            MessageBox::Show("Wypełnij wszystkie pola", "Puste pola", MessageBoxButtons::OK, MessageBoxIcon::Warning);
            server_box->Focus();
        }
        else
        {
            String^ host_string = server_box->Text;
            char* host = (char*)(void*)Marshal::StringToHGlobalAnsi(host_string);
            String^ port_string = port_box->Text;
            int port;
            //String^ port_string = port.ToString();
            String^ nick_string = username_box->Text;
            std::string nick(marshal_as<std::string>(nick_string));
            std::string user = "test";


            IRCClient client;
            volatile bool running;
            Thread thread;
            thread.Start(&inputThread, &client);

            if (client.InitSocket())
            {

                content_box->Text = "Socket initialized. Connecting..." + "\r\n";

                if (client.Connect(host, port))
                {
                    content_box->Text = "Connected. Loggin in..." + "\r\n";                 

                    if (client.Login(nick, user))
                    {
                        content_box->Text = "Logged." + "\r\n";                     

                        running = true;
                        signal(SIGINT, signalHandler);

                        while (client.Connected() && running)
                            client.ReceiveData();
                    }

                    if (client.Connected())
                        client.Disconnect();

                    content_box->Text = "Disconnected." + "\r\n";
                }
            }
        }
    };
    };
};




Right-click context menu Java class?

I am writing my own NetBeans IDE 8.1 plugin in Java and I am in need for a right-click context menu which has the following features:

  • A copy button (which is greyed out when no text is selected)
  • A paste button
  • A custom remove button which will do something in my plugin

Is there some sort of standard Java class for a right-click context menu in JDK8? Because I can't find anything and don't know how exactly to completely start from scratch, well, I could, but I would like to know if there is already at least some sort of template.




Shouldn't every .swift file be a class?

I have some experience in ObjC and I just started learning Swift. In Objc everything is a class through @interface in .h and @implementation of .m, or in other Swift classes that I have seen everything is usually in some form of

class MyCustomClassInhertingfrom: SomeFoundationClass { //methods & properties}

Yet here in some class named pancakeHouse.Swift there is no mention of the keyword class WHY? Isn't this a Model Class? Doesn't this break the MVC design pattern? Is this happening because of new powerful features of enums& structs vs class in Swift?_____I am confused obviously!

import UIKit
import CoreLocation

enum PriceGuide : Int {
  case Unknown = 0
  case Low = 1
  case Medium = 2
  case High = 3
}

extension PriceGuide : CustomStringConvertible {
  var description : String {
    switch self {
    case .Unknown:
      return "?"
    case .Low:
      return "$"
    case .Medium:
      return "$$"
    case .High:
      return "$$$"
    }
  }
}

enum PancakeRating {
  case Unknown
  case Rating(Int)
}

extension PancakeRating {
  init?(value: Int) {
    if value > 0 && value <= 5 {
      self = .Rating(value)
    } else {
      self = .Unknown
    }
  }
}

extension PancakeRating {
  var ratingImage : UIImage? {
    guard let baseName = ratingImageName else {
      return nil
    }
    return UIImage(named: baseName)
  }

  var smallRatingImage : UIImage? {
    guard let baseName = ratingImageName else {
      return nil
    }
    return UIImage(named: "\(baseName)_small")
  }

  private var ratingImageName : String? {
    switch self {
    case .Unknown:
      return nil
    case .Rating(let value):
      return "pancake_rate_\(value)"
    }
  }
}



 struct PancakeHouse {
  let name: String
  let photo: UIImage?
  let thumbnail: UIImage?
  let priceGuide: PriceGuide
  let location: CLLocationCoordinate2D?
  let details: String
  let rating: PancakeRating
}

extension PancakeHouse {
   init?(dict: [String : AnyObject]) {
    guard let name = dict["name"] as? String,
      let priceGuideRaw = dict["priceGuide"] as? Int,
      let priceGuide = PriceGuide(rawValue: priceGuideRaw),
      let details = dict["details"] as? String,
      let ratingRaw = dict["rating"] as? Int,
      let rating = PancakeRating(value: ratingRaw) else {
        return nil
    }

    self.name = name
    self.priceGuide = priceGuide
    self.details = details
    self.rating = rating

    if let imageName = dict["imageName"] as? String where !imageName.isEmpty {
      photo = UIImage(named: imageName)
    } else {
      photo = nil
    }

    if let thumbnailName = dict["thumbnailName"] as? String where !thumbnailName.isEmpty {
      thumbnail = UIImage(named: thumbnailName)
    } else {
      thumbnail = nil
    }

    if let latitude = dict["latitude"] as? Double,
      let longitude = dict["longitude"] as? Double {
        location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    } else {
      location = nil
    }
  }
}

extension PancakeHouse {
  static func loadDefaultPancakeHouses() -> [PancakeHouse]? {
    return self.loadPancakeHousesFromPlistNamed("pancake_houses")
  } 

  static func loadPancakeHousesFromPlistNamed(plistName: String) -> [PancakeHouse]? {
    guard let path = NSBundle.mainBundle().pathForResource(plistName, ofType: "plist"),
      let array = NSArray(contentsOfFile: path) as? [[String : AnyObject]] else {
        return nil
    }

    return array.map { PancakeHouse(dict: $0) }
                .filter { $0 != nil }
                .map { $0! }
  }
}

extension PancakeHouse : CustomStringConvertible {
  var description : String {
    return "\(name) :: \(details)"
  }
}

extension PancakeHouse: Equatable {
}

func ==(lhs: PancakeHouse, rhs: PancakeHouse) -> Bool {
  return lhs.name == rhs.name
}

Note: I would like an answer that also includes comparison of the .swift vs .h + .m; don't just consider this as a specific question, consider it as a general question, kindly explain or link the prerequisites detailed needed to understand this question)




How do I create a class with a main method to read information from a text file and to display Information in java

The first programming project involves writing a program that computes the salaries for a collection of employees of different types. This program consists of four classes. The first class is the Employee class, which contains the employee's name and monthly salary, which is specified in whole dollars. It should have three methods:

A constructor that allows the name and monthly salary to be initialized. A method named annualSalary that returns the salary for a whole year. A toString method that returns a string containing the name and monthly salary, appropriately labeled. The Employee class has two subclasses. The first is Salesman. It has an additional instance variable that contains the annual sales in whole dollars for that salesman. It should have the same three methods:

A constructor that allows the name, monthly salary and annual sales to be initialized. An overridden method annualSalary that returns the salary for a whole year. The salary for a salesman consists of the base salary computed from the monthly salary plus a commission. The commission is computed as 2% of that salesman's annual sales. The maximum commission a salesman can earn is $20,000. An overridden toString method that returns a string containing the name, monthly salary and annual sales, appropriately labeled. The second subclass is Executive. It has an additional instance variable that reflects the current stock price. It should have the same three methods:

A constructor that allows the name, monthly salary and stock price to be initialized. An overridden method annualSalary that returns the salary for a whole year. The salary for an executive consists of the base salary computed from the monthly salary plus a bonus. The bonus is $30,000 if the current stock price is greater than $50 and nothing otherwise. An overridden toString method that returns a string containing the name, monthly salary and stock price, appropriately labeled. Finally there should be a fourth class that contains the main method. It should read in employee information from a text file. Each line of the text file will represent the information for one employee for one year. An example of how the text file will look is shown below:

2014 Employee Smith,John 2000 2015 Salesman Jones,Bill 3000 100000 2014 Executive Bush,George 5000 55 The year is the first data element on the line. The file will contain employee information for only two years: 2014 and 2015. Next is the type of the employee followed by the employee name and the monthly salary. For salesmen, the final value is their annual sales and for executives the stock price. As the employees are read in, Employee objects of the appropriate type should be created and they should be stored in one of two arrays depending upon the year. You may assume that the file will contain no more than ten employee records for each year and that the data in the file will be formatted correctly.

Once all the employee data is read in, a report should be displayed on the console for each of the two years. Each line of the report should contain all original data supplied for each employee together with that employee's annual salary for the year. For each of the two years, an average of all salaries for all employees for that year should be computed and displayed.

Be sure to follow good programming style, which means making all instance variables private, naming all constants and avoiding the duplication of code. Furthermore you must select enough different kinds of employees to completely test the program.

I'm not sure if my code is written correctly. Also I'm unsure how to make the 4th method w/text.file to read and display the correct information. I'm still learning and trying to improve. Please point out errors or if you know a better way to write any certain part:

 //Super Class

public class Employee {

//Instance variables of super
private String name;
private double monthlySal;
double annualSalary;



//Super constructor
public Employee(String name, double monthlySal) {
 this.name = name;//Initialization
 this.monthlySal = monthlySal;//Initialization
}//End of constructor`enter code here`


//Method for annualSalary
public void annualSalary(double annualSalary){
    this.annualSalary = monthlySal * 12;
    System.out.println("Annual Salary: " +annualSalary);
}//End of method


//toString Method
public String toString() {
    return "Employee Name: " + name + "\n" + "monthly Salary: " +monthlySal;
   }
}

//1st Subclass
public class Salesman extends Employee {
private String name;
private double monthlySal;
private double annualSales;
private double commission;
private double annualSalary;//Annual Salary

//subclass Constructor
  public Salesman(String name, double monthlySal, double annualSalary,  double   commission) {
    super(name, monthlySal);
    this.annualSales = annualSales;
    this.commission = 0.2 * annualSales;
 }//End of constructor



//Overridden Method
@Override
public void annualSalary(double annualSalary){
this.annualSalary = commission + super.annualSalary;

}//End of Override Method

//Overriden toString Method
@Override
public String toString(){
    return "Employee Name: " + name + "\n" + "Monthly Salary: " + monthlySal  + "\n" + "Annual Sales: " +annualSales;
}

}

//2nd Subclass
public class Executive extends Employee {

private double stockPrice;
private String name;
private double monthlySal;
private double annualSalary; 
private double bonus = 0;


 //Constructor
 public Executive(String name, double monthlySal, double annualSalary, double stockPrice) {
    super(name, monthlySal);
    this.stockPrice = stockPrice;
    this.annualSalary = annualSalary;

    if(stockPrice >= 50) {
        bonus = 30000;
    } else {
        bonus = 0;
    }//End of If Me
}//End of constructor

//Override Method for annualSalary
@Override
public void annualSalary(double annualSalary){
    this.annualSalary = super.annualSalary + bonus;
}//end of Override Method

//toString Override Method
@Override
public String toString() {
return "Employee Name: " + name + "\n" + "Monthly Salary: " + monthlySal + "\n" + "Current Stock Price: " +stockPrice;
}

}

//Text File - employee.txt
2014 Employee Clark, Sam 3000
2014 Salesman Samson, Jones 4000 40000
2014 Executive Brandon, Thurman 10000 70
2015 Executive Brandon, Thurman 11000 70
2015 Salesman Samson, Jones 4500 30000
2015 Employee Clark, Sam 3500