Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

33 snippets
  • Implementation of the Quick Sort algorithm in Python

    def quick_sort(arr):
        if len(arr) <= 1:
            return arr
        else:
            pivot = arr[0]
            left = [x for x in arr[1:] if x <= pivot]
            right = [x for x in arr[1:] if x > pivot]
            return quick_sort(left) + [pivot] + quick_sort(right)
    
    # Example usage:
    input_array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    sorted_array = quick_sort(input_array)
    
    print("Original Array:", input_array)
    print("Sorted Array:", sorted_array)
    

    In this code, the quick_sort function is a recursive implementation of the Quick Sort algorithm. The pivot element is chosen as the first element of the array, and elements are partitioned into two sub-arrays (left and right) based on their relationship to the pivot. The function is then called recursively on the left and right sub-arrays until the entire array is sorted.

  • Simple implementation of the Quick Sort algorithm in PHP

    <?php
    
    function quickSort(array $array): array
    {
        $length = count($array);
    
        if ($length <= 1) {
            return $array;
        }
    
        $pivot = $array[0];
        $left = $right = [];
    
        for ($i = 1; $i < $length; $i++) {
            if ($array[$i] < $pivot) {
                $left[] = $array[$i];
            } else {
                $right[] = $array[$i];
            }
        }
    
        return array_merge(quickSort($left), [$pivot], quickSort($right));
    }
    
    // Example usage:
    $array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
    $sortedArray = quickSort($array);
    
    echo "Original Array: " . implode(", ", $array) . "\n";
    echo "Sorted Array: " . implode(", ", $sortedArray) . "\n";
    
    

    Here's a simple implementation of the Quick Sort algorithm in PHP

  • Check if a file exists or not in Go

    package main
    
    import (
    	"errors"
    	"fmt"
    	"os"
    )
    
    func main() {
    	filePath := "file.txt"
    
    	if _, err := os.Stat(filePath); errors.Is(err, os.ErrNotExist) {
    		fmt.Println("file not exists")
    	} else {
    		fmt.Println("file exists")
    	}
    }
  • Example of using Go timers

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func main() {
    	firstTimer := time.NewTimer(3 * time.Second)
    	value := <-firstTimer.C // value is a current time
    
    	fmt.Printf("first timer expired: %v\n", value) // the line printed 3 seconds after running code
    
    	secondTimer := time.NewTimer(2 * time.Second)
    
    	go func() {
    		<-secondTimer.C
    		fmt.Println("second timer expired") // the line is not printed because the second timer is stopped before expiration
    	}()
    
    	stop := secondTimer.Stop() // stop second timer before it expired
    
    	if stop {
    		fmt.Println("second timer is stopped")
    	}
    }
    
    // $ go run timers.go
    // first timer expired: 2024-02-09 22:32:57.570649221 +0700 +07 m=+3.002054417
    // second timer is stopped

    Timers allow you to execute one event in the future. You tell the timer how long you want to wait and it provides a channel to be notified at that time. The first timer will wait for 3 seconds. <-firstTimer.C blocks the timer C channel until a message (current time) is sent indicating that the timer has expired. If you just want to wait, you can use time.Sleep. One reason a timer can be useful is that you can cancel the timer before it expires. The first timer expires 3s after the program starts, but the second is stopped before it expires.

  • Atomic counters in Go

    package main
    
    import (
    	"fmt"
    	"sync"
    	"sync/atomic"
    )
    
    func main() {
    	var atomicCounter, nonAtomicCounter uint64
    	wg := sync.WaitGroup{}
    
    	for i := 0; i < 50; i++ {
    		wg.Add(1)
    
    		go func() { // run 50 goroutines, each goroutine increases the counter 1000 times
    			for c := 0; c < 1000; c++ {
    				atomic.AddUint64(&atomicCounter, 1) // increase atomic counter
    				nonAtomicCounter++ // increase non-atomic counter
    			}
    
    			wg.Done()
    		}()
    	}
    
    	wg.Wait() // wait until all goroutines finish
    	
    	fmt.Println("atomic counter value:", atomicCounter)
    	fmt.Println("non atomic counter value:", nonAtomicCounter)
    }
    
    // go run counters.go 
    // atomic counter value: 50000
    // non atomic counter value: 30648

    An example of using the sync/atomic package for atomic counters accessed by goroutines.

  • Panic recovery in Go

    package main
    
    import "fmt"
    
    func main() {
        // Recover function must be called inside a deferred function.
        // When the enclosing function panics, defer is activated and the restore call inside it catches the panic.
        defer func() {
            if r := recover(); r != nil {
                fmt.Printf("recovered: %s\n", r)
            }
        }()
    
        panic("some fatal error")
        
        // This code won't run because of panic.
        // Basic operations stop during a panic and resume during a deferred close.
        fmt.Println("after panic")
    }

    Go allows you to recover from a panic with a built-in recover function. Recovery can prevent a panic from causing the program to abort and instead allow it to continue executing.

  • CSV file handling in Python

    import csv
    
    # Writing to a CSV file
    with open('data.csv', 'w', newline='') as csvfile:
        fieldnames = ['name', 'age', 'city']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    
        writer.writeheader()
        writer.writerow({'name': 'John', 'age': 30, 'city': 'New York'})
        writer.writerow({'name': 'Alice', 'age': 25, 'city': 'London'})
    
    # Reading from a CSV file
    with open('data.csv', newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row)

    Examples of code for writing to a csv file and reading from a csv file.

  • How Select on Channel Works in Golang

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        // in this example we will choose between two channels
        c1 := make(chan string)
        c2 := make(chan string)
    
        go func() {
            time.Sleep(1 * time.Second)
            c1 <- "one"
        }()
    
        // each channel will receive a value after some time
        go func() {
            time.Sleep(2 * time.Second)
            c2 <- "two"
        }()
    
        // use select statement to wait for both values ​​at the same time,
        // printing each one as it arrives
        for i := 0; i < 2; i++ {
            select {
            case msg1 := <-c1:
                fmt.Println("received", msg1)
            case msg2 := <-c2:
                fmt.Println("received", msg2)
            }
        }
    }

    Select statement allows you to wait for multiple operations on a channel.

  • Binary search algorithm in Python

    # Returns index of target in arr if present, else -1
    def binary_search(arr, target):
    	low = 0
    	high = len(arr) - 1
    
    	while low <= high:
    		# Check base case
    		mid = (high + low) // 2
    
    		# If element is smaller than mid, then it can only
    		# be present in left subarray
    		if arr[mid] > target:
    			high = mid - 1
    		# Else the element can only be present in right subarray
    		elif arr[mid] < target:
    			low = mid + 1
    		# If element is present at the middle itself
    		else:
    			return mid
    
    	# Element is not present in the array
    	return -1
    
    # Test array
    arr = [ 2, 3, 4, 10, 40 ]
    target = 10
    
    result = binary_search(arr, target)
    
    if result != -1:
    	print("Element is present at index", str(result))
    else:
    	print("Element is not present in array")

    Binary Search is a searching algorithm for finding an element's position in a sorted array. In this approach, the element is always searched in the middle of a portion of an array.

  • Binary search algorithm in Go

    package main
    
    import "fmt"
    
    // return target index if it exists in arr
    func search(arr []int, target int) int {
        low := 0
        high := len(arr) - 1
    
        for low <= high {
            mid := (low + high) / 2
    
            if arr[mid] < target {
                low = mid + 1
            } else if arr[mid] > target {
                high = mid - 1
            } else {
                return mid
            }
        }
    
        return -1
    }
    
    func main() {
        target := 7
        items := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        fmt.Printf("Element '%d' index is %d", target, search(items, target))
    }
    
    // $ output
    // 6

    The binary search algorithm employs a divide-and-conquer approach to locate an item within a sorted array or list. It begins by comparing the target value to the middle element of the array. If they are not identical, the algorithm eliminates the half of the array where the target cannot reside and proceeds the search on the remaining half. This process iterates, with each step narrowing down the search range until the target value is discovered. If the search concludes with an empty remaining half, it indicates that the target is not present in the array.

  • Example of WaitGroup in Go

    package main
    
    import (
    	"fmt"
    	"sync"
    	"time"
    )
    
    func main() {
    	wg := &sync.WaitGroup{} // WaitGroup is used to wait for the execution of all running goroutines
    
    	for i := 1; i <= 5; i++ {
    		wg.Add(1) // launch several goroutines and increment the counter in WaitGroup for each running goroutine
    
    		go func(id int) {
    			worker(id, wg)
    		}(i)
    	}
    
    	fmt.Println("waiting for all goroutines to complete")
    	wg.Wait() // block the execution of the program until the WaitGroup counter becomes equal to 0 again
    	fmt.Println("done")
    }
    
    func worker(id int, wg *sync.WaitGroup) {
    	fmt.Printf("worker %d started\n", id)
    	time.Sleep(time.Second) // Sleep simulates a long task
    	
        fmt.Printf("worker %d finished\n", id)
    	wg.Done() // notify WaitGroup that the worker has completed
    }
    
    // $ go run waitgroups.go 
    // waiting for all goroutines finished
    // worker 4 started
    // worker 1 started
    // worker 2 started
    // worker 3 started
    // worker 2 finished
    // worker 4 finished
    // worker 1 finished
    // worker 3 finished
    // done

    To wait for multiple goroutines to execute, you can use the built-in WaitGroup construct.

  • Simple http server in Go

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func hello(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "Hello, World!\n")
    }
    
    func headers(w http.ResponseWriter, req *http.Request) {
        for name, headers := range req.Header {
            for _, h := range headers {
                fmt.Fprintf(w, "%v: %v\n", name, h)
            }
        }
    }
    
    func main() {
        http.HandleFunc("/hello", hello)
        http.HandleFunc("/headers", headers)
    
        http.ListenAndServe(":8080", nil) // run http server on port 8080
    }
    

    Basic HTTP server using the net/http package. In the realm of net/http servers, a crucial concept involves handlers. These handlers implement http.Handler interface. A common method for creating a handler is to use http.HandlerFunc, applied to functions that have the required signature. Handlers receive a http.ResponseWriter and a http.Request as parameters. The response writer is employed to populate the HTTP response. Handlers can be registered on server routes by the http.HandleFunc function. This function configures the default router in the net/http package and accepts a function as its parameter. To start the http server, ListenAndServe is called with the specified port and handler. Passing nil as a second paramenter indicates using the default router we recently configured.

  • Example of timeouts in Go

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func main() {
    	first := make(chan string, 1)
    
    	go func() {
    		time.Sleep(2 * time.Second) // wait 2 seconds before send value to channel
    		first <- "first result"     // send value to the channel
    	}()
    
    	select {
    	case result := <-first:
    		fmt.Println(result)
    	case <-time.After(time.Second): // timeout occurs before the value is read from the first channel
    		fmt.Println("first timeout")
    	}
    
    	second := make(chan string, 1)
    
    	go func() {
    		time.Sleep(time.Second)   // wait 1 second before send value to the channel
    		second <- "second result" // send value to the channel
    	}()
    
    	select {
    	case result := <-second: // the value from the channel is read before the timeout expires
    		fmt.Println(result)
    	case <-time.After(2 * time.Second):
    		fmt.Println("second timeout")
    	}
    }
    
    // $ go run timeouts.go 
    // first timeout
    // second result

    Timeouts are important for programs that connect to external resources or need to limit their execution time.

  • Example of using Go tickers

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func main() {
    	ticker := time.NewTicker(time.Second)
    	fmt.Println("ticker is started")
    
    	done := make(chan struct{})
    
    	go func() {
    		for {
    			select {
    			case <-done:
    				return
    			case t := <-ticker.C:
    				fmt.Println("tick", t)
    			}
    		}
    	}()
    
    	time.Sleep(5 * time.Second)
    
    	ticker.Stop()
    	fmt.Println("ticker is stopped")
    
    	time.Sleep(5 * time.Second)
    	done <- struct{}{}
    }
    
    // go run tickers.go 
    // ticker is started
    // tick 2024-02-09 23:40:25.809616086 +0700 +07 m=+1.000091237
    // tick 2024-02-09 23:40:26.809742343 +0700 +07 m=+2.000152938
    // tick 2024-02-09 23:40:27.809804037 +0700 +07 m=+3.000214622
    // tick 2024-02-09 23:40:28.809852444 +0700 +07 m=+4.000263029
    // ticker is stopped
    // tick 2024-02-09 23:40:29.809908932 +0700 +07 m=+5.000319557
    

    Tickers allow you to repeat actions at certain intervals. A Ticker holds a channel that delivers "ticks" of a clock at intervals. Tickers can be stopped in the same way as timers. When the ticker is stopped, it will no longer be able to accept values ​​into its channel.

  • Binary search algorithm in PHP

    <?php 
      
    function binarySearch(array $arr, int $target): int 
    { 
        $low = 0; 
        $high = count($arr) - 1; 
          
        while ($low <= $high) {          
            // compute middle index 
            $mid = floor(($low + $high) / 2);  
      
            if ($arr[$mid] > $target) { 
                // search the left side of the array 
                $high = $mid -1; 
            } else if ($arr[$mid] < $target) { 
                // search the right side of the array 
                $low = $mid + 1; 
            } else {
                // element found at mid 
                return $mid; 
            }
        } 
          
        // If we reach here element x doesnt exist 
        return -1; 
    } 
      
    // Driver code 
    $arr = [1, 2, 3, 4, 5]; 
    $target = 3;
    $result = binarySearch($arr, $target);
    
    if($result !== -1) { 
        echo "Target '$target' exists at position $result"; 
    } else {
        echo "Target '$target' does not exist";
    }

    Double search is a search method used to find an element in a sorted array.

  • Channel synchronization in Go

    package main
    
    import (
        "fmt"
        "time"
    )
    
    // the channel is used to notify main goroutine that the function completed successfully
    func worker(done chan bool) {
        fmt.Println("working...")
        time.Sleep(time.Second)
        fmt.Println("done")
    
        done <- true // send a value to indicate that the function completed successfully
    }
    
    func main() {
        done := make(chan bool, 1) // create a buffered channel for notification
        go worker(done) // run worker
    
        <-done // blocked until a notification is received from the worker from the channel
               // if you remove the line <- done the program will close before the worker starts
    }

    Channels can be used to synchronize execution between goroutines. Here is an example of using a channel to wait for a goroutine to complete.

  • Worker pools in Go

    package main
    
    import (
        "fmt"
        "time"
    )
    
    // this is a worker that we will run in several parallel instances
    // these workers will receive tasks through the 'jobs' channel and send the results to 'results'
    // we will wait for one second for each task to simulate heavy requests
    func worker(id int, jobs <-chan int, results chan<- int) {
        for j := range jobs {
            fmt.Println("worker", id, "started job", j)
            time.Sleep(time.Second)
            fmt.Println("worker", id, "finished job", j)
            results <- j * 2
        }
    }
    
    func main() {
        // to use worker pool, we need to send a task and receive the execution results
        // therefore 2 channels are created
        jobs := make(chan int, 100)
        results := make(chan int, 100)
    
        // start 3 workers, initially blocked because no assignments yet
        for w := 1; w <= 3; w++ {
            go worker(w, jobs, results)
        }
    
        // send 5 jobs and then close the channel, notofying that all jobs have been sent
        for j := 1; j <= 5; j++ {
            jobs <- j
        }
    
        close(jobs)
    
        // collect all the results
        // this also ensures that the goroutines have ended
        for a := 1; a <= 5; a++ {
            <-results
        }
    }

    This example shows how to implement a worker pool using channels and goroutines.

  • Handle OS signals in Go

    package main
    
    import (
        "fmt"
        "os"
        "os/signal"
        "syscall"
    )
    
    func main() {
        sigs := make(chan os.Signal, 1) // create channel for signal, it should be buffered
        signal.Notify(sigs, syscall.SIGINT) // register the channel to receive notifications of the specified signals
        done := make(chan bool, 1)
    
        go func() {
            sig := <-sigs // wait for OS signal, once received, notify main go routine
            fmt.Printf("\nos signal: %v\n", sig)
            done <- true
        }()
    
        fmt.Println("awaiting signal")
        <-done // wait for the expected signal and then exit
        fmt.Println("exiting")
    }
    
    // $ go run main.go 
    // awaiting os signal
    // ^C
    // os signal: interrupt
    // exiting program

    Here is an example go program for processing Unix signals using channels. Signal processing can be useful, for example, for correct terminating of program when receiving SIGTINT.

  • Example of using mutexes in Go

    package main
    
    import (
    	"fmt"
    	"sync"
    )
    
    // without using mutex the following error can happen: "fatal error: concurrent map writes" while changing the map in multiple goroutines
    type Storage struct {
    	sync.Mutex
    	storage map[string]int // map is not threade-safe
    }
    
    func (s *Storage) Increment(name string) {
    	s.Lock() // lock the mutex before accessing counters
    	defer s.Unlock() // unlock the mutex at the end of the function using a defer statement
        s.storage[name]++
    }
    
    func (s *Storage) Decrement(name string) {
    	s.Lock()
        defer s.Unlock()
    	s.storage[name]--
    }
    
    func main() {
    	s := &Storage{
    		storage: make(map[string]int),
    	}
    
    	wg := sync.WaitGroup{}
    	wg.Add(5)
    
        // increment a named counter in a loop
    	increment := func(name string, count uint) {
    		for i := 0; i < int(count); i++ {
    			s.Increment(name)
    		}
    
    		wg.Done()
    	}
    
        // decrement a named counter in a loop
    	decrement := func(name string, count uint) {
    		for i := 0; i < int(count); i++ {
    			s.Decrement(name)
    		}
    
    		wg.Done()
    	}
    
        // run 5 goroutines concurrently
    	go increment("a", 1000)
    	go decrement("a", 500)
    
    	go increment("b", 1000)
    	go increment("b", 1000)
    	go decrement("b", 1500)
    
    	wg.Wait() // wait for the goroutines to finish
    
    	fmt.Println(s.storage)
    }
    
    // $ go run main.go  
    // map[a:500 b:500]
    
    // without mutex the following error can happen
    // $ go run main.go
    // fatal error: concurrent map writes

    Mutexes can be used to safely access data across multiple goroutines.This example shows how to use mutexes in Go to change a map concurrently and safely.

  • Environment variables in Go

    package main
    
    import (
    	"fmt"
    	"os"
    	"strings"
    )
    
    func main() {
    	os.Setenv("FOO", "1")
    	fmt.Println("FOO:", os.Getenv("FOO"))
    	fmt.Println("BAR:", os.Getenv("BAR"))
    
    	fmt.Println("----------------------")
    
    	for _, env := range os.Environ() {
    		pair := strings.SplitN(env, "=", 2)
    		fmt.Println(pair[0])
    	}
    }
    
    // FOO: 1
    // BAR: 
    // ----------------------
    // HOSTNAME
    // PWD
    // HOME
    // LANG
    // SHLVL
    // PATH
    // _
    // FOO

    Here's an example how you can manage environment variables. To assign a value to a key, utilize os.Setenv. Retrieve a value by key using os.Getenv, which will yield an empty string if the key isn't found. Use os.Environ to list all key/value pairs, returned as a string slice formatted as KEY=value. You can split these strings using strings.SplitN to separate keys and values.