text
stringlengths
11
4.05M
package main /* #include<string.h> char arrInC[10] = {'a', '7'}; */ import "C" import ( "fmt" "reflect" "unsafe" ) func main() { var bytesInGo []byte // 把一个go的byte数组转换成可以容纳c char数组的类型 var bytesHeader = (*reflect.SliceHeader)(unsafe.Pointer(&bytesInGo)) // 从c数组读取数据(因为c数组是数组头的指针,所以读[0]即可) bytesHeader.Data = uin...
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copy...
package main import "fmt" func NewInt() *int { var i int return &i } func main() { i := NewInt() fmt.Println(i) fmt.Println(*i) }
package sqsx import ( "context" "errors" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sqs" "github.com/aws/aws-sdk-go/service/sqs/sqsiface" ) // ReceiveMessage get a message from the queue func ReceiveMessage(ctx context.Context, cli sqsiface.SQSAPI, url string, opts ...Option) (*sqs.Messa...
package ravendb // AttachmentName represents infor about an attachment type AttachmentName struct { Name string `json:"Name"` Hash string `json:"Hash"` ContentType string `json:"ContentType"` Size int64 `json:"Size"` }
package main func AbsDivisorAndDivAgain(a, b, c int) int { div, err := AbsoultDivisor(10, 2) if err != nil { return 0 } return c / div }
/* Copyright 2020 Docker Compose CLI authors 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 a...
package main import ( "fmt" "os" "github.com/hiremaga/git-mob" ) func main() { initialsList := os.Args[1:] path := fmt.Sprintf("%s/.git-authors", os.Getenv("HOME")) config := gitmob.LoadConfiguration(path) authors := config.Authors() for _, initials := range initialsList { fmt.Printf("%#v\n", authors[init...
//Copyright 2019 Chris Wojno // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribut...
package proto const ( ResType_Gold = "gold" ResType_Food = "food" ResType_Wuhun = "wuhun" ResType_Gem = "diamonds" ResType_Trophy = "trophy" ResType_TiLi = "tili" ResType_TTTScore = "tttscore" ResType_Dbt = "Dbt" ResTyp...
// Copyright 2014 Unknwon // // 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 writ...
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
/* * Databricks * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 0.0.1 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package models type WorkspaceLanguage string // List of WorkspaceLanguage con...
package main import ( "fmt" "log" "strings" "../model" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) var db *gorm.DB var err error func main() { db, err = gorm.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local") if err != nil { log.Fatal(err)...
package encapsulation import "fmt" type Fooer interface { Foo1() Foo2() Foo3() } type Foo struct { } func (f Foo) Foo1() { fmt.Println("Foo1() here") } func (f Foo) Foo2() { fmt.Println("Foo2() here") } func (f Foo) Foo3() { fmt.Println("Foo3() here") }
package core // StockTransaction represents a Moltin inventory transaction: https://docs.moltin.com/api/catalog/inventory/stock-transactions type StockTransaction struct { ID string `json:"id,omitempty"` Type string `json:"type"` Action string `json:"action"` ProductID string `json:"product_id"` Qu...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package power import ( "context" "regexp" "time" "github.com/golang/protobuf/ptypes/empty" "chromiumos/tast/common/servo" "chromiumos/tast/errors" "chromiumos/tast/...
package v1 import ( "errors" "fmt" "os" "strconv" ) type RepositoryGorm2 struct{} func NewRepositoryGorm2() *RepositoryGorm2 { return &RepositoryGorm2{} } func (*RepositoryGorm2) User() (string, error) { user, ok := os.LookupEnv(envKeyDBUserName) if !ok { return "", errors.New("DB_USERNAME is not set") } ...
package solutions import ( "sort" ) func threeSumClosest(nums []int, target int) int { sort.Ints(nums) sum := nums[0] + nums[1] + nums[2] result := sum difference := abs(result - target) length := len(nums) for i := 0; i < length - 2; i++ { for j, k := i + 1, length - 1; j < k; {...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package cellular import ( "context" "time" "chromiumos/tast/errors" "chromiumos/tast/local/cellular" "chromiumos/tast/local/modemmanager" "chromiumos/tast/testing" ) ...
package config import "fmt" var ( // Version is the build version Version string // Build is the build number Build string // ExeName is the exe name ExeName string ) var ver string func init() { ver = version() } // BuildVersion the build version string func BuildVersion() string { return ver } func Buil...
package main import ( "fmt" "math" ) func pow(a, b int) int { return int(math.Pow(float64(a), float64(b))) } func maxProductAfterCutting_2(n int) int { if n < 2 { return 0 } if n == 2 { return 1 } if n == 3 { return 2 } res := make([]int, n+1) res[0], res[1], res[2], res[3] = 0, 1, 2, 3 for i := 4...
package chat import ( "bufio" "bytes" "fmt" "io" "net" "os" "strings" ) const ( //ui команды uiQuit = "\\quit" ) //Start метод для запуска чата //Управляет входными, выходными потоками данных func Start(conn net.Conn) error { reader := bufio.NewReader(os.Stdin) pipe := make(chan error) go listen(conn, pi...
package main import "fmt" import "container/list" func main() { graph := new(graph) test1 := &node { 1, list.New() } test2 := &node { 2, list.New() } test3 := &node { 3, list.New() } test4 := &node { 4, list.New() } graph.base = test1 test1.e.PushBack(test2) test2.e.PushBack(test3) test3.e.PushBack(test4) ...
package nebula import ( "net" "reflect" "testing" "time" "github.com/sirupsen/logrus" "github.com/slackhq/nebula/cert" "github.com/slackhq/nebula/iputil" "github.com/slackhq/nebula/test" "github.com/slackhq/nebula/udp" "github.com/stretchr/testify/assert" ) func TestControl_GetHostInfoByVpnIp(t *testing.T)...
package timestamp import ( "errors" "fmt" _ "strconv" "time" ) const shortForm1 = "2006-Jan-02" const shortForm2 = "2006-01-02" type Timestamp struct{} func (ts *Timestamp) GetTimeNow() (string, int64) { utc_t := time.Now().UTC() unix_t := utc_t.Unix() return utc_t.Format(time.RFC1123), unix_t } func (ts *...
package main /** 遍历通道里数据 */ import "fmt" func main() { ch1:=make(chan int) ch2:=make(chan int) go func() { for i := 0;i < 10; i++ { ch1<-i } close(ch1) }() go func() { for { i,ok := <-ch1 if !ok{ break } ch2 <- i*i } close(ch2) }() for i := range ch2{ fmt.Println(i) } fm...
package standard import ( G "github.com/ionous/sashimi/game" . "github.com/ionous/sashimi/script" . "github.com/ionous/sashimi/standard/live" ) // all infom giving rules: // "applies to one carried thing and one visible thing." // "can't give what you haven't got" // "can't give to yourself" // "can't give to ...
package controller import ( "github.com/skoltai/limithandling/domain" "github.com/skoltai/limithandling/store" ) // AccountController bundles the common dependencies for the controller methods type AccountController struct { ur store.UserRepository sr store.SubscriptionRepository } // NewAccountController constr...
package jsonrpc import ( "jsonrpc/transport" "strings" ) const ( JSON_RPC_VERSION string = "2.0" ) // rpc client type RpcClient struct { Method string Urls transport.Url Field map[string]interface{} Header []string Code int16 Error error Response interface{} Body string } // set fun...
package main import "fmt" func vals() (int, int){ fmt.Println("..on it..") return 4,123 } func main(){ a,b := vals() fmt.Println(a) fmt.Println(b) _,c := vals() fmt.Println(c) vals() }
package must import "testing" func BenchmarkRetrunWithVal(b *testing.B){ for i := 0; i < b.N; i++ { _=retrunWithVal() } } func BenchmarkRetrunWithPoint(b *testing.B){ for i := 0; i < b.N; i++ { _=retrunWithVal() } }
package main import ( "context" "fmt" "github.com/coreos/etcd/clientv3" "time" ) func main() { //创建etcd客户端 client,err := clientv3.New(clientv3.Config{ Endpoints:[]string{"47.92.212.70:2379"}, DialTimeout:time.Second, }) if err != nil { fmt.Println("clientv3.New err:",err) return } defer client.Clos...
package main import "fmt" func main() { var chicken map[string]int chicken = map[string]int{} chicken["januari"] = 50 chicken["februari"] = 40 chicken["mei"] = 40 fmt.Println("januari", chicken["januari"]) fmt.Println("mei", chicken["mei"]) // cara vertikal // var chicken1 = map[string]int{"januari": 50, ...
//Файловый сервер(клиент) для xyz-road. Автор — Кананыхин Сергей. package main import ( "bufio" "bytes" "fmt" "io" "io/ioutil" "log" "mime/multipart" "net/http" "os" "path/filepath" "strconv" "strings" ) const ( site = "http://127.0.0.1:8080/" help_msg = "/list -- list of uploaded files;\n" + "/add ...
package helper import ( "fmt" "testing" ) type move struct { Left string Right string Up string Down string } func TestSetField(t *testing.T) { m := map[string]interface{}{} m["Up"] = "True" m["Down"] = "False" s := &move{} err := MapToStruct(m, s) if err != nil { } t.Log("Past!") fmt.Println(m) ...
package main import "fmt" // var i float32 = 42 // var i = 42. // var i float32 = "foo" -> "WRONG FORMAT"! // var i int = 27 func main() { // var i int // i = 42 // var j float32 = 27 // k := 99. // fmt.Printf("%v, %T", i, i) // var theHttpRequest string = "https://google.com" // var i int = 42 // fmt.Print...
package route import ( "net/http" "github.com/gin-gonic/gin" "github.com/torinos-io/api/server/middleware" ) // GetCurrentUser return the current user func GetCurrentUser(c *gin.Context) { user := middleware.GetCurrentUser(c) if user == nil { c.AbortWithStatus(http.StatusUnauthorized) return } c.JSON(ht...
package config import ( "time" ) // RedisConfig Redis配置对象 type RedisConfig struct { // Redis服务器连接地址 redisConnection string // Redis服务器连接密码 password string // Redis服务器选择的数据库 database int // Redis连接池允许的最大活跃连接数量 maxActive int // Redis连接池允许的最大空闲数量 maxIdle int // 连接被回收前的空闲时间 idleTimeout time.Duration /...
/* * Wire API * * Moov Wire implements an HTTP API for creating, parsing, and validating Fedwire messages. * * API version: v1 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package openapi // ExchangeRate struct for ExchangeRate type ExchangeRate struct { // ExchangeRate is the exchang...
package http import ( "ports/client/application" "ports/client/config" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) // Server is http server type Server struct { echo *echo.Echo config *config.HTTPServer } type hi map[string]interface{} // NewServer created new server based on config ...
package ravendb import ( "net/http" ) var _ IMaintenanceOperation = &GetIndexesStatisticsOperation{} type GetIndexesStatisticsOperation struct { Command *GetIndexesStatisticsCommand } func NewGetIndexesStatisticsOperation() *GetIndexesStatisticsOperation { return &GetIndexesStatisticsOperation{} } func (o *GetI...
package main import "fmt" func Swap(x, y string) (string, string) { return y, x } func main() { x, y := "Qashwa", "Cello" fmt.Println("Before Swap:", x, y) x, y = Swap(x, y) fmt.Println("After Swap:", x, y) }
package testdata var GrafanaHelmValues = ` serviceAccount: create: true name: nameTest: ` var GrafanaHelmHelpers = `{{/* vim: set filetype=mustache: */}} {{/* Expand the name of the chart. */}} {{- define "grafana.name" -}} {{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} {{- end -}}...
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package shelf import ( "context" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/ash" "chromiumos/tast/local/chrome/uiauto/pointer" "chromiumos/tast/local...
package main import ( "bufio" "encoding/hex" "fmt" "net" "os" "runtime" "strconv" "strings" "sync" "time" ) var wg sync.WaitGroup var numberC = 0 var numberR = 0 var done chan bool var start int var end int func main() { var saddr net.UDPAddr saddr.Port = 8888 saddr.IP = net.ParseIP("127.0.0.1") server...
package cmd import ( "fmt" "strconv" "github.com/spf13/cobra" "github.com/Lavos/gbvideo" ) var enqueueCmd = &cobra.Command{ Use: "enqueue", Short: "Marks a video for download.", RunE: func(cmd *cobra.Command, args []string) error { var vd *gbvideo.VideoDownload var id_num int64 var err error for _, ...
package grpc import ( "context" "log" "time" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "github.com/notsu/grpc-playground/04-with-meta-data/pong-service/proto" ) const ( timestampFormat = time.StampNano ) // Server represents t...
package main import "fmt" type Website struct { name string length int url string } var site = Website{ name: "StudyGolang", length: 1024, url: "https://studygolang.com/", } func main() { // 通用 fmt.Printf("%v\n", site) // 相应值的默认格式 fmt.Printf("%+v\n", site) // 输出加上字段名 fmt.Printf("%#v\n", site) /...
package v1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/kubernetes/scheme" ) // SchemeGroupVersion variable for newly added kh checks to be added to Kuberhealthy var SchemeGroupVersion schema.GroupVersion // Co...
package notify type Build struct { ObjectKind string `json:"object_kind"` Ref string `json:"ref"` Tag bool `json:"tag"` BeforeSha string `json:"before_sha"` Sha string `json:"sha"` BuildId uint64 `json:"build_id"` ...
package main import "fmt" func baseMap() { m := map[string]string{ "id": "1001", "name": "zhangsan", } fmt.Println(m, len(m)) for k, v := range m { fmt.Println(k, v) } fmt.Println(m["id"]) if id, ok := m["id"]; ok { fmt.Println(id, ok) } delete(m, "name") } func enptyMap() { m2 := make(map[st...
package db_test import ( "fmt" "testing" "time" "github.com/carlmjohnson/be" "github.com/carlmjohnson/be/testfile" "github.com/jackc/pgx/v5/pgtype" "github.com/spotlightpa/almanack/internal/db" ) func TestToFromTOML(t *testing.T) { cases := map[string]db.Page{ "empty": {Frontmatter: db.Map{}}, "body": {...
package controllers type LoginController struct { BaseController } func (c *LoginController) Get() { c.TplName = "login.html" } func (c *LoginController) Post() { p := c.QueryString() c.SuccessJson(p) }
package main import ( "fmt" "os" "github.com/sirupsen/logrus" ) var log = logrus.New() var config = &Config{} var mongoClient *MongoClient var redisClient *RedisClient func main() { var err error log.SetLevel(logrus.DebugLevel) log.AddHook(NewLogrusHook()) log.Info("opening log file") logPath := "./log" f...
// Handle Mute Events package events import ( "encoding/json" "gopkg.in/redis.v3" ) // Play POST request expected JSON payload type publishMutePayload struct { Event string `json:"event"` Active bool `json:"mute"` } // Publish a Play Event from the Player to Redis. This sets the current // playing track, th...
package main import ( "database/sql" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strconv" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" ) //Book Struct type Book struct { Author string `json:"author"` ID int `json:"id"` Name string `json:"name"` Price int `json:"price"...
package routers import ( "crypto-telegram-notifyer/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/health", &controllers.HealthController{}) beego.Router("/coins", &controllers.CoinController{}) beego.Router("/alarms", &controllers.AlarmCo...
package mongo import ( "errors" mgo "github.com/globalsign/mgo" ) // ConfigDef mongo ConfigDef type ConfigDef struct { Dsn string `json:"dsn" yaml:"dsn" mapstructure:"dsn"` } // NewMongoSession NewMongoSession func NewMongoSession(mgConf *ConfigDef) (mongoSession *mgo.Session, err error) { if mgConf == nil { ...
package grpc_test import ( "context" "log" "testing" "time" pb "github.com/moecasts/microcasts/novels/pkg/grpc/pb" "github.com/stretchr/testify/assert" "google.golang.org/grpc" ) func TestBrowse(t *testing.T) { conn, svc, ctx, cancel := setup() defer conn.Close() defer cancel() t.Run("Browse novels witho...
/* Copyright 2020 Takahiro Yamashita 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...
package middleware import ( "time" "github.com/gin-gonic/gin" "go.uber.org/zap" ) func Logger() gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() c.Next() cost := time.Since(start) statusCode := c.Writer.Status() uri := c.Request.RequestURI data := []zap.Field{ // 日志类型 zap.Str...
package main import ( "fmt" "log" "math" "os" "strings" "time" "github.com/evcc-io/evcc/api" "github.com/evcc-io/evcc/util" "github.com/evcc-io/evcc/util/sponsor" "github.com/evcc-io/evcc/vehicle" ) func usage() { fmt.Print(` soc Usage: soc brand [--log level] [--param value [...]] `) } // matchesErro...
package main import ( "bufio" "fmt" "log" "os" "strings" ) var digits map[uint8]int func init() { digits = map[uint8]int{'0': 252, '1': 96, '2': 218, '3': 242, '4': 102, '5': 182, '6': 190, '7': 224, '8': 254, '9': 246} } func valid(y int, d bool, x int) bool { if d && (x&1 == 0) { return false } r...
// Package linkedlist implements a solution of the exercise titled `Linked List'. package linkedlist import "errors" var ErrEmptyList = errors.New("Empty List") // Node defines a node of linked list. type Node struct { prev, next *Node Val interface{} } // List describes a list. type List struct { first, ...
package main import ( "fmt" ) var ( n int = -1 s string = "" ) func main() { for 0 > n || n > 100 { fmt.Scan(&n) } for s == "" { fmt.Scan(&s) } for i := 0; i < n; i++ { fmt.Print("copy of ") } fmt.Print(s) }
// Below code is adapted from https://github.com/u-root/u-root/blob/master/cmds/core/mount/mount.go // That code has the below license and copyright. // // Copyright 2012-2017 the u-root Authors. All rights reserved // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. ...
package live import G "github.com/ionous/sashimi/game" type DescribePhrase struct { object string } func Describe(object string) DescribePhrase { return DescribePhrase{object} } func DescribeThe(object G.IObject) DescribePhrase { return DescribePhrase{string(object.Id())} } func (d DescribePhrase) Execute(g G.P...
package models import ( "time" //"github.com/jinzhu/gorm" ) /* CREATE TABLE `lessons` ( `id` int unsigned AUTO_INCREMENT, `created_at` timestamp NULL, `updated_at` timestamp NULL, `deleted_at` timestamp NULL, `post_id` int unsigned, `status` int, `start_time` timestamp NULL, `timeout`...
package session import ( "github.com/owenliang/go-crontab/mysql" "github.com/owenliang/go-crontab/conf" "time" "fmt" "database/sql" "github.com/owenliang/go-crontab/lock" "os" ) // 定时ping type Session struct { sessionId string pingTime int64 } var GSession *Session func InitSession() (err error) { var ( ...
package xir import ( "fmt" "reflect" "strings" ) // ParsePath takes in a dot separated path and returns and ordered list of path // components. For example node.memory.size* -> [node, memory, size*]. func ParsePath(path string) []string { return strings.Split(path, ".") } // GetProp takes a path and returns the ...
package tiltfile import ( "fmt" "path/filepath" "strconv" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/mod/semver" "github.com/tilt-dev/tilt/internal/controllers/apis/liveupdate" ctrltiltfile "github.com/tilt-dev/tilt/internal/controllers/apis/tiltfile" ...
/* * @lc app=leetcode.cn id=188 lang=golang * * [188] 买卖股票的最佳时机 IV */ // @lc code=start func maxProfit(k int, prices []int) int { n,result := len(prices),0 if k >= n/2{ for i:=1;i<n;i++ { if prices[i] > prices[i-1] { result+=(prices[i]-prices[i-1]) } } } else { hold,cash := make([]int,k+1),mak...
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
/** * @file * @copyright defined in aergo/LICENSE.txt */ package system import ( "bytes" "encoding/gob" "errors" "math/big" "sort" "github.com/aergoio/aergo/internal/common" "github.com/aergoio/aergo/internal/enc" "github.com/aergoio/aergo/state" "github.com/aergoio/aergo/types" "github.com/mr-tron/ba...
package resolvers import ( "time" "github.com/ddouglas/ledger" "github.com/ddouglas/ledger/internal/account" "github.com/ddouglas/ledger/internal/gateway" "github.com/ddouglas/ledger/internal/item" "github.com/ddouglas/ledger/internal/server/gql/dataloaders" "github.com/ddouglas/ledger/internal/server/gql/mode...
package main import "fmt" type DBCoin struct { ID int `db:"id, primarykey, autoincrement"` Name string `db:"name"` Symbol string `db:"symbol"` Rank int `db:"rank"` PriceUsd float64 `db:"price_usd"` PriceBtc float64 `db:"price_btc"` Usd24...
package main import ( "fmt" "html/template" "net/http" "strconv" "github.com/gorilla/mux" "github.com/jinzhu/gorm" _ "github.com/go-sql-driver/mysql" ) //Item Структура данных type Item struct { Id int //'sql:"AUTO_INCREMENT" gorm:"primary_key"' Title string Description string Updated ...
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package ui import ( "context" "time" uiperf "chromiumos/tast/local/bundles/cros/ui/perf" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/ash" "chromiumos...
package functions import ( "testing" "github.com/stretchr/testify/assert" ) func TestGenPath(t *testing.T) { assert.ElementsMatch(t, GenPath("com"), []string{"com"}) assert.ElementsMatch(t, GenPath("google.com"), []string{"com", "google"}) assert.ElementsMatch(t, GenPath("ads.google.com"), []string{"com", "goog...
package resources import ( "fmt" "net" "github.com/RackHD/ipam/interfaces" "github.com/RackHD/ipam/models" "github.com/RackHD/ipam/resources/factory" "gopkg.in/mgo.v2/bson" ) // SubnetResourceType is the media type assigned to a Subnet resource. const SubnetResourceType string = "application/vnd.ipam.subnet" ...
/* Copyright (c) 2019 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...
// Package function contains the core functions of aws-go. package function import ( "encoding/json" "errors" "io/ioutil" "strconv" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.co...
package function import ( "net/http" "tocoteron.com/blog/shared" ) // For Cloud Functions func Blog(w http.ResponseWriter, r *http.Request) { shared.EchoServer.ServeHTTP(w, r) }
package main import "fmt" // const p string = "spacecraft" const p = "spacecraft" func main() { // const q int = 42 const q = 42 fmt.Println("p -", p) fmt.Println("q -", q) } //a CONSTANT is a simple unchanging value
/* * quicksort.go: Quicksort for ints. * * For Introduction to Go, Spring 2010 * Kimmo Kulovesi <kkuloves@cs.helsinki.fi> */ package main import ( "fmt" "rand" srt "sort" ) // Sort the slice s in place using quicksort. func sort(s []int) { if len(s) < 2 { // Slices of length 0 and 1 are already sorted re...
package main import ( "crypto/rand" "flag" "fmt" "io" "log" "net" "os" "golang.org/x/crypto/nacl/box" ) var nonce [24]byte type secureWriter struct { Writer io.Writer Nonce *[24]byte Pub *[32]byte Priv *[32]byte } func (w *secureWriter) Write(p []byte) (n int, err error) { nonce, err := newNonce...
package simplify import ( "testing" "github.com/paulmach/orb" ) func TestSimplify(t *testing.T) { r := DouglasPeucker(10) for _, g := range orb.AllGeometries { simplify(r, g) } } func TestPolygon(t *testing.T) { p := orb.Polygon{ {{0, 0}, {1, 0}, {1, 1}, {0, 0}}, {{0, 0}, {0, 0}}, } p = DouglasPeucke...
package matcher_test import ( "testing" "time" "github.com/mylxsw/adanos-alert/internal/matcher" "github.com/mylxsw/adanos-alert/internal/repository" "github.com/mylxsw/go-ioc" "github.com/stretchr/testify/assert" "go.mongodb.org/mongo-driver/bson/primitive" ) type triggerMatcherTestCase struct { Cond str...
package handlers import ( "context" "fmt" "io" "net" "net/http" "net/url" "strconv" "time" "unicode/utf8" "github.com/gorilla/handlers" ) const lowerhex = "0123456789abcdef" type ctxKey int type CtxErr struct { Err error } func (e *CtxErr) Error() string { if e.Err == nil { return "" } return e.Err...
package main import ( "fmt" "net/http" "strings" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() //uri参数 r.GET("/uriparam/:name/:age", func(c *gin.Context) { name := c.Param("name") age := c.Param("age") c.String(http.StatusOK, name+age+"\n") }) //星号会把action后边的所有内容当成一个 r.GET("/urimara...
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package stores import ( "jean/instructions/base" "jean/instructions/factory" "jean/rtda/jvmstack" ) type FSTORE struct { base.Index8Instruction } func (f *FSTORE) Execute(frame *jvmstack.Frame) { _fstore(frame, f.Index) } func _fstore(frame *jvmstack.Frame, index uint) { val := frame.OperandStack().PopFloat()...
package main import "fmt" var Exists = struct{}{} type set struct { m map[interface{}]struct{} } func newSet(items ...interface{}) *set { s := &set{ m: make(map[interface{}]struct{}), } s.insert(items...) return s } func (s *set) insert(items ...interface{}) { for _, item := range items { s.m[item] = Exi...
package exit_shared type Class struct { ID string `bson:"id" json:"id"` Name string `bson:"name" json:"name"` } type ClassMetadata struct { ID string `json:"id"` Name string `json:"name"` } func (t *Class) Metadata() ClassMetadata { return ClassMetadata{ ID: t.ID, Name: t.Name, } }
package common import ( "shared/utility/errors" ) const ( ErrCodeDefault = -1 ErrCodeTokenInvalid = 5 ErrCodeUserCacheInvalid = 11 ErrCodeUserNotFound = 12 ErrCodeWhileList = 13 ErrCodeUserLoginInOtherClient = 14 ErrCodeLoginSdkError = 15 ErrCode...
package core import ( "regexp" ) //CollationRule sorts deployments pulled from BOSH directors into deployment // categories. type CollationRule interface { //DeploymentName should return empty-string if the rule cannot apply to this // input DeploymentGroup(CollationDeploymentInput) string } //DeploymentRegexCap...
package gcp import ( "errors" "testing" "github.com/NYTimes/gizmo/pubsub" "golang.org/x/net/context" ) func TestGCPSubscriber(t *testing.T) { msgs := []*testMessage{ &testMessage{data: []byte("1")}, &testMessage{data: []byte("2")}, &testMessage{data: []byte("3")}, &testMessage{data: []byte("4")}, &tes...
package command type command interface { execute() } func Execute(c command) { c.execute() }
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { if list1 == nil { return list2 } if list2 == nil { return list1 } var head *ListNode if list1.Val < list2.Val { head = list1 head.Next = mergeTwoLists(list1.Next, list2) } else { head = list2 head.Next = mergeTwoLists(list1, list2.Next...