I am sending CurrentPage value 1, but it gives a null reference exception in set.
lblCurrentPage is a label control. CurrentPage is one variable.
public int CurrentPage
{
get { return int.Parse(lblCurrentPage.Text); }
set {
lblCurrentPage.Text = Convert.ToString(value);
}
}
You have a massive lack of info for us to go on, but i'll make a suggestion. Check that lblCurrentPage is actually set to a real control, i.e. make sure the label has been instantiated before you try to set its properties.
public int CurrentPage
{
get
{
int temp = 0;
if (lblCurrentPage != null)
{
int.TryParse(lblCurrentPage.Text, out temp);
}
return temp;
}
set
{
if (lblCurrentPage != null)
lblCurrentPage.Text = Convert.ToString(value);
}
}
Related
The List EleccionSinSeleccionClase is just a list of a class who has a String on it.
class EleccionSinSeleccionClase {
String Eleccion;
}
The state List is another class:
class EleccionConSleccionClase {
String Eleccion;
bool selec;
}
The problem is that I want to copy the first into the state of the StateNotifier, this line break the code.
This is the line: state[i].Eleccion = ListaElecciones[i].Eleccion;
class EleccionesConSeleccionNotifier
extends StateNotifier<List<EleccionConSleccionClase>> {
final List<EleccionSinSeleccionClase> ListaElecciones;
EleccionesConSeleccionNotifier({required this.ListaElecciones}) : super([]);
void init(){
print(ListaElecciones.length.toString());
if(ListaElecciones.length != 0){
for (int i = 0; i < ListaElecciones.length; i++) {
state[i].Eleccion = ListaElecciones[i].Eleccion; ////HERE////
}
}
}
}
final eleccionConSleccionStateNotifierProvider = StateNotifierProvider<
EleccionesConSeleccionNotifier, List<EleccionConSleccionClase>>((ref) {
final eleccioneswatch =
ref.watch(eleccionesSinSeleccionStateNotifierProvider);
return EleccionesConSeleccionNotifier(ListaElecciones: eleccioneswatch)..init();
});
Maybe the problem is that you initialize state as an empty list super([]) and then you're trying to change a value in an index that doesn't exist (state[i] where the list is obviously empty and cannot access that position)
void init(){
print(ListaElecciones.length.toString());
if(ListaElecciones.length != 0){
/// you will need to check if both lists are the same lenght if you actually want to do this
/// without failling
/*for (int i = 0; i < ListaElecciones.length; i++) {
state[i].Eleccion = ListaElecciones[i].Eleccion; ////HERE////
}*/
/// if you only want to copy Eleccion parameter in a new class this would be the easiest way
state = ListaElecciones.map((cb) => EleccionConSleccionClase(Eleccion: cb.Eleccion)).toList();
}
}
I'm working on a inventory system and i had working Crafting system, now i wanted to create RPG like crafting queue where you can click like 3 times on a item and it wil lcraft for you 3 time if you have enough resources, and i started working on it but for some reason, the original crafting system broke, here is what happens when you want to craft something
When you click on Crafting Recipe:
//override Use Function
public override void Use() {
//call AddCraftingItem from Inventory
Inventory.instance.AddCraftingItem(this);
}
AddCraftingItem:
public void AddCraftingItem(CraftinRecipe newCraftingRecipe) {
CraftingQueue.Enqueue(newCraftingRecipe);
if(!isCrafting) {
isCrafting = true;
//start crafting
StartCoroutine(CraftItem());
}
}
CraftItem:
private IEnumerator CraftItem() {
//check if queue is empty
if(CraftingQueue.Count == 0) {
Debug.Log("Queue is empty");
isCrafting = false;
yield break;
}
CraftinRecipe currentRecipe = CraftingQueue.Dequeue();
//check if we have enough resources
//this is where things broke
//CraftItem return false
if(!currentRecipe.CraftItem()) {
//Debug.Log("You don't have enough Resources");
CraftingQueue.Clear();
isCrafting = false;
yield break;
}
Debug.Log("TEST");
yield return new WaitForSeconds(currentRecipe.craftTime * 1.1f);
//add item to inventory
AddItem(currentRecipe.result);
Debug.Log("Added " + currentRecipe.result + " to inventory");
//check if continue crafting
if(CraftingQueue.Count > 0) {
yield return StartCoroutine(CraftItem());
} else {
isCrafting = false;
}
}
CraftItem:
public bool CraftItem() {
if(!CanCraft()) {
//Debug.Log("CanCraft returned false");
return false;
} else {
Debug.Log("CanCraft returned true");
}
RemoveIngredientsFromInventory();
//start crafting
ParentCraftingSlot.StartCrafting();
return true;
}
CanCraft function:
//function that return bool if we can craft the Item
public bool CanCraft() {
//loop trough each ingredient type of ingredient in ingredient
//(don't worry bro i don't understand what i just said too)
foreach(Ingredient ingredient in ingredients) {
//bool if we Contains current Ingredients
//here this function return false
bool ContainsCurrentIngredient = Inventory.instance.ContainsItem(ingredient.item,
ingredient.amount);
//if ContainsCurrentIngredient is false
if(!ContainsCurrentIngredient) {
//we return false
return false;
}
}
//return true
return true;
}
ContainItems (this is where things are broken):
//function that return true or false
//if we have enough Item to craft something
public bool ContainsItem(Item item, int amount) {
//make some variables objects etc
int ItemCounter = 0;
//loop through InventoryItemList with variable i type of Item
//(don't worry i don't know what i just said too #6)
foreach(Item i in InventoryItemList) {
//if i is equal to item
//this is the broken part
if(i == item) {
Debug.Log(i);
Debug.Log(item);
//we add 1 to Item Counter
ItemCounter++;
} else {
Debug.Log("i is not equal to item");
}
}
//if ItemCounter is bigger then or equal to amount
if(ItemCounter >= amount) {
/*Debug.Log("ContainsItem returned true");
Debug.Log(ItemCounter);*/
//we return true
//that means we have enough items to craft something
return true;
} else /*else*/ {
/*Debug.Log("ContainsItem returned false");
Debug.Log(ItemCounter);*/
//we return false
//that means we don't have enough item to craft something
return false;
}
}
so the problem is, in the InventoryItemList there are clones of one item, lets just say i have 2 irons and i need 1 iron to craft something, and my guess is that the problem is that i is clone so its not equal to the item and thats why it doesn't add 1 to itemCounter and then the script thinks we don't have enough resources to craft something, i tried to search and ask some of my friends how to check if that clone is equal to the item and i'm trying to fix this thing for like 2 days, i would love to hear any answers how to fix it or how to make my code more optimal, thanks for reading
Instead of directly checking i == item have some property in Item class which contains information of item type something like following
public class item
{
public enum Type
{
IronBar, GoldBar //etc
}
public Type itemType;
}
Then in your ContainItems() you could use something like
public bool ContainsItem(Item.Type itemType, int amount){
// other code
foreach(Item i in InventoryItemList) {
if(i.itemType == itemType) {
ItemCounter++;
}
// other code
}
I develop extension of PDT plugin. I need dialog with interfaces only (not classes). Basic code looks like it:
OpenTypeSelectionDialog2 dialog = new OpenTypeSelectionDialog2(
DLTKUIPlugin.getActiveWorkbenchShell(),
multi,
PlatformUI.getWorkbench().getProgressService(),
null,
type,
PHPUILanguageToolkit.getInstance());
It's works fine but I get classes and interfaces together (type variables). Is any method to filter it? I can't find this kind of mechanism in PDT but classes and interfaces are recognize correctly (icons next to names).
I don't know if its the best solution but it works.
int falseFlags = 0;
int trueFlags = 0;
IDLTKSearchScope scope = SearchEngine.createSearchScope(getScriptFolder().getScriptProject());
trueFlags = PHPFlags.AccInterface;
OpenTypeSelectionDialog2 dialog = new OpenTypeSelectionDialog2(
DLTKUIPlugin.getActiveWorkbenchShell(),
multi,
PlatformUI.getWorkbench().getProgressService(),
scope,
IDLTKSearchConstants.TYPE,
new PHPTypeSelectionExtension(trueFlags, falseFlags),
PHPUILanguageToolkit.getInstance());
And PHPTypeSelectionExtension looks like this:
public class PHPTypeSelectionExtension extends TypeSelectionExtension {
/**
* #see PHPFlags
*/
private int trueFlags = 0;
private int falseFlags = 0;
public PHPTypeSelectionExtension() {
}
public PHPTypeSelectionExtension(int trueFlags, int falseFlags) {
super();
this.trueFlags = trueFlags;
this.falseFlags = falseFlags;
}
#Override
public ITypeInfoFilterExtension getFilterExtension() {
return new ITypeInfoFilterExtension() {
#Override
public boolean select(ITypeInfoRequestor typeInfoRequestor) {
if (falseFlags != 0 && (falseFlags & typeInfoRequestor.getModifiers()) != 0) {
// Try to filter by black list.
return false;
} else if (trueFlags == 0 || (trueFlags & typeInfoRequestor.getModifiers()) != 0) {
// Try to filter by white list, if trueFlags == 0 this is fine 'couse we pass black list.
return true;
} else {
// Rest is filter out.
return false;
}
}
};
}
#SuppressWarnings("restriction")
#Override
public ISelectionStatusValidator getSelectionValidator() {
return new TypedElementSelectionValidator(new Class[] {IType.class, INamespace.class}, false);
}
}
In GTK+, is it possible to access the GtkWidget -- text entry for file name in GtkFileChooser? I want to disable the editable attribute of the text entry using gtk_entry_set_editable.
As far as I know, no.
What do you ultimately want to achieve? Perhaps there is another approach.
If one had a legitimate reason to get a pointer to the GtkEntry, then derive from GtkFileChooserDialog, which will probably mutate into a GtkFileChooserDefault. GObject will complain about an illegal cast when checking type instance even though it works and the data of derived object can be accessed without errors, use GTK_FILE_CHOOSER instead of MY_FILE_CHOOSER to avoid the warning messages and a local static for the entry pointer. The entry widget is NOT accessible during construction. Here is the pertinent code:
static GtkEntry *chooser_entry;
static void my_file_chooser_finalize (GObject *object)
{
chooser_entry = NULL;
(G_OBJECT_CLASS (my_file_chooser_parent_class))->finalize (object);
}
static void my_file_chooser_init (MyFileChooser *self)
{
chooser_entry = NULL;
}
static void look_for_entry(GtkWidget *widget, void *self)
{
if (GTK_IS_ENTRY(widget)) {
chooser_entry = (GtkEntry*)widget;
}
else if (GTK_IS_CONTAINER(widget)) {
gtk_container_forall ( GTK_CONTAINER (widget), look_for_entry, self);
}
}
static void file_chooser_find_entry (GtkWidget *chooser)
{
GList *children, *iter;
/* Get all objects inside the dialog */
children = gtk_container_get_children (GTK_CONTAINER (chooser));
for (iter = children; iter; iter = iter->next) {
if (GTK_IS_CONTAINER(iter->data)) {
gtk_container_forall ( GTK_CONTAINER (iter->data), look_for_entry, chooser);
if (chooser_entry != NULL) {
break;
}
}
}
g_list_free (children);
}
GtkEntry *my_file_chooser_get_entry (GtkWidget *widget)
{
if (chooser_entry == NULL) {
file_chooser_find_entry (widget);
}
return chooser_entry;
}
char *my_file_chooser_get_entry_text(GtkWidget *widget)
{
char *text;
GtkEntry *entry;
text = NULL;
if (GTK_IS_FILE_CHOOSER(widget)) {
entry = my_file_chooser_get_entry(widget);
if (GTK_IS_ENTRY(entry)) {
if (gtk_entry_get_text_length (entry)) {
text = g_strdup (gtk_entry_get_text(entry));
}
}
}
return text;
}
Maybe not ideal, but works.
Update: I can't get "Balancing" to work, because I cannot get "doAVLBalance" to recognize the member functions "isBalanced()", "isRightHeavy()", "isLeftHeavy". And I don't know why! I tried Sash's example(3rd answer) exactly but I get "deceleration is incompatible" and I couldn't fix that...so I tried doing it my way...and it tells me those member functions don't exist, when they clearly do.
"Error: class "IntBinaryTree:TreeNode" has no member "isRightHeavy".
I'm stuck after trying for the last 4 hours :(. Updated code below, help would be much appreciated!!
I'm creating a String based Binary Search Tree and need to make it a "Balanced" tree. How do I do this?* Help please!! Thanks in advance!
BinarySearchTree.cpp:
bool IntBinaryTree::leftRotation(TreeNode *root)
{
//TreeNode *nodePtr = root; // Can use nodePtr instead of root, better?
// root, nodePtr, this->?
if(NULL == root)
{return NULL;}
TreeNode *rightOfTheRoot = root->right;
root->right = rightOfTheRoot->left;
rightOfTheRoot->left = root;
return rightOfTheRoot;
}
bool IntBinaryTree::rightRotation(TreeNode *root)
{
if(NULL == root)
{return NULL;}
TreeNode *leftOfTheRoot = root->left;
root->left = leftOfTheRoot->right;
leftOfTheRoot->right = root;
return leftOfTheRoot;
}
bool IntBinaryTree::doAVLBalance(TreeNode *root)
{
if(NULL==root)
{return NULL;}
else if(root->isBalanced()) // Don't have "isBalanced"
{return root;}
root->left = doAVLBalance(root->left);
root->right = doAVLBalance(root->right);
getDepth(root); //Don't have this function yet
if(root->isRightHeavy()) // Don't have "isRightHeavey"
{
if(root->right->isLeftheavey())
{
root->right = rightRotation(root->right);
}
root = leftRotation(root);
}
else if(root->isLeftheavey()) // Don't have "isLeftHeavey"
{
if(root->left->isRightHeavey())
{
root->left = leftRotation(root->left);
}
root = rightRotation(root);
}
return root;
}
void IntBinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode)
{
if(nodePtr == NULL)
nodePtr = newNode; //Insert node
else if(newNode->value < nodePtr->value)
insert(nodePtr->left, newNode); //Search left branch
else
insert(nodePtr->right, newNode); //search right branch
}
//
// Displays the number of nodes in the Tree
int IntBinaryTree::numberNodes(TreeNode *root)
{
TreeNode *nodePtr = root;
if(root == NULL)
return 0;
int count = 1; // our actual node
if(nodePtr->left !=NULL)
{ count += numberNodes(nodePtr->left);
}
if(nodePtr->right != NULL)
{
count += numberNodes(nodePtr->right);
}
return count;
}
// Insert member function
void IntBinaryTree::insertNode(string num)
{
TreeNode *newNode; // Poitner to a new node.
// Create a new node and store num in it.
newNode = new TreeNode;
newNode->value = num;
newNode->left = newNode->right = NULL;
//Insert the node.
insert(root, newNode);
}
// More member functions, etc.
BinarySearchTree.h:
class IntBinaryTree
{
private:
struct TreeNode
{
string value; // Value in the node
TreeNode *left; // Pointer to left child node
TreeNode *right; // Pointer to right child node
};
//Private Members Functions
// Removed for shortness
void displayInOrder(TreeNode *) const;
public:
TreeNode *root;
//Constructor
IntBinaryTree()
{ root = NULL; }
//Destructor
~IntBinaryTree()
{ destroySubTree(root); }
// Binary tree Operations
void insertNode(string);
// Removed for shortness
int numberNodes(TreeNode *root);
//int balancedTree(string, int, int); // TreeBalanced
bool leftRotation(TreeNode *root);
bool rightRotation(TreeNode *root);
bool doAVLBalance(TreeNode *root); // void doAVLBalance();
bool isAVLBalanced();
int calculateAndGetAVLBalanceFactor(TreeNode *root);
int getAVLBalanceFactor()
{
TreeNode *nodePtr = root; // Okay to do this? instead of just
// left->mDepth
// right->mDepth
int leftTreeDepth = (left !=NULL) ? nodePtr->left->Depth : -1;
int rightTreeDepth = (right != NULL) ? nodePtr->right->Depth : -1;
return(leftTreeDepth - rightTreeDepth);
}
bool isRightheavey() { return (getAVLBalanceFactor() <= -2); }
bool isLeftheavey() { return (getAVLBalanceFactor() >= 2); }
bool isBalanced()
{
int balanceFactor = getAVLBalanceFactor();
return (balanceFactor >= -1 && balanceFactor <= 1);
}
int getDepth(TreeNode *root); // getDepth
void displayInOrder() const
{ displayInOrder(root); }
// Removed for shortness
};
Programmers use AVL Tree concepts to balance binary trees. It is quite simple. More information can be found online. Quick wiki link
Below is the sample code which does tree balance using AVL algorithm.
Node *BinarySearchTree::leftRotation(Node *root)
{
if(NULL == root)
{
return NULL;
}
Node *rightOfTheRoot = root->mRight;
root->mRight = rightOfTheRoot->mLeft;
rightOfTheRoot->mLeft = root;
return rightOfTheRoot;
}
Node *BinarySearchTree::rightRotation(Node *root)
{
if(NULL == root)
{
return NULL;
}
Node *leftOfTheRoot = root->mLeft;
root->mLeft = leftOfTheRoot->mRight;
leftOfTheRoot->mRight = root;
return leftOfTheRoot;
}
Node *BinarySearchTree::doAVLBalance(Node *root)
{
if(NULL == root)
{
return NULL;
}
else if(root->isBalanced())
{
return root;
}
root->mLeft = doAVLBalance(root->mLeft);
root->mRight = doAVLBalance(root->mRight);
getDepth(root);
if(root->isRightHeavy())
{
if(root->mRight->isLeftHeavy())
{
root->mRight = rightRotation(root->mRight);
}
root = leftRotation(root);
}
else if(root->isLeftHeavy())
{
if(root->mLeft->isRightHeavy())
{
root->mLeft = leftRotation(root->mLeft);
}
root = rightRotation(root);
}
return root;
}
Class Definition
class BinarySearchTree
{
public:
// .. lots of methods
Node *getRoot();
int getDepth(Node *root);
bool isAVLBalanced();
int calculateAndGetAVLBalanceFactor(Node *root);
void doAVLBalance();
private:
Node *mRoot;
};
class Node
{
public:
int mData;
Node *mLeft;
Node *mRight;
bool mHasVisited;
int mDepth;
public:
Node(int data)
: mData(data),
mLeft(NULL),
mRight(NULL),
mHasVisited(false),
mDepth(0)
{
}
int getData() { return mData; }
void setData(int data) { mData = data; }
void setRight(Node *right) { mRight = right;}
void setLeft(Node *left) { mLeft = left; }
Node * getRight() { return mRight; }
Node * getLeft() { return mLeft; }
bool hasLeft() { return (mLeft != NULL); }
bool hasRight() { return (mRight != NULL); }
bool isVisited() { return (mHasVisited == true); }
int getAVLBalanceFactor()
{
int leftTreeDepth = (mLeft != NULL) ? mLeft->mDepth : -1;
int rightTreeDepth = (mRight != NULL) ? mRight->mDepth : -1;
return(leftTreeDepth - rightTreeDepth);
}
bool isRightHeavy() { return (getAVLBalanceFactor() <= -2); }
bool isLeftHeavy() { return (getAVLBalanceFactor() >= 2); }
bool isBalanced()
{
int balanceFactor = getAVLBalanceFactor();
return (balanceFactor >= -1 && balanceFactor <= 1);
}
};
There are many ways to do this, but I'd suggest that you actually not do this as all. If you want to store a BST of strings, there are much better options:
Use a prewritten binary search tree class. The C++ std::set class offers the same time guarantees as a balanced binary search tree and is often implemented as such. It's substantially easier to use than rolling you own BST.
Use a trie instead. The trie data structure is simpler and more efficient than a BST of strings, requires no balancing at all, and is faster than a BST.
If you really must write your own balanced BST, you have many options. Most BST implementations that use balancing are extremely complex and are not for the faint of heart. I'd suggest implementing either a treap or a splay tree, which are two balanced BST structures that are rather simple to implement. They're both more complex than the code you have above and I can't in this short space provide an implementation, but a Wikipedia search for these structures should give you plenty of advice on how to proceed.
Hope this helps!
Unfortunately, we programmers are literal beasts.
make it a "Balanced" tree.
"Balanced" is context dependent. The introductory data structures classes typically refer to a tree being "balanced" when the difference between the node of greatest depth and the node of least depth is minimized. However, as mentioned by Sir Templatetypedef, a splay tree is considered a balancing tree. This is because it can balance trees rather well in cases that few nodes accessed together at one time frequently. This is because it takes less node traversals to get at the data in a splay tree than a conventional binary tree in these cases. On the other hand, its worst-case performance on an access-by-access basis can be as bad as a linked list.
Speaking of linked lists...
Because otherwise without the "Balancing" it's the same as a linked-list I read and defeats the purpose.
It can be as bad, but for randomized inserts it isn't. If you insert already-sorted data, most binary search tree implementations will store data like an bloated and ordered linked list. However, that's only because you're building one side of the tree continually. (Imagine inserting 1, 2, 3, 4, 5, 6, 7, etc... into a binary tree. Try it on paper and see what happens.)
If you have to balance in a theoretical worst-case-must-guaranteed sense, I recommend looking up red-black trees. (Google it, second link is pretty good.)
If you have to balance it in a reasonable way for this particular scenario, I'd go with integer indices and a decent hash function -- that way the balancing will happen probabilistically without any extra code. That is to say, make your comparison function look like hash(strA) < hash(strB) instead of what you've got now. (For a quick but effective hash for this case, look up FNV hashing. First hit on Google. Go down until you see useful code.) You can worry about the details of implementation efficiency if you want to. (For example, you don't have to perform both hashes every single time you compare since one of the strings never changes.)
If you can get away with it, I strongly recommend the latter if you're in a crunch for time and want something fast. Otherwise, red-black trees are worthwhile since they're extremely useful in practice when you need to roll your own height-balanced binary trees.
Finally, addressing your code above, see the comments in the code below:
int IntBinaryTree::numberNodes(TreeNode *root)
{
if(root = NULL) // You're using '=' where you want '==' -- common mistake.
// Consider getting used to putting the value first -- that is,
// "NULL == root". That way if you make that mistake again, the
// compiler will error in many cases.
return 0;
/*
if(TreeNode.left=null && TreeNode.right==null) // Meant to use '==' again.
{ return 1; }
return numberNodes(node.left) + numberNodes(node.right);
*/
int count = 1; // our actual node
if (left != NULL)
{
// You likely meant 'root.left' on the next line, not 'TreeNode.left'.
count += numberNodes(TreeNode.left);
// That's probably the line that's giving you the error.
}
if (right != NULL)
{
count += numberNodes(root.right);
}
return count;
}