Go Library - getcode

Overview

This is a Golang library to automatically get an authorization code for retrieving access token using OAuth2.

Description

When it retrieves an access token and refresh token using OAuth2, the code for retrieving them has to be got by authorization on own browser. In order to retrieve the code, in generally, users have to click the authorization button and copy the code on the browser. This library can be automatically got the code by launching HTML server as a redirected server. At first, I have used this for retrieving the code from Google. But recently I noticed that this can be used for other sites. They are Google, GitHub, Slack and so on. This library can be used for creating such applications.

Retrieving Access Token for Google APIs

Gists

This sample is for retrieving access token for Google APIs. I created this for studying newStateToken().

Preparation

In order to use this sample, please do as follows.

  1. Deploy and launch Web Apps for retrieving redirect uri
    • On the Script Editor
      • File
      • -> Manage Versions
      • -> Save New Version
      • Publish
      • -> Deploy as Web App
      • -> At Execute the app as, select “your account”
      • -> At Who has access to the app, select “Only myself”
      • -> Click “Deploy”
      • -> Click “latest code” (By this click, it launches the authorization process.)
      • -> Please copy URL shown in the top of your browser as the redirect URI. And please modify the redirect URI like https://script.google.com/macros/s/#####/usercallback.
  2. Open console project
    • On the Script Editor
      • -> Resources
      • -> Cloud Platform Project
      • -> Click “Projects currently associated with this script”
      • -> Click API in start guide
  3. Retrieve client id and client secret
    • On the Console Project
      • Click authentication information at left side
      • -> Create a valid Client ID as OAyth client ID
      • -> Choose Web Application
      • -> Input Name (This is a name you want.)
      • -> Input redirect URI that you have already copied.
      • -> done
      • -> Please copy client ID and client Secret in a pop-up window.

Here, you have client ID, client Secret and redirect URI to retrieving refresh token and access token. These can be used for following sample script.

Updated: GAS Library - SOUWA

SOUWA means summing in Japanese. SOUWA can sum string elements in an array at the high speed. The speed of SOUWA with the pyramid algorithm is about 380 times faster than that of the standard method. New algorithm for summing array elements was developed for SOUWA. You can see the detailed report of this library at here. If you are interested in this, I’m glad.

It was updated to v1.0.2. Please check it out. https://github.com/tanaikech/SOUWA_GAS

Benchmark: Retrieving Values from Deep Nested JSON at Golang

This sample script is for retrieving values from a deep nested JSON. There are 2 patterns. So for these, the benchmark were measured.

Script :

package main

import (
    "encoding/json"
    "testing"
)

const (
    data = `{
      "A_key1": {
        "B_key1": {
          "C_key": "value"
        }
      }
    }`
)

func BenchmarkB1(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        var p map[string]interface{}
        json.Unmarshal([]byte(data), &p)
        a1 := p["A_key1"]
        a2 := p["A_key1"].(map[string]interface{})["B_key1"]
        a3 := p["A_key1"].(map[string]interface{})["B_key1"].(map[string]interface{})["C_key"]
        _ = a1 // --> map[B_key1:map[C_key:value]]
        _ = a2 // --> map[C_key:value]
        _ = a3 // --> value
    }
}

func BenchmarkB2(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        var p map[string]interface{}
        json.Unmarshal([]byte(data), &p)
        b1 := p["A_key1"]
        temp, _ := json.Marshal(b1)
        json.Unmarshal(temp, &p)
        b2 := p["B_key1"]
        temp, _ = json.Marshal(b2)
        json.Unmarshal(temp, &p)
        b3 := p["C_key"]
        _ = b1 // --> map[B_key1:map[C_key:value]]
        _ = b2 // --> map[C_key:value]
        _ = b3 // --> value
    }
}

Result :

$ go test -bench .
BenchmarkB1-4             300000              4177 ns/op
BenchmarkB2-4             100000             13619 ns/op
PASS

It was found that the process cost of json.Unmarshal() was high. json.Unmarshal() for test 2 is 3 times larger than that for test 1.

Reopening Current File as a File with New Name at Sublime

This is for Sublime Text. This sample is for reopening current file as a file with new file name. The current file is closed when reopening a new file.

newfilename = "new file name"
contents = self.view.substr(sublime.Region(0, self.view.size()))
window = self.view.window()
window.run_command('close_file')
view = window.new_file()
view.set_name(newfilename)
view.settings().set("auto_indent", False)
view.run_command("insert", {"characters": contents})
view.set_scratch(True)
view.run_command("prompt_save_as")

Flow of this sample

  1. Copy all text on current file to memory (contents).
  2. Close current file.
  3. Create new file with new file name.
  4. Paste contents to new file.
  5. Open dialog box for saving new file.

Search Route and Embedding Map using Custom Function on Spreadsheet

This sample script is for searching route between place A and B and embedding a map by custom function on Spreadsheet.

I think that this method is one of various ideas.

Problem

When the map is embedded to a cell on spreadsheet as an image, the function =IMAGE() is suitable for this situation. However, Class Maps, setFormula() for importing =IMAGE() and DriveApp.createFile() for creating images from maps also cannot be used for custom functions.

Updated: CLI Tool - goris

goris is a CLI tool to search for images with Google Reverse Image Search.

Today, it was updated to v1.1.0. Please check it out. https://github.com/tanaikech/goris

When images are matched to a searched image, web pages with matching images are retrieved. These are web pages displayed on Google top page. When this is not used, images are retrieved. This was added as a boolean option. (This was added by a request.)

Giving and Retrieving Parameters for Chart at GAS

This sample script is for retrieving parameters from a chart. The chart created by both Google Apps Script and manually operation can be used.

Creates Chart

When a chart is created, it supposes following parameters.

var parameters = {
  "title": "x axis",
  "fontName": "Arial",
  "minValue": 0,
  "maxValue": 100,
  "titleTextStyle": {
    "color": "#c0c0c0",
    "fontSize": 10,
    "fontName": "Roboto",
    "italic": true,
    "bold": false
  }
};

.setOption('hAxis', parameters)

Retrieve Parameters From Chart

For the chart created by above parameters, in order to retrieve the parameters, it uses following script.

Error Handling for Subprocess at Python

This sample is for error handling for subprocess.Popen. It confirms whether the execution file is existing. If the execution file is also not in the path, the error message is shown.

import subprocess

res = subprocess.Popen(
    "application",  #  <- Execution file
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    shell=True
).communicate()

if len(res[1]) == 0:
    print("ok: Application is existing.")
else:
    print("Error: Application is not found.")

Using Constructor Between Classes at Python

This sample is for using constructor between classes at Python.

Sample :

class test1:

    def __init__(self):
        self.msg = "sample text"


class test2:

    def __init__(self):
        self.msg = test1().msg


print(test2().msg)

>>> sample text