S

@supriyo_biswas

XML parsing

Go
2 years ago
package main import ( "encoding/xml" "fmt" ) type Tagging struct { XMLName xml.Name `xml:"Tagging"` TagSet TagSet `xml:"TagSet"`

url escape: path escape vs query escape

Go
2 years ago
package main import ( "fmt" "net/url" ) func main() { str := "Hello, World!"

Merging two JSON files using jq

Bash
2 years ago
#!/bin/bash echo '{"foo":{"bar":"X","baz":"Y"},"hello":{"abc":"A"}}' > config.json echo '{"hello":{"def":"B"}}' > config2.json # merge using the * operator jq -s '.[0] * .[1]' config.json config2.json

Adding a new key to a file using jq

Bash
2 years ago
#!/bin/bash echo '{"foo":{"bar":"X","baz":"Y"},"hello":{"abc":"A"}}' > config.json jq . config.json jq '.hello += {"def": "B"}' config.json > config.json.tmp mv config.json.tmp config.json jq . config.json

Intensity of double slit experiment

Python
2 years ago
import numpy as np import matplotlib.pyplot as plt # Constants wl = 500e-9 # wavelength of light d = 1 # distance between slits # Create an array of angles theta = np.linspace(-np.pi / 10e5, np.pi / 10e5, 500)

Generating a random string in Golang

Go
2 years ago
package main import ( "fmt" "encoding/base64" "crypto/rand" ) func randomString(n int) (string, error) { data := make([]byte, n)

UUIDv7 (as v4) generation

TypeScript
2 years ago
import { randomBytes } from 'crypto' function generateUuid4(): string { const time = Date.now(); const timeHex = time.toString(16).padStart(12, '0'); const randomHex = randomBytes(4).toString('hex'); const variant = '8'; // The variant for UUIDv4 is always '8' const version = '4'; // The version for UUIDv4 is always '4' return `${timeHex}-4${randomHex.substr(1, 3)}-${version}${randomHex.substr(4, 3)}-${variant}${randomHex.substr(7)}`; }

Check if domains in a list exist

Bash
2 years ago
#!/bin/bash # invoke as ./script.sh LIST OUTLIST urlcheck() { curl --connect-timeout 5 --output /dev/null --silent --head --fail "$1" } while read -r domain; do if urlcheck "$domain"; then

Error interface and wrapping errors in Golang

Go
2 years ago
package main import ( "fmt" "errors" ) type MyError struct { Err error Detail string

Splitting a string into N parts

Go
2 years ago
package main import ( "fmt" "strings" ) func main() { s := "foo bar baz" for i, part := range strings.SplitN(s, " ", 1) {

Split an address into parts in Go

Go
2 years ago
package main import ( "fmt" "net" ) func main() { // s := "[::1]:9000" s := "localhost:9000"

URL Encoding in Go

Go
2 years ago
package main import ( "fmt" "strings" ) func urlEncode(s string) string { b := strings.Builder{} b.Grow(len(s))

Regexp MustCompile/MatchString in Golang

Go
2 years ago
package main import ( "fmt" "regexp" ) func main() { pat := regexp.MustCompile(`\s`) s := "hello world"

URL parsing in Go

Go
2 years ago
package main import ( "fmt" "net/url" ) func main() { u1, err := url.ParseRequestURI("google.com") fmt.Println(u1, err)

Convert a list of strings to a regex

Python
2 years ago
#!/usr/bin/env python3 import re import sys from argparse import ArgumentParser from typing import Any, Sequence class TrieNode: def __init__(self): self.children = {}

Months between two dates

PHP
2 years ago
<?php function getYearsAndMonthsBetweenDates($startDate, $endDate) { $start = new DateTime($startDate); $end = new DateTime($endDate); $interval = new DateInterval('P1M'); $periods = new DatePeriod($start, $interval, $end); // We add $interval to include the end month too $yearMonths = [];

pSBC

NodeJS
2 years ago
// from: https://github.com/PimpTrizkit/PJs/wiki/12.-Shade,-Blend-and-Convert-a-Web-Color-(pSBC.js)#stackoverflow-archive-begin const pSBC=(p,c0,c1,l)=>{ let r,g,b,P,f,t,h,i=parseInt,m=Math.round,a=typeof(c1)=="string"; if(typeof(p)!="number"||p<-1||p>1||typeof(c0)!="string"||(c0[0]!='r'&&c0[0]!='#')||(c1&&!a))return null; if(!this.pSBCr)this.pSBCr=(d)=>{ let n=d.length,x={}; if(n>9){ [r,g,b,a]=d=d.split(","),n=d.length; if(n<3||n>4)return nu

Regex range generation

Python
3 years ago
def char_ranges(s): if len(s) == 0: return s result = [] start = s[0] end = s[0] for i in range(1, len(s)): if ord(s[i]) - ord(s[i-1]) == 1:

Shannon entropy

C
3 years ago
#include <stdio.h> #include <math.h> #include <string.h> float calculate_entropy(FILE *file) { int byte_counts[256] = {0}; int total_bytes = 0; float entropy = 0; int ch;

Marshalling a JSON string

Go
3 years ago
package main import ( "encoding/json" "fmt" ) func main() { str := "Hello, World!" jsonStr, err := json.Marshal(str) if err != nil { fmt.Println("Error encoding JSON")