• 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.

Contact

Member
Oct 27, 2017
287
Hi, need some advice on Octave.

How do I construct a Hull White tree for Pricing Options? I'm at a loss and I don't even know how to start. The option I'm pricing involves a Zt state variable (that follows a Ornstein Uhlenbeck process) and the payoff function is as follow:

Ik6jLrv.png


Ultimately I'm suppose to figure out a payoff for when te=2, so I only require Z2. Even then, how do I derive Z2?

Also, the risk neutral mean EQ, is it correct that the way to implement this is to assign probabilities pu, pd and pm to the function contained within EQ?

Many thanks.
You can calculate derivatives in matlab using diff().
Let's say you want to to calculate the derivarive of cos(x):
Code:
syms x;
f = cos(x);
df = diff(f)
Octave should be the same, the most you should have to do is import a package.
 
Oct 28, 2017
10,000
Ok so the first problem is that GetRefAPI isn't actually in cl_main.c. What is in cl_main.c is this:

Code:
ret = GetRefAPI( REF_API_VERSION, &ri );

That is just a call to the function. What we need is the definition of the function. I searched the GitHub, and it shows up in various places. For example, in tr_public.h we have this:

Code:
refexport_t*GetRefAPI( int apiVersion, refimport_t *rimp );

But that is not a definition, that is a declaration. A declaration just says "hey there's a function called GetRefAPI and here's the signature. You can call it, but since I don't have the code for it, the linker is going to have to figure this out."

A definition is where the code actually occurs. That is in code/renderer/tr_init.c. Which you can see here:

Code:
refexport_t *GetRefAPI ( int apiVersion, refimport_t *rimp ) {
  static refexport_t re;
  ...
}

What this means is that the important object file is going to be tr_init.obj. For any given symbol (function, variable, etc) exactly one object file should contain a symbol for it. That's what I was getting at with the dumpbin commands. I was trying to see "does this object file have the right symbol?" If it does, and the name is correct, you won't get an unresolved external.

So when diagnosing this kind of thing, you have to ask:

1) Which object file contains the definition
2) Is that object file being linked in
3) If not, why not? If so, why isn't the name matching?

So now that we know it should be in tr_init.obj we go back and look at the link line again. This time we're looking for tr_init.obj. And we see, it is nowhere to be found.

So this brings us to #3 above. The proper object file is not being linked in, and we need to know why.

I went to the top level of the GitHub repo and saw that there is a quake3.vcproj file. I opened it up in GitHub (not in VS), and Ctrl+F'ed for tr_init.c found that this project does not even compile this file. So it needs to be coming from somewhere else. Probably it's compiled in a different file and then supposed to be linked in to the final project. So I opened the .sln instead and saw that there is another project called renderer/renderer.vcproj and sure enough, this is the project that compiles tr_init.c.

So now we have a clue. quake3.vcproj is supposed to be linking in the files from renderer.vcproj, but it isn't. How is it supposed to link them in? Well, in renderer.vcproj we see this line:

Code:
OutputFile=".\Debug_TA\renderer.lib"

So we can tell that it is supposed to be outputting a file named renderer.lib, and presumably this file is supposed to be linked into the final executable. Remember one of the first observations I made when I looked at the link line was that there are no quake-specific libraries.

So to fix it. The first thing to check is: Did you open quake3.sln or did you open quake3.vcproj? If it's the latter, that's the problem. Open the .sln file instead. However, I suspect you are already opening the .sln file.

This could be an issue with such an old version of the MSVC project file format not fully forwards-compatible with the new version, so when it tries to upgrade, information is lost. The reason I suspect this is because I don't see anything in any of the project files or solution files to indicate that quake3.exe (from quake3.vcproj) should try to link renderer.lib (from renderer.vcproj).

If you just want to test this theory out, go into quake3.vcproj, edit project settings, go to Linker and find Additional Input files then add a full absolute path to renderer.lib on your hard drive.

I suspect the errors will go away. If you want to do it the "right" way, probably in the solution file you need to add a dependency from quake3.vcproj to renderer.vcproj, and then in the Configuration Properties > Linker > General for the quake3 project, make sure "Link Library Dependencies" is set to Yes

