• Ever wanted an RSS feed of all your favorite gaming news sites? Go check out our new Gaming Headlines feed! Read more about it here.
  • We have made minor adjustments to how the search bar works on ResetEra. You can read about the changes here.

Deleted member 40797

User requested account closure
Banned
Mar 8, 2018
1,008
Hello all. I'm in the last couple of weeks of my Data Structures and Algorithms C++ class. I need help. I can't like...wrap my head around some of these more complex data structures like Binary Search Trees, LinkedLists and others. Like how do I implement them and use them in a problems. Any suggestions for reading, or better yet interactive lessons on these things would be appreciated.

I find it useful to think about linked lists and binary search trees as recursive data types. For example, a list is either: (a) the empty list; or (b) a non-empty list consisting of an element (the head of the list) and another list (the tail of the list). If you think about the recursive structure of a linked list, its applications are immediate: a linked list provides O(1) access to its head and tail and O(n) access to arbitrary elements, because a linked list is a linear arrangement of data. In other words, a linked list arranges data in such a way that accessing the most recently inserted element is trivial, but accessing arbitrary elements takes time proportional to the length of the list. When you think about applications of a linked list (as opposed to an array), the question you should ask is: do I need to to efficiently access arbitrary elements, or merely the most recently accessed element? If you are only performing linear operations on your data, a linked list might be appropriate; if you need randomized access, an array might be better. The same considerations apply to binary search trees, except that (unbalanced) binary search trees can access elements more efficiently when their inputs are randomized. In the worst case, binary search trees have the same complexity as linked lists.

This doesn't really help with the implementation, but I really think considering the "shape" of your data structure is helpful. The implementation follows pretty trivially by considering the shape of the data structure you want to implement (assuming you are working in a standard programming languages).
 
Last edited:

MotiD

Member
Oct 26, 2017
1,560
What's a good IDE for Mac? Mainly for C and later on C++
is the default C compiler for Mac good enough?
 

metaprogram

Member
Oct 28, 2017
1,174
Xcode is the "standard" IDE, but Microsoft has recently released Visual Studio for Mac, and it's supposedly pretty good (and improving rapidly as they are putting a lot of effort into it). Personally I despise Xcode because the UI is just completely illogical
 

Zelenogorsk

Banned
Mar 1, 2018
1,567
First semester CS student here. I just spent two hours trying to figure out a logic error in a final project, and I finally found it! Feels amazing.
 

milch

Member
Oct 25, 2017
569
First semester CS student here. I just spent two hours trying to figure out a logic error in a final project, and I finally found it! Feels amazing.

I wonder if there's a feeling like the parallel elation of "oh I found it!!!" and self-hate of "well that was fucking stupid" in other fields.

Seems like a fundamental emotion of programming.
 

MotiD

Member
Oct 26, 2017
1,560
Xcode is the "standard" IDE, but Microsoft has recently released Visual Studio for Mac, and it's supposedly pretty good (and improving rapidly as they are putting a lot of effort into it). Personally I despise Xcode because the UI is just completely illogical
I'm using CLion and really enjoying it.

Thanks.
This is for personal use so I don't feel like paying for CLion. Using Xcode for now.

I've been away from programming for some time and decided to go over my C course homework from a while ago to decide if I really wanna have another go at Software Engineering or pursue another degree and I'm struggling with something relatively simple - reorganize a string (if the input is 'this is' the output should be 'is this') without using string.h (only arrays, functions, loops and condition statements)
I managed to hack together a solution but it's just an embarrassing piece of code that still has flaws. I feel like something like this should be relatively simple and I had an idea on how to do it right away but when I had to translate it to code it took what I feel like are unnecessary additions that only complicate things. Probably didn't help that I'm stubborn and stuck to this idea until I could make it work instead of trying to think of another solution.
 

Dany1899

Member
Dec 23, 2017
4,219
Thanks.
This is for personal use so I don't feel like paying for CLion. Using Xcode for now.

I've been away from programming for some time and decided to go over my C course homework from a while ago to decide if I really wanna have another go at Software Engineering or pursue another degree and I'm struggling with something relatively simple - reorganize a string (if the input is 'this is' the output should be 'is this') without using string.h (only arrays, functions, loops and condition statements)
I managed to hack together a solution but it's just an embarrassing piece of code that still has flaws. I feel like something like this should be relatively simple and I had an idea on how to do it right away but when I had to translate it to code it took what I feel like are unnecessary additions that only complicate things. Probably didn't help that I'm stubborn and stuck to this idea until I could make it work instead of trying to think of another solution.

At the beginning a not easy task is to adapt the algorithm we thought to solve a problem into code. But if you're approaching the first time to programming, I would give you the same advice I give the 1-year students when I assist in the C programming laboratories ad a scholarship holder: before starting to write code, it's correct (as I think you did) to think about the algorithm itself, then after this first step the second one is to answer the question: how can I implement my idea in the programming languace I chose to or I must use? In several case this translation can alo be more difficult than getting the idea and can lead to a refinement of the original idea: if the data structure I thought it's too expensive to construct, maybe it's better to change some aspects of it, for example.

