text
stringlengths
11
4.05M
/* Copyright 2021 The KubeVela 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 agreed to in writing, so...
package output import ( "fmt" "github.com/fatih/color" ) func Info(s string) { green := color.New(color.FgGreen, color.Bold) green.Printf("[%-12s] ", "Information") fmt.Print(s) } func Error(s string) { red := color.New(color.FgRed, color.Bold) red.Printf("[%-12s] ", "Error") fmt.Print(s) } func ...
package handler import ( "fmt" "html/template" "io" "net/http" "os" "path/filepath" "strconv" "strings" "github.com/GoGroup/Movie-and-events/event" "github.com/GoGroup/Movie-and-events/form" "github.com/GoGroup/Movie-and-events/hash" "github.com/GoGroup/Movie-and-events/rtoken" "github.com/GoGroup/Movi...
package seeders import ( "math/rand" "time" "github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/entity" "github.com/bxcodec/faker/v3" ) type TransactionsSeeders struct { StatusPayment string `faker:"oneof: passed, failed"` } func TransactionsSeedersUp(number int) { seeder := TransactionsSe...
package main import ( . "ast" cg "backend/codeGeneration" fw "backend/filewriter" "fmt" "io/ioutil" "os" "parser" "path/filepath" ) const SYNTAX_ERROR = 100 const SEMANTIC_ERROR = 200 func main() { armList := &fw.ARMList{} file := os.Args[1] // index 1 is file path b, err := ioutil.ReadFile(file) if err...
package cloudflare import ( "testing" "github.com/stretchr/testify/assert" ) func TestResourceProperties(t *testing.T) { testCases := map[string]struct { container *ResourceContainer expectedRoute string expectedType string expectedIdentifier string }{ account: { container: ...
package cls import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" ) type LogSets struct { LogSets []LogSet `json:"logsets"` } type LogSet struct { LogSetID string `json:"logset_id"` LogSetName string `json:"logset_name"` CreateTime string `json:"create_time"` Period int ...
package protobuf import ( "encoding" ) var generators = newInterfaceRegistry() // InterfaceMarshaler is used to differentiate implementations of an // interface when encoding/decoding type InterfaceMarshaler interface { encoding.BinaryMarshaler MarshalID() [8]byte } // InterfaceGeneratorFunc generates an instanc...
package boshio_test import ( "errors" "io" "io/ioutil" "net/http" "net/url" "os" "path/filepath" "strings" "time" "github.com/concourse/bosh-io-stemcell-resource/boshio" "github.com/concourse/bosh-io-stemcell-resource/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) type EOFReader struct{...
package util import ( "log" "regexp" ) const NameRegexFragment = `(([a-zA-Z][a-zA-Z0-9_\-\.]*[a-zA-Z0-9])|([a-zA-Z]))` const NameRegexPattern = `^` + NameRegexFragment + `$` var NameRegex = regexp.MustCompile(NameRegexPattern) const URIRegexPattern = `^(` + NameRegexFragment + `[\/]?)*$` var URIRegex = regexp.M...
// Copyright 2013 Walter Schulze // // 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...
package repositories import ( "database/sql" "errors" "fmt" "log" "ocg-be/database" "ocg-be/models" "reflect" ) type ProductStorage struct { } type RequestGetProductByCollectionId struct { CollectionId int `json:"collection_id"` Limit int `json:"limit"` Offset int `json:"offset"` Pag...
package audit import ( "context" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" api "nighthawkapi/api/core" "nighthawkapi/api/handlers/config" "strconv" elastic "gopkg.in/olivere/elastic.v5" "github.com/gorilla/mux" ) type ReturnBucket struct { Key string `json:"key"` DocCount int64 `json:...
// Copyright © 2021 Attestant Limited. // 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 ...
package cointop import ( "log" "os/exec" "github.com/jroimartin/gocui" ) func (ct *Cointop) setKeybinding(key interface{}, callback func(g *gocui.Gui, v *gocui.View) error) { var err error switch t := key.(type) { case gocui.Key: err = ct.g.SetKeybinding("", t, gocui.ModNone, callback) case rune: err = ct...
package memory import ( "context" "errors" "go.uber.org/zap" "github.com/silverspase/todo/internal/modules/todo" "github.com/silverspase/todo/internal/modules/todo/model" ) type memoryStorage struct { items map[string]model.Item // TODO change to sync.Map // itemsArray []model.Item // TODO use this for pagin...
package component import "image/color" // Rect component. type Rect struct { Color color.RGBA W, H int32 Active bool } // NewRect rect constructor. func NewRect(c color.RGBA, w, h int32, active bool) *Rect { return &Rect{c, w, h, active} } // Name component implementation. func (c *Rect) Name() string { ret...
package db import ( "os" "github.com/sirupsen/logrus" "gitlab.com/NagByte/Palette/common" "gitlab.com/NagByte/Palette/db/mongo" "gitlab.com/NagByte/Palette/db/neo4j" "gitlab.com/NagByte/Palette/db/wrapper" ) var ( Neo wrapper.Database Mongo wrapper.Database ) func init() { mongoInit() neoInit() } func...
// 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 ...
package Models type Client struct { Id uint `json:"id"` Name string `json:"name"` URL string `json:"url"` Description string `json:"description"` } func (c *Client) TableName() string { return "client" }
package main import ( "context" "log" pb "github.com/naichadouban/learngrpc/demo7-simple-http/proto" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "net" "time" ) const ( port = ":8010" ) type ...
package app import ( "errors" "strings" "testing" "github.com/10gen/realm-cli/internal/cli" "github.com/10gen/realm-cli/internal/cloud/realm" "github.com/10gen/realm-cli/internal/utils/test/assert" "github.com/10gen/realm-cli/internal/utils/test/mock" "go.mongodb.org/mongo-driver/bson/primitive" ) func Test...
package main import ( "fmt" ) func main() { for i := 0; i < 1; i++ { switch { case true: fmt.Println("hello") break // target is switch } fmt.Println("world") // reachable } fmt.Println("----- use label -----") FOR: for i := 0; i < 1; i++ { switch { case true: fmt.Println("hello") break ...
package core import ( "encoding/hex" "fmt" "github.com/golang/protobuf/ptypes" "github.com/mr-tron/base58/base58" "github.com/textileio/go-textile/crypto" "github.com/textileio/go-textile/pb" "golang.org/x/crypto/bcrypt" ) // CafeTokens lists all locally-stored (bcrypt hashed) tokens func (t *Textile) CafeTok...
package filepath import "strings" // Join is an explicit-OS version of path/filepath's Join. func Join(os string, elem ...string) string { sep := Separator(os) return Clean(os, strings.Join(elem, string(sep))) }
package endpoints import ( "github.com/aws/aws-sdk-go/service/ec2" ) type Clients struct { EC2 EC2Client } // EC2Client describes the methods required to be implemented by a EC2 AWS client. type EC2Client interface { DescribeInstances(*ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) }
package testapplication import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" ) // NewHandler returns a handler for "testapplication" type messages. func NewHandler(keeper Keeper) sdk.Handler{ return func(ctx sdk.Context, msg sdk.Msg) sdk.Result{ switch msg := msg.(type){ case MsgTransmitBol: return h...
package main import ( "net/http" "html/template" "io" ) var t *template.Template func init(){ t=template.Must(template.ParseFiles("112_ajaxserver2.html")) } func main() { http.HandleFunc("/",index) http.HandleFunc("/foo",foo) http.Handle("/favicon.ico",http.NotFoundHandler()) http.ListenAndServe(":8080",nil...
/* * randmat: random number generation * * input: * nrows, ncols: the number of rows and columns * s: the seed * * output: * Randmat_matrix: a nrows x ncols integer matrix * */ package all var Randmat_matrix [][]byte; func randvec(row, n, seed int, done chan bool) { LCG_A := uint32(1664525) LCG_C :=...
package flag import ( "testing" rzcheck "github.com/robert-zaremba/checkers" gocheck "gopkg.in/check.v1" ) // Hook up gocheck into the "go test" runner. func Test(t *testing.T) { gocheck.TestingT(t) } type ExtraSuite struct{} func init() { gocheck.Suite(&ExtraSuite{}) } func (s *ExtraSuite) TestValidateDirExi...
package calendar import ( "context" "github.com/Azimkhan/go-calendar-grpc/internal/models" ) type Usecase interface { Fetch(ctx context.Context) ([]*models.CalendarEvent, error) GetByID(ctx context.Context, id int64) (*models.CalendarEvent, error) Update(ctx context.Context, ar *models.CalendarEvent) error Stor...
package request import "github.com/dmitrymomot/go-jwt" type ( // Auth interface Auth interface { GetAccessToken() string GetUserID() string SetUserID(uid string) GetUserRole() string SetUserRole(role string) GetAppID() string SetAppID(aid string) GetClaims() jwt.Claims SetClaims(claims jwt.Claims)...
package main type person struct { name string username string age int } func (r *person) isFirst() { r.username = "Qaroev" r.name = "Gulboy" r.age = 22 } func main() { ma1() } func (r *person) ma1() { r.isFirst() }
package routers import ( "github.com/astaxie/beego" "github.com/astaxie/beego/context/param" ) func init() { beego.GlobalControllerRouter["sdrms/controllers:CategoryTypeController"] = append(beego.GlobalControllerRouter["sdrms/controllers:CategoryTypeController"], beego.ControllerComments{ Method: "Index", ...
package services import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "log" "net/http" "github.com/constant-money/constant-event/config" ) // HookService : struct type HookService struct{} // Event : send data to logic server func (h HookService) Event(jsonData map[string]interface{}) error { conf :...
package main import ( "io/ioutil" "os" "tibiaScrapper/bazaar" "tibiaScrapper/utils" "time" "github.com/gocolly/colly/v2" log "github.com/sirupsen/logrus" ) type character struct { Url string `json:"url"` Name string `json:"char_name"` CrawledAt time.Time `json:"crawled_at"` } type page struct {...
package supl import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01700101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:supl.017.001.01 Document"` Message *PaymentSD1V01 `xml:"PmtSD1"` } func (d *Document01700101) AddMessage() *PaymentSD1V01 { d...
package main import ( "fmt" "time" "testing" "sync" ) // Messing with goroutines func prnt(s string) { fmt.Printf("[%s]\t\t%s\n", time.Now().String(), s) } func main() { prnt("tests") } func Test1(t *testing.T) { prnt("Test1 start") go gotest() time.Sleep(time.Millisecond * 10) ...
package main import ( "encoding/json" "flag" "fmt" "log" "os" "github.com/doza-daniel/diameter/convexhull" "github.com/doza-daniel/diameter/line" "github.com/doza-daniel/diameter/point" ) func main() { flag.String("json", "", "JSON array of points") flag.Parse() file := flag.Arg(0) var in *os.File if ...
package wsr var errorMap map[int32]string = make(map[int32]string, 50) //成功 const ERR_SUCC int32 = 0 //基础设施错误 const ERR_LOAD_LIB int32 = 1000 const ERR_INTERFACE int32 = 1002 const ERR_COM_PORT_NOTFOUND int32 = 1003 //业务错误 const ERR_UUID_LENGTH int32 = 2000 const ERR_LOAD_PSW_LEN int32 = 2001 const ERR_SET_PSW_LEN...
package server import ( "2019_2_IBAT/pkg/app/auth/session" . "2019_2_IBAT/pkg/app/chat/models" "2019_2_IBAT/pkg/app/chat/repository" "2019_2_IBAT/pkg/app/chat/service" "2019_2_IBAT/pkg/pkg/config" "2019_2_IBAT/pkg/pkg/db_connect" "2019_2_IBAT/pkg/pkg/middleware" "strconv" "sync" "net/http" "fmt" "log" ...
package server import ( "net/http" "fmt" "log" oauthsvc "github.com/danielsomerfield/authful/server/service/oauth" "time" "github.com/danielsomerfield/authful/common/util" "github.com/danielsomerfield/authful/server/handlers/oauth/token" "github.com/danielsomerfield/authful/server/handlers/oauth/authorization"...
package binarytree import ( "testing" "github.com/stretchr/testify/assert" ) func generateBinaryTree() *BinaryTree { // generateBinaryTree() should create the following binary tree // 10 // / \ // 5 15 // / \ / \ // 3 7 13 17 // /\ /...
package main import ( "fmt" "sort" "strconv" "sync" ) // сюда писать код func SingleHash(in, out chan interface{}) { var muMD5 sync.Mutex for val := range in { data := fmt.Sprintf("%d", val) ch_crc32_1 := dataSignerCrc32(data) muMD5.Lock() md5 := DataSignerMd5(data) muMD5.Unlock() ch_crc32_2 := ...
package evaluator import ( "github.com/kasworld/nonkey/config/builtinfunctions" "github.com/kasworld/nonkey/interpreter/object" ) func init() { builtinfunctions.BuiltinFunctions = map[string]*object.Builtin{ "version": {Fn: builtinVersion}, "args": {Fn: builtinArgs}, "chmod": {Fn: b...
package config //TODO: better way https://dev.to/ilyakaznacheev/a-clean-way-to-pass-configs-in-a-go-application-1g64 // https://eltonminetto.dev/en/post/2018-06-25-golang-usando-build-tags/ //GeneralConfig GeneralConfig type GeneralConfig struct { DatabaseHost string DatabaseName string APIPort string } //De...
package main import "fmt" func main() { // num1, num2 := 3,5 // 数学运算: 加减乘除 fmt.Println("请输入两个整数:") var num1 int var num2 int fmt.Scanln(&num1,&num2) //输入想要执行的操作 fmt.Println("请输入要执行的操作符号(+、-、*、/):") var str string fmt.Scanln(&str) // + 、 - 、* 、/ switch str { // + 、 - 、* 、/ case "+": fmt.Println("两数相...
package main import "fmt" func main() { var t int fmt.Scan(&t) for i := 0; i < t; i++ { var n int fmt.Scan(&n) // sum divisible by 3 arith3 := finiteArithmethicSum(n-1, 3) // sum divisible by 5 arith5 := finiteArithmethicSum(n-1, 5) // sum of duplicates arith15 := finiteArithmethicSum(n-1, 15) //...
package toolkit import ( "sort" "strings" ) // GetFieldsNameByTag is to get an array of field names from the label value // The parameter `source` must be a structure, // The parameter `tagValue` specifies a structure tagValue. func GetFieldsNameByTag(source interface{}, tagValue string) (fields []string, err error...
package controllers import "github.com/gin-gonic/gin" type IController interface { } type IResourceController interface { Index(*gin.Context) Create(*gin.Context) Store(*gin.Context) Show(*gin.Context) Edit(*gin.Context) Update(*gin.Context) Destroy(*gin.Context) } func ResourceController(g *gin.RouterGroup,...
package wechat import ( mpoauth2 "gopkg.in/chanxuehong/wechat.v2/mp/oauth2" wxuser "gopkg.in/chanxuehong/wechat.v2/mp/user" "gopkg.in/chanxuehong/wechat.v2/oauth2" ) // GetUserInfo 根据微信 OpenID 获得用户信息 func (u *Wxmp) GetUserInfo(openID string) (*wxuser.UserInfo, error) { const lang = "zh_CN" return wxuser.Get(u.We...
package main import ( "github.com/docker/app/internal" app "github.com/docker/app/internal/commands" "github.com/docker/cli/cli-plugins/manager" "github.com/docker/cli/cli-plugins/plugin" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" ) func main() { plugin.Run(func(dockerCli command.Cli) *cobra....
// Package dogmatiqapp is an practice Dogma application. package dogmatiqapp
package model import ( "github.com/jinzhu/gorm" ) type RecordModel struct { db *gorm.DB } type Record struct { ID int `json:"id"` DomainID int `json:"domain_id"` Name string `json:"name"` Type string `json:"type"` Content string `json:"content"` TTL int `json:"ttl"` Prio ...
package main import ( "fmt" ) func main() { s1 := []int{1} fmt.Println("s1 = ", s1) fmt.Printf("s1: len = %d, cap = %d\n", len(s1), cap(s1)) // append函数,是向切片末尾追加元素,并且返回一个新的切片 s1 = append(s1, 2) fmt.Println("s1 = ", s1) fmt.Printf("s1: len = %d, cap = %d\n", len(s1), cap(s1)) s1 = append(s1, 3) fmt.Println...
// Go support for Protocol Buffers RPC which compatiable with https://github.com/Baidu-ecom/Jprotobuf-rpc-socket // // Copyright 2002-2007 the original author or 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 ...
package main import ( "fmt" "log" "net" ) func main() { host, _, err := net.SplitHostPort("127.0.0.1:12345") if err != nil { log.Fatalln(err) } addr := net.ParseIP(host) if addr == nil { println("not valid ip") } else { fmt.Printf("ip: %s\n", addr) } }
package main import ( "context" "database/sql" "fmt" "log" "math/rand" "time" "github.com/Rican7/retry" "github.com/Rican7/retry/backoff" "github.com/Rican7/retry/jitter" "github.com/Rican7/retry/strategy" ) func doQuery(ctx context.Context, db *sql.DB, runnerId string) { ticker := time.NewTicker(10 * ti...
package main func main() { } func postorderTraversal(root *TreeNode) (res []int) { addPath := func(node *TreeNode) { path := []int{} for ; node != nil; node = node.Right { path = append(path, node.Val) } for i := len(path) - 1; i >= 0; i-- { res = append(res, path[i]) } } p1 := root for p1 != ni...
package main import "fmt" // type person struct { // name string // age int // } // func newPerson(name string, age int) person { // return person{ // name: name, // age: age, // } // } // func (p person) older() { // p.age++ // } // func (p *person) oldert() { // //(*p).age++ // p.age++ //语法糖 // } // ...
package quark import ( "log" "net/http" "time" ) // 用户请求拦截器 func UserRequestInterceptor(ct Context) error { token := ct.GetAccessToken() if token == "" { return Next } // 令牌校验 user, has := VerifyAccessToken(token) if !has { return ct.To401() } if user != "" { ct.User = user ct.Request.Header.Add(...
package main import ( "encoding/json" "fmt" "github.com/gorilla/mux" "time" "log" "os" _"strings" _"context" "net/http" "golang.org/x/crypto/bcrypt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "github.com/joho/godotenv" "github.com/dgrijalva/jwt-go" ) type Exceptio...
package main import ( "ms/sun/servises/file_service/file_common" "net/url" "ms/sun/shared/helper" ) func main() { url, _ := url.Parse("http://localhost:5151/post_file/1518506476136010007_180.jpg") req := file_common.NewRowReq(file_common.HttpCategories[1], url) //helper.PertyPrintNew(req) helper.PertyPrint...
package routers import ( "github.com/gin-gonic/gin" "net/http" "regexp" ) func InitRouter() *gin.Engine { router := gin.Default() router.Use(CorsMiddleware()) router.GET("/test", func(ctx *gin.Context) { ctx.String(200, "its working") }) SetNoteRouter(router) SetMemberRouter(router) SetTagRouter(router) ...
package main import ( "fmt" "log" "sync" ) var wg1 sync.WaitGroup func init() { log.SetFlags(log.Lshortfile) } func producer1(sch chan<- int) { defer wg1.Done() for i := 0; i < 10; i++ { sch <- i fmt.Printf("ch<------生产 %d\n", i) } close(sch) } func consumer1(rch <-chan int) { defer wg1.Done() for v ...
/* Package slack is a Connection to the Slack Real Time Messaging API (https://api.slack.com/rtm). To use this connection, you will need to create a custom bot user. See https://api.slack.com/bot-users#custom_bot_users. Once you've created a bot user, you will need to initialize the Slack connection using the API key ...
// Copyright 2018 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 models import ( "github.com/labstack/echo/v4" "net/http" ) type httpContext struct { c echo.Context } type Response struct { Code int `json:"code"` MessageCode int `json:"message_code"` Message string `json:"message"` Data interface{} `json:"data"` } type Result...
package mongodb import ( "gopkg.in/mgo.v2" "sync" ) var ( ins *mgo.Session conErr error once sync.Once dbUrl string ) // 实例化Mongo func Connect() *mgo.Session { once.Do(func() { dbUrl = "mongodb://myuser:mypass@localhost:40001,otherhost:40001/mydb" ins, conErr = mgo.Dial("localhost:27017") if conErr != ...
package main import ( "fmt" "net/http" "os" "os/exec" "strings" "time" "github.com/go-redis/redis" "github.com/gocolly/colly" ) const ( restockurl = "https://www.queens.cz/kat/2/boty-tenisky-panske/?sort=new" ) type product struct { ID, Name, Price, Thumb, URL string } func atc(id, name, url, price, thum...
package logs import ( "bufio" "context" "sort" "strings" "sync" "time" log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/k...
package main import ( "context" "fmt" "go.etcd.io/etcd/clientv3" "time" ) func main() { cli, err := clientv3.New(clientv3.Config { Endpoints: []string{"127.0.0.1:2379"}, // etcd的节点,可以传入多个 DialTimeout: 5*time.Second, // 连接超时时间 }) if err != nil { fmt.Printf("connect to etcd failed, err: %v \n", err) ret...
/* * Tencent is pleased to support the open source community by making Blueking Container Service 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 obta...
package main import ( "fmt" "strconv" ) func main() { var _ = Valid("") } func Valid(ccNumber string) (valid bool) { // ccNumber = "378282246310005" ccNumber = "4539148803436467" ccInt, err := strconv.Atoi(ccNumber) if err != nil { return false } cardDigits := []int{} for ccInt > 0 { cardDigits = appen...
package main // OK! 3'54 import ( "bufio" "fmt" "os" "strconv" ) var sc = bufio.NewScanner(os.Stdin) func nextInt() int { sc.Scan() i, e := strconv.Atoi(sc.Text()) if e != nil { panic(e) } return i } func main() { /* 初期化開始 */ sc.Split(bufio.ScanWords) x := nextInt() y := nextInt() /* 初期化終了 */ fmt....
/** *@Author: haoxiongxiao *@Date: 2019/2/2 *@Description: CREATE GO FILE sms_api_services */ package sms_api_services import ( "bysj/models" "bysj/models/redi" "github.com/garyburd/redigo/redis" "github.com/lexkong/log" "github.com/spf13/viper" "github.com/xhaoxiong/ShowApiSdk/normalRequest" ) type SmsApiServi...
package mutexs import ( "testing" ) func TestMutexChannel(t*testing.T){ MutexChannel() } func TestMutexChannelBuffer(t*testing.T){ MutexChannelBuffer() }
package dcp // Given an integer n, return the length of the longest consecutive run of 1s in its binary representation. // For example, given 156, you should return 3. func longestConsecutive1s(n int) int { longest, current := 0, 0 for n > 0 { r := n % 2 n /= 2 if r == 0 { current = 0 } else { curren...
package day6 import ( "fmt" ) func part1(a_tree *tree) int { sum := 0 for _, node := range a_tree.nodes { sum += node.depth } return sum } func part2(a_tree *tree) int { n_transfers := 0 you, san := a_tree.nodes["YOU"].parent, a_tree.nodes["SAN"].parent for you.depth < san.depth { san = san.parent n_t...
// Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license"...
package alibabacloud import ( "fmt" "strings" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/validation/field" "github.com/openshift/installer/pkg/types" alibabacloudtypes "github.com/openshift/installer/pkg/types/alibabacloud" ) // Validate executes platform-specific validation. func Valid...
package main import "fmt" func main() { if 7%5 == 0 { //if 7 is divisible by 5 fmt.Println("buset bg") } else { //penulisan else di golang harus 1line setelah tutup if{} fmt.Println("kayae tidak mungkin. males mau jabarin") } if 10+10 == 20 { // check color formating... // buset.. // digolang statment ...
package inform import ( // Standard library "io/ioutil" "net/http" "net/url" "strings" // Third-party packages "github.com/pkg/errors" ) // Options represent user-configurable values, which are used in processing commands // and formatting output. type Options struct { Prefix string } // Default values for ...
package message const ( InvalidRequest = "Invalid Request." SomethingWrong = "Something Went Wrong. Please try again." EmailInUse = "email address already in use" EmailNotRegistered = "Email is not registered with us." TokenIsNotValid = "Token is invalid." TokenIsExpired = "Token is ...
package ttlcache import ( "fmt" "math/rand" "testing" "time" ) func TestCleanupLatency(t *testing.T) { t.Run("100kv", func(t *testing.T) { cache := NewCache(0) for _, kv := range genKV(100) { cache.Set(kv[0], kv[1]) } time.Sleep(1100 * time.Millisecond) now := time.Now() cache.Cleanup() fmt.Prin...
package tail import ( "bufio" "context" "log" "os" "sync" "github.com/marcsauter/rtail/pkg/pb" ) // Tailer interface type Tailer interface { File(context.Context, *pb.FileRequest) } // tail type tail struct { sync.Mutex wg *sync.WaitGroup stream pb.Proxy_RegisterClient } // New returns a new Tailer f...
package lib import ( "encoding/json" "errors" "fmt" "log" "net/http" "net/url" ) // Google Maps API reference on reverse geocoding. // https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding const ( MAP_API_URL = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false" MAP_Q_URL ...
package main import ( post "actions/post" "cp" "da" "log" "routes" "github.com/hjin-me/banana" ) func main() { ctx := banana.App() log.Println("server started") cfg, ok := ctx.Value("cfg").(banana.AppCfg) if !ok { log.Fatalln("configuration not ok") } dsnRaw, ok := cfg.Env.Db["mysql"] if !ok { log.F...
package fileversion import "github.com/scjalliance/drivestream/resource" // Reference is a file version reference. type Reference interface { // File returns the ID of the file. File() resource.ID // Version returns the version number of the file. Version() resource.Version // Create creates a new file version...
package dbinitializer import ( "database/sql" "fmt" "log" "github.com/kenigbolo/go-web-app/model" _ "github.com/lib/pq" // Database initializer ) // ConnectToDatabase function func ConnectToDatabase() *sql.DB { db, err := sql.Open("postgres", "postgres://postgres:postgres@localhost/go_web_app?sslmode=disable")...
package models type Project struct { name string criteria Criteria } //docAddress表示项目文件地址 //proAddress表示项目地址 type CreateProjectResult struct { DocAddress interface{} ProAddress interface{} }
// Copyright 2017 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 state func (state *luaState) GetTop() int { return state.stack.top } func (state *luaState) AbsIndex(idx int) int { return state.stack.absIndex(idx) } func (state *luaState) CheckStack(n int) bool { state.stack.check(n) return true } func (state *luaState) Pop(n int) { for i := 0; i < n; i++ { state....
package cryptutil import ( "crypto/hmac" "crypto/sha512" "golang.org/x/crypto/bcrypt" "google.golang.org/protobuf/proto" ) // Hash generates a hash of data using HMAC-SHA-512/256. The tag is intended to // be a natural-language string describing the purpose of the hash, such as // "hash file for lookup key" or "...
package utils import ( "net/http" "strings" tr "github.com/ebikode/eLearning-core/translation" "github.com/go-sql-driver/mysql" ) const ( // ER_DUP_ENTRY ER_DUP_ENTRY = 1062 AdminStaffID = "uix_admins_staff_id" AdminPhone = "uix_admins_phone" AdminEmail = "uix_admins_email" AccountP...
package model import ( "time" ) type BaseModel struct { ID int `gorm:"column:id;primary_key" json:"id"` CreatedAt time.Time `gorm:"column:created_at" json:"created_at"` UpdatedAt time.Time `gorm:"column:updated_at" sql:"index" json:"updated_at"` DeletedAt *time.Time `gorm:"column:deleted_at" sql:...
// Copyright (c) Facebook, Inc. and its affiliates. // All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. package main import ( "fmt" "github.com/davecgh/go-spew/spew" "github.com/facebookexperimental/GOAR/taile...
package controller import ( "model" "appengine" "net/http" "html/template" ) var transactionsTmpl = template.Must(template.ParseFiles("templates/transactions.html")) func transactions(c appengine.Context, w http.ResponseWriter, r *http.Request) error { budget, err := model.CurrentBudget(c) if err != nil { ht...
package main import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "io/ioutil" "log" "net/http" "os" "path/filepath" "strings" "github.com/urfave/cli/v2" "golang.org/x/crypto/pbkdf2" ) type Paste struct { Paste struct { Nam...
package problem0039 import "testing" func TestCombininationSum(t *testing.T) { t.Log(combinationSum([]int{2, 3, 6, 7}, 7)) t.Log(combinationSum([]int{2, 3, 5}, 8)) }