Holy text dump Batman, thanks. All of that makes sense and yeah, I still sometimes confuse declarations and definitions, but after this ordeal, I think I'm not confused anymore. So that's how you diagnose linkages, that's actually pretty cool. So that's how that works, cool. I'll check but I'm pretty sure it was the .sln file. Makes perfect sense and I was suspect or worried about those possible compatibility issues. Those two solutions sound good to me, I'll try them out! I'm going to be "saving" this information because it's a good general guide and rife with information. I really did end up learning a lot. Sincerely, thank you very much!
 

metaprogram

Member
Oct 28, 2017
1,174
Holy text dump Batman, thanks. All of that makes sense and yeah, I still sometimes confuse declarations and definitions, but after this ordeal, I think I'm not confused anymore. So that's how you diagnose linkages, that's actually pretty cool. So that's how that works, cool. I'll check but I'm pretty sure it was the .sln file. Makes perfect sense and I was suspect or worried about those possible compatibility issues. Those two solutions sound good to me, I'll try them out! I'm going to be "saving" this information because it's a good general guide and rife with information. I really did end up learning a lot. Sincerely, thank you very much!

I actually work on a linker, so your question tickled the right spot and I felt like responding in depth :) Because not enough people understand this stuff well.
 
Oct 28, 2017
10,000
I actually work on a linker, so your question tickled the right spot and I felt like responding in depth :) Because not enough people understand this stuff well.

You're right that most people do not understand this stuff (guilty). As such I do find it fascinating and could possibly somewhat follow the conversation, so if you ever feel like talking about your work/project, I would enjoy it; at least I think I would anyway.
 

Megasoum

Member
Oct 25, 2017
22,568
I imagine you guys already know about this but my teacher just sent us that link after tring to explain Quick-Sort for like an hour lol

 

Grenouille

Member
Nov 26, 2017
664
Started working with Node.js and asynchronicity has been punishing me. I cant even print an array in order, what the hell
 

Contact

