Programming thread. Git gud edition

Programming threads making you better. This thread themes is gitting gud by any means possible.
The natty way obviously....you didn't really think about cheating did you user. i see that adderall prescription don't lie.
i'm gonna post some resources on popular languages so theirs no excuse for you to not git gud. other than laziness.

WHAT YOU DOING user?
post progress so we know you're not some faggot who larps and pretends he knows what he's talking about. because this isn't one of your linux distro threads or systemd thread we're here to talk about programming. my project right now is making bots via python for popular chat rooms chatango, discord, irc, etc. it's pretty comfy. but enough about me what are you doing?

RESOURCES
did you think i forgot about this the only resources you need is the drive to get better.there isn't a single book or website in the world that would get you off you're fat ass and learn to do something that could benefit you in the future. this has to come from deep within. you think top level programmers were born with the skill to create some of the most beautiful programs no they worked at it. natural talent only goes so far faggot git gud or just give up already.

also does anyone have the programming challenges Holla Forums made i lost it when my hard drive dieded

Other urls found in this thread:

fuckdreamhost.com/
gitgud.io/m712/terminal-incremental
en.wikipedia.org/wiki/Free_list)
isocpp.org/
gist.github.com/anonymous/9f958afa08493e09ec51e71bfb1430be
u.nya.is/wfdelu.tar.bz2
ghostbin.com/paste/fxh2y
ghostbin.com/paste/8zvdz
git.savannah.gnu.org/cgit/coreutils.git/tree/src/cat.c
git.savannah.gnu.org/cgit/coreutils.git/tree/src/cat.c?id=b25038ce9a234ea0906ddcbd8a0012e917e6c661
tech.jonathangardner.net/wiki/Why_Java_Sucks
ceylon-lang.org/blog/2016/06/02/ceylon-on-android/
scala-android.org/
expressjs.com/
youtube.com/watch?v=gnsO8-xJ8rs
stackoverflow.com/questions/517127/how-do-i-write-output-in-same-place-on-the-console
youtube.com/watch?v=qWVUQPWa67M
github.com/diasdavid/simple-raytracer).
sprunge.us/BGHd
github.com/7Y2RPXK3ETDCNRDD/Koondelick
nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/
blog.llvm.org/2011/05/what-every-c-programmer-should-know.html
blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html
blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html
blog.regehr.org/archives/213
blog.regehr.org/archives/226
blog.regehr.org/archives/232
cl.cam.ac.uk/~pes20/cerberus/notes50-survey-discussion.html
learnyouahaskell.com/chapters
play.rust-lang.org/?version=stable&mode=release
doc.rust-lang.org/std/primitive.i32.html
play.rust-lang.org/?gist=416528422184ca383339a895bff5c366&version=stable
ideone.com/qqVjao
play.rust-lang.org/?gist=37bd152f6bc7fb6c4c469f6789e53014&version=stable
huonw.github.io/blog/2016/04/myths-and-legends-about-integer-overflow-in-rust/
doc.rust-lang.org/reference/behavior-not-considered-unsafe.html
github.com/rust-lang/rfcs/blob/master/text/0560-integer-overflow.md
port70.net/~nsz/c/c89/c89-draft.html#3.3.7
port70.net/~nsz/c/c89/c89-draft.html#A.6.2
twitter.com/SFWRedditVideos

I applied to a dev job with a fake resume about my skills & experience.
How do i keep this job while knowing next to nothing about software engineering?

here's the plan. start researching and training yourself for the job while also using google to solve everyday problems. until you become a pro at it. it's basically playing a game of catch up. but you never started. if you really want this you have to commit countless hours for it or else you will fall off and be fired. The next best thing is finding someone who is qualified and pay them to do you're work for you but since money don't grow on trees I would choose the latter. or find a trusted co-worker to do you're work for you while you actually learn the material either way its a lot of work. why did you lie user?

i believe in you user you're gonna make it!

Because I wanted a job and this is the easiest way.
You should try it sometime

yea until you have to actually do the job than you're fucked and posting on Holla Forums for help. you should have just bitten the bullet and went to collage. but do whatever you want. make sure you post results of this experience once it's over it would be one heck of story to tell your children too. especially if they don't have to work a single day in their lives because it worked.

Thanks, you just convinced me to never go to school again.

Give me a break faggot it's 4 am here. also i never said i went to collage but for fields like this it is mostly required some form of training. you can't just jump straight into it.

or you could have been learning how to do this shit since you were a kid so you are now proficient at it without any schools, faggot

Are you supposed to roll for the first image. If so, consider this my roll.
Scared because now I actually have to do some programming instead of reading about it and studying math

I've been forever in this conundrum where I can code up all kinds of applications and games and things with javascript/html5, but I have no idea how to do anything properly.

I can't learn the right way to do things by doing it on my own, because I'll just keep using my problem solving skills to solve problems with complete disregard for any efficiency or quality since I don't know the first thing about either.

I don't know what I'm supposed to do or where I'm supposed to look for guidance. I'd like to help with open source projects and do proof of concept modifications to imageboard software and do mods for videogames and the like, but I wouldn't even know how to install/set an imageboard locally if you gave me the source code. I've dabbed a little bit on server software, but if you told me to add ffmpeg to my server or use redis caching, I'd have no idea what doing that entails in any capacity whatsoever. What am I even supposed to look up if I want to learn to do this kind of stuff? I'm absolutely lost and most of the time I just can't be bothered to figure something like that out since I can already technically program stupid things with javascript.

I am afraid you are beyond hope.

Thanks for this meme, it improved my day

Fuck me dead.
All I want is to learn engine programming to make my own 2D tile engine, but every single tutorial is just "durr muh platformers or just lern unity xD"

How do I learn this shit? I don't want to quit my job to start a degree in CS, I just want to learn for a couple hours every day until I'm competent with Holla Forums.

Ask a programmer friend to do it for you and focus on art instead?

handmade hero
enjoy your hundreds of hours faggot

i would say start at the top and make your way down. until you reach the limitations of another game engine. you would have gain a lot of experience and know what you want exactly. video games are some of the most complex programs out there and someone with a couple of years of experiences is still a novice give it time you will learn. Most people who are making game engines now got into rom hacking so maybe you should check that out.

Op here working on the ftp client today. will use thread to document progress but now i'm just doing research

Is this bullshit list available in text form? What is this shit?

This. I actually got my first programming job through word of mouth (you need to not be a shut-in for this) and from that point on college stopped mattering at all because I had past work experience that proved my skills.

I do have a college degree, but it's completely unrelated and I have never used. In fact, the diploma is still sitting there at the university's basement, waiting for me to go and collect it.

So start learning to do the shit you want to do, the opportunity will come eventually. Better be prepared.

Speaking of projects and bots, I have a very simple but very cool one that works like this (I won't post any code because I regularly delete all my data. I don't keep any personal data long term that isn't work-related):

chatbot part:

It's amazing how well it works given its simplicity. The last time I implemented it I parsed the Holla Forums archive (3 days worth of threads) and it simulated a banal conversation with a pollack pretty well. The only issue is it doesn't take pictures into account, so sometimes the context would get weird without them. Still pretty cool if you trained it with chat logs and the like, as long as the community is as monothematic as a board's.

Which language?

I first implemented in C++ and then C#. Last time JS because I wanted to get it done quick and dirty and Node had everything I needed built in.

What difference does it make though?

roll.

roll

Static website generator.
I've looked at it online and it seems like some kind of Django thing, Am I right ?

shitpost

Django is a web framework and way, way more complex than a static site generator.
Think more along the lines of a blog, where you feed it your text, maybe with some markup symbols added, and it creates the html for you.
Example from a thread a while back were pelican and hugo.


I drew a polygon. where poly means 3) Using Ada with bindings to SDL. Now to add the transformations part.

Ok, I see, thanks.

ROLLING

nop, fuck this shit.
re-roll

too easy. re-roll.

roll

Truly a lost cause

You seem so desperate that I'll reply out of pity.

roll

ME TOO
fuckdreamhost.com/

Rolling

nodevs get out

That's why roll images are always cancer that ruins threads with no exceptions.

n = 4line = [0] * (n+1)line[n] = 1for i in xrange(n): nxt = [0] * (n+1) for j in xrange(n): nxt[j] = line[j] + line[j+1] line = nxt p = "" for e in line: if e == 0: p += ' ' else: p += '%i '%e print p
lol if I don't write python in a while I always end up writing crap like this

...

Not going to post all the code, but will give a rough outline of it.
I knew about using Augmented matrices and why they are handy, see Wikipedia article on affine transformations.
Created matrix and vector private types so you can't access parts of the matix you aren't supposed to.
Straight forward functions to construct said vectors and matrices as well. I missed some matrix manipulation functions so created those.

Array of Vector holds the coordinates. A procedure that applies a transformation to each vector in the array, and function that takes the array of vectors and returns a Line_array(begin and end points), which is what SDL can plot.
The sdl draw function works with integers, the vectors and matrices all floats.

Put draw and transform procedure in a loop, don't clear, and you get pic related.
Done, and Reroll

Fuck, I can't figure out how to make an infinite board.

You might need more memory for that.


Made a mastermind game, just a console version. Scoring seems to be correct, but a having some tests for it would be nice.
I put some IO in a separate package, about 70 lines for the body.
with MasterIO; use MasterIO;procedure Mastermind is Guess, Secret : Row := (others => Empty); type PegCountArray is array(Peg) of natural; CountArray, LoopArray : PegCountArray := (others => 0); Black, White : Natural; NumGuess : Positive := 1; begin SetRandom(Secret); --You need to know how many times each color is in the Secret to -- prevent scoring pegs multiple times. for foo of Secret loop CountArray(foo) := CountArray(foo) + 1; end loop; -------------------- -- Main game loop -- -------------------- while NumGuess

Rolling

There is a small error in the scoring section, some additional bookkeeping is needed to prevent scoring a single pin both black and white.

gas yourself

...

Porting video game maps (forking an abandoned repo).
A before and after.

...

looks like a UT map? What game is this?

It's the map Sky Temples from Reflex. It's ported from that to the idTech 3 map source format (so it can be touched up in a map editor).

You will not.

Tested my program against an online simulator, M3 navy with no plugs in the plugboard and wheels I, II, and III. And it werks.
Great feeling to feed you encoded stuff in the simulator and get the plaintext back.
Protip is to start with with small discs A-F to test with and reason about how to best approach it.

Come on, faggots. Step it up and git gud.
Inb4 no code posted, I'll have to restructure it a bit to make it presentable,

why are you larping?

