/dpt/ - Daily Programming Thread

Old thread: What are you working on, Sup Forums?

Other urls found in this thread:

doc.rust-lang.org/book/second-edition/
github.com/torvalds/linux
stackoverflow.com/questions/13332012/double-vs-double-in-java
youtube.com/watch?v=R9c-_neaxeU
twitter.com/NSFWRedditGif

Is this a good pattern for growing a vector?
Someone pointed out that i should be checking the return value of realloc, but how do you even recover from an out of memory error without spinlocking realloc until it returns more memory?
This doesn't even work on linux because it will keep giving you memory even if there's none left.

if (buf->size < buf->len + (size * nmemb))
{
buf->size = (buf->size * 1.25f) + (size * nmemb);
buf->mem = realloc(buf->mem, buf->size + 1);
}

>but how do you even recover from an out of memory error without spinlocking realloc until it returns more memory?

Crashing.

Explicitly crashing is better than just dereferencing some NULL pointer, though.
It's probably worth writing a "crashing" wrapper over malloc and friends which does all of the checks for you. It can also help catch some malloc bugs, where you accidentally pass a massive integer (e.g. from casting negative numbers to unsigned).

void *xmalloc(size_t n)
{
void *ptr = malloc(n);
if (!ptr) {
fprintf(stderr, "Allocation of size %zu failed: %s", n, strerror(errno));
exit(1);
}
return ptr;
}
etc.

How do I make secure dynamic websites? I want to make clones of websites such as Sup Forums and Facebook from scratch but I don't want to get hacked.

Made this SpringAttach component. It updates one object to match another with optional "spring" parameters.

treat all user input as malicious

>good pattern
Is it the best? Definitively no.
Good enough for you? Most likely.
>i should be checking the return value of realloc
Yeah, you should. Because if you catch the error right then and there you know what happened. If your memory is unexpectedly insufficient at some point that's not pleasing.
Another option is to align the vector to page boundaries and place the end of the vector of course if you want to be consistent with that you only allocate entire consecutive pages. I've actually seen people do this because they thought a branch was bad for some reason. Very misguided.
>spinlock
Unlikely to solve anything. If I wanted to avoid crashes I'd paint my memory into categories and free some of it that's very low priority or recoverable. It's a pain to develop around that but it's doable.

This is of course being overzealous.
What you should do is use std::vector :)

Should I stop all running threads before returning from the main function, or can I safely assume that the OS will do it for me?

sepples question:
if I have something like this

