/dpt/ - Daily Programming Thread

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

Other urls found in this thread:

letoverlambda.com/index.cl/guest/chap4.html
twitter.com/AnonBabble

...

This is how to generate Pi in C
#include
#include

int main(void) {
double n = 3;
long long k = 2;
while (true) {
if (k > 1000000) {
break;
}
n += 4.0 / (k * (k + 1) * (k + 2));
n -= 4.0 / ((k + 2) * (k + 3) * (k + 4));
k += 4;
}
printf("pi = %.15f\n", n);
return 0;
}


This is how to generate Pi in Rust
fn main() {
let mut n: f64 = 3.0;
let mut k: i64 = 2;
loop {
if k > 1000000 {
break;
}
n += 4.0 / (k as f64 * (k as f64 + 1.0) * (k as f64 + 2.0));
n -= 4.0 / ((k as f64 + 2.0) * (k as f64 + 3.0) * (k as f64 + 4.0));
k += 4;
}
println!("pi = {}", n);
}


Seriously, what the fuck

Going through C++ book. Pretty cool stuff.

That said, what is some project that I could use to cement my knowledge of C? Not looking at toys like "implement a binary tree" - looking at something that actually does something.

I was thinking about a simple web framework since it includes:
> handling utf-8
> sockets
> asynchronous stuff
> using third party libs (parsing http)

>(parsing http)
just use regex

Am kinda lazy and already did an http parser in another project.

fn main() {
let mut n: f64 = 3.0;
let mut k: f64 = 2.0;
loop {
if k > 1000000.0 {
break;
}
n += 4.0 / (k * (k + 1.0) * (k + 2.0));
n -= 4.0 / ((k + 2.0) * (k + 3.0) * (k + 4.0));
k += 4.0;
}
println!("pi = {}", n);
}

fixed that for you.
mixing ints and floats in rust is a bad idea

i'm at an important crossroads, please advise me

should i ditch c++ and learn c, not knowing anything about how to program without oop, or should i stick with c++?

Is there any particular reason you want to switch? I mean almost all C syntax works just fine in C++, are you going for a minimalism thing?

How to generate pi in x87:
fldpi

>x87
deprecated

YOU WANT A FUCKING ANIME CLUB STORY!?!? WELL HERE'S ONE FOR YA
>GO TO FUCKING ANIME CLUB
>BITCHES SEE MY FLY ASS TASTE IN ANIME LIKE K-ON! AND TALKS SHIT ABOUT K-ON!
>"Those fucking moeblobs are shit, watch real anime like Naruto" SOME NARUTO FAGGOT SAID
>RUN UP TOWARD HIM AND RIP HIS FUCKING NARUTO HEADBAND
>I PUT IT IN MY MOUTH AND CHEW IT WHILE HE CRIES ON THE FLOOR SCREAMING HIS MOM BOUGHT THAT FOR HIM BEFORE SHE DIED OF CANCER AND AIDS ON HIS BIRTHDAY BEFORE CHRISTMAS
>I DIGEST THAT SHIT, OPEN THAT FUCKING FAGGOT'S MOUTH AND SHIT DOWN THAT SHIT THROUGH HIS THROAT
>THE FAGGOT CHOKES ON IT AND DIES WHILE ME AND THE BITCHES GO OUT AND WATCH THE K-ON! MOVIE

>Rustfags of all people telling me D is dead

Is it resource efficient to do preliminary simple calculations to find a result close that's close enough before passing it on to a more complex calculation?

"The most powerful programming language is Lisp. If you don't know Lisp (or its variant, Scheme), you don't know what it means for a programming language to be powerful and elegant. Once you learn Lisp, you will see what is lacking in most other languages." -Richard Stallman

>garbage collection

>implying I care
Not that I wouldn't be happy if they finally get the GC out of Phobos

Possibly, depending on exactly what you're doing, but why would you ever optimize for memory instead of for processor cycles?

Is it resource efficient to find an impossible to find solution to a differential equation, rather than making a series approximation?

