Index

C Compendium

IO

FILE* fout = stdout; 
fprintf(fout, "hello\n");
//stdout is := fdopen(1, "w");
read_items = fscanf(fin, "%20s %20s", vn, nn);
fprintf(out, "hey");
fflush(out);
void flush(FILE* in) //superior to fflush, somehow
{
    char buf;
    for(;(buf = fgetc(in)) != '\n' && buf != EOF;);
}
fprintf(out, "\033[H\033[2J");

Files

FILE* out = fopen("test.txt", "w");
int fd = fileno(out); //!
close(1); //closing stdout
dup(fd); //stdout is now "test.txt"
FILE* out = fdopen(1, "w");
fprintf(out, "hello\n");

Memory

new->vn = malloc(strlen(vn)+1);
new->nn = malloc(strlen(nn)+1);
strcpy(new->vn, vn);
strcpy(new->nn, nn);
char* str = malloc(sizeof(char)*16);
snprintf(str, 16, "%u.%u.%u.%u", x0, x1, x2, x3);

Multi- Proc/Thread

int pid = fork();
    if(!pid) //child
    {
        ...
	exit(EXIT_SUCCESS);
    }
    else //parent
    {
        wait(NULL);
        ...
int fd[2];
pipe(fd);
int pid = fork();
if(pid) { write(fd[1], "parent->child"); }
else { write(fd[0], "child->parent"); }
void* thread_callee(void* data)
{ ... }

void thread_caller()
{   
    struct data info;
    pthread_t num;
    // int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);
    pthread_create(&num, NULL, thread_callee, (void*) &info);
    pthread_join(num, NULL);
}
pthread_t num;
pthread_create(&num, NULL, callee, (void *) data);
pthread_detach(num);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex);
//critical
pthread_mutex_unlock(&mutex);
pthread_cond_t con = PTHREAD_COND_INITIALIZER;
...
pthread_mutex_lock(&mutex);
pthread_cond_wait(&con, &mutex);
...
pthread_mutex_unlock(&mutex);
...
pthread_cond_destroy(con);

// unblock with:

pthread_cond_signal(con);
pthread_cond_broadcast(con);

System

execvp(list[0], list);
//when list is a tokenized char** of the arguments

Networking

UDP
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>  
int fd = socket(AF_INET, SOCK_DGRAM, 0);

struct sockaddr_in addr ;
addr.sin_family = AF_INET;
addr.sin_port = htons(4711);
addr.sin_addr.s_addr = htonl(INADDR_ANY);

bind(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in));

char buf[64];
int len, flen;
struct sockaddr_in from;
flen = sizeof(struct sockaddr_in);
len = recvfrom(fd, buf, 64, 0, (struct sockaddr*) &from, &flen);
close(fd);
fd = socket(AF_INET, SOCK_DGRAM, 0);

struct sockaddr_in dest;
dest.sin_family = AF_INET;
dest.sin_port = htons(4711);
dest.sin_addr.s_addr = inet_addr("127.0.0.1");

char buf[64];

err = sendto(fd, buf, 64, 0, (struct sockaddr*) &dest, sizeof(struct sockaddr_in));

close(fd);
TCP
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
fd = socket(AF_INET, SOCK_STREAM, 0);

struct sockaddr_in dest;
dest.sin_family = AF_INET;
dest.sin_port = htons(4711);
dest.sin_addr.s_addr = inet_addr("127.0.0.1");

connect(fd, (struct sockaddr*) &dest, sizeof(sockaddr_in));

char buf[64];

write(fd, buf, 64);

close(fd);
int fd, new_sock;
struct sockaddr_in client_addr, server_addr;
socklen_t sockaddr_in_len = sizeof(struct sockaddr_in);

fd = socket(AF_INET, SOCK_STREAM, 0);

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(4711);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

bind(fd, (struct sockaddr *) &server_addr, sockaddr_in_len);

listen(fd, 5);

new_sock = accept(fd, (struct sockaddr *) &client_addr, &sockaddr_in_len);

