• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Koren

Member
srand(x) redefines the seed, it must be called exactly once, and must be before the first call of the rand() function

Even if you put it on the dice roll file, you will have to create an unique function for it, and would have to call it in main. So Its better to just use it directly in main
You can put in in the dice function too...

Code:
int Roll(const int nbsides) {
 static bool init=false;

 if (init == false) {
 srand(time(NULL));
 init = true; 
 }

 return rand() % nbsides; 
}

Not as efficient (a bool on the heap and a test for each call), but I sometimes like to put the initialization inside the function itself, you can prevent people using the function without initializing it this way.
 
You can put in in the dice function too...

Code:
int Roll(const int nbsides) {
 static bool init=false;

 if (init == false) {
 srand(time(NULL));
 init = true; 
 }

 return rand() % nbsides; 
}

Not as efficient (a bool on the heap and a test for each call), but I sometimes like to put the initialization inside the function itself, you can prevent people using the function without initializing it this way.

Err... Don't do this. First of all it's not thread safe. Second of all srand() affects the global seed, so now you're saying that nobody else in your entire program except thsi function is allowed to generated random numbers for any reason. Including if you statically link a library which requires generates random numbers.

Seriously, junk like this is the reason C++ came along with a much better random number system. You don't have to mess around with the seed. Here's some code to roll a dice that doesn't suck.

Code:
#include <random>
std::default_random_engine generator;

int roll(int sides)
{
    std::uniform_int_distribution<int> distribution(1,sides);
    return distribution(generator);  // generates number in the range 1..6
}

You don't need to understand it. Just copy it.

Note that you don't want to declare the generator in the function, because that will re-seed it every time.
 

Koren

Member
Err... Don't do this. First of all it's not thread safe.
As far as I remember, rand() itself is not thread safe. What are you talking about, srand in a thread or rand itself?

Second of all srand() affects the global seed, so now you're saying that nobody else in your entire program except thsi function is allowed to generated random numbers for any reason.
That's actually a bit dramatic, I think, or I miss something... Obviously, you don't want to reseed often, especially with something so weak than time(NULL). Seeding twice may cause issues, should you for example require several random numbers elsewhere in the same second and calling this in the middle. I suspect it won't cause too many issues in many cases, though.

Programs that need really good random won't use rand anyway.

But I agree that you shouldn't be doing this everywhere, and I shouldn't have suggested it. I still think that forcing initialization at first use or at least checking it can help avoiding issues.