Member
Oct 27, 2017
287
Does anyone know any HTML/CSS/JS template for a tournament bracket type of thing? I'm looking for something like https://disneybracket.com/ but I've found nothing (yes, I know I can copy the code, but I'd like something a little prettier).
 

Megasoum

Member
Oct 25, 2017
22,568
Hey guys, I need help with with a JAVA Swing UI.

So basically I have a Superclass for a JDialog window to manage users in a company. I have to re-use the same window for Adding users, editing users or viewing users so I'll be making a class for each of those usecases extending the superclass.

They all have the same basic objects (labels, textboxes, etc) but with different proprieties (editable, text value, etc) and two buttons at the bottom including one that will be different for each of those variants. The window uses two JPanels. One for all the labels and textboxes and one for the 2 buttons at the bottom.

Right now the way I'm planning on doing the structure is basically

Superclass ------- Subclass 1 ---- Subclass 1 Event Listener
!
!-------------- Subclass 2 ---- Subclass 2 Event Listener
!
|-------------- Subclass 3 ---- Subclass 3 Event Listener


Now my issue is that I'm not 100% sure how to handle those buttons? I've tried a couple of different approaches but I can't get it to work?

I've tried creating the two buttons in the superclass and then editing them in the subclass to write a different name but that didn't work.

I tried to create them in the subclass but then they don't show up?


I had another idea just now... I guess I could create all the buttons (like the actual buttons with proper name and text for each of the subclasses) in the superclass, set them all to not visible and only show the ones I want in each subclasses? I guess that could work (in theory anyway) but I feel like this isn't the "proper" way so it's not ideal for a school project...



Edit: All right, figured it out!
 
Last edited:

RZetko

Member
Oct 27, 2017
522
Is this a good thread to ask questions in? I'm trying to figure something out in Vue if anyone knows anything about that.

I just started learning Vue like 2 weeks ago, so I'm not the best at it. And I'm using it for web development.

Basically, I'm on a page and I have an array that I'm using. Now I have a link to another page, which I'm using a <router-link> to do that, and I'm passing a few params with it as well. But on the page I go to I need to use that same array and I'm not sure how to do this. I've tried to find my answer from the Vue documentation and also just from google searching, but no luck.

Little bit late but I can help you with that. Check out official VueX library which is used for state management. In short you can create stores (something like a global variables) with their own states, getters & setters. I use Vue on daily basis in my work and worked on multiple projects built with it so if you want any help just ask away and I'll try to help you best I can.
 

mugurumakensei

Elizabeth, I’m coming to join you!
Member
Oct 25, 2017
11,328
That's one thing. But promises are hardly better than callbacks it's all callbacks under the hood after all.
Async/Await does kinda help but you still have many of the same issues. Thinking about Async things is hard!

I like to use bluebird js for my asynchronous needs.

http://bluebirdjs.com/docs/api/promise.each.html

Asynchronous each.
There's also Promise.map which you can use to process each item in the collection if you need to rely on any modified state of the collection from the caller.
 

turbobrick

Member
Oct 25, 2017
13,085
Phoenix, AZ
Little bit late but I can help you with that. Check out official VueX library which is used for state management. In short you can create stores (something like a global variables) with their own states, getters & setters. I use Vue on daily basis in my work and worked on multiple projects built with it so if you want any help just ask away and I'll try to help you best I can.

ok. While I did end up figuring it out, I did end up checking out the vuex library which was helpful for other sections I was working on.

I ended up being able to query the info I needed in the apollo section.

This was something job related, and what makes it harder, is our company doesn't believe in documenting code. Makes it take longer to figure things out.
 
Oct 25, 2017
3,789
That's one thing. But promises are hardly better than callbacks it's all callbacks under the hood after all.
Async/Await does kinda help but you still have many of the same issues. Thinking about Async things is hard!

Promises have composibility and simplify via flatmapping which makes it much easier to intuit in highly async applications. If you find it hard to keep things in order then I'd actually recommend promises without async/await simply because it makes it much more explicit the scope in which you expect your variables to be.
 

mugurumakensei

Elizabeth, I’m coming to join you!
Member
Oct 25, 2017
11,328
Promises have composibility and simplify via flatmapping which makes it much easier to intuit in highly async applications. If you find it hard to keep things in order then I'd actually recommend promises without async/await simply because it makes it much more explicit the scope in which you expect your variables to be.

Also then / catch is an asynchronous equivalent to try / catch.

Chainability, composition, and stack trace preservation are big reasons for using promises over callbacks.

And promises is becoming the standard even in other languages such as Java and C++ for task based asynchronous programming.
 

Cyborg009

Member
Oct 28, 2017
1,241
hey guys I wanted to know does anyone know what I should do/make when I need to login to a website and check if some text has changed? This third party company we're using does reports for us but can't tell us when their system fails to pull data from our databse. I just need to login and check if text has been changed. The login part would be easy in java, python, java(selenium), even powershell but I'm not sure how I would check the text.
 
Oct 25, 2017
3,789
hey guys I wanted to know does anyone know what I should do/make when I need to login to a website and check if some text has changed? This third party company we're using does reports for us but can't tell us when their system fails to pull data from our databse. I just need to login and check if text has been changed. The login part would be easy in java, python, java(selenium), even powershell but I'm not sure how I would check the text.

Save text to file on each run. Compare with last run.
 

Megasoum

Member
Oct 25, 2017
22,568
Hey guys... So I'm almost done with my Java Swing project, trying to tweak the last couple of details and I just can't get my JTable to fit properly in the window... Anybody has an idea on how I could fix it?

So this is the constructor on my main window class... Pardon the french, I have to use french variables for everything because of school.

Code:
public FenetreRecherche() {
        
        setTitle("Média Pour Tous (MPT) - Annuaire Téléphonique");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 740, 350);
        setLocation((int)(screenSize.getWidth() / 2 ) - 370, (int)(screenSize.getHeight() / 2 ) - 175);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new GridLayout(4, 1, 0, 0));
        
        ecouteur = new FenetreRechercheEcouteur(this);
        
        
        panneauHaut = new JPanel();
        panneauHaut.setBorder(new TitledBorder(null, "Type de recherche", TitledBorder.LEFT, TitledBorder.TOP, null, new Color(0, 0, 0)));
        contentPane.add(panneauHaut);
        panneauHaut.setLayout(new GridLayout(0, 2, 0, 0));
        
        radioMatricule = new JRadioButton("Matricule");
        radioMatricule.setSelected(true);
        panneauHaut.add(radioMatricule);
        
        radioPrenom = new JRadioButton("Prénom");
        panneauHaut.add(radioPrenom);
        
        radioTous = new JRadioButton("Tous");
        panneauHaut.add(radioTous);
        
        radioNom = new JRadioButton("Nom");
        panneauHaut.add(radioNom);
        
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(radioMatricule);
        buttonGroup.add(radioPrenom);
        buttonGroup.add(radioTous);
        buttonGroup.add(radioNom);

        radioMatricule.addActionListener(ecouteur);
        radioPrenom.addActionListener(ecouteur);
        radioTous.addActionListener(ecouteur);
        radioNom.addActionListener(ecouteur);       
        
        
        panneauRecherche = new JPanel();
        FlowLayout flowLayout_1 = (FlowLayout) panneauRecherche.getLayout();
        flowLayout_1.setVgap(15);
        contentPane.add(panneauRecherche);
        
        textRecherche = new JTextField();
        panneauRecherche.add(textRecherche);
        textRecherche.setColumns(20);
        
        boutonRecherche = new JButton("Rechercher");
        panneauRecherche.add(boutonRecherche);
        boutonRecherche.addActionListener(ecouteur);
        
        panneauListe = new JPanel();
        panneauListe.setPreferredSize(new Dimension(20, 15));
        panneauListe.setOpaque(true);
        panneauListe.setVisible(false);
        contentPane.add(panneauListe);
        
        
        tableResultats = new JTable();
        tableResultats.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tableResultats.setFillsViewportHeight(true);
        tableResultats.setPreferredScrollableViewportSize(new Dimension(700, 70));
        modelListe = creerModeleAvecColonnesNonEditables();
        tableResultats.setModel(modelListe);
        tableResultats.setRowSelectionInterval(0, 0);
        
        tableResultats.getColumnModel().getColumn(0).setResizable(false);
        tableResultats.getColumnModel().getColumn(0).setPreferredWidth(50);
        tableResultats.getColumnModel().getColumn(1).setResizable(false);
        tableResultats.getColumnModel().getColumn(1).setPreferredWidth(65);
        tableResultats.getColumnModel().getColumn(2).setResizable(false);
        tableResultats.getColumnModel().getColumn(2).setPreferredWidth(92);
        tableResultats.getColumnModel().getColumn(3).setResizable(false);
        tableResultats.getColumnModel().getColumn(3).setPreferredWidth(20);
        tableResultats.getColumnModel().getColumn(4).setResizable(false);
        tableResultats.getColumnModel().getColumn(4).setPreferredWidth(20);   

        
        JScrollPane scrollPane = new JScrollPane(tableResultats);
        scrollPane.setPreferredSize(new Dimension(700, 60));
        panneauListe.add(scrollPane);
        
        JPanel panelBoutons = new JPanel();
        FlowLayout fl_panelBoutons = (FlowLayout) panelBoutons.getLayout();
        fl_panelBoutons.setVgap(20);
        fl_panelBoutons.setAlignment(FlowLayout.RIGHT);
        contentPane.add(panelBoutons);
        
        boutonAjouter = new JButton("Ajouter");
        panelBoutons.add(boutonAjouter);
        boutonAjouter.addActionListener(ecouteur);
        
        boutonModifier = new JButton("Modifier");
        panelBoutons.add(boutonModifier);
        boutonModifier.addActionListener(ecouteur);
        boutonModifier.setEnabled(false);
        
        boutonSupprimer = new JButton("Supprimer");
        panelBoutons.add(boutonSupprimer);
        boutonSupprimer.addActionListener(ecouteur);
        boutonSupprimer.setEnabled(false);
        
        boutonAfficher = new JButton("Afficher");
        panelBoutons.add(boutonAfficher);
        boutonAfficher.addActionListener(ecouteur);
        boutonAfficher.setEnabled(false);
        
        boutonFermer = new JButton("Fermer");
        panelBoutons.add(boutonFermer);
        boutonFermer.addActionListener(ecouteur);
    }

