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.

45 snippets
  • 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")
    	}
    }

    To check if a certain file exists inside a given directory in Golang, the Stat() and isNotExists() functions from the os package can be used. The Stat() function is used to return a file information structure that describes the file.

  • How to detect OS in bash script?

    #!/bin/bash
    
    die()
    {
        echo "ERROR: $*" >&2
        exit 1
    }
    
    detect_os ()
    {
        OS="$(uname -s)"
        ARCH="$(uname -m)"
    
        case "$OS" in
            Linux)
                if [ -e /etc/lsb-release ]; then
                    source /etc/lsb-release
    
                    DIST_ID="${DISTRIB_ID}"
                    OS_VERSION="${DISTRIB_RELEASE}"
                    OS_CODENAME="${DISTRIB_CODENAME}"
                elif [ -e /etc/os-release]; then
                    source /etc/os-release
    
                    DIST_ID="${ID}"
                    OS_VERSION="${VERSION_ID}"
                    OS_CODENAME="${VERSION_CODENAME}"
    
                elif [ $(which lsb_release 2>/dev/null) ]; then
                    DIST_ID="$(lsb_release -s -i)"
                    OS_VERSION="$(lsb_release -s -r)"
                    OS_CODENAME="$(lsb_release -s -c)"
                else
                    die "Colud not get OS information"
                fi
    
                case "$DIST_ID" in
                    RedHat*)
                        OS_NAME="RedHat" ;;
                    debian)
                        OS_NAME="Debian" ;;
                    *)
                        OS_NAME="${DIST_ID}" ;;
                esac
                ;;
            *)
                die "Unsupported OS family: $OS"
                ;;
        esac
    
        echo "${OS}"
        echo "${OS_NAME}"
        echo "${OS_VERSION}"
        echo "${OS_CODENAME}"
    }

    This script returns OS information such as type, name, codename and version. It supports the following Linux distributions: Ubuntu, Debian, CentOS, RedHat. If you want to add support for other distributions, write in the comments below.

  • 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

  • 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.