text
stringlengths
11
4.05M
// Copyright 2017 Intel Corporation. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "fmt" "github.com/intel-go/cpuid" ) func main() { fmt.Printf("VendorString: %s\n", cpuid.VendorIdentificatorString) fmt.Printf("ProcessorBra...
package types const ( QueryHTLC = "htlc" ) // QueryHTLCParams is the query parameters for 'custom/htlc/htlc' type QueryHTLCParams struct { HashLock []byte }
// Copyright (c) 2020 Blockwatch Data Inc. // Author: alex@blockwatch.cc package chain import ( "fmt" ) type OpStatus int const ( OpStatusInvalid OpStatus = iota // 0 OpStatusApplied // 1 (success) OpStatusFailed OpStatusSkipped OpStatusBacktracked ) func (t OpStatus) IsValid() bool { return...
package config import ( "os" "path" "strings" "testing" "github.com/stretchr/testify/assert" rootcmd "github.com/instructure-bridge/muss/cmd" "github.com/instructure-bridge/muss/config" "github.com/instructure-bridge/muss/testutil" ) func testShowCommand(t *testing.T, cfg *config.ProjectConfig, args []strin...
package main import ( "fmt" "time" ) func main() { fmt.Println("Time in GO") t := time.Now() fmt.Println(t) fmt.Println(t.Year()) fmt.Println(t.Month()) fmt.Println(t.Day()) timeString := "January 21, 2020" from := "January 2, 2006" resTime, err := time.Parse(from, timeString) if err != nil { fmt.P...
package model import ( "github.com/pedromss/kafli/config/constants" "time" ) // Rate represents an interval in which to execute an action type Rate struct { Duration *time.Duration } func (cd Rate) String() string { if cd.Duration != nil { return cd.Duration.String() } return "" } // Set sets the rate valu...
package main import ( "fmt" "strconv" ) const pi=3.14 type test struct{ Ip string name string count int } func main(){ fmt.Println(pi) var res map[string]test res=make(map[string]test,99) res["192.168"]=test{"192.168","chunk",2} res["192.167"]=test{"192.167","block_gate",2} var resu string for i,_:=range...
/* 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 main import ( "context" "dat520/lab3/failuredetector" "dat520/lab3/leaderdetector" "encoding/json" "fmt" "log" "net" "os" "os/signal" "sort" "syscall" "time" ) const BufferSize = 1024 type main_server struct { connnection *net.UDPConn failureDetectorObj *failuredetector.EvtFailur...
package main const x = 10 // definido somente quando for usado var y int = 10 // definido na declaração var a int var b float64 // várias constantes const ( c1 int = 100 c3 float64 = 100.40 ) func main() { // a = x // x será int // b = x // x será float // a = y // sucesso // b = y // erro }
// go切片 // 切片是拥有相同类型元素的可变长度的序列是基于数组类型做的一层封装 灵活支持自动扩容 // 切片拥有自己的长度和容量 len()求长度 cap()求切片的容量 package main import "fmt" func main(){ /* var a []string var b = []int{} var c = []bool{false,true} // var d = []bool{false,true} fmt.Println(a) fmt.Println(b) fmt.Println(c) fmt.Println(a == nil) fmt.Println(b == nil)...
// package main // import "fmt" // type Inner struct { // X int // } // type Outer struct { // Inner // X int // } // func main() { // o := Outer{ // Inner: Inner{ // X: 10, // }, // X: 20, // } // fmt.Println(o.X) // fmt.Println(o.Inner.X) // }
// Copyright 2015-2018 trivago N.V. // // 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 ...
/* Description: Create a program that will solve the banker’s algorithm. This algorithm stops deadlocks from happening by not allowing processes to start if they don’t have access to the resources necessary to finish. A process is allocated certain resources from the start, and there are other available resources. In ...
package model import ( "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/bson/primitive" "github.com/mongodb/mongo-go-driver/mongo" log "github.com/sirupsen/logrus" ) // User ... type User struct { Model `bson:",inline"` Block bool `bson:"block"` ...
package main import ( "crypto/sha1" "encoding/base64" "encoding/json" "flag" "fmt" "io" "io/ioutil" "log" "net/http" "os" "os/exec" "path/filepath" "strings" "time" "context" "golang.org/x/sync/errgroup" ) var ( userPass = flag.String("github_user_pass", "", "If non-empty, a user:password strin...
package mkhttpclient import ( "context" "encoding/json" "io/ioutil" "net/http" "strings" "testing" "time" ) func TestHttpOption(t *testing.T) { if c, ok := NewHTTPClient("http://domain").(*httpClient); !ok { t.Fatalf("NewHttpClient error") } else { currConfig := parseBaseConfig(defaultBaseConfig, c.optio...
package handler import ( "encoding/json" proto "github.com/kazoup/config/srv/proto/config" elastic "github.com/kazoup/elastic/srv/proto/elastic" flag "github.com/kazoup/flag/srv/proto/flag" "github.com/micro/go-micro/client" "github.com/micro/go-micro/errors" "golang.org/x/net/context" "io/ioutil" ) // Config...
package main import ( "context" "fmt" "log" "time" "github.com/utilitywarehouse/go-pubsub" "github.com/utilitywarehouse/go-pubsub/mockqueue" ) func main() { q := mockqueue.NewMockQueue() // MockQueue implements both source and sink var cons pubsub.MessageSource = q var sink pubsub.MessageSink = q go fu...
package osbuild2 // Tree inputs type TreeInput struct { inputCommon } func (TreeInput) isInput() {} func NewTreeInput() *TreeInput { input := new(TreeInput) input.Type = "org.osbuild.tree" input.Origin = "org.osbuild.pipeline" return input }
package data // add new change date func InsertChangedDate(tx *fiorm.FiTX,details []model.BasicDailyData){ } func NotifyReporter(){ }
package main import ( "errors" "fmt" "io" "net" "net/http" "runtime" "strings" "syscall" "time" awsauth "github.com/crunchyroll/go-aws-auth" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/s3" "github.com/rs/zerolog/log" ) var statRate float32 = 1 // List of headers to forwar...
/* * EVE Swagger Interface * * An OpenAPI for EVE Online * * OpenAPI spec version: 0.4.1.dev1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ package swagger // 201 created object type PostCharactersCharacterIdFittingsCreated struct { // fitting_id integer FittingId int32 `json:"f...
package main const api_url = "https://dictionary.skyeng.ru/api/public/v1" const api_v2_url = "https://dictionary.skyeng.ru/api/v2/" const exact_word_url = api_v2_url + "search-word-exact?word=" const words_url = api_url + "/words/search" const meanings_url = api_url + "/meanings"
package handlers import ( "encoding/json" "fmt" "io/ioutil" "net/http" "github.com/YAWAL/ERP-common-lib/logging" "github.com/YAWAL/ERP-common-lib/models" "github.com/YAWAL/HumanResourceMicroservice/src/repository" "github.com/gorilla/mux" ) const ( positionParameter = "position" idPara...
package main import ( "context" "fmt" "strings" ) func Handler(ctx context.Context, request *GatewayRequest) (map[string]interface{}, error) { res, err := handleRequest(ctx, request) if err != nil { if userErr, ok := err.(*userError); ok { return map[string]interface{}{ "statusCode": userErr.status, ...
package main import ( "errors" "flag" "fmt" "io" "io/ioutil" "log" "net" "net/http" "net/http/fcgi" _ "net/http/pprof" "net/url" "os" "os/signal" "runtime" "strconv" "strings" "sync/atomic" "syscall" "time" "github.com/golang/glog" "github.com/naoina/toml" "github.com/smartnews/yoya-thumber/thum...
package main import "golang.org/x/tour/pic" // Pic creates a picture // interresting values are: // // (x+y)/2 // // x*y // // x^y func Pic(dx, dy int) [][]uint8 { picture := make([][]uint8, dy) for y, _ := range picture { for x := 0; x < dx; x++ { val := uint8(x * y) picture[y] = append(picture[y], val) ...
package main import ( "crypto/sha256" "database/sql" "encoding/json" "fmt" "github.com/dustin/go-humanize" "github.com/gorilla/mux" "io" "net/http" "strconv" "strings" "github.com/espebra/filebin2/ds" "github.com/espebra/filebin2/s3" ) func (h *HTTP) viewAdminDashboard(w http.ResponseWriter, r *http.Requ...
package styles type addStyleReq struct { Name string `json:"name"` Description string `json:"description,omitempty"` Sld string `json:"sld"` Type string `json:"type" description:"point/line/polygon"` }
package main import ( "crypto/md5" "crypto/sha1" "crypto/sha256" "crypto/sha512" "hash" "math/rand" "testing" "golang.org/x/crypto/blake2b" "golang.org/x/crypto/sha3" ) func benchmarkHash(b *testing.B, h hash.Hash) { data := make([]byte, 1024) rand.Read(data) b.ResetTimer() for n := 0; n < b.N; n++ { ...
package blocks import ( "github.com/bouncepaw/mycomarkup/v2/util" ) // Heading is a formatted heading in the document. type Heading struct { // Level is a number between 1 and 6. Level uint Contents Formatted Src string } func (h Heading) isBlock() {} // GetContents returns the heading's contents. func...
package domain import "errors" var ( ErrUserAlreadyExists = errors.New("user is exists") ErrUsernameHasTaken = errors.New("username has taken before") ErrUserNotFound = errors.New("user could not found") )
package benchmarks import ( "errors" "io/ioutil" "os" "testing" "time" log "github.com/go-playground/log/v8" "github.com/go-playground/log/v8/handlers/json" ) var errExample = errors.New("fail") type user struct { Name string `json:"name"` Email string `json:"email"` CreatedAt time.Time `js...
package golang func decode(encoded []int, first int) []int { length := len(encoded) ans := make([]int, length+1, length+1) ans[0] = first for i := 1; i <= length; i++ { ans[i] = ans[i-1] ^ encoded[i-1] } return ans }
package main import ( "Open_IM/internal/rpc/user" "flag" ) func main() { rpcPort := flag.Int("port", 10100, "rpc listening port") flag.Parse() rpcServer := user.NewUserServer(*rpcPort) rpcServer.Run() }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //130. Surrounded Regions //Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. //A region is captured by fl...
package main import ( "encoding/json" "fmt" "log" "net/http" "net/url" "github.com/gorilla/mux" ) // Handler represents a web app handler type Handler struct { router *mux.Router storage Storage address string } // Response for json response type Response struct { Message interface{} `json:"message"` } ...
package main import ( "encoding/json" "reflect" "sort" "strings" ) const ( diffType = "diff-type" diffLengthBody = "diff-length-body" diffLengthArray = "diff-length-array" diffValue = "diff-value" ) func Equal(vx interface{}, vy interface{}) (bool, string) { if reflect.TypeOf(vx) != reflect.T...
// // Copyright 2021 IBM 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 ...
package cipher import ( "encoding/base64" "encoding/hex" ) // Base64Encode 将字节数组进行base64编码成字符串 // data: 需要编码的字节数组 // return:编码后的字符串 func Base64Encode(data []byte) string { return base64.StdEncoding.EncodeToString(data) } // Base64Decode 将字符串进行base64解码成字节数组 // data: 需要解码的字符串 // return:success(解码后的字节数组、nil),fai...
package main import ( "fmt" "github.com/ethereum/go-ethereum/common/hexutil" "log" "net/http" "golang.org/x/text/transform" "golang.org/x/text/encoding/simplifiedchinese" "strings" "io/ioutil" "github.com/sanguohot/medichain/util" ) func DecodeToGBK(utf8Str string) (dst string, err error) { var trans transfo...
package service import ( "context" "errors" "git.dustess.com/mk-base/util/crypto" blogDao "git.dustess.com/mk-training/mk-blog-svc/pkg/blog/dao" blogModel "git.dustess.com/mk-training/mk-blog-svc/pkg/blog/model" "git.dustess.com/mk-training/mk-blog-svc/pkg/blogstatistics/dao" "git.dustess.com/mk-training/mk-blo...
package middleware import ( "bytes" "fmt" "io/ioutil" "net/http" "net/http/httptest" "net/url" "strings" "testing" ) func TestRequestEntry(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) defer server.Close() r...
package main type Location interface { CanReceive(Card) bool Receive(Card) CanGiveCard() bool GiveCard() Card ActiveCard() (Card, bool) }
// 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...
package shared import ( "fmt" "io" "math/rand" "os" "time" ) var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") func RandSeq(n int) string { // Generates a random sequence of characters of fixed length. // Used to generate a username when the user doesn't enter one rand....
package event import ( "testing" ) type testEvent struct { SimpleEvent Chan chan string } func (testEvent) EventType() string { return "testEvent" } func TestManager_HasEvent(t *testing.T) { tests := []struct { name string args string want bool }{ { "good entry", "test1", true, }, { "b...
package main import ( "fmt" "time" ) func main() { var layout string = "2006-01-02 15:04:05" var timeStr string = "2019-12-12 15:22:12" timeObj1, _ := time.Parse(layout, timeStr) fmt.Println(timeObj1) timeObj2, _ := time.ParseInLocation(layout, timeStr, time.Local) fmt.Println(timeObj2) }
package tpls func init() { registerTemplate("css.html", ` <style type="text/css"> *{border:0; padding:0; margin:0;} li { list-style: none; } body { background: #e2e2e2 } a { text-decoration: none; color: #000; } ...
package models import ( "encoding/csv" "fmt" "io" "os" "path/filepath" "strconv" "yuelng.com/explorer/api/services" ) func add_account(name string, tel string, pass string, team_type int) { db := services.InitDB() defer db.Close() if db.Where("tel = ?", tel).First(&Account{}).RecordNotFound() { // accoun...
/** * tag_handler * @author liuzhen * @Description 标签handle * @version 1.0.0 2021/1/28 17:04 */ package handler import ( "backend/src/module" "backend/src/service" "github.com/gin-gonic/gin" ) // 添加标签 func AddTag(ctx *gin.Context) { var param module.Tag _ = ctx.ShouldBind(&param) result := service.AddTag(...
package primitives import ( "encoding/xml" ) //ConditionOperatorType is a direct mapping of XSD ST_ConditionalFormattingOperator type ConditionOperatorType byte //ConditionOperatorType maps for marshal/unmarshal process var ( ToConditionOperatorType map[string]ConditionOperatorType FromConditionOperatorType map...
// Package settingsAccount returns account struct. package settingsAccount import ( "github.com/MerinEREN/iiPackages/api" "github.com/MerinEREN/iiPackages/datastore/account" "github.com/MerinEREN/iiPackages/session" "google.golang.org/appengine/datastore" "log" "net/http" ) // Handler returns account struct via...
package cryptocompare import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "time" ) type TopByMarketCapResponse struct { Message string `json:"Message,omitempty"` Type int `json:"Type,omitempty"` Metadata struct { Count int `json:"Count,omitempty"` } `json:"MetaData,omitempty"` SponsoredDa...
package pod import ( "encoding/json" log "github.com/sirupsen/logrus" apiv1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/strategicpatch" ) func LogChanges(oldPod *apiv1.Pod, newPod *apiv1.Pod) { a, _ := json.Marshal(oldPod) b, _ := json.Marshal(newPod) patch, _ := strategicpatch.CreateTwoWayMergePatch(a...
package utils const ( // ConfigurationFilePath is the constant path to the configuration file needed to start the application // written from root file since the application starts from `make run` ConfigurationFilePath = "local-config.yml" // PathPing stores the defualt address of storage directory of ping data P...
package exporter import ( "fmt" "github.com/ktsstudio/selectel-exporter/pkg/selapi" "github.com/prometheus/client_golang/prometheus" "time" ) type datastoreMetrics struct { memoryPercent prometheus.Gauge memoryBytes prometheus.Gauge cpu prometheus.Gauge diskPercent prometheus.Gauge diskBytes ...
package metrics import ( "context" "strings" "go.opencensus.io/plugin/ocgrpc" "go.opencensus.io/stats/view" "go.opencensus.io/tag" "google.golang.org/grpc" grpcstats "google.golang.org/grpc/stats" "github.com/pomerium/pomerium/internal/log" ) // GRPC Views var ( // GRPCClientViews contains opencensus views...
package midtrans import ( "github.com/imrenagi/go-payment" "github.com/imrenagi/go-payment/gateway/midtrans/snap" "github.com/imrenagi/go-payment/invoice" "fmt" midsnap "github.com/midtrans/midtrans-go/snap" ) // NewSnapFromInvoice create snap charge request func NewSnapFromInvoice(inv *invoice.Invoice) (*mids...
package controller import ( "net/http" "net/http/httptest" "testing" "github.com/gorilla/mux" "github.com/golang/mock/gomock" ) func AuthenticationPassThroughMiddleware(delegate func(w http.ResponseWriter, r *http.Request)) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ...
package thread import ( "fmt" "sync" "time" ) var rub int = 100 func Trouble() { m := sync.Mutex{} go a() go b() m.Lock() time.Sleep(time.Second * 2) fmt.Printf("Итого осталось %d\n", rub) m.Unlock() } func a() { if rub == 0 { fmt.Println("Недостаточно сретств") return } rub -= 100 fmt.Printf("И...
package main //Using comparison operators to initialize boolean type variables import "fmt" func main() { g := (1 == 0) h := (24 <= 42) i := (77 >= 77) j := (12 != 21) k := (69 > 96) l := (1.618 < 3.14159265) fmt.Printf("%v\n%v\n%v\n%v\n%v\n%v\n", g, h, i, j, k, l) }
package sese import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03500207 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.035.002.07 Document"` Message *SecuritiesFinancingConfirmation002V07 `xml:"SctiesFincgConf"` } fu...
package main import ( "bufio" "bytes" "flag" "fmt" "os" "strings" "time" "unicode" "unicode/utf8" "github.com/bclement/boltsh" "github.com/boltdb/bolt" ) var raw = flag.Bool("raw", false, "Dump values as byte arrays instead of strings") type CommandFunc func(level boltsh.Level, args []string) boltsh.Leve...
package controllers import ( "github.com/astaxie/beego" "gowechatsubscribe/models" "gowechatsubscribe/dblite" "strconv" ) type HomeController struct { beego.Controller } func (c *HomeController) Get() { c.Data["IsHome"] = true login := checkAccount(c.Ctx) c.Data["IsLogin"] = login if !login { c.Redirect("...
package main import "fmt" func main() { //变量声明 var //常量声明 const const a float32 = 10 //a = 20 //err 常量不允许修改 fmt.Println(a) fmt.Printf("%T\n",a) //自动推导类型 const b,c = 3.14,3.2 // 没有使用:= fmt.Println(b,c) fmt.Printf("%T",b) }
// 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 server import ( "encoding/json" "github.com/golang/glog" "io/ioutil" "net/http" ) type reqEdit struct { Id int Token string } func ConfigFilePagesEnable(w http.ResponseWriter, req *http.Request){ //SetHttpHeader(w,req) if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Clo...
package main func main() { x := 25 fmt.Println(x) change_value(x) fmt.Println(x) } func change_value(a int){ a := 36 }
package files import ( "../../proto" "errors" "io/ioutil" "os" "path/filepath" ) type File struct { Rootdir string } func (f *File) SendFile(args *proto.FileRequest, resp *proto.File) error { full_path := filepath.Join(f.Rootdir, args.Filename) data, err := ioutil.ReadFile(full_path) if err != nil { retu...
package crypt import ( "fmt" "math/rand" "sync" "time" "unsafe" ) /* #cgo LDFLAGS: -lcrypt #define _GNU_SOURCE #define _XOPEN_SOURCE #include <stdlib.h> #include <unistd.h> */ import "C" var mu sync.Mutex // Crypt is language wrapper for glibc crypt(3). func Crypt(pass, salt string) (string, error) { mu.Loc...
package config_test import ( "errors" "io/ioutil" "os" "path/filepath" "github.com/cloudfoundry/bosh-bootloader/application" "github.com/cloudfoundry/bosh-bootloader/config" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github...
package connectors import ( "fmt" "errors" "encoding/json" "github.com/go-playground/validator/v10" log "github.com/sirupsen/logrus" ) var ( // define custom errors ErrInvalidGoogleMetadata = errors.New("Invalid google metadata") // create new validator validate = validator.New()...
package main import "fmt" func main() { cycloneModel := 6 fmt.Println(cycloneModel) }
package backtracking func totalNQueens(n int) int { var res int var cols = make([]int, n) // 列是否占用 var xhills = make([]int, 2*n) // 左上右下是否占用 var yhills = make([]int, 2*n) // 左下右上是否占用 var queens = make([]int, n) // 存放n皇后的位置 help52(0, n, &res, &cols, &xhills, &yhills, &queens) return res } func help52(row ...
package v1 import ( "switch-onchain/internal/service" ) //v1 初始版本 type APIV1 struct { SVC *service.Service }
package youzan_gin_middleware import ( "crypto/md5" "fmt" "github.com/gin-gonic/gin" "io" "io/ioutil" "log" ) func YouZanAPIAuth(clientID string, clientSecret string) gin.HandlerFunc { return func(c *gin.Context) { currentClientID := c.Request.Header.Get("Client-Id") eventSign := c.Request.Header.Get("Even...
package addPerson import ( "context" "encoding/json" "fmt" "log" "net/http" "os" "github/thisissoon/Go-Cloud-Functions-Examples/http/addPerson/storage" "cloud.google.com/go/firestore" ) // GCLOUD_PROJECT is automatically set by the Cloud Functions runtime. var projectID = os.Getenv("GCLOUD_PROJECT") var cl...
// NOTE: Boilerplate only. Ignore this file. // Package v1beta1 contains API Schema definitions for the test v1beta1 API group // +k8s:deepcopy-gen=package,register // +groupName=test.opsI package v1beta1 import ( "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/runtime/scheme" "k8s.io...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/11/22 10:26 上午 # @File : lt_190_颠倒二进制位.go # @Description : # @Attention : */ package v2 // 关键: 计算 1的个数 func reverseBits2(num uint32) uint32 { var ret uint32 bitOneCount := 31 for bitOneCount >= 0 { // x&1 判断bitOneCount 这个位置是否为1,然后左移,这样的话,如果最后一个为1 ,则可以得到二...
package transport import ( "context" "crypto/tls" "time" "github.com/amenzhinsky/iothub/common" ) // Transport interface. type Transport interface { SetLogger(logger common.Logger) Connect(ctx context.Context, creds Credentials) error Send(ctx context.Context, msg *common.Message) error RegisterDirectMethods...
package venti import ( "bytes" "encoding/binary" "errors" "fmt" "io" "math" ) const ( EntrySize = 40 // flags EntryActive uint8 = 1 << 0 EntryDir uint8 = 1 << 1 EntryDepthShift uint8 = 2 EntryDepthMask uint8 = 7 << 2 EntryLocal uint8 = 1 << 5 EntryBig uint8 = 1 << 6 EntryNoArch...
package main import "sort" //贪心:每次尽可能多的有区间重叠,当下一个区间和当前保存的区间无重叠时,需要增加弓箭手 //每次遍历各个区间时判断要不要更新区间的值 type pair struct { first int second int } type pairlist []pair func (p pairlist) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p pairlist) Len() int { return len(p) } func (p pairlist) Less(i, j int) bool { re...
package main import ( "fmt" "io/ioutil" "log" "os" "path/filepath" "strconv" "strings" ) func main() { if len(os.Args) == 1 || (!strings.HasSuffix(os.Args[1], ".m3u") && !strings.HasSuffix(os.Args[1], ".pls")) { fmt.Printf("Usage: %s <file.m3u>\n", filepath.Base(os.Args[0])) os.Exit(1) } if raw, err :...
package admin import ( "context" "strings" "tpay_backend/adminapi/internal/common" "tpay_backend/model" "tpay_backend/adminapi/internal/svc" "tpay_backend/adminapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type AddUpstreamChannelLogic struct { logx.Logger ctx context.Context svcCtx *svc...
package leet435 import ( "fmt" "sort" ) func main() { params := [][]int{{1, 2}, {2, 3}, {3, 4}, {1, 3}} result := eraseOverlapIntervals(params) fmt.Println("------------------", result) } func eraseOverlapIntervals(intervals [][]int) int { if len(intervals) == 0 { return 0 } sort.SliceStable(intervals, fun...
package main import "C" import ( "fmt" optly "github.com/optimizely/go-sdk" "github.com/optimizely/go-sdk/pkg/client" "github.com/optimizely/go-sdk/pkg/entities" "os" ) var optlyClient *client.OptimizelyClient var user *entities.UserContext // initalizes the Optimizely SDK func Init(sdkkey, userId string) { v...
package main import ( "log" "github.com/moby/buildkit/frontend/gateway/grpcclient" "github.com/moby/buildkit/util/appcontext" "github.com/openllb/llb-yarn/yarn" ) func main() { if err := grpcclient.RunFromEnvironment(appcontext.Context(), yarn.Install); err != nil { log.Printf("fatal error: %+v", err) panic...
package nodes import ( "fmt" "reflect" "github.com/ofavre/calcgraph/executor" ) /////////////// // FanInNode // /////////////// var _ Node = (*FanInNode)(nil) var _ executor.Runer = (*FanInNode)(nil) type FanInNode struct { out DataChan inNodes []Node selectCases []reflect.SelectCase remaining int la...
package dial import ( "time" ) type NetAddress struct { Network string Address string } type NetAddressTimeout struct { NetAddress Timeout time.Duration }
// Copyright (c) 2017 Minio Inc. All rights reserved. // Use of this source code is governed by a license that can be // found in the LICENSE file. package highwayhash import ( "encoding/binary" ) const ( v0 = 0 v1 = 4 mul0 = 8 mul1 = 12 ) var ( init0 = [4]uint64{0xdbe6d5d5fe4cce2f, 0xa4093822299f31d0, 0x...
package controllers import ( "encoding/json" "log" "math/rand" "net/http" "time" "url_shortener/data" "url_shortener/models" "github.com/gorilla/mux" ) // CreateShortURL crea una referencia de una url en la base de datos func CreateShortURL(w http.ResponseWriter, r *http.Request) { dir := models.Direction{...
package operations import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ) // Result bulabula type Result string // Result Constants bulabula var ( ResultNone Result = "none" ResultGot Result = "got" ResultListed Result = "listed" ResultCreated Result = "created" Res...
// Copyright 2014 Brett Slatkin // // 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 repository import ( "context" "github.com/jackc/pgx/v4/pgxpool" "github.com/teploff/otus/calendar/domain/entity" "github.com/teploff/otus/calendar/domain/repository" "time" ) type eventRepository struct { pgxPool *pgxpool.Pool } // NewEventRepository returns repository of events via PostgreSQL database...
package pakr import ( "fmt" "sort" ) func Example_solve() { P := NewPackage // Define an index that represents all available Packages // and their dependencies index := []Dependency{ { P("A", "1.0.0"), []Packages{ {P("B", "1.0.0")}, }, }, { P("A", "2.0.0"), []Packages{ {P("B", "2.0.0")},...
package deletespot import ( "context" "testing" mock_db "github.com/doniacld/outdoorsight/internal/db/mocks" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDeleteSpot(t *testing.T) { tt := map[string]struct { request DeleteSpotRequ...
package main import ( "fmt" "strings" "tools" ) func main() { stdin, err := tools.FetchStdin() if err != nil { panic(err) } //fmt.Println(stdin) cellData := makeCell(stdin[0]) //tools.PrintStruct(cellData) result := countMarble(cellData) fmt.Println(result) } type cell struct { values [3]bool } fun...
package main import ( "encoding/base64" "fmt" ) var coder = base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") func base64Encode(src []byte) []byte { return []byte(coder.EncodeToString(src)) } func base64Decode(src []byte) ([]byte, error) { return coder.DecodeString(string(sr...