text
stringlengths
11
4.05M
package main import "fmt" func main(){ var c string = "A" var age int =2 var result float32 = 4.33 fmt.Println(c, age, result) }
package main import ( "fmt" "runtime" ) var x1 int var y1 rune var z1 byte func main() { x := 42 y := 45.55 fmt.Println(x) fmt.Println(y) fmt.Printf("%T\n", x) fmt.Printf("%T\n", y) x1 = 454 fmt.Println(x1) y1 = 343 fmt.Println(y1) z1 = 0 fmt.Println(z1) fmt.Println(runtime.GOMAXPROCS) fmt.Println(ru...
package main import ( "flag" "github.com/fmstephe/fstrconv" "github.com/fmstephe/matching_engine/matcher" "github.com/fmstephe/matching_engine/msg" "log" "math/rand" "os" "runtime/pprof" "time" ) const ( StockId = uint32(1) ) var ( filePath = flag.String("f", "", "Relative path to an ITCH file providing...
package main import "fmt" type stack struct { list []int } func (s *stack) push(elem int) { s.list = append(s.list, elem) } func (s *stack) pop() error { if len(s.list) == 0 { return fmt.Errorf("Stack is empty") } s.list = s.list[:len(s.list)-1] return nil } func (s *stack) Head() (int, error) { if len(s....
package handler import ( "encoding/json" "keepassapi/helper" "keepassapi/model" "net/http" "github.com/gorilla/mux" ) func Get(w http.ResponseWriter, r *http.Request) { path := "/" + mux.Vars(r)["path"] forceVal := r.URL.Query()["force"] force := false if len(forceVal) > 0 && forceVal[0] == "true" { force...
package worker import ( "context" "errors" "fmt" "log" "net" "net/http" nrpc "net/rpc" "sync" "time" "github.com/DataDog/hyperloglog" "github.com/giolekva/unique/rpc" ) type shutdownListener struct { cond *sync.Cond } func (l *shutdownListener) Shutdown(req *rpc.ShutdownRequest, resp *rpc.ShutdownRespon...
package dao import "fmt" // ErrUserNotFound is returned when a user for the provided ID was not found type ErrUserNotFound string func (e ErrUserNotFound) Error() string { return fmt.Sprintf("user not found with ID %s", string(e)) } // ErrPictureNotFound is returned when a picture for the provided ID was not found...
package actions import ( "errors" "github.com/barrydev/api-3h-shop/src/common/connect" "github.com/barrydev/api-3h-shop/src/factories" "github.com/barrydev/api-3h-shop/src/model" ) func GetOrderItemByOrderId(orderId int64) ([]*model.OrderItemJoinProduct, error) { query := connect.QueryMySQL{ QueryString: "WHER...
package amazonpa import ( "testing" "time" ) func newTestClient() *Client { config := Config{ "AKIAIOSFODNN7EXAMPLE", "1234567890", "mytag-20", "US", false, } return NewClient(config) } func TestRequestHasDefaultParameters(t *testing.T) { client := newTestClient() startTime := time.Now() request :...
package priorityqueue import ( "github.com/stretchr/testify/assert" "testing" ) func Test_PriorityQueue(t *testing.T) { pq := &PriorityQueue{&_PriorityQueue{}} pq.Push(5, 5) pq.Push(10, 10) pq.Push(3, 3) pq.Push(2, 2) pq.Push(8, 8) assert.Equal(t, 5, pq.Len()) assert.Equal(t, 10, pq.Pop()) assert.Equal(t...
// +build !gorilla // +build !raw package client import ( "context" "crypto/tls" "net" "net/http" "net/url" "nhooyr.io/websocket" ) func (cl *client) dial(p string, h http.Header) (conn net.Conn, err error) { var ( c = cl.Config ub = &url.URL{ Scheme: c.GetSchemeWS(), Host: c.GetAddr(), Path:...
/* Purpose: Call and test client library As will soon become apparent, I have no experience writing Go Or any other compiled language Let's see how we go */ package main import ( "fmt" // "log" "net/http" "io/ioutil" // "os" // "src/client" ) const baseURL = "https://api.form3.tech/" func main() { fetchR...
/* * Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. * * file: sflow_qa.go * details: sFlow packet handler for Query API Server * */ package msghandler import ( "bytes" "encoding/json" "fmt" opts "github.com/Juniper/collector/flow-translator/options" ) // SflowQAMessage sFlow message struc...
package splitIntoFibonacci import ( "strconv" "testing" ) func Test_splitIntoFibonacci(t *testing.T) { type args struct { S string } tests := []struct { name string args args want []int }{ // TODO: Add test cases. { name: "first", args: args{ S: "123456579", }, want: []int{123, 456, ...
package server // Data passed through channel from requested response type responseChunk struct { Bytes []byte Error error }
package realm import ( "encoding/json" "fmt" "io" "mime/multipart" "net/http" "os" "path/filepath" "github.com/10gen/realm-cli/internal/utils/api" ) const ( hostingPathPattern = appPathPattern + "/hosting" hostingAssetsPathPattern = hostingPathPattern + "/assets" hostingAssetPathPattern = hostingAs...
package storage type JsonStarage struct { } func NewJsonStarage() *JsonStarage { s := &JsonStarage{} return s }
// arrays.go package arrays import ( "errors" ) var startOfArrayIndex = 0 func SetArrayStartIndexToOne() { startOfArrayIndex = 1 } //Insert returns the array with element inserted at given position. func Insert(a []int, pos, val int) (b []int, err error) { pos -= startOfArrayIndex if len(a) < pos || pos < 0 { ...
/* Package testsuite has nothing to use in your application. This package is a backend independent test suite to verify the compatibility of this repository. */ package testsuite // import "go.mercari.io/datastore/testsuite"
package validator import ( "fmt" "os" "path" "sort" "strings" "github.com/authelia/authelia/v4/internal/configuration/schema" "github.com/authelia/authelia/v4/internal/utils" ) // ValidateServerTLS checks a server TLS configuration is correct. func ValidateServerTLS(config *schema.Configuration, validator *sc...
package internal import ( "context" "fmt" "strings" "time" fsAPI "github.com/matrix-org/dendrite/federationsender/api" "github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/gomatrixserverlib...
package db var globalVariables map[string]string func GetGlobalVariables() { rows, err := sqlDB.Query("SHOW GLOBAL VARIABLES") if checkErr(err, "GetGlobalVariables.Query") { return } var Variable_name string var Value string globalVariables = make(map[string]string) for rows.Next() { e...
package admin import ( "beego-blog/models" "fmt" "github.com/astaxie/beego/orm" "time" ) type UserController struct { BaseController } func (c *UserController) UserList () { c.Islogin() o := orm.NewOrm() var maps []orm.Params num, _ := o.Raw("SELECT * FROM user").Values(&maps) fmt.Println(num) //page := u...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/7/1 9:14 上午 # @File : jz_13_调整数组顺序使奇数位于偶数之前_test.go.go # @Description : # @Attention : */ package offer import ( "fmt" "testing" ) func Test_reOrderArray2(t *testing.T) { fmt.Println(reOrderArray2([]int{2, 4, 6, 5, 7})) }
// Package azure provides a cluster-destroyer for Azure clusters. package azure
package main /* * @lc app=leetcode id=337 lang=golang * * [337] House Robber III */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /* 遇到二叉树,一律优先递归完成 递归可以将很多复杂的问题简单话 // 这题还可以加上一个cache, 防止重复计算 */ ...
package gocql import ( "time" "github.com/b2wdigital/goignite/pkg/config" "log" ) const ( Hosts = "transport.client.gocql.hosts" Port = "transport.client.gocql.port" Username = "transport.client.gocql.username" Password = "transport.clien...
package matrix_util // SpiralOrder 获取矩阵螺旋顺。 func SpiralOrder(matrix [][]int) []int { // 1. 获取矩阵高度、宽度。 height, width := GetHeightAndWidth(matrix) // 2. 初始化。 upBound := 0 downBound := height - 1 leftBound := 0 rightBound := width - 1 // 3. 只有一个元素时。 if upBound == downBound && leftBound == rightBound { return...
/* * Package channel * LoopStack implementation * * Part of XPMC. * Defines elements that can represent MML loops (e.g. [cde | d+g]3 ) and stacks * on which you can store such elements. * * /Mic, 2014 */ package channel import "../utils" type LoopStackElem struct { StartPos int /* Th...
package main import ( "fmt" ) func main() { rls := `This is a raw litteral string "or so they say"` fmt.Println(rls) }
package rdx import "github.com/golang/protobuf/ptypes/duration" type Config struct { Network string Addr string Password string Db int32 DialTimeout *duration.Duration ReadTimeout *duration.Duration WriteTimeout *duration.Duration }
package main func bfs(start int, nodes map[int][]int, fn func (int)) { frontier := []int{start} visited := map[int]bool{} next := []int{} for 0 < len(frontier) { next = []int{} for _, node := range frontier { visited[node] = true fn(node) for _, n :=...
package dev import ( "fmt" "net/http" "os" "path/filepath" "time" "github.com/devspace-cloud/devspace/pkg/util/log" "github.com/pkg/errors" "github.com/devspace-cloud/devspace/e2e/utils" "github.com/devspace-cloud/devspace/pkg/devspace/config/generated" "github.com/devspace-cloud/devspace/pkg/devspace/conf...
/* 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 writ...
package parser // Node ... type Node struct { kind int value *int op1 *Node op2 *Node op3 *Node } // NewNode ... func NewNode(kind int, value *int, op1 *Node, op2 *Node, op3 *Node) *Node { return &Node{ kind: kind, value: value, op1: op1, op2: op2, op3: op3, } } // Kinds const ( KindP...
package serv type ( User struct { Id int Name string } UserMsg struct { User User Msg string Time string } )
/* @Time : 2019/4/12 19:29 @Author : yanKoo @File : talk_cloud_app_login_impl @Software: GoLand @Description: */ package server import ( pb "api/talk_cloud" "context" "database/sql" "log" tu "pkg/user" tuc "pkg/user_cache" "sync" ) type TalkCloudServiceImpl struct{} // 用户登录 func (tcs *TalkCloudServiceImpl) ...
package tdbdir_test import ( "database/sql/driver" "fmt" "bitbucket.org/matchmove/go-database/tdbdir" ) func ExampleGetExecFunc() { fq := tdbdir.GetExecFunc(tdbdir.Directory{ "DELETE FROM table WHERE id = ?": tdbdir.Entry{ Test: func(query string, args []driver.Value) (error, bool) { return nil, len(arg...
package convert import ( "errors" "fmt" "reflect" "github.com/google/skylark" "github.com/google/skylark/resolve" ) func init() { resolve.AllowNestedDef = true // allow def statements within function bodies resolve.AllowLambda = true // allow lambda expressions resolve.AllowFloat = true // allow float...
package pdns_api import ( "bytes" "fmt" "net" "net/http" "net/http/httptest" "reflect" "testing" ) func Test_httpAuth_Authenticate(t *testing.T) { type fields struct { requestHeader map[string]string } tests := []struct { name string userID string secret string fields fields want []stri...
package main import "fmt" func main() { //1,1,2,3,5,8,13,21,34,55 //第十个斐波那数是55 //num := 10 //fmt.Println(fbn(num)) fmt.Println(test(2)) fmt.Println(test(3)) fmt.Println(test(4)) fmt.Println(test(5)) } func fbn(num int) int { if num == 1 || num == 2 { return 1 } else { return fbn(num-1) + fbn(num-2) } } ...
package 前缀和 func pivotIndex(nums []int) int { sum := make([]int, len(nums)+1) // 获取前缀和, sum[i] 表示 nums[:i+1] 的和 for i := 1; i <= len(nums); i++ { sum[i] = sum[i-1] + nums[i-1] } for i := 1; i <= len(nums); i++ { left := sum[i-1] // nums[:i]的和 right := sum[len(nums)] - sum[i] // nums[i+1:]的和 ...
package logging import ( "context" "runtime/debug" "cloud.google.com/go/logging" "github.com/spf13/viper" ) const ( LogConsumers = "gamedb.consumers" LogGameDB = "gamedb" ) var ( ctx = context.Background() client *logging.Client ) // Called from main func Init() { var err error client, err = loggin...
package http import ( "net/http" "github.com/gorilla/mux" "github.com/upframe/api" ) // Serve ... func Serve(c *api.Config) { r := mux.NewRouter() r.NotFoundHandler = &notFoundHandler{Config: c} r.HandleFunc("/tokens/validate", s(placebo, c)).Methods("POST") r.HandleFunc("/tokens/get", i(tokensGet, c)).Meth...
package internal import "github.com/m3hm3t/customerapi3/internal/model" type Service interface { GetByID(uint) (*model.Customer, error) GetByEmail(string) (*model.Customer, error) GetByUsername(string) (*model.Customer, error) Create(*model.Customer) error Update(*model.Customer) error Delete(*model.Customer) e...
package leetcode import "testing" func TestMaxArea(t *testing.T) { tests := []struct { height []int max int }{ { height: []int{1, 8, 6, 2, 5, 4, 8, 3, 7}, max: 49, }, } for i, tt := range tests { if got, want := maxArea(tt.height), tt.max; got != want { t.Errorf("%d: maxArea: got %v, want...
package wxclient //var ( // addNewsUrl = "https://api.weixin.qq.com/cgi-bin/material/add_news" // addPictureUrl = "https://api.weixin.qq.com/cgi-bin/material/add_material" //) // //func doPost(accessToken string, newBytes []byte) (*msgtypetype.ArticlesResp, error) { // postReq, err := http.NewRequest("POST", string...
// Copyright 2017 European Digital Reading Lab. All rights reserved. // Licensed to the Readium Foundation under one or more contributor license agreements. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file exposed on Github (readium) in the project repository. pack...
package main import ( "fmt" ) func main() { x := 11 //incValor(x) incValorPonteiro(&x) fmt.Println(x) } func incValor(x int) { x++ fmt.Println("Na função:", x) } func incValorPonteiro(x *int) { *x++ fmt.Println("Na função:", *x) }
package user import ( "encoding/json" "fmt" "neosmemo/backend/handler" "neosmemo/backend/helper" "neosmemo/backend/model" "neosmemo/backend/util" "net/http" "time" "github.com/julienschmidt/httprouter" ) // GetAllUser just for test func GetAllUser(w http.ResponseWriter, _ *http.Request, _ httprouter.Params)...
/* Package session implements a simple session handler for use with the Go http package. */ package session import ( "crypto/rand" "errors" "fmt" "io" "net/http" "sync" "time" ) /* SessionStorage interface is used and required by SessionManager. Sessions passed as parameters can be used concurrently. All meth...
package main import ( "fmt" "log" "time" "github.com/tanema/gween" "github.com/tanema/gween/ease" ) type Event struct { Text string Time string Multiplier int Y float32 Tween *gween.Sequence } func (event *Event) Done() bool { _, _, done := event.Tween.Update(0) return done } ...
package contracts import ( "context" "payment/internal/dto" "payment/internal/models" ) //IPaymentService ... type IPaymentService interface { FindAccaunt(ctx, id int) error CreateAccount(ctx context.Context, account dto.Account) (models.AccountAttributes, error) UpdateAccountAmount(ctx context.Context, accoun...
package ksqlparser import ( "fmt" "strings" ) type streamSelect struct { Expressions aliasedExpressions Identifier identifier Joins *[]joinExpression Where *[]*Condition Partition string } func (s *streamSelect) String() string { var sb []string sb = append(sb, s.Expressions.String()) sb = a...
package core import ( "fmt" "github.com/iotaledger/wasp/packages/coretypes" "github.com/iotaledger/wasp/packages/hashing" "github.com/iotaledger/wasp/packages/vm/core/accounts" "github.com/iotaledger/wasp/packages/vm/core/blob" "github.com/iotaledger/wasp/packages/vm/core/eventlog" "github.com/iotaledger/wasp/p...
// Copyright 2016 The Hugo Authors. 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 ...
package huffman_tree import ( "fmt" "strings" ) // 给定 n 个权值作为 n 个叶子节点, 构造一棵二叉树, 若该数的带权路径长度达到最小, // 则称这样的树为 Huffman Tree, 权值越大离根节点越近 // A // /\ // / \ // / \ // B C(10) // /\ // / \ // / \ // D(13) E(15) // 节点D的带权路径长度为 根到该节点的路径长度(2) * 节点的权(13) ...
package resolver import ( "github.com/dalloriam/websynth/app/audio" "github.com/dalloriam/synthia/core" ) type ChannelResolver struct { sys *audio.System channel *core.MixerChannel } func (r *ChannelResolver) Volume() *KnobResolver { return &KnobResolver{r.sys, r.channel.Volume} } func (r *ChannelResolver...
package math // Vector2 type type Vector2 struct { X float64 Y float64 }
package util import ( "sync" "time" "github.com/OopsMouse/arbitgo/models" ) type DepthCache struct { cache map[string]*models.Depth lock *sync.Mutex expireTime time.Duration } func NewDepthCache() *DepthCache { d := &DepthCache{ cache: map[string]*models.Depth{}, lock: new(sync.Mute...
/* * Minio Client (C) 2015 Minio, 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 agr...
package main import ( "bufio" "bytes" "context" "flag" "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "time" "github.com/google/uuid" "github.com/sdeoras/token/proto" "github.com/sirupsen/logrus" "google.golang.org/grpc" ) var key string func main() { t := time.Now() var b bytes.Buffer ...
package main import ( "fmt" "encoding/csv" "net/http" "io" "os" "math/rand" "time" ) func main() { http.HandleFunc("/", handler) http.HandleFunc("/elasticSearch", handler1) http.ListenAndServe(":8081", nil) } func handler(w http.ResponseWriter, r *http.Request){ fmt...
package controllers import ( "SocialWebsite/config" "SocialWebsite/models" "encoding/json" "gopkg.in/confluentinc/confluent-kafka-go.v1/kafka" "log" ) //Sends user and page visited to Kafka Topic func ProduceUserPageRequest(usernameToSend string, pageToSend string) { // Delivery report handler for produced mes...
package subscribe import ( "context" "sync/atomic" "time" "github.com/spf13/cobra" "github.com/tsaikd/KDGoLib/cliutil/cobrather" "github.com/tsaikd/go-grpc-echo/client" "github.com/tsaikd/go-grpc-echo/logger" "golang.org/x/sync/errgroup" ) var flagURL = &cobrather.StringFlag{ Name: "subscribe.url", Defa...
package tasks import ( "encoding/json" "fmt" "io" "log" "os" "sort" "strconv" "text/tabwriter" ) // TaskMaster handles adding and removing tasks to a master "list". type TaskMaster struct { Tasks []Task sortationMode string } // Sortation functions. func (s *TaskMaster) Len() ...
package rpc type LanguageChanged struct { LanguageID string `json:"language_id"` ViewID string `json:"view_id"` }
package filepath import ( "regexp" "strings" ) var windowsAbs = regexp.MustCompile(`^[a-zA-Z]:\\.*$`) // Abs is a version of path/filepath's Abs with an explicit operating // system and current working directory. func Abs(os, path, cwd string) (_ string, err error) { if IsAbs(os, path) { return Clean(os, path),...
package brain import ( "encoding/json" "fmt" "io/ioutil" "math" "os" "path/filepath" ) var VERSION = "v0.0.3" type BayesBrain struct { FeaturesFrequency map[string]float64 CategoriesFrequency map[string]float64 FeaturesFrequencyInEachCategory map[string]map[string]float64 Categori...
// slices package main import "fmt" func main() { // declarar slices de enteros vacío var numeros []int // crear un loop que mea 10 valores al slice creado for i:= 0; i < 10; i++ { numeros = append(numeros, i*10) } // iterar sobte el slices y mostrar cada valor for _, numero := range numeros { fmt.Print...
package rest import "net/http" // APIClient is our custom client type APIClient struct { *http.Client } // NewAPIClient constructor initializes the client with our // custom Transport func NewAPIClient(username, password string) *APIClient { t := http.Transport{} return &APIClient{ Client: &http.Client{ Tran...
package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" ) func main() { // クライアントが持っているapiKeyと仮定 const apiKey = "Test1Key" const apiSecret = "Test1Secret" // hmac.New関数で第一引数にアルゴリズム、第二引数に暗号化する対象を指定しbyteにしてhashを作る h := hmac.New(sha256.New, []byte(apiKey)) // byteの配列でhashを表示する fmt.Println(h)...
package main import ( "fmt" "sort" ) // https://leetcode-cn.com/problems/meeting-rooms-ii/ //------------------------------------------------------------------------------ func minMeetingRooms(data [][]int) int { n := len(data) if n < 2 { return n } sort.Sort(intervals(data)) var seg [][]int for i := 0; ...
package models import ( "lec13/config" _ "github.com/lib/pq" //engine ) //GetAllUsers ... func GetAllUsers(users *[]User) error { if err := config.DB.Find(users).Error; err != nil { return err } return nil } //CreateUser ... func CreateUser(user *User) error { if err := config.DB.Create(user).Error; err != ...
package main import "fmt" func modify(map1 map[int]int) { map1[10] = 900 } //定义一个学生的结构体 type Stu struct { Name string Age int Address string } func main() { map1 := make(map[int]int) map1[1] = 90 map1[2] = 88 map1[10] = 1 map1[20] = 2 modify(map1) fmt.Println(map1) students := make(map[string]Stu) stu...
package main import ( "fmt" "sort" "strconv" ) func main() { fmt.Println("vim-go") var nums []int var target int var output [][]int nums = []int{1, 0, -1, 0, -2, 2} target = 0 output = fourSum(nums, target) fmt.Println(output) } func fourSum(nums []int, target int) [][]int { sort.Ints(nums) return nS...
package scheduler import ( "context" "sync/atomic" ) type orderBookOrder struct { total int fulfilled int book *orderBook } func (o *orderBookOrder) Total() int { return o.total } func (o *orderBookOrder) Remaining() int { return o.total - o.fulfilled } func (o *orderBookOrder) Fulfilled() int { r...
package config func (c *config) getCmd() []string { shell := "cmd" args := []string{shell} if c.Cmd == "" { return args } return append(args, "/c", c.Cmd) }
package ttlib import ( "encoding/binary" "fmt" "io" ) // readBytes reads a uint16 number of bytes to read from the reader, // then reads that number of bytes into a buffer to return. If the // number of bytes is greater than `limit`, an error is returned. func readBytes(conn io.Reader, limit uint16) ([]byte, erro...
// Package color represents simple 3 byte color type package color import "fmt" type ColorByte byte type Color struct { Red ColorByte Green ColorByte Blue ColorByte } func (b ColorByte) Scale(x float64) ColorByte { y := float64(b) * x if y > 255 { return ColorByte(255) } else if y < 0 { return ColorByt...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //404. Sum of Left Leaves //Find the sum of all left leaves in a given binary tree. //Example: // 3 // / \ // 9 20 // / \ // 15 7 //Ther...
package main import ( "fmt" "log" ) func orders() { log.Println("================= ORDER =================") if err := checkEnv(); err != nil { fmt.Println(err) return } orders, err := c.ListOrders(10, 0) // order, err := c.ViewOrder("3863157") if err != nil { log.Println(err) return } for _, orde...
package test import ( "testing" "go.uber.org/zap" zapobserver "go.uber.org/zap/zaptest/observer" ) func TestS_FooBar(t *testing.T) { core, obs := zapobserver.New(zap.InfoLevel) // // core, obs := zapobserver.New(zap.FatalLevel) // the test will be failed logger := zap.New(core) s := S{ logger: logger, } ...
package user import ( "strings" "oauth-server-lite/g" "oauth-server-lite/models/ldap" "oauth-server-lite/models/oauth" ) func LdapLogin(username, password string) (err error) { lc := ldap.LDAP_CONFIG{ Addr: g.Config().LDAP.Addr, BaseDn: g.Config().LDAP.BaseDn, BindDn: g.Config().LDAP.BindDn,...
package main import ( "bytes" "database/sql" "flag" "fmt" "io" "log" "os" "os/signal" "regexp" "runtime" "strings" "sync" "time" "github.com/beefsack/mysql-glb/mygl" _ "github.com/go-sql-driver/mysql" ) const flagPassDefault = "((read from STDIN))" var roRegexp = regexp.MustCompile(`(?i)^\s*select`) ...
type MinStack struct { s []int } /** initialize your data structure here. */ func Constructor() MinStack { return MinStack{[]int{}} } func (this *MinStack) Push(x int) { this.s = append(this.s, x) } func (this *MinStack) Pop() { this.s = this.s[0:len(this.s)-1] } func (this *MinStack) ...
package host import ( "fmt" "reflect" "strings" "testing" "time" "gitlab.com/NebulousLabs/Sia/build" "gitlab.com/NebulousLabs/Sia/crypto" "gitlab.com/NebulousLabs/Sia/modules" "gitlab.com/NebulousLabs/Sia/types" "gitlab.com/NebulousLabs/fastrand" ) // TestRPCSubscribe is a set of tests related to the regis...
package input import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGibberishInputConfigValidation(t *testing.T) { // First element is a config, second element is a string expected in the // config error. for _, test := range [][2]string{ {`length...
package cmd import ( "copyto/logic" "github.com/spf13/afero" "github.com/spf13/cobra" "os" ) var verbose bool var appFileSystem afero.Fs var appPrinter logic.Printer // newRoot represents the root command func newRoot() *cobra.Command { return &cobra.Command{ Use: "copyto", Short: "copyto is a small one ...
package color type ColorRGB struct { Red float32 Green float32 Blue float32 } func New(red float32, green float32, blue float32) ColorRGB { return ColorRGB{Red: red, Green: green, Blue: blue} } func (self ColorRGB) Add(other ColorRGB) ColorRGB { return ColorRGB{ Red: self.Red + other.Red, Green: self.G...
package main import ( "database/sql" "github.com/gin-gonic/gin" _ "github.com/go-sql-driver/mysql" "gopkg.in/gorp.v1" "log" "strconv" ) type User struct { Id int64 `db:"id" json:"id"` Email string `db:"email" json:"email"` Password string `db:"password" json:"password"` Name ...
// Copyright 2016 Kranz. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package setting import ( "net/url" "os" "os/exec" "path" "path/filepath" "runtime" "strings" "github.com/Unknwon/com" "gopkg.in/ini.v1" "github.com/rodkranz/...
package main import "fmt" /** * created: 2019/7/30 13:17 * By Will Fan */ func main() { chanOwner := func() <-chan int{ result := make(chan int, 5) go func() { defer close(result) for i := 0; i<=5; i++ { result <- i } }() return result } consumer := func(result <-chan int) { for res :=...
package webhookserver import ( "os" "github.com/open-policy-agent/cert-controller/pkg/rotator" "go.uber.org/zap" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller...
package storages import "sync" const ShardCount = 32 type ConcurrentMap []*ConcurrentMapShared type ConcurrentMapShared struct { items map[string]interface{} sync.RWMutex } func NewConcurrentMap() ConcurrentMap { m := make(ConcurrentMap, ShardCount) for i := 0; i < ShardCount; i++ { m[i] = &ConcurrentMapShare...
package polling import ( "sync" "time" ) // PollerFunc is a function to be polled type PollerFunc func() interface{} // Poller represents everything needed for polling a function type Poller struct { Channel chan interface{} Poll PollerFunc WaitInterval time.Duration isStopped bool isFinished ...
package raft import ( "fmt" "strconv" //"sync" "bytes" "encoding/binary" "encoding/gob" "errors" "github.com/syndtr/goleveldb/leveldb" ) // create new log object which will stay with server for life func createNewLog(dbPath string) *Log { db, err := leveldb.OpenFile(dbPath, nil) if err != nil { panic(fmt....
// Copyright 2022 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 2015 The quotesrv 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 main import ( "flag" "io" "io/ioutil" "log" "net/http" "os" "regexp" "sync" "github.com/jroimartin/orujo" "github.com/jroimartin/orujo...
package main import ( "flag" "fmt" "log" "os" "os/exec" "os/signal" "strings" "time" "unicode" "github.com/radovskyb/watcher" ) func main() { interval := flag.String("interval", "100ms", "watcher poll interval") recursive := flag.Bool("recursive", true, "watch folders recursively") dotfiles := flag.Bool...