Seriously, junk like this is the reason C++ came along with a much better random number system. You don't have to mess around with the seed.
I agree, your example is what I use most of the time, but he said "easiest". It usually takes me a couple try to get the correct command when I need it (and I don't have my memorandum handy). And isn't the support still not perfect?

You don't need to understand it. Just copy it.
I'm not sure that's a good way to look at things, you'll also get a lot of junk in code if people are just copying solutions found on stackexchange and similar sources... The comment about seeding that follow actually proves it, I think.
 
That's actually a bit dramatic, I think, or I miss something... Obviously, you don't want to reseed often, especially with something so weak than time(NULL). Seeding twice may cause issues, should you for example require several random numbers elsewhere in the same second and calling this in the middle. I suspect it won't cause too many issues in many cases, though.

What I mean is, srand() affects global state of your entire program that anyone else in your entire program that calls rand() depends on. This is why srand() is usually called early in main, because you don't always have control over every line of code compiled into your program. Imagine if there was some library that depended on being able to call rand(), and now in your program you had to make sure you called "rollDice" before that library code executed.

FWIW I always forget how to call c++ random number generator too. Luckily you can google "c++ random" and click on the link that says <random>, which is usually first or second, and the code you need is right there.

Only excuse to ever use rand for any reason at all is if you're in an environment where C++ is banned.

In fact, I would argue that despite having to type a few extra colon and lines of code, the c++ method *is* the easiest, for the simple reason that it actually does what you expect in all circumstances.
 

Koren

Member
Imagine if there was some library that depended on being able to call rand(), and now in your program you had to make sure you called "rollDice" before that library code executed.
The library can still call rand(), especially if it calls srand() before...

The biggest problem I can see is that two srand at the same second will cause rand() results between the two calls being duplicated after the second call.

FWIW I always forget how to call c++ random number generator too. Luckily you can google "c++ random" and click on the link that says <random>, which is usually first or second, and the code you need is right there.
This is the kind of things I keeps as snippets... I often code in bullet trains, for example, and I don't want to rely on being able to reach the Internet ^_^

I regularly need to freeze the seed, too (so that I can debug an algorithm by always getting the same random values).

Only excuse to ever use rand for any reason at all is if you're in an environment where C++ is banned.
How is the support? I barely use anything else than g++ and cland, currently...

In fact, I would argue that despite having to type a few extra colon and lines of code, the c++ method *is* the easiest, for the simple reason that it actually does what you expect in all circumstances.
Fair enough...
 

Ambitious

Member
This semester, I did a group assignment for a lecture together with another guy. He seriously had the worst code style I've ever seen. Or rather, he didn't have any style at all. It was an inconsistent mess.

- Several methods without any blank lines to visually separate different parts. Absolutely unnecessary blank lines in other locations (e.g. a catch block starting with a blank line, followed by a generated printStackTrace). No spaces around operators. No space between an if/try and the following opening bracket.
- Lack of indentation in many, many blocks. Apparently random indentation in some methods: Some lines were properly indented, then a few were too far to the right, then a few were too far to the left, and so on.
- Incomprehensible variable names, many of them just two to three letters long. Variable names in multiple languages (some in English, some in German). Some in camel case, most of the time in lowercase.

He even wrote a class with a lowercase name. Let that sink in. A class with a lowercase name. He really couldn't give less of a shit, I guess.

And that's just the code style. The actual code sucked too. Half-broken crap, cobbled together from code he copied from me.
 

JesseZao

Member
This semester, I did a group assignment for a lecture together with another guy. He seriously had the worst code style I've ever seen. Or rather, he didn't have any style at all. It was an inconsistent mess.

- Several methods without any blank lines to visually separate different parts. Absolutely unnecessary blank lines in other locations (e.g. a catch block starting with a blank line, followed by a generated printStackTrace). No spaces around operators. No space between an if/try and the following opening bracket.
- Lack of indentation in many, many blocks. Apparently random indentation in some methods: Some lines were properly indented, then a few were too far to the right, then a few were too far to the left, and so on.
- Incomprehensible variable names, many of them just two to three letters long. Variable names in multiple languages (some in English, some in German). Some in camel case, most of the time in lowercase.

He even wrote a class with a lowercase name. Let that sink in. A class with a lowercase name. He really couldn't give less of a shit, I guess.

And that's just the code style. The actual code sucked too. Half-broken crap, cobbled together from code he copied from me.

Ugh. Coding group projects for class can be the worst. I had a guy once, who flat out said, "I'm taking this class again, so I have all of the code we'd need for this project. Don't worry, I got 100% on all of the group work. I just did bad on the individual stuff."

Sure enough, I would look at some code he would write for a module and it was literally the example code from the book with the book variables and everything. I don't know how he got as far as he did. Code travels through his head, but nothing is processed before it's spit out.
 
This semester, I did a group assignment for a lecture together with another guy. He seriously had the worst code style I've ever seen. Or rather, he didn't have any style at all. It was an inconsistent mess.

- Several methods without any blank lines to visually separate different parts. Absolutely unnecessary blank lines in other locations (e.g. a catch block starting with a blank line, followed by a generated printStackTrace). No spaces around operators. No space between an if/try and the following opening bracket.
- Lack of indentation in many, many blocks. Apparently random indentation in some methods: Some lines were properly indented, then a few were too far to the right, then a few were too far to the left, and so on.
- Incomprehensible variable names, many of them just two to three letters long. Variable names in multiple languages (some in English, some in German). Some in camel case, most of the time in lowercase.

He even wrote a class with a lowercase name. Let that sink in. A class with a lowercase name. He really couldn't give less of a shit, I guess.

And that's just the code style. The actual code sucked too. Half-broken crap, cobbled together from code he copied from me.

Class with a lowercase name isn't the worst thing i can think of, the entire STL uses that style, as does boost
 
Only excuse to ever use rand for any reason at all is if you're in an environment where C++ is banned.
Even then, it's still not a great idea- there's other, much better sources of randomness that can be used in C programs or kernel modules. Linux developers generally recommend using /dev/{u}random, or get_random_bytes() if you're in a module. There's generally always something that provides a better source of randomness than what rand() would provide.

This semester, I did a group assignment for a lecture together with another guy. He seriously had the worst code style I've ever seen. Or rather, he didn't have any style at all. It was an inconsistent mess.
I had this problem my first two and a half years of college CS courses. In some cases, I would put enough pressure on the other group members early enough that they'd drop the course (and then merge with another group who also had members drop), or in other cases just muscle through it. It's not working having to spend more hours fixing up someone else's broken code than just writing it yourself.
 
This semester, I did a group assignment for a lecture together with another guy. He seriously had the worst code style I've ever seen. Or rather, he didn't have any style at all. It was an inconsistent mess.

- Several methods without any blank lines to visually separate different parts. Absolutely unnecessary blank lines in other locations (e.g. a catch block starting with a blank line, followed by a generated printStackTrace). No spaces around operators. No space between an if/try and the following opening bracket.
- Lack of indentation in many, many blocks. Apparently random indentation in some methods: Some lines were properly indented, then a few were too far to the right, then a few were too far to the left, and so on.
- Incomprehensible variable names, many of them just two to three letters long. Variable names in multiple languages (some in English, some in German). Some in camel case, most of the time in lowercase.

He even wrote a class with a lowercase name. Let that sink in. A class with a lowercase name. He really couldn't give less of a shit, I guess.

And that's just the code style. The actual code sucked too. Half-broken crap, cobbled together from code he copied from me.

Boy you're in for a surprise when you get out into industry (wrt variable/class naming and conventions).
 

Kieli

Member
I don't understand how these folks even make it past data structures, algorithms, computer architecture, and other weeder courses designed to filter them out...
 

Makai

Member
I worked on an enterprise project where every field was public. Each field has probably 100 references in multiple classes.
 

Slavik81

Member
As a C++ guy dipping my fingers in NodeJS, I'm blown away by how everything is tied together with shoe string. There's a billion tutorials for everything, half of them are garbage, three-quarters of them are outdated because they're a whole 2 years old and the functions they use are deprecated.

Most frustratingly: almost no libraries contain documentation explaining how they actually work. Every library is a magical wand designed so you don't have to know anything. The documentation thus tells you nothing but how to plug it in. This assures that you will do something wrong, because you don't understand what you're doing.

I'm looking at session cookies, for instance. Every tutorial I've seen has put the session secret as a literal text string in program source code, and they've all just been stuff like '5ec|2et'. None of them actually mention what this secret is used for, how to choose it, how to keep it safe, what attacks to worry about, and what to do if it gets leaked, or what happens if you change it.

Maybe I'm just an ignorant non-webdev and everybody else has the background knowledge of HTTP and other aspects of development, so they look at a library and just know how it works. On the other hand, I have a sneaking suspicion that more than a few node-based websites use the strings 'keyboard cat', 'topsecret', 'S3CRE7', or 'blargadeeblargblarg' as their session secrets.
 

Ambitious

Member
Class with a lowercase name isn't the worst thing i can think of, the entire STL uses that style, as does boost

But it was a Java project, and all other classes had camel case names. Just not this one.

Even then, it's still not a great idea- there's other, much better sources of randomness that can be used in C programs or kernel modules. Linux developers generally recommend using /dev/{u}random, or get_random_bytes() if you're in a module. There's generally always something that provides a better source of randomness than what rand() would provide.


I had this problem my first two and a half years of college CS courses. In some cases, I would put enough pressure on the other group members early enough that they'd drop the course (and then merge with another group who also had members drop), or in other cases just muscle through it. It's not working having to spend more hours fixing up someone else's broken code than just writing it yourself.

Merging with other groups wasn't possible, unfortunately. We had to work in pairs, and the course happened to have an even number of attendees.

I really couldn't write his part by myself. My part was more than enough work. The assignment was a high-concurrency distributed system with several different actors, and I spent like ten hours alone just hunting down deadlocks and race conditions while keeping the throughput as high as possible. In addition to just writing the code, taking over his part would have required me to re-familiarize with a technology I haven't worked with in years, and it's not like I don't have any other assignments for other courses. There just wasn't enough time.

I don't understand how these folks even make it past data structures, algorithms, computer architecture, and other weeder courses designed to filter them out...

Strangely enough, he has way more work experience than me. He used to work at a well-known Mac software developer, and currently he's with a medium-size company which works on aviation systems.

I worked on an enterprise project where every field was public. Each field has probably 100 references in multiple classes.

I worked on an enterprise project which had a truckload of methods that were each several hundred lines long, most of it copy-paste code full of errors.
 
As a C++ guy dipping my fingers in NodeJS, I'm blown away by how everything is tied together with shoe string. There's a billion tutorials for everything, half of them are garbage, three-quarters of them are outdated because they're a whole 2 years old and the functions they use are deprecated.

Most frustratingly: almost no libraries contain documentation explaining how they actually work. Every library is a magical wand designed so you don't have to know anything. The documentation thus tells you nothing but how to plug it in. This assures that you will do something wrong, because you don't understand what you're doing.

I'm looking at session cookies, for instance. Every tutorial I've seen has put the session secret as a literal text string in program source code, and they've all just been stuff like '5ec|2et'. None of them actually mention what this secret is used for, how to choose it, how to keep it safe, what attacks to worry about, and what to do if it gets leaked, or what happens if you change it.

I have had zero problems like that and I use Node every single day, both at work and on my free time. Any examples of libraries that you use that have had inadequate documentation (tutorials not withstanding)?

For example, Connect (and Express) both use https://github.com/expressjs/cookie-session, which states that:

keys

The list of keys to use to sign & verify cookie values. Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation.

secret

A string which will be used as single key if keys is not provided.

That pretty much answers what it is and what attacks to worry about, what to do if it gets leaked or what happens if you change it. How to keep it safe?

1. Don't allow raw access to the file on your server (which should be obvious enough)
2. Don't put the secret your source control

How to do this? Put the file into it's configuration file, for example .config, prevent it from getting to source control (with something like .gitignore), prevent your server from ever serving any dotfiles, require it and use the value throughout your program.

I can how this information should most likely be on every tutorial out there, but security is always the coders responsibility first and if you don't know how to handle potentially sensitive data, you shouldn't probably be handling sensitive data in the first place. How disastrous would a session secret leak be then? Not at all or very, I guess.
 

Trident

Loaded With Aspartame
Huh? How do you convert "4.2" to an integer ignoring the decimal and get 420? I'm not following

That'll teach me to drive-by post and not follow up. Basically this:

Iterate through the characters, ensuring each one is between '0' and '9' (or '.') as a sanity check. If there's only one character after the '.', append a zero. If there is no '.', append two zeroes. If there's more than two characters after the '.', that's another good sanity check that the input was faulty. (If there's multiple '.', that's another sanity check)

Finally, remove the '.' char and convert the string to an int.

Not the shortest solution, but it's logically straight forward, inherently involves a lot of sanity checks, and doesn't rely on knowing how the machine handles floats.
 

Slavik81

Member
I have had zero problems like that and I use Node every single day, both at work and on my free time. Any examples of libraries that you use that have had inadequate documentation (tutorials not withstanding)?
As one example, I struggled to find any information about what precompilation actually did for handlebars and nunjucks. Marko was the only templating engine for which I could find any sample output. Though, once I saw what Marko was doing, nunjucks made a lot more sense to me. I gave Handlebars one last look-over, and decided it would require more research to figure out how it worked, so I installed nunjucks.

Though, there's still a bit of magic. For some reason, you pass your express app to have nunjucks configure it. A bug report actually gave me a much better idea of what it was doing than the documentation.

One other notable example was when or why you get url-encoded bodies vs json-encoded bodies. Everywhere I looked, I saw people saying that directly using bodyParser was deprecated, so you needed to replace it with bodyParser.json and bodyParser.urlencoded. Of course, presumably they're two separate calls because you may not actually need both, but in the half-dozen conversations I saw about porting, nobody actually ever mentioned that you only need the json parser if you've explicitly set your form to use a json body upon post. Maybe that was obvious to everyone else.

Perhaps I'm just overly cautious, but I want to know what every option I set does, and the purpose of every line of code in my program. From libraries I directly depend on, I just need a general idea of their architecture, and a solid grasp of the principles to avoid doing something slow or stupid with them.

At the moment, I'm inspecting the JavaScript bindings for Argon2, because I don't trust them. Though, that's an entirely different problem. And one for another day, actually. It's time for me to sleep.

That pretty much answers what it is and what attacks to worry about, what to do if it gets leaked or what happens if you change it. How to keep it safe?

1. Don't allow raw access to the file on your server (which should be obvious enough)
2. Don't put the secret your source control

How to do this? Put the file into it's configuration file, for example .config, prevent it from getting to source control (with something like .gitignore), prevent your server from ever serving any dotfiles, require it and use the value throughout your program.

I can how this information should most likely be on every tutorial out there, but security is always the coders responsibility first and if you don't know how to handle potentially sensitive data, you shouldn't probably be handling sensitive data in the first place. How disastrous would a session secret leak be then? Not at all or very, I guess.
I was looking at express-session, which is less clear about how the secret is used.

Though, even the cookie-session docs could use improvement. When I think about keys, I usually think of ssh keys, gpg keys or ssl keys. All of which are generated with specific commands, and have specific format requirements. A recommendation on how to choose your keys might be a nice addition. I'm not entirely sure how much entropy is required, but I used `head -c 64 /dev/random | base64` and grabbed the first ~60 characters of the output. I'm guessing that's long enough.
 
As one example, I struggled to find any information about what precompilation actually did for handlebars and nunjucks. Marko was the only templating engine for which I could find any sample output. Though, once I saw what Marko was doing, nunjucks made a lot more sense to me. I gave Handlebars one last look-over, and decided it would require more research to figure out how it worked, so I installed nunjucks.

...

Perhaps I'm just overly cautious, but I want to know what every option I set does, and the purpose of every line of code in my program. From libraries I directly depend on, I just need a general idea of their architecture, and a solid grasp of the principles to avoid doing something slow or stupid with them.

I understand where you are coming from and I think that your C++ background creates the "issue" in the second paragraph, which directly reflects to the first point: you are micro-optimizing things before you have even started.

For example with picking the templating language, do you really need to know what the precompiled output looks like? Unless you are either developing the parser or developing the compiler: most likely not. Performance obviously matters, but can you make educated guesses how performant a templating language is just by glancing at the compiled code? You could, but still you could have easily measured the performance of two or five or ten templating languages while you were at it.

There's an obvious difference between "what is does", "how it does it" and "how exactly line-by-line it does it". For someone looking for a templating language, the first point and second points are usually the ones they are interested in.

For example Handlebars compiles template like this:

Code:
<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>

with context like this:
Code:
var context = {title: "My New Post", body: "This is my first post!"};

to something that looks like this:

Code:
<div class="entry">
  <h1>My New Post</h1>
  <div class="body">
    This is my first post!
  </div>
</div>

and it took like a fraction of an second. Do you like the syntax? Is the syntax robust enough for you? If yes, then Handlebars might be a good choice for you. If turns out it isn't, you can change it relatively easily later. I am not saying that you shouldn't be critical when choosing the libraries you'll want to use, but by going through everything line-by-line you'll never get any actual work done.

The trust issue much more harder to overcome. If you cannot trust the libraries you are using, why use libraries?

JavaScript has pretty amazing debugging tools though if you want to step through the code line by line.

Though, even the cookie-session docs could use improvement. When I think about keys, I usually think of ssh keys, gpg keys or ssl keys. All of which are generated with specific commands, and have specific format requirements. A recommendation on how to choose your keys might be a nice addition. I'm not entirely sure how much entropy is required, but I used `head -c 64 /dev/random | base64` and grabbed the first ~60 characters of the output. I'm guessing that's long enough.

The secret itself isn't a key per ce, it's a secret string that is used as salt.
 

KageZero

Member
I'm working on a simple program similar to a notes which will allows users to store thoughts, informations etc to a remote database. The program is written using c# wpf and mssql as a remote database.
I want to extend my program a bit now. What i want is to make it run in the background and when a user enters a shortcut (example ctrl+o) a small textbox should appear where the mouse cursor is located and user should be able to enter the data into the textbox and save it, instead of bringing the wpf window. So far i have managed to register keyboard input but i have no idea how should i create an input window at the mouse location.
Can anyone link me to some resources where i could read a bit about this?
 

Trident

Loaded With Aspartame
Code:
int main(void) {
    char last_initial;
    printf("What is your name? : ");
    string name = GetString();
    printf("%c", name[0]);
    for(int i= 0; i < strlen(name); i++){
        if(name[i] == ' ') {
            last_initial = name[i+1];
            printf("%c", last_initial);
        }
    }
    printf("\n");
}

So I'm going over some of my stuff from last semester and trying to improve on them. What's a better way to do this? Ultimately, you type in your name and it spits out your initials. Is there a better way to handle this? Having 3 printf statements seems like a bit much.

I'm curious if other people disagree with me here, but I think the best way to go about situations like this is to ask yourself "what characters are actually initials in real life?" The answer: characters that are the first letter of a word.

Next, how do we know when characters are the first letter of a word? The answer: when they are either the first character, or immediately proceeding a space, AND also a letter.

So now you know your two requirements:

1. First character in string OR first character after ' '
2. A letter (i.e. between 'a' and 'z' or between 'A' and 'Z'

Now you can write an if statement to capture these requirements:

for (int i= 0; i < name.size(); i++)
{
if ((i == 0 || name[i-1] == ' ') && (name >= 'A' && name <= 'Z') || (name >= 'a' && name <= 'z')))
{
printf("%c", last_initial);​
}

}


Depending on what situations the program is being used for, you may also want to sanitize input against non-letter, non dash, non-space characters. Always assume your users are using your program every wrong way possible.

One note: you may wonder if (i == 0 || name[i-1] == ' ') will crash in the case of 0, since name[0 -1] = name[-1], which is outside the array. But for 'or' conditionals, C++ will move on once any of the conditionals are met, so in the case of 0, it will pass via i == 0.
 
I'm curious if other people disagree with me here, but I think the best way to go about situations like this is to ask yourself "what characters are actually initials in real life?" The answer: characters that are the first letter of a word.

Next, how do we know when characters are the first letter of a word? The answer: when they are either the first character, or immediately proceeding a space, AND also a letter.

So now you know your two requirements:

1. First character in string OR first character after ' '
2. A letter (i.e. between 'a' and 'z' or between 'A' and 'Z'

Now you can write an if statement to capture these requirements:

Code:
for (int i= 0; i < name.size(); i++)
{
if ((i == 0 || name[i-1] == ' ') && (name[i] >= 'A' && name[i] <= 'Z') || (name[i] >= 'a' && name[i] <= 'z'))) 
{
printf("%c", last_initial);
}
}


Depending on what situations the program is being used for, you may also want to sanitize input against non-letter, non dash, non-space characters. Always assume your users are using your program every wrong way possible.

One note: you may wonder if (i == 0 || name[i-1] == ' ') will crash in the case of 0, since name[0 -1] = name[-1], which is outside the array. But for 'or' conditionals, C++ will move on once any of the conditionals are met, so in the case of 0, it will pass via i == 0.


My choice would be to use C++, so you can cut out a lot of the cruft associated with all these letter checks.

Code:
int main(void) {
    std::string name;
    std::cout << "What is your name? "
    std::cin >> name;
    std::string::size_t space = name.find_first_of(' ');
    std::string::size_t next = name.find_first_not_of(' ', space);
    std::cout << name[0] << "." << name[next] << "." << std::endl;
}
 

Trident

Loaded With Aspartame
My choice would be to use C++, so you can cut out a lot of the cruft associated with all these letter checks.

Code:
int main(void) {
    std::string name;
    std::cout << "What is your name? "
    std::cin >> name;
    std::string::size_t space = name.find_first_of(' ');
    std::string::size_t next = name.find_first_not_of(' ', space);
    std::cout << name[0] << "." << name[next] << "." << std::endl;
}

Yeah, using c++ std is always preferable, although this doesn't sanitize input, even against common use cases of middle names, not to mention invalid characters or leading spaces.
 
Yeah, using c++ std is always preferable, although this doesn't sanitize input, even against common use cases of middle names.

Oh yea?! Well.. well.. yours doesn't handle the name 4real

In all seriousness, if you really want something bulletproof, you will need to use a regular expression. Mr. Cpp I-King IV, Jr.

Good luck!
 

Trident

Loaded With Aspartame
Oh yea?! Well.. well.. yours doesn't handle the name 4real

In all seriousness, if you really want something bulletproof, you will need to use a regular expression. Mr. Cpp I-King IV, Jr.

Good luck!

Hahaha, you're right, I was presuming rules for names that don't necessarily exist.
 

Slavik81

Member
I understand where you are coming from and I think that your C++ background creates the "issue" in the second paragraph, which directly reflects to the first point: you are micro-optimizing things before you have even started.
I don't really agree with that. Performance was a consideration, but ultimately I picked nunjucks because I felt I understood it better than handlebars. My impression is that it's actually a little slower.

The trust issue much more harder to overcome. If you cannot trust the libraries you are using, why use libraries?
I trust the authors of the argon2 C library. It's new, but has been carefully reviewed. Unfortunately, the author of the recommended javascript bindings for the library appears to have made a few mistakes in terminology. I believe I encountered a bug as well. Given that it handles passwords, I want to be sure those issues are not indicative of deeper problems with the integration.

The bindings consist of a couple hundred lines of C++ code. Spending a few hours checking them in detail is both a matter of personal interest, and a decent way to give back to the community.
 
Some of these posts make me very happy that my workplace requires everyone to use the same formatter for their code

Being required to learn PEP 8 during my first internship has really helped me. The review tool would flag any PEP 8 violation automatically and people wouldn't even the commit a second glance if you didn't give a very good reason as to why.

Of course, it came with the downside of making looking at student code the following year extremely painful...
 

upandaway

Member
Luckily I've been working more or less with the same handful of students so far and they're all fine. Looking at some other students' assignments though I can't imagine how it feels to be the one who grades all of these
 

Koren

Member
Being required to learn PEP 8 during my first internship has really helped me.
I find a couple of those rules a bit strict. I'm curious to know whether people stick to it down to the letter...

I prefer
Code:
alpha = 1.23
beta  = 2.34
psi   = 3.45
gamma = 4.56
tau   = 5.67

to
Code:
alpha = 1.23
beta = 2.34
psi = 3.45
gamma = 4.56
tau = 5.67

even if I know PEP 8 ask for the second. I may even add a space before positive values if there's negative ones, and choose what I find the most readable.

I obviously don't won't align the = in the case presented in PEP 8, but that's a bit extreme.


(I'l also go on using my own couple choices for code I write alone, a couple differences in capitalizations and a space before semicolon in tests...)
 
I find a couple of those rules a bit strict. I'm curious to know whether people stick to it down to the letter...
E221 is certainly one of the more commonly overlooked errors in most PEP 8, and people usually won't care if you violate it in a case like this. It's still good to check for though, as sometimes you'll use it somewhere you didn't intend/doesn't match the case you presented. A lot of well written code will have some number of PEP 8 violations, but that number is usually very small.
 

Koren

Member
though I can't imagine how it feels to be the one who grades all of these
I do, and it can be a nightmare, especially on papier, but most of the time, coding conventions (especially capitalization choices) aren't the worst offenders.

For example, lack of comments with 1-character names taken at random is awful (when they begin the algorithm with
Code:
a, b, f, k, l, j = 0, 1, -7, len(L), [ (1,) ], "Hello World"
(I'm only half joking), I know I'm in for a wacky ride.


Especially when they have strange implementation ideas.

And even more when they're too clever. ^_^

Take an example: find whether "110" appears before "011" in a string, or "011" appears before "110", or if none of them appears.

Code:
def Search(s) :
    if s[0] == '1' and s[1] == '1' :
        for i in range(2, len(s)) :
            if s[i] == '0' :
                return '110'
    if s[0] == '0' or s[1] == '0' :
        for i in range(1, len(s)-1) :
            if s[i] == '1' and s[i+1] == s[i] :
               return '011'
    return None

Perfectly fine, clever when you understand it, even if strangely written at times, but when it's 12AM, you're tired, are in a hurry and have read a lot of completely rubbish answers...

It would probably have been far easier with a " else " instead of the " if s[0] == '0' or s[1] == '0' ".


That makes me wonder how many errors I miss, and how often I consider wrong perfectly valid code (should happen less often, when I have a doubt, I test, but I still make errors sometimes).
 

bidguy

Banned
can anyone tell me why this isnt working ? it should fill the array with random numbers 1-9 and give out the sum of all odd and even numbers at the end but its not working. i assume i did something wrong with mathrandom

class Sum{
public static void main(String[]args){

int [] a = new int[100];
int sumg=0,sumu=0;

for (int i=1; i<a.length;i++){
a =(int)Math.random()*9;


if(a%2==0){
sumg += a;


}

else

sumu += a;



}

System.out.println("g = "+ sumg+ "\tu= "+ sumu);



}


}
 

Koren

Member
IIRC, random gives a float in [0,1) so you'll get ints between 0 and 8 when truncated to int. The loop should start at 0. And you need parenthesis to do the *9 before the conversion to int, I think, or you'll only get 0.

Isn't there a nextInt function, btw, to get random integers?
 
can anyone tell me why this isnt working ? it should fill the array with random numbers 1-9 and give out the sum of all odd and even numbers at the end but its not working. i assume i did something wrong with mathrandom

You're typecasting Math.random() to int and then multiplying with 9, you need parentheses like this:

(int)(Math.random()*9);

+ what Koren said

Edit: Dammit :p
 

upandaway

Member
I do, and it can be a nightmare, especially on papier, but most of the time, coding conventions (especially capitalization choices) aren't the worst offenders.

For example, lack of comments with 1-character names taken at random is awful (when they begin the algorithm with
Code:
a, b, f, k, l, j = 0, 1, -7, len(L), [ (1,) ], "Hello World"
(I'm only half joking), I know I'm in for a wacky ride.


Especially when they have strange implementation ideas.

And even more when they're too clever. ^_^

Take an example: find whether "110" appears before "011" in a string, or "011" appears before "110", or if none of them appears.

Code:
def Search(s) :
    if s[0] == '1' and s[1] == '1' :
        for i in range(2, len(s)) :
            if s[i] == '0' :
                return '110'
    if s[0] == '0' or s[1] == '0' :
        for i in range(1, len(s)-1) :
            if s[i] == '1' and s[i+1] == s[i] :
               return '011'
    return None

Perfectly fine, clever when you understand it, even if strangely written at times, but when it's 12AM, you're tired, are in a hurry and have read a lot of completely rubbish answers...

It would probably have been far easier with a " else " instead of the " if s[0] == '0' or s[1] == '0' ".


That makes me wonder how many errors I miss, and how often I consider wrong perfectly valid code (should happen less often, when I have a doubt, I test, but I still make errors sometimes).
Wow do you grade them based on whether they work or not? That sounds really frustrating. If we hand something in, either it has automatic tests for correctness (then the grader just grades based on style/readability) or if it's on paper, we have to write a natural explanation + mathematical proof that it works.

About your example I guess it depends on the context of the assignment. We got that exercise in automata class last year and in that class, noticing that 110 can only appear first in the beginning is the whole point of the question. In a different setting I could definitely be confused by that answer
 

Ambitious

Member
can anyone tell me why this isnt working ? it should fill the array with random numbers 1-9 and give out the sum of all odd and even numbers at the end but its not working. i assume i did something wrong with mathrandom

If you want just a hint to figure it out yourself:
Inspect the numbers you're writing into the array.

If you just want the solution:
You think you're calculating a random number between 0 and 9 and then casting it to an integer, but the casting operator has higher precedence than multiplication. So the random number is first cast to int and only then it's multiplicated with 9.

Math.random() returns a random number greater than or equal to 0.0 and less than 1.0, so the cast to int will always result in zero. Zero is multiplicated with nine, which is zero again.

So, in short: Use parentheses.
a =(int) (Math.random()*9);

But I would recommend you to use the java.util.Random class for random numbers. By using the nextInt() method, you don't have to cast.

Create the Random object before the loop:
Random rand = new Random();

..and use this inside the loop:
a = rand.nextInt(9);

There's one more mistake regarding the numbers: You want random numbers from 1 to 9, but as mentioned above, the upper bound of Math.random (and also Random.nextInt) is exclusive. So you're actually getting random numbers between 0 and 8. Therefore, just add 1 (e.g. a = rand.nextInt(9) + 1).


Oh, and your loop variable is initialized with 1. In Java, indices are zero-based.
 

Koren

Member
Wow do you grade them based on whether they work or not?
I must at least know whether it works or not... It can be akward because they're beginners, and sometimes have really strange ideas. I sometimes type the answers to check limit cases to avoid headaches ^_^

I'm in a prep school for high schools that have entry exams where you write code on paper, so yes, I have to check code on paper quite often. I don't mind small syntax errors at all, but checking borders on loops or limit cases can be exhausting.

At least, it's small pieces of code, barely never more than 10 lines when written properly (but I've seen valid solution in two pages for what I do in an inliner).

I've had to grade in the past complete compiler source code with only dozens of printed pages of source code and as many pages of poorly written doxygen, that was really awful. Especially when they've faked the output...


About your example I guess it depends on the context of the assignment. We got that exercise in automata class last year and in that class, noticing that 110 can only appear first in the beginning is the whole point of the question. In a different setting I could definitely be confused by that answer
That's exactly it: I knew the idea, but it wasn't suggested, and since they've only had 15-20h of lessons and as much practice on computers, starting from scratch, I wasn't expecting such an answer.

Especially without a single line of explanation.
 

Massa

Member
Luckily I've been working more or less with the same handful of students so far and they're all fine. Looking at some other students' assignments though I can't imagine how it feels to be the one who grades all of these

FWIW, working with other students is something that can be a pain in the ass but it's one of the most important things you'll do in college. No matter how bad you think they are, you'll most likely have to deal with worse in your career. If you think they're really bad try doing the assignments in pair programming, they'll learn something and you'll probably learn something too. Take leadership when you do it.

The worse case scenario is the person that doesn't want to do anything, not the bad programmer. Just having extra eyes on your code and explaining things to them can be more helpful than doing it on your own.
 

Somnid

Member
If these are just regular command line apps can you not just have an app that feeds them all the test cases and reads the output to pass it? You're programmer, automating repetitive tasks it what you do.
 
If these are just regular command line apps can you not just have an app that feeds them all the test cases and reads the output to pass it? You're programmer, automating repetitive tasks it what you do.

Amen to that. After that you would only need to review the coding style (unless you enforce the coding style too).

When you create (or someone else creates) the assignments, create tests to go with those. Then tell the students that the assignment must pass the test suite. (Additional bonus for creating additional test for something that is missing from the test suite)
 
Amen to that. After that you would only need to review the coding style (unless you enforce the coding style too).

When you create (or someone else creates) the assignments, create tests to go with those. Then tell the students that the assignment must pass the test suite. (Additional bonus for creating additional test for something that is missing from the test suite)

Write a clang-format specification that enforces the coding style. Have your script run clang-format against the source code and write the output to a new file. diff the files. If they don't match flag the file.

This won't catch variable naming conventions or anything like, that but it will catch syntactic style.
 

Koren

Member
That's only possible when you can get a electronic version, though.

In my case, since they'll be evaluated on paper later, I can't avoid training them on paper, too. It's quite a different exercise.

Beside, I had organized their first exam on computer. I had a test suite, alongside automated checking. I ended up printing the code and reading them wuth a pen. The success on automated tests was low, but as beginners, they're bound to make small mistakes. I can't be too harsh on them because arguments are swapped, because they return "true" instead of True, or because they made a small indexing error... I'm trying to train them to use test suites, reduce the misunderstanding, and because it's really important, but it takes time.


About this, the compiler assignement wasn't mine, I had little to say about how it worked... Phd students do as they're told ;) But in a similar assignement, we had automated test suites. Half of the tests were looking for proof of cheating, not correctness. ^_^ 3 groups out of 4 had at least parts that weren't theirs... It could be OK if they had understanded it when they added it in their project, but most of the time, they didn't :/
 
Top Bottom