text
stringlengths
11
4.05M
package password import ( "golang.org/x/crypto/bcrypt" ) func HashAndSalt(plaintextPassword string) (string, error) { hash, err := bcrypt.GenerateFromPassword([]byte(plaintextPassword), bcrypt.MinCost) if err != nil { return "", err } return string(hash), nil } func ComparePlaintextWithEncypted(plaintextPass...
/* Tencent is pleased to support the open source community by making Basic Service Configuration Platform available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain...
package models import ( "github.com/astaxie/beego/orm" "time" ) //`id` bigint(20) NOT NULL COMMENT '主键id', //`current_price` varchar(50) DEFAULT NULL COMMENT '当前价格', //`balance` varchar(50) DEFAULT NULL COMMENT '差额', //`price_rate` varchar(50) DEFAULT NULL COMMENT '增长率', //`begin_date` datetime DEFAULT NULL COMMENT...
// Copyright 2021 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 ...
package proto // nolint:lll func _() { /* dummy file that fixes this error when build tag proto is not specified: $ go mod tidy [...] github.com/jwkohnen/airac imports github.com/jwkohnen/airac/proto: module github.com/jwkohnen/airac@latest found (v1.0.4), but does not contain package github.c...
package main import "fmt" type user struct{} type manager struct { user // 匿名字段 } func (user) toString() string { return "user" } func (m manager) toString() string { return m.user.toString() + "; manager" } func main() { var m manager fmt.Println(m.toString()) fmt.Println(m.user.toString()) }
package main import "fmt" func main() { var t complex64 t = 2.1 + 3.14i fmt.Println(t) //自动推导类型 //默认为complex128 t1 := 3.3 + 4.4i fmt.Printf("%T\n",t1) //通过内建函数 取实部 虚部 fmt.Println(real(t1),imag(t1)) }
package bash import ( "os/exec" "github.com/swanwish/go-common/logs" ) func ExecuteCmd(command string) (string, error) { logs.Debugf("Execute command %s", command) cmd := exec.Command("bash", "-c", command) cmdOutput, err := cmd.CombinedOutput() if err != nil { logs.Errorf("Failed to combiled output, the er...
//Example of how to use generic tool to pipe in workloads and use //concurrency to process input package main import ( "bufio" "flag" "fmt" "log" "net/http" "os" "sync" ) var n int type task interface { process() output() } type factory interface { create(line string) task } // build program //echo "http...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //82. Remove Duplicates from Sorted List II //Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers f...
package engine import ( "math" "regexp" ) type IRoutes interface { Use(...HandlerFunc) IRoutes Handle(string, string, ...HandlerFunc) IRoutes Any(string, ...HandlerFunc) IRoutes GET(string, ...HandlerFunc) IRoutes POST(string, ...HandlerFunc) IRoutes } type IRouter interface { IRoutes Group(string, ...Hand...
package main import ( "log" "os/exec" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestVersion(t *testing.T) { version := executeChecked("go run main.go -v") assert.Equal(t, "oi version 0.0.1\n", version) } func executeChecked(command string) (output string) { words := strings.Split(comma...
package v1alpha1 import ( v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // TrilioVaultSpec defines the desired state of TrilioVault type TrilioVaultSpec struct { // Scope for the application which will be installed in the cluster // NamespaceScope or ClusterScope ApplicationScope strin...
// Copyright 2016-present, 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 ag...
package hello func Hello() string { return "Hello, world." } package hello import "rsc.io/quote/v3" func Hello() string { return quote.HelloV3() } func Proverb() string { return quote.Concurrency() } $ cat hello_test.go package hello import ( "testing" ) func TestHello(t *testing.T) { want := "H...
package main import ( "testing" "github.com/jackytck/projecteuler/tools" ) func TestP76(t *testing.T) { cases := []tools.TestCase{ {In: 100, Out: 190569291}, } tools.TestIntInt(t, cases, dp, "P76") }
package fileutil import ( "os" "runtime" ) // Exists returns whether the given file or directory exists or not. func Exists(path string) bool { _, err := os.Stat(path) return !os.IsNotExist(err) } // HomeDir returns the path to the current user's home directory. func HomeDir() string { if runtime.GOOS == "windo...
package types import ( "fmt" cmn "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/common" ) // VoteMessage is sent when voting for a proposal (or lack thereof). type VoteMessage struct { Vote *Vote } // CommitStepMessage is sent when a block is committed. type CommitStepMessage struct { Height ...
package main import ( "fmt" "os" "github.com/hoop33/perm/cmd" "github.com/hoop33/perm/config" ) func main() { // Don't launch if we aren't going to be able to save our configuration if err := verifyConfigDir(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } cmd.Execute() } func verifyConfigDir()...
/* * Copyright 2018 Haines Chan * * This program is free software; you can redistribute and/or modify it * under the terms of the standard MIT license. See LICENSE for more details */ package etcd import ( "context" "crypto/tls" "fmt" "net" "strings" "time" "github.com/coreos/etcd/clientv3" "github.com/...
package cmd import ( log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" ) // RootCmd is the root command of tankerctl var RootCmd = &cobra.Command{ Use: "tankerctl", Short: "Export gasoline data as sensision metrics", } func init() { cobra.OnInitialize(configure) RootCmd.Per...
package main import ( "fmt" "os" "github.com/Cloud-Foundations/Dominator/lib/log" ) func showImageSubcommand(args []string, logger log.DebugLogger) error { if err := showImage(args[0]); err != nil { return fmt.Errorf("error showing image: %s", err) } return nil } func showImage(image string) error { fs, _,...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //132. Palindrome Partitioning II //Given a string s, partition s such that every substring of the partition is a palindrome. //Return the minimum cuts...
package ntp import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/authelia/authelia/v4/internal/configuration/schema" "github.com/authelia/authelia/v4/internal/configuration/validator" ) func TestShouldCheckNTPV4(t *testing.T) { config := &schema.Configuration{ NTP: schema.NTP{ Addre...
package meda import ( "context" "database/sql" "github.com/jmoiron/sqlx" "github.com/pkg/errors" ) const checksumWarningsTableNameBase = "checksum_warnings" func (d *DB) ChecksumWarningsTableName() string { return d.Config.TablePrefix + checksumWarningsTableNameBase } const checksumWarningsCreateTableQuery = ...
/* Challenge Premise Bob is a novice pianist who can only play sequences of single notes. In addition, he does quite an interesting thing: for every note after the first, if it's higher than the previous note was, he uses the finger directly to the right of the previous finger used; if lower, to the left; if the same...
package logger import ( "errors" "fmt" _ "github.com/mailru/easyjson/gen" "path/filepath" "runtime" "strings" "time" ) const ISO8601 = "2006-02-03 15:04:05" const ( LevelError = iota LevelWarning LevelInformational LevelDebug ) //easyjson type logger struct { level uint8 `json:"omitempty"` Level ...
package qiwi import ( "fmt" "strconv" ) type currency string const ( RUB currency = "RUB" USD currency = "USD" EUR currency = "EUR" //GBP Currency = "GBP" ) // kopeeksInRuble used to make float amount value from int const kopeeksInRuble float64 = 100 type money float64 func toMoney(a int) money { return mo...
package ping import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_ping_unit(t *testing.T) { Convey("ping", t, func() { Convey("ParsePingResponseLine()", func() { tests := []string{ "64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.052 ms", ...
/* * @lc app=leetcode.cn id=999 lang=golang * * [999] 可以被一步捕获的棋子数 */ package main // @lc code=start func numRookCaptures(board [][]byte) int { var rookX, rookY int for i := 0; i < len(board); i++ { flag := false for j := 0; j < len(board[0]); j++ { if board[i][j] == 'R' { rookX, rookY = i, j flag ...
package main import ( "log" ) func getMaxProfit(stockPrices []int) int { var lowestPrice int var highestPrice int var lowestPriceIndex int var highestPriceIndex int for i, price := range stockPrices { if (price < lowestPrice || lowestPrice == 0) && i != len(stockPrices)-1 { lowestPrice = price lowestPr...
package main import ( "os" "fmt" "time" "errors" "math/rand" ioutil "io/ioutil" http "net/http" ) // HealthBadCount suck it var HealthBadCount = 0 func statusServer() { http.HandleFunc("/ping", pingHandle) http.HandleFunc("/health", healthHandle) http.HandleFunc("/healthBad", healthBadHandl...
package parser import ( "errors" "fmt" "regexp" "time" "github.com/alecthomas/participle" "github.com/alecthomas/participle/lexer" "github.com/flynn/biscuit-go" "github.com/flynn/biscuit-go/datalog" ) var ( ErrVariableInFact = errors.New("parser: a fact cannot contain any variables") ) var defaultParserOpt...
package main import ( "testing" ) func TestCalcScore(t *testing.T) { userAns := []int{1, 2, 3, 45, 6} examAns := []int{1, 2, 3, 45, 6} score := calcScore(&userAns, &examAns) if score != 5 { t.Errorf("should be 5 by given: %v and %v", userAns, examAns) } userAns = []int{1, 2} examAns = []int{1, 2} score = c...
package main import "fmt" func main() { fmt.Println(test("abc", "cba", true)) fmt.Println(test("abc", "abd", false)) } func permutation(a, b string) bool { mapA := make(map[int32]int) for _, val := range a { mapA[val]++ } for _, val := range b { mapA[val]-- if mapA[val] < 0 { return false } } re...
package entity import ( "time" "github.com/fatih/structs" ) type NetworkFee struct { Id int64 TransactionId int64 MerchantId int64 FromAccountId int64 AddressId int64 Chain string Token string Address string Tag string Calculate...
package models import "time" type User struct { ID int `gorm:"primary_key" json:"id"` Username string `gorm:"column:username;type:varchar(40);unique;not null" json:”username” ` Email string `gorm:"column:email;type:varchar(40);unique;not null" json:”email” ` Password string `gorm:"column:password;typ...
package auth import ( "context" "net/http" "github.com/google/uuid" "github.com/micro/go-micro/v2/metadata" ) // GenerateToken 是用户凭证的生成函数 func GenerateToken() string { return uuid.New().String() } // contextKey 用于获取上下文环境 type contextKey string // AccessTokenKey 用于从 Context 的 Metadata 中获取和设置用户会话访问凭证 const Acce...
package main /* #include "httpd_cb.h" #include <string.h> #include <stdio.h> static fn_client_accepted client_accepted = NULL; static void set_httpd_cb(void* cb) { client_accepted = (fn_client_accepted)cb; } static void request_coming(int client_id) { client_accepted(client_id); } static void iter_env(void* iter_...
package server import ( "github.com/gin-gonic/gin" "github.com/sanguohot/medichain/service" "github.com/sanguohot/medichain/util" "github.com/sanguohot/medichain/zap" uberZap "go.uber.org/zap" "io/ioutil" "net/http" "time" ) func PongHandler(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "pong", ...
package main import ( "flag" "github.com/pkg/profile" "github.com/sergeyfrolov/gotapdance/tapdance" "github.com/sergeyfrolov/gotapdance/tdproxy" "os" ) func main() { defer profile.Start().Stop() var port = flag.Int("port", 10500, "TapDance will listen for connections on this port.") var assets_location = fla...
/* Custom storage-cient (for benchmarking purposes). Edit IPs with the IPs of the server you want to connect to Program can be runned like this: go run main.go numberOfRequests mode(r/read/Read/READ or w/Write/write/WRITE) @author: Andrea Esposito */ package main import ( "context" "encoding/csv" "errors" "fmt" ...
package binomialheap import ( "fmt" ) type BiNode struct { key int degree int child *BiNode sibling *BiNode parent *BiNode } type Blist struct { head *BiNode size int } func CreateNewHeap() *Blist { return &Blist{head: nil, size: 0} } func CreateNewNode(keyval int) *BiNode { return &BiNode{key: ke...
package main import ( "github.com/qiniu/db/mgoutil.v3" "gopkg.in/mgo.v2/bson" ) type M map[string]interface{} type User struct { UserId bson.ObjectId `json:"userId" bson:"_id"` Phone string `json:"phone" bson:"phone"` //用户ID Name string `json:"name" bson:"name"` //用户名 Avatar stri...
package oauth2 import ( "errors" ) type ReferenceToken interface { TokenID() string ClientID() string Expiry() int64 AccessToken() string } // referenceToken stores all relevant information for reference tokens type referenceToken struct { tokenID string clientID string expiry int64 accessToken ...
package common import "time" type Report struct { Timestamp time.Time Message string PhotoId string PhotoCaption string Type string } type ReportInfo struct { Timestamp time.Time Message string PhotoId string PhotoCaption string Type string Latitude float64 L...
package main import ( "bufio" "fmt" "os" ) // readLines reads a whole file into memory // and returns a slice of its lines. func readLines(path string) ([][]rune, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() var lines [][]rune scanner := bufio.NewScanner(file) ...
package main import ( "bytes" "container/list" "crypto/rand" "encoding/hex" "flag" "fmt" "io/ioutil" "log" "net/http" "net/http/httputil" "net/url" "os" "sync" "time" "github.com/op/go-logging" "github.com/ugorji/go/codec" "gopkg.in/redis.v3" ) var logger = logging.MustGetLogger("cachier") var forma...
package redisClient import ( "fmt" "github.com/garyburd/redigo/redis" ) /** * 向redis中写入一个key—val类型的字符串 * @key string 参数的主键 * @val string 需要写入缓存的值 * @Ex int 超时时间(秒) 参数为0时,永远不过期 * return 返回影响行数 */ func (this *RedisPool) StringWrite(key string, val string, EX int) { key = this.prefix + ":" + key var err ...
package main import ( "fmt" "io/ioutil" "log" "net/http" ) func main() { fmt.Println("Starting our app") response, err := http.Get("https://api.coinbase.com/v2/prices/BTC-USD/buy") if err != nil { log.Fatal("The Http request failed with an error", err) } data, _ := ioutil.ReadAll(response.Body) fmt.Pri...
package main import ( "fmt" "strconv" ) func main() { result := "50" fmt.Println(strconv.Atoi(result)) }
package main import ( "image" "image/color" "os" "image/png" ) var img = image.NewRGBA(image.Rect(0,0,500,500)) //area of figure var col color.Color func main() { col = color.RGBA{0, 0, 255, 255} // Red //VLine(10, 20, 80) //HLine(10, 20, 80) col = color.RGBA{255, 0, 0, 255} // Green //Rect(0,0,100,100...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/10/9 8:41 上午 # @File : lt_125_验证回文字符串.go # @Description : # @Attention : */ package offer import "strings" // 解题关键: 首尾双指针遍历即可 func isPalindrome(s string) bool { ret := "" for i := range s { if isalnum(s[i]) { ret += string(s[i]) } } s = strings.To...
package logger import ( "fmt" "os" "runtime" "strings" "time" "github.com/labstack/echo/v4" "github.com/sirupsen/logrus" "gopkg.in/natefinch/lumberjack.v2" ) var hasLoad = false var lg = logrus.New() // loadConfig - Load intial config func loadConfig() { lg.SetReportCaller(true) f := "/log.log" if os.Ge...
package dingtalk import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "io/ioutil" "net" "net/http" "strconv" "strings" "time" "github.com/pkg/errors" "go.uber.org/zap" "prometheus-alertmanager-dingtalk/config" "prometheus-alertmanager-dingtalk/zaplog" ) func NewDingTalk() ...
package first import ( "go/token" "github.com/bunniesandbeatings/go-flavor-parser/architecture" ) type Context struct { Filename string Package *architecture.Package Fset *token.FileSet }
package main import ( "fmt" "time" ) func write(ch chan int) { for i := 0; i < 100; i++ { ch <- i fmt.Println("generate ", i) } } func read(ch chan int) { for { b := <-ch fmt.Println(b) time.Sleep(10 * time.Millisecond) } } func main() { chann := make(chan int, 10) go write(chann) go read(chann...
package main func sortArray(nums []int) []int { quickSort2(0, len(nums)-1, nums) return nums } func partition4(i, j int, nums []int) int { key := nums[i] left := i for i < j { for i < j && nums[j] > key { j-- } // 注意先后顺序不能颠倒 for i < j && nums[i] <= key { i++ } if i < j { nums[i], nums[j] = ...
package main import ( "errors" "fmt" "log" "net" "os" "os/signal" "runtime" "strconv" "syscall" "time" "github.com/pkg/profile" "github.com/scottshotgg/proximity/pkg/buffs" grpc_node "github.com/scottshotgg/proximity/pkg/node/grpc" "google.golang.org/grpc" "google.golang.org/grpc/reflection" ) func Pr...
/* * Copyright 2018, CS Systemes d'Information, http://www.c-s.fr * * 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 requir...
/* Copyright (c) 2016 Jason Ish * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions...
package gce import ( "github.com/caos/orbos/internal/helpers" "github.com/caos/orbos/internal/operator/orbiter/kinds/clusters/core/infra" "github.com/caos/orbos/mntr" uuid "github.com/satori/go.uuid" ) func destroy(svc *machinesService, delegates map[string]interface{}) error { return helpers.Fanout([]func() err...
package handler import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "github.com/tada3/triton/logging" "github.com/tada3/triton/weather" "github.com/tada3/triton/weather/model" "github.com/tada3/triton/weather/util" "github.com/tada3/triton/game" "github.com/tada3/triton/protocol" "github.com...
package timingwheel import ( "math/rand" "sync" "time" ) var ( count = 5 tws = []*TimingWheel{} once sync.Once ) func init() { for i := 0; i < count; i++ { tw := New(1*time.Second, 600) // 10 minite tw.Start() tws = append(tws, tw) } } func SetDefaultTimeingWheels(obj []*TimingWheel) { for _, tw :...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-25 10:50 * Description: *****************************************************************/ package pdl type PDLQuery interface { GetServiceByFullN...
package manage import ( "github.com/gin-gonic/gin" "server-monitor-admin/global" "server-monitor-admin/global/response" ) func Test1(c *gin.Context) { println(global.VIPER) println(global.VIPER.GetString("test.name")) response.OkMsg(global.VIPER.GetString("test.name"), c) } func Test2(c *gin.Context) { c.Get(...
package main import ( "fmt" ) func main() { var x [4]string //var x[5]int fmt.Println(x) x[0] = "May" x[1] = "June" x[2] = "July" x[3] = "August" fmt.Println(x) fmt.Println(len(x)) fmt.Println(cap(x)) }
/* Copyright 2023 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 sequentialdigits import ( "sort" "strconv" "strings" ) func isSequential(nums []int) bool { isSequential := true for ind := 0; ind < len(nums)-1; ind++ { numInt := nums[ind] nextNumInt := nums[ind+1] if nextNumInt-numInt != 1 { isSequential = false break } } return isSequential } func ba...
package chargen import "math/rand" func randomItem(items []string) string { return items[rand.Intn(len(items))] } func itemInCollection(item string, collection []string) bool { for _, element := range collection { if item == element { return true } } return false }
// Copyright 2021 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package redis import ( "fmt" "github.com/gin-gonic/gin" "github.com/go-session/redis" "github.com/go-session/session" "github.com/linqiurong2021/gin-arcgis/config" ) // RedisStore RedisStore var RedisStore session.Store // InitRedisSession 初始化 func InitRedisSession(cfg *config.RedisConfig) { addr := fmt.Sprin...
/* xkcd is everyone's favorite webcomic, and you will be writing a program that will bring a little bit more humor to us all. Your objective in this challenge is to write a program which will take a number as input and display that xkcd and its title-text (mousover text). Input Your program will take a positive inte...
package pg_astro import ( "bufio" "bytes" "log" "net" "sync" "time" ) var printMx sync.Mutex type Server struct { Addr string IdleTimeout time.Duration IdleControllerTimeout time.Duration MaxReadBytes int64 listener net.Listener conns map[*conn]struct{} mu ...
package main import ( "fmt" "strconv" ) // Person define struct type Person struct { firstName, lastName, city, gender string age int } // Greeting method , (value reciever) GOOD for CALULATION func (p Person) greet() string { return "Hello, my name is " + p.firstName + " " + p.las...
package sheet_logic import ( "fmt" "hub/sheet_logic/sheet_logic_types" ) const EmptyExpressionName string = "<none>" type GrammarContext interface { GetIntValue(string) (int64, error) GetFloatValue(string) (float64, error) GetStringValue(string) (string, error) GetBoolValue(string) (bool, error) } type Gramma...
package render import ( "net/http" renderer "github.com/unrolled/render" ) var ( Renderer *renderer.Render ) func init() { Renderer = renderer.New() } func Render(w http.ResponseWriter, e renderer.Engine, data interface{}) error { return Renderer.Render(w, e, data) } func Data(w http.ResponseWriter, status i...
package keeper_test import ( "github.com/irisnet/irismod/modules/nft/keeper" "github.com/irisnet/irismod/modules/nft/types" ) func (suite *KeeperSuite) TestSetCollection() { nft := types.NewBaseNFT(tokenID, tokenNm, address, tokenURI, tokenData) // create a new NFT and add it to the collection created with the NF...
package main import "fmt" /* Ranging over a channel and closing it after it's done */ func main() { c := make(chan int) fmt.Println("For science!") //SEND go func() { for i := 20; i >= 0; i-- { c <- i } close(c) //if we don't close - deadlock }() //RECEIVE for val := range c { fmt.Println(val) } ...
package service import ( "fmt" "github.com/gorilla/mux" "jabrok.com/global" "net/http" "strconv" ) func Start() { r := mux.NewRouter() r.HandleFunc("/", HandleRoot).Methods("GET") r.HandleFunc("/boom", HandleBoom).Methods("GET") r.HandleFunc("/status", HandleStatus).Methods("GET") r.HandleFunc("/sd", Handle...
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type CoerceToDomain struct { Xpr ast.Node Arg ast.Node Resulttype Oid Resulttypmod int32 Resultcollid Oid Coercionformat CoercionForm Location int } func (n *CoerceToDomain) Pos() int { return n.Location ...
// Copyright 2015,2016,2017,2018,2019 SeukWon Kang (kasworld@gmail.com) // 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...
package tcp import ( "MP1/errorchecker" "MP1/messages" "fmt" "net" "time" ) // Configure a node to listen for tcp connections. func (node Node) UnicastReceive() { // Listen to an unused TCP port on localhost. port := ":" + node.Port listener, err := net.Listen("tcp", port) errorchecker.CheckError(err) defer...
// Service to handle connections from puppet server package impl import ( "bufio" "io/ioutil" "log" "net" "sync" "time" ) type Service struct { waitGroup *sync.WaitGroup listener *net.TCPListener env *EnvironmentCollection } // Store a pointer to environment collections to call funcs func (s *Service...
package main import ( "fmt" "math" ) //思路:充分利用满二叉树的性质 //在第level层时,当前节点值为label,则可以找到其对称节点为b=2^level-1+2^(level-1)-label //2^level-1+2^(level-1)即为该层对称节点总和 //找到其对称节点后,该对称节点的父节点即为当前label的上一层父节点 //然后每次循环直到label为0 func pathInZigZagTree(label int) []int { level := int(math.Log2(float64(label))) res := make([]int, level+...
package main import ( "fmt" "os" _ "github.com/zquestz/visago/visagoapi/clarifai" _ "github.com/zquestz/visago/visagoapi/googlevision" _ "github.com/zquestz/visago/visagoapi/imagga" "github.com/zquestz/visago/cmd" ) func main() { setupSignalHandlers() if err := cmd.FilesCmd.Execute(); err != nil { fmt.Fp...
package main /** 剑指 Offer 20. 表示数值的字符串 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。 例如,字符串"+100"、"5e2"、"-123"、"3.1416"、"-1E-16"、"0123"都表示数值,但"12e"、"1a3.14"、"1.2.3"、"+-5"及"12e+5.4"都不是。 */ /** Error */ func IsNumber(s string) bool { // nothing to do. return false }
package config import ( "fmt" "log" "os" "strconv" "github.com/joho/godotenv" ) var ( // ConnString is the database connection string ConnString = "" // APIPort is the port where API will listen to APIPort = 0 ) // LoadEnv will load the environment variables func LoadEnv() { var error error if error = ...
package main import ( "encoding/csv" "fmt" "io" "net/http" "os" "path/filepath" "sort" "strconv" "time" ) func recursiveDirectoryHandlerFunc( rw http.ResponseWriter, r *http.Request, c Context) error { rw.Header().Set("Content-Type", "text/csv; charset=utf-8") w := csv.NewWriter(rw) w.Write([]string{"Pa...
// Copyright 2015 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...
// Copyright 2021 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 template // ParamsMain is the data structure for the Control Plane Initializer template. type ParamsMain struct { IAMRoles *ParamsMainIAMRoles }
// Copyright 2020 The Swarm 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 pricing_test import ( "bytes" "context" "io/ioutil" "math/big" "reflect" "testing" "github.com/ethersphere/bee/pkg/logging" "github.com/eth...
package main import "fmt" func generadorimPares() func() int { i := int(1) // i permanecerá en el clousure de la función anónima a retornar return func() int { var impar = i i += 2 return impar } } func main() { nextimPar := generadorimPares() fmt.Println(nextimPar()) fmt.Println(nextimPar()) fmt.Printl...
package main import ( "flag" "fmt" "os" ) const Usage = ` addBlock --data DATA "add a block to block chain" printChain "print all blocks" ` type CLI struct { bc *BlockChian } func (cli *CLI)Run() { if len(os.Args) < 2 { fmt.Println("too few parameters!\n", Usage) os.Exit(1) } addBlockCm...
package treecmds import ( "fmt" "strings" "github.com/Nv7-Github/Nv7Haven/eod/trees" "github.com/Nv7-Github/Nv7Haven/eod/types" "github.com/bwmarrin/discordgo" ) func (b *TreeCmds) NotationCmd(elem string, m types.Msg, rsp types.Rsp) { b.lock.RLock() dat, exists := b.dat[m.GuildID] b.lock.RUnlock() if !exis...
// // Copyright 2020 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 ...
// Copyright 2018 Diego Bernardes. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package repository import ( "context" "encoding/json" "fmt" "net/http" "net/url" "time" "github.com/pkg/errors" "github.com/diegobernardes/flare" ) ...
package error import ( "github.com/allentom/youcomic-api/services" "github.com/gin-gonic/gin" ) //error => ApiError var errorMapping = map[error]ApiError{ JsonParseError: parseJsonApiError, UserAuthFailError: userAuthFailedApiError, PermissionError: permissionDeniedApiError, RequestPathError: requestPathA...
package g2util import ( "reflect" ) // ValueIndirect ...值类型 func ValueIndirect(val reflect.Value) reflect.Value { for val.Kind() == reflect.Ptr { val = val.Elem() } return val } // NewValue ... func NewValue(bean interface{}) (val interface{}) { v := ValueIndirect(reflect.ValueOf(bean)) /*if v.IsZero() { p...