Now this is totally functional but it comes out looking like this:

l5eLzFk.png


The JTable is ok width wise but it looks really dumb with basically only 3 rows visible and the ton of whitespace before and after in the window. I tried to play around with some of the values for "panneauListe" which is the panel controlling the table but no matter how much I change the numbers, the table doesn't actually change at all?

Thanks!
 

ss_lemonade

Member
Oct 27, 2017
6,659
While this isn't exactly a programming-type question, I was wondering if anyone knew the answer to this: is Android Chrome known for sending duplicate POST requests? Like literal, sub-second duplicate requests? I asked this question once on Stackoverflow and nobody answered. Whenever I try searching for information on this, I only find a handful of people experiencing the same issue but no concrete info on what exactly is going on.

It happens so sporadically too that it makes it hard to debug. I only see hints of it happening from web server logs (this is where I see the Android user agent) and application logs (eg. my web app throwing exceptions from attempts to insert duplicate data to a database table, or random db lock timeouts when request updates a specific database table row)
 
Oct 25, 2017
3,789
While this isn't exactly a programming-type question, I was wondering if anyone knew the answer to this: is Android Chrome known for sending duplicate POST requests? Like literal, sub-second duplicate requests? I asked this question once on Stackoverflow and nobody answered. Whenever I try searching for information on this, I only find a handful of people experiencing the same issue but no concrete info on what exactly is going on.