printf("Received connection from %s\n", inet_ntoa(client_addr.sin_addr));

char buf[2048];

read(new_sock, buf, 2048);

Assembly x86 (intel)

General and Compilation

.intel_syntax noprefix
.data
  ...
.global _start
_start:
  ...
   mov eax, 1
   mov ebx, 1
   int 0x08

can be compiled and run with:

as -32 --gstabs -o TARGET.o FILENAME.ASM
ld -m elf_i386 TARGET.o
./a.out

.data Section

creating variables

num: .int 3

0 1 2 3
00000011 0..0 0..0 0..0

num is a label, at that position in .data we store an int (int should be 4 Bytes)
str: .string "A String"
str is a label, at that position in .data we store a string

0 1 2 3 4 5 6 7 8
‘a’ 32 ‘S’ ‘t’ ‘r’ ‘i’ ‘n’ ‘g’ 0
calculating length
Instructions
Stack
sub esp, 4
mov [esp], eax

# equals

push eax

and analogue:

pop eax
xor eax, eax

# equals

add esp, 4
xor eax, eax

Syscalls

push eax # para n
... 
push eax # para 1

call FUNC

add esp, <4*n>
push ebp
mov ebp, esp
# these two can be 'enter 0,0' too

mov eax, [ebp+8] # para 1
...
mov eax, [ebp+4+n*4] # para n

... # here is the body

mov esp, ebp
pop ebp
# these two can be 'leave'

ret
push eax
...
add esp, 4
Calling x86 from C
.global FUNCNAME
.type FUNCNAME @function
FUNCNAME:
  ...  
inline assembly in C
int big_endian()
{
	asm
	(
		"xor eax, eax;"
		"inc eax;"
		"push eax;"
		"movb al, [esp+3];"
		"mov esp, ebp;"
	);
}
int in, out1, out2;
	in = 5;
	asm
	(
		"mov eax, %2;" 
		"mov %0, eax;" 
		"mov %1, eax;"		
		: "=r"(out1), "=r"(out2)
		: "r"(in)
	);

NASM amd64

Example

section .data

    str: db "Hello World", 10	; define byte
    str_len equ $ - str 	; equ is a '#define'      
    buf: resq 4			; reserves four quadword
    
section .text
global _start

func:
    ...

_start:

    ; sys_write
    mov RAX, 1
    mov RDI, 1          ; stdout
    mov RSI, str        
    mov RDX, str_len    
    syscall
	
    call func
    
    ; sys_exit
    mov RAX, 60
    mov RDI, 0          ; error code
    syscall

Compilation

nasm -f elf64 hello_world.s ld hello_world.o ./a.out

Go Compendium

Misc

func test(a... int) {
	print(len(a))
}

Variables

Strings

reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
f, err := os.Open("file.txt")
defer f.Close()
check(err)
buf := make([]byte, 64)
f.Read(buf)
f, err := os.Create("file.txt")
defer f.Close()
check(err)
f.Write([]byte(str))

Slices

matrix := make([][]int, ROWS)
for i:=0; i<ROWS; i++{
	matrix[i] = make([]int, COLS)
}
list := make([]int, 5)
...
for indx, elem := range list{
    fmt.Printf("%d: %d\n", indx, elem)
}

Structs

type Person struct {
    name string
}

Network

TCP Server
ln,_ := net.Listen("tcp", ":4711")
var wg sync.WaitGroup
for {
    conn,_ := ln.Accept()
    wg.Add(1)
    go func(c net.Conn){
        defer wg.Done()
        res,_ := bufio.NewReader(conn).ReadBytes(0)
        fmt.Fprintf(conn, "%s", str)
    }(conn)
}
wg.Wait()
TCP Client
Go conn,_ := net.Dial("tcp", "192.168.0.38:4711")
fmt.Fprintf(conn, "%s", str)
res,_ := bufio.NewReader(conn).ReadBytes(0)

System

Goroutines

