How to use the html/template package in Golang

Tagged golang, html, template, reload  Languages go, bash

Features:

  • template reloading
  • view helpers
  • HTML files are embedded in the binary
package main

import (
    rice "github.com/GeertJohan/go.rice"
    "gitlab.com/christianhellsten/go-utils/log"
    "html/template"
    "net/http"
    "os"
    "path/filepath"
    "strings"
)

type renderTemplateFunc func(w http.ResponseWriter, tmpl string, p interface{})

var renderTemplate renderTemplateFunc
var templates = template.New("").Funcs(templateMap)
var templateBox *rice.Box

func loadTemplates() {
    if config.debug {
        renderTemplate = renderTemplateDev
    } else {
        renderTemplate = renderTemplateProd
        newTemplate := func(path string, _ os.FileInfo, _ error) error {
            if path == "" {
                return nil
            }
            templateString, err := templateBox.String(path)
            if err != nil {
                log.Fatal("Unable to parse: path=%s, err=%s", path, err)
            }
            templates.New(filepath.Join("tmpl", path)).Parse(templateString)
            return nil
        }
        // Load and parse templates from binary or disk
        templateBox = rice.MustFindBox("tmpl")
        templateBox.Walk("", newTemplate)
    }
}

var (
    templateMap = template.FuncMap{
        "Upper": func(s string) string {
            return strings.ToUpper(s)
        },
    }
)

func renderTemplateProd(w http.ResponseWriter, tmpl string, p interface{}) {
    err := templates.ExecuteTemplate(w, tmpl, p)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

func renderTemplateDev(w http.ResponseWriter, tmpl string, p interface{}) {
    t, _ := template.ParseFiles(tmpl)
    t.Execute(w, p)
}

Usage:

go get
go get github.com/GeertJohan/go.rice/rice
rice embed-go
go build

Reference: https://github.com/jmcfarlane/golang-templates-example

Testing Whenever with Rspec

Tagged cron, rspec, whenever  Languages ruby
require 'spec_helper'
require 'whenever'

describe Whenever do
  def gen_cron(stage:)
    x = Whenever::JobList.new(
      file: Rails.root.join("config", "schedule.rb").to_s,
      set: "stage=#{stage}"
    ).generate_cron_output
    x.gsub(Dir.pwd, "")
  end

  it "generates correct cron configuration for each stage" do
    [ :qa, :production ].each do |stage|
      expected = File.read("spec/fixtures/#{stage}.cron")
      cron = gen_cron(stage: stage)
      # NOTE: Uncomment to update expected cron configuration
      #File.open("spec/fixtures/#{stage}.cron", "w") {|x| x << cron }
      assert_equal expected.strip, cron.strip
    end
  end
end

How to get the latest version number from a list of git tags

Tagged bash, git, version, zsh  Languages bash

This will print the latest version number that a git repository has been tagged with:

$ git tag -l 'v*' | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n | tail -n 1
v1.5.6

Note that some versions of the sort command have a —version-sort switch, and some don’t:

sort: unrecognized option `--version-sort'
Try `sort --help' for more information.

Simple content negotation in Golang

Tagged accept, go  Languages go
func DoSomething(r *http.Request) string {
    accept := r.Header.Get("Accept")
    switch accept {
    case "application/json":
        return renderJSON()
    case "application/xml":
        return renderXML()
    }
    return renderHTML()
}

How to fix 80% of IE browser issues

Tagged bug, html, ie, internet explorer, compatibility  Languages 

Tell IE to use standards mode, not quirks mode

Define your doctype in your HTML:

<!DOCTYPE> element

See: https://msdn.microsoft.com/en-us/library/cc288325(v=vs.85).aspx

Tell IE to not use compatibility mode

This prevents, for example, IE 11 from using IE 7 rendering mode which can happen for many reasons.

If you can’t add an HTTP header, then add this to your HTML and pray that it helps:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

IE is using a compatibility mode if you see “compatible; MSIE” in the user agent header:

"Mozilla/4.0 (compatible; MSIE 7.0;"

See:

Validate your HTML and CSS

https://validator.w3.org/

Use an IE hack

Try “zoom” or “!important”.

XPath with namespaces example in Go

Tagged go, xml, xpath  Languages go
package main

import (
    "fmt"
    "github.com/moovweb/gokogiri"
    "github.com/moovweb/gokogiri/xpath"
    "io/ioutil"
)

func main() {
    xml, _ := ioutil.ReadFile("elrc-20130531.xml")
    doc, _ := gokogiri.ParseXml(xml)
    defer doc.Free()
    xp := doc.DocXPathCtx()
    xp.RegisterNamespace("xbrli", "http://www.xbrl.org/2003/instance")
    x := xpath.Compile("//xbrli:context")
    groups, err := doc.Search(x)
    if err != nil {
        fmt.Println(err)
    }
    for i, group := range groups {
        fmt.Println(i, group.Content())
    }
}
go get
go run main.go

Switching from Tensorflow to Theano backend in Keras

Tagged keras, tensorflow, theano  Languages 
  • Fixing “ValueError: Negative dimension size caused by subtracting 2 from 1 for ‘MaxPool_1’ (op: ‘MaxPool’) with input shapes: [?,1,112,128].”

Change Keras’ backend from Tensorflow to Theano:

{
  "image_dim_ordering": "tf", 
  "epsilon": 1e-07, 
  "floatx": "float32", 
  "backend": "tensorflow"
}
{
  "image_dim_ordering": "tf", 
  "epsilon": 1e-07, 
  "floatx": "float32", 
  "backend": "theano"
}
  • Fixing “ValueError: The shape of the input to “Flatten” is not fully defined (got (0, 7, 512). Make sure to pass a complete “input_shape” or “batch_input_shape” argument to the first layer in your model.”

Change Keras’ image dimension ordering convention from “tf” (Tensorflow) to “th” (Theano):

{
  "image_dim_ordering": "tf", 
  "epsilon": 1e-07, 
  "floatx": "float32", 
  "backend": "theano"
}
{
  "image_dim_ordering": "th", 
  "epsilon": 1e-07, 
  "floatx": "float32", 
  "backend": "theano"
}

Reference

https://keras.io/backend/