text
stringlengths
11
4.05M
package pkg import ( "net/http" "strconv" ) func ParsePagination(r *http.Request, defaultLimit, defaultOffset, maxLimit int64) (int64, int64) { var offset, limit int64 var err error if offsetParam := r.URL.Query().Get("offset"); offsetParam == "" { offset = defaultOffset } else { offset, err = strconv.Pars...
package TLV import ( "github.com/andrewz1/gosmpp/Exception" "github.com/andrewz1/gosmpp/PDU/Common" "github.com/andrewz1/gosmpp/Utils" ) var DONT_CHECK_LIMIT = -1 type ITLV interface { GetTag() uint16 SetTag(tag uint16) SetData(bb *Utils.ByteBuffer) (err *Exception.Exception) GetData() (*Utils.ByteBuffer, *Ex...
// This code is released under the MIT License // Copyright (c) 2020 Marco Molteni and the timeit contributors. package main import ( "bytes" "fmt" "os" "os/exec" "path/filepath" "strings" "syscall" "testing" "time" ) var ( SLEEPIT, _ = filepath.Abs("../../bin/sleepit") ) func TestRun(t *testing.T) { tes...
package http import ( "bytes" "net/http" "net/http/httptest" "testing" "github.com/ricardolonga/workshop-go/domain/user" "github.com/stretchr/testify/assert" ) func TestWithRecorder(t *testing.T) { userService := user.NewService() router := NewHandler(userService) response := httptest.NewRecorder() endpo...
package main import ( "flag" "fmt" "github.com/facebookgo/flagenv" "log" "regexp" "strconv" "strings" ) var lineWrap string func stringToInt(numberStr string) (int, error) { if numberStr == "" { return 1, nil } number, err := strconv.ParseFloat(numberStr, 10) if err != nil { return 0, fmt.Errorf("Cann...
package datastoresql import ( "context" "errors" "fmt" "github.com/direktiv/direktiv/pkg/refactor/mirror" "github.com/direktiv/direktiv/pkg/util" "github.com/google/uuid" "gorm.io/gorm" ) type sqlMirrorStore struct { // database connection. db *gorm.DB // symmetric encryption key to encrypt and decrypt mir...
package function import ( "encoding/json" "fmt" "strconv" "github.com/10gen/realm-cli/internal/cli" "github.com/10gen/realm-cli/internal/cli/user" "github.com/10gen/realm-cli/internal/cloud/realm" "github.com/10gen/realm-cli/internal/terminal" "github.com/10gen/realm-cli/internal/utils/flags" ) // CommandMet...
/* * Copyright 2017 StreamSets 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...
package graphql_test import ( "testing" "github.com/graphql-go/graphql" "github.com/graphql-go/graphql/gqlerrors" "github.com/graphql-go/graphql/testutil" ) func TestValidate_UniqueVariableNames_UniqueVariableNames(t *testing.T) { testutil.ExpectPassesRule(t, graphql.UniqueVariableNamesRule, ` query A($x:...
package models import "time" // Space Defines a space where an event can occur.... type Space struct { SpaceID string `json:"spaceId" db:"space_id"` GroupID string `json:"groupId" db:"group_id"` Name string `json:"name" db:"name"` Description string `json:"description" db:"description"`...
package shardkv import "../kvraft" // // Sharded key/value server. // Lots of replica groups, each running op-at-a-time paxos. // Shardmaster decides which group serves each shard. // Shardmaster may change shard assignment from time to time. // // You will have to modify these definitions. // const ( OK ...
package main import ( "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func Test(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Link Looker") } var _ = Describe("#getPage", func() { It("when given a valid url", func() { validURL := "https://www.google.com" _, err := getPage(validU...
package admin import ( "encoding/json" "fmt" "net/http" "time" "github.com/jcgregorio/slog" "github.com/jcgregorio/webmention-func/config" ) type Claims struct { Mail string `json:"email"` Aud string `json:"aud"` Name string `json:"name"` Picture string `json:"picture"` } var ( client = &http.C...
package product import ( "context" "encoding/json" "errors" "fmt" "github.com/itsmeadi/cart/src/entities/models" "github.com/itsmeadi/cart/src/interfaces/db/cache" "io/ioutil" "net/http" "time" ) type Product struct { Url string Client *http.Client Cache *cache.ProductCache } var ERRINVALIDRESPONSE =...
package gvabe import ( "crypto/x509" "encoding/pem" "fmt" "log" "os" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/btnguyen2k/henge" "github.com/btnguyen2k/prom" _ "github.com/denisenkom/go-mssqldb" _ "github.com/go-sql-driver/mysql" _ "github.com/godr...
package main import ( "golang.org/x/tour/tree" "fmt" ) func Walk(t *tree.Tree, ch chan int) { defer close(ch) var walk func(t *tree.Tree) walk = func(t *tree.Tree) { if t == nil {return} walk(t.Left) ch <- t.Value walk(t.Right) } walk(t) //close(ch) possible instead of defer } func Sa...
package app import ( "flag" "fmt" "io/ioutil" "net" "net/http" "os" "os/exec" "regexp" "syscall" "time" log "github.com/sirupsen/logrus" ) // WaitCondition represents any condition that can be waited for type WaitCondition interface { String() string Check() error } // PathWait is used for waiting on a...
package main import ( "${MOD_NAME}/hello" ) func main() { hello.Hello() }
package storage import ( "time" "github.com/pkg/errors" "github.com/saromanov/gleek/internal/models" pb "github.com/saromanov/gleek/proto" ) // CreateTask provides inserting of the task func (s *Storage) CreateTask(t *pb.Task) (int64, error) { result, err := s.db.Exec(taskSchema) if err != nil { return 0, er...
// 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 main import "fmt" type car interface { move() } type peugeot struct { name string } type ferari struct { name string } func (p peugeot) move() { fmt.Printf("%s run sportly\n", p.name) } func (f ferari) move() { fmt.Printf("%s run very fastly", f.name) } func main() { var c car //声明一个car类型的变量 ...
package app import ( "strings" "github.com/btnguyen2k/prom" "github.com/btnguyen2k/henge" "main/src/gvabe/bo/user" ) // NewAppDaoMongo is helper method to create MongoDB-implementation of AppDao. // // Available: since v0.6.0 func NewAppDaoMongo(mc *prom.MongoConnect, collectionName string) AppDao { txMode :=...
package main import ( "log" "os" "strconv" "sync" "github.com/vjeantet/grok" ) func parseError(workernum int, loglines chan string, result chan int, errs chan string, wg *sync.WaitGroup) { defer wg.Done() logger_prefix := "worker " + strconv.Itoa(workernum) + " " var logger = log.New(os.Stderr, logger_prefix...
package math import "fmt" //Q01 求一个整数的二进制表示 func Q01(decimal int64) string { var ret string var b int64 for i := 32; i > 0; i = i - 1 { b = decimal & 1 ret = fmt.Sprint(b) + ret decimal = decimal >> 1 } return ret }
package main import ( "log" "math" . "github.com/fogleman/fauxgl" kingpin "gopkg.in/alecthomas/kingpin.v2" ) var ( // scale = kingpin.Flag("scale", "Scale factor.").Short('s').Required().Float64() count = kingpin.Flag("count", "Number of repeats.").Short('n').Required().Int() axisX = kingpin.Flag("x", "Use...
package routes import ( "alta/model" "database/sql" "net/http" "strconv" "github.com/labstack/echo/v4" ) // import ( // "net/http" // "github.com/labstack/echo/v4" // ) // // handlerRegister to handle user's registration // func handlerRegister(c echo.Context) error { // u := new(user.User) // // binding...
package mongodb import ( "context" "errors" "testing" "github.com/brigadecore/brigade/v2/apiserver/internal/api" "github.com/brigadecore/brigade/v2/apiserver/internal/lib/mongodb" mongoTesting "github.com/brigadecore/brigade/v2/apiserver/internal/lib/mongodb/testing" // nolint: lll "github.com/brigadecore/brig...
package conclusion func nextGreatestLetter(letters []byte, target byte) byte { low, high := 0, len(letters)-1 for low < high { mid := low + (high-low)>>1 if letters[mid] == target { low = mid + 1 } else if letters[mid] > target { high = mid - 1 } else { low = mid + 1 } } if letters[low] > targe...
package main import ( "math" "strconv" "strings" ) var finfp = math.Inf(1) var finfn = math.Inf(-1) func InterfaceMapToMapID(m map[string]interface{}) map[MapID]string { var nw map[MapID]string nw = make(map[MapID]string) for a, b := range m { i := b.(MapID) nw[i] = a } return nw } func AddLowerCaseMa...
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-2019 Datadog, Inc. package extendeddaemonset import ( datadoghqv1alpha1 "github.com/datadog/e...
package models import "time" type SysQuartzJob struct { ID int `gorm:"primary_key" json:"id"` //ID BeanName string `json:"bean_name"` //Spring Bean名称 CronExpression string `json:"cron_expression"` //cron 表达式 IsPause []byte `json:"is_pause"` ...
package config import ( "errors" "os" "strconv" "time" "github.com/joho/godotenv" ) // Reader is a struct containing all the methods used for retrieving config values type Reader struct{} // NewReader is a function that creates a new reader func NewReader() *Reader { return &Reader{} } // ReadFirebaseCredent...
package store import ( //"gopkg.in/pg.v3" "tantan-demo/model" //"time" "tantan-demo/util" ) func DeleteAccountRows() error { _, err := util.Db.Exec(`delete from account`) return err } func DeleteRelationRows() error { _, err := util.Db.Exec(`delete from relation`) return err } func QueryOneAccount(account ...
package lints import "testing" func TestAllLintsHaveUpdateReport(t *testing.T) { for name, lint := range Lints { if lint.updateReport == nil { t.Errorf("lint %s has nil updateReport", name) } } } func TestAllLintsHaveNameDescriptionProvidence(t *testing.T) { for name, lint := range Lints { if lint.Name =...
package main import ( "context" "fmt" "os" "os/signal" "syscall" "github.com/sirupsen/logrus" prefixed "github.com/t-tomalak/logrus-prefixed-formatter" "github.com/serbanmarti/fiber_rest_api/server" ) func main() { // Configure base logging logrus.SetFormatter(&prefixed.TextFormatter{ DisableColors: f...
package sys import ( "runtime" "testing" "unsafe" "github.com/cilium/ebpf/internal/unix" qt "github.com/frankban/quicktest" ) func TestSigset(t *testing.T) { const maxSignal = unix.Signal(unsafe.Sizeof(unix.Sigset_t{}) * 8) // Type-infer a sigset word. This is a typed uint of 32 or 64 bits depending // on ...
package template const ( errorHtml = `<html> <head> <title>404</title> </head> <body> <div>404</div> </body> </html> ` )
// Package schema stores our graphql schema in a string using bindata to compile it in the binary package schema //go:generate go-bindata -ignore=\.go -pkg=schema -o=bindata.go ./... // GetRootSchema returns the schema.graphql string stored in bindata.go func GetRootSchema() string { return string(MustAsset("schema....
package clustersserver_test import ( "context" helmv2 "github.com/fluxcd/helm-controller/api/v2beta1" kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1" pb "github.com/fluxcd/webui/pkg/rpc/clusters" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1...
package fram import ( "encoding/json" "fmt" "net/http" "strings" ) func (c *Client) CreateBaseURLSource(bus BaseURLSource) (*Result, error) { rb, err := json.Marshal(bus) if err != nil { return nil, err } req, err := http.NewRequest("PUT", fmt.Sprintf("%s/json/realm-config/services/baseurl", c.HostURL), st...
package day03 import ( "fmt" "time" ) func Timer() { wg.Add(1) timer() wg.Wait() } func timer() { //创建定时器 fmt.Println(time.Now()) timerPtr1 := time.NewTimer(time.Second * 2) //方式一 fmt.Println(<-timerPtr1.C) time.AfterFunc(time.Second, callBackFun) //方式二 } func callBackFun() { defer wg.Done() fmt.Printl...
package models import "github.com/uadmin/uadmin" // Category model ... type Category struct { uadmin.Model Name string `uadmin:"required"` Icon string `uadmin:"image"` } // Validate function ... func (c Category) Validate() (errMsg map[string]string) { // Initialize the error messages errMsg = map[string]string...
package main import ( "GoShare" "fmt" "github.com/kardianos/osext" ) func main() { fmt.Println("main called") err := Shares.InitConfig() fmt.Println("main called") if err != nil { Shares.CreateFolder(Shares.LogFilePath) fmt.Println("config error ", err, Shares.LogFilePath) } // logconf := &golog.Logger...
package main import ( "fmt" "math/rand" ) //对象赋值接口: 对象只要实现了接口声明的函数即可赋值 //接口赋值接口: 接口如果包含其他接口声明的函数即可把自己赋值给其他接口, 往子集赋, 典型的例子任何接口都可以给空接口赋值 //接口指向对象的类型查询 //接口组合, 接口为引用语义, 接口的匿名组合的时候不用加*。 接口组合不能有同名的方法。 //接口的默认值 nil type AccessMysql struct { endpoint []string } //随机访问 func (p *AccessMysql) balance() { i := rand.Intn(l...
package commands import ( "fmt" "io/ioutil" "net" "path/filepath" "strings" yaml "gopkg.in/yaml.v2" "github.com/cloudfoundry/bosh-bootloader/storage" ) type PrintEnv struct { stateValidator stateValidator logger logger terraformManager terraformOutputter } type envSetter interface { Set(key,...
package errors type errorWrapper struct { rootError error errorStack []stackItem errorState map[string]interface{} } func WrapError(err error) *errorWrapper { ew, ok := err.(*errorWrapper) if !ok { ew = NewError(err, make(map[string]interface{})).(*errorWrapper) } ew.errorStack = append(ew.errorStack, new...
package common /* Generated using mavgen - https://github.com/ArduPilot/pymavlink/ Copyright 2020 queue-b <https://github.com/queue-b> Permission is hereby granted, free of charge, to any person obtaining a copy of the generated software (the "Generated Software"), to deal in the Generated Software without restricti...
package main import ( "log" "regexp" "github.com/pandada8/logd/lib/common" "github.com/spf13/viper" ) type Matcher struct { Rules []MatcherRuleSet } type MatcherRuleSet struct { Rules []MatcherRule Output string } type MatcherRule struct { Field string Match *regexp.Regexp String *string } func NewMa...
package service import ( "log" "net/http" "../router" ) func StartService(port string,routes router.Routes) { r := router.NewRouter(routes) http.Handle("/", r) log.Println("Starting HTTP service at " + port) err := http.ListenAndServe(":"+port, nil) // Goroutine will block here if err != nil { log.Println...
package true_git import ( "bytes" "context" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "strings" "time" "github.com/werf/lockgate" "github.com/werf/werf/pkg/util/timestamps" "github.com/werf/werf/pkg/werf" "github.com/werf/logboek" ) type WithWorkTreeOptions struct { HasSubmodules bool } func ...
package main import ( "strings" "os/exec" "fmt" ) func main() { guilder := Guilder{} guilder.ExecJoined("docker run -d --net=host hekonsek/streamshift-zookeeper:0.0.1-SNAPSHOT") guilder.ExecJoined("docker run -d --net=host hekonsek/streamshift-kafka:0.0.1-SNAPSHOT") guilder.AssumeExecNotContains("go test", "...
/* Copyright 2020 The Kubernetes 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, ...
package dao type SessionData interface { GetID()(sessionId string) Get(key string)(value interface{}, err error) Set(key string, value interface{})(err error) Del(key string) (err error) Save()(err error) }
package runner import ( "context" "testing" "time" "github.com/SentientTechnologies/studio-go-runner/internal/types" "github.com/ericchiang/k8s" core "github.com/ericchiang/k8s/apis/core/v1" meta "github.com/ericchiang/k8s/apis/meta/v1" "github.com/go-stack/stack" "github.com/karlmutch/errors" "github.co...
package mutual import ( "testing" "github.com/stretchr/testify/assert" ) func makeIncreasingTimestamps(half int) []timestamp { res := make([]timestamp, 0, half*2) for i := 0; i < half; i++ { res = append(res, timestamp{time: i, process: i * 2}, timestamp{time: i, process: i*2 + 1}, ) } return res } ...
/* Write a function graph(f, low, high, tests) that outputs a probability graph of the function f from range low to high (inclusive) over tests tests (i.e., counting the frequencies of f() outputs). f takes no arguments and returns an integer, low, high and tests are all integer values. For example, a function f that ...
package main import "fmt" func main() { // penulisan deklarasi variabel var name string var age = 27 country := "Indonesia" // penulisan deklarasi multiple variabel var ( firstName = "Danil" lastName = "Syah" ) fmt.Println(firstName + lastName...
package message import ( "strings" "github.com/pkg/errors" ) // ErrorMessage 错误信息类型 type ErrorMessage string // String func (em ErrorMessage) String() string { return string(em) } // Error func (em ErrorMessage) Error() error { return errors.New(em.String()) } // Param 参数设置 func (em ErrorMessage) Param(param ...
package main import ( "fmt" "sync" ) // run with -race flag to see race conditions func main() { var m sync.Mutex done := false total := 0 go func() { m.Lock() done = true m.Unlock() total += 2 total += 4 }() m.Lock() done = false m.Unlock() m.Lock() fmt.Println(done) m.Unlock() fmt.Println...
package request import ( "compress/gzip" "context" "fmt" "log" "net/http" "net/url" "time" ) type Request struct { client *http.Client userAgent string } func New(userAgent string) Request { return Request{ client: &http.Client{}, userAgent: userAgent, } } func (r Request) Do(ctx context.Contex...
package main import ( "fmt" "strings" ) type xy struct { x, y int } type grid struct { d map[xy]rune max xy } func loaddata(input string) grid { g := grid{map[xy]rune{}, xy{0, 0}} y := 0 for _, line := range strings.Split(input, "\n") { line = strings.TrimSpace(line) if line == "" { continue } ...
package main import "fmt" func basicPointer() { value := 1 var pointer *int pointer = &value fmt.Println(pointer) fmt.Println(*pointer) } func equalPointer() { value := 1 fmt.Println(value == *(&value)) } func changeValueFromPointer() { value := "hello" var pointer *string pointer = &value *pointer = ...
package main import ( "fmt" "html/template" "net/http" ) func handler(writer http.ResponseWriter, request *http.Request) { fmt.Fprintf(writer, "Hello World, %s!", request.URL.Path[1:]) } // to run from the command line type go run main.go // Open a browser and navigate to localhost:5555 func main() { http.Handl...
package main import "net/http" import "fmt" import "io" import "strings" import "time" import "os" import "net" import "bufio" var _=os.Stdout var _=time.Second var _=bufio.ErrBufferFull var _ net.Conn var indexHtml=`<!doctype html> <html> <head> <script> var source=new EventSource("/events"); source.addEvent...
package sudoku import ( "fmt" "log" "math" "os" "strconv" "strings" ) //The number of solves we should average the signals together for before asking them for their difficulty //Note: this should be set to the num-solves parameter used to train the currently configured weights. const _NUM_SOLVES_FOR_DIFFICULTY ...
package ast const BEGIN = 57346 const END = 57347 const CLASS = 57348 const OPEN = 57349 const CLOSE = 57350 const NEW = 57351 const DOT = 57352 const THIS = 57353 const IS = 57354 const SKIP = 57355 const READ = 57356 const FREE = 57357 const RETURN = 57358 const EXIT = 57359 const PRINT = 57360 const PRINTLN = 57361...
package main import "fmt" func closure() func() { text := "Dentro de la funcion closure" funcion1 := func() { fmt.Println(text) } return funcion1 } func main() { text := "Dentro de la funcion main" fmt.Println(text) funcionNueva := closure() funcionNueva() }
package solutions import ( "fmt" "testing" ) func TestFirstUniqChar(t *testing.T) { t.Run("Test firstUniqChar", func(t *testing.T) { var tests = []struct { input string want int }{ {"leetcode", 0}, {"loveleetcode", 2}, {"aabb", -1}, {"ccca", 3}, } for _, v := range tests { t.Run(fmt.S...
package models type User struct { ID int Firstname string Secondname string Thirdname string Phone int }
package main import ( "bytes" "encoding/json" "github.com/streadway/amqp" "math/rand" "net/http" "time" ) var queueDrinks = true // RandomizeHandler randomizes a drink and puts it on the queue func RandomizeHandler(w http.ResponseWriter, r *http.Request) { var randomizeRequest RandomizeRequest randomizeReque...
package admin import ( "context" "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 PlanformChannelSettingLogic struct { logx.Logger ctx context.Context svcCtx *svc.Servic...
package PDU import "github.com/andrewz1/gosmpp/Data" type BindTransceiver struct { BindRequest } func NewBindTransceiver() *BindTransceiver { a := &BindTransceiver{} a.Construct() return a } func (c *BindTransceiver) Construct() { defer c.SetRealReference(c) c.BindRequest.Construct() c.SetCommandId(Data.BI...
package server import ( "fmt" "net/http" "github.com/facebookgo/grace/gracehttp" "github.com/syariatifaris/shopeetax/app/resource/uires" "github.com/syariatifaris/shopeetax/app/service/api" "github.com/syariatifaris/shopeetax/app/usecase" taxusecase "github.com/syariatifaris/shopeetax/app/usecase/tax" ) //In...
package cmd import ( "net/http" "github.com/textileio/go-textile/pb" ) func Summary() error { var info pb.Summary res, err := executeJsonPbCmd(http.MethodGet, "summary", params{}, &info) if err != nil { return err } output(res) return nil }
package main import ( "errors" "log" "strconv" "gopkg.in/mgo.v2" "github.com/ileyd/sonarr" "gopkg.in/mgo.v2/bson" ) // Collection names const ( SeriesCollection = "series" ) // Series describes a series we have in our database type Series struct { ID bson.ObjectId `json:"_id,omitempty" bson:"_i...
// Copyright 2020 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
//https://leetcode-cn.com/problems/4sum/ package main import "fmt" import "sort" func main() { nums := []int{1, 0, -1, 0, -2, 2} target := 0 fmt.Println(fourSum(nums, target)) } func fourSum(nums []int, target int) [][]int { result := [][]int{} if len(nums) < 4 { return result } sort.Ints...
package gateway import ( "reflect" "testing" ) func TestGenerateJWT(t *testing.T) { type args struct { serviceID string secret []byte } tests := []struct { name string args args want string wantErr bool }{ // TODO: Add test cases. } for _, tt := range tests { t.Run(tt.name, func(t ...
package env import ( "fmt" "github.com/stretchr/testify/assert" "go.uber.org/zap" commonenv "knative.dev/eventing-kafka/pkg/common/env" "log" "os" "strconv" "testing" ) // Test Constants const ( serviceAccount = "TestServiceAccount" metricsPort = "9999" kafkaProvider = "confluent" kafkaOffsetCommitMe...
package main /** 410. 分割数组的最大值 给定一个非负整数数组和一个整数 m,你需要将这个数组分成 m 个非空的连续子数组。设计一个算法使得这 m 个子数组各自和的最大值最小。 注意: 数组长度 n 满足以下条件: - `1 ≤ n ≤ 1000` - `1 ≤ m ≤ min(50, n)` 示例1: ``` 输入: nums = [7,2,5,10,8] m = 2 输出: 18 解释: 一共有四种方法将nums分割为2个子数组。 其中最好的方式是将其分为[7,2,5] 和 [10,8], 因为此时这两个子数组各自的和的最大值为18,在所有情况中最小。 ``` */ /** 有点难这题,着实没想...
package git import ( "os/exec" "github.com/acrap/git_pswitcher/profile" ) //SwitchToProfile switch to chosen git profile func SwitchToProfile(p profile.Profile) error { var err error if _, err = exec.Command("git", "config", "--global", "user.name", p.Name).Output(); err != nil { return err } if _, err = ex...
package template const ( homeIndex = `{{define "Content"}}<div>久等网络</div>{{end}}` )
// iota. package main import ( "fmt" "strconv" ) func main() { us := []uint{50, 2, 1, 9, 1<<64 - 1} fmt.Println("uint slice:", us) for _, u := range us { fmt.Printf("%s %s\n", strconv.FormatUint(uint64(u), 10), strconv.Itoa(int(u))) } }
package sdkconnector import ( "github.com/hyperledger/fabric-sdk-go/pkg/client/msp" "github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt" providersmsp "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/msp" "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" ) //CreateChannel creates a Fabric channel. N...
package main import ( "github.com/therecipe/qt/androidextras" "github.com/therecipe/qt/core" ) type NotificationClient struct { core.QObject _ string `property:"notification,auto,changed"` } func (c *NotificationClient) notificationChanged(n string) { var err = androidextras.QAndroidJniObject_C...
package main import ( "fmt" ) func main() { mySlice := []int{777, 666, 555, 444, 333, 222, 111} fmt.Println(mySlice) } /* Exercise: write a program that creates a slice of int using shorthand notation then prints the slice */
// Copyright 2013 tsuru 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 queue import ( "bytes" "encoding/json" "fmt" "github.com/adeven/redismq" "io" "strings" "time" ) type redismqQ struct { name string queue ...
// Copyright (c) 2020 Tailscale Inc & 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 derpmap contains information about Tailscale.com's production DERP nodes. package derpmap import ( "fmt" "strings" "tailscale.com/ta...
package pipeline import "context" // NewPipeline initializes the workers and // connects them, it returns the input of the pipeline // and the final output func NewPipeline(ctx context.Context, numEncoders, numPrinters int) (chan string, chan string) { inEncode := make(chan string, numEncoders) inPrint := make(chan...
package wrpc import( "strings" "strconv" ) type Node struct { address string port int weight int } func ServerNode(node string) *Node { split := strings.Split(node, ":") port,_ := strconv.Atoi(split[1]) if len(split) >= 3 { weight,_ := strconv.Atoi(split[2]) return &Node{split[0], port, weight} } retur...
package main import ( "fmt" "os" "github.com/Haski007/shipping-apis/internal/shipping" "github.com/sirupsen/logrus" "github.com/urfave/cli" ) var Version string func main() { app := cli.App{ Name: "shipping", Usage: "Mock shipping APIs to get best deal", Version: Version, Action: func(c *cli.Cont...
package main import ( "fmt" "log" "os" "time" ) func printFileInfo() { fileInfo, err := os.Stat("test.txt") if err != nil { log.Fatal(err) } fmt.Println("File name:", fileInfo.Name()) fmt.Println("Size in bytes:", fileInfo.Size()) fmt.Println("Permissions:", fileInfo.Mode()) fmt.Println("Last modified:"...
package handler import ( "context" "errors" "path/filepath" "testing" jinmuidpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1" generalpb "github.com/jinmukeji/proto/v3/gen/micro/idl/ptypes/v2" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) type SmsNotificationT...
package router import ( docs "BearApp/docs" Accountapi "BearApp/handler" "log" "time" cors "github.com/itsjamie/gin-cors" // "net/http" "github.com/gin-contrib/sessions" redis "github.com/gin-contrib/sessions/redis" "github.com/gin-contrib/static" "github.com/gin-gonic/gin" // 載入文檔 ginSwagger "github.co...
// ViChart library for Go // Author: Tad Vizbaras // License: http://github.com/tadvi/vichart/blob/master/LICENSE // package vichart import ( "fmt" "github.com/ajstarks/svgo" "math" ) const ( PieGstyle = "font-family:Calibri; font-size:14" PieStyle = "fill:white;stroke:black;stroke-width:2px;" PieFillS...
// Copyright (c) 2016, M Bogus. // This source file is part of the AMQP-RPC open source project // Licensed under Apache License v2.0 // See LICENSE file for license information package amqprpc_test import ( "encoding/json" "errors" "fmt" "log" "math" "testing" "github.com/mbogus/amqprpc" "github.com/streadw...
package core import ( "time" "github.com/dosco/graphjin/core/internal/sdata" ) func (g *GraphJin) initDBWatcher() error { gj := g.Load().(*graphjin) // no schema polling in production if gj.prod { return nil } ps := gj.conf.DBSchemaPollDuration switch { case ps < (1 * time.Second): return nil case ...
package rest_api import ( "github.com/Nubes3/nubes3-user-service/internal/aggregate" "github.com/Nubes3/nubes3-user-service/internal/api/middlewares" "github.com/gin-gonic/gin" "net/http" ) func routing(r *gin.Engine) { } func Serve() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(http.St...
package fifth import "fmt" func (i *Interpreter) LoadPrimitives() { i.SetPrimitive("+", i.add()) i.SetPrimitive("-", i.sub()) i.SetPrimitive("*", i.mult()) i.SetPrimitive("/", i.div()) i.SetPrimitive(".", i.dot) i.SetPrimitive("dup", i.dup) i.SetPrimitive(".s", i.show) i.SetPrimitive(".r", i.rShow) i.SetPri...
package eztv import ( "errors" "github.com/odwrtw/eztv" polochon "github.com/odwrtw/polochon/lib" "github.com/sirupsen/logrus" ) // Make sure that the module is a torrenter, an explorer and a searcher var ( _ polochon.Torrenter = (*Eztv)(nil) _ polochon.Explorer = (*Eztv)(nil) _ polochon.Searcher = (*Eztv)(...