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

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