Here is the code for the enigma simulator.
Main is fairly small, just the creation of the Enigma, An array with the selection of a set of wheels ('Access ~= pointer).
And a simple loop to encode and output the encrypted plaintext.

Package enigma contains a bunch of types. Most of the Text related ones are public, and you could add your own wheels.
The Enigmarotors record is private, since you don't want or need access to its internals. The types used in enigma record are private as well, since you don't really need those.
The body is mostly helper functions to convert the various discs to their numeric equivalents. The bodies of Encode and Step are shown.
with ada.Text_IO; use Ada.Text_IO;with enigma; use enigma;procedure Main is -- Test 3 rotor system; Enigma : EnigmaRotors(3); Wheels : Wheel_Selection := (I'Access, II'Access, III'Access); Plaintext : String := "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; begin -- Setup the enigma Setup(E => Enigma, EW => EW, UKW => UKW_B, W => Wheels); Put_Line("Enigma output: "); For char of Plaintext loop Step(Enigma); put(encode(char, enigma)); end loop;end Main;package enigma is subtype letter is Character range 'A' .. 'Z'; type Idx is mod letter'Range_Length; type wiring is array ( Idx) of letter; type NotchArray is array (Positive range ) of letter; type Wheel_Config(Steps : Positive) is record W : wiring; Notch : Notcharray(1 .. Steps); end record; type Wheel_Config_Acc is access all Wheel_Config; type Wheel_Selection is array(Positive range ) of Wheel_Config_Acc; type Rotor_type is array(Idx) of Idx; ------------------ -- Rotor Wiring -- ------------------ EW : wiring := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; UKW_B : wiring := "YRUHQSLDPXNGOKMIEBFZCWVJAT"; I : aliased Wheel_Config := (1, "EKMFLGDQVZNTOWYHXUSPAIBRCJ", "Q"); II : aliased Wheel_Config := (1, "AJDKSIRUXBLHWTMCQGZNPYFVOE", "E"); III : aliased Wheel_Config := (1, "BDFHJLCPRTXVZNYEIWGAKMUSQO", "V"); IV : aliased Wheel_Config := (1, "ESOVPZJAYQUIRHXLNFTGKDCMWB", "J"); V : aliased Wheel_Config := (1, "VZBRGITYUPSDNHLXAWMJQOFECK", "Z"); --------------- --Enigma Type-- --------------- subtype RotorRange is Positive range 3 .. 4; Type Enigmarotors(Num : RotorRange) is private; ------------------- --Setup Procedure-- ------------------- procedure Setup(E : in out EnigmaRotors; EW: Wiring; UKW : Wiring; W : Wheel_Selection); --Encoding and stepping function Encode(Ch : Character; Enigma : EnigmaRotors) return Character; procedure Step(Rotorset : in out EnigmaRotors);private ---------------- --Entry wheel -- ---------------- type entry_type is array (Letter) of Idx; type exit_type is array (Idx) of Letter; type EW_Type is record input : entry_type; output : exit_type; end record; ---------------- -- Rotor stuff-- ---------------- type NumNoch_arr is array (1 .. 2) of Idx; type RotorRecord is record Forward : Rotor_type; Backward : Rotor_type; Pos : Idx := 0; offset : Idx := 0; NumNotch : Positive; notches : NumNoch_arr; end record; Type Rotorset_Type is array(Positive range ) of RotorRecord; Type Enigmarotors(Num : RotorRange) is record EW : EW_Type; UKW : Rotor_type; R : Rotorset_Type(1 .. Num); end record;end enigma;

2/2
package body enigma is ----------------------------- -- Various helper functions-- ----------------------------- function Encode (Ch : Character; Enigma : Enigmarotors) return Character is curr : Idx := Enigma.EW.input (letter (Ch)); tmp : Positive; begin for whl of Enigma.R loop curr := curr + (whl.Forward (curr + whl.Pos)); end loop; curr := Enigma.UKW (curr); for whl in Enigma.R'Range loop tmp := Enigma.R'Last - whl + Enigma.R'First; --This steps backwards curr := curr + Enigma.R(tmp).Backward(curr + Enigma.R(tmp).Pos); end loop; return Character (Enigma.EW.output (curr)); end Encode; procedure Step (Rotorset : in out Enigmarotors) is state : array (1 .. Rotorset.Num) of Idx; function TestNotch (W : Positive) return Boolean is begin for foo in 1 .. Rotorset.R (W).NumNotch loop if state (W) = Rotorset.R (W).notches (foo) then return True; end if; end loop; return False; end TestNotch; begin for foo in state'Range loop state (foo) := Rotorset.R (foo).Pos; --save the current state end loop; --Always increment the first wheel Rotorset.R (1).Pos := Rotorset.R (1).Pos + 1; if TestNotch (1) or TestNotch (2) then -- Double stepping Rotorset.R (2).Pos := Rotorset.R (2).Pos + 1; end if; if TestNotch (2) then Rotorset.R (3).Pos := Rotorset.R (3).Pos + 1; end if; end Step;end enigma;

Nice. I knew you would deliver, but I had to make sure.

rollin

just added some more bloat features to my multiple sources multiple targets python copy script. It can now write a log file and rename files to their hashes. There's still some more shit I want to add to it

rollan

I fuckin' hate making user interfaces and every bit of code related to them.

Graphics are kind of fun though.

ayy

Roll.

...

Rollin'

There's like 8 different "IMP" languages.

Rerollin' like a fag.

anybody have a good tutorial on understanding bitwise operators?

Why don't you just use them and see what happens? That's not so hard.

rolling

I wonder what percent of code/programs ever gets read/downloaded. also roll since I'm here

(defun fact (n) (defun pp (n ans) (if (

I have a couple of programming challenge pics, dunno wherefrom.

and couple more.

Any guess as to what do these structs are supposed to do?
typedef struct tagFreenode{ struct tagFreenode * nextfree;} Freenode ;typedef struct tagFreelist{ Freenode * head; int nodesize;} Freelist ;

It's a linked list but it carries no data. There should be some other stuff in tagFreenode.

I want to start learning another programming language. I've spent a few years with Python, both for practical work, and to do algorithms and data structure exercises. But now I have a project in mind where an interpreted language is too slow.

I originally learned to program using C++ many years ago, so I am considering going back to that. But is that the best option? What about Java? Or plain old C?

For reference, I want to build a basic smoothed particle hydornamics simulator.

I am currently making a clicker/incremental like game, but it's in the terminal and works by typing.
gitgud.io/m712/terminal-incremental
It's probably gonna stall though as I want to work on Blazechan now.

ROLLING

ROLL
Started learning C++ going for my CS degree about a year ago, currently trying to work my way through SICP and algorithm analysis stuff before the fall semester starts. I don't really have any projects of my own atm. Most I've done outside college assignments and overall learning is make a very primitive spell check app in Qt for shits, better than nothing I guess.

It's a freelist (en.wikipedia.org/wiki/Free_list)
pointer tomfoolery must be used to access the actual buffer each node marks. Maybe the buffer is in the (nextfree, nextfree + nodesize] range of addresses?

Thanks user. I'd never seen one of these before.

Just be aware that they have an agenda to lock you into proprietary formats user, same as Apple or Microsoft would.

If you don't need a GUI for your app (or aren't willing to use a more standards-compliant framework like GTKMM or FLTK) I'd recommend you try to stick strictly with the ISO standard C++14.
isocpp.org/

wtf gitgud?

Last thing I made is a step sequencer and arpeggiator for midi which can synchronize its tempo to the external clock.Too lazy to complete anything cuz depressed and my life is a complete shit.
Best thread on Holla Forums now so have my bump

Spent a few days trying to understand how Fortunes algorithm works. I didn't succeed but I did get it outputting pngs.

Rollan

Interviewing for a job that will involve sending patches to kubernetes upstream tomorrow.

What should I learn about Go?

I'm just here to roll.

rolling

Generics.

Done. I have no idea how to tune my bells though. Rate my 133t skillz.
gist.github.com/anonymous/9f958afa08493e09ec51e71bfb1430be

Here's no. 93 from the first problem set, binary search. Messy, but gets the job done and works for any datatype that has ==, defined.

How about a rule for getting quads? Make a bot that makes a shitpost to this thread, checks its post number, and then posts the code for the program corresponding to that post number. Then repeat.

Anyway, rollan

#include #include template int binarySearch(std::vector * searchVector, T target, int start, int end){ std::cout at(newEnd) == target) return newEnd; if (newStart == newEnd) return -1; if ((newEnd - newStart) == 1) return -1; return binarySearch(searchVector, target, newStart, newEnd);}template void bSearchOutput(std::vector * searchVector, T target){ int outcome = binarySearch(searchVector, target, 0, searchVector->size()-1); if (outcome == -1) std::cout

rollin again

That's the account system gitgud's creators made, it's not an external service.

#include #include #include static const unsigned N = 5;static int rules[N * N];enum V { Ro, Pa, Sc, Li, Sp };static const char *name[N] = { "Rock", "Paper", "Scissor", "Lizard", "Spock" };void init_rules() { auto R = [](V a, V b) { rules[a + N * b] = 1; rules[b + N * a] = -1; }; R(Sc, Pa); R(Pa, Ro); R(Ro, Li); R(Li, Sp); R(Sp, Sc); R(Sc, Li); R(Li, Pa); R(Pa, Sp); R(Sp, Ro); R(Ro, Sc);}V v_of_name(const char *name) { for (unsigned i = 0; i < N; ++i) if (!std::strcmp(name, ::name[i])) return (V)i; return (V)-1;}int rps(V a, V b) { return rules[a + N * b];}int main(int argc, char *argv[]) { if (argc != 3) return 1; V a = v_of_name(argv[1]), b = v_of_name(argv[2]); if (a == (V)-1 || b == (V)-1) return 1; init_rules(); const char *result[] = {"Lose", "Tie", "Win"}; std::printf("%s %s -> %s\n", name[a], name[b], result[1 + rps(a, b)]); return 0;}

This Lisp code has some defects.
First you must not nest defun. This may work in an interpreted environment, but in compilation it does not.
That's because the compiler only looks at defuns which appear as top-level forms.
Use labels to define a local function which is recursive.
(defun fact (n) (labels ((pp (n ans) (if (

Rolling. I'll do it in Lisp.

This is RSA written in Common Lisp.

#!/usr/bin/sbcl --script(in-package #:cl-user)(defun modexp (base exponent modulus) "Modular exponentiation" (cond ((= modulus 1) 0) (t (labels ((rec (base exponent acc) (cond ((> exponent 0) (rec (mod (* base base) modulus) (ash exponent -1) (if (= 1 (logand exponent 1)) (mod (* acc base) modulus) acc))) (t acc)))) (rec (mod base modulus) exponent 1)))))(defun message->integer (message) (let ((value 0)) (check-type message vector) (loop :for byte :across message :do (check-type byte (unsigned-byte 8)) (setf value (+ byte (ash value 8)))) value))(defun integer->message (value) (check-type value (integer 0)) (let* ((size (ceiling (integer-length value) 8)) (message (make-array size :element-type '(unsigned-byte 8)))) (dotimes (i size message) (setf (aref message (- size i 1)) (logand value 255) value (ash value -8)))))(defun rsa (message key modulus) (integer->message (modexp (message->integer message) key modulus)))(defun char->byte (c) (coerce (char-code c) '(unsigned-byte 8)))(defun string->bytes (str) (map 'vector #'char->byte str))(defun codes->string (seq) (map 'string #'code-char seq))(defconstant +public-exponent+ #x10001)(defconstant +private-exponent+ #x7b76b46c27051c9d7f7b53f7ae749df4cc859a68bf64b94dc52f47ddffa5f5ada757fb77f44268e3dc13d73a5b33c956daad89e1138a95610005a7d219fbe621)(defconstant +modulus+ #x00c3fc2e007167c268128203050ff65ab63d736fe2fdfcdab989f2375e0939ef499b773fee6996880f7b60e10ffdf63a9e42775d52e3a28291f53ee2e784d61661)(let* ((plaintext (string->bytes "Hello, World!")) (ciphertext (rsa plaintext +public-exponent+ +modulus+))) (print (codes->string (rsa ciphertext +private-exponent+ +modulus+))))

That's certainly a challenge alright.

I never programmed a MMORPG but I imagine it as a database.
You send it a transaction, the server validates and responds.
- ok
- transgression of the game's rules (cheat)
- concurrent action failure (the chest you clicked has been already taken, the space you try to move to has become occupied, etc.)

Can someone give me a quick rundown on when it's appropriate to/how to properly dispose of pointers? I created a linked list in C++ so I could learn, but I feel like I'm creating dangling pointers and memory leaks all over because I'm still super new to pointers.

OK here's a few points for you.
1. the rule is that everything you allocate with new/new[]/malloc should be matched with delete/delete[]/free.
In an ordinary linked list, that means you'll want to clean up by removing each list node off the front and deleting it in turn.
2. Valgrind is a good tool to check your program's execution for memory leaks, and I would recommend using it, especially if you're unsure of your programming.
3. Since you use C++, at some point you should learn to use RAII, which makes memory cleanup automatic. For instance see std::unique_ptr.

4. After realising that C++ is complete trash switch to a better language like Ada, D, Nim or Rust.

None of these languages fully replace it, or they fail in various aspects where C++ doesn't.
(and I'll agree that C++ is generally a shitshow of bad language design.)
I have a git repo of benchmarked, optimized numerical code, unfortunately with my name on it, and I would challenge any Rustfag/Adafag/whatever to rewrite it and to try matching its speed.

Ada is a mess

I made the dankest flappy pepe.
u.nya.is/wfdelu.tar.bz2

#include "SDL2/SDL.h"#include #include #include #define ARRLEN 200SDL_Renderer *renderer = NULL;void render();void swap(int *a, int *b){ int temp = *a; *a = *b; *b = temp; }void stoogeSort(int *arr, int i, int j){ if(arr[i] > arr[j]){ swap(&arr[i], &arr[j]); render(arr, 1); } if((j-i+1) > 2){ int t = (j-i+1)/3; stoogeSort(arr, i, j-t); stoogeSort(arr, i+t, j); stoogeSort(arr, i, j-t); }}void random_vals(int max_val, int arr_len, int *arr){ for(int i=0;i

Let's roll again

I made it in Ocaml for a change.
This one crawls wikipedia articles and stops at Adolf Hitler.

wikicrawler.ocp

begin program "wikicrawler" files = [ "wikicrawler.ml" ] requires = [ "curl" "markup" "str" ]end

wikicrawler.ml

let dst_article = "Adolf_Hitler";;let re_article = Str.regexp ( (* url base, absolute, relative, with or without https: *) "^\\(\\(\\(https:\\)?//en.wikipedia.org\\)?/wiki/\\)?" ^ (* url path *) "\\([^#/]+\\)" ^ (* target *) "\\(#.*\\)?" ^ "$");;let get_article_links pagedata = let targets = ref [] in Markup.string pagedata |> Markup.parse_html |> Markup.signals |> Markup.iter (fun x -> match x with | `Start_element ((ns, name), attrs) -> if (String.equal name "a") then ( try let (ns, name), target = List.find (fun ((_, name), _) -> (String.equal name "href")) attrs in if Str.string_match re_article target 0 then ( let link = (Str.matched_group 4 target) in if not ((String.equal link "Main_Page") || (String.contains link ':')) then ( targets := !targets @ [link] ) ); with Not_found -> () ) | _ -> ()); !targets;;let rec follow_wikilink link depth = Printf.printf "[%d] %s\n" depth link; flush stdout; let islink = Str.string_match re_article link 0 in if not islink then failwith (Printf.sprintf "Not a link: %s" link) else let pagename = Str.matched_group 4 link in let url = "en.wikipedia.org/wiki/" ^ pagename in let buffer = Buffer.create 16384 in let conn = Curl.init () in Curl.set_url conn url; Curl.set_followlocation conn true; Curl.set_writefunction conn (fun data -> Buffer.add_string buffer data; String.length data); Curl.perform conn; Curl.cleanup conn; let pagedata = Buffer.contents buffer in let targets = get_article_links pagedata in let reach_dst = List.exists (fun x -> (String.equal x dst_article)) targets in if reach_dst then ( Printf.printf "[%d] %s\n" (1 + depth) dst_article; flush stdout; () ) else let n = List.length targets in follow_wikilink (List.nth targets (Random.int n)) (1 + depth);;let _ = Curl.global_init Curl.CURLINIT_GLOBALALL; follow_wikilink "Special:Random" 0; Curl.global_cleanup;;

how do i transfer multiple, random values of one list to another in python? i know how to use pop with this kind of thing, but it only works for one element like this:

list = ["1", "2", "3", "4", "5"]x = list.pop(random.randint(0,len(list)))

You could do it like you were doing or use sets.
import randomlst = [1,2,3,4,5]x = []for i in xrange(2): #num values you want to get x.append(lst.pop(random.randrange(len(lst))))

Using sets
import randomlst = [1,2,3,4,5] ##don't call it listx = random.sample(lst,2) #num elements you wantlst = list(set(lst).difference(x)) #this will remove all elements in x from lst

thanks a lot, hadn't thought of this.

rollo

rawl

Guess ill roll

I'm reading programming principles with c++, because im a total noob. I can't really say I'm doing much besides reading. I plan on reading k&r next

rolling

How do I learn to program properly?

I can keep coding my script shit as long as I want, but you can't learn to become a skyscraper architect by building a 1000 dog houses.

The thing is I can already make games and applications, but I don't know the first thing about what I'm doing completely wrong. As long as it works, how am I supposed to know it's stupid if all I have is myself and my stupid script?

...

I don't want to be pajeet forever m8.

I'm learning Prolog and Erlang this weekend. I'm never going to use either of them but I though it'd be fun to try out.
Prolog so far reminds me of Haskell with the pattern matching.
fizzbuzz(101).fizzbuzz(N) :- ( mod(N,15)=:= 0, write('FizzBuzz'); mod(N,3) =:= 0, write('Fizz'); mod(N,5) =:= 0, write('Buzz'); write(N) ), nl, N1 is N + 1, fizzbuzz(N1).
Though that's probably not how you would actually write a loop.

I've been reading The C Programming Language (2nd ed), and I'm currently on exercise 1-13.
So far, I've got this:
//Makes a horizontal histogram of word lengths, WIP#include main(){ int c, wl, top, bottom; top = bottom = 0; double hist[45];//Is there way to make the array "expand" to whatever input I input? give it? while((c = getchar()) !=EOF){ if(c != ' '||c != '\n'||c != '\t'|| c != '.' || c != ',' || c != '!'){ //is there a less meme tier way to say if(c = )? ++wl; } ++hist[wl]; if(wl > top) top = wl; if(wl < bottom) bottom = wl; wl = 0; } printf("\n"); while(bottom

//mixing up || and && is fairly common triple check your logic with stuff like thisif(c!=' '&&c!='\n'&&...&&){ ++wl;}else{ //you forgot this which caused wl to never go past 1++hist[wl];...wl = 0;}//for less meme tier there's#include if(isalpha(c)){++wl;}else{...}
expanding the array based on input involves using realloc() but you should probably forget that for a while as you can get some very difficult bugs if you mess it up.
You should also nearly always compile using the -Wall -Werror flags, they mean show all warnings and treat all warnings as errors.

fuck it why not
roll

I've gotten decent enough at OOP to make a shit tier game in java.
Now what? I want to make use of this skill or challenge myself but I can't really think of anything, I've started digging into C and python but learning different languages doesn't really seem like the way forward.
Also should I quit if it's just going to be a hobby? I mean making that game was pretty hard work, but even though it was utter shit it felt really good and made me think I could start making some useful shit with this, or even get into gamedev as a hobby at some point.

Make a botnet if you want monies.

I'm so despondent about everything. Everything I try goes totally wrong. There's no escape from this hole here. I feel drained. So far, I still haven't found a real purpose in life. Sometimes, I'm afraid to get out of bed in the morning. There's nothing to get up for.

Rolling

This is so relevant to the state of my life at the moment, unfortunately. At least I have finally found some relative peace in solitude. Be strong user.

join your countries military

rollin

roll

#!/bin/shls $*

rolling

Bad, this is how it should be written.
#!/bin/shexec ls -- "$@"
This is a better one.
#!/bin/shexec find -- "$@"

rollan

Just making a shitty bot for telegram IRC so that I can finally push my acquaintances back to IRC. But nooo, they HAVE to have stickers and shit.

rolling, need to git gud with C

fuck that re-rolling

great success

#include char input;int main() { printf(" ()\n"); printf("--[]--\n"); printf(" // \n"); printf(" `` \n"); printf("This is a little man, what should he do?\n"); printf("1: Hang himself.\n"); printf("Choice:"); scanf("%c",&input); if (input=='1') { printf("\n .-' `-. \n"); printf(" :` . . . `: \n"); printf(" :.` `.` `.` `.: \n"); printf(" / / / / \n"); printf(" `/ / / /' \n"); printf(" `/ Y / ||' \n"); printf(" `|' || \n"); printf(" () || \n"); printf(" --[]-- || \n"); printf(" // || \n"); printf(" `` || \n"); printf(" || \n"); printf("--------------"); printf("\nThe little man has died.\n"); } return 0;}

Rolling for Bash

Is that book decent? I need a book or something to get back into C preferably something not tailored to people who have no clue what they're doing.

"C: A Modern Approach" seems to be a pretty good introduction to C book if you can find it and find it for cheap. Otherwise, K&R's ANSI C book is everyone's Ol' Faithful.

rolling

barrelroll

reposting because I borked the code tags
Current iteration:
//Making a Histogram based on the commonness of word length, v???, electric boogaloo#include #include int main(){ int c, wl; int array[40]; while((c = getchar()) != EOF) if(isalpha(c)) ++wl; else { ++array[wl]; wl = 0; } int counter; counter = 40; while(counter > 0){ printf("%d %d letter words", array[counter], counter); --counter; } return 0;}
Here's what the output looks like for input "meme"
[email protected]/* */:~$ gcc -Wall -Werror 1.6.ex1-13-v2.c && ./a.outMeme1808507248 40 letter words0 39 letter words4195520 38 letter words0 37 letter words4195936 36 letter words0 35 letter words0 34 letter words0 33 letter words0 32 letter words0 31 letter words4196013 30 letter words0 29 letter words1 28 letter words0 27 letter words0 26 letter words32579 25 letter words817516968 24 letter words32579 23 letter words817505472 22 letter words32579 21 letter words811499944 20 letter words32766 19 letter words1808507272 18 letter words0 17 letter words-1 16 letter words0 15 letter words4195128 14 letter words0 13 letter words-163754450 12 letter words32766 11 letter words1808506912 10 letter words32766 9 letter words1808506928 8 letter words32579 7 letter words81751824 6 letter words0 5 letter words0 4 letter words32579 3 letter words81751628 2 letter words32579 1 letter words
The numbers change everytime btw. I think the problem is the loop is trying to access parts of the array that don't have any data in them, but I don't know how to fix it

Made a video player for 8ch.

It automatically finds the next video file in the thread and plays it when the current video ends.

It also shows the origin post link, and you can hover over it to see the post the video is from.

Im studying C. Currently going through the libraries section of beej's book and I'll read the C programming language after some of that.
yesterday I wrote a simple version of cat, though even though its basic it still does two more things than I ever ever use cat for. I called it chen and aliased cat to chen in my mkshrc. using software you wrote yourself is fun. The code, since its short
#include #include void chen(FILE *file){ for(char c = fgetc(file);c != EOF;c = fgetc(file)){ fputc(c,stdout); }}int main(int argc, const char **argv){ FILE *fp; if(argc == 1){ chen(stdin); } for(int i = 1;i < argc;i++){ if((fp = fopen(argv[i],"r")) == NULL){ exit(1); } chen(fp); fclose(fp); } fflush(stdout); exit(0);}
rolling for something to do next, unless its over my head right now.

stop
in rust: ghostbin.com/paste/fxh2y
output: ghostbin.com/paste/8zvdz

it's trash
use gnu cat.c: git.savannah.gnu.org/cgit/coreutils.git/tree/src/cat.c

Yeah you're right about the cause
int array[40];for(int i=0;i

...

it exits if it cant open it.
whats wrong?

this is what a simple program looks like after being worked on for 20 years.

25 years ago it was that different.
git.savannah.gnu.org/cgit/coreutils.git/tree/src/cat.c?id=b25038ce9a234ea0906ddcbd8a0012e917e6c661

rolling

rollan

It occurred to me since I can't make a lisp interpreter, that the image itself is shit. The difficulty of these varies wildly, there should be 3 different tiers with an easy, medium, and hard option for the same numbers, or something like that, so people can't constantly retreat to "rerolling" and actually have to make something.

Triangle number generator is literally just (in lua):
print("Enter number to generate triangle number.")i = io.read()o = (i * (i+1)) / 2print (o)

Whereas a lisp interpreter probably takes an hour+ to make.

I'll make connect four, it seems like a decent challenge since i'm a nodev.

Any advice on making an RSS feed reader? I'm not troubled on how to do it, I just didn't know if anyone knew of any pretty neat features or ideas for it. It seems RSS isn't really as popular nowadays and I'm not sure why.

How do I solve this?

This was actually pretty fun to make.

Currently learning Fortran because I'm no quiche eater. I'd like to use Fortran 77 for the autisms, but apparently it doesn't have many available libraries on the web.

...

Fortran has tons of math libraries if that's what you're after.
Public domain math routines which are very stable, some of which are still gold standard for current math software, free and commercial.
cf. netlib.org (blas, lapack, slatec...)

I've always had a plan to learn programming of some sort, but I never got around to it, so I'm asking for help here.
What should be my first language, what IDE should I use and where can I find some resources for learning it? I was thinking of Java, because people told me it was actually practical and not a meme language.
Please do not say Rust or any meme language or anything really hard like C.

Scheme, Racket
DrRacket, Emacs
SICP, The Little Schemer

No, you can learn it letter. Learning Java first will be no fun.
tech.jonathangardner.net/wiki/Why_Java_Sucks
You defensively don't want to deal with all of Java's drawbacks right away.
If you still want to learn something more like Java, consider Kotlin.

Those sound like meme languages.

C is one of the easier languages. What's hard about it is making big programs because it doesn't have all kinds of fancy bells and whistles in it.

wooooooow

Using a sword is easy, but winning a fight is not.

how does memory unsafety fit into this analogy?

Go eat some rusty nails if you love rust so much.

not an argument

Looks like I hit a nerve.

Also as far as the analogy, memory unsafety is you licking the blade of the sword. Gladly Rust has a safety grid around the blade for you so you can't accidentally cut your baby fingers.

Is Kotlin any improvement over Java?

ceylon > scala > kotlin > java

But can I use Ceylon/Scala without much pain on Android?

of course:
ceylon-lang.org/blog/2016/06/02/ceylon-on-android/
scala-android.org/

That's interesting. I will look into it.

In Python I have a if statement that looks like this

if a == b or a == c or a == d

is there a way for me to wrap up all that into just one thing, so I don't have to do the 'or' for each one? so, if a == either b, c or d

something like if a == (b, c, d), i tried this and it didnt work but something like that if you see what i mean

You can use "in" for that

if a in (b, c, d)

You could also use a set instead of a tuple:

if a in {b, c, d}

Essentially, this is doing a "containment" test, to see if a is either identical to (using the 'is' operator) or equal to (using the == operator) any element contained in the container.

What makes Ceylon better than Scala?

I've done a lot of Node, what exactly do you mean?

A good server to start with (at least if you use Node) is ExpressJS. Just write down everything in the tutorial down on your machine, and run it. Don't copy-paste, the writing down helps with learning.
expressjs.com/
youtube.com/watch?v=gnsO8-xJ8rs

Usually, that would mean something like thumbnail creation. On your server-side code (somewhere inside the code of that ExpressJS tutorial) you would probably import a ffmpeg package. It worries about talking to the installed ffmpeg library installed on your server. Then, you can use the methods/functions to perform different operations, all called from Javascript code in your server.

Honestly I haven't messed with this yet, but this is much more advanced.
Still, eventually you'll just install the REDIS software, install some other package in Node for your Express server to call, and then you can interact with REDIS.
I'd recommend looking at tutorials of this on Youtube, it's a surprisingly good resource.

learn python, get decent at it and moving on to something more useful will be a lot easier. theres some neat things you can do with python also and its very easy to learn.

Is there a way to change text retroactively in Python at the same place?

print(""" |||/===============\||| ||| CHARACTER STATS ||| |||=================||| ||| HP - """ + str(player.hp) + """ ||| ||| Strength - """ + str(player.strength) + """ ||| ||| Dexterity - """ + str(player.dexterity) + """ ||| |||\===============/||| """)

So print that. Then keep it in the same place on the screen and change the hp, strength and dexterity in the same spot instead of printing it out again. But at the same time there'd also need to be code below it including a raw_input for the player to make a choice of which skill to level up.


Thanks

Can we get more challenges?
Possibly less gay stuff and more math/web related? No one cares about GUIs

stackoverflow.com/questions/517127/how-do-i-write-output-in-same-place-on-the-console

Can someone tell me what's wrong with this bash script? I lost my .bashrc file from my previous installation when I moved distros so I'm making it again and I swear the syntax is fine here but it keeps behaving strangely.
function wew() {if ["$1" == "scan"] then sudo iw wls1 scan | grep SSIDelif ["$1" == "conn"] then sudo nmcli dev wifi connect $2 password $3elif ["$1" == "dconn"] then sudo nmcli dev disconnect wls1fi}

Is there any reason why you aren't using the alias command?

I just prefer having all of my little scripts in .bashrc. It's 6 of one half a dozen of the other.

roll

man 1 test

To spoon feed you, space between square brackets and the arguments and use a single equal sign.

you've fallen into the #1 trap with programming and being tech.

That's not learning \ trying something new everyday.

A lot of noob techfags think they can just get good at some particular aspect of computers, then other techfags will do the rest. It doesn't work like that except if you are god-tier fucking amazing at what you've specialized in.

You need to be able to do a bit of everything, and to be able to learn a bit of anything.

when I 1st started tech I fell into this trap head 1st. I saw others who had started the same time I did, and actually thought I was doing better than them when they ran off and started learning all sorts of bits of random other computer tech, while I just concentrated on my preferred programming language.
When I finished a product I found I was paralyzed, because I couldn't get it out on the net, set up a pay in account, use net advertising, use companies, liaise with other techies.

you have to start from scratch with a new 'jack of all trades' mindset. No one wants to hire a computer geek that can't do shit without other computer geeks to help him. You're the one who should be able to help all others wrt computers.

Its one thing to write your own code. Its a completely different thing to seriously work on someone else's code as part of a team.
If you can do the latter, you're a programmer.

Start by modding other peoples work from github. Small programs only count as warm up.
Goal is to make a legit useful fork \ mod of some large object orientated program.
That's a valuable skill. Be warned other people's object orientated code can be monstrous. Don't try tackle something too big or you will be defeated morally. Also its a big exercise in asking for a lot of help. help \ communication with other coders is a staple necessity of all coders. You need to do a lot of it. The best millionaire coders I know spend sizable amounts of their time being taught how to do the same shit, just in a different language.

rollus pocus

that's shit, rerolling

roll

I'm evaluating not assigning.

Found it, seems you have to terminate the true/false check after an elif with a semicolon.

Anybody have a recommendation for intro / mid level shell scripting pdf?

...

Dude, what the fuck.

1. c should be a char, not int.
2. You don't initialize wl, so it's going to be garbage during first iteration.
3. Since you reset wl in each loop, it's always to be either 1 or 0.
4. Hence, top is going to be either 1 or 0.
5. You don't decrease wl anywhere so bottom is always going to be 0 (or garbage if it's signed).

Also, formatting is terrible. Let the code breathe a bit.

bunny time

Make something funny with the stanford bunny.

retarded niggermonkey detected

I spend 8 hours a day on the computer and I can't force myself to learn this shit. Kill me now.

post a throw away email or discord and I might be willing to give you a hand if you're nice enough.

There's really nothing like it.

I've seen a lot of people implementing ray-tracing. Are you all into CG? Why ray-tracing?

I'm just trying to write a few programs that are somewhat complex so that I can hopefully get an entry level job.

most jobs aren't interested in raytracing though

Why what kind of thing are jobs interested in? Neural nets?

just make a few simple websites and webapps in javascript and also java. you'll have a job 30 years before a C nigger this way

Because plain ray tracer is extremely simple to implement and it looks "cool" to an average normie.

Is there a place to get a good overview of different programming languages and their differences, ideally with a preview of syntax?

I've started to think that one of the biggest reasons I don't have motivation to do things is because I don't like any of the languages I've tried. It's like you love jogging but your shoes are too small, you can do it but it's constant discomfort and wishing you had something else.

hyperpolyglot is nice. You could also try rosettacode to compare small programs.

learnxinyminutes

roll

I'm extremely new to programming but I am forcing myself to learn. I initially attempted to learn C, but I found it to be over-complicated. I was told to wait until I had reached an intermediate skill level before trying again.

I'm forcing myself to learn Python now. The syntax is quite different from C and being forced to indent is pretty annoying. Every new programmer seems to be recommended Python... I'm not going to hop languages again because I've already dumped C and I'm not gonna ditch everything I've learned in Python to learn another language, but am I going about this the right way?

learn haskell

roll

Where can I learn data-oriented programming?

People always shit on OOP but I still don't know how else to program and nobody ever points at any resources or examples.

Like show me an example of OOP code, and an example of data-oriented code, both doing the same thing.

Read SICP, learn Scheme

c is a horrible language. you should only consider learning it if you already know how to program.
python is a good beginner language. it is dynamically typed though which sucks balls. once you're comfortable with python, you should really look into a statically typed language.
the problem is just that the only "good" statically typed languages are modern c++, ceylon, crystal, rust, or functional programming languages.
c# and java suck because you have to fall back to type checking at runtime. go is a complete meme (lol no generics) and you should never learn it (unless you want shitty webdev jobs).

if I want to be a back-end Java developer what I have to know for an entry level job? what if I want to be a mobile (android) Java developer?

C is, compared to most other languages, relatively simple. To illustrate: It's a "you can actually know the ins and outs of the language without going on a pilgrimage for 20 years" kind-of simple.
That said, what makes C "difficult" for most beginners is that it barely helps you with anything. You're on your own to do pretty much anything.
It's actually not a bad starting point for a beginner. It teaches you how most other programming languages behave on the lower level, as well as how the OS expects a program to behave. It also helps you learn how to think preventively, to analyze and handle most exceptional cases you can think of.
But, if you don't like it, that's fine. Not everyone has the same goal in programming.

Python (especially version 3), is one of the most complete and powerful scripting languages available. Its overwhelming standard library will leave you with little more to desire. You can write both throwaway scripts and huge complex programs with it. Just, don't expect to get even close to mastering it in 2 years. Like you've mentioned, python (and python people) is(/are) very prickly about the code style. Indentation is a must, because it's the core of the language, but you'll rarely find a python project that doesn't enforce the PEP8 (with something like flake8, for example). This is a double-edged sword: On one hand, it forces everyone to maintain proper coding practices, and as a result, most python code looks beautiful. On the other hand, if you prefer CamelCase for anything other than objects, or prefer one space instead of two for an end-of-line comment, don't expect other people to be happy about that.
I, personally think that the PEP8 is a very reasonable code style, and employ some parts of it in other languages as well, but, as always, YMMV.

Look - in the end it barely matters what your language of choice is. "Learning" a language only starts to be effective when you're actually using it. Try making something you want to make, or contributing to some project in any language. Use google if you don't know how to do something, and don't just copy-paste, but learn how what you're copying works, and adapt it to your needs. Ask for help if you get stuck.
Continue using Python if you're looking to actually make something, learn C if you want to learn how things work on a lower level, or simply prefer it, or use any other language if you find something to do with it - I'd personally recommend Love2D if you want to make a game (Lua is a C-tier language in terms of complexity, but Javascript-tier in terms of "pick up and start using right away"). It's lots of fun.

Unless I'm misunderstanding you, it's just avoiding having useful information be meta. Most people hear about it from game devs where novices subclass the hell out of everything then run into trouble when trying to support mods or when they find themselves creating massive inheritance trees to handle 'objects' which are similar to many other objects but not in every way.

So I keep posting this on halfchan /dpt/ but nobody ever responds, and SO didn't help me either.
How should I test this code? (preferably with cmocka in mind)

args.h:
#ifndef ARGS_H#define ARGS_Hstruct args{ int count, silent, verbose; char *output_file;};int parse_args(int, char**);#endif /* ARGS_H */

args.c:
#include #include #include "args.h"/* argp requires these to be global */const char *argp_program_version = PACKAGE_VERSION;const char *argp_program_bug_address = PACKAGE_BUGREPORT;error_t parse_opt(int key, char *arg, struct argp_state *state){ struct args *args = state->input; if (args->count > 128) argp_usage(state); switch (key) { case 'q': case 's': args->silent = 1; break; case 'v': args->verbose = 1; break; case 'o': args->output_file = arg; break; case ARGP_KEY_ARG: if (args->count-- < 0) break; break; case ARGP_KEY_END: if (state->arg_num < 1) argp_usage(state); break; default: return ARGP_ERR_UNKNOWN; break; } return 0;}int parse_args(int argc, char **argv){ const char* doc = "Viewer"; char args_doc[] = "file1.jpg file2.png file3.bmp ..."; struct argp_option options[] = { {"verbose",'v', 0, 0, "Produce verbose output", 0}, {"quiet", 'q', 0, 0, "Don't produce any output", 0}, {"silent", 's', 0, OPTION_ALIAS, NULL, 0}, {"output", 'o', "FILE", 0, "Output to FILE instead of std output", 0}, {0} }; struct argp argp = {options, parse_opt, args_doc, doc, NULL, 0, NULL}; struct args args; args.count = argc; args.silent = args.verbose = 0; args.output_file = "-"; return argp_parse(&argp, argc, argv, 0, 0, &args);}

Basically all the shit in parse_args is boilerplate and setting up structs to pass to argp_parse, which then iterates over argv and calls parse_opt as a callback with the updated state.
The only problem is that argp_usage() actually terminates the program, and with it, the test.
I thought about mocking out parse_opt but it wouldn't be right to mock a function just to trivially alter its functionality, and besides, would it even make sense to test parse_opt since I cannot reasonably call it directly without having to emulate all the state of argp, so integration tests probably won't work.
I'm tempted to give this unit a VIP pass and not even test it, but then if I'm making exceptions for my tests this early in, I'm really fugged when I get to the OpenGL part of my program.
What do?

Rolling.

t. guy who never tried to write one

if college kids do it for a homework assignment it's NOT that hard

So you've written one then?

Just pronounced XEON like a Brooklyn jew would in my head.

writing a barebones raytracer is very easy you retarded nigger.

What could possibly be difficult about this?

I learned Java first, its syntax is similar to C, but it's a lot more gentle on you than C is. Granted tis also not as useful as C imo.

You're kind of proving his point. If you understand vectors, this picture gives you straightforward equations to use (even though they are very long). That said, if you asked me to start calculating this manually on paper, I'd start running. But this sort of rote calculation is straight-forward to program, because there's not a lot of complex state management (at least, not in the picture).

So you've written one then?

You too. Holla Forums sure isn't filled with larpers.

New to C, it seems to work, but can anyone tell me if there are any huge errors in here? I tried to write a function for getting string input of an unknown length from stdin safely.

#include #include char *readstring(const char *prompt){ size_t capacity = 4, len = 0; char *str = malloc(sizeof(char) * capacity), *returnstr; printf("%s", prompt); int c; while (1) { c = getchar(); if (c == EOF || c == '\r' || c == '\n') { str[len++] = '\0'; returnstr = realloc(str, sizeof(char) * len); if (returnstr == NULL) return NULL; else return returnstr; } else { if (len < capacity) str[len++] = c; else { str = realloc(str, sizeof(char) * (capacity *= 2)); if (str == NULL) return NULL; str[len++] = c; } } }}int main(void){ char *input = readstring("Enter a string: "); printf("%s\n", input); free(input); return 0;}

there is nothing difficult about this image.


i have not written one. im not really interested in that stuff. but i know how raytracing works (it is very simple). all you need is a basic understanding of linear algebra.
the hard part is making it run and look good in real time.

i actually agree


fn main() { print!("Enter a string: "); let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap(); println!("{}", input);}

...

I don't see any huge errors, but I'd make few changes.
[code]#include
#include

char *readstring(const char *prompt)
{
size_t capacity = 4, len = 0;
/* >sizeof(char) */
char *str = malloc(sizeof(char) * capacity), *returnstr;
/* you're chacking realloc for NULL, why not malloc? */

/* printf is overkill */
fputs(prompt, stdout);

int c;
while (1) {
c = getchar();
/* swich IMO makes the intent clearer */
switch (c) {
case EOF:
case '\r':
case '\n':
str[len++] = '\0';
return realloc(str, sizeof(char) * len);
/* chacking for NULL is pointless, if you're just gonna return value identical to returnstr */
default:
/* you're assinging c to str[len++] either way, so just have condition for realloc */
if (len >= capacity) {
str = realloc(str, sizeof(char) * (capacity *= 2));
if (str == NULL) return NULL;
}
str[len++] = c;
}
}
}

int main(void)
{
char *input = readstring("Enter a string: ");
/* puts will do just fine */
puts(input);
free(input);
return 0;
}

Don't swap between printf and fputs, that's premature optimization. If someone needs to tweak the prompt, they shouldn't need to change the whole function around. It's pointless in this case anyway as modern C compilers are smart enough (yes, even gcc) to detect a string that has no formatting options and will convert it to a call to puts.

So, I'm learning java for uni reasons
I already know the basics and have to turn in a small game and its documented sourcecode to pass an exam
I'm following this YT series to learn the fundamentals of gamemaking am I doing right?
youtube.com/watch?v=qWVUQPWa67M

pathetic

pathetic

Sure thing user. I too am an expert in things I don't care about and have never done.
Just like make code.

not an argument


never even come close to saying this. i was talking about a _barebones_ raytracer. i fully acknowledged that a fully-featured, real-time raytracer is hard.
even javashit niggers can write raytracers (github.com/diasdavid/simple-raytracer). but you are still whining about how hard raytracing is.
protip: you learn everything you need to know about writing a simple raytracer in the first few lectures of linear algebra at university you faggot.

I'm no expert but it's super simple just: rendering equation + real-time = raytracer. Pretty fucking easy. All you need is first year algebra and probably trigonometry, the hardest part is pythagoras theorem but the rest is trivial.
Now I've never written a real-time anything but that's just because it doesn't interest me like I've already solved it just by thinking it, why would I even bother typing the code in.

Roll

is D worth learning? It looks like (and advertizes itself as) an unfucked C++. It hasn't had much traction though, and therefore libraries are a bit scant.

Thank you, that was a big oversight by me not checking the original malloc for NULL. I noticed it was pointless to use char *returnstr at all in the time between posting this and you replying though, thanks.

Why is this code giving me a segmentation fault?

#include #include #include void fn(char **str){ size_t capacity = 3; *str = malloc(sizeof(char) * capacity); *str[0] = 'a'; *str[1] = '\0'; return;}int main(){ char *str; fn(&str); free(str); return 0;}

[] has a higher precedence than *, so when you say *str[1] = 0, you are writing to the second element of str, which does not exist, rather than the second element of *str. Wrap the *str in parentheses.

No. It requires GC to be useful in any way and that excludes it from nearly every domain C/C++ still thrive in.

Thank you very much, I have been struggling for over an hour and couldn't think of the right keywords to google.

this wouldn't have happened with rust

sprunge.us/BGHd

Maybe, but it turns you into a massive faggot.

not an argument

Say I have something like this
struct X{int a,b,c;};struct Y{int a,b,c,d,e;};
And I have some function that for example wants to get the value of a in either type of struct.
How do I do this in a way that doesn't involve duplicating loops for both structs I write?
I think I'm going wrong in my design.

use arrays

That may be, can't help you without the details, could a union be helpful? Anyway, since a is first I'm pretty sure you cant just cast the value or pointer to int.

templateint get_a(const T& t){ return t.a;}


:^)

Thanks anons I think you're right.

tbh I'd be even more confused in sepples. I learned sepples with a heavy reliance on inheritance so my mind is kinda ruined in that language.

macro_rules! a { ($e:expr) => { $e.a }}

Like this:
struct parent { int a, b, c; };struct child { struct parent p; int d, e; };int get_a(struct parent *p) { return p->a; }int main () { struct child c; int a = get_a((struct parent)&c);}

That code uses templates; there's no OOP in it at all.


#define GET_A(t) ((t).a)


:^)))))))

Your shorter life expectancy tells me otherwise

still not an argument

Is there a standard I should follow in C for functions that return a pointer to dynamically allocated memory so the programmer calling the function remembers to free it? For example, would prepending the function with an m (m_function()) be ok?

yeah there is. it is called a "memory safe language". there are actually a wide variety of languages that are "memory safe".

No. Generally, C programmers assume that when they're handed a pointer that there's a corresponding function to free it unless told otherwise. If you have a function that creates something that needs cleaned up, create a function to clean it up, don't tell them to call free() directly on it even if it would work. Like, foo_query_dildos() -> foo_query_free().

Back to India, Pajeet.

For example

int readstring(char ** str, char *prompt){ // code that prompts for user input}int main(){ char* str; readstring(&str, "Enter a string: "); // free(str) return 0;}

You would make a function called readstring_free(char *str)?

Yeah, always have a corresponding free function, don't leave it to the caller. You might someday want to use pooled memory or a custom allocator internally and you don't want to have your hands tied.

If it's just something like a string, I'd just have the user use free, and have foo_free(...) only when it's a custom struct or something like that.

Rolling for something to learn scheme for.

I'm learning basic syntax over at codecademy (I know it's shit for learning code, but it's good for picking up the basic concepts that I never had a chance to learn because ghetto High School) and plan to jump over to freecodecamp afterwards. Are there any resources I should be made aware of?

I don't really need programming for my job at the moment. It's more I'm just learning for fun and to keep busy/as an extra skill to have on hand when I make a minor career swap (currently in Electronics Manufacturing/Process Controls, plan to go into the navy as a CTN Cryptological Network Technician next year in order to increase employability at the $25/hour+ jobs since my current wages are in the $15-$20/hour range).

Current knowledge:

Oh, and education level is some Mechanical Engineering (dropped out because had to support family financially, that's where I picked up MATLAB for Physics/Calculus), a dozen certifications, and an AAS in Electronics Technology.

if you're joining the navy they'll teach you everything you need to know, no point in doing it on your own because you probably wont pick the right stuff. Learning programming for "employability" and never actually using it is fucking dumb though. No one cares that you "know" it because it's impossible to prove, they care that you actually did things with it.

Military teaches stuff to stupid standards that are worthless in the real world 99% of the time anyways. It's why so many military nurses/doctors can't find employment with hospitals.

I think you're missing the point.

Not the guy you're responding to, but wouldn't it be possible to implicitly cast the type when calling get_a, to avoid casting it yourself? I guess you'd get a warning, and it'd be dangerous since both types are incompatible.
Wouldn't get_a(&c.p) work? With proper names this'd be more clear, less error-prone (it'd allow you to relocate struct p around in c), and the compiler wouldn't whine.

This would work if the compiler knows the type of the struct, but then user probably wouldn't have a problem in the first place. He probably has a void pointer or something.
Although I agree, you should do get_a(&c.p) it will work even if you move the parent around in the struct. I don't know what that user was thinking.

The casting he's doing is a result of having learned OOP first and it damaging the brain. In the real world of professional C projects, we all use something like you'll find in Linux, 'container_of', rather than emulating single inheritance.

I'm not sure what problem you were trying to solve user.
for each parent: get_a(&parent);for each child: get_a((struct parent) &child);//vs naive solutionfor each parent: parent.a;for each child: child.parent.a;
And I'd now have hardcoded the parent struct to be at the start of the child.

Everyone told me my project is shit, but I'm okay with it.
What do you think, Holla Forums? Is the code okay? Or should i rewrite some parts? I know that the app itself is not that good, but it's not done yet.

github.com/7Y2RPXK3ETDCNRDD/Koondelick

I'm fucking bored anyway, roll. will post code

Already created one before but it's at my home PC, so what the hell.

What said. I was assuming that the user has an array of pointers to stucts of both types, which is why I highlighted that he could treat the child as if it was the parent. If he had the type of the struct, he could just have two separate get_a functions.

if ((str = malloc(size) == NULL) return 0;
or
str = malloc(size);if (str == NULL) return 0;

if (!(str = malloc(size))) return 0;

I only looked at the last commit real quick, but are you aware you're doing capture by value here? It doesn't look like you intend to copy daytask but you are.

connect(task_container.findTask(daytask.task_id), &Task::Deleted, [date, daytask] {

Not safe enough.
Liek dis:

#include #include #include #include #ifdef __GNUC____attribute__ ((format(__printf__, 1, 2)))#endif_Noreturn void die(const char *format, ...){ va_list vargs; va_start(vargs, format); vfprintf(stderr, format, vargs); va_end(vargs); exit(EXIT_FAILURE);}#define DIE(fmt, ...) die("ERROR [ %s:%d in %s() ]\n" fmt, \ __FILE__, __LINE__, __func__, __VA_ARGS__)#ifdef __GNUC____attribute__((malloc))#endifvoid *safe_malloc(size_t n){ errno = 0; void *p = malloc(n); if (!p) { perror(NULL); fprintf(stderr, "Could not allocate %zu bytes\n", n); DIE("%s\n", "Exiting..."); } return p;}#ifdef __GNUC____attribute__((malloc))#endifvoid *safe_realloc(void **ptr, size_t n){ errno = 0; void *p = realloc(*ptr, n); if (!p) { perror(NULL); fprintf(stderr, "Could not allocate %zu bytes\n", n); DIE("%s\n", "Exiting..."); } return p;}void et_freep(void **p){ free(*p); *p = NULL;}char *readstring(void){ const char *prompt = "Enter a string: "; size_t capacity = 4, len = 0; char *str = safe_malloc(sizeof(char) * capacity), *returnstr; printf("%s", prompt); int c; while ((c = getchar()) != EOF && c != '\r' && c != '\n') { if (len < capacity) str[len++] = c; else { str = safe_realloc((void**) &str, sizeof(char) * (capacity *= 2)); str[len++] = c; } } str[len++] = '\0'; returnstr = safe_realloc((void**) &str, sizeof(char) * len); return returnstr;}int main(void){ char *input = readstring(); if (input == NULL) DIE("%s\n", "something borked"); printf("%s\n", input); et_freep((void**) &input); return EXIT_SUCCESS;

I should note, while it's removed there's no indication it was because you realized it was a copy so I figure it's likely this mistake would be in other parts of the code.

why is it not safe enough?

'Handling' errors by tearing down the user's process from within a library is itself an error.

He's probably an angry rustfag with nothing to do but troll while his helloworld.rs undergoes an hour long compile.

bump

why is it not safe enough?>>776024
You didn't post any code.

I'm the one who posted

Can anyone tell me why this keeps printing the same memory address?

#include #include int readstr(char **str, const char *prompt){ size_t capacity = 8, len = 0; if ((*str = malloc(sizeof(char) * capacity)) == NULL) return 0; fputs(prompt, stdout); char c; while (1) { c = getchar(); if (c == EOF || c == '\r' || c == '\n') { (*str)[len++] = '\0'; if (len < capacity) { if ((*str = realloc(*str, sizeof(char) * len)) == NULL) return 0; } return 1; } else { if (len < capacity) (*str)[len++] = c; else { capacity *= 2; if ((*str = realloc(*str, sizeof(char) * capacity)) == NULL) return 0; (*str)[len++] = c; } } }}int main(void){ char *str; while (1) { if (!readstr(&str, "Enter a string: ")) { puts("Failed to allocate memory, exiting."); break; } if (!strcmp(str, "exit")) { puts("Exiting."); free(str); break; } else { printf("You entered: %s\n", str); printf("Memory Address: %p\n", &str); free(str); } } return 0;}

No. But I can give you a pointer to a pointer.

Because you're freeing it and the allocator is reusing it. Or is your concern that realloc isn't changing the address on the longer strings? I've not looked at your function in depth but realloc not changing the address isn't unusual. Allocators generally use blocks larger than your allocation, and when that's the case, it's practically free for them to resize a block that still fits inside the real allocation.

Btw, you probably are writing a null outside the bounds of the array if you type exactly 8 characters then hit enter. At least, just from eyeballing it that's what it looks like to me.

Don't wrap lines and omit braces. Either put it all on one line or use braces.

nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/

Weird, it works fine with exactly 8 characters, but I see now. Does this fix that? It seems to work either way for some reason.

#include #include #include int readstr(char **str, const char *prompt){ size_t capacity = 8, len = 0; if ((*str = malloc(sizeof(char) * capacity)) == NULL) return 0; fputs(prompt, stdout); char c; while (1) { c = getchar(); if (c == EOF || c == '\r' || c == '\n') { if (len < capacity) { (*str)[len++] = '\0'; if ((*str = realloc(*str, len)) == NULL) return 0; } else if (len == capacity) { if ((*str = realloc(*str, len+1)) == NULL) return 0; (*str)[len++] = '\0'; } return 1; } else { if (len < capacity) (*str)[len++] = c; else { capacity *= 2; if ((*str = realloc(*str, capacity)) == NULL) return 0; (*str)[len++] = c; } } }}int main(void){ char *str; while (1) { if (!readstr(&str, "Enter a string: ")) { puts("Failed to allocate memory, exiting."); break; } if (!strcmp(str, "exit")) { puts("Exiting."); free(str); break; } else { printf("You entered: %s\n", str); printf("Memory Address: %p\n", &str); free(str); } } return 0;}

I'm currently freelancing. Right now I'm doing an Android game and a bruteforcer for algebra problems in C# (type in equation, plugs in fucktillions of different numbers from 0.0000000 to 10000000000000 until it gets the answer).

pleb

I have literally never made that kind of error, and if I did, gcc would warn me.

No, it didn't. It wrote out of bounds and went into undefined behavior. Welcome to C. This is a great opportunity for you to learn to use valgrind as it's essential to C development:

[email protected]/* */:~/tmp$ valgrind ./a.out==26362== Memcheck, a memory error detector==26362== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.==26362== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info==26362== Command: ./a.out==26362==Enter a string: 12345678==26362== Invalid write of size 1==26362== at 0x108972: readstr (in /home/user/tmp/a.out)==26362== by 0x108A60: main (in /home/user/tmp/a.out)==26362== Address 0x51d7048 is 0 bytes after a block of size 8 alloc'd==26362== at 0x4C2BBAF: malloc (vg_replace_malloc.c:299)==26362== by 0x10890B: readstr (in /home/user/tmp/a.out)==26362== by 0x108A60: main (in /home/user/tmp/a.out)==26362====26362== Invalid read of size 1==26362== at 0x4C2EDB4: strlen (vg_replace_strmem.c:454)==26362== by 0x4E80D77: vfprintf (vfprintf.c:1637)==26362== by 0x4E871F8: printf (printf.c:33)==26362== by 0x108ABB: main (in /home/user/tmp/a.out)==26362== Address 0x51d7048 is 0 bytes after a block of size 8 alloc'd==26362== at 0x4C2BBAF: malloc (vg_replace_malloc.c:299)==26362== by 0x10890B: readstr (in /home/user/tmp/a.out)==26362== by 0x108A60: main (in /home/user/tmp/a.out)==26362==You entered: 12345678Memory Address: 0xfff0003c8

Other problems:

- your code continues running after hitting EOF. Try 'echo hi | ./yourshit'. It will spam you forever.

- you're printing the address you stored the pointer at not the pointer itself.

- the 'if(len == capacity)' is unnecessary - that condition will always be true in the else.

- the unreachable code that returns 1 would leave the string unterminated and the main() function would read out of bounds into undefined behavior.

- if realloc() fails, the block isn't freed. So you have several memory leaks on error conditions.

- the loop is way overcomplicated and hard to visually debug. I'd reject this commit just having glanced at it.

- (style) The API of readstr is unnecessarily complicated and should return a pointer.

A quick rewrite that may or may not be correct as I was in the middle of masturbating when I saw this thread update and I need to get back to it:

#include #include #include #include char *readstr(char const *prompt) { char *str = NULL; size_t capacity = 0, initial_capacity = 8, len = 0; char c, out; bool done = false; fputs(prompt, stdout); while(!done) { c = getchar(); if(c == EOF || c == '\r' || c == '\n') { c = '\0'; done = true; } if(len == capacity) { if(!capacity) capacity = initial_capacity; else capacity *= 2; if(!(str = realloc(str, capacity))) { free(str); return 0; } } str[len++] = c; } if(!(str = realloc(str, len))) { free(str); return 0; } return str;}int main(void) { char *str; while(!feof(stdin)) { if(!(str = readstr("Enter a string: "))) { puts("Failed to allocate memory, exiting."); return 1; } if(strcmp(str, "exit") == 0) { puts("Exiting."); free(str); break; } else { printf("You entered: %s\n", str); printf("Memory Address: %p\n", str); free(str); } } return 0;}

Don't be a faggot. That style has caused numerous security problems, there was one in Jabber 1.4.2 I personally found, and even if you're Mr. Perfect the people who work on your code long after you're gone might not be. Don't leave landmines in code you fucking Pajeet.

I fucked up and the realloc needs to not overwrite the str ptr on error so you can free it. Anyway, you can fix that.

Your attempted fix of the realloc leaks calls free(NULL). Haven't checked the rest because fuck that's a lot to read right now. Good job on checking it out though.

free(NULL) isn't an error.

It doesn't fix the realloc leak though. As he mentioned here which wasn't posted yet when I was writing my message.

I'm those (you)s. I know.

Did you miss
? I actually pay attention to compiler warnings. If the people who work on my code in the future don't, then perhaps they are the Pajeets.

Quick fix just for completeness before I wander off for a bit.

#include #include #include #include char *readstr(char const *prompt) { char *str = NULL; char *newstr; size_t capacity = 0, initial_capacity = 8, len = 0; char c, out; bool done = false; fputs(prompt, stdout); while(!done) { c = getchar(); if(c == EOF || c == '\r' || c == '\n') { c = '\0'; done = true; } if(len == capacity) { if(!capacity) capacity = initial_capacity; else capacity *= 2; if(!(newstr = realloc(str, capacity))) { free(str); return 0; } str = newstr; } str[len++] = c; } if(!(newstr = realloc(str, len))) { free(str); return 0; } str = newstr; return str;}int main(void) { char *str; while(!feof(stdin)) { if(!(str = readstr("Enter a string: "))) { puts("Failed to allocate memory, exiting."); return 1; } if(strcmp(str, "exit") == 0) { puts("Exiting."); free(str); break; } else { printf("You entered: %s\n", str); printf("Memory Address: %p\n", str); free(str); } } return 0;}

-Wmisleading-indentation isn't on by default and isn't in all compilers or versions of gcc that are still in use today. Don't make excuses for being a fuckup that compiler authors have to babysit. These are powerful tools with few safeties and you need to be careful with them. Write safe code or or go back to webdev.

Rajesh pls

...

That return 1 isn't unreachable, 1 is returned every time as long realloc doesn't fail, it is just incorrectly indented.

I don't pass the actual model data around, only their id.
Well, currently the view is responsible for redrawing itself after asking the controller to remove data from the model. It might be better to move that functionality to a controller. Thanks, user.

I meant to say "only their copies"

It looked like more than id to me. The task_id gets copied, but then the whole daytask it came from gets copied, too.

roll goes in all fields

nice get but wasted on no delivery

I literally just made that post. I'm not god (yet).

ok maybe that get will be wasted. I'm not that experienced with programming (I spend far more time learning about it than doing it) and I don't even know morse code. I've only made an ASCII code to text converter and that was by accident.

bump

Some time has passed since then, so how far have you gotten in making the game? Are you stuck on something? Is there something you need to know that the tutorial doesn't provide?

I worked eight hours to embarass this faggot, where are the (You)s

Thank you for all your help, especially this post .

I rate it ">vector class"/10.

I want to learn programming. What language should I learn and how?

if you worked eight hours to prove how easy it was then congrats user you won. Please post your address so I can send you the prize.

From one beginner to another I reccomend C, starting with Beej halls guide to C and then onto whatever other book, im doing K&R now.
Its been the easiest for me out of all the ones ive tried because its simple and fairly explicit.
Books for python expected me to just do vague shit and have it just werk lol look its so easy!!!
So I got confused because 'how the fuck do I know what this will do in literally any other situtation other than this specific one?' and gave up.
in C, with the book I reccomend at least, its clear what you're actually doing not just what you're using it to achieve, so you can understand what it would do elsewhere.

rollan

stop. kill yourself.
c is a horrible language full of bad design decisions. there are only very few reasons why you would ever want to use c and being a beginner is definitely not one of them.
just an example of the insanity that c is:
blog.llvm.org/2011/05/what-every-c-programmer-should-know.html
blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html
blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html

blog.regehr.org/archives/213
blog.regehr.org/archives/226
blog.regehr.org/archives/232

No, I'm implementing basic jump physics and gravity, but since it's my first attempt at this, maybe i'm doing something wrong

...

What languages are they trying to make you use?

All I read from your links is that UB enables optimizations and bad compilers produce bad results.

but user. I, as a beginner, have found C easier and nicer than other languages, and its helped me learn much better than any others.
If I find issue with it later I can learn a new language later.
I dont yet know enough to tell, and will not just listen to someone on Holla Forums who really comes across like a LARPer whos made a decision about what their gimmick is. So far it seems well designed and elegant to me, but I'll see as I learn :)

c is the opposite of well designed and elegent. but whatever have fun unlearning c when you discover it's harmful. should have learned ocaml/haskell.

cl.cam.ac.uk/~pes20/cerberus/notes50-survey-discussion.html
lol

That's how it goes fast you fucking webdev. If you can't handle it safely, stick to webdev languages someone built with C that keep you safe from yourself.

not an argument

What language do I do first?

...

Go ahead and remove all the UBs in this function without harming the speed, faggot. Show us how they aren't necessary in a low level gotta go fast language and it was all just poor design rather than intentional so we could make your shitty webdev languages that protect you from yourself run fast. x and y should be treated as unavailable until runtime.
int foo(int x, int y) { return x

C disassembly:
foo:.LFB0: .cfi_startproc movl %edi, %eax movl %esi, %ecx sall %cl, %eax ret .cfi_endproc

The equivalent in Rust:
pub fn foo(x: i32, y: i8) -> i32 { x str.0: .ascii "/tmp/compiler-explorer-compiler117712-6-sunx0v.uvaq0k9/example.rs"str.1: .ascii "attempt to shift left with overflow"panic_loc.2: .quad str.1 .quad 35 .quad str.0 .quad 65 .long 3 .zero 4

lol

Nim.

enjoy getting buttraped thanks to ub. i will gladly take a minimal performance hit in exchange for a big security gain.


rust doesnt do overflow/underflow checking with optimizations enabled. as always cfags demonstrate that they are just larpers who can only write hello world/fizzbuzz/echo in c.
lol

haskell tbh
learnyouahaskell.com/chapters

What's the best resource for learning Python?

roll

What a joke.

I thought Rust was supposed to not let undefined things happen? What's the point of it, then?

stop posting retard. in rust overflow/underflow is defined.

You can't really prevent a shift depending on user input from failing, except, well, prohibiting user input from manipulating the amount of bits shifted. I'm unsure if Rust does this.
In any case, yes, Rust, and any kind of programming language that doesn't run in a VM will have some kind of UB. You can't support multiple architectures without it.

shift is defined in rust.
rust has no ub.

How? What happens on under-/overflow depends on the architecture.

The issue is a shift of 32 on a 32 bit value is defined differently on some processors, so this is more than just overflow/underflow. This has been used to exploit certain machines. Some return the original value, some return 0.

Nope, it obviously isn't.

no it isnt

yes it is

All of those UBs are literally not defined in release mode in Rust, I just tested it. They all generated undefined behavior unless compiled in debug mode.
Rustfags are still going to have integer overflow CVEs, lol.

You're full of shit. I would believe Rust prevents you from doing it, either at compile time or at runtime by throwing an error (with all the runtime costs that has). You can, however, not "define" undefined behavior without having any kind of runtime costs.

LARPer.
You would be wrong. Rust is garbage and allows nearly as much undefined behavior as C. Use Java or .NET for secure software, Rust is UNSAFE BY DESIGN.

Go to play.rust-lang.org/?version=stable&mode=release and put this in:

extern crate rand;use rand::Rng;pub fn foo(x: i32, y: i8) -> i32 { x

nigger are you retarded? rust has defined overflow/underflow semantics. if they align with the target architecture all is good. if not, rustc will have to emit some additional instructions to make it behave the way rust specifies. what so hard to understand about this? rust has no ub.

>371671665

It's like the MySQL of languages.

Nigger, do you even read?


All I'm trying to say is that is wrong. Safety has a runtime cost.

rust allows no ub.


look it up nigger: doc.rust-lang.org/std/primitive.i32.html
>Panic-free bitwise shift-left; yields self

lol

there is no undefined version. in debug mode

Except you did.

This implies that it does whatever the CPU decides to do, which is architecture-dependent, and thus, undefined.
Even if that wasn't you, fucking read the thread before responding.

The value still gets smaller from shifting it left. Even if you define this incorrect behavior as correct, it's still going to fuck up software. Java and .NET prevent this. Rust is unsafe.

no it says that rust inserts no code to check if overflow/underflow happens. it doesn't imply anything.
i read the whole thread


not an argument

...

If you don't insert code to check for the overflow flag or other way to determine whether it has overflowed, you can't have your defined behavior.

No you don't understand. Integer overflow in C is undefined behavior and bad. But the exact same integer overflow in Rust is defined because we said so so it's good. C is dead!

>yields self

integer overflow is defined in rust. so it isnt the same as in c

But the exact same shit happens, nigger. Exactly the fucking same result.

with c it depends on the target architecture and the compiler. with rust it is the same on every architecture.

It's the same in C on every modern compiler and architecture. You could put a configure.ac rule in that only allows building on targets where it does this to "define" it just like Rust, but it's still both integer overflow and a shift operand error that are being allowed to produce garbage results.

lol. what about compilers and architectures that arent modern?
>Panic-free bitwise shift-left; yields self

I can't think of anything after 1960 that might do it differently. Can you?
>371671665

it is what rust is defined to produce. it isn't rusts fault if the programmer is too retarded to know what shifting left does
play.rust-lang.org/?gist=416528422184ca383339a895bff5c366&version=stable

Ok kid.

nice strawman.
i never said that the result is garbage. that was you.
i never said that when c does it, it's bad. that was you.
i only said that overflow/underflow is defined in rust.

What's the point of rust then if it just says unsafe, unexpected behavior is defined? It's basically just C with bounds checking at that point, so if I want real safety I should be using .NET, right? The rust is for safety thing seems to have been a meme.

LMAO. Holla Forums is so fucking retarded.
>371671665

it it unexpected to you because you are retarded.
no. you don't a fucking clue about rust nor c. i suggest that you learn to program or leave this board.
c# is a "good" beginners language

ARM:

LMAO

Go suck a CoC, rustfag. It's clear if I want security that rust is the wrong language and that Java and .NET provide superior safety at similar speeds.

I don't know what to say. I hope I'm being trolled.

lol
lol no fearless concurrency

What's more important, a speed difference of a few percent, or not getting pwned by an integer overflow or a shift operand overflow?

wew lad.

ideone.com/qqVjao
SUPERIOR SAFETY

...

lol

Wow, that's pretty terrifying. So Java/.NETfags have to write it as 371671665 * (2 = width of type [-Wshift-count-overflow] std::cout

rust declines to compile
play.rust-lang.org/?gist=37bd152f6bc7fb6c4c469f6789e53014&version=stable

what did you expect? 0?

same problem user. 2 is a signed 32 bit integer in java/.net

2

You expect a signed left shift to silently make a positive number negative? Programmers usually don't, which is why we have integer overflow CVEs.

In .NET,
Console.WriteLine("{0}", 371671665 * (1

Rolling.

Looks like Java and rust are unsafe, and .NET and C++ are safe.

...

i expexted it to shift left by 38 & 31.
this has nothing to do with overflowing.


actually rust declines to compile

larper defeated

...

???
dont use signed integers if you dont want negative values

lol

First shitty attempt, I'll probably give it a GUI or something so that it's a bit less trivial. Maybe throw in some other factors like sex.

So C/C++ integer overflows and shift operand errors are now considered safe, rustfag?

It's a signed shift (sar). x86 handles overflow in retard mode and changes the sign while ARM does it safely. Rust has decided to define retard mode as correct (obviously for benchmark reasons) and will be slow as shit on ARM as they'll need to emulate doing it wrong. Meanwhile, programmers are exposed to integer overflow errors just like in C and C++.

it isnt
it isnt

Rolling

I avoided Rust because the syntax seems like an ightmare, I've considered learning it because of their claims of it being safe and fast, to learn it's not even safe, their main gimmick, makes me lose interest all over again.

I'm not the guy shilling rust, I haven't even learned it for the same reason you specified. However, I'd like to make an effort to correct this.
Rust is a *memory*-safe language. With it's design it can prevent all kinds of memory-related errors such as reading out of bounds or use-after-free. It can't, however, be *logically* safe.
If you overflow a number, rust will try to prevent you from doing it, but it can't prevent all cases of it. However, Rust *defines*, in contrast to other languages, what happens when you do so. This means that overflowing or shifting a number too much will always do the same thing on every platform, and it might need to generate some extra code for that.

Yes, it still accomplishes what it set out to do.
No, it can't solve a programmer being out-right retarded, it can only help prove that several kinds of errors are not possible within your program and tries to prevent the rest by removing undefined behavior and warning you.

Also, I'd like to add this article for further reading, because Holla Forums is retarded.
huonw.github.io/blog/2016/04/myths-and-legends-about-integer-overflow-in-rust/

doc.rust-lang.org/reference/behavior-not-considered-unsafe.html

github.com/rust-lang/rfcs/blob/master/text/0560-integer-overflow.md
>Shift operations () on a value of with N can be passed a shift value >= N. It is unclear what behaviour should result from this, so the shift value is unconditionally masked to be modulo N to ensure that the argument is always in range.

compare that to ansi c:
>The value of E1E2 is E1 right-shifted E2 bit positions. The right shift is equivalent to division by 2^E2 if E1 is unsigned of if it has a non-negative value; otherwise the result is implementation-defined

compare that to c89:
port70.net/~nsz/c/c89/c89-draft.html#3.3.7

port70.net/~nsz/c/c89/c89-draft.html#A.6.2

oops ignore the "compare that to ansi c:" section

I'd understand lying about experiences because the workforce's fascination with that thing, but when you lie about education you just shot yourself in the foot. I actually don't mean like a degree or something, I mean education as in knowing what to do without relying on Google. I mean they're going to depend on you to do the job quickly. But this is doable. Hard, but doable to quickly learn the programming you need for the job. Another advice is to find a way to google the things you need without your job finding out.

Knight's tour was a fun one. I transform the square array into a linear one, and calculate all legal moves for each field.
Initial solution was just a simple brute force with backtracking when you get stuck. Worked up until 7x7. 8x8 would probably take somewhere between a few hours and a day.
Next I implemented the Warnsdorff rule and added some bookkeeping to the array with legal moves to keep track of steps taken incase back tracking is needed.
8x8 take milliseconds to calculate. Even 180x180 gets finished in about half a second, and even then most time is spend in printing the result to console.

Roll

Not sure where to ask this, so I'll just ask it here.
I was looking into reversed index search and I'm not sure I understand how it works.
From what I understand it's basically taking all info that you could search for(such as book title, in the pic) and leaving it in another file pointing to each respective file.
If that's correct, then, using the books example, how is it faster than just having something like an array of book structs and just checking the propriety "name" from each? It would only be better than that if you have a fuck load of books saved each in it's own file, then you wouldn't have to load each file into RAM, only the reverse index list, which has a considerably smaller size, thanks to the lack of useless info. That would only make it lighter on RAM though, and not faster.

The index can have better search times due to being smaller as well as having a non-linear structure such as a tree or hash table which would have a better time complexity.

anons, I'm wanting to learn a lower-level language. I'm fairly proficient with python (for scripting) and lisp (for larger functional-type programs).

I thought of learning D, but anons have said its immature and lacks programs to use as learning experience. Should I just go C, or maybe something else?

Also it'd be great if you have any suggestions for a book on the language.

forgot to mention: preferably something that covers low(er)-level programming in general as well as the language. From browsing K&R it seems rather more of a specification of C than a book to learn the language as a programming noob.

If you're coming from higher level languages, then C might seem a bit unwieldly. You'll probably need to spend quite a while re-thinking how you write programs.

You won't find a lot of books that teach you C without any background. Most of them expect you've either programmed before or you know assembly and want something that maps to it.
Usually, it doesn't really matter how many people use a language, or how many examples there are, unless you're looking to contribute to something or want employment. For all other purposes vritually any language is okay, as you can just figure out your style yourself, and can get by with the API docs.

I didn't know about that. Thanks user.
Also, to add to that, some guy who works with databases told me the best thing about reverse index search is having a common propriety listed a single time for multiple objects/structs. Going back to the book example because I can't explain shit without examples, if you could search for authors, something which is usually repeated a lot in large book databases, you could have each author listed a single time, each which would then point to a fuck ton of books.