void Foo() {
O *o = new O();
o->setCallback([]() {
//do stuff
}
}

how do I access o from the lambda without making o a member of the class? and no I cant pass it ass parameter.

trying to learn rust, any suggested resources Sup Forums?

inb4 rust = autism hurrrrrr

There is no notion of a parent-child relationship between threads. Once the two threads are running they're basically peers. Main thread can exit while other thread's still running.

Read this: doc.rust-lang.org/book/second-edition/
After that, put it into practice.

rust = autism

someone's a clever boy

inb4 doesn't mean shit if you do it to your own post.

>implying shit you say on Sup Forums actually matters

Depends on platform but yes.
I don't consider it a good strategy because it'll put you in a position of asking 'but what if the program exits without this thread finishing?'.
Maybe you're not doing something important enough for that though.
No that's not true generally (considering the majority of machines). It certainly could be true somewhere but when you consider Unix, Linux and Windows that's definitively not the case.
You can make this happen usually, disassociate the main thread from the process exit. So basically main can return/exit but your other threads keep going.
Basically you should read the documentation and find out.

ok solved. delete tits because you guys suck ass

Solid answer. Thanks m8.

So you figured out you need to capture the o in the closure scope then?

ode solver works.

Should add that you should probably read the docs too.
I assumed a relatively low level language and OS functionality. If you're in Java/Python for instance I can't say.

Any non brainlets know the best way to normalize these coordinates in java?

I want to convert from a double that can be +-10^18 in size to an int between 0 and 500?

int normalizeStarX(Double i){
i=((i+508743946216137.0d)/841387073191675000.0d)*500;
System.out.println(i.intValue());
return i.intValue();
}

for the x coords -508743946216137 is as low as these values go and 841387073191675000 is as high, but I always output 0 for some reason.

FuckX.h:
Fuck Nvidia
Fuck Apple
Fuck Microsoft
Fuck OpenGl
Fuck NCurses

>non-brainlets
Harsh
>normalize these coordinates
sure ju..
>in java?
You certainly don't have room to insult people.
Why do you think this is language specific? Fucking idiot.

Do you have a github page? I'd like to follow this project.

>Harsh
I was calling myself a brainlet... if I can't solve this but I state a person who isn't a brainlet can, I am implying I am a brainlet.

>in java
well I just started writing in java today and I don't know the specific syntax to use or if what I am doing is retarded.

>Fuck NCurses
Over the line.

>well I just started writing in java today and I don't know the specific syntax to use or if what I am doing is retarded.
I only specified the specific language because I believed my thought process to be correct, but I am still getting all 0's so it could be a problem with how I use the language.
I really don't understand why this is a reason for you to insult me.

>Is this a good pattern for growing a vector?
no
>buf->len + (size * nmemb)
unchecked overflow
perror & abort

github.com/torvalds/linux

Excellent.
Submit a patch or something loser.

I dunno. Print i before normalization to see if the numbers you want are actually in the variable.

Find the (absolute) max of the list once instead of hardcoding those truly magical numbers, divide each number by it, and then multiply by 500. Right? The absolute max divided by itself is 1, multiply by 500 to get the max value in your range.

Further, you're trying to return a double as an integer value. Did you want to quantize those numbers as integers, or what?

People who fall for the "self-documenting code" meme are terrible, terrible programmers.

I hope to never be on a team with you, worthless Pajeets. I blame California for this epidemic.

>Did you want to quantize those numbers as integers, or what?
I just want to draw them on a map so I need integers for the pixel locations.

>self-documenting code
I think it's excellent actually. If you knew someone who knows how to do this where possible everything will be clear and you won't have to deal with many outdated comments (like I do).
If they don't then they write completely maintainable code and you should tell them immediately for their own sake.

>People who fall for the "self-documenting code" meme are terrible, terrible programmers.
Or they're plain old shitters who only write trivial programs.

>muh complicated program

Is it true? Is the akaribbs user still lurking?

so im trying to create some simple client server socket shit in c. basically uploading a txt file from the server to the client

everything seems to work alright but on the client file, it prints the content i want and then prints @@@@@ forever

gonna paste the relevant code from server.c

int fd = open("test", O_RDONLY);

while(size = read(fd, buf, 4096)){
if (send(client_socket, buf, size, 0) < 0){
printf("error\n");
exit(1);
}
}

client.c

int fd = open("test1", O_WRONLY | O_APPEND);
if (fd < 0) {
printf("error\n");
exit(1);
}
memset(buf, 0, 4096);
recv(sv_socket, buf, sizeof(buf), 0);

write(fd, buf, sizeof(buf));


what am i being retarded on

i've only written sockets in python, but shouldn't you close your client socket?

user you should do this instead:
int normalize(Double i, Double minimum, Double maximum, Double multiplier){
Double result = multiplier*(i-minimum)/(maximum-minimum);
System.out.println("As Double: " + result); //Just for your verifying convenience
System.out.println("As int: " + result.intValue());
return result.intValue();
}
int normalizeStarX(Double i){
return normalize(i, -Math.pow(10,18), Math.pow(10,18), 500.0d);
}

Also don't write double with capital D as here.

null terminator

Ok what is the difference between double and Double?

akaribbs was great

>not building higher level functionality from small self-documenting generic procedures

free_mem(parse(allocate(load("file.txt"))))

>explicit free_mem

>muh gc

Dude, parse returns something that free_mem can free. That's the problem here.

>That's the problem here.
Hey, there's lots of problem here, but I'm not going to list 'em all. I'm too drunk to do that.

stackoverflow.com/questions/13332012/double-vs-double-in-java
It's a fair question. I don't know Java enough to answer that confidently. I actually thought it was some silly case insensitivity.
I say primitive types are better whenever you can just because they bring less complexity. That's my personal opinion. I expect double to be a primitive type. I generally expect to read lowercase double. That's from C++ though.

I suppose if you're new you shouldn't actually care.

forgot that but not the problem
gonna try this shit

but for some reason i fucked it up and it isnt even printing anything anymore i hate c

Thanks a bunch for your help, I haven't implemented all of your suggestions yet but I did get this mark 1 version working for now which will suffice for today.

>Ok what is the difference between double and Double?
One is the boxed form of the other: a double is a primitive, 8 bytes of floating point goodness, and a Double is a simple object holding an (immutable) double.

It's not complicated or anything.

They should have named one odouble or something

>named one odouble
That'd be OK until St Patrick's Day, when all the values would get drunk.

you are a funny man

FUCK C++ hard

Don't let it reproduce.

...

Are there any good starting guides or reading lists for machine learning?

funny how?

you make jokes

i don't care about your python experience, fucking twat. we use real languages here, not fucking startup shit for adult daycares. what the fuck do you think you're doing turning up in a hoodie and shorts, you look disgraceful, the reason i can get away with it is i already work here

you list some fucking web frameworks like i'm supposed to recognize them, i don't care, if i wanted someone who could point and click shit together then the job posting would have made that clear. sitting around for 3 years growing a mustache and playing with php isn't a substitute for a degree

trumped up cunt, the reason i'm not telling you more context is because this is an interview and i've only got an hour to figure out whether you can program. i'm not inclined to be generous if i don't have a clear answer at the end of it because too many useless pricks are good at pretending they can when they can't

you probably couldn't handle the banter here anyway

who me?

yes you

It also might be nice to provide __LINE__ to xmalloc

Very basic machine learning:
youtube.com/watch?v=R9c-_neaxeU

I've started using Love2d for a game project I'm making and I gotta tell ya, Lua is..interesting.

Do you see it?

non-integral health and float comparison?

>ranged for
i love up to date anime

like dis. It's retarded to tear down the process from inside your own API so it you're going to EXIT_FAILURE just do it from the top level so you can properly unwind the stack before exiting.

#include
#include
#include

#ifdef __GNUC__
__attribute__ ((format(__printf__, 1, 2)))
#endif
_Noreturn void err_log(const char *format, ...)
{
va_list vargs;
va_start(vargs, format);
vfprintf(stderr, format, vargs);
va_end(vargs);
}


#define ERR_LOG(format, ...) err_log("ERROR [ %s:%d in %s() ]\n" format, __FILE__, __LINE__, __func__, __VA_ARGS__)

a dsl for predicting the behavior of rational agents in a relational world model (like the ones you usually find in text adventures)

couldn't be

damage is taken for each debuff you have on you

What kind of a masochist would do game logic with cpp?

I want to access an offline git repo from multiple machines. What's the easiest way to do this?
Can I just grant local network access to the repo directory?

>_Noreturn
But you're returning.
Also, use . Nobody wants to look at that _N shit.

two hours until the next advent of code problem, lads

>lads
go to bed user

FILE *fd, has to be a pointer since the size of the file will change.

I'm trying to print all of the files inside a directory using Haskell. I have a global flag that controls whether or not it should print recursively. I'm new to Haskell so I'm wondering if there's a more correct way to handle this kind of conditional execution.

printFiles :: FilePath -> IO ()
printFiles [] = return ()
printFiles dir = do
contents

O shit lol I forgot

lots of people lol. not everybody is a brainlet who needs to use C# or python for everything

How do I learn junior developer-grade C++ in the next 28 days, with only 2-3 hours a day to learn?

Trying out converting some of my massive project to Kotlin because I'm tired of dealing with Java's archaic lack of decent functionals, iterating manually and verbosely like a moped with a busted tire.

I like the emphasis on immutables and nullable vs non-nullable distinctions, but I could do without all these arbitrary-as-fuck gaps in normal C-style grammar impleentations. Just let do a proper for loop. I have to travel over extremely weird, but still logical and concise intervals. Not everything is a linear int progression.

there's a function in Control.Monad called "when" (and similarly one called "unless")

when True action = action
when False action = return ()

when recursive (mapM_ printFiles directories)

Have you considered Scala?

1. What level are you at now?
2. Why did you put yourself in this position you dumb fuck
3. Stop putting yourself in these positions and dragging down the rest of the team, we don't enjoy it
4. pls respond

I'm starting with Kotlin because it seemed easier to find support for. I'll get over my petty grievances then maybe see if Scala offers anything different/better.

And then I'll have 50,000 lines of code, 60% written in Java 30% in Kotlin, 9% in Scala, 0.9% in Groovy and 0.1% in Visual Basic just because. That'll show them.

...

Missing a break after the DestroyMe() call. If multiple debuffs are active and hp is low enough to die from one tick, DestroyMe() could be called multiple times before that for loop is exited.

t. someone who writes game logic in cpp.

1. Some knowledge of Java and Python, some knowledge of pointers, no real projects
2. I have an interview at the start of January and I'd like a job
3. The job won't start until next July so I actually have slightly more time to git gud
4. (You)

>massive project
what's your project lad?

r8 my advent code solution in C++
constexpr long day1p1(const char input[], const size_t &index)
{
return (input[index] != 0) ?
(
(
(input[index] == input[(index + 1) % strlen(input)]) ?
input[index] - '0':
0
) + day1p1(input, index+1)
): 0;
}

constexpr long day1p2(const char input[], const size_t &index)
{
return (input[index] != 0) ?
(
(
(input[index] == input[(index + (strlen(input) / 2)) % strlen(input)]) ?
input[index] - '0':
0
) + day1p2(input, index+1)
): 0;
}

Sounds alright. Since you have experience with more than one language/syntax family, I recommend two things: read through existing code (follow a relevant project a github, review the commits that come in) to see how other people use the language realistically (and modern-style), and smash out a few small mock projects to familiarise yourself with what C++ has to offer for each kind of problem.
Something like: Given a CSV of (artist,album,song title,genre) come up with a way to store it that allows you to e.g. fuzzy-search for a song/artist, or implement shuffle-by-album.
Nothing too complex, but involves a wide enough range of realistic generic tasks you'll be performing.

Think about how you would build a playlist from this "media library". What about a dynamic playlist like "infrequently played".
Play around with sqlite bindings for shits and gigs (and eventually real gigs)

Thanks for the suggestions. I think you're right, I need to bust out some projects. I'm always afraid of starting projects unless I'm fully acquainted with the language/library and I think I can do the project perfectly, which is why I have nothing to show for my time spent coding.