var wg = sync.WaitGroup{}
wg.Add(1)
go func() {
    defer wg.Done()
    fmt.Print("Hello from Thread\n")
}()
wg.Wait()
var mutex = sync.Mutex{}
mutex.Lock()
...
mutex.Unlock()
c := make(chan int)
go func() {
    c <- 2 //waits until other Goroutine receives
}()
println(<-c)
var sem = make(chan int, RSRC)

func foo(){
	sem<-0 //grab one rsrc
	...
	<-sem //release rsrc
}

CGO

//#include <stdio.h>
//void print_it() {printf("LuL");}
import "C"
func main() {
    C.print_it()
}

and run with go run main.go in Linux.

or run go build while

//#include "file.h"
import "C"
...

Rust Compendium

contact rust@bwuah.me

General

Format

Unwrap Error

my_vector.last().unwrap() to get the last element, and not a wrapper including errors.

String to Int

my_string.parse::<i64>().unwrap()

Enumerate

for (index, element) in ___.into_iter().enumerate() {...}

Command Line Parameter

let args: Vec<String> = std::env::args().collect()
std::env::args() returns an iterator, collect() converts it into a vector.

Type Hints

let mat1: Vec<Vec<i64>> = ...
Annotate the type, usually rustc can infere the type.

For Loop

for x in 0..10
{
    println!("{}", x);
}

Pattern Matching

match args[2].as_str()
{
    "+" => mat3 = mat_add(mat1, mat2),
    "-" => mat3 = mat_sub(mat1, mat2),
     _  => panic!("Fuck"),
}

File I/O

use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;

fn main() -> std::io::Result<()> 
{
    let file = File::open("text.txt")?;
    let mut buf_r = BufReader::new(file);
    let mut content = String::new();
    buf_r.read_to_string(&mut content)?;
    println!("{}", content);
    Ok(())
}

Assertions

conditional termination of the programme

Threading

use std::thread;

fn main()
{
    let mut var = "oof";
    let mut thrd = thread::spawn( move ||
    {
       println!("{}", var); 
    });
    thrd.join();
}

Mutexes

use std::sync::Mutex;
fn main()
{
    let m = Mutex::new(String::from("oof"));

    {
        let mut x = m.lock().unwrap();
        *x += " oof af";
    }

    println!("{:?}", m);
}

Channels

use std::sync::mpsc;
...
let (t, r) = mpsc::channel();
t.send("oooof").unwrap();
let str = r.recv().unwrap());

Wait Groups

use std::thread;

let wg = chan::WaitGroup::new();
for _ in 0..4
{
	wg.add(1);
	let wg = wg.clone
	thread::spawn(move ||
	{
		...
		wg.done();
	})
}
wg.wait();

Subprocess

std::process::Command;
let output = Command::new("echo").arg("Hello\n".output();

Fork

extern crate nix;
use nix::sys::signal::*;
use nix::unistd::*;

fn main()
{
    match fork().expect("fork failed")
    {
        ForkResult::Parent{child_pid} =>
	{
	    ...
	}
	ForkResult::Child =>
	{
	     ...
	}
    }
}

Python Compendium

Timer

from timeit import default_timer as timer
t1 = timer()
foo()
t2 = timer()
elapsed_time = t2-t1

Matplotlib

import matplotlib.pyplot as pp
x = [a for a in range(100)]
y = [a*a for a in range(100)]
# here: y(x) : x -> x^2 
pp.plot(x, y)
pp.ylabel("A label for y")
pp.xlabel("A label for x")
pp.grid(True)
pp.show()

Pic

Numpy

import numpy as np  

# create an NxM Matrix of ints, with random initialisation
np.random.randint(0, 2, (n, m), dtype=int)

# create an NxM Matrix of floats, values are whatever was in memory before
np.empty((n, m), dtype=float)

# create an NxM Matrix of Ints, randomly in [min, max[
np.random.randint(min, max , (n, m), dtype=int)

# multiply Matrices
np.matmul(A, B)

# equality check
np.array_equal(A, B)

Other

Custom Data Models

Tkinter