It happens so sporadically too that it makes it hard to debug. I only see hints of it happening from web server logs (this is where I see the Android user agent) and application logs (eg. my web app throwing exceptions from attempts to insert duplicate data to a database table, or random db lock timeouts when request updates a specific database table row)

Ajax or actual HTML form?
 
Oct 25, 2017
3,789
Normal form. I also added some client side javascript to disable the submit button on click but all that obviously does is prevent user errors like double submits. Not microsecond duplicate post requests

So you are using javascript for posting? I'm not clear.

I would be very surprised to learn a typical HTML form with no js could produce this and it would be very difficult to debug. More likely, I think it's probably a double-submit either due to the way the event handlers work or some other weird client thing. Either way the second scenario is easier to debug so try submitting with script instead.
 

ss_lemonade

Member
Oct 27, 2017
6,659
So you are using javascript for posting? I'm not clear.

I would be very surprised to learn a typical HTML form with no js could produce this and it would be very difficult to debug. More likely, I think it's probably a double-submit either due to the way the event handlers work or some other weird client thing. Either way the second scenario is easier to debug so try submitting with script instead.
No, I don't use Javascript to submit the form. I just disable the button when the form is submitted to prevent instances where the user accidentally double clicks on the submit button. Even without this Javascript in place though, I was still seeing this double submit phenomenon and according to web server access logs, the user agent always showed Android Chrome devices doing it.
 

ss_lemonade

Member
Oct 27, 2017
6,659
So you are using javascript for posting? I'm not clear.

I would be very surprised to learn a typical HTML form with no js could produce this and it would be very difficult to debug. More likely, I think it's probably a double-submit either due to the way the event handlers work or some other weird client thing. Either way the second scenario is easier to debug so try submitting with script instead.
So I looked at my web server logs today because I saw the issue happen again (it triggered a deadlock warning on a mysql database innodb table row that the POST request was supposed to run an update query on using PHP) and found 5 duplicate requests at the exact same second from the same IP address, again with an android chrome device user agent.

I honestly have no idea anymore why I keep seeing sporadic duplicate requests and why they always (from what I noticed) come from android devices using Chrome.
 

mugurumakensei

Elizabeth, I’m coming to join you!
Member
Oct 25, 2017
11,328
Vue > React. That's all I have to say about JS frameworks. Angular doesn't exist to me.
 

phisheep

Quis Custodiet Ipsos Custodes
Member
Oct 26, 2017
4,762
I need some help guys.

After happily getting back into coding with Python, and getting reasonably competent with it, I decided to spread my wings a bit and try my hand at C. Getting along swimmingly with reading books and reading code on GitHub.

But, I haven't been able to get myself set up with a compiler and environment on Windows. I'm no slouch technically, but I downloaded Visual Studio and can't make head nor tail out of how to compile and run things.

Is there any really basic guide about what to do to get set up? Or something other than the impenetrable Visual Studio that I should be using instead?
 

Barls

Member
Oct 25, 2017
277
I need some help guys.

After happily getting back into coding with Python, and getting reasonably competent with it, I decided to spread my wings a bit and try my hand at C. Getting along swimmingly with reading books and reading code on GitHub.

But, I haven't been able to get myself set up with a compiler and environment on Windows. I'm no slouch technically, but I downloaded Visual Studio and can't make head nor tail out of how to compile and run things.

