text
stringlengths
11
4.05M
package rpc type Processor interface { Execute(request Request) Response }
package format import "sync" // Storage holds data for cross-execution storage type Storage struct { sync.RWMutex // Lets not have lists explode data map[string]interface{} } func (s *Storage) checkMap() { s.Lock() if s.data == nil { s.data = make(map[string]interface{}) } s.Unlock() } func (s *Stor...
package bd import ( "context" "log" "time" "github.com/MiguelAngelderobles/microblog/models" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) /*MongoCN es el objeto de conexión a la base de datos*/ var MongoCN = ConectarBD() var cli...
package main import "testing" //TestMode for test mode func TestMode(t *testing.T) { cases := []struct { in, want []float64 }{ {[]float64{1}, []float64{}}, {[]float64{1, 3, 4}, []float64{}}, {[]float64{1, 2, 2, 3, 3, 4}, []float64{2, 3}}, } for _, c := range cases { got := mode(c.in) if !Float64SliceE...
package prservice import ( "os" "bytes" "io/ioutil" "net/http" "testing" "net/http/httptest" fm "github.com/cyg2009/MyTestCode/pkg/functionmanager" ) func TestMain(m *testing.M) { wd, _ := os.Getwd() os.Setenv("RUNTIME_ROOT", wd) os.Setenv("RUNTIME_LAMBDA", wd + "/../../runtime/bi...
package bench import ( "bytes" "io/ioutil" "os/exec" "runtime" "time" ) type TraceRoute struct { Name string Host string Result string Duration time.Duration finished bool } func NewTraceRoute(name, host string) (tr *TraceRoute) { return &TraceRoute{ Name: name, Host: host, } } func (tr *...
package handle import ( "boiler/pkg/service" "context" "github.com/gocraft/work" ) func New(srv service.Interface) Handle { return Handle{srv} } type Handle struct { service service.Interface } func (h *Handle) DeleteUser(j *work.Job) error { return h.service.DeleteUser(context.Background(), j.ArgInt64("id")...
package slacktest import ( "context" "testing" "github.com/stretchr/testify/assert" ) func TestGenerateDefaultRTMInfo(t *testing.T) { wsurl := "ws://127.0.0.1:5555/ws" ctx := context.TODO() info := generateRTMInfo(ctx, wsurl) assert.Equal(t, wsurl, info.URL) assert.True(t, info.Ok) assert.Equal(t, defaultBo...
package main import ( "fmt" "sort" ) /* @DESC 成交额/流通市值 = 换手率 假设 任何一个市场资金都是在流动的, 那么跟踪资金最好的方式就是成交额 换手率表示单股, 热度/交易热情/追逐 评分 = 换手 + 主力流入占比 */ func strategy001(gds map[string]*GeneralData) { // 开始打分 var list GeneralDatas for _, gd := range gds { gd.score = gd.changehands + gd.mainP list = append(list,...
package project const ( // Version is the project version. // It is returned to clients upon connection, in GetState responses, as well as the launcher instance. Version = "1.0.0" )
// 3. Single-byte XOR cipher package main import ( "bufio" "encoding/hex" "fmt" "io" "io/ioutil" "os" ) const sample = "alice.txt" func main() { f, err := os.Open(sample) if err != nil { fmt.Fprintln(os.Stderr, err) return } score, err := ScoreFunc(f) if err != nil { fmt.Fprintln(os.Stderr, err) ...
package app type ResCode int64 const ( // 成功(默认返回状态码) CodeSuccess ResCode = 0 // 全局未知异常 CodeSeverError ResCode = 500 // 请求失败(一般前端处理,不常用) CodeBadRequest ResCode = 400 // 请求资源不存在(静态资源不存在,不常用) CodeDataNotFount ResCode = 404 // 登录、权限认证异常 CodeLoginExpire ResCode = 401 // 权限不足 CodeIdentityNotRow ResCode = 403 )...
package main import ( "bytes" "encoding/json" "flag" "github.com/stbuehler/go-termrecording/exportAsciinemaJson" "github.com/stbuehler/go-termrecording/recording" "io" "io/ioutil" "os" ) func bytesSectionReader(b []byte) *io.SectionReader { return io.NewSectionReader(bytes.NewReader(b), 0, int64(len(b))) } ...
package cmd import ( "github.com/myechuri/ukd/server/api" "github.com/spf13/cobra" "golang.org/x/net/context" "google.golang.org/grpc" "log" ) func status(cmd *cobra.Command, args []string) { // TODO: TLS serverAddress := cmd.InheritedFlags().Lookup("server-endpoint").Value.String() conn, err := grpc.Dial(ser...
// The MIT License (MIT) // // Copyright (c) 2021 Yawning Angel. // // 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, ...
package model type Comment struct { isSingleLine bool comment string } func NewComment() *Comment { return &Comment{} } func (this *Comment) SetComment(comment string) { this.comment = comment } func (this *Comment) GetComment() string { return this.comment } func (this *Comment) IsSingleLine() bool { r...
package ip_api import ( "bytes" "encoding/json" "errors" "log" "net/http" "strconv" "strings" ) //URI for the free IP-API const FreeAPIURI = "http://ip-api.com/" //URI for the pro IP-API const ProAPIURI = "https://pro.ip-api.com/" type Location struct { Status string `json:"status,omitempty"` Message ...
package robot import ( "compress/gzip" "errors" "io" "io/ioutil" "net/http" "os" "strings" "time" "github.com/golang/glog" "golang.org/x/text/encoding/simplifiedchinese" "golang.org/x/text/transform" ) const maxRetry int = 5 var UA string = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebK...
package main import ( "go/types" "github.com/pkg/errors" ) var ( elmBool = &ElmBasicType{name: "Bool", codec: "bool"} elmFloat = &ElmBasicType{name: "Float", codec: "float"} elmInt = &ElmBasicType{name: "Int", codec: "int"} elmString = &ElmBasicType{name: "String", codec: "string"} ) // ElmType represen...
package main import ( "fmt" "golangPractice/chat_room/model" "golangPractice/chat_room/protocol" ) //保存在线好友列表 var onlineUserMap map[int]*model.User = make(map[int]*model.User, 16) func showOnlineUserList() { //显示在线用户列表 fmt.Println("--------------【online user list】-------------") for id, _ := range onlineUserMa...
package web import ( "log" "time" "github.com/tebeka/selenium" ) const waitingTimeBeforeFind = 500 type Finder struct { WebDriver selenium.WebDriver } func (f *Finder) FindElement(selector string) selenium.WebElement { log.Printf("%+v\n", selector) time.Sleep(waitingTimeBeforeFind * time.Millisecond) we, er...
package JsonParsers type GamesOffersJson struct { Id int `json:"id"` ParentId int `json:"parent section id"` Name string `json:"offer name"` Price string `json:"price"` Currency string `json:"currency"` Discount string `json:"discount"` Gift string `json:"gift"` IdSeller string `json:"id...
// できるだけコンパクトにKB、MB、...、YBまでのconst宣言を書きなさい package main import "fmt" const ( B = 1 KB = B * 1000 MB = KB * 1000 GB = MB * 1000 TB = GB * 1000 PG = TB * 1000 EB = PG * 1000 ZB = EB * 1000 YB = ZB * 1000 ) func main() { fmt.Println(B, KB, MB) }
package bp2build import ( "android/soong/bazel" "fmt" ) // Data from the code generation process that is used to improve compatibility // between build systems. type CodegenCompatLayer struct { // A map from the original module name to the generated/handcrafted Bazel // label for legacy build systems to be able t...
package form3_test import ( "context" "errors" "log" "os" "testing" "time" "github.com/matryer/is" "github.com/namsral/flag" "github.com/tehsphinx/form3" ) var endpoint string var debugEnabled bool const orgID = "eb0bd6f5-c3f5-44b2-b677-acd23cdde73c" func TestMain(m *testing.M) { flag.StringVar(&endpoint...
package bot import ( "strings" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" ) var ( markdownV2Replacer = strings.NewReplacer( func(chars string) []string { out := make([]string, 0, len(chars)*2) for _, c := range chars { out = append(out, string(c), "\\"+string(c)) } return out }...
package machinery type MachineryEvent interface { String() string AddStateFrom(...MachineryState) StateTo(MachineryState) AllowAction(...MachineryAction) } type BasicEvent struct { event string statesFrom []MachineryState stateTo MachineryState actions []MachineryAction } func (e BasicEvent) Event...
package firewall import ( "bufio" "fmt" "regexp" "strconv" "strings" "github.com/Sirupsen/logrus" ) var ( iptableRuleRe = regexp.MustCompile(`^(\d+).*?ACCEPT.*?dpt:(\d+)`) ) // PortExistsError is an error when an iptables definition exists for a port. type PortExistsError struct { Port int } func (e *PortE...
package main import "fmt" import "strconv" import "os" func main() { var PRIME_COUNT_STR = os.Getenv("PRIME_COUNT") var PRIME_COUNT, err = strconv.Atoi(PRIME_COUNT_STR) var BENCH_DEBUG = os.Getenv("BENCH_DEBUG") if err != nil { fmt.Println("Please set the PRIME_COUNT environment variable.") os.Exit(-1) } pr...
package lists import ( "testing" ) func TestNew(t *testing.T) { list := New("Hello") if list.Head.Value != "Hello" { t.Fail() } if list.Head.NextNode != nil { t.Fail() } } func TestPush(t *testing.T) { list := New("Hello") if list.Head.Value != "Hello" { t.Fatal("Head value != Hello") } if list.He...
/* Package servicePacks "Every package should have a package comment, a block comment preceding the package clause. For multi-file packages, the package comment only needs to be present in one file, and any one will do. The package comment should introduce the package and provide information relevant to the package as ...
package main import "fmt" // 547. 朋友圈 // 班上有 N 名学生。其中有些人是朋友,有些则不是。他们的友谊具有是传递性。如果已知 A 是 B 的朋友,B 是 C 的朋友,那么我们可以认为 A 也是 C 的朋友。所谓的朋友圈,是指所有朋友的集合。 // 给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系。如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道。你必须输出所有学生中的已知的朋友圈总数. // 注意: // N 在[1,200]的范围内。 // 对于所有学生,有M[i][i] = 1。 // 如果有M[i][j] = 1,则有M...
package main import ( "fmt" "os" "strings" "testing" "time" "github.com/nuttapp/pinghist/dal" "github.com/nuttapp/pinghist/ping" . "github.com/smartystreets/goconvey/convey" ) func Test_main_unit(t *testing.T) { Convey("main", t, func() { parts := strings.Split(time.Now().Format("2006-01-02-07:00"), "-") ...
package command import ( "fmt" "os" "text/tabwriter" "github.com/jclem/graphsh/introspection" "github.com/jclem/graphsh/types" ) // Ls lists fields for the current node type Ls struct{} func testLs(input string) (Command, error) { if input == "ls" { return &Ls{}, nil } return nil, nil } // Execute imple...
package 套模板 var combinationSequence [][]int // 结果集 func combinationSum3(k int, n int) [][]int { /* 1. 进行一些预处理 */ candidates := make([]int, 9) combinationSequence = make([][]int, 0) for i := 1; i <= 9; i++ { candidates[i-1] = i } /* 2. 调用回溯函数 */ combinationSumExec(candidates, n, k, make([]int, 0, 10)) ...
package msg // xlattice_go/msg/in_q_test.go import ( "encoding/hex" "fmt" xr "github.com/jddixon/rnglib_go" xi "github.com/jddixon/xlNodeID_go" xn "github.com/jddixon/xlNode_go" xt "github.com/jddixon/xlTransport_go" xu "github.com/jddixon/xlUtil_go" . "gopkg.in/check.v1" "time" ) var _ = fmt.Print var _ = ...
package parser // MapArgs is an Args implementation which is used for the type // inference necessary to support the postgres wire protocol. // See various TypeCheck() implementations for details. // // key is 1 index. type MapArgs map[string]Datum
package handler import ( "fmt" "github.com/gin-gonic/gin" "log" "net/http" "proxy_download/model" "regexp" "strconv" "strings" ) func EmailDetail(context *gin.Context) { var email model.Email idString := context.Param("id") id, _ := strconv.Atoi(idString) emailDetail, err := email.Detail(id) if err != ...
/* You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. The letters in J are guaranteed distinct, and all characters in J and S are letters. ...
package main import ( "fmt" "os" ) func test(s ...string) { for i, a := range s { fmt.Println(i, a) } } func main() { argument := os.Args if len(argument) == 1 { return } test(argument...) test("Ankita", "somi", "harsh", "mansi", "deepika") }
package main import ( "fmt" "html/template" "io/ioutil" "log" "net/http" "regexp" ) var templates *template.Template var validPath *regexp.Regexp func init() { // call ParseFiles once at program initialization, // parsing all templates into a single *Template. // Then we can use the ExecuteTemplate method t...
package authorization import ( "fmt" "regexp" "strings" "github.com/authelia/authelia/v4/internal/utils" ) // NewAccessControlDomain creates a new SubjectObjectMatcher that matches the domain as a basic string. func NewAccessControlDomain(domain string) (subjcets bool, rule AccessControlDomain) { m := &AccessCo...
package integers // Add takes two integers and returns the sum of them func Add(x,y int)(sum int){ sum = x + y return }
package main import ( "flag" "fmt" "log" "os" "path/filepath" "github.com/gomods/athens/cmd/proxy/actions" "github.com/gomods/athens/pkg/build" "github.com/gomods/athens/pkg/config" ) var ( configFile = flag.String("config_file", filepath.Join("..", "..", "config.dev.toml"), "The path to the config file") ...
package ppu import ( "github.com/vfreex/gones/pkg/emulator/memory" ) // The logical screen resolution processed by the PPU is 256x240 pixels // The PPU renders 262 scanlines per frame. // Each scanline lasts for 341 PPU clock cycles (113.667 CPU clock cycles; 1 CPU cycle = 3 PPU cycles), // with each clock cycle pro...
// Package app contains business object (BO) and data access object (DAO) implementations for Application. package app import ( "encoding/json" "log" "net/url" "reflect" "sort" "strings" "github.com/btnguyen2k/consu/reddo" "github.com/btnguyen2k/henge" "main/src/gvabe/bo" ) // NewApp is helper function to c...
// Copyright 2021, Pulumi Corporation. All rights reserved. package logging import ( "bufio" "github.com/go-logr/logr" "github.com/pulumi/pulumi/sdk/v3/go/common/util/contract" "io" logf "sigs.k8s.io/controller-runtime/pkg/log" ) // Logger is a simple wrapper around go-logr to simplify distinguishing debug // ...
package commands type Destroy struct{} func (command *Destroy) Execute(handles []string) error { client := globalClient() for _, handle := range handles { err := client.Destroy(handle) failIf(err) } return nil }
package main import ( "os" "os/exec" "syscall" log "github.com/sirupsen/logrus" ) func main() { if len(os.Args) < 2 { log.Errorln("missing commands") return } switch os.Args[1] { case "run": run() default: log.Errorln("wrong command") return } } func run() { log.Infof("Running %v", os.Args[2:])...
package main import ( "bytes" "crypto/tls" "crypto/x509" "io/ioutil" "log" "net/http" ) func main() { // load client cert cert, err := tls.LoadX509KeyPair("client.crt", "client.key") if err != nil { log.Fatal(err) } // load CA cert caCert, err := ioutil.ReadFile("ca.crt") if err !=...
package main import "fmt" // type speakHit interface { // speak() // // 只要实现speak()方法的变量,全部都是speakHit类型 // } // // 引出接口的实例 // type cat struct { // } // type dog struct { // } // type person struct { // } // func (c cat) speak() { // fmt.Println("miao miao miao~") // } // func (d dog) speak() { // fmt.Println("w...
package testutil import ( "bytes" "errors" "fmt" "math/rand" "sync" "testing" ma "gx/ipfs/QmNTCey11oxhb1AxDnQBRHtdhap6Ctud872NjAYPYYXPuc/go-multiaddr" ci "gx/ipfs/QmNiJiXwWE3kRhZrC5ej3kSjWHm337pYfhjLGSCDNKJP2s/go-libp2p-crypto" peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer" pte...
package main import ( "fmt" "io" "math" "math/rand" "os" "regexp" "time" ) var stripAnsiStart = regexp.MustCompile("^\033" + `\[(\d+)(;\d+)?(;\d+)?[m|K]`) type LolWriter struct { base io.Writer os int li int spread float64 freq float64 } var tabSpaces = []byte(" ") func (w *LolWriter...
package cmd import ( "github.com/Atrox/homedir" "github.com/spf13/cobra" "github.com/daticahealth/datikube/kubectl" "github.com/daticahealth/datikube/logs" ) var setContext = func() *cobra.Command { cmd := &cobra.Command{ Use: "set-context <name> <cluster-url> <ca-file>", Short: "Add or update cluster cont...
package main import ( "fmt" "math/rand" ) func main() { fmt.Println(rand10()) fmt.Println(rand10()) fmt.Println(rand10()) fmt.Println(rand10()) } func rand10() int { //1,7 // 1,7 // 1,49 x := rand7() + rand7() return x%10 + 1 } func rand7() int { return 1 + rand.Intn(7) }
package main import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/rightscale/rsc/gen" ) var _ = Describe("ParamAnalyzer", func() { var ( params map[string]interface{} analyzer *ParamAnalyzer ) JustBeforeEach(func() { analyzer = NewAnalyzer(params) }) Context("with an empty pat...
package server import ( "io" "io/ioutil" "log" "mime/multipart" "os" "strings" ) // File used to handle file path and file operation. // We use interface so we can swap it to other file storage easily type File interface { GetFile(src string) ([]byte, error) Upload(file *multipart.FileHeader, destPath string)...
/* Copyright 2019 Gravitational, 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, soft...
package main import "testing" type tbp struct { Dir string Fn string Page } // TODO add more test cases and tests in general! func TestBuildPage(t *testing.T) { tableTests := []tbp{ { Dir: "pages", Fn: "index.html", Page: Page{ BaseDir: "pages", LinkDir: "", FileName: "...
package coinchange import "testing" func TestCoinChange(t *testing.T) { var tests = []struct { coins []int amount int expect int }{ {[]int{1, 2, 5}, 11, 3}, {[]int{2}, 3, -1}, {[]int{7, 2, 3, 6}, 13, 2}, {[]int{3, 2, 4}, 6, 2}, } for _, test := range tests { if got, _ := coinChange(test.coins, t...
package rectangle import "fmt" //A is variable for ... const A, b = 20, 30 func init() { fmt.Println("rectmetr.go init function") fmt.Println("A var is:", A, "b var is:", b) } //Area is function for ...... func Area(width, length float64) float64 { return width * length } func innerArea(width, length float64) f...
package main import "fmt" //Map adalah kumpulan key value yang dimana key nya bersifat unik tidak boleh sama //Tipe data valuenya haruslah bertipe yang sama //Berbeda dengan Array dan Slice data yang dimasukan ke Map boleh sebanyak banyaknya, dengan catatan keynya harus berbeda //Bila key nya sama maka otomatis key d...
package main import "fmt" func main() { ch := make(chan int, 2) ch <- 100 ch <- 200 fmt.Println(<-ch) fmt.Println(<-ch) }
// Package sdrtime groups utility functions to convert time and ticks. package sdrtime // #cgo CFLAGS: -g -Wall // #cgo LDFLAGS: -lSoapySDR // #include <SoapySDR/Time.h> import "C" // TicksToTimeNs converts a tick count into a time in nanoseconds using the tick rate. // // Params: // - ticks: a integer tick count //...
package main import ( "fmt" ) func main() { var x float64 fmt.Scan(&x) var y float64 fmt.Scan(&y) fmt.Printf("%.3f km/l\n", x/y) }
package rank // beginner, master... type Rank struct { ID string `datastore:"-"` Values map[string]string `json:"values"` } type Ranks map[string]*Rank
package fixer import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/url" ) // Client ... type Client struct { APIKey string BaseURL *url.URL UserAgent string httpClient *http.Client } // APIError ... type APIError struct { Code int `json:"code"` Type string `json:"type"` Info string `json...
// +build integrate package postgres import ( "testing" "github.com/jackc/pgx/pgtype" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/neuronlabs/neuron-core/query" ) // TestRepositoryGet tests get repository function. func TestRepositoryGet(t *testing.T) { c, db := prep...
// Copyright (c) 2018-2020 Double All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package captcha import ( "crypto/aes" "crypto/cipher" "crypto/md5" "crypto/rand" "encoding/hex" "io" ) // Some get or a default value func Some(target i...
package agora import ( "fmt" "math" ) const pageSize = 4 const pageSize8 = 8 // GetPageSize method func GetPageSize(isDualCamera int8) int { if isDualCamera == 1 { return pageSize } else { return pageSize8 } } // GetTotalPage method. func GetTotalPage(total int, isDualCamera int8) int8 { if isDualCamera =...
// Copyright (C) 2018 Storj Labs, Inc. // See LICENSE for copying information. package overlay //go:generate protoc --go_out=plugins=grpc:. overlay.proto
package ecr import ( "fmt" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" awsecr "github.com/aws/aws-sdk-go/service/ecr" "github.com/aws/aws-sdk-go/service/ecr/ecriface" ecrapi "github.com/awslabs/amazon-ecr-credential-helper/ecr-login/...
package text import ( "strings" "unicode/utf8" "github.com/Vovan-VE/maze-go/pkg/maze/data" ) // Exporter implements MazeExporter for text format type Exporter struct { *baseConfig } // NewExporter creates new Exporter func NewExporter() *Exporter { return &Exporter{newBaseConfig()} } // ConfigureExport config...
package browser import ( "github.com/golang/freetype/truetype" "github.com/llgcode/draw2d" ) type FontCache map[string]*truetype.Font func (f FontCache) Load(fd draw2d.FontData) (*truetype.Font, error) { font, ok := f[fd.Name] if !ok { return f["roboto"], nil } return font, nil } func (f *FontCache) Store(f...
package fixtures // Useful SQL queries: // --- // Generate 10 UUID v4 // SELECT uuid_generate_v4() FROM generate_series(1,10); // // Get timezones // Select * from pg_timezone_names() import ( "database/sql" "time" models "github.com/gomeetups/gomeetups/models" ) // Addresses - Contains address fixtures for gr...
/* * @lc app=leetcode.cn id=98 lang=golang * * [98] 验证二叉搜索树 */ package main import "math" type TreeNode struct { Val int Left *TreeNode Right *TreeNode } /* 直接判断左右值 func isValidBST(root *TreeNode) bool { return isValidbst(root, math.MinInt64, math.MaxInt64) } func isValidbst(root *TreeNode, min, max float...
package main import ( "fmt" "sort" "strconv" ) func main() { var vec []int = make([]int, 0, 3) for { var temp string fmt.Scan(&temp) if temp == "X" { break } number, err := strconv.Atoi(temp) _ = err vec = append(vec, number) sort.Ints(vec) for i, v := range vec { fmt.Printf("%d ...
package sigma import ( "math" "github.com/yash-ontic/morgoth" "github.com/yash-ontic/morgoth/counter" ) // Simple fingerprinter that computes both mean and standard deviation of a window. // Fingerprints are compared to see if the means are more than n deviations apart. type Sigma struct { deviations float64 } ...
package urlutil import ( "net/url" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestIsRedirectAllowed(t *testing.T) { // from: https://raw.githubusercontent.com/random-robbie/open-redirect/master/payloads.txt rawurls := strings.Fields(` &%0d%0a1Location...
package main import ( "fmt" "github.com/gorilla/mux" "net/http" ) func getView(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") fmt.Fprintln(w, "<h1>GET!</h1>") } func postView(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") fmt.Fprint...
package user import ( "encoding/json" "github.com/MerinEREN/iiPackages/datastore/user" "github.com/MerinEREN/iiPackages/session" "google.golang.org/appengine/datastore" "google.golang.org/appengine/memcache" "log" ) // Get tries to return logged user from the memcache first, // if fails, tries to return logged ...
package main import "fmt" func main(){ f := func(v string)bool{ return v=="golang" } resutl := match("golang", f) fmt.Println(resutl) } //membuat function yang mengembalikan nilai boolean func match(v string, f func(string)bool)bool{ if f(v){ return true } return false }
// Copyright 2023 Google LLC. 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 applica...
//************************************************************************// // rsc - RightScale API command line tool // // Generated with: // $ praxisgen -metadata=ss/ssm/restful_doc -output=ss/ssm -pkg=ssm -target=1.0 -client=API // // The content of this file is auto-generated, DO NOT MODIFY //*...
package raft // raft export interface // push entries to raft cluster func PushEntries(string entries) // set entries commit recv chan func SetCommitEntriesChan(entries_recv chan<-string);
package vugu import ( "testing" "github.com/stretchr/testify/assert" ) func TestBuildEnvCachedComponent(t *testing.T) { assert := assert.New(t) be, err := NewBuildEnv() assert.NoError(err) assert.NotNil(be) { // just double check sane behavior for these keys k1 := MakeCompKey(1, 1) k2 := MakeCompKey(1,...
// Copyright 2023 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 i...
package method import ( "github.com/jinzhu/gorm" "go-admin/models" ) func PagingServer(pageParams models.KPIQueryParam, db *gorm.DB) { var total int limit := pageParams.PageSize offset := pageParams.PageSize * (pageParams.Current - 1) _ = db.Model(&models.KPI{}).Count(&total).Error db.Limit(limit).Offset(offse...
package main import ( "fmt" "math" ) const ( InitialStep = float64(1) Delta = .000000001 ) type ErrNegativeSqrt float64 func (e ErrNegativeSqrt) Error() string { return fmt.Sprintf("Cannot Sqrt negative number: %g", float64(e)) } func newtonsMethod(x float64) (float64, error) { if x < 0 { return 0, E...
package client import ( "bufio" "fmt" "io/ioutil" "net" "net/http" "net/url" "os" "path" "strconv" "strings" printer "github.com/olekukonko/tablewriter" konfig "github.com/zalando/chimp/conf/client" . "github.com/zalando/chimp/types" "golang.org/x/crypto/ssh/terminal" ) //Client is the struct for acces...
package crypt_test import ( "testing" "github.com/GehirnInc/crypt" _ "github.com/GehirnInc/crypt/apr1_crypt" "github.com/stretchr/testify/assert" ) func TestIsHashSupported(t *testing.T) { apr1 := crypt.IsHashSupported("$apr1$salt$hash") assert.True(t, apr1) other := crypt.IsHashSupported("$unknown$salt$hash"...
package main import "fmt" func plusTwo() func(int) int { return func(x int) int { return x + 2 } } func plusX() func(int) int { return func(x int) int { return x + x } } func main() { p := plusTwo() x := plusX() fmt.Println(p(2)) fmt.Println(x(3)) }
package email import ( "bytes" "html/template" "log" "github.com/VolticFroogo/Animal-Pictures/models" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ses" ) // Register sends the account registry email. func Register(code, username, email string) (err...
package models import ( "context" "database/sql" "fmt" "strings" "github.com/jmoiron/sqlx" ) // LoadPersonConfig returns the config for person model entries. func LoadPersonConfig(dialect *SQLDialect) *DatabaseModel { conf := ModelConfig{ Create: `CREATE TABLE IF NOT EXISTS person( id $TEXT PRIMARY KEY, ...
package tplmgr import ( "context" "net/http" "strings" "github.com/justinas/nosurf" "github.com/pkg/errors" "github.com/volatiletech/authboss" ) type HTMLData = authboss.HTMLData type AuthbossHTMLRenderer struct { extension string } func NewAuthbossHTMLRenderer() *AuthbossHTMLRenderer { return &AuthbossHTM...
package rpc import ( "encoding/json" "errors" ) const ( JSON_RPC_VER = "2.0" MaxMultiRequest = 10 ParseErr = -32700 // -32700 语法解析错误,服务端接收到无效的json。该错误发送于服务器尝试解析json文本 InvalidRequest = -32600 // -32600 无效请求发送的json不是一个有效的请求对象。 MethodNotFound = -32601 // -32601 找不到方法 该方法不存在或无效 InvalidParamErr = -326...
package process import ( "github.com/yacc2007/pop-network/types" "github.com/yacc2007/pop-network/vm" "sync" "github.com/pkg/errors" log "github.com/Sirupsen/logrus" "github.com/yacc2007/pop-network/util" ) var ( ResultHashNotMatch error = errors.New("data hash not match") ) type Executor...
package main import ( "errors" "strconv" ) var teams = [TeamCount]string{"yellow", "red", "green", "blue"} func NotationRollFromString(rollStr string) (*roll, error) { if len(rollStr) != 3 { return nil, errors.New("roll should be in format die1+die2") } else if rollStr[1] != '+' { return nil, errors.New("bad...
/* Tencent is pleased to support the open source community by making Basic Service Configuration Platform available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain...
package wps import ( `encoding/json` `fmt` ) const ( // 状态码 // StatusOk 成功 StatusOk string = "200" // 参数错误 // StatusParamsError string = "400" ) // Wps 金山文档 type Wps struct { // ApiUrl 服务器地址 ApiUrl string `json:"apiUrl"` // PreviewUrl 浏览地址 ViewUrl string `json:"viewUrl"` // 文档预览前缀 PreviewPrefix string `...