Also, in your Rust example you're adding float literals to k, which you don't do in the C example (e.g k + 2.0 instead of k + 2).
A fairer example:
fn main() {
let mut n: f64 = 3.0;
let mut k: i64 = 2;
loop {
if k > 1000000 {
break;
}
n += 4.0 / (k * (k + 1) * (k + 2)) as f64;
n -= 4.0 / ((k + 2) * (k + 3) * (k + 4)) as f64;
k += 4;
}
println!("pi = {}", n);
}

The only difference to the C code is the explicit cast to double, but otherwise it's the same.

parsing http with regex is a security risk, it's fine if you're just doing it on the command line for something personal but inside your app fuck no

>security risk
how?

I'm trying to compute 3x3 determinants for cramer's rule, and this only seems to work half the time.
Am I supposed to subtract more than once, or does this only apply when computing the second 2x2 determinant?

int det3(int mat[3][4], int r)
{
unsigned i, j, c, det = 0;
for (c = 0; c < 3; c++) /* column */
{
unsigned a[4], idx = 0;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
if (r != i && c != j)
a[idx++] = mat[i][j];
int neg = (c == 1) ? -1 : 1;
det += neg * (mat[r][c] * ((a[0] * a[3]) - (a[1] * a[2])));
putchar('\n');
}
return det;
}

No it isn't, you fucking retard. Kill yourself.

it absolutely is, does nobody Defcon/Blackhat here?

Rust's regex library has been fuzz tested, it's the only one I'm aware of that's at all 'safe' to even consider using for simple regex. The other's will have tons of exploits

The easiest way to get started with bug hunting is set up afl-fuzzing on some trivial code that has lots of potential for going wrong. Stuff like JSON/HTML/HTTP parsing in C/C++ is a great candidate to find integer/buffer overflow or complexity bugs. Throw some CPU time for the fuzzing, and pretty soon you should have a handful of repro cases.

If someone wants a suggestion for a project to try some fuzzing against, the h2o/libh2o web server and its HTTP parser component (picohttpparser) look very well written but not very well tested (only a handful of hand written, hard coded test cases). I'm pretty sure there's one or more potentially disastrous bugs in it because there always is disasterous bugs in any kind of regex that hasn't been fuzzed relentlessly.

Arbitrary code could be a security risk in this.

Use LU decomp.

I THINK I know what you are doing wrong. 2x2 matrices are called the "minors" of a 3x3 matrix Let them = M. Then the "co-factor" is (-1)^(i + j) * M_ij. Thus in the case where we use row 0 entries as our co-factors to get the determinant, C_00 = (-1)^0 * M_00 = 1 * M_00, C_01 = (-1)^(1)*M_01 = -1 * M, ect. (Det is the sum of each co-factor * its value, i.e. A[i][j] * C_ij). Wolfram has a good page on determinants if you wanna better explanation.

H-hey, is there a game engine, or some kind of tool which could create/run a browser game with session system (I mean recognize a player, allow him to save his progress etc.) and multiplayer support? If yes, how much user friendly is it? I know some programming, but not much.

Writing such an engine could be a fun and enthralling learning experience for you.

No, fuck that. Been there, got burned, never again.

redpill me on radare2

then maybe programming isn't for you

I just know what I can handle and what I cannot. Hence me asking about the engine.

not him, but the most interesting part in programming a game is the engine itself.

If you can't make an engine, you're not a real programmer.

You're just a sissy webdev who needs a big strong programmer to write all your tools and your runtime environment.

Probably could do that with Godot. I know it can export to HTML5.

How to generate pi in Lisp:
PI

>he thinks calling a built-in constant is generating

>falling for obvious bait

How do I pick a name for my project?
The best I can come up with is some completely undescriptive and unpronouncable acroynm.

Pick some anime meme reference

>backpedaling to "any code can have bugs"
mkay
inb4
>adding 2 numbers is a security risk
>cpus are a security risk
>being alive is a security risk

>mkay

>tfw Java is all I think about day and night

I can't stop it either

;; C like code
(do ((n 3) (k 2 (+ k 4)))
((> k 1000000) (format t "~x~%" n))
(progn
(incf n (/ 4.0 (* k (+ k 1) (+ k 2))))
(decf n (/ 4.0 (* (+ k 2) (+ k 3) (+ k 4))))))

