Friday, November 12, 2021

JavaScript useful Date related (week,month,quarter) functions

As we all seen JavaScript is the most preferred programming language of the Internet.

Here are someuseful functions to iterate through the weeks / months / quarters in your code using simple JS functions.

    const weekRange = (num) => {
        // num defintion: -1 is pevious week, likewise -2,-3 OR only 1, 2 for upcoming weeks.
        let mydate = new Date();
        let mydate2 = new Date();
        num = num * 7; // 7 days per week * counter
        let x = mydate.getDate() - mydate.getDay() + 1; // +1 to set the first day of the week as Monday
        mydate.setDate(x + num);
        mydate.setHours(0, 0, 0); // setting the 0,0,0 to cover entire week right from day one midnight
        mydate2.setDate(x + num + 5 + 1); // +6 to calculatethe Saturday EOD
        mydate2.setHours(23, 59, 0); // setting 23,59 tp cover last day of the week till midnight
        return [mydate, mydate2]; //return array to compare the window with
    };

    const monthName = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    ];

    const browseMonths = (num) => {
        // pass number of months you wish to add or subtract.
        let DateObj = new Date();
        DateObj.setMonth(DateObj.getMonth() + num);
        return DateObj;
    };


    const browseQuarter = (num) => {
        // num is ctr passed to calculate the future or past months
        let DateObj = new Date();
        let qstart = new Date();
        let qend = new Date();
        let quarter = "";
        num = parseInt(num);

        if (num !== 0) {
            DateObj.setMonth(DateObj.getMonth() + num * 3);
        } else {
            DateObj.setMonth(DateObj.getMonth());
        }
        const month = parseInt(DateObj.getMonth());

        if (month >= 0 && month <= 2) {
            quarter = "Q1 " + DateObj.getFullYear();
            //console.log(DateObj.toDateString());
            qstart = new Date(DateObj);
            qend = new Date(DateObj);
            qstart.setMonth(0);
            qstart.setDate(1);
            qstart.setHours(0, 0, 0);
            qend.setMonth(2);
            qend.setDate(31);
            qend.setHours(23, 59, 0);
        } else if (month >= 3 && month <= 5) {
            quarter = "Q2 " + DateObj.getFullYear();
            //console.log(DateObj.toDateString());
            qstart = new Date(DateObj);
            qend = new Date(DateObj);
            qstart.setMonth(3);
            qstart.setDate(1);
            qstart.setHours(0, 0, 0);
            qend.setMonth(5);
            qend.setDate(30);
            qend.setHours(23, 59, 0);
        } else if (month >= 6 && month <= 8) {
            quarter = "Q3 " + DateObj.getFullYear();
            //console.log(DateObj.toDateString());
            qstart = new Date(DateObj);
            qend = new Date(DateObj);
            qstart.setMonth(6);
            qstart.setDate(1);
            qstart.setHours(0, 0, 0);
            qend.setMonth(8);
            qend.setDate(30);
            qend.setHours(23, 59, 0);
        } else if (month >= 9 && month <= 11) {
            quarter = "Q4 " + DateObj.getFullYear();
            //console.log(DateObj.toDateString());
            qstart = new Date(DateObj);
            qend = new Date(DateObj);
            qstart.setMonth(9);
            qstart.setDate(1);
            qstart.setHours(0, 0, 0);
            qend.setMonth(11);
            qend.setDate(31);
            qend.setHours(23, 59, 0);
        } else {
            quarter = "";
        }
        return [quarter, qstart, qend];
    };

Friday, February 5, 2021

GoLang - Concurrency - channels for queueing

 package main


import (
    "fmt"
    "os"
    "time"
)

func add(a, b float64float64 {
    return a + b
}

func pause(sec int) {
    for i := 0; i <= sec; i++ {
        fmt.Println(" tic tic ", i)
        time.Sleep(time.Second / 4)
    }
}

func onetoten() {
    for i := 1; i <= 10; i++ {
        fmt.Print(" ", i)
        time.Sleep(time.Second / 4)
    }
}

func backg(msg chan string) {
    for {
        // wait for order from main func
        fmt.Println("print from inside backg goroutine: ", <-msg)
        // got the message now do something
        onetoten()
        pause(5)
    }
    //fmt.Println("The End!")
}

func main() {
    //fmt.Println(add(2, 3))
    //go pause(5)
    var mystring string
    mychannel := make(chan string5)
    defer close(mychannel)
    mychannel <- "Initial value for channel"
    go backg(mychannel)

    for {
        fmt.Println("\r\n Enter Text:")
        fmt.Scanln(&mystring)
        fmt.Printf("%s", mystring)
        mychannel <- mystring
        if mystring == "q" {
            os.Exit(0)
        }
    }

}

GoLang - process multiple files concurrently

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "strconv"
    "strings"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func analyze(msg string) {
    var total float64
    var min float64
    var max float64
    var numlines float64
    total = 0
    numlines = 0
    max = 0
    min = 1000000000
    dat2 := make([]string200)
    // read the file
    daterr := ioutil.ReadFile(msg)
    check(err)
    dat2 = strings.Split(string(dat), "\r\n")
    // iterate through the text file
    for i := 0; i < len(dat2); i++ {
        //fmt.Println("inside for loop", i)
        if figerr := strconv.ParseFloat(dat2[i], 64); err == nil {
            //total + new value
            total = total + fig
            numlines = numlines + 1
            if min > fig {
                min = fig
            }
            if max < fig {
                max = fig
            }

            //fmt.Println(fig)
        } else {
            // print error if not parsed
            fmt.Println(err)
            break
        }
    }
    fmt.Println("Analysis of file:", msg)
    fmt.Println("Total is:", total)
    fmt.Println("Total figures:", numlines)
    fmt.Println("Average is:", total/numlines)
    fmt.Println("Max: ", max, "Min: ", min)
}

func main() {

    var mystring string
    myslice := make([]string3)

    myslice[0] = "random_numbers1.txt"
    myslice[1] = "random_numbers2.txt"
    myslice[2] = "random_numbers3.txt"

    for i := 0; i < len(myslice); i++ {
        // trigger analyze as go routine
        // no need to use channels as we dont need to Queue anything
        go analyze(myslice[i])
    }

    for {
        fmt.Println("\r\n Enter Filename:")
        fmt.Scanln(&mystring)
        fmt.Printf("%s", mystring)
        if mystring == "q" {
            os.Exit(0)
        } else {
            go analyze(mystring)
        }

    }

}

GoLang - file analyze function

 package main


import (
    "fmt"
    "io/ioutil"
    "strconv"
    "strings"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {
    var total float64
    var min float64
    var max float64
    var numlines float64
    total = 0
    numlines = 0
    max = 0
    min = 1000000000
    dat2 := make([]string200)
    // read the file
    daterr := ioutil.ReadFile("random_numbers1.txt")
    check(err)
    dat2 = strings.Split(string(dat), "\r\n")
    // iterate through the text file
    for i := 0; i < len(dat2); i++ {
        //fmt.Println("inside for loop", i)
        if figerr := strconv.ParseFloat(dat2[i], 64); err == nil {
            //total + new value
            total = total + fig
            numlines = numlines + 1
            if min > fig {
                min = fig
            }
            if max < fig {
                max = fig
            }

            //fmt.Println(fig)
        } else {
            // print error if not parsed
            fmt.Println(err)
        }
    }
    fmt.Println("Total is:", total)
    fmt.Println("Total fgures:", numlines)
    fmt.Println("Average is:", total/numlines)
    fmt.Println("Max: ", max, "Min: ", min)
}