All Go Rust Python PHP JavaScript
Chrome Dev Summit to secure your spot in workshops, office hours and learning lounges!

How to sort a vector in Rust

In Rust, there are 2 ways to sort a vector. Using sort Method The sort(&mut self) method sorts the slice. This sort is stable (i.e., does not reorder equal elements) and O(n * log(n)) worst-case. For example, fn main() { let mut v = [3, -5, 2, 6, 1]; v.sort(); println!("{:?}", v); let mut s = ["b", "d", "c", "a"]; s.sort(); println!("{:?}", s); } [-5, 1, 2, 3, 6] ["a", "b", "c", "d"] Using sort_by Method The sort_by(&mut self, compare: F) method sorts the slice with a comparator function. The comparator function must define a total ordering for the elements in the slice. If the ordering is not total, the order of the elements is unspecified. For example, fn main() { let mut v = [5, 4, 1, 3, 2]; v.sort_by(|a, b| a.cmp(b)); println!("{:?}", v); let mut s = ["b", "d", "c", "a"]; s.sort_by(|a, b| b.cmp(a)); println!("{:?}", s); } [1, 2, 3, 4, 5] ["d", "c", "b", "a"]
Tomoki

How to Check if a Slice Contains an Element in Go

In Golang, there are 2 ways to check if a slice contains an element. Using contains Function The following example should cover whatever you are trying to do: package main import "fmt" func Contains[E comparable](s []E, v E) bool { for _, vs := range s { if vs == v { return true } } return false } func main() { s := []string{"Gopher", "Alice", "Bob"} fmt.Println(Contains(s, "Bob")) fmt.Println(Contains(s, "bob")) } true false Using slices.Contains Function Starting with Go 1.18, you can use the slices package – specifically the generic Contains function: package main import ( "fmt" "golang.org/x/exp/slices" ) func main() { s := []string{"Gopher", "Alice", "Bob"} b := slices.Contains(s, "Bob") fmt.Println(b) b = slices.Contains(s, "bob") fmt.Println(b) } true false
ada

How to Sort a Slice in Go

In Golang, using the sort.Slice function is the easiest way to sort a slice Using Slice Function You simply pass an anonymous function to the sort.Slice function: package main import ( "fmt" "sort" ) func main() { s := []string{"Houston", "Atlanta", "Boston"} sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) fmt.Println(s) a := []int{6, 4, 2} sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) fmt.Println(a) } [Atlanta Boston Houston] [2 4 6] Slice sorts the slice x given the provided less function. It panics if x is not a slice. See the following example: package main import ( "fmt" "sort" ) func main() { people := []struct { Name string Age int }{ {"Gopher", 7}, {"Alice", 55}, {"Vera", 24}, {"Bob", 75}, } sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name }) fmt.Println("By name:", people) sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age }) fmt.Println("By age:", people) } By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}] By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]
Tomoki

How to Check String is In Json Format in Go

In Golang, there are 2 ways to check string is in json format. Using Unmarshal Function The following example should cover whatever you are trying to do: package main import ( "encoding/json" "fmt" ) func isJson(s string) bool { var js json.RawMessage return json.Unmarshal([]byte(s), &js) == nil } func isQuotedJson(s string) bool { var js map[string]interface{} return json.Unmarshal([]byte(s), &js) == nil } func main() { s := `{"key":"value"}` b := isJson(s) fmt.Println(b) b = isQuotedJson(s) fmt.Println(b) } true true Using Standard Library Function Standard encoding/json library contains json.Valid function starting from go 1.9. This function may be used for checking whether the provided string is a valid json: package main import ( "encoding/json" "fmt" ) func main() { s := `{"key":"value"}` b := json.Valid([]byte(s)) fmt.Println(b) } true
pooriabt

How to Make a Shallow Copy of a Slice in Go

In Golang, there are 2 ways to duplicate slices. Using append Function You could write one simple statement to make a shallow copy of a slice. The following example should cover whatever you are trying to do: package main import "fmt" type T int func main() { a := []T{1, 2} b := append([]T(nil), a...) fmt.Println(a, b) b[1] = 4 fmt.Println(a, b) } [1 2] [1 2] [1 2] [1 4] Using copy Function See the following example: package main import "fmt" type T int func main() { a := []T{1, 2} b := make([]T, len(a)) copy(b, a) fmt.Println(a, b) b[1] = 4 fmt.Println(a, b) } [1 2] [1 2] [1 2] [1 4]
Unused

How to Get Name of Current Script in Python

In Python, using the __file__ is the easiest way to get name of current script. Using Module Attributes You can use __file__ to get the name of the current file. When used in the main module, this is the name of the script that was originally invoked. See the following example: #!/usr/bin/python3 # Import module import os print(__file__) # omit the directory part print(os.path.basename(__file__)) /home/python/demo.py demo.py
Unused

How to Determine Whether a Given Integer is Between two Other Integers in Python

In Python, there are 2 ways to determine whether a given integer is between two other integers. Using Comparisons Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a See the following example: #!/usr/bin/python3 i = 20 if 10 < i < 40: print(True) True Using range For example, #!/usr/bin/python3 i = 10 r = range(10, 30) if i in range(10, 30): print(True) print(30 in r) print(20 in r) True False True
ada

How to Delete a Character from a String in Python

In Python, there are 2 ways to delete a character from a string. Using replace Method The str.replace(old, new[, count]) method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. See the following example: #!/usr/bin/python3 s = "Hello" s = s.replace("l", "") print(s) Heo Using Slice Syntax Specify the start index and the end index, separated by a colon, to return a part of the string. For example, #!/usr/bin/python3 # remove character def remove(str, rep): i = str.find(rep) if i == -1: return str str = str[:i]+str[i+1:] return remove(str, rep) s = "Hello" s = remove(s, 'l') print(s) Heo
Unused