Is there any really basic guide about what to do to get set up? Or something other than the impenetrable Visual Studio that I should be using instead?

I've enjoyed using VS Code with the python plug ins. You can have a command prompt as a side bar and compile/run all in the same window.

A quick glance looks like this will be helpful.

Nevermind - I just reread your post and it says C, not Python...
 
Last edited:

ChrisR

Member
Oct 26, 2017
6,797
Google fuck anyone else over today with their API Platform changes?

Going to have to retool the very small website my company hosts because fuck paying $1000 a month
 

MotiD

Member
Oct 26, 2017
1,560
I'm trying to write a function that receives a string from main and determines which words are even and which are odd, and only print the words that are even
The way I'm thinking about this is let's say I received the string 'Reset Era is not even' - I go over the string letter by letter and use a counter, while also copying each letter into a new string. The moment I detect space (' ') I stop and if the counter is divisible by 2 with no remainder I print the new array. In any case I want to wipe the new array so it copies every word on its own.

This is my attempt at going over the string letter by letter and copying it into a new one, but it ends up crashing and I'm not sure why?
Code:
#define _CRT_SECURE_NO_WARNINGS
#define SIZE 80
#include <stdio.h>
#include <stdlib.h>

char *evenorodd(char *str)
{
    int count = 0;
    char *newstr;
    newstr = str;
    *newstr = (char*)malloc(SIZE * sizeof(char));
    while (*str)
    {
        while (*str != ' ') {
            *newstr = *str;
            newstr++;
            str++;
            count++;
        }
    }
    puts(newstr);
}

int main()
{
    int result;
    char strmain[SIZE];
    gets(strmain);
    result = evenorodd(strmain);

    return 0;
}

I'm very new to pointers and memory allocation so I know for sure I must be doing some things wrong :p

Edit: Alright, found out why it was crashing (forget to add ++ in the while loop to str), but it's still not working as intended
 
Last edited:

mugurumakensei

Elizabeth, I’m coming to join you!
Member
Oct 25, 2017
11,328
Not incrementing the str pointer for one. So, it's an infinite loop. newstr is getting incremented so eventually you write out of the programs memory bounds producing a segfault.
 

erd

Self-Requested Temporary Ban
Banned
Oct 25, 2017
1,181
I'm trying to write a function that receives a string from main and determines which words are even and which are odd, and only print the words that are even
The way I'm thinking about this is let's say I received the string 'Reset Era is not even' - I go over the string letter by letter and use a counter, while also copying each letter into a new string. The moment I detect space (' ') I stop and if the counter is divisible by 2 with no remainder I print the new array. In any case I want to wipe the new array so it copies every word on its own.

This is my attempt at going over the string letter by letter and copying it into a new one, but it ends up crashing and I'm not sure why?

I'm very new to pointers and memory allocation so I know for sure I must be doing some things wrong :p

Edit: Alright, found out why it was crashing (forget to add ++ in the while loop to str), but it's still not working as intended

I haven't programmed in C in a while, so I hope I'm not talking nonsense, but aside from not incrementing str, I see a lot of problems with this code:
  • evenodd() is defined to return a char*, but result in result = evenorodd(strmain) is an integer. Not really relevant at the moment, but should still be fixed.
  • I don't fully understand your initialization of newstr. If you want to initialize it to a new block of memory with malloc, then *newstr = (char*)malloc(SIZE * sizeof(char)); doesn't work, since the malloc returns a char pointer, while *newstr is just a char. Should be just newstr. In your case, you first assign newstring to point to the same location as str, and then change the first character of str to something random. I doubt that's what you want to do. There probably is a way to reuse the address of str, but just allocating a new block of memory is much simpler
Apart from that, the biggest problem is that unless you end your input with a space, you'll still have an infinite loop since the program will be stuck in the inner loop, while only the outer loop checks for the end of the string.

Then there's the newstr, which just doesn't really work yet:
  • First, it's not null terminated. In C, a string is a collection of bytes followed by a null terminator (a zero byte) that signifies the string ends there. Otherwise, the string just keeps on going.
  • You edit it with a pointer (newstr), which is fine - you add a character with *newstr = *str and increment the pointer to the next spot with newstr++. Unfortunately, you don't save the starting address of the string, so when you get to puts(newstr), you're telling it to print from the location of the newstr pointer, which is at the end of the string.