About the complexity you mention, the most important defition is that provided by the Big-O notation (you can read something more here if you're interested -> http://pages.cs.wisc.edu/~vernon/cs367/notes/3.COMPLEXITY.html) but at the beginning it's always better not to consider this aspect. To learn it's fundamental to bang your hed against a wall even if you're trying to solve a challenge which in the past thousands of people have completex in a much more efficient way. Then you will understand how to optimisize your code too, but there is time for thinking about efficiency and complexity.
My suggestion is not to give up, Software Engineering is a though faculty but it can gives you big satisfactions and as soon as you enter in the right mentality, you'll see that coding your ideas in different languages and in an efficient way will become less difficult.
 

phisheep

Quis Custodiet Ipsos Custodes
Member
Oct 26, 2017
4,904
Thanks.
This is for personal use so I don't feel like paying for CLion. Using Xcode for now.

I've been away from programming for some time and decided to go over my C course homework from a while ago to decide if I really wanna have another go at Software Engineering or pursue another degree and I'm struggling with something relatively simple - reorganize a string (if the input is 'this is' the output should be 'is this') without using string.h (only arrays, functions, loops and condition statements)
I managed to hack together a solution but it's just an embarrassing piece of code that still has flaws. I feel like something like this should be relatively simple and I had an idea on how to do it right away but when I had to translate it to code it took what I feel like are unnecessary additions that only complicate things. Probably didn't help that I'm stubborn and stuck to this idea until I could make it work instead of trying to think of another solution.

Like you, I'm back to coding after a (long) break, and I'm forever getting stuck like this. It's like a writers block sort of thing.

What I find really helps is to try out it a few different ways. With your problem, I'd probably try:
- reverse the string first (or read it backwards), see if that makes it easier
- implement (array-based) queue and stack mechanisms and:
for character in string
...for character in word
......add to queue
...add queue to stack
then just pop them all in the right order
- then realise that is way too complicated, because the letters in each word are already in order, so just stack the words
- then realise that really, the string actually is a representation of a stack of words, we just need to read it the right way
- and end up with just writing an unstacker instead

That's probably not a huge amount of help with this particular problem, but it is the sort of thought process that helps me get from stuck to unstuck.
 

Klappdrachen

One Winged Slayer
Member
Oct 26, 2017
1,631
I have this assignment where I'm supposed to code a simple, text-based Hangman game in Java that asks the user to enter a letter (15 tries). The program I have now is able to look for the letter and show it, but I don't know how to save the users input so that the already entered letters stay visible until the end. I have considered using a separate character array to do that, but I don't know how to implement it. Could anyone give me a hint? This is what I have so far:

Java:
        for(int t=1; t<=15; t++) {
            
            System.out.println("Turn " + t + ":");
            Scanner input = new Scanner(System.in);
            char Letter = input.next().charAt(0);
            
                for(int i=0; i<charray.length; i++) {
                
                    if (charray[i] == Letter) {
                        System.out.print(Letter);     
                    } else if (charray[i] != Letter) {
                        System.out.print("_ ");   
                    }       
                }       
        }
 
Oct 25, 2017
4,826
New York City
I have this assignment where I'm supposed to code a simple, text-based Hangman game in Java that asks the user to enter a letter (15 tries). The program I have now is able to look for the letter and show it, but I don't know how to save the users input so that the already entered letters stay visible until the end. I have considered using a separate character array to do that, but I don't know how to implement it. Could anyone give me a hint? This is what I have so far:

Java:
        for(int t=1; t<=15; t++) {
           
            System.out.println("Turn " + t + ":");
            Scanner input = new Scanner(System.in);
            char Letter = input.next().charAt(0);
           
                for(int i=0; i<charray.length; i++) {
               
                    if (charray[i] == Letter) {
                        System.out.print(Letter);    
                    } else if (charray[i] != Letter) {
                        System.out.print("_ ");  
                    }      
                }      
        }
There are a few ways you can go about doing this. A simple way is to use an array of guesses to hold all of the player's guesses. You would insert each new guess into the array until the player runs out of guesses.

And then after you do that, you can display the word the player is guessing like _ESE_ E_A by using a loop to look at each guessed letter in the array. You may need to use a loop inside of a loop to write the whole string.

But if you know functions, then consider using them, then you could write a function such as hasCharacterBeenGuessed(char letter) or something similar.
 

Klappdrachen

One Winged Slayer
Member
Oct 26, 2017
1,631
I will try to write a method when I come home. Maybe writing an own method for this will make it easier. Thanks🙏
 

Post Reply

Member
Aug 1, 2018
4,538
I have this assignment where I'm supposed to code a simple, text-based Hangman game in Java that asks the user to enter a letter (15 tries). The program I have now is able to look for the letter and show it, but I don't know how to save the users input so that the already entered letters stay visible until the end. I have considered using a separate character array to do that, but I don't know how to implement it. Could anyone give me a hint? This is what I have so far:

Java:
        for(int t=1; t<=15; t++) {
           
            System.out.println("Turn " + t + ":");
            Scanner input = new Scanner(System.in);
            char Letter = input.next().charAt(0);
           
                for(int i=0; i<charray.length; i++) {
               
                    if (charray[i] == Letter) {
                        System.out.print(Letter);    
                    } else if (charray[i] != Letter) {
                        System.out.print("_ ");  
                    }      
                }      
        }

I'm assuming this is a school assignment, so I won't post my complete solution, but you're going to want to have at least 1 other array where you can persist the data between guesses.

Here's my expanded part of what you posted so far (note: I haven't coded in Java in forever, so there's probably cleaner ways of doing it):

Java:
        // ask for input until no more chances or correct answer
        for(int t = 0; t < numGuesses; t++) 
        {
            // turn prompt
            System.out.println("Turn " + t + ":");
            char Letter = input.next().charAt(0);
            
            // iterate through answer and check for matches
            for(int i = 0; i < charray.length; i++) 
            {
                if (charray[i] == Letter) 
                {
                    //System.out.print(Letter); 
                    answerArray[i] = Letter;
                }
            }
            
            // add guess to guessed char[]
            guessedArray[t] = Letter;

            // do other stuff
            
        } // end for loop

Also just some coding tips:

- Java uses 0-indexed arrays (meaning the first position of the array is at position '0'), so starting your for-loop at 1 and checking to see if it's equal to the number of times you want to iterate isn't really a great idea. It's extra mental overhead that you have to hang on to when dealing with your code that you could just eliminate by just starting at 0.

- Also, hard-coding numbers into your code can cause a lot of extra work for you as your programs start to grow and you need to make changes, so using a variable in-place of hard-coded numbers is a better idea.
 

Klappdrachen

One Winged Slayer
Member
Oct 26, 2017
1,631
So I tried to include an array for the answers, but it gives me this warning:
The local variable answer may not have been initialized.
It suggests initializing it, but when I click on that it initializes the array with "null" and I get a NullPointerException error.
Java:
if (charray[i] == Letter) {
                        System.out.print(Letter);
                        answer[i] = Letter;

- Java uses 0-indexed arrays (meaning the first position of the array is at position '0'), so starting your for-loop at 1 and checking to see if it's equal to the number of times you want to iterate isn't really a great idea. It's extra mental overhead that you have to hang on to when dealing with your code that you could just eliminate by just starting at 0.

- Also, hard-coding numbers into your code can cause a lot of extra work for you as your programs start to grow and you need to make changes, so using a variable in-place of hard-coded numbers is a better idea.

Thanks for the advice, I actually knew this stuff but sometimes I do the stupidest things.
 

Post Reply

Member
Aug 1, 2018
4,538
So I tried to include an array for the answers, but it gives me this warning:
The local variable answer may not have been initialized.
It suggests initializing it, but when I click on that it initializes the array with "null" and I get a NullPointerException error.
Java:
if (charray[i] == Letter) {
                        System.out.print(Letter);
                        answer[i] = Letter;

Yeah, you'll have to initialize the array before you can use it. I definitely suggest reading up on value types vs reference types and how Java deals with them.

Here's some information on how to create, initialize and work with arrays in Java:

https://www.tutorialspoint.com/java/java_arrays.htm
 

shazrobot

Member
Oct 28, 2017
882
My Data Structures and Algorithms final was a complete mess. 4 questions out of 10 had massive errors in the questions themselves that ended up with them being challenged during the final. So time spent on this questions was a total wash. I'm super frustrated right now.
 
Oct 25, 2017
4,826
New York City
One more piece of advice for Klappdrachen is to name your variables something meaningful, i.e. don't call your char[] "charray". That's the equivalent of naming your newborn child "person" lol. Name it something like "secretWord" or "targetWord" or something.

Even if you think "I know what my code means, it's my code", even for the smallest pieces of code you write it can help so much if you have meaningful names.
 

iareharSon

Member
Oct 30, 2017
8,974
Hi All -

Can someone help with this? We have an HTML tool at work that an old coworker's husband created to check to see if a client is a within the bounds of a gang hotspot based on their address. It worked until recently due to the API being outdated. I tried updating the API, which allowed the map to open, but I'm no longer able to see the boundaries or search for a location. I'm assuming some of the syntax needs to be updated as well? I have no idea D:

https://codeshare.io/5MoOVO

Edit: Never mind, I figured it out. When I created the new API, I forgot to check 'Places,' but it's working perfectly now.
 
Last edited:

Cyborg009

Member
Oct 28, 2017
1,251
So I'm having a lot of trouble using a ups api since I'm new at this. Looking at the API I'm suppose to send a json post request to the site and get back a response but I'm not sure how to tackle this. Doesn't help that I'm doing this in VB. My friend told me using soap would be much easier to do.
 

Zevenberge

Member
Oct 27, 2017
570
I don't know the VB syntax, but you can look at the HttpClient class and the PostWithJsonAsync extention method: https://docs.microsoft.com/en-us/previous-versions/visualstudio/hh944521(v=vs.118). If you want to go back to the basics, you can use the PostAsync method and serialize your object yourself. You'll want to model the desired request into a class and use the default serialisation (e.g. Newtonsoft.Json) to create a json string.

In my experience a json API is much simpler than a soap API, as json is standardized.
 

Cyborg009

Member
Oct 28, 2017
1,251
I don't know the VB syntax, but you can look at the HttpClient class and the PostWithJsonAsync extention method: https://docs.microsoft.com/en- she/previous-versions/visualstudio/hh944521(v=vs.118). If you want to go back to the basics, you can use the PostAsync method and serialize your object yourself. You'll want to model the desired request into a class and use the default serialisation (e.g. Newtonsoft.Json) to create a json string.

In my experience a json API is much simpler than a soap API, as json is standardized.
Thanks I'll look into this right now. I heard about Newton soft as well.
 

Klappdrachen

One Winged Slayer
Member
Oct 26, 2017
1,631
I am still completely stumped by this Hangman exercise. I'm wondering why I even need two arrays for it (guessed[] and answer[]) or more specifically, why are the contents of answer[] seemingly deleted after every iteration of the loop? If I try to print answer[] outside the loop it just prints underscores. Secondly, I have no idea how to make the letters remain on screen after they have been guessed correctly. This is what it looks like:

Code:
s
 _  _  _  _  _  _  s  _  _  _  _  _  _  _  _  Turn 2:
d
 _  d  _  _  _  _  _  _  _  _  _  _  d  _  _  Turn 3:
r
 _  _  _  _  _  _  _  _  _  _  _  _  _  _  r  Turn 4:

And here's the code:
Java:
for(int i=0; i<secretWord.length; i++) {
                
                    if (secretWord[i] == Letter) {
                        answer[i] = Letter;
                        System.out.print(" " + answer[i] + " ");
                        guessed[i] = answer[i];
                        
                        
                    } else if (secretWord[i] != Letter) {
                        System.out.print(" _ ");   
                        answer[i] = '_';
                        guessed[i] = '_'; // If I remove this, the letters
                                          // are saved in guessed[]. With it
                                          // included, it prints "__________"
                    }
I've been trying many different things for hours now, none of them worked.
 

metaprogram

Member
Oct 28, 2017
1,174
You haven't showed the whole loop I think.

Also, you are overwriting previously guessed letters with '_' every time through the loop. For example, imagine the word is "fruit" and the user guesses "f". So then you end up with answer = "f _ _ _ _". then the next time the user guesses "r". It will enter the loop, the else branch will be taken when i=0, and so it will set answer[0] = '_', overwriting the letter that was previously guessed correctly.

This is also the reason why removing the guessed line makes the letters be stored in guessed. Because then, in the else block, you won't overwrite letters which were previously guessed correctly.
 
Last edited:

Klappdrachen

One Winged Slayer
Member
Oct 26, 2017
1,631
Sorry, I thought the rest wouldn't be relevant. Here it is:
Java:
for(int t=0; t<=numGuesses; t++) {
           
            System.out.println(" Turn " + t + ":");
            Scanner input = new Scanner(System.in);
            char Letter = input.next().charAt(0);
           
                for(int i=0; i<secretWord.length; i++) {
               
                   
                    if (secretWord[i] == Letter) {
                        answer[i] = Letter;
                        System.out.print(" " + answer[i] + " ");
                        guessed[i] = answer[i];
                       
                       
                    } else if (secretWord[i] != Letter) {
                        System.out.print(" _ ");  
                        answer[i] = '_';
                        guessed[i] = '_'; // If I remove this, the letters
                                          // are saved in guessed[]. With it
                                          // included, it prints "__________"
                    }                  
                }          
        }
       
        for (int i = 0; i < guessed.length; i++) {
            System.out.print(guessed[i]);
        }

Also, you are overwriting previously guessed letters with '_' every time through the loop. For example, imagine the word is "fruit" and the user guesses "f". So then you end up with answer = "f _ _ _ _". then the next time the user guesses "r". It will enter the loop, the else branch will be taken when i=0, and so it will set answer[0] = '_', overwriting the letter that was previously guessed correctly.
Hmm, I didn't think of this at all... Maybe I should add a second condition?
 
Last edited:

Dany1899

Member
Dec 23, 2017
4,219
EDIT: I saw now that the problem was already underlined above.
Basically, if I understand, with the "else if" block you remove all the letters which were guessed in the previous turns.
For istance, let's assume the secret word is Kurisu.
Turn 0: player says u. The guessed word becomes _u___u
Turn 1: player says K. The guessed word should become Ku___u, however it becomes K_____. Why?
Because secretWord != Letter (where secretWord is u and Letter is K), so basically they are removed from your answer.

Anyway I wouldn't use two array for the answer. My suggestions would be to just use the secretWord array and the guessed array, inizialiating the guessed array with all '_' elements.
Something like this:

Java:
for(int i = 0; i < secretWord.length; i++)
guessed[i]='_';

for(int t=0; t<=numGuesses; t++) {
    
            System.out.println(" Turn " + t + ":");
            Scanner input = new Scanner(System.in);
            char Letter = input.next().charAt(0);
    
                for(int i=0; i<secretWord.length; i++) {
        
            
                    if (secretWord[i] == Letter) {
                        guessed[i] = secretWord[i];
     
                }   
        }

        for (int i = 0; i < guessed.length; i++) {
            System.out.print(guessed[i]);
        }
}
 
Last edited:

Klappdrachen

One Winged Slayer
Member
Oct 26, 2017
1,631
Anyway I wouldn't use two array for the answer. My suggestions would be to just use the secretWord array and the guessed array, inizialiating the guessed array with all '_' elements.
Yes! It worked! Initializing the array with '_' is so simple but clever 🤦‍♂️ It's just like I wanted now:
Code:
c
 _  _  a  _  _  e  _  Turn 5:
v
 _  _  a  v  _  e  _  Turn 6:
f
 _  _  a  v  _  e  _  Turn 7:
Now I just need to build a random word generator and also figure out how to make it ignore capitalization. Thanks so far everyone!
 

metaprogram

Member
Oct 28, 2017
1,174
Yes! It worked! Initializing the array with '_' is so simple but clever 🤦‍♂️ It's just like I wanted now:
Code:
c
_  _  a  _  _  e  _  Turn 5:
v
_  _  a  v  _  e  _  Turn 6:
f
_  _  a  v  _  e  _  Turn 7:
Now I just need to build a random word generator and also figure out how to make it ignore capitalization. Thanks so far everyone!

FWIW, it sounds like you were basically just staring at the code the whole time trying to figure out why it didn't work. You probably could have found the problem in about 30 seconds using a debugger, you just set a breakpoint, add your arrays to the watch window, and then go line by line until something happens that you didn't expect.
 

Klappdrachen

One Winged Slayer
Member
Oct 26, 2017
1,631
FWIW, it sounds like you were basically just staring at the code the whole time trying to figure out why it didn't work. You probably could have found the problem in about 30 seconds using a debugger, you just set a breakpoint, add your arrays to the watch window, and then go line by line until something happens that you didn't expect.
Yeah, I tried to use the debugger once and was quickly overwhelmed. Noped out of it instead of trying to familiarize myself with it (I give up quickly when it comes to this kind of stuff...). Guess I'll have to bite the bullet and properly learn how to use it.
 

Post Reply

Member
Aug 1, 2018
4,538
Yes! It worked! Initializing the array with '_' is so simple but clever 🤦‍♂️ It's just like I wanted now:
Code:
c
 _  _  a  _  _  e  _  Turn 5:
v
 _  _  a  v  _  e  _  Turn 6:
f
 _  _  a  v  _  e  _  Turn 7:
Now I just need to build a random word generator and also figure out how to make it ignore capitalization. Thanks so far everyone!

Congrats on figuring it out!

And just for the record, my use of the 2nd array was to track the letters that have been previously guessed in the event you wanted to give the user another chance to guess if they guessed with a letter they've already used or if you planned on clearing the screen or something after each guess, you'd have a running record. This is what the output of the program I wrote looked like:

7nLAkOe.png
 

Klappdrachen

One Winged Slayer
Member
Oct 26, 2017
1,631
Post Reply Yeah that's quite a bit more capable than my version 😅. Currently I'm trying to implement a way to make the game stop after all letters have been guessed (because now it asks for 15 guesses no matter what) but I have decided to spend some more time with it after that and add things the assignment didn't ask for, like a win/lose message, a record of the correct guesses (like in your example) and the possibility to restart the game after it has ended. I suppose it's a good exercise.
Also, thanks for the article you posted above, it was helpful. 👍
 
Oct 25, 2017
4,826
New York City
Does anyone know or have resources about how to draw graphics on a screen in C# using Windows Forms? I am writing a Game Boy emulator (a simple one for fun, nothing special) and want to draw graphics in a window at a constant frame rate of 60 or so FPS.

In Java using AWT, that kind of thing is easy - create a Frame (basically a window), add listeners to it, stick a Panel in it (the control to draw graphics on), set the Frame to visible, and once every 1/60th of a second call panel.repaint() to tell your onPaint listener to redraw.

In C# using WinForms, I do the same exact thing. Except Frame => Form and panel.repaint() => panel.Invalidate().

But in C#, once every few seconds or so it flickers like a madman. Anyone know why this might be? Or have any tutorials of drawing simple graphics on the screen?



(Also, one other big difference is that in Java AWT, you could write frame.setVisible(true) and all the listeners will fire off and be handled automatically on a separate thread. But in C# WinForms, if you use form.Show(), you have to manually tell the Form to handle listeners with Application.DoEvents(), which I also do in my every 1/60th of a second loop.)
 

Zevenberge

Member
Oct 27, 2017
570
It's kind of hard to analyze from here. My best guess would be to check whether there are any unexpected 'ghost' event listeners sticking around that trigger every few seconds.
 

mugurumakensei

Elizabeth, I’m coming to join you!
Member
Oct 25, 2017
11,376
Does anyone know or have resources about how to draw graphics on a screen in C# using Windows Forms? I am writing a Game Boy emulator (a simple one for fun, nothing special) and want to draw graphics in a window at a constant frame rate of 60 or so FPS.

In Java using AWT, that kind of thing is easy - create a Frame (basically a window), add listeners to it, stick a Panel in it (the control to draw graphics on), set the Frame to visible, and once every 1/60th of a second call panel.repaint() to tell your onPaint listener to redraw.

In C# using WinForms, I do the same exact thing. Except Frame => Form and panel.repaint() => panel.Invalidate().

But in C#, once every few seconds or so it flickers like a madman. Anyone know why this might be? Or have any tutorials of drawing simple graphics on the screen?

WinForms are not double buffered by default. You need to set DoubleBuffered = true

You may get a graphics context by calling CreateGraphics on the WinForm
 

Post Reply

Member
Aug 1, 2018
4,538

Klappdrachen

One Winged Slayer
Member
Oct 26, 2017
1,631
Shouldn't this return 54.32?
Java:
double d = 54.32553;
       
        System.out.println(Math.round(d * 100)/100);
Because it prints 54 🤔
 

Klappdrachen

One Winged Slayer
Member
Oct 26, 2017
1,631
Ohhh, so changing it to 100.00 works... But the expression "d*100" should still produce a double since d is a double value, right? So I was dividing a double by an integer.
 

BlueOdin

Member
Oct 26, 2017
4,014
I have a json file where an entry is build like this:

Code:
{
    "Title": "Competition for Chairs and Tables, Festival of Misfits, ICA, London, October 23- November 8, 1962",
    "Artist": [
      "Daniel Spoerri"
    ],
    "ConstituentID": [
      5569
    ],
    "ArtistBio": [
      "Swiss, born Romania. 1930"
    ],
    "Nationality": [
      "Swiss"
    ],
    "BeginDate": [
      1930
    ],
    "EndDate": [
      0
    ],
    "Gender": [
      "Male"
    ],
    "Date": "1962",
    "Medium": "Gelatin silver print",
    "Dimensions": "sheet: 10 \u00d7 8\" (25.4 \u00d7 20.3 cm)",
    "CreditLine": "The Gilbert and Lila Silverman Fluxus Collection Gift",
    "AccessionNumber": "3724.2008.P05",
    "Classification": "Photograph",
    "Department": "Prints & Illustrated Books",
    "DateAcquired": null,
    "Cataloged": "N",
    "ObjectID": 233648,
    "URL": null,
    "ThumbnailURL": null,
    "Height (cm)": 25.4,
    "Width (cm)": 20.3
  }

I want to get specific data from the file and write it to another json file with the following Python code:

Code:
import json

with open('artworks-selection.json', mode='r', encoding='utf8') as rein:
    kunstsammlung = json.load(rein)

galerie = []

for row in kunstsammlung:
    if str('River') in str(row['Title']) and len(row['Artist']) == 1:
        galerie.append((row['AccessionNumber'], row['Title'], row['Artist'], row['URL']))

with open('gruppe14-aufgabe1.json', mode='w', encoding='utf8') as raus:
    json.dump(galerie, raus, indent=2)

It takes the data I want but it makes the file look like this:

Code:
[
  [
    "1254.2000",
    "Generator Project, White Oak, Florida, Sketch, \"On St. Mary's River\"",
    [
      "Cedric Price"
    ],
    "http://www.moma.org/collection/works/868"
  ],
  [
    "367.1938",
    "Source of the Laramie River",
    [
      "Andrew Joseph Russell"
    ],
    "http://www.moma.org/collection/works/51876"
  ],
  [
    "863.1968",
    "Village, Mekong River Delta, South Vietnam",
    [
      "Dorothea Lange"
    ],
    null
  ]
]

My problem is that I also want the keys 'AccessionNumber', 'Title', 'Artist' and 'URL' to be written into the file but I don't know how. Can anyone help me?
 

PorcoLighto

Member
Oct 25, 2017
766
I have a json file where an entry is build like this:

Code:
{
    "Title": "Competition for Chairs and Tables, Festival of Misfits, ICA, London, October 23- November 8, 1962",
    "Artist": [
      "Daniel Spoerri"
    ],
    "ConstituentID": [
      5569
    ],
    "ArtistBio": [
      "Swiss, born Romania. 1930"
    ],
    "Nationality": [
      "Swiss"
    ],
    "BeginDate": [
      1930
    ],
    "EndDate": [
      0
    ],
    "Gender": [
      "Male"
    ],
    "Date": "1962",
    "Medium": "Gelatin silver print",
    "Dimensions": "sheet: 10 \u00d7 8\" (25.4 \u00d7 20.3 cm)",
    "CreditLine": "The Gilbert and Lila Silverman Fluxus Collection Gift",
    "AccessionNumber": "3724.2008.P05",
    "Classification": "Photograph",
    "Department": "Prints & Illustrated Books",
    "DateAcquired": null,
    "Cataloged": "N",
    "ObjectID": 233648,
    "URL": null,
    "ThumbnailURL": null,
    "Height (cm)": 25.4,
    "Width (cm)": 20.3
  }

I want to get specific data from the file and write it to another json file with the following Python code:

Code:
import json

with open('artworks-selection.json', mode='r', encoding='utf8') as rein:
    kunstsammlung = json.load(rein)

galerie = []

for row in kunstsammlung:
    if str('River') in str(row['Title']) and len(row['Artist']) == 1:
        galerie.append((row['AccessionNumber'], row['Title'], row['Artist'], row['URL']))

with open('gruppe14-aufgabe1.json', mode='w', encoding='utf8') as raus:
    json.dump(galerie, raus, indent=2)

It takes the data I want but it makes the file look like this:

Code:
[
  [
    "1254.2000",
    "Generator Project, White Oak, Florida, Sketch, \"On St. Mary's River\"",
    [
      "Cedric Price"
    ],
    "http://www.moma.org/collection/works/868"
  ],
  [
    "367.1938",
    "Source of the Laramie River",
    [
      "Andrew Joseph Russell"
    ],
    "http://www.moma.org/collection/works/51876"
  ],
  [
    "863.1968",
    "Village, Mekong River Delta, South Vietnam",
    [
      "Dorothea Lange"
    ],
    null
  ]
]

My problem is that I also want the keys 'AccessionNumber', 'Title', 'Artist' and 'URL' to be written into the file but I don't know how. Can anyone help me?
The problem you are having is because on the line
Python:
galerie.append((row['AccessionNumber'], row['Title'], row['Artist'], row['URL']))
you are appending to the list galerie with a tuple with only the values. If you want the json file to have the key also then you have to append a dict. Like this:
Python:
galerie.append(
    {
        'AccessionNumber':row['AccessionNumber'],
        'Title':row['Title'],
        'Artist':row['Artist'],
        'URL':row['URL'],
    }
)
 

BlueOdin

Member
Oct 26, 2017
4,014
The problem you are having is because on the line
Python:
galerie.append((row['AccessionNumber'], row['Title'], row['Artist'], row['URL']))
you are appending to the list galerie with a tuple with only the values. If you want the json file to have the key also then you have to append a dict. Like this:
Python:
galerie.append(
    {
        'AccessionNumber':row['AccessionNumber'],
        'Title':row['Title'],
        'Artist':row['Artist'],
        'URL':row['URL'],
    }
)

That did it! Thank you very much!


Ran into another problem with saving a list of Dicts to to XML. File I'm getting the data from is the same as before.

My code looks like this:

Python:
katalog = []
nummer = 0

for row3 in kunstsammlung:
    if nummer < 100:
        if row3['Cataloged'] == 'Y':
            katalog.append(row3)
            nummer = nummer + 1

    else:
        break

import xml.etree.ElementTree as ET
root = ET.Element('collection')
tree = ET.ElementTree(root)

for item in katalog:
    child = ET.SubElement(root, 'artwork')
    for item2 in item:
        child2 = ET.SubElement(root, item2)
        child2.text = str(item[item2])


tree.write('gruppe14-aufgabe3.xml', encoding='utf8')

It writes an XML file with the data but the XML file gives me error messages like start tag doesn't have the right closing tag and unexpected token.

The file is supposed to look like this:

XML:
<?xml version='1.0' encoding='UTF-8'?>
<collection>
    <artwork>
        <artists count="number of Artists">
            <artist>name of Artist</artist>
            [...]
        </artists>
        <title>Title</title>
        <objectid>ObjectID</objectid>
        <dimensions>
            <width>Width (cm) cm</width>
            <height>Height (cm) cm</height>
        </dimensions>
    </artwork>
    [...]
</collection>
 
Last edited:

PorcoLighto

Member
Oct 25, 2017
766
That did it! Thank you very much!


Ran into another problem with saving a list of Dicts to to XML. File I'm getting the data from is the same as before.

My code looks like this:

Python:
katalog = []
nummer = 0

for row3 in kunstsammlung:
    if nummer < 100:
        if row3['Cataloged'] == 'Y':
            katalog.append(row3)
            nummer = nummer + 1

    else:
        break

import xml.etree.ElementTree as ET
root = ET.Element('collection')
tree = ET.ElementTree(root)

for item in katalog:
    child = ET.SubElement(root, 'artwork')
    for item2 in item:
        child2 = ET.SubElement(root, item2)
        child2.text = str(item[item2])


tree.write('gruppe14-aufgabe3.xml', encoding='utf8')

It writes an XML file with the data but the XML file gives me error messages like start tag doesn't have the right closing tag and unexpected token.

The file is supposed to look like this:

XML:
<?xml version='1.0' encoding='UTF-8'?>
<collection>
    <artwork>
        <artists count="number of Artists">
            <artist>name of Artist</artist>
            [...]
        </artists>
        <title>Title</title>
        <objectid>ObjectID</objectid>
        <dimensions>
            <width>Width (cm) cm</width>
            <height>Height (cm) cm</height>
        </dimensions>
    </artwork>
    [...]
</collection>
Python:
for item in katalog:
    child = ET.SubElement(root, 'artwork')
    for item2 in item:
        child2 = ET.SubElement(root, item2)
        child2.text = str(item[item2])
I can see an error that child2 is supposed to be under 'artwork' but you still put 'root' as its parent node, this should still make a valid XML though.
What type is item?
 

BlueOdin

Member
Oct 26, 2017
4,014
Python:
for item in katalog:
    child = ET.SubElement(root, 'artwork')
    for item2 in item:
        child2 = ET.SubElement(root, item2)
        child2.text = str(item[item2])
I can see an error that child2 is supposed to be under 'artwork' but you still put 'root' as its parent node, this should still make a valid XML though.
What type is item?

Thanks for the answer!

So I replace the root in child2 with child? I get an error message that I can't put in a string if I put 'artwork' in.

XML:
<collection><artwork><Title>Untitled, plate 3 of 8, from the illustrated book, the puritan</Title><Artist>['Louise Bourgeois']</Artist><ConstituentID>[710]</ConstituentID><ArtistBio>['American, born France. 1911–2010']</ArtistBio><Nationality>['American']</Nationality><BeginDate>[1911]</BeginDate><EndDate>[2010]</EndDate><Gender>['Female']</Gender><Date>1990</Date><Medium>Engraving, with hand additions</Medium><Dimensions>plate: 16 3/4 x 10 13/16" (42.5 x 27.5 cm); page: 26 x 19 7/8" (66 x 50.5 cm)</Dimensions><CreditLine>Gift of the artist</CreditLine><AccessionNumber>156.1999.3</AccessionNumber><Classification>Illustrated Book</Classification><Department>Prints &amp; Illustrated Books</Department><DateAcquired>1999-05-20</DateAcquired><Cataloged>Y</Cataloged><ObjectID>130964</ObjectID><URL>http://www.moma.org/collection/works/130964</URL><ThumbnailURL>http://www.moma.org/media/W1siZiIsIjE2ODk4NSJdLFsicCIsImNvbnZlcnQiLCItcmVzaXplIDMwMHgzMDBcdTAwM2UiXV0.jpg?sha=fc9d9df54ebbeea1</ThumbnailURL><Height (cm)>42.5</Height (cm)><Width (cm)>27.5</Width (cm)></artwork>

This is how the first entry of the XML file look. In Pycharm Edu the tag <collection> and every <artwork> tag is underlined as having the wrong closing tag. <height> and <width> tags don't look right either.

Don't understand the question "What type is item?".
 

PorcoLighto

Member
Oct 25, 2017
766
Thanks for the answer!

So I replace the root in child2 with child? I get an error message that I can't put in a string if I put 'artwork' in.

XML:
<collection><artwork><Title>Untitled, plate 3 of 8, from the illustrated book, the puritan</Title><Artist>['Louise Bourgeois']</Artist><ConstituentID>[710]</ConstituentID><ArtistBio>['American, born France. 1911–2010']</ArtistBio><Nationality>['American']</Nationality><BeginDate>[1911]</BeginDate><EndDate>[2010]</EndDate><Gender>['Female']</Gender><Date>1990</Date><Medium>Engraving, with hand additions</Medium><Dimensions>plate: 16 3/4 x 10 13/16" (42.5 x 27.5 cm); page: 26 x 19 7/8" (66 x 50.5 cm)</Dimensions><CreditLine>Gift of the artist</CreditLine><AccessionNumber>156.1999.3</AccessionNumber><Classification>Illustrated Book</Classification><Department>Prints &amp; Illustrated Books</Department><DateAcquired>1999-05-20</DateAcquired><Cataloged>Y</Cataloged><ObjectID>130964</ObjectID><URL>http://www.moma.org/collection/works/130964</URL><ThumbnailURL>http://www.moma.org/media/W1siZiIsIjE2ODk4NSJdLFsicCIsImNvbnZlcnQiLCItcmVzaXplIDMwMHgzMDBcdTAwM2UiXV0.jpg?sha=fc9d9df54ebbeea1</ThumbnailURL><Height (cm)>42.5</Height (cm)><Width (cm)>27.5</Width (cm)></artwork>

This is how the first entry of the XML file look. In Pycharm Edu the tag <collection> and every <artwork> tag is underlined as having the wrong closing tag. <height> and <width> tags don't look right either.

Don't understand the question "What type is item?".
That XML is malformed because of the '(cm)' in width and height tag name. That made the rest of the document invalid.

When you create the child tag you can do this to remove that:
Python:
child2 = ET.SubElement(child, item2.replace(' (cm)','')