📜 Useful Snippets from 2017

February 13, 2018  

I have an orgmode file which contains a whole bunch of code snippets I come across. Sometime the snippets are nothing more than a first try at learning a new language, while others contain code I came across and never want to lose. The main reason for this post is more selfish than selfless - I really just want these up online so that I can access them easily. That said, I've tried to frame the problem around some of these code snippets such that a naive reader might find some of them useful (or actually find them from Google).

Golang

Parse Time > 24h

Related to this Stack Exchange question I asked: https://stackoverflow.com/questions/47067211/parsing-hhmmss-time-from-stopwatch-in-go

I had a series of stopwatch-like timestamps in a logfile formatted as hh:mm:ss, e.g. "00:03:30". How would I go about parsing such timestamps in Golang such that I could find the difference between two time intervals?

For example, substituting 00:03:30 and 00:03:00 should return 00:00:30 or 30.

func Parse(st string) (int, error) {
    var h, m, s int
    n, err := fmt.Sscanf(st, "%d:%d:%d", &h, &m, &s)
    fmt.Print(n, err)
    if err != nil || n != 3 {
        return 0, err  
    }
    return h*3600 + m*60 + s, nil
}

Simple Example of a Regex in Golang

package main

import (
 "bufio"
 "fmt"
 "os"
 "regexp"
 "time"
)

var tick = regexp.MustCompile("<clock>tick</clock>")
var timeline = regexp.MustCompile(`<hpc_elapsed_time>([-+]?[0-9]*\.?[0-9]+)</hpc_elapsed_time>`)

func main() {
 start := time.Now()            // Start a timer
 log, err := os.Open("atc.log") // Read the log file
 defer log.Close()
 check(err) // check for error in log

 reader := bufio.NewReader(log) // Start reading from the file with a reader.
 var line string                // Static declaration
 for {
	 line, err = reader.ReadString('\n') // similar to 'for line in reader'
	 findms(line)                        // call the ms regex function
	 if err != nil {                     // Manually end when no \n
		 break
	 }
 }
 elapsed := time.Since(start)
 fmt.Printf("script took %s", elapsed)
}

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

func findms(line string) {
 if tick.MatchString(line) == true {
	 fmt.Println(timeline.FindStringSubmatch(line))
 }
}

Slice of Structs in Golang

package main

import (
	"fmt"
	"math/rand"
)

type participant struct {
	id     int
	age    int
	trials []string
}

var participants []participant

func main() {
	for i := 0; i < 10; i++ {
		p := participant{
			id:  i,
			age: rand.Intn(50),
		}
		participants = append(participants, p)

	}

	for _, p := range participants {
		if p.id == 1 {
			fmt.Println(p.id, p.age)
		}
	}

}

C#

Simple Example of an Interface

A friend kindly wrote up this skeleton to help me understand interfaces in C#.

public interface IContactCustomer
{
 void ContactCustomer(string custId):
}

public class ContactCustomer : IContactCustomer
{
 void ContactCustomer(string custId)
 {}
}

public class PhoneService : ContactCustomer
{
 void ContactCustomer(string custId)
 {
	 // Code for sms-ing customer
 }
}

public class EmailService : ContactCustomer
{
 void ContacatCustomer(string custId)
 {
	 // Code for emailing customer
 }
}

static void Main()
{
 List<Customers> custList = new List<ContactCustomer>();

 for (i = 0; i < custList.Length; i++)
 {
	
 }
}

Bash

Batch Renaming 1 - X

I came across this issue as well (answer found https://stackoverflow.com/a/37826687)

I want to rename the files in a directory to sequential numbers. Based on creation date of the files.

For Example sadf.jpg to 0001.jpg, wrjr3.jpg to 0002.jpg and so on, the number of leading zeroes depending on the total amount of files (no need for extra zeroes if not needed).

ls | cat -n | while read n f; do mv "$f" "$n.extension"; done X

Killall of particular Process Linux

#2. Killall Command – Kill processes by name
#Instead of specifying a process by its PID, you can specify the name of the process. If more than one process runs with that name, all of them will be killed.
#Example: Kill all the firefox processes

killall -9 firefox

Emacs

Bind key to Dired directory

(global-set-key (kbd "C-x M-1") (lambda() (interactive)(find-file "~/Dropbox/org/")))
(global-set-key (kbd "C-x M-2") (lambda() (interactive)(find-file "~/humanfactors/michael-blog/")))
(global-set-key (kbd "C-x M-3") (lambda() (interactive)(find-file "~/Code/")))

Bibtex lookup current clipboard entry

This automatically exports a string on the clipboard to a crossref search (e.g. searching a DOI). I find this super useful when cleaning up references in bibtex.

(global-set-key (kbd "C-c C-m")
                (lambda ()
                  (interactive)
                  (crossref-lookup (current-kill 0))))

Org Mode Beamer Template

#+TITLE:     Writing Beamer presentations in org-mode
#+AUTHOR:    Eric S Fraga
#+EMAIL:     e.fraga@ucl.ac.uk
#+DATE:      [2013-03-13 Wed]
#+DESCRIPTION: Example of using org to create presentations using the beamer exporter
#+KEYWORDS:  beamer org orgmode
#+LANGUAGE:       
#+LaTeX_CLASS: beamer

;; Beamer supports alternate themes.  Choose your favourite here
#+BEAMER_THEME: metropolis [height=20pt]
#+LaTeX_CLASS_options: []

;; the beamer exporter expects to be told which level of headlines
;; defines the frames.  We use the first level headlines for sections
;; and the second (hence H:2) for frames.
;; for a column view of options and configurations for the individual
;; frames

Org Easy templates

Org mode supports insertion of empty structural elements (like #+BEGIN_SRC and #+END_SRC pairs) with just a few key strokes. This is achieved through a native template expansion mechanism. Note that Emacs has several other template mechanisms which could be used in a similar way, for example yasnippet.

To insert a structural element, type a ‘<', followed by a template selector and <TAB>. Completion takes effect only when the above keystrokes are typed on a line by itself.

The following template selectors are currently supported.


| s   | =#+BEGIN_SRC     ... #+END_SRC=\\       |
| e   | =#+BEGIN_EXAMPLE ... #+END_EXAMPLE=\\   |
| q   | =#+BEGIN_QUOTE   ... #+END_QUOTE=\\     |
| v   | =#+BEGIN_VERSE   ... #+END_VERSE=\\     |
| c   | =#+BEGIN_CENTER  ... #+END_CENTER=\\    |
| l   | =#+BEGIN_LaTeX   ... #+END_LaTeX=\\     |
| L   | =#+LaTeX:=\\                            |
| h   | =#+BEGIN_HTML    ... #+END_HTML=\\      |
| H   | =#+HTML:=\\                             |
| a   | =#+BEGIN_ASCII   ... #+END_ASCII=\\     |
| A   | =#+ASCII:=\\                            |
| i   | =#+INDEX:= line\\                       |
| I   | =#+INCLUDE:= line\\                     |

For example, on an empty line, typing "<e" and then pressing TAB, will expand into a complete EXAMPLE template.

You can install additional templates by customizing the variable org-structure-template-alist. See the docstring of the variable for additional details.

http://orgmode.org/manual/Easy-Templates.html

ImageMagick

Joining images side by side

# Full
montage [0-5].png -tile 5x1 -geometry +0+0 out.png
# Horitzontal
 convert +append *.png out.png 
# vertical
 convert -append *.png out.png