I hope this helps. I suck at C, so I can't really tell you how to fix these things properly. By fixing the above issues I got the following code, but it's probably REALLY, REALLY BAD. It hopefully at least shows the mistakes in your code though. It currently just prints each word and its length:
Code:
#define _CRT_SECURE_NO_WARNINGS
#define SIZE 80
#include <stdio.h>
#include <stdlib.h>

int evenorodd(char *str)
{
    int count = 0;
    char *newstr;
    //newstr = str;
    // Change the initialization to just initialize a new string, instead of reusing str
    newstr = (char*)malloc(SIZE * sizeof(char));
    // Remember the start of the str
    char * startstr = newstr;
    while (*str != 0)
    {
        count = 0;
        // Fix being stuck in the inner loop
        while (*str != ' ' && *str != 0) {
            *newstr = *str;
            newstr++;
            str++;
            count++;
        }
        // Null terminate newstr
        *newstr = 0;
        printf("%d, %s\n", count, startstr);
        newstr = startstr;
        // I use this to break out of the loop, making the above check useless. 
        // There are probably better ways to do this.
        if (*str == 0) {
            break;
        }
        str++;
    }
    free(newstr);
    return 0;
}

int main()
{
    int result;
    char strmain[SIZE];
    gets(strmain);
    result = evenorodd(strmain);
    return 0;
}
I also don't know if it will work in your compiler, since I used Visual Studios C++ compiler.
 

metaprogram

Member
Oct 28, 2017
1,174
I need some help guys.

After happily getting back into coding with Python, and getting reasonably competent with it, I decided to spread my wings a bit and try my hand at C. Getting along swimmingly with reading books and reading code on GitHub.

But, I haven't been able to get myself set up with a compiler and environment on Windows. I'm no slouch technically, but I downloaded Visual Studio and can't make head nor tail out of how to compile and run things.

Is there any really basic guide about what to do to get set up? Or something other than the impenetrable Visual Studio that I should be using instead?

Sorry for the late response.

1. File -> New -> Project
2. Visual C++ -> Windows Console Application. Enter a name and press enter.
3. Type your code in the auto-generated .cpp file that appears at the end.
4. Build Menu > Build Solution
5. Once it compiles successfully, F5 to run your program.
 

metaprogram

Member
Oct 28, 2017
1,174
I'm trying to write a function that receives a string from main and determines which words are even and which are odd, and only print the words that are even
The way I'm thinking about this is let's say I received the string 'Reset Era is not even' - I go over the string letter by letter and use a counter, while also copying each letter into a new string. The moment I detect space (' ') I stop and if the counter is divisible by 2 with no remainder I print the new array. In any case I want to wipe the new array so it copies every word on its own.

This is my attempt at going over the string letter by letter and copying it into a new one, but it ends up crashing and I'm not sure why?
Code:
#define _CRT_SECURE_NO_WARNINGS
#define SIZE 80
#include <stdio.h>
#include <stdlib.h>

char *evenorodd(char *str)
{
    int count = 0;
    char *newstr;
    newstr = str;
    *newstr = (char*)malloc(SIZE * sizeof(char));
    while (*str)
    {
        while (*str != ' ') {
            *newstr = *str;
            newstr++;
            str++;
            count++;
        }
    }
    puts(newstr);
}

int main()
{
    int result;
    char strmain[SIZE];
    gets(strmain);
    result = evenorodd(strmain);

    return 0;
}

I'm very new to pointers and memory allocation so I know for sure I must be doing some things wrong :p

Edit: Alright, found out why it was crashing (forget to add ++ in the while loop to str), but it's still not working as intended

TL;DR is that you're using memory allocation incorrectly. The good news is, you don't even need memory allocation for this problem. Think about your problem statement. "Scan the letters of a string, print only those words that have even number of characters." Nowhere here is there anything about copying memory. That's something you made up. Just do what the problem says. scan the letters, only print the words that have even number of characters.