How to Make a List of Alphabet Characters in Python

In Python, there are 2 ways to make a list of alphabet characters. Using string Module The string.ascii_lowercase is a pre-initialized string used as string constant. In Python, string ascii_lowercase will give the lowercase letters ‘abcdefghijklmnopqrstuvwxyz’. See the following example: #!/usr/bin/python3 # Import module import string # string.ascii_lowercase # string.ascii_uppercase # string.ascii_letters ls = list(string.ascii_lowercase) print(ls) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] Using range Function The range(start, stop[, step]) function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number. For example, #!/usr/bin/python3 ls = list(map(chr, range(97, 123))) print(ls) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] String module features: Object type: ##### string.whitespace \t\n\r\v\f ##### string.ascii_letters abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ##### string.ascii_lowercase abcdefghijklmnopqrstuvwxyz ##### string.ascii_uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ ##### string.digits 0123456789 ##### string.hexdigits 0123456789abcdefABCDEF ##### string.octdigits 01234567 ##### string.printable digits + ascii_letters + punctuation + whitespace ##### string.punctuation !"#$%&\'()*+,-./:;[email protected][\\]^_`{|}~
Patcher56

How to Marshal / Unmarshal Json with a Custom Type Attribute in Go

In Golang, using the Unmarshal JSON function is the easiest way to Marshal / Unmarshal json with a custom type attribute. JSON (JavaScript Object Notation) is a lightweight data-interchange format. Using UnmarshalJSON Function Example on custom UnmarshalJSON and MarshalJSON. The following example should cover whatever you are trying to do: package main import ( "encoding/json" "fmt" "strconv" "time" ) type CustTimeUinx int64 func (t *CustTimeUinx) UnmarshalJSON(b []byte) error { s, _ := strconv.Unquote(string(b)) uinx := int64(0) if len(s) != 0 { d, _ := time.Parse("2006-01-02 15:04:05", s) uinx = d.Unix() } *t = CustTimeUinx(uinx) return nil } func (t *CustTimeUinx) MarshalJSON() ([]byte, error) { uinx := int64(*t) quoted := strconv.Quote(time.Unix(uinx, 0).Format("2006-01-02 15:04:05")) return []byte(quoted), nil } type TestItem struct { Curr CustTimeUinx `json:"Curr"` } func main() { // Unmarshal Json s := `{"curr":"2022-06-26 10:00:00", "age":10}` var data TestItem json.Unmarshal([]byte(s), &data) b, _ := json.MarshalIndent(data, "", " ") fmt.Printf("%s\n", b) // Marshal Json d := TestItem{ Curr: CustTimeUinx(1656237600), } js, _ := json.Marshal(&d) fmt.Printf("%s\n", js) } { "Curr": 1656237600 } {"Curr":"2022-06-26 18:00:00"}
aweis

How to Get a Random Number Between a Float Range in Python

In Python, using the uniform function is the easiest way to get a random number between a float range. Using uniform Method The random.uniform(a, b) method returns a random floating point number N such that a See the following example: #!/usr/bin/python3 # Import module import random a = random.uniform(1.3, 2.4) print(a) 1.654179463181758 2.044145546151235 The end-point value b may or may not be included in the range depending on floating-point rounding in the equation a + (b-a) * random(). if you want generate a random float with N digits to the right of point, you can make this: #!/usr/bin/python3 # Import module import random a = random.uniform(1.3, 2.4) b = round(a, 4) print(b) 2.2657
Unused

How to Extract All the Numbers Contained in a String in Python

In Python, there are 2 ways to extract all the numbers contained in a string. Using List Comprehension List comprehensions provide a concise way to create lists. If you only want to extract only positive integers, try the following: #!/usr/bin/python3 s = "The 2.0L 2023 AMG C 63 Wagon" l = [int(c) for c in s.split() if c.isdigit()] print(l) [2023, 63] The other solution is: #!/usr/bin/python3 s = "The2.0L2023AMGC63Wagon" s = ''.join((ch if ch in '0123456789.' else ' ') for ch in s) l = [float(i) for i in s.split()] print(l) [2.0, 2023.0, 63.0] Using Regexp A more robust version would be: #!/usr/bin/python3 # Import module import re s = "The2.0L2023AM.GC63Wagon" l = re.findall(r'[-+]?(?:\d*\.\d+|\d+)', s) print(l) [2023, 63] To catch different patterns it is helpful to query with different patterns. different number patterns'[\d]+[.,\d]+'(finds commas) 12,300 or 12,300.00'[\d]*[.][\d]+'(finds floats) 0.123 or .123'[\d]+'(finds integers) 123'[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'(finds integers) 123'[\d]+'Combine with pipe ( | ) into one pattern with multiple or conditionals.
Sambhav Khandelwal

How to Encrypt and Decrypt a String Using AES CBC in Go

In Golang, using the crypto/aes package is the easiest way to encrypt a string using AES CBC. Ehrsam, Meyer, Smith and Tuchman invented the cipher block chaining (CBC) mode of operation in 1976. In CBC mode, each block of plaintext is XORed with the previous ciphertext block before being encrypted. Using NewCBCEncrypter Function The cipher.NewCBCEncrypter(cipher Block) function returns returns a BlockMode which encrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block's block size. The following example should cover whatever you are trying to do: package main import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/hex" "errors" "fmt" "io" ) func PKCS7Padding(ciphertext []byte, blockSize, after int) []byte { padding := (blockSize - len(ciphertext)%blockSize) padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } func PKCS7Unpad(b []byte, blocksize int) ([]byte, error) { if blocksize <= 0 { return nil, errors.New("invalid blocksize") } if len(b) == 0 { return nil, errors.New("unpad error") } if len(b)%blocksize != 0 { return nil, errors.New("unpad error") } c := b[len(b)-1] n := int(c) if n == 0 || n > len(b) { return nil, errors.New("unpad error") } for i := 0; i < n; i++ { if b[len(b)-n+i] != c { return nil, errors.New("unpad error") } } return b[:len(b)-n], nil } func AesCBCEncrypt(key string, text string) (string, error) { plaintext := PKCS7Padding([]byte(text), aes.BlockSize, len(text)) // CBC mode works on blocks so plaintexts may need to be padded to the // next whole block. if len(plaintext)%aes.BlockSize != 0 { return "", errors.New("plaintext is not a multiple of the block size") } block, err := aes.NewCipher([]byte(key)) if err != nil { return "", err } // The IV needs to be unique, but not secure. Therefore it's common to // include it at the beginning of the ciphertext. ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { panic(err) } mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext) // It's important to remember that ciphertexts must be authenticated // (i.e. by using crypto/hmac) as well as being encrypted in order to // be secure. return hex.EncodeToString(ciphertext), nil } func AesCBCDecrypt(key string, text string) (string, error) { ciphertext, err := hex.DecodeString(text) if err != nil { return "", err } block, err := aes.NewCipher([]byte(key)) if err != nil { return "", err } if len(ciphertext) < aes.BlockSize { return "", errors.New("ciphertext too short") } iv := ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:] // CBC mode always works in whole blocks. if len(ciphertext)%aes.BlockSize != 0 { return "", errors.New("ciphertext is not a multiple of the block size") } mode := cipher.NewCBCDecrypter(block, iv) mode.CryptBlocks(ciphertext, ciphertext) // If the original plaintext lengths are not a multiple of the block // size, padding would have to be added when encrypting, which would be // removed at this point. ciphertext, _ = PKCS7Unpad(ciphertext, aes.BlockSize) return string(ciphertext[:]), nil } func main() { s := "Hello" key := "zb0SLh88rdSHswjcgcC6949ZUuopGXTt" ciphertext, _ := AesCBCEncrypt(key, s) fmt.Println(ciphertext) plaintext, _ := AesCBCDecrypt(key, ciphertext) fmt.Printf("Decrypt:: %s\n", plaintext) } 22fb92560a7a1e7a9ba881943d5e078c517343133049b8ff4b5492a7b2276b3e Decrypt:: Hello
Tomoki

How to Encrypt and Decrypt a String Using AES GCM 256 in Go

In Golang, using the crypto/aes package is the easiest way to encrypt a string using AES GCM 256. In cryptography, Galois/Counter Mode (GCM) is a mode of operation for symmetric-key cryptographic block ciphers which is widely adopted for its performance. Using NewGCM Function The cipher.NewGCM(cipher Block) function returns the given 128-bit, block cipher wrapped in Galois Counter Mode with the standard nonce length. The following example should cover whatever you are trying to do: package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/hex" "fmt" "io" ) func AesGCMIv() ([]byte, error) { // Never use more than 2^32 random nonces with a given key because of the risk of a repeat. nonce := make([]byte, 12) if _, err := io.ReadFull(rand.Reader, nonce); err != nil { return nil, err } return nonce, nil } func AesGCMEncrypt(key string, text string) (string, error) { // When decoded the key should be 16 bytes (AES-128) or 32 (AES-256). block, err := aes.NewCipher([]byte(key)) if err != nil { return "", err } plaintext := []byte(text) nonce, err := AesGCMIv() if err != nil { return "", err } aesgcm, err := cipher.NewGCM(block) if err != nil { return "", err } ciphertext := aesgcm.Seal(nonce, nonce, plaintext, nil) return fmt.Sprintf("%x", ciphertext), nil } func AesGCMDecrypt(key string, text string) (string, error) { // When decoded the key should be 16 bytes (AES-128) or 32 (AES-256). block, err := aes.NewCipher([]byte(key)) if err != nil { return "", err } aesgcm, err := cipher.NewGCM(block) if err != nil { return "", err } in, _ := hex.DecodeString(text) ns := aesgcm.NonceSize() nonce, ciphertext := in[:ns], in[ns:] plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil) if err != nil { return "", err } return string(plaintext[:]), nil } func main() { s := "Hello" key := "zb0SLh88rdSHswjcgcC6949ZUuopGXTt" ciphertext, _ := AesGCMEncrypt(key, s) fmt.Println(ciphertext) plaintext, _ := AesGCMDecrypt(key, ciphertext) fmt.Printf("Decrypt:: %s\n", plaintext) } 0680f8fef173fd969bb073d614e7059b62147b0e8eb6a7fdbe3040a8cd3a0d05c5 Decrypt:: Hello
Tomoki

How to Generate a SHA256 HMAC Hash from a String in Go

In Golang, using the crypto/hmac library is the easiest way to generate a SHA256 HMAC Hash from a string. In cryptography, an HMAC (hash-based message authentication code) is a specific type of message authentication code (MAC) involving a cryptographic hash function and a secret cryptographic key. Using hmac Package The hmac.New() function returns a new HMAC hash using the given hash.Hash type and key. The following example should cover whatever you are trying to do: package main import ( "crypto/hmac" "crypto/sha256" "fmt" ) func main() { s := "Hello" key := "FDJ1mnhuzjFjTdwhq7DtZG2Cq9kuuEZCG" h := hmac.New(sha256.New, []byte(key)) h.Write([]byte(s)) fmt.Printf("%x\n", h.Sum(nil)) fmt.Printf("%x\n", sha256.Sum256([]byte(s))) } b5352927e7a57a6485fa4afa7452b3817abe47d07c8aa2511bdcb9a43ac0f224 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969 Generating a MD5 HMAC Hash For example, package main import ( "crypto/hmac" "crypto/md5" "fmt" ) func main() { s := "Hello" key := "FDJ1mnhuzjFjTdwhq7DtZG2Cq9kuuEZCG" h := hmac.New(md5.New, []byte(key)) h.Write([]byte(s)) fmt.Printf("%x\n", h.Sum(nil)) } ed1d2af782f2fa171867e4e810bf9a3d block length: Hash function H b, bytes L, bytes MD5 64 16 SHA-1 64 20 SHA-224 64 28 SHA-256 64 32 SHA-512/224 128 28 SHA-512/256 128 32 SHA-384 128 48 SHA-512 128 64 SHA3-224 144 28 SHA3-256 136 32 SHA3-384 104 48 SHA3-512 72 64 out = H( in )L = length( out )b = H's internal block length
ada

How to Get a SHA256 Hash from a String in Go

In Golang, using the Sum256 function is the easiest way to get a SHA256 hash from a string. Go implements several hash functions in various crypto/* packages. Using Sum256 Function The sha256.Sum256() function returns the SHA256 checksum of the data. The following example should cover whatever you are trying to do: package main import ( "crypto/sha256" "encoding/hex" "fmt" ) func main() { s := "Hello" sum := sha256.Sum256([]byte(s)) fmt.Printf("%x\n", sum) fmt.Println(hex.EncodeToString(sum[:])) } 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969 Using New Function New returns a new hash.Hash computing the SHA256 checksum. For example, package main import ( "crypto/sha256" "fmt" ) func main() { h := sha256.New() h.Write([]byte("Hello")) h.Write([]byte("World")) fmt.Printf("%x\n", h.Sum(nil)) } 872e4e50ce9990d8b041330c47c9ddd11bec6b503ae9386a99da8584e9bb12c4 Generate SHA256 checksum of a file. See the following example: package main import ( "crypto/sha256" "fmt" "io" "os" ) func main() { f, err := os.Open("ins.txt") if err != nil { // log.Fatal(err) } defer f.Close() h := sha256.New() if _, err := io.Copy(h, f); err != nil { // log.Fatal(err) } fmt.Printf("%x\n", h.Sum(nil)) } 39866a50dfb27f5b96f075b3cbf9179096c87495983782427a0422c611a30e1e
ada

How to Get a MD5 Hash from a String in Go

In Golang, using the Sum function is the easiest way to get a MD5 hash from a string. Using Sum Function The md5.Sum() function returns the MD5 checksum of the data. The following example should cover whatever you are trying to do: package main import ( "crypto/md5" "encoding/hex" "fmt" ) func main() { b := []byte("Hello") out := md5.Sum(b) fmt.Printf("%x\n", out) // EncodeToString fmt.Println(hex.EncodeToString(out[:])) } 8b1a9953c4611296a827abf8c47804d7 8b1a9953c4611296a827abf8c47804d7 Using New Function New returns a new hash.Hash computing the MD5 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash. For example, package main import ( "crypto/md5" "fmt" "io" ) func main() { h := md5.New() io.WriteString(h, "Hello") io.WriteString(h, "Word") fmt.Printf("%x\n", h.Sum(nil)) } 04b6f86d49716af8d4f2edf01a309fc8 Generate MD5 checksum of a file. See the following example: package main import ( "crypto/md5" "fmt" "io" "os" ) func main() { f, err := os.Open("ins.txt") if err != nil { // log.Fatal(err) } defer f.Close() h := md5.New() if _, err := io.Copy(h, f); err != nil { // log.Fatal(err) } fmt.Printf("%x\n", h.Sum(nil)) } 3dca0fa76621281bfb7ffab47c860502
aweis

How to Check if IP Address is in Private Network Space in Go

In Golang, using the IsPrivate function is the easiest way to check if IP address is in private network space. Using IsPrivate Function The IsPrivate() function reports whether ip is a private address, according to RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses). The following example should cover whatever you are trying to do: // Go 1.17+ package main import ( "fmt" "net" ) func main() { ip := "1.1.1.1" addr := net.ParseIP(ip) fmt.Println(addr.IsPrivate()) ip = "10.3.4.0" addr = net.ParseIP(ip) fmt.Println(addr.IsPrivate()) } false true This requires Go 1.17. Using RFC1918 Here is an example with a list of RFC1918 address plus these others and a simple check against them as isPrivateIP(ip net.IP): package main import ( "fmt" "net" ) var privIPBlocks []*net.IPNet func isPrivate(ip string) bool { // init blocks if len(privIPBlocks) == 0 { for _, cidr := range []string{ "127.0.0.0/8", // IPv4 loopback "10.0.0.0/8", // RFC1918 "172.16.0.0/12", // RFC1918 "192.168.0.0/16", // RFC1918 "169.254.0.0/16", // RFC3927 link-local "::1/128", // IPv6 loopback "fe80::/10", // IPv6 link-local "fc00::/7", // IPv6 unique local addr } { _, block, err := net.ParseCIDR(cidr) if err != nil { panic(fmt.Errorf("parse error on %q: %v", cidr, err)) } privIPBlocks = append(privIPBlocks, block) } } addr := net.ParseIP(ip) if addr.IsLoopback() || addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() { return true } for _, block := range privIPBlocks { if block.Contains(addr) { return true } } return false } func main() { ip := "1.1.1.1" fmt.Println(isPrivate(ip)) ip = "10.3.4.0" fmt.Println(isPrivate(ip)) } false true
aweis

How to Get the Full URL in PHP

In PHP, using the $_SERVER variable is the easiest way to get the full URL. Using $_SERVER Variable $_SERVER is an array containing information such as headers, paths, and script locations. The following example should cover whatever you are trying to do: $link = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; // escaped $link = htmlspecialchars($link, ENT_QUOTES, 'UTF-8'); echo $link; //installmd.com/code/php/hash.php?p=1
url
Sambhav Khandelwal

How to check if a string contains a specific word in PHP

In PHP, there are 2 ways to check if a string contains a specific word. Using strpos Function The strpos(string $haystack, string $needle, int $offset = 0): int|false function finds the numeric position of the first occurrence of needle in the haystack string. For example, $str = "hello"; $pos = strpos($str, "l"); var_dump($pos); $pos = strpos($str, "b"); var_dump($pos); int(2) bool(false) Using preg_match Function A simple match for are could look something like this: $str = "hello"; $m = preg_match("/lo/i", $str); var_dump($m); $m = preg_match("/b/i", $str); var_dump($m); int(1) int(0)
ada

How to Delete an Element from an Array in PHP

In PHP, there are 3 ways to delete an element from an array. Using unset Function The unset(mixed $var, mixed ...$vars): void function destroys the specified variables. For example, $arr = ["a", "b", "d"]; unset($arr[1]); print_r($arr); Array ( [0] => a [2] => d ) Note that when you use unset() the array keys won’t change. If you want to reindex the keys you can use array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0. Using array_splice Function The array_splice(): array function removes a portion of the array and replace it with something else. $arr = ["a", "b", "d"]; array_splice($arr, 1, 1); print_r($arr); Array ( [0] => a [1] => d ) Using array_filter Function If you want to delete all elements with a specific value in the array you can use array_filter(). See the following example: $arr = ["a", "b", "d", "b"]; $arr = array_filter($arr, function($ele){ return $ele !== "b"; }); print_r($arr); Array ( [0] => a [2] => d )
Sambhav Khandelwal

How to Put the Current Thread to Sleep in Rust

In Rust, using the thread::sleep_ms method is the easiest way to put the current thread to sleep. Using sleep_ms Method The thread::sleep_ms() method puts the current thread to sleep for at least the specified amount of time. For example, use std::{thread, time::Duration, time::SystemTime}; fn main() { println!("{:?}", SystemTime::now()); // Sleep thread::sleep(Duration::from_millis(4000)); println!("{:?}", SystemTime::now()); } SystemTime { tv_sec: 1653360055, tv_nsec: 949217277 } SystemTime { tv_sec: 1653360059, tv_nsec: 949449668 }
Sambhav Khandelwal

How to Convert a String to int in Rust

In Rust, using the parse method is the easiest way to convert a string to int. Using parse Method The str::parse::<T>() method parses this string slice into another type. For example, fn main() { let s = "100".to_string(); println!("{}", s.parse::<i32>().unwrap()); match "10a".parse::<i32>() { Ok(n) => println!("Ok"), Err(e) => println!("{}", e), } } 100 invalid digit found in string
Tomoki

How to Check if a String Contains Whitespace in Rust

In Rust, there are 2 ways to check if a string contains whitespace. Using char::is_whitespace char::is_whitespace returns true if the character has the Unicode White_Space property. You can pass char::is_whitespace to .contains(): fn main() { println!("{}", "Hello World".contains(char::is_whitespace)); // a non-breaking space println!("{}", "Hello\u{A0}World".contains(char::is_whitespace)); println!("{}", "Hello\taWorld".contains(char::is_whitespace)); } true true true Alternatively, you can use char::is_ascii_whitespace if you only want to match ASCII whitespace (space, horizontal tab, newline, form feed, or carriage return). Using as_bytes Method If you're only looking for ASCII whitespace: fn main() { let mut s = "Hello World"; println!("{}", s.as_bytes().iter().any(u8::is_ascii_whitespace)); // a non-breaking space s = "Hello\u{A0}World"; println!("{}", s.as_bytes().iter().any(u8::is_ascii_whitespace)); s = "Hello\tWorld"; println!("{}", s.as_bytes().iter().any(u8::is_ascii_whitespace)); } true false true
Unused

How to Split a String into a List in Python

In Python, using the str.split method is the easiest way to split a string into a list Using split Method The str.split(sep=None, maxsplit=- 1) method returns a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. For example, #!/usr/bin/python3 s = "a,b,c,d" a = s.split(",") print(a) b = s.split(",", maxsplit=2) print(b) ['a', 'b', 'c', 'd'] ['a', 'b', 'c,d']
ada

How to Set the Current Working Directory in Python

In Python, using the os.chdir method is the easiest way to set the current working directory Using chdir Method The os.chdir(path) method changes the current working directory to path. For example, #!/usr/bin/python3 # Import module import os os.chdir("/data/site") Prints the current working directory: #!/usr/bin/python3 # Import module import os print(os.getcwd()) /home/data/python
Unused

How to Get the Psition of a Character in Python

In Python, there are 3 ways to get the position of a character. Using find Method The str.find(sub[, start[, end]]) method returns the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. For example, #!/usr/bin/python3 a = "There are two" i = a.find('r') print(i) i = a.find('rb') print(i) 3 -1 Using index Method Like find(), but raise ValueError when the substring is not found. The following example should cover whatever you are trying to do: #!/usr/bin/python3 a = "There are two" i = a.index('r') print(i) i = a.index('rb') 3 ValueError: substring not found Using List Comprehension If you need to find all positions of a character in a string, you can do the following: #!/usr/bin/python3 s = "There are two" l = [pos for pos, char in enumerate(s) if char == 'r' ] print(l) [3, 7]
aweis

How to Append Integer to Beginning of List in Python

In Python, there are 2 ways to append integer to beginning of list. Using insert Method The list.insert() method inserts an item at a given position. The first argument is the index of the element before which to insert. For example, #!/usr/bin/python3 a = [1, 2, 3] a.insert(0, 5) print(a) [5, 1, 2, 3] Using Unpack List The following example should cover whatever you are trying to do: #!/usr/bin/python3 a = [1, 2, 3] a = [5, *a] print(a) [5, 1, 2, 3]
pooriabt

How to Calculate Number of Days Between Two Given Dates in Python

In Python, using the timedelta object is the easiest way to calculate number of days between two given dates. Using timedelta If you have two date objects, you can just subtract them, which computes a timedelta object. In this program, we will calculate number of days between two given dates. #!/usr/bin/python3 # Import module import datetime d1 = datetime.date(2022, 5, 1) d2 = datetime.date(2022, 5, 22) delta = d2 - d1 print(delta.days) 21
Unused

How to Delete the Contents of a Folder in Python

In Python, there are 2 ways to delete the contents of a folder. Using rmtree Method The shutil.rmtree() method deletes an entire directory tree; path must point to a directory. For example, #!/usr/bin/python3 # Import module import os, shutil def remove_dir(path): for filename in os.listdir(path): filepath = os.path.join(path, filename) try: if os.path.isfile(filepath) or os.path.islink(filepath): os.unlink(filepath) elif os.path.isdir(filepath): shutil.rmtree(filepath) except Exception as e: print(e) remove_dir("abcde") Using glob Method You can simply do this: #!/usr/bin/python3 # Import module import os, glob files = glob.glob('abcde/*') # files = glob.glob('abcde/*.txt') for f in files: os.remove(f)
Tomoki

How to Do Case Insensitive String Comparison in Python

In Python, there are 2 do case insensitive string comparison. Using casefold Method The str.casefold() method returns a casefolded copy of the string. Casefolded strings may be used for caseless matching. For example, #!/usr/bin/python3 a = "Hello" b = "heLLo" print(a.casefold() == b.casefold()) print(a == b) print("ß".casefold() == "SS".casefold()) True False True The German lowercase letter 'ß' is equivalent to "ss". Using lower Method The following example should cover whatever you are trying to do: #!/usr/bin/python3 a = "Hello" b = "heLLo" print(a.lower() == b.lower()) print(a == b) print('ß'.lower() == 'SS'.lower()) True False False
pooriabt

How to Find Out the Number of CPUs in Python

In Python, there are 2 ways to find out the number of CPUs. Using multiprocessing Module The multiprocessing.cpu_count() method returns the number of CPUs in the system. For example, #!/usr/bin/python3 # Import module import multiprocessing cpus = multiprocessing.cpu_count() print(cpus) 4 When the number of CPUs cannot be determined a NotImplementedError is raised. Using os Module The os.cpu_count() method returns the number of CPUs in the system. Returns None if undetermined. The following example should cover whatever you are trying to do: #!/usr/bin/python3 # Import module import os cpus = os.cpu_count() print(cpus) 4
Sambhav Khandelwal

How to Get Current Time in Milliseconds in Python

In Python, there are 3 ways to get current time in milliseconds. Using time Method The time.time() method returns the time in seconds since the epoch as a floating point number. For example, #!/usr/bin/python3 # Import module import time ms = round(time.time() * 1000) print(ms) 1652865940186 Using time_ns Method The time.time_ns() method returns time as an integer number of nanoseconds since the epoch. The following example should cover whatever you are trying to do: #!/usr/bin/python3 # Import module import time ms = time.time_ns() print(ms) 1652866090096069080 Using microsecond Attribute For example, #!/usr/bin/python3 # Import module import datetime t = datetime.datetime.now() ms = t.microsecond print(ms) 452195
Patcher56

How to Convert all Strings in a List to Int in Python

In Python, there are 2 ways to convert all strings in a list to int. Using map Method You can convert all strings in a list to int using the map method. For example, #!/usr/bin/python3 a = ["1", "2", "4", "5"] b = list(map(int, a)) print(b) [1, 2, 4, 5] Using List Comprehension The following example should cover whatever you are trying to do: #!/usr/bin/python3 a = ["1", "2", "4", "5"] b = [int(i) for i in a] print(b) [1, 2, 4, 5]
Sambhav Khandelwal

How to Capitalize the First Letter of each Word in a String in Python

In Python, there are 2 ways to capitalize the first letter of each word in a string. Using title Method The str.title() method returns a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase. The following example should cover whatever you are trying to do: #!/usr/bin/python3 s = "method of a string" print(s.title()) Method Of A String Using capwords Method Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). For example, #!/usr/bin/python3 # Import module import string s = "method of a string" print(string.capwords(s)) Method Of A String
Patcher56

How to Get the Day of Week Given a Date in Python

In Python, there are 2 ways to get the day of week given a date. Using weekday Method The weekday() method returns the day of the week as an integer, where Monday is 0 and Sunday is 6. The following example should cover whatever you are trying to do: #!/usr/bin/python3 # Import module import datetime import calendar d = datetime.datetime.today() print(d.weekday()) # Monday print(calendar.day_name[d.weekday()]) 0 Monday Using strftime Method You can get the day of week given a date using the strftime Method. For example, #!/usr/bin/python3 # Import module import datetime d = datetime.datetime.today() print(d.strftime("%A")) Monday
Sambhav Khandelwal

How to Escape the Html in Go

In Golang, there are 2 ways to escape the html. Using EscapeString Function The html.EscapeString() function escapes special characters like ", &, ' and ". The following example should cover whatever you are trying to do: package main import ( "fmt" "html" ) func main() { s := "<script>alert(1);</script>" s = html.EscapeString(s) fmt.Println(s) } <script>alert(1);</script> Using HTMLEscapeString Funcion The template.HTMLEscapeString() function returns the escaped HTML equivalent of the plain text data s. For example, package main import ( "fmt" "text/template" ) func main() { s := "<script>alert(1);</script>" s = template.HTMLEscapeString(s) fmt.Println(s) } <script>alert(1);</script>
ada

How to Change the Current Directory in Go

In Golang, there are 2 ways to change the current directory. Using Dir Property Usually if you need a command to run from a specific directory, you can specify that as the Dir property on the Command, for example: package main import ( "os/exec" ) func main() { cmd := exec.Command("ls", "-al") cmd.Dir = "/home/user" cmd.Run() } Using os.Chdir Function The os.Chdir() function changes the current working directory to the named directory. If there is an error, it will be of type *PathError. For example, package main import ( "fmt" "os" ) func main() { h, _ := os.UserHomeDir() fmt.Println(h) err := os.Chdir("/root/go") if err != nil { panic(err) } } /root This doesn't change the terminal location.
Unused

How to Check if Directory on Path is Empty in Go

In Golang, using the Readdirnames function is the easiest way to check if directory on path is empty. Using Readdirnames Function The file.Readdirnames(n int) function reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order. If n > 0, Readdirnames returns at most n names. In this case, if Readdirnames returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF. The following example should cover whatever you are trying to do: package main import ( "fmt" "io" "os" ) func IsEmpty(path string) (bool, error) { f, err := os.Open(path) if err != nil { return false, err } defer f.Close() // OR f.Readdir(1) _, err = f.Readdirnames(1) if err == io.EOF { return true, nil } return false, err } func main() { fmt.Println(IsEmpty("a")) fmt.Println(IsEmpty("b")) } true <nil> false <nil>
Sambhav Khandelwal

How to Remove Invalid UTF-8 Characters from a String in Go

In Golang, there are 3 ways to remove invalid UTF-8 characters from a string. Using ToValidUTF8 Function The strings.ToValidUTF8() function returns a copy of the string s with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty. The following example should cover whatever you are trying to do: package main import ( "fmt" "strings" ) func main() { s := "a\xc5bd" s = strings.ToValidUTF8(s, "") fmt.Printf("%q\n", s) } "abd" Using Map function In Go 1.11+, it's also very easy to do the same using the Map function and utf8.RuneError like this: package main import ( "fmt" "strings" "unicode/utf8" ) func main() { s := "a\xc5bd" valid := func(r rune) rune { if r == utf8.RuneError { return -1 } return r } s = strings.Map(valid, s) fmt.Printf("%q\n", s) } "abd" Using Range For example, package main import ( "fmt" "unicode/utf8" ) func ToValid(s string) string { if utf8.ValidString(s) { return s } v := make([]rune, 0, len(s)) for i, r := range s { if r == utf8.RuneError { _, size := utf8.DecodeLastRuneInString(s[i:]) if size == 1 { continue } } v = append(v, r) } return string(v) } func main() { s := "a\xc5b\x8ad" s = ToValid(s) fmt.Printf("%q\n", s) } "abd"
pooriabt

How to Check if a File is a Valid Image in Go

In Golang, there are 2 ways to check if a file is a valid image. Using DetectContentType Function The http.DetectContentType() function implements the algorithm described at https://mimesniff.spec.whatwg.org/ to determine the Content-Type of the given data. It considers at most the first 512 bytes of data. DetectContentType always returns a valid MIME type: if it cannot determine a more specific one, it returns "application/octet-stream". The following example should cover whatever you are trying to do: package main import ( "fmt" "net/http" "os" ) func main() { f, _ := os.Open("icon.png") defer f.Close() buff := make([]byte, 512) if _, err := f.Read(buff); err != nil { // panic() fmt.Println(err) } s := http.DetectContentType(buff) fmt.Println(s) } image/png Using Magic Number What is usually done is checking if the file has the right magic number for the image file format you want. While this test is not super accurate, it is usually good enough. package main import ( "fmt" "os" "strings" ) var magicTable = map[string]string{ "\xff\xd8\xff": "image/jpeg", "\x89PNG\r\n\x1a\n": "image/png", "GIF87a": "image/gif", "GIF89a": "image/gif", } func DetectType(b []byte) string { s := string(b) for key, val := range magicTable { if strings.HasPrefix(s, key) { return val } } return "" } func main() { f, _ := os.Open("icon.png") defer f.Close() buff := make([]byte, 512) if _, err := f.Read(buff); err != nil { // panic() fmt.Println(err) } s := DetectType(buff) fmt.Println(s) } image/png Matching an image type pattern An image MIME type is a MIME type whose type is "image". Byte Pattern Image MIME Type 00 00 01 00 image/x-icon 00 00 02 00 image/x-icon 42 4D image/x-icon 47 49 46 38 37 61 image/gif 47 49 46 38 39 61 image/gif 52 49 46 46 00 00 00 00 57 45 42 50 56 50 image/webp 89 50 4E 47 0D 0A 1A 0A image/png FF D8 FF image/jpeg
pooriabt

How to Count Characters in a String in Go

In Golang, there are 2 ways to count characters in a string. Using RuneCountInString Function Straight forward natively use the utf8.RuneCountInString() The following example should cover whatever you are trying to do: package main import ( "fmt" "unicode/utf8" ) func main() { s := "Hello,世界" i := utf8.RuneCountInString(s) fmt.Println(i) } 8 Using strings.Count Function The strings.Count() function counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s. For example, package main import ( "fmt" "strings" ) func main() { s := "Hello,世界" i := strings.Count(s, "l") fmt.Println(i) // 1 + number i = strings.Count(s, "") fmt.Printf("points: %d\n", i) fmt.Printf("length: %d\n", len(s)) } 2 points: 9 length: 12
aweis

How to Remove the First Character of a String in Go

In Golang, using the DecodeRuneInString function is the easiest way to remove the first character of a string. Using DecodeRuneInString Function The following example should cover whatever you are trying to do: package main import ( "fmt" "unicode/utf8" ) func trimFirstRune(s string) string { _, i := utf8.DecodeRuneInString(s) return s[i:] } func main() { fmt.Println(trimFirstRune("Hello")) fmt.Println(trimFirstRune("世界")) } ello 界 Using Range You can use range to get the size of the first rune and then slice: package main import "fmt" func trimFirstRune(s string) string { for i := range s { if i > 0 { return s[i:] } } return "" } func main() { fmt.Println(trimFirstRune("Hello")) fmt.Println(trimFirstRune("世界")) } ello 界
Patcher56

How to Clear a bytes.Buffer in Go

In Golang, using the buffer.Reset function is the easiest way to clear a bytes.Buffer Using buffer.Reset Function The buffer.Reset() function resets the buffer to be empty, but it retains the underlying storage for use by future writes. Reset is the same as Truncate(0). See the following example: package main import ( "bytes" "fmt" ) func main() { var b bytes.Buffer // A Buffer needs no initialization. b.Write([]byte("Hello ")) b.ReadByte() fmt.Printf("%v\n", b) // Clear b.Reset() fmt.Printf("%v\n", b) } {[72 101 108 108 111 32] 1 -1} {[] 0 0}
Unused

How to Print the Memory Address of a Slice in Go

In Golang, using the %p verbs is the easiest way to print the memory address of a slice. Using fmt.Printf Function Pointer: %p base 16 notation, with leading 0x. The %b, %d, %o, %x and %X verbs also work with pointers, formatting the value exactly as if it were an nteger. See the following example: package main import "fmt" func main() { a := []int{1, 2, 3} b := a[:] fmt.Printf("&a: %p\n", &a) fmt.Printf("&b: %p\n", &b) fmt.Printf(" a: %p\n", a) } &a: 0xc0000ac018 &b: 0xc0000ac030 a: 0xc0000ba000
Tomoki

How to Set Environment Variables in Python

In Python, using the os.environ variable is the easiest way to set environment variables Using os.environ Variable os.environ behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get and set operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings. For example, #!/usr/bin/python3 # Import module import os # Environment variables must be strings os.environ["GIT_PATH"] = "/usr/local" print(os.environ["GIT_PATH"]) /usr/local Python Errors str expected, not int: os.environ["GIT_VER"] = 1 File "/usr/local/lib/python3.10/os.py", line 756, in encode raise TypeError("str expected, not %s" % type(value).__name__) TypeError: str expected, not int
Sambhav Khandelwal

How to Get a List of All Subdirectories in the Current Directory in Python

In Python, there are 2 ways to get a list of all subdirectories in the current directory. Using os.walk Function The os.walk() method generates the file names in a directory tree by walking the tree either top-down or bottom-up. The following example: #!/usr/bin/python3 # Import module import os fs = os.walk(".") for root, dirs, files in fs: print(files) ['demo.py', 'start.sh', 'file.txt'] ['a.txt'] Using glob Function using the glob function is the easiest way to get a list of all subdirectories in the current directory. #!/usr/bin/python3 # Import module import glob fs = glob.glob("./*/*", recursive = True) for f in fs: print(f) ./a/a.txt Don't forget the trailing / after the *.
pooriabt

How to Get Key by Value in Dictionary in Python

In Python, there are 3 ways to get key by value in dictionary. Using keys Function Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position. The following example: #!/usr/bin/python3 d = {"a": 1, "b": 2, "c": 1} key = list(d.keys())[list(d.values()).index(1)] print(key) a Using List Comprehension Using a list comprehension is the most Pythonic way: #!/usr/bin/python3 d = {"a": 1, "b": 2, "c": 1} keys = [key for key, val in d.items() if val == 1] print(keys) ['a', 'c'] Using dict Method The following example should cover whatever you are trying to do: #!/usr/bin/python3 d = {"a": 1, "b": 2, "c": 1} key = dict((v,k) for k,v in d.items()).get(1) print(key) c
aweis

How to Remove all Empty Strings from a List of Strings in Python

In Python, there are 3 ways to remove all empty strings from a list of strings. Using filter Function The filter(function, iterable) function constructs an iterator from those elements of iterable for which function returns true. The following example: #!/usr/bin/python3 a = ["a", "", " ", "c", " "] # b = list(filter(bool, a)) # b = list(filter(len, a)) b = list(filter(None, a)) print(b) b = list(filter(str.strip, a)) print(b) ['a', ' ', 'c', ' '] ['a', 'c'] Using List Comprehension Using a list comprehension is the most Pythonic way: #!/usr/bin/python3 a = ["a", "", " ", "c", " "] b = [x for x in a if x.strip()] print(b) ['a', 'c'] Using join Method The following example should cover whatever you are trying to do: #!/usr/bin/python3 a = ["a", "", " ", "c", " "] b = ' '.join(a).split() print(b) ['a', 'c']
Sambhav Khandelwal

How to Get the System Hostname in Python

In Python, there are 3 ways to get the system hostname. Using gethostname Method The socket.gethostname() method returns a string containing the hostname of the machine where the Python interpreter is currently executing. For example, #!/usr/bin/python3 # Import module import socket print(socket.gethostname()) installmd.com Using platform Module The Path.resolve() method returns the computer’s network name (may not be fully qualified!). An empty string is returned if the value cannot be determined. #!/usr/bin/python3 # Import module import platform print(platform.node()) installmd.com Using uname Method You will probably load the os module anyway, so another suggestion would be: #!/usr/bin/python3 # Import module import os print(os.uname()[1]) print(os.uname()) installmd.com posix.uname_result(sysname='Linux', nodename='installmd.com', release='3.10.0-1160.el7.x86_64', version='#1 SMP Mon Oct 19 16:18:59 UTC 2020', machine='x86_64')
Tomoki