text
stringlengths
11
4.05M
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package feedback import ( "context" "time" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/tast/local/apps" "chromiumos/tast/local/chrome" "chromiumos...
// +build mage package main import ( "bytes" "encoding/base64" "fmt" "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" "io/ioutil" "os" "strings" "text/template" ) const APP_NAME = "maglev-admission-webhook-golang" // Install glide dependencies and update the lockfile for glide func Deps() error ...
package main import ( "catalog-ingestion/controller" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() catalogActor := r.Group("ingestion") { catalogActor.POST("/product", controller.ReceiveProduct) } r.Run(":8081") // listen and serve on 0.0.0.0:8080 }
// Менеджер БД тегов для аудио репозитория. // Следит за целостностью БД самостоятельно. package dbm import ( "context" "encoding/json" "os" "os/signal" "syscall" "github.com/jackc/pgx/v4" "github.com/pkg/errors" "github.com/streadway/amqp" "github.com/ytsiuryn/ds-audiodbm/entity" srv "github.com/ytsiuryn...
package leetcode import ( "testing" "github.com/go-playground/assert/v2" ) func TestClimbStairs(t *testing.T) { testcases := []struct { arg0 int except int }{ { 1, 1, }, { 2, 2, }, { 3, 3, }, { 4, 5, }, } for _, testcase := range testcases { result := climbStairs...
package local import ( "errors" "fmt" "os" "path" "github.com/traPtitech/trap-collection-server/src/config" ) type DirectoryManager struct { rootPath string } func NewDirectoryManager(conf config.StorageLocal) (*DirectoryManager, error) { rootPath, err := conf.Path() if err != nil { return nil, fmt.Errorf...
package main import ( "fmt" ) func main() { const NUM int = 20 var i int = 10 for i <= NUM { fmt.Println(i) i++ if i > 15 { break } } }
package slices func Sum(numbers [] int) int { var sum int for _, number := range numbers { sum = sum + number } return sum }
// Copyright (C) 2019 Google 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 t...
package main import "fmt" /* You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: Input: n...
package game import ( "math" "math/rand" "sync" "time" ) var random = rand.New(rand.NewSource(time.Now().UnixNano())) var speed float32 = 1 var TurnSpeed float32 = 5 var width = 1280 var heigth = 720 var canShoot bool var shootTimer = 100 //24 width 38 heigth type Player struct { Pos Position `json:"position...
package hashmap //hashmap的数组个数 const bucketCount = 20 type HashMap struct { //数组元素为连表的头指针 Buckets [bucketCount]*LinkNode } //连表结构 type LinkNode struct { //存储key value Data KV //下一个节点 Next *LinkNode } type KV struct { Key string Value string } func CreateLink() *LinkNode { //头结点数据为空 是为了标识这个链表还没有存储键值对 retu...
package main import ( "fmt" corev2 "github.com/sensu/sensu-go/api/core/v2" "github.com/sensu/sensu-plugins-go-library/sensu" "strings" "github.com/bluele/slack" ) type HandlerConfig struct { sensu.PluginConfig SlackWebhookUrl string SlackChannel string SlackUsername string SlackIconUrl string } co...
package main import "fmt" func main() { myFriendsName := "Mar" switch { case len(myFriendsName) == 2: fmt.Println("Hi my friend with name of length 2") case myFriendsName == "Tim": fmt.Println("Hey Tim") case myFriendsName == "Jenny": fmt.Println("Hey Jenny") case myFriendsName == "Marcus", myFriendsNam...
package main import ( "fmt" "log" "time" "github.com/carterjones/bittrex" ) func main() { c := bittrex.New("", "") // Create a candle handler that prints candles. candleHandler := func(c bittrex.Candle) { fmt.Println(c) } // Begin processing candles at a one minute interval. c.ProcessCandles(1*time.Minute...
package main import ( "fmt" "log" "net/http" "./controllers" ) func main() { http.HandleFunc("/", index) http.HandleFunc("/catalog", controllers.Catalog) http.HandleFunc("/show", controllers.Show) http.HandleFunc("/help", controllers.HelpProcess) http.HandleFunc("/about", controllers.AboutProcess) http.Han...
package constants // DefaultScheme is the scheme that should be prepended to user-provided // URLs that do not specify a scheme. const DefaultScheme string = "http" // SupportedUrlSchemes contains the schemes that the goget application // currently supports. It is intended to be used for checking if user-provided // ...
package routes import ( "commerce/context" "commerce/helpers" "commerce/models" "commerce/normalizer" "fmt" "net/http" "strconv" "github.com/gin-gonic/gin" ) func initOrders(m *models.Models, n normalizer.Normalizer) *orders { return &orders{ models: m, normalier: n, } } type orders struct { model...
package main import ( "encoding/json" "fmt" "sort" "golang.org/x/crypto/bcrypt" ) // ColorGroup is a struct type ColorGroup struct { ID int Name string Colors []string } // Animal is a struct type Animal struct { Name string // fields must start upper case for JSON to work Order string } func main(...
package platform import "fmt" func GetCustomerGroup(customerID string) string { return fmt.Sprintf("tenant-%s", customerID) }
package mem func Hash(key string, len int) uint64
package models import "gopkg.in/mgo.v2/bson" // Lease is a mgo model representing a collection of Subnet resources. type Lease struct { ID bson.ObjectId `bson:"_id"` Name string `bson:"name"` Tags []string `bson:"tags"` Metadata interface{} `bson:"metadata"` Subnet bs...
package main import ( "context" "fmt" ) func Rpc(ctx context.Context, url string) error { result := make(chan int) //err := make(chan error) go func() { isSuccess := false if isSuccess { result <- 1} //} else { // err <- errors.New("some error") //} }() select { case <-ctx.Done(): return ctx....
package transport // Layer represents a transport protocol layer. type Layer interface { Listen(port int) (interface{}, error) Dial(address string) (interface{}, error) }
package lib_gc_panic_catching import ( "fmt" "log" "runtime" "time" ) func PanicCatching(functionName string, params ...string) { if r := recover(); r != nil { t := time.Now() if params == nil { params = []string{} } msg := fmt.Sprintf("%s PANIC at %s : PANIC Defered recover: %v. With params: %v.\n", ...
package main import ( "bufio" "fmt" "os" "time" ) func get(out chan string) { reader := bufio.NewReader(os.Stdin) result, _, _ := reader.ReadLine() out <- string(result) } func timeout(out chan int) { time.Sleep(time.Duration(time.Duration.Seconds(10000))) out <- 1 } func main() { echo := make(chan string...
package actions import ( "strconv" "testing" "time" "github.com/gaia-adm/pumba/container" "github.com/gaia-adm/pumba/container/mockclient" "github.com/samalba/dockerclient" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) func makeContainersN(n int) ([]string, []container.Container) ...
/* Created on 2018/11/21 13:59 author: ChenJinLong Content: */ package main import "fmt" type Type int16 func (t Type) ToInt16() int16 { return int16(t) } // 遗迹阶段 const ( SignUp Type = iota + 1 // 报名期 ExploreOpen //探索期开启 ExploreClose //探索期关闭 ExploreShrink ...
package command import ( "bytes" "encoding/json" "testing" "github.com/mitchellh/cli" "github.com/pragkent/aliyun-disk/volume" ) func TestInitCommand_Run(t *testing.T) { var bu bytes.Buffer ui := &cli.BasicUi{ Writer: &bu, } meta := &Meta{ Ui: ui, Driver: volume.NewFakeDriver(), } cmd := &Init...
package main import "fmt" func main() { res2, res4 := rectangle(6, 4) fmt.Println("zhouzhang", res2, "mianji", res4) } func rectangle(len, wid float64) (peri float64, area float64) { peri = (len + wid) * 2 area = len * wid return }
package main import( "testing" ) func value()bool{ return true } func testvalidate_1(t *testing.T) { //expected :=value() actual:=validate(121) //value, _ := regexp.MatchString("^[1]+[0-9]{2}$", strconv.Itoa(no)) if actual != false{ t.Error("Fail") } //return value }
package main import "github.com/HotCodeGroup/warscript-games/jmodels" func getGameBySlugImpl(slug string) (*jmodels.GameFull, error) { game, err := Games.GetGameBySlug(slug) if err != nil { return nil, err } return &jmodels.GameFull{ Game: jmodels.Game{ Slug: game.Slug, Title: game....
package service import ( "context" "github.com/kyawmyintthein/golangRestfulAPISample/config" "github.com/kyawmyintthein/golangRestfulAPISample/infrastructure" ) type HealthServiceInterface interface { HealthCheck(ctx context.Context) error DBHealthCheck(ctx context.Context) (string, error) } type HealthService ...
//go:build !windows // +build !windows package main import _ "embed" //go:embed image.png var iconData []byte
package rand import ( "divsperf/randval/create/tools" "divsperf/randval/parse" "fmt" "testing" ) func TestRand_Generate(t *testing.T) { randToken_1_rs := []rune{5+48} randToken_1 := parse.Token{ parse.INT, &randToken_1_rs, nil, } randToken_2_rs := []rune{3+48,3+48} randToken_2 := parse.Token{ parse.I...
package login_grpc import ( "context" "errors" "fmt" _ "github.com/lib/pq" "github.com/overmesgit/awesomeSql/login" "github.com/overmesgit/awesomeSql/login_psql" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "log" "net" "os" ) type server struct { service login.U...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package cryptohome import ( "bytes" "context" "io/ioutil" "path/filepath" "time" uda "chromiumos/system_api/user_data_auth_proto" "chromiumos/tast/common/hwsec" "ch...
package main import ( "mq" "fmt" "time" ) func main() { //OnceTopic() ManyTopic() } // 一个topic 测试 func OnceTopic() { m := mq.NewClient() m.SetConditions(10) var topic = "ruu" ch,err :=m.Subscribe(topic) if err != nil{ fmt.Println("subscribe failed") return } go OncePub(m) OnceSub(ch,m) defer m.C...
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package tcp // ConnCallback is an interface of methods that are used as callbacks on a connection type ConnCallback interface { // OnConnect is called when the connection was accepted, // If the return value of false is closed OnConnect(*Conn) bool // OnMessage is called when the connection receives a packet, //...
package main //Writing Go code typically requires functionality declared from within other packages. To enable //the use of exported types and/or functions declared and contained within other packages, whether //they are provided as part of the standard Go library, or by 3rd party providers, you use the import //state...
// Copyright 2019 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package operations // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/swag" strfmt "...
// Copyright (C) 2015-Present Pivotal Software, Inc. All rights reserved. // This program and the accompanying materials are made available under // the terms of the 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 th...
// Copyright (C) 2017 Google 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 t...
// Copyright 2019 Istio 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 i...
package spacebattles import ( "fmt" "io" "strconv" "strings" "time" "github.com/mebyus/ffd/cmn" "github.com/mebyus/ffd/document" "github.com/mebyus/ffd/planner" "github.com/mebyus/ffd/track/fic" "golang.org/x/net/html" ) func (t *sbTools) Check(target string) (info *fic.Info, err error) { baseURL, _, id, ...
package main import ( "fmt" "io/ioutil" "strings" "bytes" ) type RepeatedMessage struct { messages []string correctedMessage string } func main() { message := parseInput("day6input") fmt.Println(message) message.correctMessage() fmt.Println(message) } func parseInput(filename string) RepeatedMes...
package agent import ( "encoding/json" "github.com/Klevry/klevr/pkg/common" "github.com/Klevry/klevr/pkg/communicator" "github.com/NexClipper/logger" ) func (agent *KlevrAgent) tempHealthCheck() { uri := agent.Manager + "/agents/" + agent.AgentKey + "/tempHeartBeat" logger.Debugf(agent.AgentKey) rb := &comm...
// Copyright 2016 Andreas Pannewitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package x // =========================================================================== // Opta represents an option - somthing one can 'optare' (=choose)...
package main import "testing" func TestHello(t *testing.T) { assertCorrectMessage := func(t testing.TB, got, exp string) { t.Helper() if got != exp { t.Errorf("got %q expected %q", got, exp) } } t.Run("saying hello to people", func(t *testing.T) { got := hello("Christian", "english") exp := "Hello Chr...
package main import ( "fmt" ) func hello(ch chan string) { ch <- "Hello world goroutine" } func main() { ch := make(chan string) go hello(ch) responseFromGoroutine := <-ch fmt.Println(responseFromGoroutine) fmt.Println("main goroutine") }
package main import "fmt" func main() { obj := Constructor() obj.Add(3) // [3] obj.Add(0) // [3,0] obj.Add(2) // [3,0,2] obj.Add(5) // [3,0,2,5] obj.Add(4) // [3,0,2,5,4] fmt.Println(obj.List) obj.GetProduct(2) // 返回 20 。最后 2 个数字的乘积是 5 * 4 = 20 obj.GetProduct(3) // 返回 40 。最后 3 个数字的乘积是 2 * 5 * 4 = 40 obj.Get...
package linkedlist import ( "errors" "fmt" ) type Node struct { Val interface{} Next *Node } type LinkedList struct { first *Node } func (ll *LinkedList) InsertBeg(v interface{}) { newNode := &Node{Val: v, Next: ll.first} ll.first = newNode } func (ll *LinkedList) Remove(v interface{}) error { if ll.firs...
package main import ( "fmt" "github.com/aasisodiya/aws/s3" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func main() { lambda.Start(HandleRequest) // request := events.APIGatewayProxyRequest { // Headers: map[string]string { // "bucketname":"test-bucket-delete-later-2", //...
package event import ( "fmt" "github.com/xuperchain/xupercore/kernel/engines/xuperos/common" pb "github.com/xuperchain/xupercore/protos" ) // Router distribute events according to the event type and filter type Router struct { topics map[pb.SubscribeType]Topic } // NewRounterFromChainMG instance Router from Cha...
package image import ( gocontext "context" "regexp" "strings" "github.com/travis-ci/worker/config" ) // EnvSelector implements Selector for environment-based mappings type EnvSelector struct { c *config.ProviderConfig lookup map[string]string } // NewEnvSelector builds a new EnvSelector from the given *confi...
package eventsourcing import ( "fmt" "github.com/caos/logging" "github.com/caos/zitadel/internal/crypto" "github.com/caos/zitadel/internal/errors" "github.com/caos/zitadel/internal/id" "github.com/caos/zitadel/internal/project/model" "strings" ) //ClientID random_number@projectname (eg. 495894098234@zitadel) f...
package reference import ( "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" bdv1 "code.cloudfoundry.org/quarks-operator/pkg/kube/apis/boshdeployment/v1alpha1" qstsv1a1 "code.cloudfoundry.org/quarks-operator/pkg/kube/apis/quarksstatefulset/v1alpha1" ) // GetConfigMapsReferencedBy returns a list of all names fo...
package service import ( "hdg.com/db-demo/src/server/model" "hdg.com/db-demo/src/server/dao" "hdg.com/db-demo/src/server/common" "errors" "fmt" "hdg.com/db-demo/src/server/cache" "time" ) type UserService interface { GetUser(id int) *model.User GetCacheUser(id int) *model.User } type UserServiceImpl struct ...
package exporter import ( "container/heap" ) type extdataLooseLesser interface{ Less(x interface{}) bool } type extdataIterMerge struct{ h extdataIterHeap } func extdataIterMergeFrom(nexts ...func() (info ExtData, ok bool)) *extdataIterMerge { h := make(extdataIterHeap, 0, len(nexts)) for _, next := range nexts {...
/* Dynamic Programming is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems, so that we do not have to re-compute them when needed later. This sim...
// Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved. // This program and the accompanying materials are made available under the terms of the 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 Licen...
// Copyright © Copyright 2020 Orion Labs, 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...
package schema import ( "sync" "time" ) type SystemLoadEntity struct { timestamp int64 loadAvg float32 } type SystemLoadDto struct { LoadAvg float32 } type SystemLoadTable struct { entities []*SystemLoadEntity mtx *sync.RWMutex } func (t *SystemLoadTable) Init() *SystemLoadTable { t.entities = []*Sy...
package main import ( "errors" "fmt" ) func fetchData(data string) (string, error) { if data != "invalid" { return "No error", nil } errorData := errors.New("invalid data received") return "", errorData } func main() { currentString, err := fetchData("Some data") fmt.Println("Current String :", currentStri...
// 公众号下的用户服务列表 // 1. 前端获取微信公众号需要的有效用户授权url // 2. 微信用户是否已经绑定(备注:前端获取有效url后,访问微信公众号。若有效,则微信公众号会回调, 前端解析url,会拿到appid和拿AccessToken所需要的code) package controllers import ( "strings" "github.com/1046102779/common/consts" . "github.com/1046102779/official_account/logger" "github.com/1046102779/official_account/models" "g...
package dashboard import "namanerp/controllers/_base" type FinanceDashboardController struct { base.BaseController } // Get request for main controller func (c *FinanceDashboardController) Get() { c.Data["webTitle"] = "Dashboard 1" c.Data["metaDescription"] = "NamanERP | Finance & Accounting Dashboard" c.Data["...
package awattar import ( "encoding/json" "time" ) const RegionURI = "https://api.awattar.%s/v1/marketdata" type Prices struct { Data []PriceInfo } type PriceInfo struct { StartTimestamp time.Time `json:"start_timestamp"` EndTimestamp time.Time `json:"end_timestamp"` Marketprice float64 `json:"marketpri...
package main import ( "errors" "log" "github.com/tidwall/gjson" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) var ( // ErrNameNotProvided is thrown when a name is not provided ErrNameNotProvided = errors.New("no name was provided in the HTTP body") ) // H...
package dashboard import ( keptnapi "github.com/keptn/go-utils/pkg/lib" "github.com/stretchr/testify/assert" "testing" ) func TestParseMarkdownConfigurationParams(t *testing.T) { testConfigs := []struct { input string expectedScore *keptnapi.SLOScore expectedComparison *keptnapi.SLOCompari...
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package config import ( "github.com/eduardogpg/gonv" "fmt" ) type Config interface{ url() string } type DatabaseConfig struct { username string password string host string port int database string debug bool } type ServerConfig struct { host string port int debug bool } var database *DatabaseConfig v...
package main import ( "fmt" "time" ) func main() { timer1 := time.NewTimer(2 * time.Second) <-timer1.C fmt.Println("Timer 1 expired") timer2 := time.NewTimer(time.Second) go func() { <-timer2.C fmt.Println("Timer 2 expired") }() // the Goroutine above is waiting on the expiration via timer2's // sign...
package main import "fmt" // Square ... type Square struct { side float64 } func (z Square) area() float64 { return z.side * z.side } // Shape ... type Shape interface { area() float64 } func info(z Shape) { fmt.Println("z...(Square struct)", z) fmt.Println("z area...(Square's area)", z.area()) } func main()...
package adapter import ( "testing" ) func TestShouldFilterEmtpy(t *testing.T) { rh, err := NewResourceHelper("", "") if err != nil { t.Errorf("empty excludes should not return error") } filter := rh.shouldFilter("what", "ever") if filter == true { t.Errorf("empty excludes should not trigger filter") } } ...
package talib type Kline struct { Open float64 High float64 Low float64 Close float64 }
/* * Copyright (c) zrcoder 2019-2020. All rights reserved. */ package best_time_to_buy_and_sell_stock import "math" /* 给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。 你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。 返回获得利润的最大值。 示例 1: 输入: prices = [1, 3, 2, 8, 4, 9], fee = 2 输出: 8 解释: ...
// Copyright 2017 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package api import ( "fmt" "net/url" "strconv" ) func (c *InfraClient) queryAlertInfraConditions(policyID int) ([]AlertInfraCondition, error) { conditions := []AlertInfraCondition{} reqURL, err := url.Parse("/alerts/conditions") if err != nil { return nil, err } qs := reqURL.Query() qs.Set("policy_id", s...
package geo import ( "github.com/buckhx/diglet/util" "github.com/buckhx/rtreego" ) var ( RtreeMinChildren = 25 RtreeMaxChildren = 50 pointLen = 0.00001 //~1m ) type Rtree struct { rtree *rtreego.Rtree } func NewRtree() *Rtree { return &Rtree{ rtree: rtreego.NewTree(RtreeMinChildren, RtreeMaxChildre...
// Copyright (c) 2011 Mateusz Czapliński (Go port) // Copyright (c) 2011 Mahir Iqbal (as3 version) // 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 li...
package eventsourcing import ( "github.com/caos/logging" "github.com/caos/zitadel/internal/cache" "github.com/caos/zitadel/internal/cache/config" "github.com/caos/zitadel/internal/eventstore/models" "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model" ) type IamCache struct { iamCache cache.Cac...
package payment type Transaction struct { ID uint64 Amount int64 }
// Copyright 2018 The go-Dacchain Authors // This file is part of the go-Dacchain library. // // The go-Dacchain library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License...
package dboperation import "github.com/SuperTikuwa/webpro-app/model" func CreateSchedule(schedule *model.Schedule) error { db := gormConnect() defer db.Close() return db.Create(*schedule).Error } func SelectAllScheduleByUserID(userID int64) ([]model.Schedule, error) { db := gormConnect() defer db.Close() var...
package main import "unicode" //241. 为运算表达式设计优先级 //给你一个由数字和运算符组成的字符串expression ,按不同优先级组合数字和运算符,计算并返回所有可能组合的结果。你可以 按任意顺序 返回答案。 // //生成的测试用例满足其对应输出值符合 32 位整数范围,不同结果的数量不超过 10^4 。 // // // //示例 1: // //输入:expression = "2-1-1" //输出:[0,2] //解释: //((2-1)-1) = 0 //(2-(1-1)) = 2 //示例 2: // //输入:expression = "2*3-4*5" //输出:[-3...
package configuration import ( "github.com/go-redis/redis" "log" "os" ) func NewRedisClient() *redis.Client { url := os.Getenv("REDIS") opt, err := redis.ParseURL(url) if err != nil { log.Fatal(err) } client := redis.NewClient(opt) _, redisError := client.Ping().Result() if redisError != nil { log.Fa...
package panic_recover import "fmt" //延迟调用中引发的错误,可被后续延迟调用捕获,但仅最后一个错误可被捕获。 func PanicDelay() { // 此处无法被捕获 defer func() { panic("fis defer panic") }() defer func() { fmt.Println(recover()) }() // 最后一个延迟调用引发的错误 覆盖前一个 defer func() { panic("second defer panic") }() // 被覆盖 defer func() { panic("defer panic...
package main import ( "log" "net/http" "text/template" "github.com/lancatlin/balance" ) var tpl *template.Template func init() { tpl = template.Must(template.ParseFiles("index.gohtml")) } func index(w http.ResponseWriter, r *http.Request) { equation := r.FormValue("a") if equation == "" { tpl.Execute(w, n...
package service /** * 1。GO语言在命名的时候,一般会在单词后面添加er,如有写操作的接口叫writer,有字符串功能叫stringer,又关闭功能的 接口叫closer * 2.方法名:当方法名首字母大写时,且这个接口类型名首字母也是大写是,这个方法可以被接口所在的包之外的代码访问 * 3. 参数列表、返回值列表:参数列表和返回值列表中的参数变量名可以被忽略 * */ type writer interface { Writer([]byte) error } /** * 开发中常见的接口及写法 * 这个接口可以调用Writer()方法写入一个字节数组,返回值告诉写入字节数,和可能发生的错...
package memtaskmgr import ( "context" "fmt" "sync" "testing" "github.com/go-courier/mq/worker" "github.com/go-courier/mq" ) var taskMgr = NewMemTaskMgr() func BenchmarkTaskMgr(b *testing.B) { for i := 0; i < b.N; i++ { _ = taskMgr.Push("TEST", mq.NewTask("", nil, fmt.Sprintf("%d", i))) _, _ = taskMgr.Sh...
package c func (ch Child) assertErrorTolerance() (uint32, *ErrorToleranceReached) { errTolerance := ch.spec.ErrTolerance switch errTolerance.check(ch.restartCount, ch.createdAt) { case errToleranceSurpassed: return 0, &ErrorToleranceReached{ failedChildName: ch.GetRuntimeName(), failedChildErrCount: ...
package main import ( "fmt" log "github.com/sirupsen/logrus" "sync" // "strings" simhash "minHashLzwAsync/src/simhash" ) // Worker is a struct type in charge of concurrent hashing and compression type Worker struct { c chan ChanType } var rw sync.RWMutex func (w *Worker) acceptString() { log.Info("inside wo...
// Copyright 2017 The go-ethereum Authors // This file is part of go-ethereum. // // go-ethereum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
package types import ( sdk "github.com/cosmos/cosmos-sdk/types" ) const ( DefaultCodespace sdk.CodespaceType = ModuleName CodeOrderDoesNotExist sdk.CodeType = 101 ) func ErrOrderDoesNotExist(codespace sdk.CodespaceType) sdk.Error { return sdk.NewError(codespace, CodeOrderDoesNotExist, "Order does not exist") }
package extract import ( "github.com/OlegSchwann/GoDao/internal/template" "go/ast" "go/token" "runtime" "strings" ) func Extract(file *ast.File) (dot template.DotType, err error) { // copy package name dot.PackageName = file.Name.Name // copy all used packages directly // TODO: Copy all used packages from t...
package main import "github.com/centricwebestate/kissmetricsgo" import "net/url" func main() { // Initialise the Go Library km := kmgo.NewKM("yourapikeyhere") // Create a list of properties to send to kiss (can be empty) properties := url.Values{} properties.Set("test property", "true") // Finally create the ...
package server import "net/http" func GetApiMethods(w http.ResponseWriter, r *http.Request) (interface{}, *HandlerError) { return AllApiMethods, nil } func Handle(){ } func StartSubchain(){ } func CloseSubchain(){ } func JoinSubchain(){ } var START_SUBCHAIN = ApiMethod{ Name : "StartSubchain", Signature: ...
/** 四则运算 分为操作数和操作符号两个栈,依次进栈 操作符这边假如等待进栈的符号优先级<=操作符栈栈顶的元素, 那就先从栈中弹出一个符号,两个数,做完操作后,再压栈 */ package stack import ( "strconv" ) var ( // 操作符的优先级 opPrior = map[string]int{ "+": 1, "-": 1, "x": 2, "/": 2, } // 操作符的元素方式 opCal = map[string]CalFunc{ "+": plus, "-": minus, "x": multiply, "/": divide, } ) ...