text stringlengths 11 4.05M |
|---|
package main
import "fmt"
func main() {
x := struct {
nome string
idade int
}{
nome: "Maior",
idade: 50,
}
fmt.Println(x)
}
|
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "swagger-filter",
Short: "Filter a swagger specification by endpoint",
Long: `Filter a swagger specification by endpoint`,
RunE: filterCmd,
Args: cobra.MinimumNArgs(2),
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize()
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.swagger-filter.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().StringSliceP("endpoint", "", nil, "Endpoints to filter, by exact path")
rootCmd.Flags().StringSliceP("endpoint-prefix", "", nil, "Endpoints to filter, by prefix")
rootCmd.Flags().StringSliceP("endpoint-regexp", "", nil, "Endpoints to filter, by regexp")
}
|
package confighandler
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestConfigHandler(t *testing.T) {
data := []byte(`
[streamjuryconfig]
SuperUserId = 123456
ChannelId = -987654
ApiKey = "abcdefg:1234"
ResultsAbsPath = "/var/www/blargh/"
`)
tomlConfig := LoadConfig(data)
assert.Equal(t, 123456, tomlConfig.StreamjuryConfig.SuperUserId)
assert.Equal(t, int64(-987654), tomlConfig.StreamjuryConfig.ChannelId)
assert.Equal(t, "abcdefg:1234", tomlConfig.StreamjuryConfig.ApiKey)
assert.Equal(t, "/var/www/blargh/", tomlConfig.StreamjuryConfig.ResultsAbsPath)
}
|
func main() {
conn, err := grpc.Dial("localhost:9999", grpc.WithInsecure())
if err != nil {
log.Fatalf("連線失敗:%v", err)
}
defer conn.Close()
c := pb.NewEchoClient(conn)
r, err := c.Echo(context.Background(), &pb.EchoRequest{Msg: "HI HI HI HI"})
if err != nil {
log.Fatalf("無法執行 Plus 函式:%v", err)
}
log.Printf("回傳結果:%s , 時間:%d", r.Msg, r.Unixtime)
}
|
/*
Copyright © 2021 Faruk AK <kakuraf@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// providerCmd represents the provider command
var providerCmd = &cobra.Command{
Use: "provider",
Short: "Add a provider your module",
Long: `A module is a container for multiple resources that are used together.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Provider creating...")
region, _ := cmd.Flags().GetString("region") // ./terrathor provider --region=eu-west-1
if region != "" {
createProvider("test", region)
}
},
}
func init() {
rootCmd.AddCommand(providerCmd)
providerCmd.PersistentFlags().String("region", "", "Region of provider")
providerCmd.MarkPersistentFlagRequired("region")
}
func createProvider(folderName string, region string) {
vars := make(map[string]string)
vars["region"] = region
pies := []File{
{
TemplatePath: "./templates/provider/provider.tmpl",
FilePath: "test/provider.tf",
FolderPath: folderName,
},
{
TemplatePath: "./templates/provider/tfvars.tmpl",
FilePath: "test/terraform.tfvars",
FolderPath: folderName,
},
{
TemplatePath: "./templates/provider/variables.tmpl",
FilePath: "test/variables.tf",
FolderPath: folderName,
},
}
for _, p := range pies {
p.CreateFolder()
t := p.Parse()
fs := p.CreateFile()
err := t.Execute(fs, vars)
p.ErrorHandler(err)
defer fs.Close()
}
}
|
/*
命題
"paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.
さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.
*/
package main
import (
"fmt"
"strings"
)
func biGram(str string) []string {
list := strings.Split(str, "")
var grams []string
for i := range list {
if i == 0 {
continue
}
grams = append(grams, list[i - 1] + list[i])
}
return grams
}
func uniqueGram(biGram []string) []string {
unique := []string{}
for _, gram := range biGram {
strUnique := strings.Join(unique, " ")
if !strings.Contains(strUnique, gram) {
unique = append(unique, gram)
}
}
return unique
}
func union(biGrams ...[]string) []string {
var unionGram []string
for _, biGram := range biGrams {
if len(unionGram) == 0 {
unionGram = biGram
}
for _, gram := range biGram {
strUnionGram := strings.Join(unionGram, " ")
if !strings.Contains(strUnionGram, gram) {
unionGram = append(unionGram, gram)
}
}
}
return unionGram
}
func intersection(biGrams ...[]string) []string {
var inGram []string
for i, biGram := range biGrams {
if i == 0 {
continue
}
prevGram := biGrams[i - 1]
for _, gram := range biGram {
strPrevGram := strings.Join(prevGram, " ")
if strings.Contains(strPrevGram, gram) {
inGram = append(inGram, gram)
}
}
}
return uniqueGram(inGram)
}
func difference(biGrams ...[]string) []string {
var diffGram []string
for i, currentBiGram := range biGrams {
if i == 0 {
continue
}
prevGram := biGrams[i - 1]
for _, gram := range prevGram {
strCurrentGram := strings.Join(currentBiGram, " ")
if !strings.Contains(strCurrentGram, gram) {
diffGram = append(diffGram, gram)
}
}
}
return uniqueGram(diffGram)
}
func isInclude(strSlice []string, keyword string) bool {
str := strings.Join(strSlice, " ")
return strings.Contains(str, keyword)
}
func main() {
str1 := "paraparaparadise"
str2 := "paragraph"
biGramX := biGram(str1)
biGramY := biGram(str2)
uniqueGramX := uniqueGram(biGramX)
uniqueGramY := uniqueGram(biGramY)
fmt.Println("X bi-gram", biGramX)
fmt.Println("Y bi-gram", biGramY)
fmt.Println("和集合", union(uniqueGramX, uniqueGramY))
fmt.Println("積集合", intersection(uniqueGramX, uniqueGramY))
fmt.Println("差集合", difference(uniqueGramX, uniqueGramY))
fmt.Println("Xにseが含まれるか", isInclude(biGramX, "se"))
fmt.Println("Yにseが含まれるか", isInclude(biGramY, "se"))
/* =>
X bi-gram [pa ar ra ap pa ar ra ap pa ar ra ad di is se]
Y bi-gram [pa ar ra ag gr ra ap ph]
和集合 [pa ar ra ap ad di is se ag gr ph]
積集合 [pa ar ra ap]
差集合 [ad di is se]
Xにseが含まれるか true
Yにseが含まれるか false
*/
}
|
package main
func isMatch(s string, p string) bool {
isVisit = make(map[int]bool)
return isMatchExec(s, p, len(s), len(p))
}
var isVisit map[int]bool
func hash(ends, endp int) int {
return (ends << 20) | endp
}
func isMatchExec(s string, p string, ends, endp int) bool {
if ends == 0 && endp == 0 {
return true
}
if endp == 0 {
return false
}
if ends == 0 {
for i := 0; i < endp; i++ {
if p[i] != '*' {
return false
}
}
return true
}
hashNumber := hash(ends, endp)
if x, ok := isVisit[hashNumber]; ok {
return x
}
ans := false
if s[ends-1] == p[endp-1] || p[endp-1] == '?' {
ans = isMatchExec(s, p, ends-1, endp-1)
} else {
if p[endp-1] == '*' {
for i := ends; i >= 0 && ans == false; i-- {
ans = isMatchExec(s, p, i, endp-1)
}
}
}
isVisit[hashNumber] = ans
return ans
}
/*
总结
1. 第一次写想到了记忆化搜索,但是哈希函数采用的是字符串哈希,所以超时了。
2. 第二次就用数字哈希,然后就AC了。
3. 所以尽量不要采用字符串哈希..很慢..
4. 这题和编辑距离类似,都是匹配问题。
5. 这题官方还有使用暴力法、DP做的。
*/
|
package minion
import (
"testing"
"time"
"github.com/quilt/quilt/db"
"github.com/quilt/quilt/stitch"
"github.com/stretchr/testify/assert"
)
const testImage = "alpine"
func TestContainerTxn(t *testing.T) {
conn := db.New()
trigg := conn.Trigger(db.ContainerTable).C
spec := ""
testContainerTxn(t, conn, spec)
assert.False(t, fired(trigg))
spec = `deployment.deploy(
new Service("a", [new Container("alpine", ["tail"])])
)`
testContainerTxn(t, conn, spec)
assert.True(t, fired(trigg))
testContainerTxn(t, conn, spec)
assert.False(t, fired(trigg))
spec = `var b = new Container("alpine", ["tail"]);
deployment.deploy([
new Service("b", [b]),
new Service("a", [b, new Container("alpine", ["tail"])])
]);`
testContainerTxn(t, conn, spec)
assert.True(t, fired(trigg))
spec = `var b = new Service("b", [new Container("alpine", ["cat"])]);
deployment.deploy([
b,
new Service("a",
b.containers.concat([new Container("alpine", ["tail"])])),
]);`
testContainerTxn(t, conn, spec)
assert.True(t, fired(trigg))
spec = `var b = new Service("b", [new Container("ubuntu", ["cat"])]);
deployment.deploy([
b,
new Service("a",
b.containers.concat([new Container("alpine", ["tail"])])),
]);`
testContainerTxn(t, conn, spec)
assert.True(t, fired(trigg))
spec = `deployment.deploy(
new Service("a", [
new Container("alpine", ["cat"]),
new Container("alpine", ["cat"])
])
);`
testContainerTxn(t, conn, spec)
assert.True(t, fired(trigg))
spec = `deployment.deploy(
new Service("a", [new Container("alpine")])
)`
testContainerTxn(t, conn, spec)
assert.True(t, fired(trigg))
spec = `var b = new Service("b", [new Container("alpine")]);
var c = new Service("c", [new Container("alpine")]);
deployment.deploy([
b,
c,
new Service("a", b.containers.concat(c.containers)),
])`
testContainerTxn(t, conn, spec)
assert.True(t, fired(trigg))
testContainerTxn(t, conn, spec)
assert.False(t, fired(trigg))
}
func testContainerTxn(t *testing.T, conn db.Conn, spec string) {
compiled, err := stitch.FromJavascript(spec, stitch.DefaultImportGetter)
assert.Nil(t, err)
var containers []db.Container
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
updatePolicy(view, compiled.String())
containers = view.SelectFromContainer(nil)
return nil
})
for _, e := range queryContainers(compiled) {
found := false
for i, c := range containers {
if e.StitchID == c.StitchID {
containers = append(containers[:i], containers[i+1:]...)
found = true
break
}
}
assert.True(t, found)
}
assert.Empty(t, containers)
}
func TestConnectionTxn(t *testing.T) {
conn := db.New()
trigg := conn.Trigger(db.ConnectionTable).C
pre := `var a = new Service("a", [new Container("alpine")]);
var b = new Service("b", [new Container("alpine")]);
var c = new Service("c", [new Container("alpine")]);
deployment.deploy([a, b, c]);`
spec := ""
testConnectionTxn(t, conn, spec)
assert.False(t, fired(trigg))
spec = pre + `a.connect(80, a);`
testConnectionTxn(t, conn, spec)
assert.True(t, fired(trigg))
testConnectionTxn(t, conn, spec)
assert.False(t, fired(trigg))
spec = pre + `a.connect(90, a);`
testConnectionTxn(t, conn, spec)
assert.True(t, fired(trigg))
testConnectionTxn(t, conn, spec)
assert.False(t, fired(trigg))
spec = pre + `b.connect(90, a);
b.connect(90, c);
b.connect(100, b);
c.connect(101, a);`
testConnectionTxn(t, conn, spec)
assert.True(t, fired(trigg))
testConnectionTxn(t, conn, spec)
assert.False(t, fired(trigg))
spec = pre
testConnectionTxn(t, conn, spec)
assert.True(t, fired(trigg))
testConnectionTxn(t, conn, spec)
assert.False(t, fired(trigg))
}
func testConnectionTxn(t *testing.T, conn db.Conn, spec string) {
compiled, err := stitch.FromJavascript(spec, stitch.DefaultImportGetter)
assert.Nil(t, err)
var connections []db.Connection
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
updatePolicy(view, compiled.String())
connections = view.SelectFromConnection(nil)
return nil
})
exp := compiled.Connections
for _, e := range exp {
found := false
for i, c := range connections {
if e.From == c.From && e.To == c.To && e.MinPort == c.MinPort &&
e.MaxPort == c.MaxPort {
connections = append(
connections[:i], connections[i+1:]...)
found = true
break
}
}
assert.True(t, found)
}
assert.Empty(t, connections)
}
func fired(c chan struct{}) bool {
time.Sleep(5 * time.Millisecond)
select {
case <-c:
return true
default:
return false
}
}
func TestPlacementTxn(t *testing.T) {
conn := db.New()
checkPlacement := func(spec string, exp ...db.Placement) {
compiled, err := stitch.FromJavascript(spec,
stitch.DefaultImportGetter)
assert.Nil(t, err)
placements := map[db.Placement]struct{}{}
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
updatePolicy(view, compiled.String())
res := view.SelectFromPlacement(nil)
// Set the ID to 0 so that we can use reflect.DeepEqual.
for _, p := range res {
p.ID = 0
placements[p] = struct{}{}
}
return nil
})
assert.Equal(t, len(exp), len(placements))
for _, p := range exp {
_, ok := placements[p]
assert.True(t, ok)
}
}
pre := `var foo = new Service("foo", [new Container("foo")]);
var bar = new Service("bar", [new Container("bar")]);
var baz = new Service("baz", [new Container("bar")]);
deployment.deploy([foo, bar, baz]);`
// Create an exclusive placement.
spec := pre + `bar.place(new LabelRule(true, foo));`
checkPlacement(spec,
db.Placement{
TargetLabel: "bar",
Exclusive: true,
OtherLabel: "foo",
},
)
// Change the placement from "exclusive" to "on".
spec = pre + `bar.place(new LabelRule(false, foo));`
checkPlacement(spec,
db.Placement{
TargetLabel: "bar",
Exclusive: false,
OtherLabel: "foo",
},
)
// Add another placement constraint.
spec = pre + `bar.place(new LabelRule(false, foo));
bar.place(new LabelRule(true, bar));`
checkPlacement(spec,
db.Placement{
TargetLabel: "bar",
Exclusive: false,
OtherLabel: "foo",
},
db.Placement{
TargetLabel: "bar",
Exclusive: true,
OtherLabel: "bar",
},
)
// Machine placement
spec = pre + `foo.place(new MachineRule(false, {size: "m4.large"}));`
checkPlacement(spec,
db.Placement{
TargetLabel: "foo",
Exclusive: false,
Size: "m4.large",
},
)
// Port placement
spec = pre + `publicInternet.connect(80, foo);
publicInternet.connect(81, foo);`
checkPlacement(spec,
db.Placement{
TargetLabel: "foo",
Exclusive: true,
OtherLabel: "foo",
},
)
spec = pre + `publicInternet.connect(80, foo);
publicInternet.connect(80, bar);
(function() {
publicInternet.connect(81, bar);
publicInternet.connect(81, baz);
})()`
checkPlacement(spec,
db.Placement{
TargetLabel: "foo",
Exclusive: true,
OtherLabel: "foo",
},
db.Placement{
TargetLabel: "bar",
Exclusive: true,
OtherLabel: "bar",
},
db.Placement{
TargetLabel: "foo",
Exclusive: true,
OtherLabel: "bar",
},
db.Placement{
TargetLabel: "bar",
Exclusive: true,
OtherLabel: "foo",
},
db.Placement{
TargetLabel: "baz",
Exclusive: true,
OtherLabel: "baz",
},
db.Placement{
TargetLabel: "bar",
Exclusive: true,
OtherLabel: "baz",
},
db.Placement{
TargetLabel: "baz",
Exclusive: true,
OtherLabel: "bar",
},
)
}
|
package param
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/json-iterator/go"
"github.com/toolkits/pkg/errors"
)
func String(r *http.Request, key string, defVal string) string {
if val, ok := r.URL.Query()[key]; ok {
if val[0] == "" {
return defVal
}
return strings.TrimSpace(val[0])
}
if r.Form == nil {
errors.Dangerous(r.ParseForm())
}
val := r.Form.Get(key)
if val == "" {
return defVal
}
return strings.TrimSpace(val)
}
func MustString(r *http.Request, key string, displayName ...string) string {
val := String(r, key, "")
if val == "" {
name := key
if len(displayName) > 0 {
name = displayName[0]
}
errors.Bomb("%s is necessary", name)
}
return val
}
func Int64(r *http.Request, key string, defVal int64) int64 {
raw := String(r, key, "")
if raw == "" {
return defVal
}
val, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return defVal
}
return val
}
func MustInt64(r *http.Request, key string, displayName ...string) int64 {
raw := String(r, key, "")
if raw == "" {
name := key
if len(displayName) > 0 {
name = displayName[0]
}
errors.Bomb("%s is necessary", name)
}
val, err := strconv.ParseInt(raw, 10, 64)
errors.Dangerous(err)
return val
}
func Int(r *http.Request, key string, defVal int) int {
raw := String(r, key, "")
if raw == "" {
return defVal
}
val, err := strconv.Atoi(raw)
if err != nil {
return defVal
}
return val
}
func MustInt(r *http.Request, key string, displayName ...string) int {
name := key
if len(displayName) > 0 {
name = displayName[0]
}
raw := String(r, key, "")
if raw == "" {
errors.Bomb("%s is necessary", name)
}
val, err := strconv.Atoi(raw)
if err != nil {
errors.Bomb("%s should be integer", name)
}
return val
}
func Float64(r *http.Request, key string, defVal float64) float64 {
raw := String(r, key, "")
if raw == "" {
return defVal
}
val, err := strconv.ParseFloat(raw, 64)
if err != nil {
return defVal
}
return val
}
func MustFloat64(r *http.Request, key string, displayName ...string) float64 {
raw := String(r, key, "")
if raw == "" {
name := key
if len(displayName) > 0 {
name = displayName[0]
}
errors.Bomb("%s is necessary", name)
}
val, err := strconv.ParseFloat(raw, 64)
errors.Dangerous(err)
return val
}
func Bool(r *http.Request, key string, defVal bool) bool {
raw := String(r, key, "")
if raw == "true" || raw == "1" || raw == "on" || raw == "checked" || raw == "yes" {
return true
} else if raw == "false" || raw == "0" || raw == "off" || raw == "" || raw == "no" {
return false
}
return defVal
}
func MustBool(r *http.Request, key string) bool {
raw := ""
if val, ok := r.URL.Query()[key]; ok {
raw = strings.TrimSpace(val[0])
} else {
errors.Bomb("%s is necessary", key)
}
if raw == "true" || raw == "1" || raw == "on" || raw == "checked" || raw == "yes" {
return true
} else if raw == "false" || raw == "0" || raw == "off" || raw == "" || raw == "no" {
return false
} else {
errors.Bomb("bad request")
}
return false
}
func BindJson(r *http.Request, obj interface{}) error {
if r.Body == nil {
return fmt.Errorf("Empty request body")
}
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
err := json.Unmarshal(body, obj)
if err != nil {
return fmt.Errorf("unmarshal body %s err:%v", string(body), err)
}
return err
}
|
package logger
import (
"sync"
"github.com/sirupsen/logrus"
)
var logger *logrus.Logger
var onceInitLogger sync.Once
func Get() *logrus.Logger {
onceInitLogger.Do(func() {
logger = logrus.New()
logger.SetFormatter(&logrus.JSONFormatter{
FieldMap: logrus.FieldMap{
"FieldKeyTime": "time",
"FieldKeyLevel": "level",
"FieldKeyMsg": "msg",
},
})
})
return logger
}
|
package gostomp
import (
"bytes"
"strings"
)
var (
replacerEncodeValues = strings.NewReplacer(
"\\", "\\\\",
"\r", "\\r",
"\n", "\\n",
":", "\\c",
)
replacerDecodeValues = strings.NewReplacer(
"\\r", "\r",
"\\n", "\n",
"\\c", ":",
"\\\\", "\\",
)
)
// Encodes a header value using STOMP value encoding
func encodeValue(s string) []byte {
var buf bytes.Buffer
buf.Grow(len(s))
replacerEncodeValues.WriteString(&buf, s)
return buf.Bytes()
}
// Unencodes a header value using STOMP value encoding
func decodeValue(b []byte) (string, error) {
s := replacerDecodeValues.Replace(string(b))
return s, nil
}
|
package structs
//easyjson:json
type User struct {
ID int
Name string
Login string
Password string
Email string
Status string
}
|
package backtracking
import "sort"
func permuteUnique(nums []int) [][]int {
sort.Ints(nums)
var res [][]int
var cur []int
help47(nums, map[int]bool{}, &res, &cur)
return res
}
func help47(nums []int, used map[int]bool, res *[][]int, cur *[]int) {
if len(*cur) == len(nums) {
tmp := make([]int, len(nums))
copy(tmp, *cur)
*res = append(*res, tmp)
return
}
for i := 0; i < len(nums); i++ {
if used[i] {
continue
}
if i > 0 && nums[i-1] == nums[i] && used[i-1] {
continue
}
*cur = append(*cur, nums[i])
used[i] = true
help47(nums, used, res, cur)
used[i] = false
*cur = (*cur)[:len(*cur)-1]
}
}
|
package reservasi
import(
"net/http"
"html/template"
"log"
"fmt"
conn "project_reservasi/src/config"
m "project_reservasi/src/model"
)
func ReservasiHandler(w http.ResponseWriter,r *http.Request){
http.FileServer(http.Dir("assets"))
// var data = map[string]interface{}{
// "title": "Learning Golang Web",
// "name": "Kelompok 2",
// }
// var err = tmpl.ExecuteTemplate(w, "reservasi", data)
// if err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// }
var tmpl = template.Must(template.ParseFiles(
"views/user/reservasi/reservasi.html",
"views/user/atribut/head.html",
"views/user/atribut/top.html",
"views/user/atribut/script.html",
"views/user/atribut/footer.html",
))
switch r.Method {
case "GET":
db := conn.Connect()
selDB, err := db.Query("SELECT id, name, date, time FROM booking ORDER BY id ASC")
if err != nil {
panic(err.Error())
}
emp := m.Reservasi{}
res := []m.Reservasi{}
for selDB.Next() {
var id int
var name, date, time string
err = selDB.Scan(&id, &name, &date, &time)
if err != nil {
panic(err.Error())
}
emp.Id = id
emp.Name = name
emp.Date = date
emp.Time = time
res = append(res, emp)
}
// fmt.Println(emp.Name)
tmpl.ExecuteTemplate(w, "reservasi", res)
defer db.Close()
case "POST":
fmt.Fprintf(w, "Sorry, only GET methods are supported.")
default:
fmt.Fprintf(w, "Sorry, only GET methods are supported.")
}
}
func Reservasi(w http.ResponseWriter,r *http.Request){
db := conn.Connect()
if r.Method == "POST" {
name := r.FormValue("name")
email := r.FormValue("email")
phone := r.FormValue("phone")
date := r.FormValue("date")
time := r.FormValue("time")
person := r.FormValue("person")
insForm, err := db.Prepare("INSERT INTO booking(name, email, phone, date, time, person) VALUES(?,?,?,?,?,?)")
if err != nil {
panic(err.Error())
}
insForm.Exec(name, email, phone, date, time, person)
log.Println("INSERT: name: " + name + " sukses")
}
defer db.Close()
http.Redirect(w, r, "/reservasi", 301)
} |
func containsDuplicate(nums []int) bool {
m:=make(map[int]int)
for _,v:=range nums{
if _,ok:=m[v];ok{
return true
}
m[v] = 1
}
return false
}
|
package main
import (
"DeanFoleyDev/go-url-shortener/cmd/api"
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
readyCheck := make(chan struct{}, 1)
sigs := make(chan os.Signal, 1)
apiDone := make(chan struct{}, 1)
closedServices := make(chan struct{})
go api.Launch(readyCheck, apiDone, closedServices)
<-readyCheck
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
close(apiDone)
}()
<-closedServices
fmt.Println("Server shut down. Goodbye!")
}
|
package main
import (
"bufio"
"errors"
"fmt"
"os"
homedir "github.com/mitchellh/go-homedir"
)
type FileInfo struct {
name string
namepath string
file *os.File
buf []string
}
func OpenFile(filename string) (*FileInfo, error) {
name, err := homedir.Expand(filename)
if err != nil {
return nil, err
}
file, err := os.Open(name)
if err != nil {
return nil, err
}
defer file.Close()
info, err := os.Stat(name)
if err != nil {
return nil, err
}
if info.IsDir() {
return nil, fmt.Errorf("%s is a directory", name)
}
scanner := bufio.NewScanner(file)
var str []string
for scanner.Scan() {
text := ""
for _, v := range []byte(scanner.Text()) {
if v == byte('\t') {
text += " "
continue
}
text += string(v)
}
str = append(str, text+"\n")
}
if err := scanner.Err(); err != nil {
return nil, errors.New(fmt.Sprintf("scanner err:", err))
}
return &FileInfo{
name: file.Name(),
namepath: name,
file: file,
buf: str,
}, nil
}
func (f *FileInfo) GetLine() int {
return len(f.buf)
}
func (f *FileInfo) GetCol(y int) int {
if len(f.buf[y]) == 1 {
return 0
} else if len(f.buf[y]) == 0 {
return 0
}
return len(f.buf[y]) - 1
}
func (f *FileInfo) GetName() string {
return f.file.Name()
}
|
package qstring
type MIMEType string
const (
Audio MIMEType = "application/vnd.google-apps.audio"
Document MIMEType = "application/vnd.google-apps.document"
Drawing MIMEType = "application/vnd.google-apps.drawing"
File MIMEType = "application/vnd.google-apps.file"
Folder MIMEType = "application/vnd.google-apps.folder"
Form MIMEType = "application/vnd.google-apps.form"
FusionTable MIMEType = "application/vnd.google-apps.fusiontable"
Map MIMEType = "application/vnd.google-apps.map"
Photo MIMEType = "application/vnd.google-apps.photo"
Presentation MIMEType = "application/vnd.google-apps.presentation"
Script MIMEType = "application/vnd.google-apps.script"
Site MIMEType = "application/vnd.google-apps.site"
SpreadSheet MIMEType = "application/vnd.google-apps.spreadsheet"
Unknown MIMEType = "application/vnd.google-apps.unknown"
Video MIMEType = "application/vnd.google-apps.video"
DriveSDK MIMEType = "application/vnd.google-apps.drive-sdk "
)
// MimeTypeBuilder are used to construct queries for matching against mimeTypes.
// As opposed to regular enums, mimeTypes also support the contains operator.
//
// Prefer not using builders directly, instead using the constructors.
type MimeTypeBuilder struct {
builder *EnumBuilder
}
func (b *MimeTypeBuilder) EQ(name MIMEType) *Builder {
return b.builder.EQ(string(name))
}
func (b *MimeTypeBuilder) NE(name MIMEType) *Builder {
return b.builder.NE(string(name))
}
func (b *MimeTypeBuilder) Contains(param MIMEType) *Builder {
b.builder.builder.WriteString(" contains '")
b.builder.builder.WriteString(string(param))
b.builder.builder.WriteString("'")
return &Builder{builder: b.builder.builder}
}
|
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
"time"
)
func getBackupFile(prj Project) (string, error) {
// вариант, когда файл с бэкапом базы уже есть на диске
if len(prj.ExistFile) > 0 {
// извлекаем имя файла из полного пути
arr := strings.Split(prj.ExistFile, "/")
return arr[len(arr)-1], nil
}
// далее вариант создания бэкапа базы из докер контейнера
// формируем название файла с учетом даты создания бэкапа
fileName := fmt.Sprintf("%s_dump_%s.zip", prj.Name, time.Now().Format("2006_01_02"))
// формируем и исполняем команду в bush
cmd := exec.Command("sh", "-c", strings.Join([]string{
"cd " + prj.Path,
fmt.Sprintf("docker exec -t %s pg_dumpall -c -U postgres > %s_dump", prj.DockerPgName, prj.Name),
fmt.Sprintf("zip %s %s_dump", fileName, prj.Name), // архивируем бэкап
fmt.Sprintf("rm %s_dump", prj.Name), // удаляем бэкап
}, ";"))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return "", err
}
// проверяем что в результате выполнения команды в bash на диске появился нужный нам файл
fullPath := fmt.Sprintf("%s/%s", prj.Path, fileName)
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
return "", errors.New(fmt.Sprintf("file %s not created", fullPath))
}
return fileName, nil
}
func removeBackupFile(path string) {
cmd := exec.Command("sh", "-c", strings.Join([]string{
fmt.Sprintf("rm %s", path),
}, ";"))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
fmt.Printf("removeBackupFile err %s\n", err)
}
}
|
func fourSum(nums []int, target int) [][]int {
res := [][]int{}
sort.Ints(nums)
for idxa := 0; idxa < len(nums) - 3; idxa += 1{
va := nums[idxa]
if idxa > 0 && nums[idxa - 1] == va {
continue
}
for idxb := idxa + 1; idxb < len(nums) - 2; idxb += 1{
vb := nums[idxb]
if idxb > idxa + 1 && nums[idxb - 1] == vb {
continue
}
for idxc, idxd := idxb + 1, len(nums) -1; idxc < idxd; {
vc, vd := nums[idxc], nums[idxd]
if idxc > idxb + 1 && nums[idxc - 1] == vc {
idxc += 1
continue
}
s := va + vb + vc + vd
if s == target {
res = append(res, []int{va, vb, vc, vd})
idxd -= 1
idxc += 1
} else if s < target {
idxc += 1
} else {
idxd -= 1
}
}
}
}
return res
}
|
package fcache
import (
"testing"
)
// go test -run=^^$ -bench=^BenchmarkMemCacheSet$ -benchmem
func BenchmarkMemCacheSet(b *testing.B) {
cache := NewMemCache(100, false)
b.ResetTimer()
for i := 0; i < b.N; i++ {
cache.Set("key", []byte("value"))
}
}
// go test -run=^^$ -bench=^BenchmarkMemCacheGet$ -benchmem
func BenchmarkMemCacheGet(b *testing.B) {
cache := NewMemCache(100, false)
cache.Set("key", []byte("value"))
b.ResetTimer()
for i := 0; i < b.N; i++ {
cache.Get("key")
}
}
// go test -run=^^$ -bench=^BenchmarkDiskCacheSet$ -benchmem
func BenchmarkDiskCacheSet(b *testing.B) {
cache := NewDiskCache(100, false, "./cache")
b.ResetTimer()
for i := 0; i < b.N; i++ {
cache.Set("key", []byte("value"))
}
}
// go test -run=^^$ -bench=^BenchmarkDiskCacheGet$ -benchmem
func BenchmarkDiskCacheGet(b *testing.B) {
cache := NewDiskCache(100, false, "./cache")
cache.Set("key", []byte("value"))
b.ResetTimer()
for i := 0; i < b.N; i++ {
cache.Get("key")
}
}
|
//go:generate swagger generate spec
package main
import (
"fmt"
"net/http"
"os"
"github.com/getaceres/payment-demo/frontend"
"github.com/getaceres/payment-demo/persistence/mongo"
"github.com/gorilla/mux"
"github.com/spf13/cobra"
)
func main() {
var port int
var connectionURL string
var cmdServe = &cobra.Command{
Use: "serve",
Short: "Start the API server",
Long: `This will start the server listening in the provided or the default port`,
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
startServer(port, connectionURL)
},
}
cmdServe.Flags().IntVarP(&port, "port", "p", 8080, "Port to serve")
cmdServe.Flags().StringVarP(&connectionURL, "mongourl", "m", "mongodb://localhost:27017", "Connection URL to a MongoDB database")
var rootCmd = &cobra.Command{Use: "payment-demo"}
rootCmd.AddCommand(cmdServe)
rootCmd.Execute()
}
func startServer(port int, connectionURL string) {
router := mux.NewRouter()
repository, err := mongo.NewMongoPaymentRepository(connectionURL, "payment-demo")
if err != nil {
fmt.Printf("Error initializing MongoDB repository: %s", err.Error())
os.Exit(-1)
}
frontend := frontend.FrontendV1{
Router: router,
PaymentRepository: repository,
}
frontend.InitializeRoutes()
err = http.ListenAndServe(fmt.Sprintf(":%d", port), router)
if err != nil {
fmt.Printf("Error initializing service: %s", err.Error())
os.Exit(-1)
}
}
|
package main
import (
"os"
"vm"
)
func main() {
vm := vm.NewVM()
vm.Execute(os.Args[1])
}
|
package datasetapi
import (
"context"
dstypes "github.com/lexis-project/lexis-backend-services-interface-datasets.git/client/data_set_management"
"github.com/lexis-project/lexis-backend-services-api.git/models"
"github.com/lexis-project/lexis-backend-services-api.git/restapi/operations/data_set_management"
"github.com/go-openapi/runtime/middleware"
l "gitlab.com/cyclops-utilities/logging"
)
func (p *DataSetAPI) CreateSSHFSExport(ctx context.Context, params data_set_management.CreateSSHFSExportParams) middleware.Responder { // need to include params here..
rparams := dstypes.CreateSSHFSExportParams{
Parameters: dstypes.CreateSSHFSExportBody{
Host: params.Parameters.Host,
Pubkey: params.Parameters.Pubkey,
Path: params.Parameters.Path,
},
}
res, err := p.getClient(params.HTTPRequest).DataSetManagement.CreateSSHFSExport(ctx, &rparams)
if err != nil {
l.Info.Printf("Error calling CreateSSHFSExport endpoint\n")
switch err.(type) {
case *dstypes.CreateSSHFSExportBadRequest: // 400
v := err.(*dstypes.CreateSSHFSExportBadRequest)
payload := models.ErrorResponse{
ErrorString: v.Payload.ErrorString,
}
return data_set_management.NewCreateSSHFSExportBadRequest().WithPayload(&payload)
case *dstypes.CreateSSHFSExportUnauthorized: // 401
v := err.(*dstypes.CreateSSHFSExportUnauthorized)
payload := models.ErrorResponse{
ErrorString: v.Payload.ErrorString,
}
return data_set_management.NewCreateSSHFSExportUnauthorized().WithPayload(&payload)
case *dstypes.CreateSSHFSExportForbidden: // 403
v := err.(*dstypes.CreateSSHFSExportForbidden)
payload := models.ErrorResponse{
ErrorString: v.Payload.ErrorString,
}
return data_set_management.NewCreateSSHFSExportForbidden().WithPayload(&payload)
case *dstypes.CreateSSHFSExportServiceUnavailable: // 503
v := err.(*dstypes.CreateSSHFSExportServiceUnavailable)
payload := models.ErrorResponse{
ErrorString: v.Payload.ErrorString,
}
return data_set_management.NewCreateSSHFSExportServiceUnavailable().WithPayload(&payload)
default:
payload := fillErrorResponse(err)
return data_set_management.NewCreateSSHFSExportServiceUnavailable().WithPayload(payload)
}
}
ret := data_set_management.CreateSSHFSExportCreatedBody{
User: res.Payload.User,
Sshfs: res.Payload.Sshfs,
}
return data_set_management.NewCreateSSHFSExportCreated().WithPayload(&ret)
}
func (p *DataSetAPI) DeleteSSHFSExport(ctx context.Context, params data_set_management.DeleteSSHFSExportParams) middleware.Responder { // need to include params here..
rparams := dstypes.DeleteSSHFSExportParams{
Parameters: dstypes.DeleteSSHFSExportBody{
User: params.Parameters.User,
Path: params.Parameters.Path,
},
}
_, err := p.getClient(params.HTTPRequest).DataSetManagement.DeleteSSHFSExport(ctx, &rparams)
if err != nil {
l.Info.Printf("Error calling DeleteSSHFSExport endpoint\n")
switch err.(type) {
case *dstypes.DeleteSSHFSExportBadRequest: // 400
v := err.(*dstypes.DeleteSSHFSExportBadRequest)
payload := models.ErrorResponse{
ErrorString: v.Payload.ErrorString,
}
return data_set_management.NewDeleteSSHFSExportBadRequest().WithPayload(&payload)
case *dstypes.DeleteSSHFSExportUnauthorized: // 401
v := err.(*dstypes.DeleteSSHFSExportUnauthorized)
payload := models.ErrorResponse{
ErrorString: v.Payload.ErrorString,
}
return data_set_management.NewDeleteSSHFSExportUnauthorized().WithPayload(&payload)
case *dstypes.DeleteSSHFSExportForbidden: // 403
v := err.(*dstypes.DeleteSSHFSExportForbidden)
payload := models.ErrorResponse{
ErrorString: v.Payload.ErrorString,
}
return data_set_management.NewDeleteSSHFSExportForbidden().WithPayload(&payload)
case *dstypes.DeleteSSHFSExportNotFound: // 404
v := err.(*dstypes.DeleteSSHFSExportNotFound)
payload := models.ErrorResponse{
ErrorString: v.Payload.ErrorString,
}
return data_set_management.NewDeleteSSHFSExportNotFound().WithPayload(&payload)
case *dstypes.DeleteSSHFSExportBadGateway: // 502
v := err.(*dstypes.DeleteSSHFSExportBadGateway)
payload := models.ErrorResponse{
ErrorString: v.Payload.ErrorString,
}
return data_set_management.NewDeleteSSHFSExportBadGateway().WithPayload(&payload)
case *dstypes.DeleteSSHFSExportServiceUnavailable: // 503
v := err.(*dstypes.DeleteSSHFSExportServiceUnavailable)
payload := models.ErrorResponse{
ErrorString: v.Payload.ErrorString,
}
return data_set_management.NewDeleteSSHFSExportServiceUnavailable().WithPayload(&payload)
default:
payload := fillErrorResponse(err)
return data_set_management.NewDeleteSSHFSExportServiceUnavailable().WithPayload(payload)
}
}
return data_set_management.NewDeleteSSHFSExportNoContent()
}
|
package main
import (
"github.com/gorilla/mux"
"net/http"
"encoding/json"
"log"
)
type UserInfo struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/api/query/{name}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
//這邊就把 name 帶入 UserInfo
u := &UserInfo{
Name: vars["name"],
Age: 18,
}
b, err := json.Marshal(u)
if err != nil {
log.Println(err)
return
}
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
w.WriteHeader(http.StatusOK)
w.Write(b)
})
//聽8000 port
log.Fatal(http.ListenAndServe(":8900", r))
}
|
package canvas
import (
"fmt"
"strings"
"testing"
"github.com/calbim/ray-tracer/src/color"
)
func TestCanvas(t *testing.T) {
c := New(10, 20)
if c.width != 10 || c.height != 20 {
t.Errorf("Canvas width and height should be 10 and 20 respectively")
}
for i := 0; i < c.height; i++ {
for j := 0; j < c.width; j++ {
pixelColor := c.Pixels[i][j]
if !pixelColor.Equals(color.Black) {
t.Errorf("wanted pixel color to be %v, got %v", color.Black, pixelColor)
}
}
}
}
func TestWriteToCanvas(t *testing.T) {
c := New(10, 20)
r := color.New(1, 0, 0)
c.WritePixel(2, 3, r)
col := c.Pixels[3][2]
if !col.Equals(r) {
t.Errorf("wanted color at (3,2)= %v, got %v", r, col)
}
}
func TestCanvastoPPM(t *testing.T) {
c := New(5, 3)
c1 := color.New(1.5, 0, 0)
c2 := color.New(0, 0.5, 0)
c3 := color.New(-0.5, 0, 1)
c.WritePixel(0, 0, c1)
c.WritePixel(2, 1, c2)
c.WritePixel(4, 2, c3)
ppm := c.ToPPM()
ppmSplit := strings.Split(ppm, "\n")
if ppmSplit[0] != "P3" {
t.Errorf("First line of ppm header should be P3")
}
if ppmSplit[1] != "5 3" {
t.Errorf("Second line of ppm header should be 5 3")
}
if ppmSplit[2] != "255" {
t.Errorf("Third line of ppm header should be 255")
}
fmt.Println(ppmSplit[3])
if strings.Trim(ppmSplit[3], " ") != "255 0 0 0 0 0 0 0 0 0 0 0 0 0 0" {
t.Errorf("Line 1: Incorect PPM conversion")
}
if strings.Trim(ppmSplit[4], " ") != "0 0 0 0 0 0 0 128 0 0 0 0 0 0 0" {
t.Errorf("Line 2: Incorect PPM conversion")
}
if strings.Trim(ppmSplit[5], " ") != "0 0 0 0 0 0 0 0 0 0 0 0 0 0 255" {
t.Errorf("Line 3: Incorect PPM conversion")
}
}
|
package main
import (
l4g "base/log4go"
"net/http"
)
type HttpRequestInfo struct {
action string
req *http.Request
closeChan chan bool
}
func NewHttpRequestInfo(action string, req *http.Request, c chan bool) *HttpRequestInfo {
return &HttpRequestInfo{
action: action,
req: req,
closeChan: c,
}
}
type HttpHandlerPool struct {
pool_id int
}
func NewHttpHandlerPool(i int) *HttpHandlerPool {
return &HttpHandlerPool{
pool_id: i,
}
}
func (this *HttpHandlerPool) Process() {
for {
l4g.Debug("HttpHandlerPool processs %d", this.pool_id)
select {
case request := <-g_handler_chan:
g_HttpCommandM.Dispatcher(request.action, request.req, this)
request.closeChan <- true
}
}
l4g.Debug("HttpHandlerPool processs %d finish", this.pool_id)
}
|
package marshall
import (
"fmt"
"testing"
)
func TestLoad(t *testing.T) {
var json_string string = `{
"basics": {
"name": "John Doe",
"label": "Programmer",
"image": "",
"email": "john@gmail.com",
"phone": "(912) 555-4321",
"url": "https://johndoe.com",
"summary": "A summary of John Doe…",
"location": {
"address": "2712 Broadway St",
"postalCode": "CA 94115",
"city": "San Francisco",
"countryCode": "US",
"region": "California"
},
"profiles": [{
"network": "Twitter",
"username": "john",
"url": "https://twitter.com/john"
},
{
"network": "Reddit",
"username": "john",
"url": "https://reddit.com/john"
}]
}
}`
var input []byte = []byte(json_string)
fmt.Println(len(input))
var resume Resume = LoadJsonFile("../../resume.json") //(input)
// var resume Resume = LoadJsonString(input)
// t.Log(resume)
t.Log(resume)
}
|
package models_test
import (
"crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
"io"
"github.com/cloudfoundry-incubator/cloud-service-broker/db_service/models"
"github.com/cloudfoundry-incubator/cloud-service-broker/db_service/models/fakes"
"github.com/cloudfoundry-incubator/cloud-service-broker/internal/encryption/gcmencryptor"
"github.com/cloudfoundry-incubator/cloud-service-broker/internal/encryption/noopencryptor"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func newKey() [32]byte {
dbKey := make([]byte, 32)
io.ReadFull(rand.Reader, dbKey)
return sha256.Sum256(dbKey)
}
var _ = Describe("Db", func() {
var encryptor models.Encryptor
AfterEach(func() {
models.SetEncryptor(nil)
})
Describe("ServiceBindingCredentials", func() {
Context("GCM encryptor", func() {
BeforeEach(func() {
key := newKey()
encryptor = gcmencryptor.New(key)
models.SetEncryptor(encryptor)
})
Describe("SetOtherDetails", func() {
It("encrypts the field", func() {
const expectedJSON = `{"some":["json","blob","here"]}`
otherDetails := map[string]interface{}{
"some": []interface{}{"json", "blob", "here"},
}
credentials := models.ServiceBindingCredentials{}
err := credentials.SetOtherDetails(otherDetails)
Expect(err).ToNot(HaveOccurred())
By("checking that it's no longer in plaintext")
Expect(credentials.OtherDetails).ToNot(Equal(expectedJSON))
By("being able to decrypt to get the value")
decrypted, err := encryptor.Decrypt(credentials.OtherDetails)
Expect(err).ToNot(HaveOccurred())
Expect(string(decrypted)).To(Equal(expectedJSON))
})
})
Describe("GetOtherDetails", func() {
It("can decrypt what it had previously encrypted", func() {
By("encrypting a field")
otherDetails := map[string]interface{}{
"some": []interface{}{"json", "blob", "here"},
}
credentials := models.ServiceBindingCredentials{}
credentials.SetOtherDetails(otherDetails)
By("checking that it's encrypted")
Expect(credentials.OtherDetails).ToNot(ContainSubstring("some"))
By("decrypting that field")
var actualOtherDetails map[string]interface{}
err := credentials.GetOtherDetails(&actualOtherDetails)
Expect(err).ToNot(HaveOccurred())
Expect(actualOtherDetails).To(HaveLen(1))
Expect(actualOtherDetails).To(HaveKeyWithValue("some", ConsistOf("json", "blob", "here")))
})
})
})
Context("Noop encryptor", func() {
BeforeEach(func() {
encryptor = noopencryptor.New()
models.SetEncryptor(encryptor)
})
Describe("SetOtherDetails", func() {
It("marshalls json content", func() {
otherDetails := map[string]interface{}{
"some": []interface{}{"json", "blob", "here"},
}
credentials := models.ServiceBindingCredentials{}
err := credentials.SetOtherDetails(otherDetails)
Expect(err).ToNot(HaveOccurred())
Expect(credentials.OtherDetails).To(Equal(`{"some":["json","blob","here"]}`))
})
It("marshalls nil into json null", func() {
credentials := models.ServiceBindingCredentials{}
err := credentials.SetOtherDetails(nil)
Expect(err).ToNot(HaveOccurred())
Expect(credentials.OtherDetails).To(Equal("null"))
})
It("returns an error if it cannot marshall", func() {
credentials := models.ServiceBindingCredentials{}
err := credentials.SetOtherDetails(struct {
F func()
}{F: func() {}})
Expect(err).To(MatchError(ContainSubstring("unsupported type")))
Expect(credentials.OtherDetails).To(BeEmpty())
})
})
Describe("GetOtherDetails", func() {
It("unmarshalls json content", func() {
serviceBindingCredentials := models.ServiceBindingCredentials{
OtherDetails: `{"some":["json","blob","here"]}`,
}
var actualOtherDetails map[string]interface{}
err := serviceBindingCredentials.GetOtherDetails(&actualOtherDetails)
Expect(err).ToNot(HaveOccurred())
Expect(actualOtherDetails).To(HaveLen(1))
Expect(actualOtherDetails).To(HaveKeyWithValue("some", ConsistOf("json", "blob", "here")))
})
It("returns nil if is empty", func() {
serviceBindingCredentials := models.ServiceBindingCredentials{}
var actualOtherDetails map[string]interface{}
err := serviceBindingCredentials.GetOtherDetails(&actualOtherDetails)
Expect(err).ToNot(HaveOccurred())
Expect(actualOtherDetails).To(BeNil())
})
It("returns an error if unmarshalling fails", func() {
serviceBindingCredentials := models.ServiceBindingCredentials{
OtherDetails: `{"some":"badjson","here"]}`,
}
var actualOtherDetails map[string]interface{}
err := serviceBindingCredentials.GetOtherDetails(&actualOtherDetails)
Expect(err).To(MatchError(ContainSubstring("invalid character")))
Expect(actualOtherDetails).To(BeNil())
})
})
})
Describe("errors", func() {
Describe("SetOtherDetails", func() {
BeforeEach(func() {
fakeEncryptor := &fakes.FakeEncryptor{}
fakeEncryptor.EncryptReturns("", errors.New("fake encrypt error"))
encryptor = fakeEncryptor
models.SetEncryptor(encryptor)
})
It("returns the error", func() {
credentials := models.ServiceBindingCredentials{}
err := credentials.SetOtherDetails("foo")
Expect(err).To(MatchError("fake encrypt error"))
})
})
Describe("GetOtherDetails", func() {
BeforeEach(func() {
fakeEncryptor := &fakes.FakeEncryptor{}
fakeEncryptor.DecryptReturns(nil, errors.New("fake decrypt error"))
encryptor = fakeEncryptor
models.SetEncryptor(encryptor)
})
It("return the error", func() {
serviceBindingCredentials := models.ServiceBindingCredentials{
OtherDetails: "fake stuff",
}
var receiver interface{}
err := serviceBindingCredentials.GetOtherDetails(&receiver)
Expect(err).To(MatchError("fake decrypt error"))
})
})
})
})
Describe("ServiceInstanceDetails", func() {
Context("GCM encryptor", func() {
BeforeEach(func() {
key := newKey()
encryptor = gcmencryptor.New(key)
models.SetEncryptor(encryptor)
})
Describe("SetOtherDetails", func() {
It("marshalls json content", func() {
otherDetails := map[string]interface{}{
"some": []interface{}{"json", "blob", "here"},
}
details := models.ServiceInstanceDetails{}
err := details.SetOtherDetails(otherDetails)
Expect(err).ToNot(HaveOccurred())
decryptedDetails, err := encryptor.Decrypt(details.OtherDetails)
Expect(err).ToNot(HaveOccurred())
Expect(string(decryptedDetails)).To(Equal(`{"some":["json","blob","here"]}`))
})
It("marshalls nil into json null", func() {
details := models.ServiceInstanceDetails{}
err := details.SetOtherDetails(nil)
Expect(err).ToNot(HaveOccurred())
decryptedDetails, err := encryptor.Decrypt(details.OtherDetails)
Expect(err).ToNot(HaveOccurred())
Expect(string(decryptedDetails)).To(Equal("null"))
})
})
Describe("GetOtherDetails", func() {
It("decrypts and unmarshalls json content", func() {
encryptedDetails, _ := encryptor.Encrypt([]byte(`{"some":["json","blob","here"]}`))
serviceInstanceDetails := models.ServiceInstanceDetails{
OtherDetails: string(encryptedDetails),
}
var actualOtherDetails map[string]interface{}
err := serviceInstanceDetails.GetOtherDetails(&actualOtherDetails)
Expect(err).ToNot(HaveOccurred())
var arrayOfInterface []interface{}
arrayOfInterface = append(arrayOfInterface, "json", "blob", "here")
expectedOtherDetails := map[string]interface{}{
"some": arrayOfInterface,
}
Expect(actualOtherDetails).To(Equal(expectedOtherDetails))
})
It("returns nil if is empty", func() {
serviceInstanceDetails := models.ServiceInstanceDetails{}
var actualOtherDetails map[string]interface{}
err := serviceInstanceDetails.GetOtherDetails(&actualOtherDetails)
Expect(err).ToNot(HaveOccurred())
Expect(actualOtherDetails).To(BeNil())
})
})
It("Can decrypt what it had previously encrypted", func() {
serviceInstanceDetails := models.ServiceInstanceDetails{}
input := map[string]interface{}{
"some": []string{"json", "blob", "here"},
}
serviceInstanceDetails.SetOtherDetails(input)
var actualOtherDetails map[string]interface{}
err := serviceInstanceDetails.GetOtherDetails(&actualOtherDetails)
Expect(err).ToNot(HaveOccurred())
var arrayOfInterface []interface{}
arrayOfInterface = append(arrayOfInterface, "json", "blob", "here")
expectedOtherDetails := map[string]interface{}{
"some": arrayOfInterface,
}
Expect(actualOtherDetails).To(Equal(expectedOtherDetails))
})
})
Context("Noop encryptor", func() {
BeforeEach(func() {
encryptor = noopencryptor.New()
models.SetEncryptor(encryptor)
})
Describe("SetOtherDetails", func() {
It("marshalls json content", func() {
otherDetails := map[string]interface{}{
"some": []interface{}{"json", "blob", "here"},
}
details := models.ServiceInstanceDetails{}
err := details.SetOtherDetails(otherDetails)
Expect(err).ToNot(HaveOccurred())
Expect(details.OtherDetails).To(Equal(`{"some":["json","blob","here"]}`))
})
It("marshalls nil into json null", func() {
details := models.ServiceInstanceDetails{}
err := details.SetOtherDetails(nil)
Expect(err).ToNot(HaveOccurred())
Expect(details.OtherDetails).To(Equal("null"))
})
})
Describe("GetOtherDetails", func() {
It("unmarshalls json content", func() {
serviceInstanceDetails := models.ServiceInstanceDetails{
OtherDetails: `{"some":["json","blob","here"]}`,
}
var actualOtherDetails map[string]interface{}
err := serviceInstanceDetails.GetOtherDetails(&actualOtherDetails)
Expect(err).ToNot(HaveOccurred())
var arrayOfInterface []interface{}
arrayOfInterface = append(arrayOfInterface, "json", "blob", "here")
expectedOtherDetails := map[string]interface{}{
"some": arrayOfInterface,
}
Expect(actualOtherDetails).To(Equal(expectedOtherDetails))
})
It("returns nil if is empty", func() {
serviceInstanceDetails := models.ServiceInstanceDetails{}
var actualOtherDetails map[string]interface{}
err := serviceInstanceDetails.GetOtherDetails(&actualOtherDetails)
Expect(err).ToNot(HaveOccurred())
Expect(actualOtherDetails).To(BeNil())
})
})
})
Describe("errors", func() {
Describe("SetOtherDetails", func() {
It("returns an error if it cannot marshall", func() {
details := models.ServiceInstanceDetails{}
err := details.SetOtherDetails(struct {
F func()
}{F: func() {}})
Expect(err).To(HaveOccurred(), "Should have returned an error")
Expect(details.OtherDetails).To(BeEmpty())
})
Context("When there are errors while encrypting", func() {
BeforeEach(func() {
fakeEncryptor := &fakes.FakeEncryptor{}
fakeEncryptor.EncryptReturns("", errors.New("some error"))
encryptor = fakeEncryptor
models.SetEncryptor(encryptor)
})
It("returns an error", func() {
details := models.ServiceInstanceDetails{}
var someDetails []byte
err := details.SetOtherDetails(someDetails)
Expect(err).To(MatchError("some error"))
})
})
})
Describe("GetOtherDetails", func() {
Context("When there are errors while unmarshalling", func() {
BeforeEach(func() {
fakeEncryptor := &fakes.FakeEncryptor{}
fakeEncryptor.DecryptReturns([]byte(`{"some":"badjson", "here"]}`), nil)
encryptor = fakeEncryptor
models.SetEncryptor(encryptor)
})
It("returns an error", func() {
serviceInstanceDetails := models.ServiceInstanceDetails{
OtherDetails: "something not nil",
}
var actualOtherDetails map[string]interface{}
err := serviceInstanceDetails.GetOtherDetails(&actualOtherDetails)
Expect(err).To(MatchError(ContainSubstring("invalid character")))
Expect(actualOtherDetails).To(BeNil())
})
})
Context("When there are errors while decrypting", func() {
BeforeEach(func() {
fakeEncryptor := &fakes.FakeEncryptor{}
fakeEncryptor.DecryptReturns(nil, errors.New("some error"))
encryptor = fakeEncryptor
models.SetEncryptor(encryptor)
})
It("returns an error", func() {
details := models.ServiceInstanceDetails{
OtherDetails: "something not nil",
}
var actualOtherDetails map[string]interface{}
err := details.GetOtherDetails(&actualOtherDetails)
Expect(err).To(MatchError("some error"))
})
})
})
})
})
Describe("ProvisionRequestDetails", func() {
Context("GCM encryptor", func() {
BeforeEach(func() {
key := newKey()
encryptor = gcmencryptor.New(key)
models.SetEncryptor(encryptor)
})
Describe("SetRequestDetails", func() {
It("encrypts and sets the details", func() {
details := models.ProvisionRequestDetails{}
rawMessage := []byte(`{"key":"value"}`)
details.SetRequestDetails(rawMessage)
decryptedDetails, err := encryptor.Decrypt(details.RequestDetails)
Expect(err).ToNot(HaveOccurred())
Expect(string(decryptedDetails)).To(Equal(`{"key":"value"}`))
})
It("converts nil to the empty string", func() {
details := models.ProvisionRequestDetails{}
details.SetRequestDetails(nil)
decryptedDetails, err := encryptor.Decrypt(details.RequestDetails)
Expect(err).ToNot(HaveOccurred())
Expect(decryptedDetails).To(BeEmpty())
})
It("converts empty array to the empty string", func() {
details := models.ProvisionRequestDetails{}
var rawMessage []byte
details.SetRequestDetails(rawMessage)
decryptedDetails, err := encryptor.Decrypt(details.RequestDetails)
Expect(err).ToNot(HaveOccurred())
Expect(decryptedDetails).To(BeEmpty())
})
})
Describe("GetRequestDetails", func() {
It("gets as RawMessage", func() {
encryptedDetails, _ := encryptor.Encrypt([]byte(`{"some":["json","blob","here"]}`))
requestDetails := models.ProvisionRequestDetails{
RequestDetails: string(encryptedDetails),
}
details, err := requestDetails.GetRequestDetails()
rawMessage := json.RawMessage(`{"some":["json","blob","here"]}`)
Expect(err).ToNot(HaveOccurred())
Expect(details).To(Equal(rawMessage))
})
})
It("Can decrypt what it had previously encrypted", func() {
details := models.ProvisionRequestDetails{}
rawMessage := json.RawMessage(`{"key":"value"}`)
details.SetRequestDetails(rawMessage)
actualDetails, err := details.GetRequestDetails()
Expect(err).ToNot(HaveOccurred())
Expect(actualDetails).To(Equal(rawMessage))
})
})
Context("Noop encryptor", func() {
BeforeEach(func() {
encryptor = noopencryptor.New()
models.SetEncryptor(encryptor)
})
Describe("SetRequestDetails", func() {
It("sets the details", func() {
details := models.ProvisionRequestDetails{}
rawMessage := []byte(`{"key":"value"}`)
details.SetRequestDetails(rawMessage)
Expect(details.RequestDetails).To(Equal("{\"key\":\"value\"}"))
})
It("converts nil to the empty string", func() {
details := models.ProvisionRequestDetails{}
details.SetRequestDetails(nil)
Expect(details.RequestDetails).To(BeEmpty())
})
It("converts empty array to the empty string", func() {
details := models.ProvisionRequestDetails{}
var rawMessage []byte
details.SetRequestDetails(rawMessage)
Expect(details.RequestDetails).To(BeEmpty())
})
})
Describe("GetRequestDetails", func() {
It("gets as RawMessage", func() {
requestDetails := models.ProvisionRequestDetails{
RequestDetails: `{"some":["json","blob","here"]}`,
}
details, err := requestDetails.GetRequestDetails()
rawMessage := json.RawMessage(`{"some":["json","blob","here"]}`)
Expect(err).ToNot(HaveOccurred())
Expect(details).To(Equal(rawMessage))
})
})
})
Describe("errors", func() {
Context("SetRequestDetails", func() {
BeforeEach(func() {
fakeEncryptor := &fakes.FakeEncryptor{}
fakeEncryptor.EncryptReturns("", errors.New("some error"))
encryptor = fakeEncryptor
models.SetEncryptor(encryptor)
})
It("returns an error when there are errors while encrypting", func() {
details := models.ProvisionRequestDetails{}
var rawMessage []byte
err := details.SetRequestDetails(rawMessage)
Expect(err).To(MatchError("some error"))
})
})
Context("GetRequestDetails", func() {
BeforeEach(func() {
fakeEncryptor := &fakes.FakeEncryptor{}
fakeEncryptor.DecryptReturns(nil, errors.New("some error"))
encryptor = fakeEncryptor
models.SetEncryptor(encryptor)
})
It("returns an error when there are errors while decrypting", func() {
requestDetails := models.ProvisionRequestDetails{
RequestDetails: "some string",
}
details, err := requestDetails.GetRequestDetails()
Expect(err).To(MatchError("some error"))
Expect(details).To(BeNil())
})
})
})
})
Describe("TerraformDeployment", func() {
const plaintext = "plaintext"
Context("GCM encryptor", func() {
BeforeEach(func() {
key := newKey()
encryptor = gcmencryptor.New(key)
models.SetEncryptor(encryptor)
})
Describe("SetWorkspace", func() {
It("encrypts the workspace", func() {
By("making sure it's no longer in plaintext")
var t models.TerraformDeployment
err := t.SetWorkspace(plaintext)
Expect(err).NotTo(HaveOccurred())
Expect(t.Workspace).NotTo(Equal(plaintext))
By("being able to decrypt it")
p, err := encryptor.Decrypt(t.Workspace)
Expect(err).NotTo(HaveOccurred())
Expect(p).To(Equal([]byte(plaintext)))
})
})
Describe("GetWorkspace", func() {
var t models.TerraformDeployment
BeforeEach(func() {
err := t.SetWorkspace(plaintext)
Expect(err).NotTo(HaveOccurred())
})
It("can read a previously encrypted workspace", func() {
By("checking that it's not in plaintext")
Expect(t.Workspace).NotTo(Equal(plaintext))
By("reading the plaintext")
p, err := t.GetWorkspace()
Expect(err).NotTo(HaveOccurred())
Expect(p).To(Equal(plaintext))
})
})
})
Context("Noop encryptor", func() {
BeforeEach(func() {
encryptor = noopencryptor.New()
models.SetEncryptor(encryptor)
})
Describe("SetWorkspace", func() {
It("sets the workspace in plaintext", func() {
var t models.TerraformDeployment
err := t.SetWorkspace(plaintext)
Expect(err).NotTo(HaveOccurred())
Expect(t.Workspace).To(Equal(plaintext))
})
})
Describe("GetWorkspace", func() {
It("reads the plaintext workspace", func() {
t := models.TerraformDeployment{Workspace: plaintext}
v, err := t.GetWorkspace()
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(plaintext))
})
})
})
Describe("errors", func() {
Describe("SetWorkspace", func() {
BeforeEach(func() {
fakeEncryptor := &fakes.FakeEncryptor{}
fakeEncryptor.EncryptReturns("", errors.New("fake encryption error"))
encryptor = fakeEncryptor
models.SetEncryptor(encryptor)
})
It("returns encryption errors", func() {
var t models.TerraformDeployment
err := t.SetWorkspace(plaintext)
Expect(err).To(MatchError("fake encryption error"))
})
})
Describe("GetWorkspace", func() {
BeforeEach(func() {
fakeEncryptor := &fakes.FakeEncryptor{}
fakeEncryptor.DecryptReturns(nil, errors.New("fake decryption error"))
encryptor = fakeEncryptor
models.SetEncryptor(encryptor)
})
It("returns decryption errors", func() {
t := models.TerraformDeployment{Workspace: plaintext}
v, err := t.GetWorkspace()
Expect(err).To(MatchError("fake decryption error"))
Expect(v).To(BeEmpty())
})
})
})
})
})
|
package tesla
/// POST Get Access Token
// Auth is an authorization structure for the Tesla API.
var AuthURL = "/oauth/token"
type RefreshAuthToken struct {
GrantType string `json:"grant_type"`
RefreshToken string `json:"refresh_token"`
ClientID string `json:"client_id"`
Scope string `json:"scope"`
}
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
CreatedAt int `json:"created_at"`
}
var ListVehiclesURL = "/api/1/vehicles"
// Vehicle is a structure that describes a single Tesla vehicle.
type Vehicle struct {
ID int `json:"id"`
VehicleID int `json:"vehicle_id"`
Vin string `json:"vin"`
DisplayName string `json:"display_name"`
OptionCodes string `json:"option_codes"`
Color interface{} `json:"color"`
Tokens []string `json:"tokens"`
State string `json:"state"`
InService bool `json:"in_service"`
IDS string `json:"id_s"`
CalendarEnabled bool `json:"calendar_enabled"`
BackseatToken interface{} `json:"backseat_token"`
BackseatTokenUpdatedAt interface{} `json:"backseat_token_updated_at"`
}
// Vehicles encapsulates a collection of Tesla Vehicles.
type Vehicles []struct {
*Vehicle
}
// VehiclesResponse is the response to a vehicles API query.
type VehiclesResponse struct {
Response Vehicles `json:"response"`
Count int `json:"count"`
}
// Mobile Enabled
var MobileEnabledURL = "/api/1/vehicles/%d/mobile_enabled"
type MobileEnabledResponse struct {
Response bool `json:"response"`
}
// Charge State
var ChargStateURL = "/api/1/vehicles/%d/data_request/charge_state"
// ChargeState is the actual charge_state data
type ChargeState struct {
BatteryHeaterOn bool `json:"battery_heater_on"`
BatteryLevel int `json:"battery_level"`
BatteryRange float64 `json:"battery_range"`
ChargeCurrentRequest int `json:"charge_current_request"`
ChargeCurrentRequestMax int `json:"charge_current_request_max"`
ChargeEnableRequest bool `json:"charge_enable_request"`
ChargeLimitSoc int `json:"charge_limit_soc"`
ChargeLimitSocMax int `json:"charge_limit_soc_max"`
ChargeLimitSocMin int `json:"charge_limit_soc_min"`
ChargeLimitSocStd int `json:"charge_limit_soc_std"`
ChargeMilesAddedIdeal float64 `json:"charge_miles_added_ideal"`
ChargeMilesAddedRated float64 `json:"charge_miles_added_rated"`
ChargePortColdWeatherMode bool `json:"charge_port_cold_weather_mode"`
ChargePortDoorOpen bool `json:"charge_port_door_open"`
ChargePortLatch string `json:"charge_port_latch"` // "Engaged", "Disengaged"
ChargeRate float64 `json:"charge_rate"`
ChargeToMaxRange bool `json:"charge_to_max_range"`
ChargerActualCurrent int `json:"charge_actual_current"`
ChargerPhases int `json:"charge_phases"` // 1?
ChargerPilotCurrent int `json:"charger_pilot_current"`
ChargerPower int `json:"charger_power"`
ChargerVoltage int `json:"charger_voltage"`
ChargingState string `json:"charging_state"` // "Stopped", "Starting", "Charging", "Disconnected"
ConnChargeCable string `json:"conn_charge_cable"`
EstBatteryRange float64 `json:"est_battery_range"`
FastChargerBrand string `json:"fast_charger_brand"`
FastChargerPresent bool `json:"fast_charger_present"`
FastChargerType string `json:"fast_charger_type"`
IdealBatteryRange float64 `json:"ideal_battery_range"`
ManagedChargingActive bool `json:"managed_charging_active"`
ManagedChargingStartTime interface{} `json:"managed_charging_start_time"`
ManagedChargingUserCancelled bool `json:"managed_charging_user_cancelled"`
MaxRangeChargeCounter int `json:"max_range_charge_counter"`
NotEnoughPowerToHeat bool `json:"not_enough_power_to_heat"`
ScheduledChargingPending bool `json:"scheduled_charging_pending"`
ScheduledChargingStartTime int `json:"scheduled_charging_start_time"` // seconds
TimeToFullCharge float64 `json:"time_to_full_charge"` // in hours
TimeStamp int `json:"timestamp"` // ms
TripCharging bool `json:"trip_charging"`
UsableBatteryLevel int `json:"usable_battery_level"`
UserChargeEnableRequest bool `json:"user_charge_enable_request"`
}
type ChargeStateResponse struct {
Response ChargeState
}
// ClimateState returns the state of the climate control
type ClimateState struct {
BatteryHeater bool `json:"battery_heater"`
BatteryHeaterNoPower bool `json:"battery_heater_no_power"`
DriverTempSetting float64 `json:"driver_temp_setting"`
FanStatus int `json:"fan_status"`
InsideTemp float64 `json:"inside_temp"`
IsAutoConditioningOn bool `json:"is_auto_conditioning_on"`
IsClimateOn bool `json:"is_climate_on"`
IsFrontDefrosterOn bool `json:"is_front_defroster_on"`
IsPreconditioning bool `json:"is_preconditioning"`
IsRearDefrosterOn bool `json:"is_rear_defroster_on"`
LeftTempDirection int `json:"left_temp_direction"`
MaxAvailTemp float64 `json:"max_avail_temp"`
MinAvailTemp float64 `json:"min_avail_temp"`
OutsideTemp float64 `json:"outside_temp"`
PassengerTempSetting float64 `json:"passenger_temp_setting"`
RemoteHeaterControlEnabled bool `json:"remote_heater_control_enabled"`
RightTempDirection int `json:"right_temp_direction"`
SeatHeaterLeft int `json:"seat_heater_left"`
SeatHeaterRearCenter int `json:"seat_heater_rear_center"`
SeatHeaterRearLeft int `json:"seat_heater_rear_left"`
SeatHeaterRearLeftBack int `json:"seat_heater_rear_left_back"`
SeatHeaterRearRight int `json:"seat_heater_rear_right"`
SeatHeaterRearRightBack int `json:"seat_heater_rear_right_back"`
SeatHeaterRight int `json:"seat_heater_right"`
SideMirrorHeaters bool `json:"side_mirror_heaters"`
SmartPreconditioning bool `json:"smart_preconditioning"`
SteeringWheelHeater bool `json:"steering_wheel_heater"`
TimeStamp int `json:"timestamp"` // ms
WiperBladeHeater bool `json:"wiper_blade_heater"`
}
var ClimateStateURL = "/api/1/vehicles/%d/data_request/climate_state"
type ClimateStateResponse struct {
Response ClimateState
}
// DriveState is the result of the drive_state call, and includes information
// about vehicle position and speed
type DriveState struct {
GpsAsOf int `json:"gps_as_of"`
Heading int `json:"heading"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
NativeLatitude float64 `json:"native_latitude"`
NativeLocationSupported int `json:"native_location_supported"`
NativeLongitude float64 `json:"native_longitude"`
NativeType string `json:"native_type"`
Power int `json:"power"`
ShiftState interface{} `json:"shift_state"`
Speed interface{} `json:"speed"`
TimeStamp int `json:"timestamp"` // ms
}
var DriveStateURL = "/api/1/vehicles/%d/data_request/drive_state"
// DriveStateResponse encapsulates a DriveState object.
type DriveStateResponse struct {
Response DriveState
}
// GuiSettings return a number of settings regarding the GUI on the CID
type GuiSettings struct {
Gui24HourTime bool `json:"gui_24_hour_time"`
GuiChargeRateUnits string `json:"gui_charge_rate_units"`
GuiDistanceUnits string `json:"gui_distance_units"`
GuiRangeDisplay string `json:"gui_range_display"`
GuiTemperatureUnits string `json:"gui_temperature_units"`
TimeStamp int `json:"timestamp"` // ms
}
var GuiStateURL = "/api/1/vehicles/%d/data_request/gui_settings"
// GuiSettingsResponse encapsulates a GuiSettings object
type GuiSettingsResponse struct {
Response GuiSettings
}
// A VehicleStateMediaState returns the state of media control
type VehicleStateMediaState struct {
RemoteControlEnabled bool `json:"remote_control_enabled"`
}
// A VehicleStateSoftwareUpdate returns information on pending software updates
type VehicleStateSoftwareUpdate struct {
ExpectedDurationSec int `json:"expected_duration_sec"`
Status string `json:"status"`
}
// A VehicleStateSpeedLimitMode returns the speed limiting parameters
type VehicleStateSpeedLimitMode struct {
Active bool `json:"active"`
CurrentLimitMph float64 `json:"current_limit_mph"`
MaxLimitMph float64 `json:"max_limit_mph"`
MinLimitMph float64 `json:"min_limit_mph"`
PinCodeSet bool `json:"pin_code_set"`
}
// VehicleState is the return value from a vehicle_state call
type VehicleState struct {
APIVersion int `json:"api_version"`
AutoparkStateV2 string `json:"autopark_state_v2"`
AutoparkStyle string `json:"autopark_style"`
CalendarSupported bool `json:"calendar_supported"`
CarVersion string `json:"car_version"`
CenterDisplayState int `json:"center_display_state"`
Df int `json:"df"`
Dr int `json:"dr"`
Ft int `json:"ft"`
HomelinkNearby bool `json:"homelink_nearby"`
IsUserPresent bool `json:"is_user_present"`
LastAutoparkError string `json:"last_autopark_error"`
Locked bool `json:"locked"`
MediaState VehicleStateMediaState `json:"media_state"`
NotificationsSupported bool `json:"notifications_supported"`
Odometer float64 `json:"odometer"`
ParsedCalendarSupported bool `json:"parsed_calendar_supported"`
Pf int `json:"pf"`
Pr int `json:"pr"`
RemoteStart bool `json:"remote_start"`
RemoteStartSupported bool `json:"remote_start_started"`
Rt int `json:"rt"`
SoftwareUpdate VehicleStateSoftwareUpdate `json:"software_update"`
SpeedLimitMode VehicleStateSpeedLimitMode `json:"speed_limit_mode"`
SunRoofPercentOpen int `json:"sun_roof_percent_open"`
SunRoofState string `json:"sun_roof_state"`
TimeStamp int `json:"timestamp"` // ms
ValetMode bool `json:"valet_mode"`
ValetPinNeeded bool `json:"valet_pin_needed"`
VehicleName string `json:"vehicle_name"`
}
var VehicleStateURL = "/api/1/vehicles/%d/data_request/vehicle_state"
// VehicleStateResponse encapsulates a VehicleState object
type VehicleStateResponse struct {
Response VehicleState
}
// VehicleConfig is the return data from a vehicle_config call
type VehicleConfig struct {
CanAcceptNavigationRequests bool `json:"can_accept_navigation_requests"`
CanActuateTrunks bool `json:"can_actuate_trunks"`
CarSpecialType string `json:"car_special_type"` // "base"
CarType string `json:"car_type"` // "models"
ChargePortType string `json:"charge_port_type"`
EuVehicle bool `json:"eu_vehicle"`
ExteriorColor string `json:"exterior_color"`
HasAirSuspension bool `json:"has_air_suspension"`
HasLudicrousMode bool `json:"has_ludicrous_mode"`
MotorizedChargePort bool `json:"motorized_charge_port"`
PerfConfig string `json:"perf_config"`
Plg bool `json:"plg"`
RearSeatHeaters int `json:"rear_seat_heaters"`
RearSeatType int `json:"rear_seat_type"`
Rhd bool `json:"rhd"`
RoofColor string `json:"roof_color"` // "Colored"
SeatType int `json:"seat_type"`
SpoilerType string `json:"spoiler_type"`
SunRoofInstalled int `json:"sun_roof_installed"`
ThirdRowSeats string `json:"third_row_seats"`
TimeStamp int `json:"timestamp"` // ms
TrimBadging string `json:"trim_badging"`
WheelType string `json:"wheel_type"`
}
var VehicleConfigURL = "/api/1/vehicles/%d/data_request/vehicle_config"
// VehicleConfigResponse encapsulates a VehicleConfig
type VehicleConfigResponse struct {
Response VehicleConfig
}
// VehicleData is the actual data structure for a vehicle_data call
type VehicleData struct {
Vehicle
UserID int `json:"user_id"`
Ds DriveState `json:"drive_state"`
Cls ClimateState `json:"climate_state"`
Chs ChargeState `json:"charge_state"`
Gs GuiSettings `json:"gui_settings"`
Vs VehicleState `json:"vehicle_state"`
Vc VehicleConfig `json:"vehicle_config"`
}
var VehicleDataURL = "/api/1/vehicles/%d/vehicle_data"
// VehicleDataResponse is the return from a vehicle_data call
type VehicleDataResponse struct {
Response VehicleData
}
|
package controllers
import (
"net/http"
"github.com/gorilla/mux"
"github.com/wbreza/go-store/api/models"
"github.com/wbreza/go-store/api/services"
)
// ProductController exposes actions on the products API
type ProductController struct {
Controller
productManager services.ProductManager
router mux.Router
}
// NewProductController creates a new instance of a product controller
func NewProductController(router *mux.Router) *ProductController {
controller := ProductController{
productManager: *services.NewProductManager(),
router: *router,
}
router.HandleFunc("/products", controller.GetList).Methods(http.MethodGet)
router.HandleFunc("/products", controller.Create).Methods(http.MethodPost)
router.HandleFunc("/products/{productId}", controller.GetByID).Methods(http.MethodGet)
router.HandleFunc("/products/{productId}", controller.Update).Methods(http.MethodPut)
router.HandleFunc("/products/{productId}", controller.DeleteByID).Methods(http.MethodDelete)
return &controller
}
func (controller *ProductController) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
controller.GetList(writer, request)
}
// GetList gets a list of products
func (controller *ProductController) GetList(writer http.ResponseWriter, request *http.Request) {
products, err := controller.productManager.GetList()
if err != nil {
writer.WriteHeader(500)
}
controller.WriteJSON(writer, products)
}
// GetByID gets a product with the specified id
func (controller *ProductController) GetByID(writer http.ResponseWriter, request *http.Request) {
productID, err := controller.GetRequestParamAsInt(request, "productId")
if err != nil {
writer.WriteHeader(400)
return
}
product, err := controller.productManager.Get(productID)
if err != nil {
writer.WriteHeader(500)
return
}
if product == nil {
writer.WriteHeader(404)
return
}
controller.WriteJSON(writer, product)
}
// Create saves a new product to the data store
func (controller *ProductController) Create(writer http.ResponseWriter, request *http.Request) {
product := models.Product{}
err := controller.ParseJSONBody(request, &product)
if err != nil {
writer.WriteHeader(400)
return
}
updatedProduct, err := controller.productManager.Save(&product)
if err != nil {
writer.WriteHeader(500)
return
}
writer.WriteHeader(201)
controller.WriteJSON(writer, updatedProduct)
}
// Update updates a current product with the matching id
func (controller *ProductController) Update(writer http.ResponseWriter, request *http.Request) {
productID, err := controller.GetRequestParamAsInt(request, "productId")
if err != nil {
writer.WriteHeader(400)
return
}
product := models.Product{}
err = controller.ParseJSONBody(request, &product)
if err != nil {
writer.WriteHeader(400)
return
}
product.ID = productID
if err != nil {
writer.WriteHeader(400)
return
}
controller.productManager.Save(&product)
}
// DeleteByID removes the product with the specified id
func (controller *ProductController) DeleteByID(writer http.ResponseWriter, request *http.Request) {
productID, err := controller.GetRequestParamAsInt(request, "productId")
if err != nil {
writer.WriteHeader(400)
return
}
isDeleted, err := controller.productManager.Delete(productID)
if err != nil {
writer.WriteHeader(500)
return
}
if isDeleted {
writer.WriteHeader(204)
} else {
writer.WriteHeader(404)
}
}
|
package prservice
import (
"net/http"
"io/ioutil"
"sync"
"time"
fm "github.com/cyg2009/MyTestCode/pkg/functionmanager"
)
func makeOKResponse(w http.ResponseWriter, body string){
//w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}
func makeFailedResponse(w http.ResponseWriter, statusCode int, message string) {
// bodyContent := slscommon.NewErrorMessage(statusCode, message).ToJsonString()
//w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
w.Write([]byte(message))
}
//This will receive a function package tar file and store it
func ServeHTTPAddFunction(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
makeFailedResponse(w, http.StatusInternalServerError, "Please POST this request.")
return
}
functionId := req.Header.Get("function")
if len(functionId) == 0 {
makeFailedResponse(w, http.StatusBadRequest, "No function specified.")
return
}
data, err := ioutil.ReadAll(req.Body)
if err != nil {
makeFailedResponse(w, http.StatusInternalServerError, err.Error())
return
}
_, err = fm.GetFunctionManager().CreateFunction(functionId, data, "", nil)
if err != nil {
makeFailedResponse(w, http.StatusInternalServerError, err.Error())
return
}
body := "Add " + functionId + " successully!"
makeOKResponse(w, body)
}
func ServeHTTPInvoke(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
makeFailedResponse(w, http.StatusInternalServerError, "Please POST this request.")
return
}
functionId := req.Header.Get("function")
if len(functionId) == 0 {
makeFailedResponse(w, http.StatusBadRequest, "No function specified.")
return
}
evt, err := ioutil.ReadAll(req.Body)
if err != nil {
makeFailedResponse(w, http.StatusInternalServerError, err.Error())
return
}
//to simplify it , we treat the data as an js file index.js . TBD to replace it with a tar fil
// hack to return immediately
//makeOKResponse(w, "Function " + functionId + " invoked successfully:" + string(evt[:]))
//return
if _, ok := fm.GetFunctionManager().GetFunction(functionId); ok == false {
makeFailedResponse(w, http.StatusBadRequest, "Function " + functionId + " not exists!")
return
}
respData, _ := fm.GetFunctionManager().ExecuteFunction(functionId, evt)
makeOKResponse(w, respData)
}
func ServeHTTPConfig(w http.ResponseWriter, req *http.Request) {
makeOKResponse(w, "TBD:Configuration")
}
func ServeHTTPRemove(w http.ResponseWriter, req *http.Request) {
functionId := ""
if req.Method == "POST" {
functionId = req.Header.Get("function")
}
if req.Method == "GET" {
functionId = req.URL.Query().Get("function")
}
if len(functionId) == 0 {
makeFailedResponse(w, http.StatusBadRequest, "No function specified.")
return
}
if ok := fm.GetFunctionManager().RemoveFunction(functionId); ok == false {
makeFailedResponse(w, http.StatusBadRequest, "Fail to remove " + functionId)
return
}
makeOKResponse(w, functionId + " removed.")
}
func ServeHTTPInfo(w http.ResponseWriter, req *http.Request) {
info := fm.GetFunctionManager().GetAllFunctionsJSON()
makeOKResponse(w, info)
}
func ServeHTTPHealthCheck(w http.ResponseWriter, req *http.Request) {
t := time.Now()
body := "OK " + t.Format("20060102150405")
makeOKResponse(w, body)
}
// Singleton
var instance *http.ServeMux
var once sync.Once
func GetPrserviceHttpHandler() (*http.ServeMux) {
once.Do( func() {
instance = http.NewServeMux()
instance.HandleFunc("/health", ServeHTTPHealthCheck)
instance.HandleFunc("/config", ServeHTTPConfig)
instance.HandleFunc("/info", ServeHTTPInfo)
instance.HandleFunc("/invoke", ServeHTTPInvoke)
instance.HandleFunc("/add", ServeHTTPAddFunction)
instance.HandleFunc("/remove", ServeHTTPRemove)
})
return instance
}
|
/*
Copyright [2015] Alex Davies-Moore
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package geom
//
// func TestMultiLineString_GeoJSON(t *testing.T) {
// expected := &MultiLineString{
// Hdr{
// dim: XYZ,
// srid: 27700,
// gtype: MULTILINESTRING,
// },
// []LineString{
// LineString{
// Hdr{
// dim: XYZ,
// srid: 27700,
// gtype: LINESTRING,
// },
// []Coordinate{
// []float64{100.0, 0.0},
// []float64{101.0, 1.0},
// },
// },
// LineString{
// Hdr{
// dim: XYZ,
// srid: 27700,
// gtype: LINESTRING,
// },
// []Coordinate{
// []float64{102.0, 2.0},
// []float64{103.0, 3.0},
// },
// },
// },
// }
//
// geojson := expected.GeoJSON(true, true)
//
// t.Logf("%s\n", geojson)
// }
//
// func TestMultiPolygon_GeoJSON(t *testing.T) {
// expected := &MultiPolygon{
// Hdr{
// dim: XYZ,
// srid: 27700,
// gtype: MULTIPOLYGON,
// },
// []Polygon{
// Polygon{
// Hdr{
// dim: XYZ,
// srid: 27700,
// gtype: POLYGON,
// },
// []LinearRing{
// LinearRing{
// []Coordinate{
// []float64{100.0, 0.0},
// []float64{101.0, 0.0},
// []float64{101.0, 1.0},
// []float64{100.0, 1.0},
// []float64{100.0, 0.0},
// },
// },
// },
// },
// Polygon{
// Hdr{
// dim: XYZ,
// srid: 27700,
// gtype: POLYGON,
// },
// []LinearRing{
// LinearRing{
// []Coordinate{
// []float64{100.0, 0.0},
// []float64{101.0, 0.0},
// []float64{101.0, 1.0},
// []float64{100.0, 1.0},
// []float64{100.0, 0.0},
// },
// },
// LinearRing{
// []Coordinate{
// []float64{100.2, 0.2},
// []float64{100.8, 0.2},
// []float64{100.8, 0.8},
// []float64{100.2, 0.8},
// []float64{100.2, 0.2},
// },
// },
// },
// },
// },
// }
//
// geojson := expected.GeoJSON(true, true)
//
// t.Logf("%s\n", geojson)
// }
//
// func TestGeometryCollection_GeoJSON(t *testing.T) {
// expected := &GeometryCollection{
// Hdr{
// dim: XYZ,
// srid: 27700,
// gtype: LINESTRING,
// },
// []Geometry{
// &Point{
// Hdr{
// dim: XYZ,
// srid: 27700,
// gtype: POINT,
// },
// []float64{100.0, 0.0},
// },
// &LineString{
// Hdr{
// dim: XYZ,
// srid: 27700,
// gtype: LINESTRING,
// },
// []Coordinate{
// []float64{100.0, 0.0},
// []float64{101.0, 1.0},
// },
// },
// },
// }
//
// geojson := expected.GeoJSON(true, true)
//
// t.Logf("%s\n", geojson)
// }
|
package concurrent
type Func func()
type FuncMayError func() error
type FuncWithResult func() (result interface{})
type FuncWithResultMayError func() (result interface{}, err error)
|
// package main
//
// import (
// "fmt"
// "os"
// )
//
// func main() {
// // ファイルを開く
// file, err := os.Open("test.txt")
// // エラー判定
// if err != nil {
// // 失敗
// fmt.Println(err.Error())
// } else {
// // 成功
// fmt.Println("Successful!")
// file.Close()
// }
// }
// package main
//
// import (
// "fmt"
// "os"
// )
//
// type myAppError struct {
// msg string //エラーメッセージ
// }
//
// func (e myAppError) Error() string {
// // エラーメッセージを返す
// return e.msg
// }
//
// func testOpen() (file os.File, err error) {
// file, err := os.Open("test.txt")
// if err != nil {
// // エラーが発生したので、myAppError構造体の値を作成し、エラー情報として返す
// return nil, myAppError{"ファイルが開けません - " + err.Error()}
// }
// // 成功した場合は、error情報をnilとして返す。
// return file, nil
// }
//
// func main() {
// file, err := testOpen()
// if err != nil {
// // エラー情報が戻ってきたので、エラーとして処理する。
// fmt.Println("失敗しました。 - " + err.Error())
// os.Exit(1)
// }
// // 後略
// }
// package main
//
// func func1() {
// panic("Occured panic!")
// }
//
// func main() {
// func1()
// }
// package main
//
// import "fmt"
//
// func func1() {
// defer func() {
// fmt.Println("defer 2")
// }()
// panic("Occured panic!")
// }
//
// func main() {
// defer func() {
// fmt.Println("defer 1")
// }()
// func1()
// }
// package main
//
// func main() {
// arr := [...]int{1, 2, 3}
//
// index := 3
//
// arr[index] = 0
// }
// package main
//
// import "fmt"
//
// func func1(b bool) {
// defer func() {
// fmt.Println("defer start.")
//
// if err := recover(); err != nil {
// // パニック中だった
// fmt.Println("recovery!")
// }
// fmt.Println("defer end.")
// }()
// if b {
// panic("Occure panic!")
// }
// }
//
// func main() {
// func1(false)
// func1(true)
// }
// package main
//
// import (
// "fmt"
// "time"
// )
//
// func main() {
// fmt.Println("main start.")
//
// fmt.Println("普通に関数を呼び出す")
// serialno()
//
// fmt.Println("ゴルーチンとして呼び出す")
// go serialno()
//
// // ゴルーチン呼び出し後、sleepする
// time.Sleep(1 * time.Second)
//
// fmt.Println("main end.")
// }
//
// func serialno() {
// for i := 0; i < 5; i++ {
// fmt.Println(i)
// // 1秒間sleepする
// time.Sleep(1 * time.Second)
// }
// }
// package main
//
// import (
// "fmt"
// )
//
// func main() {
// // int型チャネルの作成
// c := make(chan int)
//
// // 送信専用チャネルを受け取り、1〜10までの数値を送信する
// go func(s chan<- int) {
// for i := 0; i < 10; i++ {
// s <- i
// }
// close(s)
// }(c)
//
// for {
// // チャネルからの受信を待機
// val, ok := <-c
// if !ok {
// // チャネルがクローズしたので、終了する
// break
// }
// // 受信したデータを表示
// fmt.Println(val)
// }
// }
// package main
//
// import (
// "fmt"
// "time"
// )
//
// func main() {
// // キャパシティ0で、int型チャネルの作成
// c := make(chan int)
//
// // 負荷のかかる作業(5秒待機)を3回繰り返した後、通知する
// go func(s chan<- int) {
// for i := 0; i < 3; i++ {
// time.Sleep(5 * time.Second)
// fmt.Println(i+1, "回完了")
// }
// // 適当な数値を送信
// s <- 0
// }(c)
//
// // 受信を待機
// <-c
//
// fmt.Println("終了")
// }
package main
import (
"fmt"
)
// 全ゴルーチン数
const goroutines = 5
func main() {
// 共有データを保持するチャネル
counter := make(chan int)
// 全ゴルーチン終了通知用のチャネル
end := make(chan bool)
// 5個のゴルーチンを実行する
for i := 0; i < goroutines; i++ {
// 共有データ(counter)を受信し、インクリメントする
go func(counter chan int) {
// チャネルから共有データの受信
val := <-counter
// +1する
val++
fmt.Println("counter = ", val)
if val == goroutines {
// 最後のゴルーチンの場合は、終了通知用のチャネルへ送信
end <- true
}
// +1したデータを、他のゴルーチンへ送信
counter <- val
}(counter)
}
// 初期値をチャネルに送信
counter <- 0
// 全ゴルーチンの終了を待機
<-end
fmt.Println("終了")
}
|
package models
import (
"crypto/rand"
"encoding/base64"
"strings"
)
const numRandomBytes = 32
func GenerateRandomString() (string, error) {
b, err := GenerateRandomBytes(numRandomBytes)
if err != nil {
return "", err
}
return EncodeBase64WithoutPadding(b), nil
}
func GenerateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return nil, err
}
return b, nil
}
func EncodeBase64WithoutPadding(input []byte) string {
encoded := base64.URLEncoding.EncodeToString(input)
parts := strings.Split(encoded, "=")
encoded = parts[0]
return encoded
}
|
package kvraft
import (
"crypto/rand"
"math/big"
"time"
"../labrpc"
"../raft"
)
var timeoutClientIntervals = []time.Duration{time.Duration(1 * time.Second), time.Duration(2 * time.Second), time.Duration(4 * time.Second)}
type Clerk struct {
servers []*labrpc.ClientEnd
// You will have to modify this struct.
lastLeaderServer int
id int64
operationNumber int
}
func nrand() int64 {
max := big.NewInt(int64(1) << 62)
bigx, _ := rand.Int(rand.Reader, max)
x := bigx.Int64()
return x
}
func MakeClerk(servers []*labrpc.ClientEnd) *Clerk {
ck := new(Clerk)
ck.servers = servers
ck.lastLeaderServer = -1
ck.id = nrand()
ck.operationNumber = 0
// You'll have to add code here.
return ck
}
func (ck *Clerk) getInitialServer() int {
var initialServer int
if ck.lastLeaderServer == -1 {
initialServer = 0
} else {
initialServer = ck.lastLeaderServer
}
return initialServer
}
//
// fetch the current value for a key.
// returns "" if the key does not exist.
// keeps trying forever in the face of all other errors.
//
// you can send an RPC with code like this:
// ok := ck.servers[i].Call("KVServer.Get", &args, &reply)
//
// the types of args and reply (including whether they are pointers)
// must match the declared types of the RPC handler function's
// arguments. and reply must be passed as a pointer.
//
func (ck *Clerk) Get(key string) string {
ck.operationNumber += 1
args := &GetArgs{}
args.ClientId = ck.id
args.ClientOperationNumber = ck.operationNumber
args.Key = key
responseCh := make(chan *GetReply)
initialServer := ck.getInitialServer()
for attemptNumber := 0; ; attemptNumber++ {
for i := initialServer; i < initialServer+len(ck.servers); i++ {
go func(i int) {
reply := &GetReply{}
ck.servers[i%len(ck.servers)].Call("KVServer.Get", args, reply)
responseCh <- reply
}(i)
select {
case <-time.After(timeoutClientIntervals[raft.Min(attemptNumber, len(timeoutClientIntervals)-1)]):
//DPrintf("timing out Get request to %d", i)
continue
case reply := <-responseCh:
if reply.Err == OK || reply.Err == ErrNoKey {
ck.lastLeaderServer = i % len(ck.servers)
//DPrintf("%d: Get %s with %s:%s", ck.lastLeaderServer, reply.Err, key, reply.Value)
return reply.Value
} else {
continue
}
}
}
time.Sleep(time.Duration(100 * time.Millisecond))
}
}
//
// shared by Put and Append.
//
// you can send an RPC with code like this:
// ok := ck.servers[i].Call("KVServer.PutAppend", &args, &reply)
//
// the types of args and reply (including whether they are pointers)
// must match the declared types of the RPC handler function's
// arguments. and reply must be passed as a pointer.
//
func (ck *Clerk) PutAppend(key string, value string, op string) {
ck.operationNumber += 1
args := &PutAppendArgs{}
args.ClientId = ck.id
args.ClientOperationNumber = ck.operationNumber
args.Key = key
args.Value = value
args.Op = op
initialServer := ck.getInitialServer()
responseCh := make(chan *PutAppendReply)
for attemptNumber := 0; ; attemptNumber++ {
for i := initialServer; i < initialServer+len(ck.servers); i++ {
go func(i int) {
reply := &PutAppendReply{}
//DPrintf("Sending request from client to server %d", i)
ck.servers[i%len(ck.servers)].Call("KVServer.PutAppend", args, reply)
responseCh <- reply
}(i)
select {
case <-time.After(timeoutClientIntervals[raft.Min(attemptNumber, len(timeoutClientIntervals)-1)]):
//DPrintf("timing out PutAppend request to %d", i)
continue
case reply := <-responseCh:
//DPrintf("client reply from %d: %v", i, reply)
if reply.Err == OK {
ck.lastLeaderServer = i % len(ck.servers)
//DPrintf("%d: %s success with %s:%s", ck.lastLeaderServer, op, key, value)
return
} else {
continue
}
}
}
time.Sleep(time.Duration(100 * time.Millisecond))
}
}
func (ck *Clerk) Put(key string, value string) {
ck.PutAppend(key, value, "Put")
}
func (ck *Clerk) Append(key string, value string) {
ck.PutAppend(key, value, "Append")
}
|
/*
* Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the under the Apache License, Version 2.0 (the "License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package httpclient
import (
"fmt"
"io"
"net/http"
"strings"
)
//go:generate counterfeiter . AuthenticatedClient
type AuthenticatedClient interface {
DoAuthenticatedGet(url string, accessToken string) (io.ReadCloser, int, error)
DoAuthenticatedDelete(url string, accessToken string) (int, error)
DoAuthenticatedPost(url string, bodyType string, body string, accessToken string) (io.ReadCloser, int, error)
DoAuthenticatedPut(url string, bodyType string, bodyStr string, accessToken string) (int, error)
}
type authenticatedClient struct {
httpClient Client
}
func NewAuthenticatedClient(httpClient Client) *authenticatedClient {
return &authenticatedClient{httpClient: httpClient}
}
func (c *authenticatedClient) DoAuthenticatedGet(url string, accessToken string) (io.ReadCloser, int, error) {
statusCode := 0
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, statusCode, fmt.Errorf("Request creation error: %s", err)
}
req.Header.Add("Accept", "application/json")
addAuthorizationHeader(req, accessToken)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, 0, fmt.Errorf("Authenticated get of '%s' failed: %s", url, err)
}
if resp.StatusCode != http.StatusOK {
return nil, resp.StatusCode, fmt.Errorf("Authenticated get of '%s' failed: %s", url, resp.Status)
}
return resp.Body, resp.StatusCode, nil
}
func (c *authenticatedClient) DoAuthenticatedDelete(url string, accessToken string) (int, error) {
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return 0, fmt.Errorf("Request creation error: %s", err)
}
req.Header.Add("Accept", "application/json")
addAuthorizationHeader(req, accessToken)
resp, err := c.httpClient.Do(req)
if err != nil {
return 0, fmt.Errorf("Authenticated delete of '%s' failed: %s", url, err)
}
if resp.StatusCode != http.StatusOK {
return resp.StatusCode, fmt.Errorf("Authenticated delete of '%s' failed: %s", url, resp.Status)
}
return resp.StatusCode, nil
}
func (c *authenticatedClient) DoAuthenticatedPost(url string, bodyType string, bodyStr string, accessToken string) (io.ReadCloser, int, error) {
body := strings.NewReader(bodyStr)
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, 0, fmt.Errorf("Request creation error: %s", err)
}
addAuthorizationHeader(req, accessToken)
req.Header.Set("Content-Type", bodyType)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, 0, fmt.Errorf("Authenticated post to '%s' failed: %s", url, err)
}
if resp.StatusCode != http.StatusOK {
return resp.Body, resp.StatusCode, fmt.Errorf("Authenticated post to '%s' failed: %s", url, resp.Status)
}
return resp.Body, resp.StatusCode, nil
}
func (c *authenticatedClient) DoAuthenticatedPut(url string, bodyType string, bodyStr string, accessToken string) (int, error) {
body := strings.NewReader(bodyStr)
req, err := http.NewRequest("PUT", url, body)
if err != nil {
return 0, fmt.Errorf("Request creation error: %s", err)
}
addAuthorizationHeader(req, accessToken)
if bodyStr != "" {
req.Header.Set("Content-Type", bodyType)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return 0, fmt.Errorf("Authenticated put of '%s' failed: %s", url, err)
}
if resp.StatusCode != http.StatusOK {
return resp.StatusCode, fmt.Errorf("Authenticated put of '%s' failed: %s", url, resp.Status)
}
return resp.StatusCode, nil
}
func addAuthorizationHeader(req *http.Request, accessToken string) {
req.Header.Add("Authorization", fmt.Sprintf("bearer %s", accessToken))
}
|
/*
Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cloudify
import (
rest "github.com/cloudify-incubator/cloudify-rest-go-client/cloudify/rest"
utils "github.com/cloudify-incubator/cloudify-rest-go-client/cloudify/utils"
)
// NodeWithGroup - full information about cloudify node
type NodeWithGroup struct {
Node
ScalingGroupName string `json:"scaling_group"`
GroupName string `json:"group"`
}
// NodeWithGroups - response from manager with nodes list
type NodeWithGroups struct {
rest.BaseMessage
Metadata rest.Metadata `json:"metadata"`
Items []NodeWithGroup `json:"items"`
}
// SelfUpdateGroups - go by nodes and update group if we have some additional info from parent
func (nwg *NodeWithGroups) SelfUpdateGroups() {
for childInd, child := range nwg.Items {
if child.HostID != child.ID {
// skip filled
if child.GroupName != "" &&
child.ScalingGroupName != "" {
continue
}
// go by childs
for _, host := range nwg.Items {
if child.HostID == host.ID &&
child.DeploymentID == host.DeploymentID {
if child.GroupName == "" {
nwg.Items[childInd].GroupName = host.GroupName
}
if child.ScalingGroupName == "" {
nwg.Items[childInd].ScalingGroupName = host.ScalingGroupName
}
}
}
}
}
}
// GetNodesFull - return nodes filtered by params
func (cl *Client) GetNodesFull(params map[string]string) (*NodeWithGroups, error) {
var nodeWithGroups NodeWithGroups
deploymentParams := map[string]string{}
nodes, err := cl.GetNodes(params)
if err != nil {
return nil, err
}
if value, ok := params["deployment_id"]; ok == true {
deploymentParams["id"] = value
}
deployments, err := cl.GetDeployments(deploymentParams)
if err != nil {
return nil, err
}
infoNodes := []NodeWithGroup{}
for _, node := range nodes.Items {
// copy original properties
fullInfo := NodeWithGroup{}
fullInfo.Node = node
fullInfo.ScalingGroupName = ""
fullInfo.GroupName = ""
// update scaling group by deployments
for _, deployment := range deployments.Items {
if deployment.ID == node.DeploymentID {
for scaleGroupName, scaleGroup := range deployment.ScalingGroups {
if utils.InList(scaleGroup.Members, node.ID) {
fullInfo.ScalingGroupName = scaleGroupName
}
}
for groupName, group := range deployment.Groups {
if utils.InList(group.Members, node.ID) {
fullInfo.GroupName = groupName
}
}
}
}
infoNodes = append(infoNodes, fullInfo)
}
// We only repack values from Nodes to new struct without total/offset changes
nodeWithGroups.Items = infoNodes
nodeWithGroups.Metadata = nodes.Metadata
// update child
nodeWithGroups.SelfUpdateGroups()
return &nodeWithGroups, nil
}
// GetStartedNodesWithType - return nodes specified type with more than zero instances
func (cl *Client) GetStartedNodesWithType(params map[string]string, nodeType string) (*Nodes, error) {
cloudNodes, err := cl.GetNodes(params)
if err != nil {
return nil, err
}
nodes := []Node{}
for _, node := range cloudNodes.Items {
if !utils.InList(node.TypeHierarchy, nodeType) ||
node.NumberOfInstances <= 0 {
continue
}
// add node to list
nodes = append(nodes, node)
}
return cl.listNodeToNodes(nodes), nil
}
|
package lambda
import (
"github.com/projecteru2/cli/cmd/utils"
"github.com/projecteru2/core/strategy"
"github.com/urfave/cli/v2"
)
// Command exports lambda subommands
func Command() *cli.Command {
return &cli.Command{
Name: "lambda",
Usage: "run commands in a workload like local",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Usage: "name for this lambda",
},
&cli.StringFlag{
Name: "network",
Usage: "SDN name",
},
&cli.StringFlag{
Name: "pod",
Usage: "where to run",
},
&cli.StringSliceFlag{
Name: "env",
Usage: "set env can use multiple times, e.g., GO111MODULE=on",
},
&cli.StringSliceFlag{
Name: "volume-request",
Usage: "set volume request can use multiple times",
},
&cli.StringSliceFlag{
Name: "volume",
Usage: "set volume limitcan use multiple times",
},
&cli.StringFlag{
Name: "working-dir",
Aliases: []string{"working_dir"},
Usage: "use as current working dir",
Value: "/",
},
&cli.StringFlag{
Name: "image",
Usage: "base image for running",
Value: "alpine:latest",
},
&cli.Float64Flag{
Name: "cpu-request",
Usage: "how many cpu request",
Value: 0,
},
&cli.Float64Flag{
Name: "cpu",
Usage: "how many cpu limit",
Value: 1.0,
},
&cli.StringFlag{
Name: "memory-request",
Usage: "memory request, support K, M, G, T",
Value: "",
},
&cli.StringFlag{
Name: "memory",
Usage: "memory limit, support K, M, G, T",
Value: "512M",
},
&cli.StringFlag{
Name: "storage-request",
Usage: "how many storage to request quota like 1M or 1G, support K, M, G, T",
Value: "",
},
&cli.StringFlag{
Name: "storage",
Usage: "how many storage to limit quota like 1M or 1G, support K, M, G, T",
Value: "",
},
&cli.IntFlag{
Name: "count",
Usage: "how many workloads",
Value: 1,
},
&cli.BoolFlag{
Name: "stdin",
Usage: "open stdin for workload",
Aliases: []string{"s"},
Value: false,
},
&cli.StringFlag{
Name: "deploy-strategy",
Usage: "deploy method auto/fill/each",
Value: strategy.Auto,
},
&cli.StringFlag{
Name: "user",
Usage: "which user",
Value: "root",
},
&cli.StringSliceFlag{
Name: "file",
Usage: "copy local file to workload, can use multiple times. src_path:dst_path",
},
&cli.BoolFlag{
Name: "async",
Usage: "run lambda async",
},
&cli.IntFlag{
Name: "async-timeout",
Usage: "for async timeout",
Value: 30,
},
&cli.BoolFlag{
Name: "privileged",
Usage: "give extended privileges to this lambda",
Aliases: []string{"p"},
Value: false,
},
&cli.StringSliceFlag{
Name: "node",
Usage: "which node to run",
},
&cli.BoolFlag{
Name: "workload-id",
Usage: "whether print workload id as prefix or not",
},
},
Action: utils.ExitCoder(cmdLambdaRun),
}
}
|
package client
import (
"github.com/maxence-charriere/go-app/v7/pkg/app"
)
// Menu ...
func Menu(home string) app.UI {
return app.Div().Body(
app.A().Href("/").Text(home),
app.A().Href("/foo").Text("Foo!"),
app.A().Href("/youtube").Text("Youtube!"),
app.A().Href("/spotify").Text("Spotify!"),
)
}
// MenuAsCompo ...
type MenuAsCompo struct {
Home string
advice string
value string
app.Compo
}
// OnMount ...
func (h *MenuAsCompo) OnMount(ctx app.Context) {
advice, _ := FetchAdvice("https://api.adviceslip.com/advice")
h.advice = advice
h.Update()
}
// Render ...
func (h *MenuAsCompo) Render() app.UI {
return app.Div().Body(
app.A().Href("/").Text(h.Home),
app.A().Href("/foo").Text("Foo!"),
app.Input().
Value(h.value).
OnKeyup(func(ctx app.Context, e app.Event) {
h.value = ctx.JSSrc.Get("value").String()
h.Update()
}),
app.P().Text(h.advice+" - "+h.value),
)
}
|
/*****************************************************************
* Copyright©,2020-2022, email: 279197148@qq.com
* Version: 1.0.0
* @Author: yangtxiang
* @Date: 2020-09-01 17:08
* Description:
*****************************************************************/
package pdlQrySvc
type TResData struct {
Status int `json:"status"`
Msg string `json:"msg"`
Content interface{} `json:"content,omitempty"`
}
func MakeResData(status int, msg string, data interface{}) *TResData {
return &TResData{
Status: status,
Msg: msg,
Content: data,
}
}
|
package vastflow
import (
"errors"
"github.com/jack0liu/logs"
"github.com/satori/go.uuid"
"reflect"
"sync"
)
type errorBasin struct {
err error
}
type Headwaters struct {
// global context
RequestId string
ReqInfo interface{} // request info from andes
atlantic AtlanticStream
// basin context
basinMu *sync.Mutex
basinDone chan struct{} // must comes from basin
basinErr *errorBasin
// river context
id string
mu sync.RWMutex // protects following fields
context map[string]interface{} // water's context
done chan struct{}
err error // set to non-nil by the first cancel call
// tmp context , not persist
tmpMu sync.RWMutex
tmpContext map[string]interface{}
}
// closedChan is a reusable closed channel.
var closedChan = make(chan struct{})
func init() {
close(closedChan)
}
func NewHeadwaters(requestId string) *Headwaters {
if len(requestId) == 0 {
logs.Error("new headwaters fail, requestId is empty")
return nil
}
return &Headwaters{
RequestId: requestId,
basinMu: &sync.Mutex{},
basinDone: make(chan struct{}),
basinErr: &errorBasin{},
context: make(map[string]interface{}, 0),
tmpContext: make(map[string]interface{}, 0),
done: make(chan struct{}),
}
}
func (hw *Headwaters) Put(key string, val interface{}) {
hw.mu.Lock()
defer hw.mu.Unlock()
if hw.context == nil {
hw.context = make(map[string]interface{}, 0)
}
hw.context[key] = val
}
func (hw *Headwaters) Del(key string) {
hw.mu.Lock()
defer hw.mu.Unlock()
if hw.context == nil {
return
}
delete(hw.context, key)
}
func (hw *Headwaters) Replace(other *Headwaters) {
hw.mu.Lock()
defer hw.mu.Unlock()
hw.context = other.context
}
func (hw *Headwaters) Get(key string) interface{} {
hw.mu.RLock()
defer hw.mu.RUnlock()
if hw.context == nil {
logs.Error("context is nil")
return nil
}
return hw.context[key]
}
func (hw *Headwaters) GetInt(key string) int {
hw.mu.RLock()
defer hw.mu.RUnlock()
if hw.context == nil {
logs.Error("context is nil")
return -1
}
v := hw.context[key]
switch v.(type) {
case int:
return v.(int)
case float64:
return int(v.(float64))
default:
logs.Warn("[%s]'s value[%v] is not int, is %v", key, v, reflect.TypeOf(v))
}
return -1
}
func (hw *Headwaters) GetString(key string) string {
hw.mu.RLock()
defer hw.mu.RUnlock()
if hw.context == nil {
logs.Error("context is nil")
return ""
}
v := hw.context[key]
if v == nil {
return ""
}
if vs, ok := v.(string); ok {
return vs
}
logs.Debug("[%s]'s value[%v] is not string, is %v", key, v, reflect.TypeOf(v))
return ""
}
func (hw *Headwaters) GetAll() map[string]interface{} {
hw.mu.RLock()
defer hw.mu.RUnlock()
if hw.context == nil {
return nil
}
return hw.context
}
func (hw *Headwaters) Cancel(err error) {
hw.mu.Lock()
defer hw.mu.Unlock()
if hw.err != nil {
return // already canceled
}
hw.err = err
if hw.done == nil {
hw.done = closedChan
} else {
close(hw.done)
}
}
func (hw *Headwaters) Done() <-chan struct{} {
hw.mu.RLock()
defer hw.mu.RUnlock()
if hw.err != nil {
hw.done = closedChan
}
if hw.done == nil {
hw.done = make(chan struct{})
}
d := hw.done
return d
}
func (hw *Headwaters) Err() error {
hw.mu.RLock()
defer hw.mu.RUnlock()
err := hw.err
return err
}
func (hw *Headwaters) copy4Basin() *Headwaters {
newContext := make(map[string]interface{}, 0)
newTmpContext := make(map[string]interface{}, 0)
hw.mu.RLock()
defer hw.mu.RUnlock()
logs.Debug("copy4Basin")
for k, v := range hw.context {
newContext[k] = v
}
for k, v := range hw.tmpContext {
newTmpContext[k] = v
}
newHeadwaters := &Headwaters{
RequestId: hw.RequestId,
ReqInfo: hw.ReqInfo,
atlantic: hw.atlantic,
basinMu: hw.basinMu,
basinDone: hw.basinDone,
basinErr: hw.basinErr,
// something new
id: uuid.NewV4().String(),
context: newContext,
done: make(chan struct{}),
tmpContext: newTmpContext,
}
return newHeadwaters
}
func (hw *Headwaters) TmpPut(key string, value string) {
hw.tmpMu.Lock()
defer hw.tmpMu.Unlock()
if hw.tmpContext == nil {
hw.tmpContext = make(map[string]interface{}, 0)
}
hw.tmpContext[key] = value
}
func (hw *Headwaters) TmpGet(key string) string {
hw.tmpMu.RLock()
defer hw.tmpMu.RUnlock()
if hw.tmpContext == nil {
logs.Info("tmpContext is nil")
return ""
}
v := hw.tmpContext[key]
if vs, ok := v.(string); ok {
return vs
}
logs.Debug("[%s]'s value[%v] is not string", key, v)
return ""
}
func (hw *Headwaters) basinFinish() <-chan struct{} {
hw.basinMu.Lock()
defer hw.basinMu.Unlock()
if hw.basinDone == nil {
logs.Info("basinDone is nil")
hw.basinDone = closedChan
}
d := hw.basinDone
return d
}
func (hw *Headwaters) basinCancel(err error) {
hw.basinMu.Lock()
defer hw.basinMu.Unlock()
if hw.basinErr == nil {
logs.Error("basinErr is nil") // headwaters is created incorrectly
return
}
if hw.basinErr.err != nil {
return // already canceled
}
hw.basinErr.err = err
if hw.basinDone == nil {
hw.basinDone = closedChan
} else {
close(hw.basinDone)
}
}
func (hw *Headwaters) basinError() error {
hw.basinMu.Lock()
defer hw.basinMu.Unlock()
if hw.basinErr == nil {
logs.Error("basinErr is nil") // headwaters is created incorrectly
return errors.New("headwaters is created incorrectly, basinErr is nil")
}
err := hw.basinErr.err
return err
}
|
package commands
import (
// HOFSTADTER_START import
"fmt"
// HOFSTADTER_END import
"github.com/spf13/cobra"
)
// HOFSTADTER_START const
// HOFSTADTER_END const
// HOFSTADTER_START var
// HOFSTADTER_END var
// HOFSTADTER_START init
// HOFSTADTER_END init
var (
RootCmd = &cobra.Command{
Use: "hello",
Short: "A simple hello world cli.",
Run: func(cmd *cobra.Command, args []string) {
logger.Debug("In helloCmd", "args", args)
// Argument Parsing
// HOFSTADTER_START cmd_run
fmt.Println("Hello! ", args)
// HOFSTADTER_END cmd_run
},
}
)
// HOFSTADTER_BELOW
|
package main
import "fmt"
func main() {
var subject string = "Gopher"
fmt.Println("First element of Gopher string: ", string("Gopher"[0]))
fmt.Printf("The first value of the subject string: %v\n", string(subject[0]))
fmt.Printf("The last value of the subject string: %v\n", string(subject[len(subject)-1]))
fmt.Println("Hello " + subject + "!")
}
|
package middleware
import (
"os"
"github.com/gin-gonic/gin"
"github.com/zmb3/spotify"
)
var scopes = []string{
spotify.ScopeUserReadPrivate,
spotify.ScopePlaylistModifyPublic,
spotify.ScopePlaylistModifyPrivate,
}
//SpotifyRequired middleware func
func SpotifyRequired() gin.HandlerFunc {
redirectURI := os.Getenv("CALLBACK_URL")
if os.Getenv("ENV") == "dev" {
redirectURI = "http://localhost:8080/v1/callback"
}
//This part is executed once when you initalize your middleware
spotify := spotify.NewAuthenticator(redirectURI, scopes...)
return func(c *gin.Context) {
c.Set("SPOTIFY", spotify)
c.Next()
}
}
|
package openid_test
import (
"fmt"
"net/http"
"github.com/emanoelxavier/openid2go/openid"
)
func AuthenticatedHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "The user was authenticated!")
}
func AuthenticatedHandlerWithUser(u *openid.User, w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "The user was authenticated! The token was issued by %v and the user is %+v.", u.Issuer, u)
}
func UnauthenticatedHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Reached without authentication!")
}
// This example demonstrates how to use of the openid middlewares to validate incoming
// ID Tokens in the HTTP Authorization header with the format 'Bearer id_token'.
// It initializes the Configuration with the desired providers (OPs) and registers two
// middlewares: openid.Authenticate and openid.AuthenticateUser.
// The former will validate the ID Token and fail the call if the token is not valid.
// The latter will do the same but forward the user's information extracted from the token to the next handler.
func Example() {
configuration, err := openid.NewConfiguration(openid.ProvidersGetter(getProviders_googlePlayground))
if err != nil {
panic(err)
}
http.Handle("/user", openid.AuthenticateUser(configuration, openid.UserHandlerFunc(AuthenticatedHandlerWithUser)))
http.Handle("/authn", openid.Authenticate(configuration, http.HandlerFunc(AuthenticatedHandler)))
http.HandleFunc("/unauth", UnauthenticatedHandler)
http.ListenAndServe(":5100", nil)
}
// getProviders returns the identity providers that will authenticate the users of the underlying service.
// A Provider is composed by its unique issuer and the collection of client IDs registered with the provider that
// are allowed to call this service.
// On this example Google OP is the provider of choice and the client ID used corresponds
// to the Google OAUTH Playground https://developers.google.com/oauthplayground
func getProviders_googlePlayground() ([]openid.Provider, error) {
provider, err := openid.NewProvider("https://accounts.google.com", []string{"407408718192.apps.googleusercontent.com"})
if err != nil {
return nil, err
}
return []openid.Provider{provider}, nil
}
|
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"github.com/ONSdigital/aws-appsync-generator/pkg/graphql"
"github.com/pkg/errors"
flag "github.com/spf13/pflag"
)
var (
manifest = ""
)
func init() {
flag.StringVarP(&manifest, "manifest", "m", "manifest.yml", "manifest file to parse")
flag.StringVarP(&graphql.GeneratedFilesPath, "output", "o", graphql.GeneratedFilesPath, "path to output generated files to (CAUTION: will be emptied before write!)")
flag.Parse()
}
func main() {
body, err := ioutil.ReadFile(manifest)
if err != nil {
log.Fatal(errors.Wrapf(err, "failed to read manifest '%s'", manifest))
}
s, err := graphql.NewSchemaFromManifest(body)
if err != nil {
log.Fatal(errors.Wrap(err, "failed to parse definition"))
}
if err := s.WriteAll(); err != nil {
fmt.Println(err)
for _, e := range s.Errors {
fmt.Printf("(error) %v\n", e.Error())
}
fmt.Println("DONE (with errors)")
os.Exit(1)
}
fmt.Println("DONE")
}
|
package server
import (
"github.com/rs/zerolog"
)
type Handlers struct {
Healthcheck
}
func NewHandlers(log zerolog.Logger) *Handlers {
return &Handlers{
Healthcheck: NewHealthcheck(log),
}
}
|
package search
import (
"testing"
"github.com/takatori/mini-search/index"
"reflect"
)
func TestProxymityRanking(t *testing.T) {
collection := []string{
"Do you quarrel, sir?",
"Quarrel sir! no, sir!",
"If you do, sir, I am for you: I serve as good a man as you.",
"No better.",
"Well, sir",
}
writer := index.NewIndexWriter()
for _, c := range collection {
writer.AddDocument(c)
}
idx := writer.Commit()
terms := []string{"quarrel", "sir"}
actual := RankProximity(idx, terms, 10)
expected := []int{1, 2}
if !reflect.DeepEqual(actual, expected) {
t.Errorf("got: %v, want: %v", actual, expected)
}
} |
package backend
import (
"encoding/json"
"math/rand"
)
// User represents an active user. The user can be in a room, or in the placement queue.
// In this implementation we will NOT save user information into the database, as we allow
// register-less entrances. Therefore, we would like User to be as simple as possible.
type User struct {
ID string
Username string
}
// MarshalJSON turns an user into a JSON string.
// As the user struct should not expose an user's ID, only the Username should be sent.
func (u *User) MarshalJSON() ([]byte, error) {
return json.Marshal(u.Username)
}
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
func randStringBytesMaskImpr(n int) string {
b := make([]byte, n)
// A rand.Int63() generates 63 random bits, enough for letterIdxMax letters!
for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
// NewUser creates a new unique user.
func NewUser(username string) User {
return User{
Username: username,
ID: randStringBytesMaskImpr(32),
}
}
|
package main
import (
"os"
"github.com/followedwind/slackbot/internal/endpoint"
"github.com/followedwind/slackbot/internal/util"
"github.com/slack-go/slack"
"github.com/taketsuru-devel/gorilla-microservice-skeleton/serverwrap"
"github.com/taketsuru-devel/gorilla-microservice-skeleton/skeletonutil"
"github.com/taketsuru-devel/gorilla-microservice-skeleton/slackwrap"
)
func main() {
util.InitLog(os.Getenv("LOG_DEBUG") == "True")
util.InitSlackClient(false, nil, nil)
server := serverwrap.NewServer(":13000")
cli := slack.New(os.Getenv("SLACK_BOT_TOKEN"))
slackSecret := os.Getenv("SIGNING_SECRET")
f := slackwrap.NewSlackHandlerFactory(cli, &slackSecret, &endpoint.DefaultEventHandler{}, &endpoint.DefaultInteractiveHandler{})
f.InitBlockAction(endpoint.GetEventIdImpl)
f.RegisterBlockAction(&endpoint.PassHandler{})
server.AddHandle("/homeiot-to-slackbot", &endpoint.HomeIotEndpoint{}).Methods("POST")
server.AddHandle("/events-endpoint", f.CreateEventEndpoint()).Methods("POST")
server.AddHandle("/interactive", f.CreateInteractiveEndpoint()).Methods("POST")
server.Start()
defer server.Stop(60)
skeletonutil.WaitSignal()
}
|
/*
for 循环
*/
package basicgrammar
/**
go已package为最小单位 定义的变量如果没有被引用idea是会报错的
这是一个for
func name的大写是 public的属性
*/
import (
"fmt"
)
//常量 const 访问权限也不一样 pkg都可以访问 使用
const b = "1213"
// break 中断整个循环 continue 中断当前循环 return 回调整个func
func Grammar() {
//变量 只能在函数 Grammar 使用
//变量命名规则 var 参数名称 类型 = 表达式
var s, sep string
//自动类型推断
var zi = "12321"
var a [3]string = [3]string{"a", "b", "c"}
//简短变量声明 自动推导
jianduan := "12321"
for i := 0; i < len(a); i++ {
s += sep + a[i]
sep = ""
}
fmt.Println(s)
fmt.Println(b)
fmt.Println(zi)
fmt.Println(zi)
fmt.Println(jianduan)
//获取变量zi的指针
p := &zi
fmt.Println(p)
//获取指针的值
fmt.Println(*p)
//可以给指针指向的变量重新赋值
*p = "0"
fmt.Println(zi)
//任何指针的零值是 nil 不理解没有测试出来
fmt.Println(&zi == nil)
}
|
package _examples
import (
"reflect"
"testing"
"time"
"github.com/ompluscator/dynamic-struct"
"gopkg.in/go-playground/validator.v9"
)
func TestExample(t *testing.T) {
instances := []interface{}{
getReaderWithNewStructForJsonExample(),
getReaderWithExtendedStructForJsonExample(),
getReaderWithMergedStructsForJsonExample(),
getReaderWithNewStructForFormExample(),
getReaderWithExtendedStructForFormExample(),
getReaderWithMergedStructsForFormExample(),
}
for _, instance := range instances {
if instance == nil {
t.Error(`TestExample - expected not to get nil`)
}
reader := dynamicstruct.NewReader(instance)
testInstance(reader, t)
}
slices := []interface{}{
getSliceOfReadersWithNewStructForJsonExample(),
getSliceOfReadersWithExtendedStructForJsonExample(),
getSliceOfReadersWithMergedStructsForJsonExample(),
}
for _, value := range slices {
if value == nil {
t.Error(`TestExample - expected not to get nil`)
}
readers := dynamicstruct.NewReader(value).ToSliceOfReaders()
for _, reader := range readers {
testInstance(reader, t)
}
}
maps := []interface{}{
getMapOfReadersWithNewStructForJsonExample(),
getMapOfReadersWithExtendedStructForJsonExample(),
getMapOfReadersWithMergedStructsForJsonExample(),
}
for _, value := range maps {
if value == nil {
t.Error(`TestExample - expected not to get nil`)
}
readers := dynamicstruct.NewReader(value).ToSliceOfReaders()
for _, reader := range readers {
testInstance(reader, t)
}
}
}
func testInstance(reader dynamicstruct.Reader, t *testing.T) {
if value := reader.GetField("Integer").Int(); value != 123 {
t.Errorf(`TestExample - expected field "Integer" to be %#v got %#v`, 123, value)
}
if value := reader.GetField("Uinteger").Uint(); value != uint(456) {
t.Errorf(`TestExample - expected field "Uinteger" to be %#v got %#v`, uint(456), value)
}
if value := reader.GetField("Text").String(); value != "example" {
t.Errorf(`TestExample - expected field "Text" to be %#v got %#v`, "example", value)
}
if value := reader.GetField("Float").Float64(); value != 123.45 {
t.Errorf(`TestExample - expected field "Float" to be %#v got %#v`, 123.45, value)
}
dateTime, err := time.Parse(time.RFC3339, "2018-12-27T19:42:31+07:00")
if err != nil {
t.Errorf(`TestExample - expected not to get error got %#v`, err)
}
if value := reader.GetField("Time").Time(); !reflect.DeepEqual(value, dateTime) {
t.Errorf(`TestExample - expected field "Time" to be %#v got %#v`, dateTime, value)
}
if value, ok := reader.GetField("Slice").Interface().([]int); !ok || !reflect.DeepEqual(value, []int{1, 2, 3}) {
t.Errorf(`TestExample - expected field "Slice" to be %#v got %#v`, []int{1, 2, 3}, value)
}
if value := reader.GetField("PointerInteger").PointerInt(); *value != 345 {
t.Errorf(`TestExample - expected field "PointerInteger" to be %#v got %#v`, 345, *value)
}
if value := reader.GetField("PointerUinteger").PointerUint(); *value != uint(234) {
t.Errorf(`TestExample - expected field "PointerUinteger" to be %#v got %#v`, uint(234), *value)
}
if value := reader.GetField("PointerFloat").PointerFloat64(); *value != 567.89 {
t.Errorf(`TestExample - expected field "PointerFloat" to be %#v got %#v`, 567.89, *value)
}
if value := reader.GetField("PointerText").PointerString(); *value != "pointer example" {
t.Errorf(`TestExample - expected field "PointerText" to be %#v got %#v`, "pointer example", *value)
}
if value := reader.GetField("PointerBoolean").PointerBool(); *value != true {
t.Errorf(`TestExample - expected field "PointerBoolean" to be %#v got %#v`, true, *value)
}
pointerDateTime, err := time.Parse(time.RFC3339, "2018-12-28T01:23:45+07:00")
if err != nil {
t.Errorf(`TestExample - expected not to get error got %#v`, err)
}
if value := reader.GetField("PointerTime").PointerTime(); !reflect.DeepEqual(value, &pointerDateTime) {
t.Errorf(`TestExample - expected field "PointerTime" to be %#v got %#v`, pointerDateTime, *value)
}
if value := reader.GetField("Anonymous").String(); value != "" {
t.Errorf(`TestExample - expected field "Anonymous" to be empty got %#v`, value)
}
subReader := dynamicstruct.NewReader(reader.GetField("SubStruct").Interface())
if value := subReader.GetField("Integer").Int(); value != 12 {
t.Errorf(`TestExample - expected field "Integer" to be %#v got %#v`, 12, value)
}
if value := subReader.GetField("Text").String(); value != "sub example" {
t.Errorf(`TestExample - expected field "Text" to be %#v got %#v`, "sub example", value)
}
err = validator.New().Struct(reader.GetValue())
if err == nil {
t.Errorf(`TestExample - expected to have error got %#v`, err)
}
validationErrors, ok := err.(validator.ValidationErrors)
if !ok {
t.Errorf(`TestExample - expected instance of *validator.ValidationErrors got %#v`, reader.GetValue())
}
for _, fieldError := range validationErrors {
fieldError.Tag()
}
fieldErrors := []validator.FieldError(validationErrors)
if len(fieldErrors) != 2 {
t.Errorf(`TestExample - expected field errors to have length %#v got %#v`, 2, len(fieldErrors))
}
checkedInteger := false
checkedText := false
for _, fieldError := range fieldErrors {
if fieldError.Field() == "Integer" {
checkedInteger = true
if fieldError.Tag() != "lt" {
t.Errorf(`TestExample - expected tag of field error to be %#v got %#v`, "lt", fieldError.Tag())
}
if fieldError.Param() != "123" {
t.Errorf(`TestExample - expected param of field error to be %#v got %#v`, "123", fieldError.Param())
}
} else if fieldError.Field() == "Anonymous" {
checkedText = true
if fieldError.Tag() != "required" {
t.Errorf(`TestExample - expected tag of field error to be %#v got %#v`, "required", fieldError.Tag())
}
}
}
if !checkedInteger {
t.Error(`TestExample - expected to have field errors for field "Integer"`)
}
if !checkedText {
t.Error(`TestExample - expected to have field errors for field "Anonymous"`)
}
}
|
package intmap
import "testing"
func TestMapInt32Set_Grow_OK(t *testing.T) {
m := NewMapInt32()
for i := int32(0); i < 100; i++ {
m.Set(i, i)
}
for i := int32(0); i < 100; i++ {
if m.Get(i) != i {
t.Fatalf("key: %d != %d", i, i)
}
}
}
func BenchmarkMapInt32Set_Stdlib(b *testing.B) {
// do bench
m := make(map[int32]int32)
var x int32
for i := 0; i < b.N; i++ {
m[x%16] = x
x++
}
}
func BenchmarkMapInt32Set_MapInt32(b *testing.B) {
// do bench
m := NewMapInt32()
var x int32
for i := 0; i < b.N; i++ {
m.Set(x%16, x)
x++
}
}
func BenchmarkMapInt32SetGrow_Stdlib(b *testing.B) {
// do bench
m := make(map[int32]int32)
var x int32
for i := 0; i < b.N; i++ {
m[x%4096] = x
x++
}
}
func BenchmarkMapInt32SetGrow_MapInt32(b *testing.B) {
// do bench
m := NewMapInt32()
var x int32
for i := 0; i < b.N; i++ {
m.Set(x%4096, x)
x++
}
}
func BenchmarkMapInt64SetGrow_Stdlib(b *testing.B) {
// do bench
m := make(map[int64]int64)
var x int64
for i := 0; i < b.N; i++ {
m[x%4096] = x
x++
}
}
func BenchmarkMapInt64SetGrow_MapInt64(b *testing.B) {
// do bench
m := NewMapInt64()
var x int64
for i := 0; i < b.N; i++ {
m.Set(x%4096, x)
x++
}
}
|
package util
import "regexp"
// Validator 数据格式验证
type Validator struct{}
// IsMobile 判断是否为手机号
func (Validator) IsMobile(value string) bool {
result, _ := regexp.MatchString(`^(1[0-9][0-9]\d{4,8})$`, value)
return result
}
// IsPhone 判断是否为固定电话号码
func (Validator) IsPhone(value string) bool {
result, _ := regexp.MatchString(`^(\d{4}-|\d{3}-)?(\d{8}|\d{7})$`, value)
return result
}
// IsPhone400 判断是否为400电话
func (Validator) IsPhone400(value string) bool {
result, _ := regexp.MatchString(`^400(-\d{3,4}){2}$`, value)
return result
}
// IsEmail 判断是否为邮箱
func (Validator) IsEmail(value string) bool {
result, _ := regexp.MatchString(`\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`, value)
return result
}
// IsIdCard 是否身份证号
func (Validator) IsIdCard(value string) bool {
result, _ := regexp.MatchString(`^\d{17}[0-9xX]$`, value)
return result
}
// IsBankCard 是否银行卡号
func (Validator) IsBankCard(value string) bool {
result, _ := regexp.MatchString(`^(\d{16}|\d{17}|\d{18}|\d{19})$`, value)
return result
}
|
package blob
import (
"encoding/json"
"golang.org/x/net/context"
"google.golang.org/appengine/log"
"google.golang.org/appengine/memcache"
"github.com/firefirestyle/engine-v01/prop"
)
type BlobManager struct {
config BlobManagerConfig
}
type BlobManagerConfig struct {
Kind string
PointerKind string
CallbackUrl string
HashLength int
}
func NewBlobManager(config BlobManagerConfig) *BlobManager {
ret := new(BlobManager)
ret.config = config
return ret
}
func Debug(ctx context.Context, message string) {
log.Infof(ctx, message)
}
/**
*
*
*/
func (obj *BlobManager) SaveSignCache(ctx context.Context, dir, name, value string) {
p := prop.NewMiniPath(dir)
key := p.GetDir() + "/" + name
if value == "" {
memcache.Delete(ctx, key)
} else {
sk, _ := json.Marshal(map[string]interface{}{
"k": obj.config.PointerKind,
"n": key,
})
memcache.Set(ctx, &memcache.Item{
Key: string(sk),
Value: []byte(value),
})
}
}
func (obj *BlobManager) LoadSignCache(ctx context.Context, dir, name string) (string, error) {
p := prop.NewMiniPath(dir)
key := p.GetDir() + "/" + name
sk, _ := json.Marshal(map[string]interface{}{
"k": obj.config.PointerKind,
"n": key,
})
item, err := memcache.Get(ctx, string(sk))
if err != nil {
return "", err
}
return string(item.Value), nil
}
|
package runner
import (
"context"
"fmt"
"strings"
"time"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
"github.com/rs/zerolog/log"
)
// Call executes an request on url using the runner context.
// ctx must be a valid runner context created with WithContext method of a runner instance.
// It returns the response time, HTTP response code, the HTTP response message an
// a boolean indicating if the content comes from a browser cache.
//
// If an error occurred while performing the request an error is returned with zero values
// on all other return values.
func Call(ctx context.Context, url string) (time.Duration, int, string, bool, error) {
v := FromContext(ctx)
url = strings.TrimSuffix(url, "/")
switch v.(type) {
case *ChromeRunner:
return runChrome(ctx, url)
case *FakeRunner:
return runFake(ctx, url)
}
return 0, 0, "", false, ErrInvalidContext
}
func runChrome(ctx context.Context, url string) (time.Duration, int, string, bool, error) {
r := FromContext(ctx).(*ChromeRunner)
log.Debug().
Str("component", "runner").
Int("id", r.ID).
Str("type", fmt.Sprintf("%T", r)).
Str("url", url).
Msg("call url")
err := r.Executor.Run(ctx, network.Enable())
if err != nil {
return 0, 0, "", false, err
}
err = r.Executor.Run(ctx,
chromedp.Navigate(url),
chromedp.Stop(),
)
if err != nil {
return 0, 0, "", false, err
}
err = r.Executor.Run(ctx, network.Disable())
if err != nil {
return 0, 0, "", false, err
}
var (
ttfb time.Duration
code int
msg string
cached bool
)
// Read received network events from runner buffer,
// read network stats and parse ttfb.
if len(r.networkEventChan) == 0 {
return 0, 0, "", false, ErrNoNetworkEventFound
}
func() {
for {
select {
case ev := <-r.networkEventChan:
if strings.TrimSuffix(ev.Response.URL, "/") == url {
log.Debug().
Str("component", "runner").
Int("id", r.ID).
Interface("ev", ev.Response.Timing).
Msg("received base url network event")
code = int(ev.Response.Status)
msg = ev.Response.StatusText
if ev.Response.Timing.ConnectStart == -1 {
ttfb = 0
cached = true
} else {
ttfb = time.Duration(ev.Response.Timing.ReceiveHeadersEnd-
ev.Response.Timing.ConnectStart) * time.Millisecond
}
}
default:
return
}
}
}()
return ttfb, code, msg, cached, nil
}
func runFake(ctx context.Context, url string) (time.Duration, int, string, bool, error) {
r := FromContext(ctx).(*FakeRunner)
log.Debug().
Str("component", "runner").
Uint("id", uint(*r)).
Str("type", fmt.Sprintf("%T", r)).
Str("url", url).
Msg("call url")
select {
case <-time.After(50 * time.Millisecond):
return 50 * time.Millisecond, 200, "OK", false, nil
case <-ctx.Done():
return 0, 0, "", false, context.Canceled
}
}
|
package models
import (
"GridService/Service-Spacdt/models/spacbasic"
"encoding/json"
"fmt"
"io/ioutil"
"strconv"
"time"
"github.com/astaxie/beego"
"github.com/pkg/errors"
"xh.common/xh_util"
_ "github.com/astaxie/beego"
"github.com/streadway/amqp"
)
func init() {
spacbasic.NativeInit()
}
var (
rabbitMQAddr string
rabbitMQExchangeName string
hchFileName string
)
func init() {
rabbitMQAddr = beego.AppConfig.String("rabbitMQAddr")
fmt.Println(rabbitMQAddr)
rabbitMQExchangeName = beego.AppConfig.String("rabbitMQExchangeName")
fmt.Println(rabbitMQExchangeName)
hchFileName = beego.AppConfig.String("hchFileName")
fmt.Println(hchFileName)
go sendRoutine()
}
func sendRoutine() {
for {
go RabbitMQSend()
time.Sleep(20 * time.Second)
}
}
func RabbitMQSend() error {
conn, err := amqp.Dial(rabbitMQAddr)
if err != nil {
fmt.Printf("amqp.Dial错误: %s\n", err.Error())
return err
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
fmt.Printf("conn.Channel错误: %s\n", err.Error())
return err
}
defer ch.Close()
//声明交换器
err = ch.ExchangeDeclare(
rabbitMQExchangeName, // name
"fanout", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
if err != nil {
fmt.Printf("ch.ExchangeDeclare错误: %s", err.Error())
return err
}
//待发送数据
err, bytes := ReadFromTxt()
if err != nil {
return err
}
// err, bytes := Trans2LonLatArr()
// if err != nil {
// return err
// }
err = ch.Publish(
rabbitMQExchangeName, // exchange
"", // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: bytes,
//Expiration: "50000", // 设置消息过期时间
})
fmt.Printf("Send %s\n", string(bytes))
if err != nil {
fmt.Printf("ch.Publish错误: %s\n", err.Error())
return err
}
return nil
}
func ReadFromTxt() (error, []byte) {
filePath := "static/" + hchFileName
//fmt.Println(filePath)
bytes, err := ioutil.ReadFile(filePath)
if err != nil {
return err, nil
}
return err, bytes
}
type LonLat struct {
Longitude float64 `json:"longitude"`
Latitude float64 `json:"latitude"`
}
type GridCrow struct {
GridId string `json:"gridId"`
Count int64 `json:"count"`
}
func Trans2LonLatArr() (error, []byte) {
var gridCrowArr []GridCrow
var lonLatArr []LonLat
err, bytes := ReadFromTxt()
if err != nil {
fmt.Println(err.Error())
return err, nil
}
err = json.Unmarshal(bytes, &gridCrowArr)
if err != nil {
fmt.Println(err.Error())
return err, nil
}
for _, val := range gridCrowArr {
var box xh_util.StBox3D
var lonLat LonLat
gridID, err := strconv.ParseUint(val.GridId, 10, 64)
if err != nil {
fmt.Println(err.Error())
return err, nil
}
b := spacbasic.NativeMakeSpatialIndexBox(gridID, &box)
if !b {
fmt.Println(b)
return errors.New("Trans2LonLatArr:spacbasic.NativeMakeSpatialIndexBox失败!"), nil
}
lonLat.Longitude = (box.SouthWest.X + box.NorthEast.X) / 2
lonLat.Latitude = (box.SouthWest.Y + box.NorthEast.Y) / 2
for i := 0; i < int(val.Count); i++ {
lonLatArr = append(lonLatArr, lonLat)
}
}
lonLatArrBytes, err := json.Marshal(lonLatArr)
if err != nil {
fmt.Println(err.Error())
return err, nil
}
return nil, lonLatArrBytes
}
|
package handler
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"proxy_download/common"
"proxy_download/model"
"strconv"
"strings"
)
func VariableDetail(context *gin.Context) {
var variable model.Variable
idString := context.Param("id")
id, _ := strconv.ParseInt(idString, 10, 64)
variableDetail, err := variable.Detail(id)
if err != nil {
fmt.Println("query table variable err = ", err)
return
}
context.JSON(http.StatusOK, Data{"list": variableDetail})
}
func VariableEdit(context *gin.Context) {
var variable model.Variable
if err := context.ShouldBind(&variable); err != nil {
context.JSON(http.StatusOK, Data{"err": "输入的数据不合法"})
log.Panicln("err ->", err.Error())
return
}
if variable.ID != 0 {
err := variable.Update()
if err != nil {
fmt.Println("update variable err = ", err)
context.JSON(http.StatusBadRequest, Data{"err": "update variable err" + err.Error()})
return
}
context.JSON(http.StatusOK, Data{"msg": "update variable success"})
return
}
id, err := variable.Save()
if err != nil {
fmt.Println("save variable err ", err)
context.JSON(http.StatusBadRequest, Data{"err": "save variable err" + err.Error()})
return
}
context.JSON(http.StatusOK, Data{"msg": "save variable success, id:" + strconv.FormatInt(id, 10)})
}
func VariableList(context *gin.Context) {
var variable model.Variable
page, err := strconv.Atoi(context.DefaultQuery("page", "1"))
pagesize, err := strconv.Atoi(context.DefaultQuery("pagesize", "10"))
fmt.Println("page ")
variables, count, err := variable.List(page, pagesize)
if err != nil {
err := fmt.Errorf("query table variable err = %v", err.Error())
fmt.Println(err)
context.JSON(http.StatusBadGateway, err)
return
}
context.JSON(http.StatusOK, Data{"list": variables, "count": count})
}
func VariableDel(context *gin.Context) {
var variables NullMap
var variable model.Variable
err := context.BindJSON(&variables)
if err != nil {
log.Println("json.Unmarshal err = ", err)
context.JSON(http.StatusOK, Data{"err": "get ids error"})
return
}
switch ids := variables["ids"].(type) {
// 对返回的元素进行判断 float64 id []interface{} ids
case float64:
if err = variable.Delete(ids); err != nil {
fmt.Println("delete variable err :", err)
context.JSON(http.StatusBadRequest, Data{"err": err})
return
}
context.JSON(http.StatusOK, Data{"msg": "del success"})
return
case []interface{}:
if err = variable.Deletes(ids); err != nil {
fmt.Println("list delete variable err :", err)
context.JSON(http.StatusBadRequest, Data{"err": err})
return
}
context.JSON(http.StatusOK, Data{"msg": "del list success"})
}
}
func VariableNameValidate(context *gin.Context) {
var params = struct {
Name string `json:"name"`
RegisterVariable string `json:"register_variable"`
VariableId int `json:"variable_id"`
TestcaseId int `json:"testcase_id"`
UserId int `json:"user_id"`
Update bool `json:"update"`
}{}
err1 := context.BindJSON(¶ms)
if err1 != nil {
fmt.Println("context.BindJSON VariableNameValidate err = ", err1)
return
}
update := params.Update
variableId := params.VariableId
userId := params.UserId
name := params.Name
testcaseId := params.TestcaseId
registerVariable := params.RegisterVariable
if update {
if variableId != 0 {
result, err := model.UpdateVariableNameValidate(variableId, userId, name)
if err != nil {
context.JSON(http.StatusBadRequest, Data{"err": err.Error()})
return
}
context.JSON(http.StatusOK, result)
return
}
result, err := model.UpdateCaseRegisterNameValidate(testcaseId, userId, registerVariable)
if err != nil {
context.JSON(http.StatusBadRequest, Data{"err": err.Error()})
return
}
context.JSON(http.StatusOK, result)
return
}
if name != "" {
registerVariable = name
}
if strings.Index(registerVariable, ",") != -1 && registerVariable != "" && len(strings.Trim(registerVariable, " ")) > 0 {
variableList := strings.Split(registerVariable, ",")
if len(variableList) != len(common.SliceToMap(variableList)) {
context.JSON(http.StatusOK, false)
return
}
for _, vbName := range variableList {
count, _ := model.QueryVariableCount(vbName, 0, userId)
if count != 0 {
context.JSON(http.StatusOK, false)
return
}
}
context.JSON(http.StatusOK, true)
return
}
count, _ := model.QueryVariableCount(registerVariable, 0, userId)
context.JSON(http.StatusOK, count == 0)
}
|
package wikipedia
import "net/http"
import "net/url"
import "errors"
import "fmt"
import "encoding/json"
import "strings"
const LANGUAGE_URL_MARKER = "{language}"
type Wikipedia interface {
Page(title string) Page
PageFromId(id string) Page
GetBaseUrl() string
SetBaseUrl(baseUrl string)
SetImagesResults(imagesResults string)
SetLinksResults(linksResults string)
SetCategoriesResults(categoriesResults string)
PreLanguageUrl() string
PostLanguageUrl() string
Language() string
SearchResults() int
GetLanguages() (languages []Language, err error)
Search(query string) (results []string, err error)
Geosearch(latitude float64, longitude float64, radius int) (results []string, err error)
RandomCount(count uint) (results []string, err error)
Random() (string, error)
ImagesResults() string
LinksResults() string
CategoriesResults() string
}
type WikipediaClient struct {
preLanguageUrl, postLanguageUrl, language string
imagesResults, linksResults, categoriesResults string
searchResults int
}
const (
ParameterError = iota
ResponseError = iota
)
type WikipediaError struct {
Type int
Err error
}
func newError(t int, e error) *WikipediaError {
return &WikipediaError{Type: t, Err: e}
}
func (e *WikipediaError) Error() string {
switch e.Type {
case ParameterError:
return fmt.Sprintf("parameter error: %s", e.Err.Error())
case ResponseError:
return fmt.Sprintf("response error: %s", e.Err.Error())
default:
return fmt.Sprintf("unknown error: %s", e.Err.Error())
}
}
type Language struct {
code, name string
}
func NewWikipedia() *WikipediaClient {
return &WikipediaClient{
preLanguageUrl: "https://",
postLanguageUrl: ".wikipedia.org/w/api.php",
language: "en",
searchResults: 10,
imagesResults: "max",
linksResults: "max",
categoriesResults: "max",
}
}
func (w *WikipediaClient) Page(title string) Page {
return NewPage(w, title)
}
func (w *WikipediaClient) PageFromId(id string) Page {
return NewPageFromId(w, id)
}
func (w *WikipediaClient) GetBaseUrl() string {
return fmt.Sprintf("%s%s%s", w.preLanguageUrl, w.language, w.postLanguageUrl)
}
func (w *WikipediaClient) SetBaseUrl(baseUrl string) {
index := strings.Index(baseUrl, LANGUAGE_URL_MARKER)
if index == -1 {
w.preLanguageUrl = baseUrl
w.language = ""
w.postLanguageUrl = ""
} else {
w.preLanguageUrl = baseUrl[0:index]
w.postLanguageUrl = baseUrl[index+len(LANGUAGE_URL_MARKER):]
}
}
func (w *WikipediaClient) ImagesResults() string {
return w.imagesResults
}
func (w *WikipediaClient) LinksResults() string {
return w.linksResults
}
func (w *WikipediaClient) CategoriesResults() string {
return w.categoriesResults
}
func (w *WikipediaClient) SetImagesResults(imagesResults string) {
w.imagesResults = imagesResults
}
func (w *WikipediaClient) SetLinksResults(linksResults string) {
w.linksResults = linksResults
}
func (w *WikipediaClient) SetCategoriesResults(categoriesResults string) {
w.categoriesResults = categoriesResults
}
func query(w Wikipedia, q map[string][]string, v interface{}) error {
resp, err := http.Get(fmt.Sprintf("%s?%s", w.GetBaseUrl(), url.Values(q).Encode()))
if err != nil {
return newError(ResponseError, err)
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&v)
if err != nil {
return newError(ResponseError, err)
}
return nil
}
func processResults(v interface{}, field string) ([]string, error) {
results := make([]string, 0)
gotResults := false
if r, ok := v.(map[string]interface{}); ok {
if query, ok := r["query"].(map[string]interface{}); ok {
if values, ok := query[field].([]interface{}); ok {
gotResults = true
for _, l := range values {
if lang, ok := l.(map[string]interface{}); ok {
if title, ok := lang["title"].(string); ok {
results = append(results, title)
}
}
}
}
}
}
if gotResults == false {
return nil, newError(ResponseError, errors.New("invalid json response"))
}
return results, nil
}
func (w *WikipediaClient) PreLanguageUrl() string {
return w.preLanguageUrl
}
func (w *WikipediaClient) PostLanguageUrl() string {
return w.postLanguageUrl
}
func (w *WikipediaClient) Language() string {
return w.language
}
func (w *WikipediaClient) SearchResults() int {
return w.searchResults
}
func (w *WikipediaClient) GetLanguages() ([]Language, error) {
var f interface{}
err := query(w, map[string][]string{
"meta": {"siteinfo"},
"siprop": {"languages"},
"format": {"json"},
"action": {"query"},
}, &f)
if err != nil {
return nil, err
}
gotLangs := false
languages := make([]Language, 0)
if r, ok := f.(map[string]interface{}); ok {
if query, ok := r["query"].(map[string]interface{}); ok {
if langs, ok := query["languages"].([]interface{}); ok {
gotLangs = true
for _, l := range langs {
if lang, ok := l.(map[string]interface{}); ok {
if code, ok := lang["code"].(string); ok {
if name, ok := lang["*"].(string); ok {
languages = append(languages, Language{code, name})
}
}
}
}
}
}
}
if gotLangs == false {
return nil, newError(ResponseError, errors.New("invalid json response"))
}
return languages, nil
}
func (w *WikipediaClient) Search(q string) ([]string, error) {
var f interface{}
err := query(w, map[string][]string{
"list": {"search"},
"srpop": {""},
"srlimit": {fmt.Sprintf("%d", w.searchResults)},
"srsearch": {q},
"format": {"json"},
"action": {"query"},
}, &f)
if err != nil {
return nil, err
}
return processResults(f, "search")
}
func (w *WikipediaClient) Geosearch(latitude float64, longitude float64, radius int) ([]string, error) {
if latitude < -90.0 || latitude > 90.0 {
return nil, newError(ParameterError, errors.New("invalid latitude"))
}
if longitude < -180.0 || longitude > 180.0 {
return nil, newError(ParameterError, errors.New("invalid longitude"))
}
if radius < -10 || radius > 10000 {
return nil, newError(ParameterError, errors.New("invalid radius"))
}
var f interface{}
err := query(w, map[string][]string{
"list": {"geosearch"},
"gsradius": {fmt.Sprintf("%d", radius)},
"gscoord": {fmt.Sprintf("%f|%f", latitude, longitude)},
"gslimit": {fmt.Sprintf("%d", w.searchResults)},
"format": {"json"},
"action": {"query"},
}, &f)
if err != nil {
return nil, err
}
return processResults(f, "geosearch")
}
func (w *WikipediaClient) RandomCount(count uint) ([]string, error) {
var f interface{}
err := query(w, map[string][]string{
"list": {"random"},
"rnnamespace": {"0"},
"rnlimit": {fmt.Sprintf("%d", count)},
"format": {"json"},
"action": {"query"},
}, &f)
if err != nil {
return nil, err
}
return processResults(f, "random")
}
func (w *WikipediaClient) Random() (string, error) {
results, err := w.RandomCount(1)
if err != nil {
return "", err
}
if len(results) == 0 {
return "", newError(ResponseError, errors.New("Got no results"))
}
return results[0], nil
}
|
package rstreams
import (
"context"
"github.com/go-redis/redis/v8"
"github.com/pkg/errors"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcorp/plumber/tunnel"
"github.com/batchcorp/plumber/validate"
)
func (r *RedisStreams) Tunnel(ctx context.Context, tunnelOpts *opts.TunnelOptions, tunnelSvc tunnel.ITunnel, errorCh chan<- *records.ErrorRecord) error {
if err := validateTunnelOptions(tunnelOpts); err != nil {
return errors.Wrap(err, "unable to validate tunnel options")
}
llog := r.log.WithField("pkg", "rstreams/tunnel")
if err := tunnelSvc.Start(ctx, "Redis Streams", errorCh); err != nil {
return errors.Wrap(err, "unable to create tunnel")
}
outboundCh := tunnelSvc.Read()
for {
select {
case outbound := <-outboundCh:
for _, streamName := range tunnelOpts.RedisStreams.Args.Streams {
_, err := r.client.XAdd(ctx, &redis.XAddArgs{
Stream: streamName,
ID: tunnelOpts.RedisStreams.Args.WriteId,
Values: map[string]interface{}{
tunnelOpts.RedisStreams.Args.Key: outbound.Blob,
},
}).Result()
if err != nil {
r.log.Errorf("unable to write message to '%s': %s", streamName, err)
continue
}
r.log.Infof("Successfully wrote message to stream '%s' with key '%s' for replay '%s'",
streamName, tunnelOpts.RedisStreams.Args.Key, outbound.ReplayId)
}
case <-ctx.Done():
llog.Debug("context cancelled")
return nil
}
}
return nil
}
func validateTunnelOptions(tunnelOpts *opts.TunnelOptions) error {
if tunnelOpts == nil {
return validate.ErrEmptyTunnelOpts
}
if tunnelOpts.RedisStreams == nil {
return validate.ErrEmptyBackendGroup
}
if tunnelOpts.RedisStreams.Args == nil {
return validate.ErrEmptyBackendArgs
}
if len(tunnelOpts.RedisStreams.Args.Streams) == 0 {
return ErrMissingStream
}
return nil
}
|
package view
import (
"html/template"
"io"
"net/http"
)
var (
VIEW_PREFIX = "view/"
VIEW_SUFFIX = ".html"
)
type ViewResolver struct {
View *View
Writer io.Writer
}
func (v *ViewResolver) Resolve() {
handlerView := *v.View
layoutName := handlerView.GetLayout()
viewName := handlerView.GetView()
var views = make([]string, 0)
if layoutName != "" {
views = append(views, VIEW_PREFIX+layoutName+VIEW_SUFFIX)
}
views = append(views, VIEW_PREFIX+viewName+VIEW_SUFFIX)
tpl := template.Must(template.New(viewName).Funcs(v.GetFuncMap()).ParseFiles(views...))
err := tpl.ExecuteTemplate(v.Writer, layoutName+VIEW_SUFFIX, handlerView.modelMap)
if err != nil {
http.Error(v.Writer.(http.ResponseWriter), http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
func (v *ViewResolver) GetFuncMap() template.FuncMap {
return template.FuncMap{
"html": func(str string) template.HTML {
return template.HTML(str)
},
}
}
|
package workspace
import (
"archive/zip"
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strconv"
"testing"
"github.com/databrickslabs/databricks-terraform/common"
"github.com/databrickslabs/databricks-terraform/internal/qa"
"github.com/stretchr/testify/assert"
)
func notebookToB64(filePath string) (string, error) {
notebookBytes, err := ioutil.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("unable to find notebook to convert to base64; %w", err)
}
return base64.StdEncoding.EncodeToString(notebookBytes), nil
}
func TestValidateNotebookPath(t *testing.T) {
testCases := []struct {
name string
notebookPath string
errorCount int
}{
{"empty_path",
"",
2},
{"correct_path",
"/directory",
0},
{"path_starts_with_no_slash",
"directory",
1},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
_, errs := ValidateNotebookPath(tc.notebookPath, "key")
assert.Lenf(t, errs, tc.errorCount, "directory '%s' does not generate the expected error count", tc.notebookPath)
})
}
}
func TestResourceNotebookCreate_DirDoesNotExists(t *testing.T) {
pythonNotebookDataB64, err := notebookToB64("acceptance/testdata/tf-test-python.py")
assert.NoError(t, err, err)
checkSum, err := convertBase64ToCheckSum(pythonNotebookDataB64)
assert.NoError(t, err, err)
path := "/test/path.py"
content := pythonNotebookDataB64
objectId := 12345
d, err := qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
{
Method: http.MethodGet,
Resource: "/api/2.0/workspace/get-status?path=%2Ftest",
Response: common.APIErrorBody{
ErrorCode: "NOT_FOUND",
Message: "not found",
},
Status: 404,
},
{
Method: http.MethodPost,
Resource: "/api/2.0/workspace/mkdirs",
Response: NotebookImportRequest{
Content: content,
Path: path,
Language: Python,
Overwrite: true,
Format: Source,
},
},
{
Method: http.MethodPost,
Resource: "/api/2.0/workspace/import",
Response: NotebookImportRequest{
Content: content,
Path: path,
Language: Python,
Overwrite: true,
Format: Source,
},
},
{
Method: http.MethodGet,
Resource: "/api/2.0/workspace/export?format=SOURCE&path=%2Ftest%2Fpath.py",
Response: NotebookContent{
Content: pythonNotebookDataB64,
},
},
{
Method: http.MethodGet,
Resource: "/api/2.0/workspace/get-status?path=%2Ftest%2Fpath.py",
Response: WorkspaceObjectStatus{
ObjectID: int64(objectId),
ObjectType: Notebook,
Path: path,
Language: Python,
},
},
},
Resource: ResourceNotebook(),
State: map[string]interface{}{
"path": path,
"content": content,
"language": string(Python),
"format": string(Source),
"overwrite": true,
"mkdirs": true,
},
Create: true,
}.Apply(t)
assert.NoError(t, err, err)
assert.Equal(t, path, d.Id())
assert.Equal(t, checkSum, d.Get("content"))
assert.Equal(t, path, d.Get("path"))
assert.Equal(t, string(Python), d.Get("language"))
assert.Equal(t, objectId, d.Get("object_id"))
}
func TestResourceNotebookCreate_NoMkdirs(t *testing.T) {
pythonNotebookDataB64, err := notebookToB64("acceptance/testdata/tf-test-python.py")
assert.NoError(t, err, err)
checkSum, err := convertBase64ToCheckSum(pythonNotebookDataB64)
assert.NoError(t, err, err)
path := "/test/path.py"
content := pythonNotebookDataB64
objectId := 12345
d, err := qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
{
Method: http.MethodPost,
Resource: "/api/2.0/workspace/import",
Response: NotebookImportRequest{
Content: content,
Path: path,
Language: Python,
Overwrite: true,
Format: Source,
},
},
{
Method: http.MethodGet,
Resource: "/api/2.0/workspace/export?format=SOURCE&path=%2Ftest%2Fpath.py",
Response: NotebookContent{
Content: pythonNotebookDataB64,
},
},
{
Method: http.MethodGet,
Resource: "/api/2.0/workspace/get-status?path=%2Ftest%2Fpath.py",
Response: WorkspaceObjectStatus{
ObjectID: int64(objectId),
ObjectType: Notebook,
Path: path,
Language: Python,
},
},
},
Resource: ResourceNotebook(),
State: map[string]interface{}{
"path": path,
"content": content,
"language": string(Python),
"format": string(Source),
"overwrite": true,
"mkdirs": false,
},
Create: true,
}.Apply(t)
assert.NoError(t, err, err)
assert.Equal(t, path, d.Id())
assert.Equal(t, checkSum, d.Get("content"))
assert.Equal(t, path, d.Get("path"))
assert.Equal(t, string(Python), d.Get("language"))
assert.Equal(t, objectId, d.Get("object_id"))
}
func TestResourceNotebookRead(t *testing.T) {
pythonNotebookDataB64, err := notebookToB64("acceptance/testdata/tf-test-python.py")
assert.NoError(t, err, err)
checkSum, err := convertBase64ToCheckSum(pythonNotebookDataB64)
assert.NoError(t, err, err)
exportFormat := Source
testId := "/test/path.py"
objectId := 12345
assert.NoError(t, err, err)
d, err := qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
{
Method: http.MethodGet,
Resource: "/api/2.0/workspace/export?format=SOURCE&path=%2Ftest%2Fpath.py",
Response: NotebookContent{
Content: pythonNotebookDataB64,
},
},
{
Method: http.MethodGet,
Resource: "/api/2.0/workspace/get-status?path=%2Ftest%2Fpath.py",
Response: WorkspaceObjectStatus{
ObjectID: int64(objectId),
ObjectType: Notebook,
Path: testId,
Language: Python,
},
},
},
Resource: ResourceNotebook(),
Read: true,
ID: testId,
State: map[string]interface{}{
"format": exportFormat,
},
}.Apply(t)
assert.NoError(t, err, err)
assert.Equal(t, testId, d.Id())
assert.Equal(t, checkSum, d.Get("content"))
assert.Equal(t, testId, d.Get("path"))
assert.Equal(t, string(Python), d.Get("language"))
assert.Equal(t, objectId, d.Get("object_id"))
}
func TestResourceNotebookDelete(t *testing.T) {
testId := "/test/path.py"
d, err := qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
{
Method: http.MethodPost,
Resource: "/api/2.0/workspace/delete",
Status: http.StatusOK,
ExpectedRequest: NotebookDeleteRequest{Path: testId, Recursive: true},
},
},
Resource: ResourceNotebook(),
Delete: true,
ID: testId,
}.Apply(t)
assert.NoError(t, err, err)
assert.Equal(t, testId, d.Id())
}
func TestResourceNotebookDelete_TooManyRequests(t *testing.T) {
testId := "/test/path.py"
d, err := qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
{
Method: http.MethodPost,
Resource: "/api/2.0/workspace/delete",
Status: http.StatusTooManyRequests,
},
{
Method: http.MethodPost,
Resource: "/api/2.0/workspace/delete",
Status: http.StatusOK,
ExpectedRequest: NotebookDeleteRequest{Path: testId, Recursive: true},
},
},
Resource: ResourceNotebook(),
Delete: true,
ID: testId,
}.Apply(t)
assert.NoError(t, err, err)
assert.Equal(t, testId, d.Id())
}
func TestResourceNotebookRead_NotFound(t *testing.T) {
d, err := qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
{ // read log output for correct url...
Method: "GET",
Resource: "/api/2.0/workspace/export?format=SOURCE&path=%2Ftest%2Fpath.py",
Response: common.APIErrorBody{
ErrorCode: "NOT_FOUND",
Message: "Item not found",
},
Status: 404,
},
},
Resource: ResourceNotebook(),
Read: true,
ID: "/test/path.py",
}.Apply(t)
assert.NoError(t, err, err)
assert.Equal(t, "", d.Id(), "Id should be empty for missing resources")
}
func TestResourceNotebookRead_Error(t *testing.T) {
d, err := qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
{ // read log output for correct url...
Method: "GET",
Resource: "/api/2.0/workspace/export?format=SOURCE&path=%2Ftest%2Fpath.py",
Response: common.APIErrorBody{
ErrorCode: "INVALID_REQUEST",
Message: "Internal error happened",
},
Status: 400,
},
},
Resource: ResourceNotebook(),
Read: true,
ID: "/test/path.py",
}.Apply(t)
qa.AssertErrorStartsWith(t, err, "Internal error happened")
assert.Equal(t, "/test/path.py", d.Id(), "Id should not be empty for error reads")
}
func TestResourceNotebookCreate(t *testing.T) {
d, err := qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
{
Method: http.MethodPost,
Resource: "/api/2.0/workspace/import",
Response: NotebookImportRequest{
Content: "YWJjCg==",
Path: "/path.py",
Language: Python,
Overwrite: true,
Format: Source,
},
},
{
Method: http.MethodGet,
Resource: "/api/2.0/workspace/export?format=SOURCE&path=%2Fpath.py",
Response: NotebookContent{
Content: "YWJjCg==",
},
},
{
Method: http.MethodGet,
Resource: "/api/2.0/workspace/get-status?path=%2Fpath.py",
Response: WorkspaceObjectStatus{
ObjectID: 4567,
ObjectType: "NOTEBOOK",
Path: "/path.py",
Language: Python,
},
},
},
Resource: ResourceNotebook(),
State: map[string]interface{}{
"content": "YWJjCg==",
"format": "SOURCE",
"language": "PYTHON",
"overwrite": true,
"path": "/path.py",
},
Create: true,
}.Apply(t)
assert.NoError(t, err, err)
assert.Equal(t, "/path.py", d.Id())
}
func TestResourceNotebookCreate_Error(t *testing.T) {
d, err := qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
{
Method: http.MethodPost,
Resource: "/api/2.0/workspace/import",
Response: common.APIErrorBody{
ErrorCode: "INVALID_REQUEST",
Message: "Internal error happened",
},
Status: 400,
},
},
Resource: ResourceNotebook(),
State: map[string]interface{}{
"content": "YWJjCg==",
"format": "SOURCE",
"language": "PYTHON",
"overwrite": true,
"path": "/path.py",
},
Create: true,
}.Apply(t)
qa.AssertErrorStartsWith(t, err, "Internal error happened")
assert.Equal(t, "", d.Id(), "Id should be empty for error creates")
}
func TestResourceNotebookDelete_Error(t *testing.T) {
d, err := qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
{
Method: "POST",
Resource: "/api/2.0/workspace/delete",
Response: common.APIErrorBody{
ErrorCode: "INVALID_REQUEST",
Message: "Internal error happened",
},
Status: 400,
},
},
Resource: ResourceNotebook(),
Delete: true,
ID: "abc",
}.Apply(t)
qa.AssertErrorStartsWith(t, err, "Internal error happened")
assert.Equal(t, "abc", d.Id())
}
func TestNotebooksAPI_Create(t *testing.T) {
type args struct {
Content string `json:"content,omitempty"`
Path string `json:"path,omitempty"`
Language Language `json:"language,omitempty"`
Overwrite bool `json:"overwrite,omitempty"`
Format ExportFormat `json:"format,omitempty"`
}
tests := []struct {
name string
response string
args args
wantErr bool
}{
{
name: "Create Test",
response: "",
args: args{
Content: "helloworld",
Path: "my-path",
Language: Python,
Overwrite: false,
Format: DBC,
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var input args
qa.AssertRequestWithMockServer(t, &tt.args, http.MethodPost, "/api/2.0/workspace/import", &input, tt.response, http.StatusOK, nil,
tt.wantErr, func(client *common.DatabricksClient) (interface{}, error) {
return nil, NewNotebooksAPI(client).Create(tt.args.Path, tt.args.Content, tt.args.Language, tt.args.Format, tt.args.Overwrite)
})
})
}
}
func TestNotebooksAPI_MkDirs(t *testing.T) {
type args struct {
Path string `json:"path,omitempty"`
}
tests := []struct {
name string
response string
args args
wantErr bool
}{
{
name: "Create Test",
response: "",
args: args{
Path: "/test/path",
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var input args
qa.AssertRequestWithMockServer(t, &tt.args, http.MethodPost, "/api/2.0/workspace/mkdirs", &input, tt.response, http.StatusOK, nil, tt.wantErr, func(client *common.DatabricksClient) (interface{}, error) {
return nil, NewNotebooksAPI(client).Mkdirs(tt.args.Path)
})
})
}
}
func TestNotebooksAPI_Delete(t *testing.T) {
type args struct {
Path string `json:"path,omitempty"`
Recursive bool `json:"recursive,omitempty"`
}
tests := []struct {
name string
response string
responseStatus int
args args
wantErr bool
}{
{
name: "Delete test",
response: "",
responseStatus: http.StatusOK,
args: args{
Path: "mypath",
Recursive: false,
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var input args
qa.AssertRequestWithMockServer(t, &tt.args, http.MethodPost, "/api/2.0/workspace/delete", &input, tt.response, tt.responseStatus, nil, tt.wantErr, func(client *common.DatabricksClient) (interface{}, error) {
return nil, NewNotebooksAPI(client).Delete(tt.args.Path, tt.args.Recursive)
})
})
}
}
func TestNotebooksAPI_ListNonRecursive(t *testing.T) {
type args struct {
Path string `json:"path"`
Recursive bool `json:"recursive"`
}
tests := []struct {
name string
response string
responseStatus int
args args
wantURI string
want []WorkspaceObjectStatus
wantErr bool
}{
{
name: "List non recursive test",
response: `{
"objects": [
{
"path": "/Users/user@example.com/project",
"object_type": "DIRECTORY",
"object_id": 123
},
{
"path": "/Users/user@example.com/PythonExampleNotebook",
"language": "PYTHON",
"object_type": "NOTEBOOK",
"object_id": 456
}
]
}`,
responseStatus: http.StatusOK,
args: args{
Path: "/test/path",
Recursive: false,
},
wantURI: "/api/2.0/workspace/list?path=%2Ftest%2Fpath",
want: []WorkspaceObjectStatus{
{
ObjectID: 123,
ObjectType: Directory,
Path: "/Users/user@example.com/project",
},
{
ObjectID: 456,
ObjectType: Notebook,
Language: Python,
Path: "/Users/user@example.com/PythonExampleNotebook",
},
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var input args
qa.AssertRequestWithMockServer(t, tt.args, http.MethodGet, tt.wantURI, &input, tt.response, tt.responseStatus, tt.want, tt.wantErr, func(client *common.DatabricksClient) (interface{}, error) {
return NewNotebooksAPI(client).List(tt.args.Path, tt.args.Recursive)
})
})
}
}
func TestNotebooksAPI_ListRecursive(t *testing.T) {
type args struct {
Path string `json:"path"`
Recursive bool `json:"recursive"`
}
tests := []struct {
name string
response []string
responseStatus []int
args []interface{}
wantURI []string
want []WorkspaceObjectStatus
wantErr bool
}{
{
name: "List recursive test",
response: []string{`{
"objects": [
{
"path": "/Users/user@example.com/project",
"object_type": "DIRECTORY",
"object_id": 123
},
{
"path": "/Users/user@example.com/PythonExampleNotebook",
"language": "PYTHON",
"object_type": "NOTEBOOK",
"object_id": 456
}
]
}`,
`{
"objects": [
{
"path": "/Users/user@example.com/Notebook2",
"language": "PYTHON",
"object_type": "NOTEBOOK",
"object_id": 457
}
]
}`,
},
responseStatus: []int{http.StatusOK, http.StatusOK},
args: []interface{}{
&args{
Path: "/test/path",
Recursive: true,
},
},
wantURI: []string{"/api/2.0/workspace/list?path=%2Ftest%2Fpath", "/api/2.0/workspace/list?path=%2FUsers%2Fuser@example.com%2Fproject"},
want: []WorkspaceObjectStatus{
{
ObjectID: 457,
ObjectType: Notebook,
Language: Python,
Path: "/Users/user@example.com/Notebook2",
},
{
ObjectID: 456,
ObjectType: Notebook,
Language: Python,
Path: "/Users/user@example.com/PythonExampleNotebook",
},
},
wantErr: false,
},
{
name: "List recursive test failure",
response: []string{`{
"objects": [
{
"path": "/Users/user@example.com/project",
"object_type": "DIRECTORY",
"object_id": 123
},
{
"path": "/Users/user@example.com/PythonExampleNotebook",
"language": "PYTHON",
"object_type": "NOTEBOOK",
"object_id": 456
}
]
}`,
``,
},
responseStatus: []int{http.StatusOK, http.StatusBadRequest},
args: []interface{}{
&args{
Path: "/test/path",
Recursive: true,
},
},
wantURI: []string{"/api/2.0/workspace/list?path=%2Ftest%2Fpath", "/api/2.0/workspace/list?path=%2FUsers%2Fuser@example.com%2Fproject"},
want: nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qa.AssertMultipleRequestsWithMockServer(t, tt.args, []string{http.MethodGet, http.MethodGet}, tt.wantURI, []interface{}{&args{}}, tt.response, tt.responseStatus, tt.want, tt.wantErr, func(client *common.DatabricksClient) (interface{}, error) {
return NewNotebooksAPI(client).List(tt.args[0].(*args).Path, tt.args[0].(*args).Recursive)
})
})
}
}
func TestNotebooksAPI_Read(t *testing.T) {
type args struct {
Path string `json:"path"`
}
tests := []struct {
name string
response string
args args
responseStatus int
wantURI string
want WorkspaceObjectStatus
wantErr bool
}{
{
name: "Read test",
response: `{
"path": "/Users/user@example.com/project/ScalaExampleNotebook",
"language": "SCALA",
"object_type": "NOTEBOOK",
"object_id": 789
}`,
args: args{
Path: "/test/path",
},
responseStatus: http.StatusOK,
want: WorkspaceObjectStatus{
ObjectID: 789,
ObjectType: Notebook,
Path: "/Users/user@example.com/project/ScalaExampleNotebook",
Language: Scala,
},
wantURI: "/api/2.0/workspace/get-status?path=%2Ftest%2Fpath",
wantErr: false,
},
{
name: "Read test failure",
response: ``,
args: args{
Path: "/test/path",
},
responseStatus: http.StatusBadRequest,
want: WorkspaceObjectStatus{},
wantURI: "/api/2.0/workspace/get-status?path=%2Ftest%2Fpath",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var input args
qa.AssertRequestWithMockServer(t, &tt.args, http.MethodGet, tt.wantURI, &input, tt.response, tt.responseStatus, tt.want, tt.wantErr, func(client *common.DatabricksClient) (interface{}, error) {
return NewNotebooksAPI(client).Read(tt.args.Path)
})
})
}
}
func TestNotebooksAPI_Export(t *testing.T) {
type args struct {
Path string `json:"path"`
Format ExportFormat `json:"format"`
}
tests := []struct {
name string
response string
args args
responseStatus int
wantURI string
want string
wantErr bool
}{
{
name: "Export test",
response: `{
"content": "Ly8gRGF0YWJyaWNrcyBub3RlYm9vayBzb3VyY2UKMSsx"
}`,
args: args{
Path: "/test/path",
Format: DBC,
},
responseStatus: http.StatusOK,
want: "Ly8gRGF0YWJyaWNrcyBub3RlYm9vayBzb3VyY2UKMSsx",
wantURI: "/api/2.0/workspace/export?format=DBC&path=%2Ftest%2Fpath",
wantErr: false,
},
{
name: "Export test failure",
response: ``,
args: args{
Path: "/test/path",
Format: DBC,
},
responseStatus: http.StatusBadRequest,
want: "",
wantURI: "/api/2.0/workspace/export?format=DBC&path=%2Ftest%2Fpath",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var input args
qa.AssertRequestWithMockServer(t, &tt.args, http.MethodGet, tt.wantURI, &input, tt.response, tt.responseStatus, tt.want, tt.wantErr, func(client *common.DatabricksClient) (interface{}, error) {
return NewNotebooksAPI(client).Export(tt.args.Path, tt.args.Format)
})
})
}
}
func TestUri(t *testing.T) {
uri := "https://sri-e2-test-workspace-3.cloud.databricks.com/api/2.0/workspace/export?format=DBC\u0026path=/demo-notebook-rbc"
t.Log(url.PathUnescape(uri))
}
// nolint this should be refactored to support dbc files
func convertZipBytesToCRC(b64 []byte) (string, error) {
r, err := zip.NewReader(bytes.NewReader(b64), int64(len(b64)))
if err != nil {
return "0", err
}
var totalSum int64
for _, f := range r.File {
if f.FileInfo().IsDir() == false {
file, err := f.Open()
if err != nil {
return "", err
}
crc, err := getDBCCheckSumForCommands(file)
if err != nil {
return "", err
}
totalSum += int64(crc)
}
}
return strconv.Itoa(int(totalSum)), nil
}
// nolint this should be refactored to support dbc files
func getDBCCheckSumForCommands(fileIO io.Reader) (int, error) {
var stringBuff bytes.Buffer
scanner := bufio.NewScanner(fileIO)
buf := make([]byte, 0, 64*1024)
scanner.Buffer(buf, 1024*1024)
for scanner.Scan() {
stringBuff.WriteString(scanner.Text())
}
jsonString := stringBuff.Bytes()
var notebook map[string]interface{}
err := json.Unmarshal(jsonString, ¬ebook)
if err != nil {
return 0, err
}
var commandsBuffer bytes.Buffer
commandsMap := map[int]string{}
commands := notebook["commands"].([]interface{})
for _, command := range commands {
commandsMap[int(command.(map[string]interface{})["position"].(float64))] = command.(map[string]interface{})["command"].(string)
}
keys := make([]int, 0, len(commandsMap))
for k := range commandsMap {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
commandsBuffer.WriteString(commandsMap[k])
}
return int(crc32.ChecksumIEEE(commandsBuffer.Bytes())), nil
}
|
package app
import (
"github.com/hashicorp/golang-lru/simplelru"
pTest "github.com/skos-ninja/truelayer-tech/svc/pokemon/services/pokeapi/test"
sTest "github.com/skos-ninja/truelayer-tech/svc/pokemon/services/shakespeare/test"
)
func newTestApp(pokemon, translation bool) *app {
pokeAPI := pTest.New(pokemon)
pLRU, _ := simplelru.NewLRU(1, nil)
shakespeare := sTest.New(translation)
sLRU, _ := simplelru.NewLRU(1, nil)
return &app{
pokeAPI: pokeAPI,
pokeLRU: pLRU,
shakespeare: shakespeare,
shakespeareLRU: sLRU,
}
}
|
// Unit tests for file configuration repository.
//
// @author TSS
package file
import (
"testing"
"github.com/mashmb/1pass/1pass-core/core/domain"
)
func setupFileConfigRepo() (*fileConfigRepo, *fileConfigRepo) {
return NewFileConfigRepo("../../../assets"), NewFileConfigRepo("")
}
func TestIsAvailable(t *testing.T) {
config, empty := setupFileConfigRepo()
expected := false
exist := empty.IsAvailable()
if exist != expected {
t.Errorf("FileExist() = %v; expected = %v", exist, expected)
}
expected = true
exist = config.IsAvailable()
if exist != expected {
t.Errorf("FileExist() = %v; expected = %v", exist, expected)
}
}
func TestGetDefaultVault(t *testing.T) {
config, empty := setupFileConfigRepo()
expected := "./assets/onepassword_data"
vault := config.GetDefaultVault()
if vault != expected {
t.Errorf("GetDefaultVault() = %v; expected = %v", vault, expected)
}
vault = empty.GetDefaultVault()
if vault != "" {
t.Errorf("GetDefaultVault() = %v; expected = %v", vault, "")
}
}
func TestGetTimeout(t *testing.T) {
config, empty := setupFileConfigRepo()
expected := 1
timeout := empty.GetTimeout()
if timeout != expected {
t.Errorf("GetTimeout() = %d; expected = %d", timeout, expected)
}
expected = 10
timeout = config.GetTimeout()
if timeout != expected {
t.Errorf("GetTimeout() = %d; expected = %d", timeout, expected)
}
}
func TestGetUpdateNotification(t *testing.T) {
config, empty := setupFileConfigRepo()
expected := true
notification := empty.GetUpdateNotification()
if notification != expected {
t.Errorf("GetUpdateNotification() = %v; expected = %v", notification, expected)
}
expected = false
notification = config.GetUpdateNotification()
if notification != expected {
t.Errorf("GetUpdateNotification() = %v; expected = %v", notification, expected)
}
}
func TestGetUpdatePeriod(t *testing.T) {
config, empty := setupFileConfigRepo()
expected := 1
period := empty.GetUpdatePeriod()
if period != expected {
t.Errorf("GetUpdatePeriod() = %d; expected = %d", period, expected)
}
expected = 7
period = config.GetUpdatePeriod()
if period != expected {
t.Errorf("GetUpdatePeriod() = %d; expected = %d", period, expected)
}
}
func TestLoadConfigFile(t *testing.T) {
config := loadConfigFile("")
if len(config) != 0 {
t.Error("loadConfigFile() should fail because config file do not exist")
}
config = loadConfigFile("../../../assets")
if len(config) == 0 {
t.Error("loadConfigFile() should pass because config file exist")
}
}
func TestSave(t *testing.T) {
config, _ := setupFileConfigRepo()
expected := ""
conf := domain.NewConfig(10, 7, false, "")
config.Save(conf)
vault := config.GetDefaultVault()
if vault != expected {
t.Errorf("Save() = %v; expected = %v", vault, expected)
}
expected = "./assets/onepassword_data"
conf.Vault = "./assets/onepassword_data"
config.Save(conf)
vault = config.GetDefaultVault()
if vault != expected {
t.Errorf("Save() = %v; expected = %v", vault, expected)
}
}
|
//
// Copyright (c) 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package virtcontainers
import (
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/vishvananda/netlink"
)
const fileMode0640 = os.FileMode(0640)
func TestVhostUserSocketPath(t *testing.T) {
// First test case: search for existing:
addresses := []netlink.Addr{
{
IPNet: &net.IPNet{
IP: net.IPv4(192, 168, 0, 2),
Mask: net.IPv4Mask(192, 168, 0, 2),
},
},
{
IPNet: &net.IPNet{
IP: net.IPv4(192, 168, 0, 1),
Mask: net.IPv4Mask(192, 168, 0, 1),
},
},
}
expectedPath := "/tmp/vhostuser_192.168.0.1"
expectedFileName := "vhu.sock"
expectedResult := fmt.Sprintf("%s/%s", expectedPath, expectedFileName)
err := os.Mkdir(expectedPath, 0777)
if err != nil {
t.Fatal(err)
}
_, err = os.Create(expectedResult)
if err != nil {
t.Fatal(err)
}
netinfo := NetworkInfo{
Addrs: addresses,
}
path, _ := vhostUserSocketPath(netinfo)
if path != expectedResult {
t.Fatalf("Got %+v\nExpecting %+v", path, expectedResult)
}
// Second test case: search doesn't include matching vsock:
addressesFalse := []netlink.Addr{
{
IPNet: &net.IPNet{
IP: net.IPv4(192, 168, 0, 4),
Mask: net.IPv4Mask(192, 168, 0, 4),
},
},
}
netinfoFail := NetworkInfo{
Addrs: addressesFalse,
}
path, _ = vhostUserSocketPath(netinfoFail)
if path != "" {
t.Fatalf("Got %+v\nExpecting %+v", path, "")
}
err = os.Remove(expectedResult)
if err != nil {
t.Fatal(err)
}
err = os.Remove(expectedPath)
if err != nil {
t.Fatal(err)
}
}
func TestIsVFIO(t *testing.T) {
type testData struct {
path string
expected bool
}
data := []testData{
{"/dev/vfio/16", true},
{"/dev/vfio/1", true},
{"/dev/vfio/", false},
{"/dev/vfio", false},
{"/dev/vf", false},
{"/dev", false},
{"/dev/vfio/vfio", false},
{"/dev/vfio/vfio/12", false},
}
for _, d := range data {
isVFIO := isVFIO(d.path)
assert.Equal(t, d.expected, isVFIO)
}
}
func TestIsBlock(t *testing.T) {
type testData struct {
devType string
expected bool
}
data := []testData{
{"b", true},
{"c", false},
{"u", false},
}
for _, d := range data {
isBlock := isBlock(DeviceInfo{DevType: d.devType})
assert.Equal(t, d.expected, isBlock)
}
}
func TestCreateDevice(t *testing.T) {
devInfo := DeviceInfo{
HostPath: "/dev/vfio/8",
DevType: "b",
}
device := createDevice(devInfo)
_, ok := device.(*VFIODevice)
assert.True(t, ok)
devInfo.HostPath = "/dev/sda"
device = createDevice(devInfo)
_, ok = device.(*BlockDevice)
assert.True(t, ok)
devInfo.HostPath = "/dev/tty"
devInfo.DevType = "c"
device = createDevice(devInfo)
_, ok = device.(*GenericDevice)
assert.True(t, ok)
}
func TestNewDevices(t *testing.T) {
savedSysDevPrefix := sysDevPrefix
major := int64(252)
minor := int64(3)
tmpDir, err := ioutil.TempDir("", "")
assert.Nil(t, err)
sysDevPrefix = tmpDir
defer func() {
os.RemoveAll(tmpDir)
sysDevPrefix = savedSysDevPrefix
}()
path := "/dev/vfio/2"
deviceInfo := DeviceInfo{
ContainerPath: "",
Major: major,
Minor: minor,
UID: 2,
GID: 2,
DevType: "c",
}
_, err = newDevices([]DeviceInfo{deviceInfo})
assert.NotNil(t, err)
format := strconv.FormatInt(major, 10) + ":" + strconv.FormatInt(minor, 10)
ueventPathPrefix := filepath.Join(sysDevPrefix, "char", format)
ueventPath := filepath.Join(ueventPathPrefix, "uevent")
// Return true for non-existent /sys/dev path.
deviceInfo.ContainerPath = path
_, err = newDevices([]DeviceInfo{deviceInfo})
assert.Nil(t, err)
err = os.MkdirAll(ueventPathPrefix, dirMode)
assert.Nil(t, err)
// Should return error for bad data in uevent file
content := []byte("nonkeyvaluedata")
err = ioutil.WriteFile(ueventPath, content, fileMode0640)
assert.Nil(t, err)
_, err = newDevices([]DeviceInfo{deviceInfo})
assert.NotNil(t, err)
content = []byte("MAJOR=252\nMINOR=3\nDEVNAME=vfio/2")
err = ioutil.WriteFile(ueventPath, content, fileMode0640)
assert.Nil(t, err)
devices, err := newDevices([]DeviceInfo{deviceInfo})
assert.Nil(t, err)
assert.Equal(t, len(devices), 1)
vfioDev, ok := devices[0].(*VFIODevice)
assert.True(t, ok)
assert.Equal(t, vfioDev.DeviceInfo.HostPath, path)
assert.Equal(t, vfioDev.DeviceInfo.ContainerPath, path)
assert.Equal(t, vfioDev.DeviceInfo.DevType, "c")
assert.Equal(t, vfioDev.DeviceInfo.Major, major)
assert.Equal(t, vfioDev.DeviceInfo.Minor, minor)
assert.Equal(t, vfioDev.DeviceInfo.UID, uint32(2))
assert.Equal(t, vfioDev.DeviceInfo.GID, uint32(2))
}
func TestGetBDF(t *testing.T) {
type testData struct {
deviceStr string
expectedBDF string
}
data := []testData{
{"0000:02:10.0", "02:10.0"},
{"0000:0210.0", ""},
{"test", ""},
{"", ""},
}
for _, d := range data {
deviceBDF, err := getBDF(d.deviceStr)
assert.Equal(t, d.expectedBDF, deviceBDF)
if d.expectedBDF == "" {
assert.NotNil(t, err)
} else {
assert.Nil(t, err)
}
}
}
func TestAttachVFIODevice(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "")
assert.Nil(t, err)
os.RemoveAll(tmpDir)
testFDIOGroup := "2"
testDeviceBDFPath := "0000:00:1c.0"
devicesDir := filepath.Join(tmpDir, testFDIOGroup, "devices")
err = os.MkdirAll(devicesDir, dirMode)
assert.Nil(t, err)
deviceFile := filepath.Join(devicesDir, testDeviceBDFPath)
_, err = os.Create(deviceFile)
assert.Nil(t, err)
savedIOMMUPath := sysIOMMUPath
sysIOMMUPath = tmpDir
defer func() {
sysIOMMUPath = savedIOMMUPath
}()
path := filepath.Join(vfioPath, testFDIOGroup)
deviceInfo := DeviceInfo{
HostPath: path,
ContainerPath: path,
DevType: "c",
}
device := createDevice(deviceInfo)
_, ok := device.(*VFIODevice)
assert.True(t, ok)
hypervisor := &mockHypervisor{}
err = device.attach(hypervisor, &Container{})
assert.Nil(t, err)
err = device.detach(hypervisor)
assert.Nil(t, err)
}
func TestAttachGenericDevice(t *testing.T) {
path := "/dev/tty2"
deviceInfo := DeviceInfo{
HostPath: path,
ContainerPath: path,
DevType: "c",
}
device := createDevice(deviceInfo)
_, ok := device.(*GenericDevice)
assert.True(t, ok)
hypervisor := &mockHypervisor{}
err := device.attach(hypervisor, &Container{})
assert.Nil(t, err)
err = device.detach(hypervisor)
assert.Nil(t, err)
}
func TestAttachBlockDevice(t *testing.T) {
fs := &filesystem{}
hypervisor := &mockHypervisor{}
hConfig := HypervisorConfig{
BlockDeviceDriver: VirtioBlock,
}
config := &PodConfig{
HypervisorConfig: hConfig,
}
pod := &Pod{
id: testPodID,
storage: fs,
hypervisor: hypervisor,
config: config,
}
contID := "100"
container := Container{
pod: pod,
id: contID,
}
// create state file
path := filepath.Join(runStoragePath, testPodID, container.ID())
err := os.MkdirAll(path, dirMode)
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(path)
stateFilePath := filepath.Join(path, stateFile)
os.Remove(stateFilePath)
_, err = os.Create(stateFilePath)
if err != nil {
t.Fatal(err)
}
defer os.Remove(stateFilePath)
path = "/dev/hda"
deviceInfo := DeviceInfo{
HostPath: path,
ContainerPath: path,
DevType: "b",
}
device := createDevice(deviceInfo)
_, ok := device.(*BlockDevice)
assert.True(t, ok)
container.state.State = ""
err = device.attach(hypervisor, &container)
assert.Nil(t, err)
err = device.detach(hypervisor)
assert.Nil(t, err)
container.state.State = StateReady
err = device.attach(hypervisor, &container)
assert.Nil(t, err)
err = device.detach(hypervisor)
assert.Nil(t, err)
container.pod.config.HypervisorConfig.BlockDeviceDriver = VirtioSCSI
err = device.attach(hypervisor, &container)
assert.Nil(t, err)
err = device.detach(hypervisor)
assert.Nil(t, err)
container.state.State = StateReady
err = device.attach(hypervisor, &container)
assert.Nil(t, err)
err = device.detach(hypervisor)
assert.Nil(t, err)
}
|
package consumers
import (
"testing"
)
func TestShouldSkipRecord(t *testing.T) {
var tests = []struct {
offset int64
skip int64
parseKey bool
key []byte
expected bool
err bool
}{
// no keys
{offset: 0, skip: 0, parseKey: false, key: make([]byte, 0), expected: false},
{offset: 1, skip: 1, parseKey: false, key: make([]byte, 0), expected: true},
{offset: 1, skip: 2, parseKey: false, key: make([]byte, 0), expected: true},
{offset: 2, skip: 1, parseKey: false, key: make([]byte, 0), expected: false},
// with parse key
{offset: 0, skip: 0, parseKey: true, key: []byte("k"), expected: false},
{offset: 1, skip: 1, parseKey: true, key: []byte("k"), expected: true},
{offset: 1, skip: 2, parseKey: true, key: []byte("k"), expected: true},
{offset: 2, skip: 1, parseKey: true, key: []byte("k"), expected: false},
// failure parse key
{offset: 0, skip: 0, parseKey: true, key: make([]byte, 0), expected: false, err: true},
}
for _, v := range tests {
shouldSkip, err := shouldSkipRecord(v.offset, v.skip, v.parseKey, &v.key)
if err != nil && !v.err {
t.Errorf("Unexpected error %s", err)
}
if shouldSkip != v.expected {
t.Errorf("Should skip: %t, Expected: %t. Offset: %d, Skip: %d, ParseKey: %t, Key: %s",
shouldSkip,
v.expected,
v.offset,
v.skip,
v.parseKey,
v.key,
)
}
}
}
func TestShouldStopConsuming(t *testing.T) {
var tests = []struct {
partitionCount int
totalPartitions int
expected bool
}{
{partitionCount: 0, totalPartitions: 0, expected: true},
{partitionCount: 1, totalPartitions: 0, expected: true},
{partitionCount: 0, totalPartitions: 1, expected: false},
{partitionCount: 1, totalPartitions: 2, expected: false},
{partitionCount: 2, totalPartitions: 2, expected: true},
{partitionCount: 3, totalPartitions: 2, expected: true},
}
for _, v := range tests {
shouldStop := shouldStopConsuming(v.partitionCount, v.totalPartitions)
if v.expected != shouldStop {
t.Errorf("Expected stop: %t but got stop %t. For %+v", v.expected, shouldStop, v)
}
}
}
|
// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package reporter
import (
"github.com/pingcap/tidb/metrics"
"github.com/prometheus/client_golang/prometheus"
)
// reporter metrics vars
var (
IgnoreExceedSQLCounter prometheus.Counter
IgnoreExceedPlanCounter prometheus.Counter
IgnoreCollectChannelFullCounter prometheus.Counter
IgnoreCollectStmtChannelFullCounter prometheus.Counter
IgnoreReportChannelFullCounter prometheus.Counter
ReportAllDurationSuccHistogram prometheus.Observer
ReportAllDurationFailedHistogram prometheus.Observer
ReportRecordDurationSuccHistogram prometheus.Observer
ReportRecordDurationFailedHistogram prometheus.Observer
ReportSQLDurationSuccHistogram prometheus.Observer
ReportSQLDurationFailedHistogram prometheus.Observer
ReportPlanDurationSuccHistogram prometheus.Observer
ReportPlanDurationFailedHistogram prometheus.Observer
TopSQLReportRecordCounterHistogram prometheus.Observer
TopSQLReportSQLCountHistogram prometheus.Observer
TopSQLReportPlanCountHistogram prometheus.Observer
)
func init() {
InitMetricsVars()
}
// InitMetricsVars init topsql reporter metrics vars.
func InitMetricsVars() {
IgnoreExceedSQLCounter = metrics.TopSQLIgnoredCounter.WithLabelValues("ignore_exceed_sql")
IgnoreExceedPlanCounter = metrics.TopSQLIgnoredCounter.WithLabelValues("ignore_exceed_plan")
IgnoreCollectChannelFullCounter = metrics.TopSQLIgnoredCounter.WithLabelValues("ignore_collect_channel_full")
IgnoreCollectStmtChannelFullCounter = metrics.TopSQLIgnoredCounter.WithLabelValues("ignore_collect_stmt_channel_full")
IgnoreReportChannelFullCounter = metrics.TopSQLIgnoredCounter.WithLabelValues("ignore_report_channel_full")
ReportAllDurationSuccHistogram = metrics.TopSQLReportDurationHistogram.WithLabelValues("all", metrics.LblOK)
ReportAllDurationFailedHistogram = metrics.TopSQLReportDurationHistogram.WithLabelValues("all", metrics.LblError)
ReportRecordDurationSuccHistogram = metrics.TopSQLReportDurationHistogram.WithLabelValues("record", metrics.LblOK)
ReportRecordDurationFailedHistogram = metrics.TopSQLReportDurationHistogram.WithLabelValues("record", metrics.LblError)
ReportSQLDurationSuccHistogram = metrics.TopSQLReportDurationHistogram.WithLabelValues("sql", metrics.LblOK)
ReportSQLDurationFailedHistogram = metrics.TopSQLReportDurationHistogram.WithLabelValues("sql", metrics.LblError)
ReportPlanDurationSuccHistogram = metrics.TopSQLReportDurationHistogram.WithLabelValues("plan", metrics.LblOK)
ReportPlanDurationFailedHistogram = metrics.TopSQLReportDurationHistogram.WithLabelValues("plan", metrics.LblError)
TopSQLReportRecordCounterHistogram = metrics.TopSQLReportDataHistogram.WithLabelValues("record")
TopSQLReportSQLCountHistogram = metrics.TopSQLReportDataHistogram.WithLabelValues("sql")
TopSQLReportPlanCountHistogram = metrics.TopSQLReportDataHistogram.WithLabelValues("plan")
}
|
package main
import "fmt"
func reduce(s string) (r string) {
for i := 0; i < len(s); i++ {
if i < len(s)-1 && s[i] == s[i+1] {
i++
} else {
r += string(s[i])
}
}
return r
}
func isUpper(c byte) bool {
return c >= 'A' && c <= 'Z'
}
func countCamelCaseWords(s string) int {
if len(s) == 0 {
return 0
}
wordCnt := 1
for i := 0; i < len(s); i++ {
if isUpper(s[i]) {
wordCnt++
}
}
return wordCnt
}
func main() {
var s string
fmt.Scanf("%s", &s)
fmt.Println(countCamelCaseWords(s))
}
|
package v1alpha1
import (
dbmodels "github.com/xinsnake/databricks-sdk-golang/azure/models"
)
// ClusterSpec is similar to dbmodels.ClusterSpec, the reason it
// exists is because dbmodels.ClusterSpec doesn't support ExistingClusterName
// ExistingClusterName allows discovering databricks clusters by it's kubernetese object name
type ClusterSpec struct {
ExistingClusterID string `json:"existing_cluster_id,omitempty" url:"existing_cluster_id,omitempty"`
ExistingClusterName string `json:"existing_cluster_name,omitempty" url:"existing_cluster_name,omitempty"`
NewCluster *dbmodels.NewCluster `json:"new_cluster,omitempty" url:"new_cluster,omitempty"`
Libraries []dbmodels.Library `json:"libraries,omitempty" url:"libraries,omitempty"`
}
// ToK8sClusterSpec converts a databricks ClusterSpec object to k8s ClusterSpec object.
// It is needed to add ExistingClusterName and follow k8s camleCase naming convention
func ToK8sClusterSpec(dbjs *dbmodels.ClusterSpec) ClusterSpec {
var k8sjs ClusterSpec
k8sjs.ExistingClusterID = dbjs.ExistingClusterID
k8sjs.NewCluster = dbjs.NewCluster
k8sjs.Libraries = dbjs.Libraries
return k8sjs
}
// ToDatabricksClusterSpec converts a k8s ClusterSpec object to a DataBricks ClusterSpec object.
// It is needed to add ExistingClusterName and follow k8s camleCase naming convention
func ToDatabricksClusterSpec(k8sjs *ClusterSpec) dbmodels.ClusterSpec {
var dbjs dbmodels.ClusterSpec
dbjs.ExistingClusterID = k8sjs.ExistingClusterID
dbjs.NewCluster = k8sjs.NewCluster
dbjs.Libraries = k8sjs.Libraries
return dbjs
}
|
package main
import (
pb "example/communication"
"fmt"
"log"
"net"
myerr "example/error"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
// Define localhost address infomation
const (
address = "127.0.0.1"
defaultname = "server"
port = 6666
)
// set ip
var ip = pb.IP{
Addr: address,
Name: defaultname,
Port: port,
}
type server struct{}
// Implement CommunicationServer interface.
func (s *server) Greet(ctxx context.Context, in *pb.GreetRequest) (*pb.GreetReply, error) {
// Validate GreetRequest
if err := in.Validate(); err != nil {
// If validation failed, server return error message.
log.Printf("Illegal GreetRequest: %v\n", err)
return nil, err /*myerr.GRError{Code: 5000, Message: "greet error"}*/
}
// Print GreetRequest
s.printGreetRequest(in)
//return &pb.GreetReply{Ip: &ip, Message: in.GetIp().GetName() + "! Hello! Connect successfully!"}, nil
return &pb.GreetReply{Ip: &ip, Message: "Hello"}, nil
}
func (s *server) Login(ctx context.Context, in *pb.AccessRequest) (*pb.AccessReply, error) {
// Validate AccessRequest
if err := in.Validate(); err != nil {
// If validation failed, server should return error message.
log.Printf("Fail to login: %v\n", err)
return nil, myerr.LRError{Code: 5000, Message: "login error"}
}
// Print AccessRequest
s.printAccessRequest(in)
return &pb.AccessReply{Ip: &ip, Message: "FeedBack: LOGIN SUCCESS!"}, nil
}
// Print GreetRequest
func (s *server) printGreetRequest(in *pb.GreetRequest) {
log.Println("~~~~~~~~~ Receive Greet Request ~~~~~~~~~")
/*
fmt.Println("Request from: ", in.GetIp().GetAddr(), ":", in.GetIp().GetPort(), in.GetIp().GetName())
fmt.Println("ID: ", in.GetId())
fmt.Println("Message: ", in.GetMessage())
fmt.Println("Num: wheel.Double: ", in.Num.Value)
*/
fmt.Println("doublenum: ", in.Doublenum.Value)
fmt.Println("floatnum: ", in.Floatnum.Value)
fmt.Println("int64num: ", in.Int64Num.Value)
fmt.Println("uint64num: ", in.Uint64Num.Value)
fmt.Println("int32num: ", in.Int32Num.Value)
fmt.Println("uint32num: ", in.Uint32Num.Value)
fmt.Println("str: ", in.Str.Value)
fmt.Println("bytes: ", string(in.B.Value))
fmt.Println("bool: ", in.Bo.Value)
}
// Print AccessRequest
func (s *server) printAccessRequest(in *pb.AccessRequest) {
log.Println("~~~~~~~~~ Receive Login Access Request ~~~~~~~~~")
fmt.Println("Request from: ", in.GetIp().GetAddr(), ":", in.GetIp().GetPort(), in.GetIp().GetName())
fmt.Println("Email: ", in.GetEmail().GetEmail())
fmt.Println("Chinese: ", in.GetIsCN())
}
func main() {
fmt.Println("=============== Here is", ip.GetName(), "(", ip.GetAddr(), ":", ip.GetPort(), ") ===============")
lis, err := net.Listen("tcp", "localhost:6666") // Listen localhost port, tcp
if err != nil {
log.Fatalf("Fail to listen port: %v", err)
}
s := grpc.NewServer() // Create a gRPC server which has no service registered and has not started to accept requests yet.
// Register a service and its implementation to the gRPC server.
pb.RegisterCommunicationServer(s, &server{})
reflection.Register(s) // Register the server reflection service on the given gRPC server.
// Serve accepts incoming connections on the listener lis, creating a new
// ServerTransport and service goroutine for each. The service goroutines
// read gRPC requests and then call the registered handlers to reply to them.
if err := s.Serve(lis); err != nil {
log.Fatalf("Failed to serve: %v", err)
}
}
|
package auth
import (
"fmt"
sdk "github.com/irisnet/irishub/types"
)
// GenesisState - all auth state that must be provided at genesis
type GenesisState struct {
CollectedFees sdk.Coins `json:"collected_fee"`
FeeAuth FeeAuth `json:"data"`
Params Params `json:"params"`
}
// Create a new genesis state
func NewGenesisState(collectedFees sdk.Coins, feeAuth FeeAuth, params Params) GenesisState {
return GenesisState{
CollectedFees: collectedFees,
FeeAuth: feeAuth,
Params: params,
}
}
// Return a default genesis state
func DefaultGenesisState() GenesisState {
return GenesisState{
CollectedFees: nil,
FeeAuth: InitialFeeAuth(),
Params: DefaultParams(),
}
}
// Init store state from genesis data
func InitGenesis(ctx sdk.Context, keeper FeeKeeper, ak AccountKeeper, data GenesisState) {
if err := ValidateGenesis(data); err != nil {
panic(err)
}
keeper.setCollectedFees(ctx, data.CollectedFees)
ak.IncreaseTotalLoosenToken(ctx, data.CollectedFees)
keeper.SetFeeAuth(ctx, data.FeeAuth)
keeper.SetParamSet(ctx, data.Params)
ak.InitTotalSupply(ctx)
}
// ExportGenesis returns a GenesisState for a given context and keeper
func ExportGenesis(ctx sdk.Context, keeper FeeKeeper, ak AccountKeeper) GenesisState {
collectedFees := keeper.GetCollectedFees(ctx)
feeAuth := keeper.GetFeeAuth(ctx)
params := keeper.GetParamSet(ctx)
return NewGenesisState(collectedFees, feeAuth, params)
}
func ValidateGenesis(data GenesisState) error {
err := validateParams(data.Params)
if err != nil {
return err
}
err = ValidateFee(data.CollectedFees)
if err != nil {
return err
}
return nil
}
func ValidateFee(collectedFee sdk.Coins) error {
if collectedFee == nil || collectedFee.Empty() {
return nil
}
if !collectedFee.IsValidIrisAtto() {
return sdk.ErrInvalidCoins(fmt.Sprintf("invalid collected fees [%s]", collectedFee))
}
return nil
}
|
package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"testing"
"time"
"github.com/giuseppe7/diane/internal"
)
func TestInitObservability(t *testing.T) {
initObservability()
tr := &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 10 * time.Second,
}
httpClient := &http.Client{
Transport: tr,
Timeout: 10 * time.Second,
}
url := fmt.Sprintf("http://0.0.0.0%s/%s", internal.ApplicationMetricsEndpointPort, internal.ApplicationMetricsEndpoint)
req, _ := http.NewRequest("GET", url, nil)
resp, err := httpClient.Do(req)
if err != nil {
t.Errorf("expected to be able to reach the metrics endpoint")
return
} else if resp.StatusCode != 200 {
t.Errorf("connected but received non-200 status code %d", resp.StatusCode)
return
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("unexpected error reading the response body")
return
}
bodyString := string(bodyBytes)
r := regexp.MustCompile(`.*_version_info (\d.*?)`)
if len(r.FindStringSubmatch(bodyString)) == 0 {
t.Errorf("expecting to find the version_info in the metrics endpoint")
}
defer resp.Body.Close()
}
|
// A Tour of Go : Flow control statements: for, if, else, switch and defer
// https://to-tour-jp.appspot.com.list/flowcontrol/1
package main
import (
"fmt"
"math"
"runtime"
"time"
)
func main() {
{
// for ループ
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println("1-1. ", sum)
// 初期化と後処理ステートメントの記述は省略可
// セミコロンも省略可
for sum < 1000 {
sum += sum
}
fmt.Println("1-2. ", sum)
}
{
// if ステートメント
fmt.Println("2-1. ", sqrt(2), sqrt(-4))
fmt.Println("2-2. ", pow(3, 2, 10), pow(3, 3, 20))
}
{
// switch ステートメント
// Goでは選択されたcaseだけを実行して、それに続くcaseは実行されない
// caseの最後に必要なbreakステートメントが、goでは自動的に提供される
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("3-1. ", "OS X")
case "linux":
fmt.Println("3-1. ", "Linux")
default:
fmt.Printf("3-1. %s\n", os)
}
// switch case は上から下へとcase を評価する
// case 条件が一致すれば、そこで停止する
today := time.Now().Weekday()
switch time.Saturday {
case today + 0:
fmt.Println("3-2. ", "Today")
case today + 2:
fmt.Println("3-2. ", "Tomorrow")
case today + 2:
fmt.Println("3-2. ", "In two days")
default:
fmt.Println("3-2. ", "Too far away")
}
}
{
// defer
// defer ステートメントは、defer へ渡した関数の実行を、呼び出し元の関数の終わりまで遅延させる。
// 渡した関数が複数ある場合、その呼び出しはスタックされ、last-in-first-out(最後に追加したものから)の順番で実行される
defer fmt.Println("4-1. ", "Hello")
defer fmt.Println("4-2. ", "World")
fmt.Println("4-3. ", "!!")
}
}
func sqrt(x float64) string {
if x < 0 {
return sqrt(-x) + "i"
}
return fmt.Sprint(math.Sqrt(x))
}
func pow(x, n, lim float64) float64 {
// if ステートメントは、for ループのように、評価するための簡単なステートメントを書くことができる
// ここで宣言された変数は、if のスコープ内でのみ有効
if v := math.Pow(x, n); v < lim {
return v
} else {
// }
// else {
// だとエラー扱い
//fmt.Printf("\t %g >= %g\n", v, lim)
}
return lim
}
|
package handlers
import (
"github.com/gorilla/context"
"github.com/roger-king/go-ecommerce/pkg/models"
"github.com/roger-king/go-ecommerce/pkg/utilities"
"github.com/sirupsen/logrus"
"net/http"
)
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if len(token) > 0 {
authedUser := models.Validate(models.JwtToken{Token: token})
context.Set(r, 'user', authedUser)
next.ServeHTTP(w, r)
} else {
utilities.RespondWithError(w, http.StatusUnauthorized, "not authorized")
}
})
}
|
package mockery
import "github.com/mitooos/thesis/mockery/model"
type UserRepository interface {
InsertUser(*model.User) error
}
type SecurityHelper interface {
HashPassword(string) (string, error)
}
type service struct {
repository UserRepository
securtiyHelper SecurityHelper
}
func (s *service) InsertUser(u *model.User) error {
var err error
u.Password, err = s.securtiyHelper.HashPassword(u.Password)
if err != nil {
return err
}
return s.repository.InsertUser(u)
}
|
package generated
type Object struct {
tableName struct{} `sql:"foo"`
ID string `json:"id" sql:"type:uuid,default:gen_random_uuid()"`
CreatedBy string `json:"createdBy"`
CreatedAt string `json:"createdAt" sql:"default:now()"`
Foo bool `json:"foo"`
Bar float64 `json:"bar"`
Baz int32 `json:"baz"`
Qux string `json:"qux"`
CamelCase string `json:"camelCase"`
}
|
package queue
import (
"encoding/json"
"errors"
"math"
"time"
"github.com/spf13/viper"
"github.com/steam-authority/steam-authority/logging"
"github.com/streadway/amqp"
)
const (
QueueApps = "Steam_Apps"
QueueAppsData = "Steam_Apps_Data"
QueueChangesData = "Steam_Changes_Data"
QueueDelaysData = "Steam_Delays_Data"
QueuePackages = "Steam_Packages"
QueuePackagesData = "Steam_Packages_Data"
QueueProfiles = "Steam_Profiles"
QueueProfilesData = "Steam_Profiles_Data"
)
var (
queues = map[string]rabbitMessageBase{}
errInvalidQueue = errors.New("invalid queue")
errEmptyMessage = errors.New("empty message")
rabbitDSN string
consumerConnection *amqp.Connection
consumerCloseChannel chan *amqp.Error
producerConnection *amqp.Connection
producerCloseChannel chan *amqp.Error
)
type queueInterface interface {
getQueueName() (string)
getRetryData() (RabbitMessageDelay)
process(msg amqp.Delivery) (ack bool, requeue bool, err error)
}
func init() {
consumerCloseChannel = make(chan *amqp.Error)
producerCloseChannel = make(chan *amqp.Error)
qs := []rabbitMessageBase{
//{Message: RabbitMessageApp{}},
{Message: RabbitMessageChanges{}},
//{Message: RabbitMessageDelay{}},
//{Message: RabbitMessagePackage{}},
//{Message: RabbitMessageProfile{}},
}
for _, v := range qs {
queues[v.Message.getQueueName()] = v
}
}
func Init() {
user := viper.GetString("RABBIT_USER")
pass := viper.GetString("RABBIT_PASS")
host := viper.GetString("RABBIT_HOST")
port := viper.GetString("RABBIT_PORT")
rabbitDSN = "amqp://" + user + ":" + pass + "@" + host + ":" + port
}
func RunConsumers() {
for _, v := range queues {
go v.consume()
}
}
func Produce(queue string, data []byte) (err error) {
if val, ok := queues[queue]; ok {
return val.produce(data)
}
return errInvalidQueue
}
type rabbitMessageBase struct {
Message queueInterface
Attempt int
StartTime time.Time // Time first placed in delay queue
EndTime time.Time // Time to retry from delay queue
}
func (s rabbitMessageBase) getQueue(conn *amqp.Connection) (ch *amqp.Channel, qu amqp.Queue, err error) {
ch, err = conn.Channel()
logging.Error(err)
qu, err = ch.QueueDeclare(s.Message.getQueueName(), true, false, false, false, nil)
logging.Error(err)
return ch, qu, err
}
func (s rabbitMessageBase) produce(data []byte) (err error) {
logging.Info("Producing to: " + s.Message.getQueueName())
// Connect
if producerConnection == nil {
producerConnection, err = amqp.Dial(rabbitDSN)
producerConnection.NotifyClose(producerCloseChannel)
if err != nil {
return err
}
}
//
ch, qu, err := s.getQueue(producerConnection)
defer ch.Close()
if err != nil {
return err
}
err = ch.Publish("", qu.Name, false, false, amqp.Publishing{
DeliveryMode: amqp.Persistent,
ContentType: "application/json",
Body: data,
})
logging.Error(err)
return nil
}
func (s rabbitMessageBase) consume() {
logging.LocalInfo("Consuming from: " + s.Message.getQueueName())
var breakFor = false
var err error
for {
// Connect
if consumerConnection == nil {
consumerConnection, err = amqp.Dial(rabbitDSN)
consumerConnection.NotifyClose(consumerCloseChannel)
if err != nil {
logging.Error(err)
return
}
}
//
ch, qu, err := s.getQueue(consumerConnection)
if err != nil {
logging.Error(err)
return
}
msgs, err := ch.Consume(qu.Name, "", false, false, false, false, nil)
if err != nil {
logging.Error(err)
return
}
for {
select {
case err = <-consumerCloseChannel:
breakFor = true
break
case msg := <-msgs:
ack, requeue, err := s.Message.process(msg)
logging.Error(err)
if ack {
msg.Ack(false)
} else {
if requeue {
err = s.requeueMessage(msg)
logging.Error(err)
}
msg.Nack(false, false)
}
}
if breakFor {
break
}
}
//conn.Close()
ch.Close()
}
}
func (s rabbitMessageBase) requeueMessage(msg amqp.Delivery) error {
delayeMessage := rabbitMessageBase{
Attempt: s.Attempt,
StartTime: s.StartTime,
EndTime: s.EndTime,
Message: RabbitMessageDelay{
OriginalMessage: string(msg.Body),
OriginalQueue: s.Message.getQueueName(),
},
}
delayeMessage.IncrementAttempts()
data, err := json.Marshal(delayeMessage)
if err != nil {
return err
}
Produce(QueueDelaysData, data)
return nil
}
func (s *rabbitMessageBase) IncrementAttempts() {
// Increment attemp
s.Attempt++
// Update end time
var min float64 = 1
var max float64 = 600
var seconds = math.Pow(1.3, float64(s.Attempt))
var minmaxed = math.Min(min+seconds, max)
var rounded = math.Round(minmaxed)
s.EndTime = s.StartTime.Add(time.Second * time.Duration(rounded))
}
|
package kindergarten
import (
"errors"
"sort"
"strings"
)
type Garden map[string][]string
var plants = map[rune]string{
'R': "radishes",
'C': "clover",
'G': "grass",
'V': "violets",
}
func NewGarden(diagram string, children []string) (*Garden, error) {
g := Garden{}
if diagram[0] != '\n' {
return nil, errors.New("wrong format")
}
diagram = strings.ReplaceAll(diagram, "\n", "")
diagramRows := []string{diagram[:len(diagram)/2], diagram[len(diagram)/2:]}
var copyChildren = make([]string, len(children))
copy(copyChildren, children)
sort.Strings(copyChildren)
if len(diagramRows) != 2 || len(diagramRows[0])/2 != len(children) || len(diagramRows[0]) != len(diagramRows[1]) ||
len(diagramRows[0])%2 != 0 {
return nil, errors.New("mismatched rows")
}
for i, child := range copyChildren[1:] {
if copyChildren[i] == child {
return nil, errors.New("Child is listed twice ")
}
}
for _, row := range diagramRows {
for i, seed := range row {
seedStr, ok := plants[seed]
if !ok {
return nil, errors.New("invaid cup codes")
}
g[copyChildren[i/2]] = append(g[copyChildren[i/2]], seedStr)
}
}
return &g, nil
}
func (g *Garden) Plants(child string) ([]string, bool) {
garden := *g
plants, ok := garden[child]
return plants, ok
}
|
package balloc
import (
"errors"
"fmt"
"runtime"
"sync"
"sync/atomic"
"unsafe"
)
var (
ErrOutOfMemory = errors.New("Not enough space allocating memory")
ErrInvalidSize = errors.New("The requested size is invalid")
)
const maxBufferSize = 0x8000000000
const alignmentBytes = 8
const alignmentBytesMinusOne = alignmentBytes - 1
type MemoryManager interface {
Allocate(size uint64, zero bool) (uint64, error)
Deallocate(pos, size uint64) error
GetPtr(pos uint64) unsafe.Pointer
GetOffset(p unsafe.Pointer) uint64
GetUsed() uint64
GetFree() uint64
Lock()
Unlock()
}
// BufferAllocator allocates memory in a preallocated buffer
type BufferAllocator struct {
bufferPtr unsafe.Pointer
bufferSize uint64
header *header
headerLock uintptr
bufferMux sync.RWMutex
}
const magic uint32 = 0xca01af01
type header struct {
magic uint32
BufferStart uint32
PageSize uint16
DataWatermark uint64
FreePage uint64
TotalUsed uint64
}
type chunk struct {
nextFree uint64
size uint32
}
var chunkSize = uint64(unsafe.Sizeof(chunk{}))
type allocPreable struct {
size uint64
}
var allocPreableSize uint64 = uint64(unsafe.Sizeof(allocPreable{}))
// NewBufferAllocator created a new buffer allocator
func NewBufferAllocator(bufPtr unsafe.Pointer, bufSize uint64, firstFree uint64, pageSize uint16) (*BufferAllocator, error) {
if bufSize&alignmentBytesMinusOne != 0 {
return nil, ErrInvalidSize
}
buffer := &BufferAllocator{
bufferPtr: bufPtr,
bufferSize: bufSize,
}
firstFree = alignSize(firstFree)
buffer.header = (*header)(unsafe.Pointer(uintptr(bufPtr) + uintptr(firstFree)))
buffer.SetPageSize(pageSize)
if buffer.header.magic != magic {
dataStart := alignSize(firstFree + uint64(unsafe.Sizeof(*buffer.header)))
dataStart = buffer.GetPageOffset(dataStart + uint64(pageSize) - 1)
buffer.header.magic = magic
buffer.header.BufferStart = uint32(dataStart)
buffer.header.DataWatermark = dataStart
buffer.header.FreePage = 0
buffer.header.TotalUsed = 0
}
return buffer, nil
}
func (b *BufferAllocator) GetHeader() *header {
return b.header
}
func (b *BufferAllocator) SetPageSize(s uint16) {
b.header.PageSize = s
}
func (b *BufferAllocator) GetPageOffset(offset uint64) uint64 {
psize := uint64(b.header.PageSize)
return (offset / psize) * psize
}
func (b *BufferAllocator) Lock() {
b.bufferMux.RLock()
}
func (b *BufferAllocator) Unlock() {
b.bufferMux.RUnlock()
}
func (b *BufferAllocator) WLock() {
b.bufferMux.Lock()
}
func (b *BufferAllocator) WUnlock() {
b.bufferMux.Unlock()
}
func (b *BufferAllocator) headLock() {
for !atomic.CompareAndSwapUintptr(&b.headerLock, 0, 1) {
runtime.Gosched()
}
}
func (b *BufferAllocator) headUnlock() {
atomic.StoreUintptr(&b.headerLock, 0)
}
func (b *BufferAllocator) SetBuffer(bufPtr unsafe.Pointer, bufSize uint64, firstFree uint64) {
firstFree = alignSize(firstFree + uint64(uintptr(bufPtr)))
b.bufferPtr = bufPtr
b.bufferSize = bufSize
b.header = (*header)(unsafe.Pointer(uintptr(firstFree)))
}
func (b *BufferAllocator) GetFree() uint64 {
b.headLock()
defer b.headUnlock()
return b.bufferSize - b.header.DataWatermark
}
func (b *BufferAllocator) GetUsed() uint64 {
return atomic.LoadUint64(&b.header.TotalUsed)
}
func (b *BufferAllocator) GetCapacity() uint64 {
return b.bufferSize
}
func (b *BufferAllocator) GetPtr(pos uint64) unsafe.Pointer {
ret := unsafe.Pointer(uintptr(b.bufferPtr) + uintptr(pos))
return ret
}
func (b *BufferAllocator) GetOffset(p unsafe.Pointer) uint64 {
return uint64(uintptr(p) - uintptr(b.bufferPtr))
}
func (b *BufferAllocator) countSequensialFreePages(offset uint64) uint64 {
psize := uint64(b.header.PageSize)
for p := offset; ; p += psize {
l := (*chunk)(b.GetPtr(p))
l.nextFree = b.header.FreePage
b.header.FreePage = p
}
}
func (b *BufferAllocator) mergeChunks(offset uint64) uint64 {
psize := uint64(b.header.PageSize)
curOff := offset
for curOff != 0 {
curChunk := b.getChunk(curOff)
if curOff+uint64(curChunk.size)*psize == b.header.DataWatermark {
b.header.DataWatermark -= uint64(curChunk.size) * psize
curOff = curChunk.nextFree
continue
}
if curChunk.nextFree == 0 {
break
}
nextChunk := b.getChunk(curChunk.nextFree)
if curChunk.nextFree == curOff+uint64(curChunk.size)*psize {
curChunk.nextFree = nextChunk.nextFree
curChunk.size += nextChunk.size
continue
} else if curChunk.nextFree+uint64(nextChunk.size)*psize == curOff {
nextChunk.size += curChunk.size
curOff = curChunk.nextFree
continue
}
break
}
return curOff
}
// Allocate a new buffer of specific size
func (b *BufferAllocator) Allocate(size uint64, zero bool) (uint64, error) {
if size == 0 {
return 0, ErrInvalidSize
}
// Ensure alignement
size = alignSize(size)
psize := uint64(b.header.PageSize)
pagesNeeded := (size + psize - 1) / psize
b.headLock()
var p uint64
chunk := b.getChunk(b.header.FreePage)
if b.header.FreePage != 0 && chunk.size == uint32(pagesNeeded) {
p = b.header.FreePage
b.header.FreePage = chunk.nextFree
//println("allocate page", p, "new free", *l)
} else if b.header.FreePage != 0 && chunk.size > uint32(pagesNeeded) {
p = b.header.FreePage
newChunk := b.getChunk(p + pagesNeeded*psize)
newChunk.nextFree = chunk.nextFree
newChunk.size = chunk.size - uint32(pagesNeeded)
b.header.FreePage = p + pagesNeeded*psize
} else {
if b.header.DataWatermark+pagesNeeded*psize > b.bufferSize {
b.headUnlock()
return 0, ErrOutOfMemory
}
p = b.header.DataWatermark
b.header.DataWatermark += pagesNeeded * psize
}
b.headUnlock()
if zero {
buf := (*[maxBufferSize]byte)(b.GetPtr(p))[:size]
for i := range buf { // Optimized by the compiler to simple memclr
buf[i] = 0
}
}
atomic.AddUint64(&b.header.TotalUsed, pagesNeeded*psize)
// fmt.Printf("+ allocate %d bytes at %d\n", size, p)
return p, nil
}
func (b *BufferAllocator) Deallocate(offset, size uint64) error {
// Ensure alignement
size = alignSize(size)
psize := uint64(b.header.PageSize)
if offset%psize != 0 {
return fmt.Errorf("Free of non page aligned address %d (%d)", offset, offset%psize)
}
pagesNeeded := (size + psize - 1) / psize
atomic.AddUint64(&b.header.TotalUsed, ^uint64(pagesNeeded*psize-1))
// println("++ Freeing ", size, "at ", offset)
b.headLock()
l := b.getChunk(offset)
l.nextFree = b.header.FreePage
l.size = uint32(pagesNeeded)
b.header.FreePage = b.mergeChunks(offset)
b.headUnlock()
return nil
}
func (b *BufferAllocator) getChunk(offset uint64) *chunk {
if offset == 0 || offset > b.bufferSize-uint64(unsafe.Sizeof(chunk{})) {
return nil
}
return (*chunk)(unsafe.Pointer(uintptr(b.bufferPtr) + uintptr(offset)))
}
func (b *BufferAllocator) getPreample(offset uint64) *allocPreable {
offset -= allocPreableSize
if offset <= 0 || offset > b.bufferSize-allocPreableSize {
return nil
}
return (*allocPreable)(unsafe.Pointer(uintptr(b.bufferPtr) + uintptr(offset)))
}
func (b *BufferAllocator) PrintFreeChunks() {
chunkPos := b.header.FreePage
var c *chunk
i := 0
s := uint64(0)
fmt.Printf("---------------------------------------\n")
for chunkPos != 0 {
c = b.getChunk(chunkPos)
fmt.Printf("Free chunk %d to %d (pages: %d)\n", chunkPos, uint32(chunkPos)+c.size*uint32(b.header.PageSize), c.size)
chunkPos = c.nextFree
i++
s += uint64(c.size)
}
fmt.Printf("---------------------------------------\n")
fmt.Printf(" Total free chunks: %d\n", i)
fmt.Printf(" Total free pages : %d\n", s)
}
func alignSize(size uint64) uint64 {
if size&alignmentBytesMinusOne != 0 {
size += alignmentBytes
size &= ^uint64(alignmentBytesMinusOne)
}
return size
}
func rangeContains(offset, size, testOffset uint64) bool {
return testOffset >= offset && testOffset < offset+size
}
|
package main
import (
"fmt"
"github.com/valyala/fasthttp"
)
func main(){
fasthttp.ListenAndServe(":8080",requestHandler)
}
func requestHandler(ctx *fasthttp.RequestCtx){
fmt.Fprintf(ctx,"m:%q,user:%q\n",ctx.Method(),ctx.UserAgent())
}
|
package util
const (
VERSION = "0.72"
)
|
package modeltests
import (
"github.com/victorsteven/fullstack/api/models"
"log"
"testing"
_ "github.com/jinzhu/gorm/dialects/mysql"
"gopkg.in/go-playground/assert.v1"
)
func TestFindAllPosts(t *testing.T) {
err := refreshUserAndPostTable()
if err != nil {
log.Fatalf("Error refreshing user and post table %v\n", err)
}
_, _, err = seedUsersAndPosts()
if err != nil {
log.Fatalf("Error seeding user and post table %v\n", err)
}
posts, err := postInstance.FindAllPosts(server.DB)
if err != nil {
t.Errorf("this is the error getting the posts: %v\n", err)
return
}
assert.Equal(t, len(*posts), 2)
}
func TestSavePost(t *testing.T) {
err := refreshUserAndPostTable()
if err != nil {
log.Fatalf("Error user and post refreshing table %v\n", err)
}
user, err := seedOneUser()
if err != nil {
log.Fatalf("Cannot seed user %v\n", err)
}
newPost := models.Post{
ID: 1,
Title: "This is the title",
Content: "This is the content",
AuthorID: user.ID,
}
savedPost, err := newPost.SavePost(server.DB)
if err != nil {
t.Errorf("this is the error getting the post: %v\n", err)
return
}
assert.Equal(t, newPost.ID, savedPost.ID)
assert.Equal(t, newPost.Title, savedPost.Title)
assert.Equal(t, newPost.Content, savedPost.Content)
assert.Equal(t, newPost.AuthorID, savedPost.AuthorID)
}
func TestGetPostByID(t *testing.T) {
err := refreshUserAndPostTable()
if err != nil {
log.Fatalf("Error refreshing user and post table: %v\n", err)
}
post, err := seedOneUserAndOnePost()
if err != nil {
log.Fatalf("Error Seeding table")
}
foundPost, err := postInstance.FindPostByID(server.DB, post.ID)
if err != nil {
t.Errorf("this is the error getting one user: %v\n", err)
return
}
assert.Equal(t, foundPost.ID, post.ID)
assert.Equal(t, foundPost.Title, post.Title)
assert.Equal(t, foundPost.Content, post.Content)
}
func TestUpdateAPost(t *testing.T) {
err := refreshUserAndPostTable()
if err != nil {
log.Fatalf("Error refreshing user and post table: %v\n", err)
}
post, err := seedOneUserAndOnePost()
if err != nil {
log.Fatalf("Error Seeding table")
}
postUpdate := models.Post{
ID: 1,
Title: "modiUpdate",
Content: "modiupdate@gmail.com",
AuthorID: post.AuthorID,
}
updatedPost, err := postUpdate.UpdateAPost(server.DB, post.ID)
if err != nil {
t.Errorf("this is the error updating the user: %v\n", err)
return
}
assert.Equal(t, updatedPost.ID, postUpdate.ID)
assert.Equal(t, updatedPost.Title, postUpdate.Title)
assert.Equal(t, updatedPost.Content, postUpdate.Content)
assert.Equal(t, updatedPost.AuthorID, postUpdate.AuthorID)
}
func TestDeleteAPost(t *testing.T) {
err := refreshUserAndPostTable()
if err != nil {
log.Fatalf("Error refreshing user and post table: %v\n", err)
}
post, err := seedOneUserAndOnePost()
if err != nil {
log.Fatalf("Error Seeding tables")
}
isDeleted, err := postInstance.DeleteAPost(server.DB, post.ID, post.AuthorID)
if err != nil {
t.Errorf("this is the error updating the user: %v\n", err)
return
}
//one shows that the record has been deleted or:
// assert.Equal(t, int(isDeleted), 1)
//Can be done this way too
assert.Equal(t, isDeleted, int64(1))
}
|
package main
import (
"fmt"
"github.com/ParsePlatform/go.inject"
"os"
)
// Interfaces
type CARFACTORY interface {
makeCar() CAR
getMake() string
}
type CAR interface {
getModel() string
}
// Concrete implementations
type FordFactory struct {
car *FordMondeo `inject:""`
}
type FordMondeo struct {
}
func (s *FordMondeo) getModel() string {
return "Mondeo"
}
func (s FordFactory) makeCar() CAR {
return s.car
}
func (s FordFactory) getMake() string {
return "Ford"
}
// Main function
func main() {
var graph inject.Graph
var carFactory FordFactory
err := graph.Provide(
&inject.Object{Value: new(FordMondeo)},
)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := graph.Populate(); err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Println("exit 2")
os.Exit(1)
}
myCar := carFactory.makeCar()
fmt.Println(myCar.getModel())
}
|
package main
import (
"fmt"
"io/ioutil"
)
func main() {
dir := "testdata"
fis, err := ioutil.ReadDir(dir)
if err != nil {
panic(err)
}
for _, fi := range fis {
fmt.Printf("%#v\n", fi)
fmt.Printf("fi.Name():%q\n\n", fi.Name())
}
}
|
package main
import (
"flag"
"log"
"net/http"
"strconv"
"sync"
"github.com/mindprince/gonvml"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
namespace = "nvidia_gpu"
)
var (
addr = flag.String("web.listen-address", ":9445", "Address to listen on for web interface and telemetry.")
labels = []string{"minor_number", "uuid", "name"}
)
type Collector struct {
sync.Mutex
numDevices prometheus.Gauge
usedMemory *prometheus.GaugeVec
totalMemory *prometheus.GaugeVec
dutyCycle *prometheus.GaugeVec
powerUsage *prometheus.GaugeVec
temperature *prometheus.GaugeVec
fanSpeed *prometheus.GaugeVec
}
func NewCollector() *Collector {
return &Collector{
numDevices: prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "num_devices",
Help: "Number of GPU devices",
},
),
usedMemory: prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "memory_used_bytes",
Help: "Memory used by the GPU device in bytes",
},
labels,
),
totalMemory: prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "memory_total_bytes",
Help: "Total memory of the GPU device in bytes",
},
labels,
),
dutyCycle: prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "duty_cycle",
Help: "Percent of time over the past sample period during which one or more kernels were executing on the GPU device",
},
labels,
),
powerUsage: prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "power_usage_milliwatts",
Help: "Power usage of the GPU device in milliwatts",
},
labels,
),
temperature: prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "temperature_celsius",
Help: "Temperature of the GPU device in celsius",
},
labels,
),
fanSpeed: prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "fanspeed_percent",
Help: "Fanspeed of the GPU device as a percent of its maximum",
},
labels,
),
}
}
func (c *Collector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.numDevices.Desc()
c.usedMemory.Describe(ch)
c.totalMemory.Describe(ch)
c.dutyCycle.Describe(ch)
c.powerUsage.Describe(ch)
c.temperature.Describe(ch)
c.fanSpeed.Describe(ch)
}
func (c *Collector) Collect(ch chan<- prometheus.Metric) {
// Only one Collect call in progress at a time.
c.Lock()
defer c.Unlock()
c.usedMemory.Reset()
c.totalMemory.Reset()
c.dutyCycle.Reset()
c.powerUsage.Reset()
c.temperature.Reset()
c.fanSpeed.Reset()
numDevices, err := gonvml.DeviceCount()
if err != nil {
log.Printf("DeviceCount() error: %v", err)
return
} else {
c.numDevices.Set(float64(numDevices))
ch <- c.numDevices
}
for i := 0; i < int(numDevices); i++ {
dev, err := gonvml.DeviceHandleByIndex(uint(i))
if err != nil {
log.Printf("DeviceHandleByIndex(%d) error: %v", i, err)
continue
}
minorNumber, err := dev.MinorNumber()
if err != nil {
log.Printf("MinorNumber() error: %v", err)
continue
}
minor := strconv.Itoa(int(minorNumber))
uuid, err := dev.UUID()
if err != nil {
log.Printf("UUID() error: %v", err)
continue
}
name, err := dev.Name()
if err != nil {
log.Printf("Name() error: %v", err)
continue
}
totalMemory, usedMemory, err := dev.MemoryInfo()
if err != nil {
log.Printf("MemoryInfo() error: %v", err)
} else {
c.usedMemory.WithLabelValues(minor, uuid, name).Set(float64(usedMemory))
c.totalMemory.WithLabelValues(minor, uuid, name).Set(float64(totalMemory))
}
dutyCycle, _, err := dev.UtilizationRates()
if err != nil {
log.Printf("UtilizationRates() error: %v", err)
} else {
c.dutyCycle.WithLabelValues(minor, uuid, name).Set(float64(dutyCycle))
}
powerUsage, err := dev.PowerUsage()
if err != nil {
log.Printf("PowerUsage() error: %v", err)
} else {
c.powerUsage.WithLabelValues(minor, uuid, name).Set(float64(powerUsage))
}
temperature, err := dev.Temperature()
if err != nil {
log.Printf("Temperature() error: %v", err)
} else {
c.temperature.WithLabelValues(minor, uuid, name).Set(float64(temperature))
}
fanSpeed, err := dev.FanSpeed()
if err != nil {
log.Printf("FanSpeed() error: %v", err)
} else {
c.fanSpeed.WithLabelValues(minor, uuid, name).Set(float64(fanSpeed))
}
}
c.usedMemory.Collect(ch)
c.totalMemory.Collect(ch)
c.dutyCycle.Collect(ch)
c.powerUsage.Collect(ch)
c.temperature.Collect(ch)
c.fanSpeed.Collect(ch)
}
func main() {
flag.Parse()
if err := gonvml.Initialize(); err != nil {
log.Fatalf("Couldn't initialize gonvml: %v. Make sure NVML is in the shared library search path.", err)
}
defer gonvml.Shutdown()
if driverVersion, err := gonvml.SystemDriverVersion(); err != nil {
log.Printf("SystemDriverVersion() error: %v", err)
} else {
log.Printf("SystemDriverVersion(): %v", driverVersion)
}
prometheus.MustRegister(NewCollector())
// Serve on all paths under addr
log.Fatalf("ListenAndServe error: %v", http.ListenAndServe(*addr, promhttp.Handler()))
}
|
package models
import (
"os"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var DB *gorm.DB
func InitDB(dbstring string) {
if dbstring == "$dbstring" {
dbstring = os.Getenv("dbstring")
}
var err error
DB, err = gorm.Open("postgres", dbstring)
if err != nil {
panic(err)
}
}
func CloseDB() {
DB.Close()
}
|
// Generated by ego on Sun Jun 14 13:23:31 2015.
// DO NOT EDIT
package main
import (
"fmt"
"html"
"io"
"github.com/kyokomi/slackbot/plugins"
)
//line templates/index.html.ego:1
func IndexTmpl(w io.Writer, pList []plugins.Plugin) error {
//line templates/index.html.ego:2
_, _ = fmt.Fprint(w, "\n\n")
//line templates/index.html.ego:4
_, _ = fmt.Fprint(w, "\n\n<!DOCTYPE html>\n<html>\n<head lang=\"en\">\n <meta charset=\"UTF-8\">\n <title>いーすん管理画面</title>\n</head>\n<body>\n <h1>いーすん管理画面</h1>\n ")
//line templates/index.html.ego:13
for idx, p := range pList {
//line templates/index.html.ego:14
_, _ = fmt.Fprint(w, "\n <li>")
//line templates/index.html.ego:14
_, _ = fmt.Fprint(w, html.EscapeString(fmt.Sprintf("%v", idx )))
//line templates/index.html.ego:14
_, _ = fmt.Fprint(w, " : ")
//line templates/index.html.ego:14
_, _ = fmt.Fprint(w, html.EscapeString(fmt.Sprintf("%v", p.Name() )))
//line templates/index.html.ego:14
_, _ = fmt.Fprint(w, "</li>\n ")
//line templates/index.html.ego:15
}
//line templates/index.html.ego:16
_, _ = fmt.Fprint(w, "\n</body>\n</html>")
return nil
}
|
package main
import (
"time"
)
type ChannelImage struct {
Url string
}
type ChannelMovie struct {
Url string
}
type ChannelItem struct {
Id int
ChannelId int
Title string
Url string
PublishedAt *time.Time
TweetedAt *time.Time
Images []*ChannelImage
Movies []*ChannelMovie
}
type Channel struct {
Id int
Code string
Title string
Url string
items []*ChannelItem
}
func (c *Channel) ConvertBlogTitle() {
switch c.Code {
case "tamai-sd":
c.Title = "玉井詩織 オフィシャルブログ「楽しおりん生活」"
case "momota-sd":
c.Title = "百田夏菜子 オフィシャルブログ「でこちゃん日記」"
case "ariyasu-sd":
c.Title = "有安杏果 オフィシャルブログ「ももパワー充電所」"
case "sasaki-sd":
c.Title = "佐々木彩夏 オフィシャルブログ「あーりんのほっぺ」"
case "takagi-sd":
c.Title = "高城れに オフィシャルブログ「ビリビリ everyday」"
}
} |
package rigis
import (
"net/http"
"net/http/httputil"
"net/url"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
type backendHost struct {
weight int
url *url.URL
rp *httputil.ReverseProxy
}
func newBackendHost(weight int, beURL *url.URL) backendHost {
bh := backendHost{
weight: weight,
url: beURL,
rp: &httputil.ReverseProxy{},
}
bh.rp.Director = bh.director
bh.rp.ModifyResponse = bh.modifyResponse
bh.rp.ErrorHandler = bh.errorHandler
return bh
}
func (bh backendHost) serveHTTP(rw http.ResponseWriter, req *http.Request) {
bh.rp.ServeHTTP(rw, req)
}
func (bh backendHost) director(req *http.Request) {
// Set Reverse Proxy Params
req.URL.Scheme = bh.url.Scheme
req.URL.Host = bh.url.Host
req.URL.Path = normalizeRpPath(bh.url.Path, req.URL.Path)
req.URL.RawQuery = normalizeRawQuery(bh.url.RawQuery, req.URL.RawQuery)
// Set Optional HTTP Request Headers
req.Header.Set("User-Agent", getUserAgent(req.Header.Get("User-Agent")))
req.Header.Set("X-Forwarded-Proto", getXForwardedProto(req.Header.Get("X-Forwarded-Proto"), viper.GetBool("TLSEnable")))
req.Header.Set("X-Forwarded-Host", getXForwardedHost(req.Header.Get("X-Forwarded-Host"), req.Host))
req.Header.Set("X-Real-IP", getRemoteAddr(req))
}
func (bh backendHost) modifyResponse(res *http.Response) error {
res.Header.Set("Server", viper.GetString("ServerName"))
logrus.WithFields(formatAccessLog(res)).Info("rigis access log")
return nil
}
func (bh backendHost) errorHandler(rw http.ResponseWriter, req *http.Request, err error) {
logrus.WithFields(formatErrorLog(req)).Error("backend server is dead")
responseError(rw, req, getErrorEntity(http.StatusServiceUnavailable))
}
|
package storage
import (
"context"
"sync"
pb "github.com/vic3r/Microservice-Go/shippy/shippy-service-consignment/proto/consignment"
r "github.com/vic3r/Microservice-Go/shippy/shippy-service-consignment/repository"
)
type Storage struct {
mu sync.RWMutex
consignments []*pb.Consignment
}
var _ r.Repository = &Storage{}
func (sto *Storage) Create(ctx context.Context, consignment *pb.Consignment) (*pb.Consignment, error) {
sto.mu.Lock()
updated := append(sto.consignments, consignment)
sto.consignments = updated
sto.mu.Unlock()
return consignment, nil
}
func (sto *Storage) GetAll(ctx context.Context, req *pb.GetRequest) ([]*pb.Consignment, error) {
return sto.consignments, nil
}
|
package handlers
import (
"errors"
"fmt"
"github.com/RecleverLogger/customerrs"
"github.com/RecleverLogger/logger"
"github.com/RecleverLogger/logger/repository"
"net/http"
)
type Config struct {
DbUrl string
DbInitialMigratePath string
}
type Service struct {
Handlers Handlers
db repository.Logs
logger logger.Logger
config *Config
}
func New(log logger.Logger, config *Config) (*Service, error) {
log.Logf("Creating service")
if config == nil {
return nil, customerrs.ServiceConfigIsNilErr()
}
if config.DbUrl == "" {
return nil, customerrs.ServiceConfigDbUrlIsEmptyErr()
}
service := &Service{
config: config,
logger: log,
}
{
db := repository.CreateDatabase(service.config.DbUrl, service.config.DbInitialMigratePath)
service.db = repository.New(db, log)
}
service.Handlers = map[string]Handler{
"Log": {"/log", service.recoveryWrap(service.Log), "POST"},
}
service.logger.Logf("Http service created")
return service, nil
}
func (s *Service) recoveryWrap(handlerFunc http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
var e error
r := recover()
if r != nil {
msg := "Handler recover from the panic"
switch r.(type) {
case string:
e = errors.New(fmt.Sprintf("Error: %s, trace: %s", msg, r))
case error:
e = errors.New(fmt.Sprintf("Error: %s, trace: %s", msg, r))
default:
e = errors.New(fmt.Sprintf("Error: %s", msg))
}
writeError(w, http.StatusInternalServerError, e)
}
}()
if handlerFunc != nil {
handlerFunc(w, r)
}
}
}
|
// Copyright 2018 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
// ===========================================================================
// IsLess returns a Predicate
// which is useful to disriminate
// if a is less than some Pair or not.
func (a Index) IsLess() Predicate {
return func(p Pair) (less bool) {
if x, less := p.(Index); less {
return x.Int.Cmp(a.Int) > 0
}
return
}
}
// IsEq returns a Predicate
// which is useful to disriminate
// if some Pair is equal to a or not.
func (a Index) IsEq() Predicate {
return func(p Pair) (equal bool) {
if x, equal := p.(Index); equal {
return x.Int.Cmp(a.Int) == 0
}
return
}
}
// IsNul returns a Predicate
// which is useful to disriminate
// if some Pair represents the zero value.
func (*Index) IsNul() Predicate {
return func(p Pair) (isNul bool) {
if x, isNul := p.(Index); isNul {
return x.IsEq()(Ordinal(0))
}
return
}
}
// IsOne returns a Predicate
// which is useful to disriminate
// if some Pair represents the multiplicative unit.
func (*Index) IsOne() Predicate {
return func(p Pair) (isOne bool) {
if x, isOne := p.(Index); isOne {
return x.IsEq()(Ordinal(1))
}
return
}
}
// IsEqInt returns a Predicate
// which is useful to disriminate
// if some int number is equal to a or not.
//
// IsEqInt is a conveninence method - syntactical sugar.
func (a Index) IsEqInt() func(int) bool {
return func(p int) bool {
return a.IsEq()(Ordinal(p))
}
}
// ===========================================================================
|
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// Code generated from the elasticsearch-specification DO NOT EDIT.
// https://github.com/elastic/elasticsearch-specification/tree/33e8a1c9cad22a5946ac735c4fba31af2da2cec2
package types
import (
"bytes"
"encoding/json"
"errors"
"io"
)
// Watch type.
//
// https://github.com/elastic/elasticsearch-specification/blob/33e8a1c9cad22a5946ac735c4fba31af2da2cec2/specification/watcher/_types/Watch.ts#L37-L47
type Watch struct {
Actions map[string]WatcherAction `json:"actions"`
Condition WatcherCondition `json:"condition"`
Input WatcherInput `json:"input"`
Metadata Metadata `json:"metadata,omitempty"`
Status *WatchStatus `json:"status,omitempty"`
ThrottlePeriod Duration `json:"throttle_period,omitempty"`
ThrottlePeriodInMillis *int64 `json:"throttle_period_in_millis,omitempty"`
Transform *TransformContainer `json:"transform,omitempty"`
Trigger TriggerContainer `json:"trigger"`
}
func (s *Watch) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
for {
t, err := dec.Token()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
switch t {
case "actions":
if s.Actions == nil {
s.Actions = make(map[string]WatcherAction, 0)
}
if err := dec.Decode(&s.Actions); err != nil {
return err
}
case "condition":
if err := dec.Decode(&s.Condition); err != nil {
return err
}
case "input":
if err := dec.Decode(&s.Input); err != nil {
return err
}
case "metadata":
if err := dec.Decode(&s.Metadata); err != nil {
return err
}
case "status":
if err := dec.Decode(&s.Status); err != nil {
return err
}
case "throttle_period":
if err := dec.Decode(&s.ThrottlePeriod); err != nil {
return err
}
case "throttle_period_in_millis":
if err := dec.Decode(&s.ThrottlePeriodInMillis); err != nil {
return err
}
case "transform":
if err := dec.Decode(&s.Transform); err != nil {
return err
}
case "trigger":
if err := dec.Decode(&s.Trigger); err != nil {
return err
}
}
}
return nil
}
// NewWatch returns a Watch.
func NewWatch() *Watch {
r := &Watch{
Actions: make(map[string]WatcherAction, 0),
}
return r
}
|
// Copyright (c) 2020 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package util
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// ReadArgsFile parses the args file and populates the map with the contents
// of that file. The parsing follows the following rules:
// * each line should contain only a single key=value pair
// * lines starting with # are ignored
// * empty lines are ignored
// * any line not following the above patterns are ignored with a warning message
func ReadArgsFile(path string, args map[string]string) error {
path, err := ExpandPath(path)
if err != nil {
return err
}
file, err := os.Open(path)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("args file not found: %s", path))
}
defer file.Close()
scanner := bufio.NewScanner(file)
if err := scanner.Err(); err != nil {
log.Fatal(err)
return err
}
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "#") && len(strings.TrimSpace(line)) != 0 {
if pair := strings.Split(line, "="); len(pair) == 2 {
args[strings.TrimSpace(pair[0])] = strings.TrimSpace(pair[1])
} else {
logrus.Warnf("unknown entry in args file: %s", line)
}
}
}
return nil
}
|
package color
const (
IndianRed = "#CD5C5C"
LightCoral = "#F08080"
Salmon = "#FA8072"
DarkSalmon = "#E9967A"
LightSalmon = "#FFA07A"
Crimson = "#DC143C"
Red = "#FF0000"
FireBrick = "#B22222"
DarkRed = "#8B0000"
Cornsilk = "#FFF8DC"
BlanchedAlmond = "#FFEBCD"
Bisque = "#FFE4C4"
NavajoWhite = "#FFDEAD"
Wheat = "#F5DEB3"
BurlyWood = "#DEB887"
Tan = "#D2B48C"
RosyBrown = "#BC8F8F"
SandyBrown = "#F4A460"
Goldenrod = "#DAA520"
DarkGoldenrod = "#B8860B"
Peru = "#CD853F"
Chocolate = "#D2691E"
SaddleBrown = "#8B4513"
Sienna = "#A0522D"
Brown = "#A52A2A"
Maroon = "#800000"
Pink = "#FFC0CB"
LightPink = "#FFB6C1"
HotPink = "#FF69B4"
DeepPink = "#FF1493"
MediumVioletRed = "#C71585"
PaleVioletRed = "#DB7093"
GreenYellow = "#ADFF2F"
Chartreuse = "#7FFF00"
LawnGreen = "#7CFC00"
Lime = "#00FF00"
LimeGreen = "#32CD32"
PaleGreen = "#98FB98"
LightGreen = "#90EE90"
MediumSpringGreen = "#00FA9A"
SpringGreen = "#00FF7F"
MediumSeaGreen = "#3CB371"
SeaGreen = "#2E8B57"
ForestGreen = "#228B22"
Green = "#008000"
DarkGreen = "#006400"
YellowGreen = "#9ACD32"
OliveDrab = "#6B8E23"
Olive = "#808000"
DarkOliveGreen = "#556B2F"
MediumAquamarine = "#66CDAA"
DarkSeaGreen = "#8FBC8F"
LightSeaGreen = "#20B2AA"
DarkCyan = "#008B8B"
Teal = "#008080"
Coral = "#FF7F50"
Tomato = "#FF6347"
OrangeRed = "#FF4500"
DarkOrange = "#FF8C00"
Orange = "#FFA500"
White = "#FFFFFF"
Snow = "#FFFAFA"
Honeydew = "#F0FFF0"
MintCream = "#F5FFFA"
Azure = "#F0FFFF"
AliceBlue = "#F0F8FF"
GhostWhite = "#F8F8FF"
WhiteSmoke = "#F5F5F5"
Seashell = "#FFF5EE"
Beige = "#F5F5DC"
OldLace = "#FDF5E6"
FloralWhite = "#FFFAF0"
Ivory = "#FFFFF0"
AntiqueWhite = "#FAEBD7"
Linen = "#FAF0E6"
LavenderBlush = "#FFF0F5"
MistyRose = "#FFE4E1"
Gold = "#FFD700"
Yellow = "#FFFF00"
LightYellow = "#FFFFE0"
LemonChiffon = "#FFFACD"
LightGoldenrodYellow = "#FAFAD2"
PapayaWhip = "#FFEFD5"
Moccasin = "#FFE4B5"
PeachPuff = "#FFDAB9"
PaleGoldenrod = "#EEE8AA"
Khaki = "#F0E68C"
DarkKhaki = "#BDB76B"
Gainsboro = "#DCDCDC"
LightGrey = "#D3D3D3"
Silver = "#C0C0C0"
DarkGray = "#A9A9A9"
Gray = "#808080"
DimGray = "#696969"
LightSlateGray = "#778899"
SlateGray = "#708090"
DarkSlateGray = "#2F4F4F"
Black = "#000000"
Aqua = "#00FFFF"
Cyan = "#00FFFF"
LightCyan = "#E0FFFF"
PaleTurquoise = "#AFEEEE"
Aquamarine = "#7FFFD4"
Turquoise = "#40E0D0"
MediumTurquoise = "#48D1CC"
DarkTurquoise = "#00CED1"
CadetBlue = "#5F9EA0"
SteelBlue = "#4682B4"
LightSteelBlue = "#B0C4DE"
PowderBlue = "#B0E0E6"
LightBlue = "#ADD8E6"
SkyBlue = "#87CEEB"
LightSkyBlue = "#87CEFA"
DeepSkyBlue = "#00BFFF"
DodgerBlue = "#1E90FF"
CornflowerBlue = "#6495ED"
MediumSlateBlue = "#7B68EE"
RoyalBlue = "#4169E1"
Blue = "#0000FF"
MediumBlue = "#0000CD"
DarkBlue = "#00008B"
Navy = "#000080"
MidnightBlue = "#191970"
Lavender = "#E6E6FA"
Thistle = "#D8BFD8"
Plum = "#DDA0DD"
Violet = "#EE82EE"
Orchid = "#DA70D6"
Fuchsia = "#FF00FF"
Magenta = "#FF00FF"
MediumOrchid = "#BA55D3"
MediumPurple = "#9370DB"
Amethyst = "#9966CC"
BlueViolet = "#8A2BE2"
DarkViolet = "#9400D3"
DarkOrchid = "#9932CC"
DarkMagenta = "#8B008B"
Purple = "#800080"
Indigo = "#4B0082"
SlateBlue = "#6A5ACD"
DarkSlateBlue = "#483D8B"
)
|
package core
import (
"errors"
)
// OrderTransactionType describes the transaction type: Bid / Ask
type OrderTransactionType uint
const (
// Bid - we are buying the base of a currency pair, or selling the quote
Bid OrderTransactionType = iota
// Ask - we are selling the base of a currency pair, or buying the quote
Ask
)
// Order represents an order
type Order struct {
Hit *Hit `json:"hit,omitempty"`
Price float64 `json:"price"`
PriceOfQuoteToBase float64 `json:"quoteToBasePrice"`
BaseVolume float64 `json:"baseVolume"`
QuoteVolume float64 `json:"quoteVolume"`
TransactionType OrderTransactionType `json:"transactionType"`
Fee float64 `json:"fee"`
TakerFee float64 `json:"takerFee"`
BaseVolumeIn float64 `json:"baseVolumeIn"`
BaseVolumeOut float64 `json:"baseVolumeOut"`
QuoteVolumeIn float64 `json:"quoteVolumeIn"`
QuoteVolumeOut float64 `json:"quoteVolumeOut"`
Progress float64 `json:"progress"`
}
// InitAsk initialize an Order, setting the transactionType to Ask
func (o *Order) InitAsk(price float64, baseVolume float64) {
o.TransactionType = Ask
o.Init(price, baseVolume)
}
// InitBid initialize an Order, setting the transactionType to Bid
func (o *Order) InitBid(price float64, baseVolume float64) {
o.TransactionType = Bid
o.Init(price, baseVolume)
}
// NewAsk initialize an Order, setting the transactionType to Ask
func NewAsk(price float64, baseVolume float64) Order {
o := Order{}
o.InitAsk(price, baseVolume)
return o
}
// NewBid returns an Order, setting the transactionType to Bid
func NewBid(price float64, baseVolume float64) Order {
o := Order{}
o.InitBid(price, baseVolume)
return o
}
// Init initialize an Order
func (o *Order) Init(price float64, baseVolume float64) {
o.Price = price
o.PriceOfQuoteToBase = 1 / price
o.TakerFee = 0.10 / 100
o.UpdateBaseVolume(baseVolume)
}
// UpdateBaseVolume cascade update on BaseVolume and QuoteVolume
func (o *Order) UpdateBaseVolume(baseVolume float64) {
o.BaseVolume = baseVolume
o.QuoteVolume = o.Price * o.BaseVolume
o.Fee = o.BaseVolume * o.TakerFee
o.updateVolumesInOut()
}
// UpdateQuoteVolume cascade update on BaseVolume and QuoteVolume
func (o *Order) UpdateQuoteVolume(quoteVolume float64) {
o.QuoteVolume = quoteVolume
o.BaseVolume = o.QuoteVolume / o.Price
o.Fee = o.BaseVolume * o.TakerFee
o.updateVolumesInOut()
}
func (o *Order) updateVolumesInOut() {
if o.TransactionType == Bid {
o.BaseVolumeIn = 0
o.QuoteVolumeIn = Trunc8(o.QuoteVolume)
o.BaseVolumeOut = Trunc8(o.BaseVolume - o.BaseVolume*o.TakerFee)
o.QuoteVolumeOut = 0
} else if o.TransactionType == Ask {
o.BaseVolumeIn = Trunc8(o.BaseVolume)
o.QuoteVolumeIn = 0
o.BaseVolumeOut = 0
o.QuoteVolumeOut = Trunc8(o.QuoteVolume - o.QuoteVolume*o.TakerFee)
}
}
// CreateMatchingAsk returns an Ask order matching the current Bid (crossing ths spread)
func (o *Order) CreateMatchingAsk() (*Order, error) {
if o.TransactionType != Bid {
return nil, errors.New("order: not a bid")
}
m := *o
m.TransactionType = Ask
return &m, nil
}
// CreateMatchingBid returns a Bid order matching the current Ask (crossing ths spread)
func (o *Order) CreateMatchingBid() (*Order, error) {
if o.TransactionType != Ask {
return nil, errors.New("order: not a ask")
}
m := *o
m.TransactionType = Bid
return &m, nil
}
|
package manager
import (
"errors"
"strings"
)
func GetVideoIDFromLink(link string) (string, error) {
var err = errors.New("Invalid link!")
parts := strings.Split(link, "=")
if len(parts) != 2 {
return "", err
}
return parts[1], nil
}
func IsLinkFromYoutube(link string) bool {
if strings.HasPrefix(link, "https://www.youtube.com") {
return true
}
return false
}
|
package arangoapi
import "gopkg.in/kataras/iris.v6"
import "time"
import "strconv"
type TimeElapsed struct {
Startime int64 `json:"startime"`
Endtime int64 `json:"endtime"`
Duration int64 `json:"duration"`
}
func Read(ctx *iris.Context) {
var timer TimeElapsed
timer.Startime =time.Now().UnixNano()
CreateRecord()
timer.Endtime =time.Now().UnixNano()
timer.Duration = timer.Endtime-timer.Startime
ctx.JSON(iris.StatusOK, timer)
}
func ReadAll(ctx *iris.Context) {
var timer TimeElapsed
ctx.JSON(iris.StatusOK, timer)
}
func Create(ctx *iris.Context) {
var timer TimeElapsed
timer.Startime =time.Now().UnixNano()
CreateRecord()
timer.Endtime =time.Now().UnixNano()
timer.Duration = timer.Endtime-timer.Startime
ctx.JSON(iris.StatusOK, timer)
}
func CreateInNumbers(ctx *iris.Context) {
number:= ctx.Param("number")
num, err := strconv.ParseInt(number, 10, 64)
if err != nil{
println(" Not a Valid String ", number)
}
var timer TimeElapsed
timer.Startime =time.Now().UnixNano()
var start int64 = 1
for i := start; i <= num; i++{
CreateRecord()
}
timer.Endtime =time.Now().UnixNano()
timer.Duration = timer.Endtime-timer.Startime
ctx.JSON(iris.StatusOK, timer)
}
func Delete(ctx *iris.Context) {
var timer TimeElapsed
ctx.JSON(iris.StatusOK, timer)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.