;; Functional style
(labels ((self (n k)
(if (> k 1000000)
(format t "~x~%" n)
(self (+ n (/ 4.0 (* k (+ k 1) (+ k 2)))
(/ -4.0 (* (+ k 2) (+ k 3) (+ k 4))))
(+ k 4)))))
(self 3 2))


Type declarations are optional.
>inb4 functional has moar lines

the graphs are nice
the debugger is a pig to use
gdb is a better debugger
binja is broken right now since the data structure crap came out
radare has better graphs right now
rax2 is a really useful tool

I'm new. How do i haskell lambdas?

\x -> e

(lambda () )

if u have to ask don't try just use something easier like C
i also do not know

>haskell

Error handling: Exceptions or error codes?

I'm leaning towards exceptions because they make life easier for the programmer and make for cleaner looking code.

>maybe these non-lisp languages really are lisp, just in a clever disguise
letoverlambda.com/index.cl/guest/chap4.html

Thanks for the reply, I'm a complete noob and have recently started learning about assembly and systems programming.

How does radare2 compare to IDA pro? Is it a decent replacement, or even in the same league? I can't afford IDA's four digit price tag.

If I want to look at graphs in radare2 and debug, do I have to run both radare2 and gdb, or can gdb be run from inside radare2?

Conditions and restarts.

Ok, how do I make my Python tkinter Widget react to all events occurring on my system, regardless of if its window has focus?

I'm trying to make an alternative to AutoHotKey, but I need it to be able to respond to any and all input from my keyboard and mouse.

Basically, an overlay to my whole system. It should NEVER NOT receive input.

i've never used IDA so i can't really say, but there's nothing you can't do with any old disassembler and a decent debugger
i generally use them as completely separate tools, generally using the disassembler's graph view to plan my paths, python scripts to automate input, and gdb to attach to the running process and analyze its behaviour.
i'll always argue that you don't need fancy tools to do this stuff. just take a lot of notes and you'll be fine.
it is possible to connect radare to gdb if you need to. i find it generally isn't necessary though.

I understand this to mean checking error codes. That's terribly annoying. What's your reasoning?

exceptions
why is this even a question?

Think of them as unnamed (anonymous) functions that you can pass around. Consider map, which takes a function and one lists, and produces a second, possibly of a different type. The function itself must map from the types in the first list to the types in the second list. Type sig:

map :: (a -> b) -> [a] -> [b]

What if our first list is integers, and we want the second list to be the square of those integers (i.e. function from int -> int). In this case, we could pass map something like:

(\x -> x**2). In this case, \ begins to define the function, all parameters before the -> define the arguments, and anything after the -> defines the function body. Our call to map would then be:

map (\x -> x**2) [1,2,3,4]

Now, here is another more interesting example:

map (\x y -> x**2 + y) [1,2,3,4]. What kind of list does this return? A list of FUNCTIONS, that take a single integer and return the sum of itself + some precomputed (in our case, either 1,2,3 or 4) squared constant. if we let F = our returned list, F[1] = f(x) = x + 4, F[2] = f(x) = x + 9, ect. Note that lambdas aren't callable like functions in C, they act more like variables, and can be passed around as such.

This how you generate Pi in bc:
echo "scale=n; 4*a(1)" | bc -l
Where n is the number of digits you wish to generate.
$ time echo "scale=10000; 4*a(1)" | bc -l
3.1415...
[...]
375676

real 1m58.092s
user 1m58.088s
sys 0m0.004s

Two reasons i often hear is that exceptions are unsafe and exceptions are expensive.

Let's say I have a C# program that generates 20 circles from an array to random poisitons and I have a circle with a static position (f.ex(50,50)).

How do I use foreach loop and Vector.Distance to determine the closest circle from the randomly placed circles to the static circle?

I see, thanks

You seem like you know a lot on this topic, could you recommend me any good books/tutorials to get started with reversing binaries?

Also, do people have jobs reverse-engineering programs? I don't intend to get a job in the field, but there are ads for programming jobs everywhere and I never any ads for reverse engineers