Code:
void printWord(char *Start, char *End) {
{
  int WordLength = End - Start;
  if (WordLength % 2 != 0)
    return;

  // print each character of the word up until the space.
  while (Start != End) {
    putchar(*Start);
    ++Start;
  }
  // print a space so that consecutive even words are separated.
  putchar(' ');
}

void evenorodd(char *str) {
  char *WordStart = str;
  char *CurrentChar = str;

  // Repeat until we encounter a null terminator
  while (*CurrentChar != '\0') {
    if (*CurrentChar == ' ') {
      printWord(WordStart, CurrentChar);


      // Skip any spaces
      while (*CurrentChar == ' ' && *CurrentChar != '\0')
        ++CurrentChar;

      // We are at the beginning of a new word.
      WordStart = CurrentChar;
    } else {
      ++CurrentChar;
    }
  }
  // Make sure to handle the last word
  printWord(WordStart, CurrentChar);
}
 

iareharSon

Member
Oct 30, 2017
8,940
I'm not sure if this is the best place to ask, but...

So we use Access to enter payroll information for a Youth jobs program. It houses client information, bi-weekly payroll information, etc. Up until now, it has been updated directly through a form within Access since we were using paper time cards. We're moving to an online time card system this Summer, so we're wanting to be able to run a report from that system - and upload the timecard information into Access. This is what the Payroll table currently tracks: https://i.imgur.com/dD1rVMe.png

The online time card system we're moving to only supplies an email address for the client (that's their username), the Regular / OT / DT hours worked, and the Pay Period End Date.

I want to just be able to just import an excel spreadsheet from the online time card system to a table and pull in the missing information. How would I do the following DLookup? So I have a table called tblClient that has the information I need. I'm making a new table called tblTSheets, and I want a certain field to pull a field called SocSecNumber from tblClient depending on if the field Username from tblTsheets matches the field Email from tblTSheets.
 

The Grizz

Member
Oct 27, 2017
2,457
So I'm not a programmer, like at all, but work with plenty of them as a BSA. I was tricked into going to a 1.5 hour lunch and learn and work titled 'Lambda Calculus and Functional Programming'. I was told there would be free lunch. There was no free lunch, only a room full of programmers who were all very intrigued and then myself, who could barely keep my head up and eyes open.

Are you people really into this lambda calculus thing? Apparently it was the basis for functional programming, or something like that?
 

metaprogram

Member
Oct 28, 2017
1,174
It's the theoretical basis for computation, but most people nowadays just think it makes them sound smart so they like to talk about it and throw words around to demonstrate how hip they are
 

Gamespawn

Member
Oct 25, 2017
854
Hey everyone, have a problem I need help with. I'm trying to grab values from a xml file and put them in a SQL table. There seems to be a problem with my loop because only the last record is sent through. would anyone be willing to take a look at my code?

Code:
<?php
$username="root";
$password="";
$hostname="localhost";
$dbname="myDavinci";



$conn = new mysqli($hostname, $username, $password, $dbname) or die('Couldnt connect to mysql');

$xml = simplexml_load_file("cd_catalog.xml") or die ("Cannot Get Values");

foreach ($xml->CD as $row) {

    
    $title=$row->TITLE;
    $artist=$row->ARTIST;
    $country=$row->COUNTRY;
    $company=$row->COMPANY;
    $price=$row->PRICE;
    $year=$row->YEAR;
    

    $sql="insert into myCD (title,artist,country,company,price,year) values ('$title','$artist','$country','$company','$price','$year')";
    

}

if ($conn->multi_query($sql) === TRUE) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}


$conn->close();

?>
 
Last edited:

mugurumakensei

Elizabeth, I’m coming to join you!
Member
Oct 25, 2017
11,328
Been a while since I worked with PHP but you're setting sql to a string in the loop. It's going to take the last value in the loop. You need to concatenate the string not reset in every iteration.
 

ry-dog

Attempted to circumvent ban with alt account
Banned
Oct 25, 2017
2,180
Anyone familiar with android, because I'm not haha.

So I have my sql lite database and content provider up and running. When it comes to displaying the data (I'm using a list view) I want to sort it according to a complex sorting algorithm I've planned out.

Would creating an array of objects (holding a row each), sorting them, and then using an array adapter to display them be horribly inefficient? Or should I just create a custom cursor adapter and figure out how to sort in that.
 
Last edited:

Theonik

Member
Oct 25, 2017
852
It all depends on how big your list is. Consider your approach will pull the whole list, sort it and then you need to store it all in memory.
You should balance the implementation cost with any speed gain and that depends on how big you expect the actual cost to be.