If there's no portable threading lib for C why don't they just compile lib in c++ and extern c the threading api?

What would happen if you "extern c" an overloaded function?

Expensive in terms of code size, yes.
In terms of run-time performance, no, provided that the exception is only thrown in exceptional situations and not used as normal control flow.
Unsafe, in what way? The exception handler winds down the stack, calling destructors on any objects and freeing their memory. That's more safe than having to check return codes and free memory manually.

> loop {
if k > 1000000 {
break;
}

what the fuck is this?

I don't know much about C#, but some pseudo-code (pseudo-C) might help you:
circle_t *circles = generate_circles();
circle_t *static_circle = get_static_circle();
circle_t *closest = NULL;
float closest_dist = INFINITY;

foreach (circle_t *now : circles)
{
float now_dist = distance(now, static_circle);
if (now_dist < closest_dist)
{
closest_dist = now_dist;
closest = now;
}
}

You cannot extern c methods you would have to declare c function that calls the overloaded method.

The same as:
>#include
>while(true)
>break;

An if-expression inside an infinite loop.

Are C++11 lambdas interchangeable with function pointers?

In what context?

Not c-style function pointers.
We have std::function nowadays.

Do you take handwritten notes of your work?

It's depressing me that my work leaves no physical trace. I'm switching to a paper work diary.

Expensive too if the error handling occurs high in the stack.

You can still print your code.

Or even better, your documentation.

For example for use in legacy C libraries, but already answered that

Yes, maybe that, too.
For now I'm just writing a few lines every day, what I worked on and what I learned. It's surprisingly motivating and helps with mental structuring

I used to take physical notes, now i have hundreds of sheets of paper with little organization and terrible retrieval.
So i go digital for everything i can.

>Expensive in terms of code size, yes.
That's funny because my code is always neater when i allow myself to use exception.

>Unsafe, in what way? I'm unsure. Maybe some who hold the opposite opinion could weigh in on this.
>calling destructors on any objects and freeing their memory.
But this assumes my code is structured from an OOP architecture. Which i'm kind of trying to learn to get away from.

I have a grid-lined notebook to help with visualizing algorithms before writing them, but it's just scratch paper.

>>Expensive in terms of code size, yes.
>That's funny because my code is always neater when i allow myself to use exception.
Compiled code size.

That can't to a significant degree, surly?

Does anyone know how to go about this?

I've tried a few things with grab_set_global, but it didn't seem to work.

I need the window to receive input from the keyboard and mouse EVEN IF the Window is NOT visible OR has focus.

In other words, it should basically run at the same level as my Window Manager, receiving all keyboard and mouse interrupts 100% of the time

It can sometimes - in embedded c++ you always disable exceptions in the compiler.

opportunities in the field are sparse, but do exist. i personally don't reverse or develop exploits for my job as much as i'd love to though.
as far as learning resources go, i'd suggest osdev, the x86 assembly wikibook and wikipedia. there's also the reverseengineering, regames and netsec subreddits, which occasionally have some good reads. however i'd only suggest using resources like them to supplement your practical experience that you gain from applying your current knowledge in real world ways, like cracking software, writing exploits or developing cheats for games.
ctfs are awesome too. check out overthewire, pwnable.kr and smashthestack.

That's mostly a case of stubbornly clinging to old habits. Nowadays there's no reason anymore not to have entire gigabytes of memory in an embedded computer.

>not to have entire gigabytes of memory in an embedded computer.
Cost

>Nowadays there's no reason anymore not to have entire gigabytes of memory in an embedded computer.

What about part cost?
You don't want a full blown microcontroller especially when they cost several dollars to do what a tiny IC and a few lines of assembler can do for fractions of a cent.

Not true, memory is cheap but why make every single board cost more instead of just -fno-exceptions?

And there's low power devices and ones that must be made as small as possible.

haskell is easier than C though.

>tfw /dpt/ is the only place I feel like I belong

Yeah, unruled comp books and a mechanical pencil. I outline algos, take debugging notes, circle "good ideas" for later.

can you please give us an example of an algo problem you did and your method please post

You do not belong anywhere.