text
stringlengths
11
4.05M
package main import ( "fmt" "os" "github.com/Konboi/ghooks" "github.com/Sirupsen/logrus" _ "github.com/joho/godotenv/autoload" "gopkg.in/alecthomas/kingpin.v2" ) type cmd struct { command string payload string } var ( defaultPort = 18889 defaultHost = "127.0.0.1" file = kingpin.Flag("config", "...
package netutil import ( "bytes" "fmt" "io" "net" "testing" "time" ) func TestHalfCloser(t *testing.T) { t.Parallel() l, err := net.Listen("tcp", "localhost:15346") if err != nil { t.Skip(err) } errCh := make(chan error, 1) done := make(chan struct{}) go func() { defer close(done) c, err := l.Ac...
package metrics import ( "net/url" "github.com/cerana/cerana/acomm" "github.com/cerana/cerana/pkg/errors" "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/load" ) // CPUResult is the result of the CPU handler. type CPUResult struct { Info []cpu.InfoStat `json:"info"` Load load.AvgStat `json:...
// Copyright 2015 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, ...
/*** Copyright 2017 Cisco Systems Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
// search package results type SearchReply struct { Code int `xml:"ReplyCode,attr"` Text string `xml:"ReplyText,attr"` MaxRows string `xml:"MAXROWS"` // make this an int Delimiter Delimiter `xml:"DELIMITER"` Columns string `xml:"COLUMNS"` Data []string `xml:"DATA"` } type Deli...
package lib import ( "github.com/dhaifley/dlib" "github.com/dhaifley/dlib/dauth" ) // PermAccess values are used to access perm records in the database. type PermAccess struct { DBS dlib.SQLExecutor } // PermAccessor is an interface describing values capable of providing // access to perm records in the database....
package requests type AddGuestRequest struct { TableId int64 `json:"table"` AccompanyingGuests int64 `json:"accompanying_guests"` }
package main import ( "bytes" "io" "testing" ) func Test_response(t *testing.T) { type args struct { input io.Reader } tests := []struct { name string args args want int64 }{ {"test1", args{bytes.NewBufferString("12.00\n20\n8")}, 15}, {"test2", args{bytes.NewBufferString("15.50\n15\n10")}, 19}, {...
package main import "fmt" func main() { nums := []int{1, 3, 4, 5, 6, 7, 8, 9, 12, 23, 34, 45, 56, 67, 78, 89, 90} fmt.Println(len(nums)) i, m := (len(nums)+1)>>1, len(nums)>>1 k := 90 count := 0 for m != 0 { if k < nums[i] { i = i - (m+1)>>1 m = m >> 1 } else if k > nums[i] { i = i + (m+1)>>1 m ...
package gw import ( "github.com/gin-gonic/gin" ) // Hook represents a global gin engine http Middleware. type Hook struct { Name string OnBefore gin.HandlerFunc OnAfter gin.HandlerFunc } func NewBeforeHook(name string, before gin.HandlerFunc) *Hook { return NewHook(name, before, nil) } func NewAfterHook(n...
package main import ( "bufio" // "golang.org/x/image/bmp" "image/jpeg" "image/png" "log" "os" ) func main() { // fi, err := os.Open("test.bmp") fi, err := os.Open("test.jpg") defer fi.Close() if err != nil { panic(err) } r := bufio.NewReader(fi) // image, err := bmp.Decode(r) image, err := jpeg.Decode...
// Copyright (c) 2018-present, MultiVAC Foundation. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. package db import ( "os" "path/filepath" "github.com/multivactech/MultiVAC/configs/params" "github.com/syndtr/goleveldb/leveldb" "gith...
// +build !prod package mysql func GetTestConfig() Config { return Config{ DSNUser: `root`, // github actions use root user with a root password DSNPassword: `githubactionpassword`, // defined as envvar in the go_tests.yaml DSNHost: `localhost`, DSNPort: 3306, Databa...
// This program implements a web service which provides a browser user // interface so that the user can design sudoku puzzles where the digits // have been replaced by emoji symbols to produce a puzzle that can also // artistically convey a symbolic message. package main import "encoding/json" import "flag" import "f...
package logger import ( "encoding/json" "fmt" "log" "time" ) func Info(message string) { fmt.Printf("[Info] %s: %s\n", timeFormat(), message) } func InfoJson(message string) { type LogEntry struct { Level string Time string Message string } logEntry := LogEntry{"Info", timeF...
// // Copyright (c) SAS Institute 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 agre...
/* 获取市场概要 api文档: https://huobiapi.github.io/docs/spot/v1/cn/#7c47ef3411 */ package huobipro import ( "encoding/json" "fmt" "strings" ) /* 字段 数据类型 描述 id integer unix时间,同时作为消息ID amount float 24小时成交量 count integer 24小时成交笔数 open float 24小时开盘价 close float 最新价 low float 24小时最低价 high float 24小时最高价 vol float 24小时成交额 *...
// Copyright 2015 go-smpp 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 pdufield import ( "bytes" "strconv" "testing" ) func TestFixed(t *testing.T) { f := &Fixed{Data: 0x34} if f.Len() != 1 { t.Fatalf("unexpected ...
// Copyright (c) 2013 The go-github AUTHORS. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list...
package repositories import ( "io/ioutil" "net/http" "strings" ) type ResponseRepository interface { Get(string) ([]byte, error) } type httpResponseRepository struct { } func (r httpResponseRepository) Get(url string) ([]byte, error) { if !strings.HasPrefix(url, "http") { url = "http://" + url } response,...
// Copyright © 2019 morgulbrut // This work is free. You can redistribute it and/or modify it under the // terms of the Do What The Fuck You Want To Public License, Version 2, // as published by Sam Hocevar. See the LICENSE file for more details. package main import "github.com/morgulbrut/findChips/cmd" func main() ...
package util const ( SuccessCode = 0 ErrorLackCode = 1 ErrorSqlCode = 2 ErrorRidesCode = 3 //参数签名秘钥 DesKey = "r5k1*8a$@8dc!dytkcs2dqz!" //redis key RedisKeyRegisteredCode = "user:registered:code:" //注册验证码 RedisKeyRegisteredCodeNumber = "user:registered:code:number:" //注册验证码次数 RedisKeyFor...
package v1beta1 import ( . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" "k8s.io/apimachinery/pkg/util/validation/field" ) var _ = Describe("Validation Webhook", func() { invalidEntries := []TableEntry{ Entry("Duplicate versions", ClusterWorkloadResourceMapp...
package main import ( "net/http" "github.com/gin-gonic/gin" ) //gin.Context封装了request和response func hello(c *gin.Context) { //返回一个json格式 c.JSON(200, gin.H{ "message": "hello world!", }) //返回string类型 c.String(http.StatusOK, "hello world") } func main() { //创建一个默认路由,同时当中包含Logger和Recovery2个中间件 r := gin.De...
package taskfile import ( "fmt" "path/filepath" "github.com/go-task/task/v3/internal/execext" "github.com/go-task/task/v3/internal/filepathext" "golang.org/x/exp/slices" "gopkg.in/yaml.v3" ) // IncludedTaskfile represents information about included taskfiles type IncludedTaskfile struct { Taskfile stri...
package model import ( ) type CmsSubjectCategory struct { AppId string `json:"appId" gorm:"type:bigint unsigned;"` // Icon string `json:"icon" gorm:"type:varchar(500);"` // 分类图标 Id int `json:"id" gorm:"type:bigint;primary_key"` // Name string `json:"name" gorm:"type:varchar(100);"...
package handler import ( "encoding/json" "net/http" "strings" "github.com/dtan44/SMUG/service" ) // Global variables var jsonMarshal func(v interface{}) ([]byte, error) const ( registerPath = "/register/" deregisterPath = "/deregister/" ) func init() { jsonMarshal = json.Marshal } //Result JSON response ...
package model // Task - service layer task model type Task struct { ID int64 Status Status Description string Assigned []int64 } func (t *Task) String() string { return t.Description }
/* * Quay Frontend * * This API allows you to perform many of the operations required to work with Quay repositories, users, and organizations. You can find out more at <a href=\"https://quay.io\">Quay</a>. * * API version: v1 * Contact: support@quay.io * Generated by: Swagger Codegen (https://github.com/swagger...
package main import ( "code.google.com/p/go.net/websocket" "encoding/json" "flag" "fmt" "github.com/fmstephe/location_server/locserver" "github.com/fmstephe/location_server/logutil" "github.com/fmstephe/location_server/msgserver" "github.com/fmstephe/location_server/msgutil/msgdef" "github.com/fmstephe/simple...
package layout type TextWidget struct { BaseWidget Value string `json:"value"` Placeholder string `json:"placeholder"` Prefix string `json:"prefix"` Suffix string `json:"suffix"` NoRepeat bool `json:"no_repeat"` Format string `json:"format"` Linkage Linkage `json:"linkage"` ...
package common const ( ALI_ACCESS_KEY_ID = "LTAIvUAUos5XypQv" ALI_ACCESS_KEY_SECRET = "t4cjImTY1fngRKYyiV2WYVrfIhGPsb" )
package plugins import ( "fmt" "github.com/petomalina/mirror/pkg/cp" "golang.org/x/tools/go/packages" "io/ioutil" "math/rand" "os" "os/exec" "path/filepath" "plugin" "reflect" "regexp" "unsafe" . "github.com/petomalina/mirror/pkg/logger" ) var ( pkgRegex = regexp.MustCompile(`(?m:^package (?P<pkg>\w+$)...
package main import ( "bufio" "flag" "fmt" "io/ioutil" "log" "math/rand" "os" "path/filepath" "strings" "time" ) // flags var cpm bool // toggle CPM or WPM var list string // input sentence list to be used var rounds int // how many sentences to be tested on func main() { rand.Seed(time.Now().UTC().Un...
package main import ( "log" "net/http" controller "./controller" "./database" "github.com/gorilla/mux" ) func check(e error) { if e != nil { panic(e) } } func main() { database.InitDB() Router := mux.NewRouter().StrictSlash(true) Router.HandleFunc("/api/messages", controller.HandleGetMessages) Router....
// Copyright 2021 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 mocking import "time" type implementation struct { store Store } func NewImplementation(store Store) *implementation { return &implementation{store: store} } func (i *implementation) MethodA(at time.Time) error { err := i.store.Open(at) if err != nil { return err } err = i.store.Sell("a", 2) if er...
package converters import ( "encoding/json" "fmt" "math/big" "reflect" "github.com/kaspanet/kaspad/domain/consensus/model" "github.com/kaspanet/kaspad/domain/consensus/utils/hashes" "github.com/kaspanet/kaspad/domain/consensus/model/externalapi" ) func jsonMarshal(output interface{}) (string, error) { byte...
package ops import ( "crypto/sha1" "os" ) func FileExists(filename string) bool { if _, err := os.Stat(filename); os.IsNotExist(err) { return false } return true } func GetSHA1(data []byte) []byte { val := make([]byte, 0, 20) sha := sha1.Sum(data) val = append(val, sha[:]...) return val } func FilterUniq...
/* * Npcf_SMPolicyControl API * * Session Management Policy Control Service © 2019, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * API version: 1.0.4 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package openapi // SessionRuleFailureCod...
package controllers import ( "net/http" . "wukongServer/models" ) type PageController struct { BaseController } func (c *PageController) Search() { kw := c.GetString(`kw`) s := wk.SearchText(kw) c.View(`page/search.html`, map[string]interface{}{ `searchRequest`: map[string]interface{}{ `kw`: kw, }, ...
package lidar import ( "bytes" "encoding/binary" "errors" "fmt" "io" "math" "reflect" "strings" ) type LasHeader struct { FileSignature string //[4]byte FileSourceID uint16 GlobalEncoding uint16 ProjectID1 uint32 ProjectID2 uint16 ProjectID3 uint16 Pro...
package common //space O(1) func RotateSlcesInt(nums []int,k int){ n := len(nums) //数组长度 k %= n //如果k>n的情况,则取k/n的余数 } func reverse(nums []int,start,end int){ for start < end { nums[start], nums[end] = nums[end], nums[start] start++ end-- } }
package ravendb // TcpConnectionInfo describes tpc connection type TcpConnectionInfo struct { Port int `json:"Port"` URL string `json:"Url"` Certificate *string `json:"Certificate"` }
package main import ( "fmt" "flag" ) func main() { var filename string flag.StringVar(&filename, "filename", "default.txt", "default txt file") flag.Parse() fmt.Println("This is a Jenkins Demo") greetEmpty := greet("") fmt.Println(greetEmpty) greetNotEmpty := greet("World") fmt.Println(greetNotEmpty) se...
package migrate import ( "bytes" "encoding/json" "fmt" "github.com/boltdb/bolt" "github.com/mpdroog/invoiced/invoice" "log" "strconv" ) const LATEST = 1 func conv0(tx *bolt.Tx) error { b := tx.Bucket([]byte("invoices")) tmp, e := tx.CreateBucketIfNotExists([]byte("invoices-tmp")) if e != nil { return e ...
package dns import ( "designPattern/ABE_oberver_responsibilitychain/b_observer_dns/observer" "math/rand" "time" "fmt" "strings" ) type IServer interface { observer.Observer IsLocal(recorder *Recorder) bool SetUpperServer(server IServer) ResponsFromUpperServer(recorder *Recorder) Sign(recorder *Recorder) } ...
package solutions import ( "container/heap" ) type Twitter struct { userList map[int]User timestamp int } type User struct { userId int follow map[int]struct{} fans map[int]struct{} news *MaxHeap posts *[]Tweet } type MaxHeap []Tweet type Tweet struct { userId int tweetI...
package model import ( "errors" "fmt" "go_api_base/db" . "go_api_base/log" "time" "strings" "strconv" "agent_keeper/package/pagination" "net/http" "encoding/json" ) var ( mysqlconn *db.DBMYSQL agentInsertSQL = `insert into agent_record(r_id,r_name,r_client,r_rule,r_where,r_callwhere,r_schedule,r_callbac...
package binarytree type Node struct { Left *Node Right *Node Value int } func (node *Node) Insert(value int) { if value > node.Value { if node.Right == nil { node.Right = &Node{ Value: value, } } else { node.Right.Insert(value) } } else if value < node.Value { if node.Left == nil { node.L...
package service import ( "github.com/smartystreets/goconvey/convey" "testing" ) func TestService_GetId(t *testing.T) { convey.Convey("TestService_GetId", t, func(c convey.C) { res, err := s.GetId("test") convey.So(err, convey.ShouldBeNil) t.Logf("res %v", res) }) } func BenchmarkService_GetId(b *testing.B)...
package factory_test import ( "github.com/RackHD/ipam/resources" . "github.com/RackHD/ipam/resources/factory" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Factory", func() { Describe("Request", func() { It("should return the requested resource", func() { resource, err := Reques...
package userbook // If the main resource has a subresource, the naming convention is // <resource><subresource>
package basefile import ( "reflect" "strings" ) //判断元素是否在string array sli map中 func IsExistIn(arr, e interface{}) bool { val := reflect.ValueOf(arr) switch val.Kind() { case reflect.String: if reflect.TypeOf(e).Kind() == reflect.String { return strings.Contains(arr.(string), e.(string)) } case reflect.Ar...
package repository import ( "github.com/kosegor/go-covid19-api/app/domain/model" "github.com/kosegor/go-covid19-api/app/interface/apierr" ) type ElasticRepository interface { Insert(*model.Incident) (*model.Incident, *apierr.ApiError) //FindByCountry(string) ([]*model.Incident, *apierr.ApiError) }
// Copyright © 2018 Wei Shen <shenwei356@gmail.com> // // 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 limitation the rights // to use, copy, modify,...
package main import "fmt" func main() { fmt.Println(factorial(4)) } func factorial(num int) int { sum := num count := num - 1 for i := 0; i < num; i++ { if count != 0 { sum *= count count-- } } return sum } //challenge from Todd to do a factorial without using recursion and using loops.
package nopaste import "testing" func TestGetRegionFromARN(t *testing.T) { arn1 := "arn:aws:sns:us-east-1:999999999:example" r1, _ := getRegionFromARN(arn1) if r1 != "us-east-1" { t.Errorf("invalid region %s from %s", r1, arn1) } arn2 := "arn:aws:sns" r2, err := getRegionFromARN(arn2) if r2 != "" || err == ...
package decode_string type pair struct { text string num int } func decodeString(s string) string { // 3[a2[c]] // stack // top -> nil // detect number: 3 // detect '[', push: 3 and "" // top -> 3 -> "" // detect text: a // detect number: 2 // detect '[', push: 2 and "a" // top -> 2 -> a -> 3 -> "" // d...
package impl_test import ( "context" "testing" "time" "github.com/mylxsw/adanos-alert/internal/repository" "github.com/mylxsw/adanos-alert/internal/repository/impl" "github.com/stretchr/testify/suite" "go.mongodb.org/mongo-driver/bson" ) type QueueTestSuit struct { suite.Suite repo repository.QueueRepo } f...
/* Copyright 2021 The Skaffold 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, sof...
package main import "sort" //524. 通过删除字母匹配到字典里最长单词 //给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。 // //如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。 // // // //示例 1: // //输入:s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] //输出:"apple" //示例 2: // //输入:s = "abpcplea", dictionary = ...
// 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...
package usecase import ( "marketplace/ads/domain" "github.com/go-pg/pg/v10" ) type ListUserAdsCmd func (db *pg.DB, userId int64) ([]domain.Ads, error) func ListUserAds() ListUserAdsCmd { return func (db *pg.DB, userId int64) ([]domain.Ads, error) { var adsArray []domain.Ads err := db.Model(&adsArray). Wh...
package main import ( "flag" "log" "time" "github.com/jroimartin/gocui" "github.com/serialx/goclair" ) func main() { var bucket, key string var timeout time.Duration flag.StringVar(&bucket, "b", "", "Bucket name.") flag.StringVar(&key, "k", "", "Object key name.") flag.DurationVar(&timeout, "d", 0, "Uploa...
package cmd import ( "fmt" "github.com/object88/isomorphicTest/client" "github.com/spf13/cobra" ) func createGenerateCommand() *cobra.Command { cmd := &cobra.Command{ Use: "generate", Short: "generate will create a new UUID", RunE: run, } return cmd } func run(_ *cobra.Command, _ []string) error { ...
// +build windows package launcher func runReaper() {}
package store import ( "strconv" model "github.com/wlanboy/kanbantabs/v2/model" ) /*AddBoard to Workplace*/ func (storage *Storage) AddBoard(board model.Board) { storage.Workplace.Lanes = append(storage.Workplace.Lanes, board) storage.Save() } /*DeleteBoard to Workplace*/ func (storage *Storage) DeleteBoard(boa...
// 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-present Datadog, Inc. package utils import ( "reflect" "testing" "github.com/DataDog/datad...
// The Manager reacts to messages send to it by Notifiers. It calls all ServiceGenerators to generate new Services // and passes these to ConfigGenerators which generate configuration files. package manager import ( "github.com/bmizerany/pat" "github.com/kelseyhightower/envconfig" "github.com/prometheus/client_gola...
package api /* the place to set constants */ const DATASTORE_USERS = "Users" const DATASTORE_TEAMS = "Teams"
/* * Swagger Kubechat * * Wrapper API of kubectl CLI command * * API version: 0.1.0 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package main import ( "log" // WARNING! // Change this to a fully-qualified import path // once you place this file into your project. // For example, ...
package tbot import ( "context" "time" "go.mongodb.org/mongo-driver/mongo" ) const article = "article" // Article is parsed article type Article struct { ID string `json:"id" bson:"_id"` Title string `json:"title" bson:"title"` Link string `json:"link" bson:"link"` Description ...
package modules import ( "encoding/json" "gopkg.in/telegram-bot-api.v4" "io/ioutil" "log" "net/http" ) type Response struct { Kind string `json: "kind"` Data map[string]interface{} `json: "data"` } func Reddit_updates(bot *tgbotapi.BotAPI,update * tgbotapi.Update){ queryId := update.CallbackQuery.ID ...
package repositories import ( "context" "headless-todo-tasks-service/internal/entities" ) type TasksRepository interface { Create(context.Context, string, string, string) (*entities.Task, error) }
package main import "fmt" type twoInts struct { X, Y int64 } func (a twoInts) method(b twoInts) twoInts { // a is a receiver return twoInts{X: a.X + b.X, Y: a.Y + b.Y} } func main() { two := twoInts{10, 0} fmt.Println(two) }
package user type User struct { Username string `json:"username"` Password string `json:"password"` Email string `json:"email"` Company Company `json:"company"` } type Company struct { Name string `json:"name"` Phone string `json:"phone"` Address string `json:"address"` }
package cache import ( "sync" "github.com/apache/servicecomb-kie/pkg/model" "github.com/go-chassis/cari/pkg/errsvc" ) var pollingCache = &LongPollingCache{} // LongPollingCache exchange space for time type LongPollingCache struct { m sync.Map } type DBResult struct { KVs *model.KVResponse Err *errsvc.Error R...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package dutcontrol is generated from dutcontrol.proto in the ti50 repository. package dutcontrol
package health import ( "bytes" "net/http" "net/url" "github.com/cerana/cerana/acomm" "github.com/cerana/cerana/pkg/errors" "github.com/cerana/cerana/pkg/logrusx" ) // HTTPStatusArgs are arguments for HTTPStatus health checks. type HTTPStatusArgs struct { URL string `json:"url"` Method string `jso...
package api_test // STARTMOCK, OMIT import ( "fmt" "testing" "github.com/imrenagi/gotalks/content/2021/testing/api" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" // HL ) type PaymentServiceMock struct { mock.Mock // HL } func (m *PaymentServiceMock) GenerateInvoice(ID string) (string...
package server import ( "github.com/zerolinke/pudge/src/pudge/log" "encoding/gob" "sync" "github.com/zerolinke/pudge/src/pudge/cache" "time" ) type cacheUrl string type TunnelRegistry struct { tunnels map[string]*Tunnel affinity *cache.LRUCache log.Logger sync.RWMutex } func NewTunnelRegistry(cacheSize ui...
package main import "fmt" // Hands-on exercise #3 // Create TYPED and UNTYPED constants. Print the values of the constants. const ( x int = 33 y = "I am a string" ) func main() { fmt.Println(x, y) }
package grpool import ( "sync" ) type Pool struct { JobQueue chan Job dispatcher *dispatcher wg sync.WaitGroup } func NewPool(numWorkers int, jobQueueLen int) *Pool { jobQueue := make(chan Job, jobQueueLen) workerPool := make(chan *worker, numWorkers) pool := &Pool{ JobQueue: jobQueue, dispat...
package metrics type AgentMetrics struct { MachineMemoryUsage int64 MachineMemoryPercentage float64 MachineCPULoad float64 ProcessResourceUsages []*ProcessResourceUsage } type ProcessResourceUsage struct { Name string CPUPercentage float64 MemoryRSS int64 }
package udwSqlite3 import ( "bytes" "github.com/tachyon-protocol/udw/udwMap" "github.com/tachyon-protocol/udw/udwStrconv" "github.com/tachyon-protocol/udw/udwStrings" "strconv" ) type GetRangeReq struct { K1 string IsDescOrder bool MinValue string MaxValue string M...
/* SPDX-License-Identifier: MIT * * Copyright (C) 2019-2020 WireGuard LLC. All Rights Reserved. */ package version import ( "os" "unsafe" "golang.org/x/sys/windows" "golang.zx2c4.com/wireguard/windows/version/wintrust" ) const ( officialCommonName = "WireGuard LLC" evPolicyOid = "2.23.140.1.3" pol...
package main import ( "errors" "flag" "io/ioutil" "log" "net/http" "net/url" "os" "strings" pit "github.com/typester/go-pit" ) var ( Endpoint string ) func main() { // parse arguments var channel string var summary string var notice bool var useAuth bool var username string var password string fl...
package lc // Time: O(n) // Benchmark: 124ms 7.9mb | 88% 61% type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func walk(node *TreeNode, level int, sums *[]int) { if node == nil { return } if level >= len(*sums) { *sums = append(*sums, 0) } walk(node.Left, level+1, sums) (*sums)[level...
package main import ( "errors" "fmt" ) type Day struct { Date string Sunrise string Sunset string } func findDay(days []Day, today string) (Day, error) { for _, day := range days { if today == day.Date { return day, nil } } return Day{}, errors.New(fmt.Sprintf("Could not find entry for '%s' in co...
package entity type Nodes []Node func (n Nodes) Exist(id string) bool { for _, v := range n { if v.Data.Id == id { return true } } return false } type Node struct { Data struct { Id string `json:"id"` Parent string `json:"parent,omitempty"` } `json:"data"` } func NewNode(id, parent string) Node ...
package client_relay // // Copyright (c) 2019 ARM Limited. // // SPDX-License-Identifier: MIT // // 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 witho...
/** * * @author nghiatc * @since Dec 6, 2019 */ package main import ( "fmt" "github.com/congnghia0609/ntc-gconf/nconf" "github.com/congnghia0609/ntc-gnats/npub" "github.com/congnghia0609/ntc-gnats/nreq" "log" "os" "os/signal" "path/filepath" "runtime" "strconv" ) func InitNConf() { _, b, _, _ := runti...
package utils import ( "math/rand" "time" ) // RandomString generate random string with lower case alphabets and digits func RandomString(length int) string { var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano())) charset := "abcdefghijklmnopqrstuvwxyz1234567890" str := make([]byte, length) ...
package github import ( "context" "errors" "fmt" "time" lru "github.com/hashicorp/golang-lru" "github.com/m-zajac/goprojectdemo/internal/app" ) // CachedClient wraps github client with caching layer. type CachedClient struct { client app.GithubClient projectsCache *lru.Cache statsCache *lru.Cache ...
package leetcode_go var pre99, q, p *TreeNode func recoverTree(root *TreeNode) { pre99, q, p = nil, nil, nil traverse(root) q.Val, p.Val = p.Val, q.Val } func traverse(root *TreeNode) { if root == nil { return } traverse(root.Left) if pre99 != nil && root.Val < pre.Val { if q == nil { q = pre99 } ...
package swaggerT import ( "reflect" "strings" "github.com/go-openapi/jsonreference" "github.com/go-openapi/spec" "github.com/ltto/gobox/ref" ) type schema struct { Map map[string]spec.Schema RefMap map[string]*spec.Schema } type Key struct { K string t reflect.Type m InterfaceMap } func NewKey(t reflec...
package acceptance_test import ( "github.com/d11wtq/bijou/runtime" "testing" ) func TestEq(t *testing.T) { AssertRunEqual(t, "(=)", runtime.True) AssertRunEqual(t, "(= 42)", runtime.True) AssertRunEqual(t, "(= 42 7)", runtime.False) AssertRunEqual(t, "(= 42 42 42)", runtime.True) AssertRunEqual(t, "(= 42 7 42 ...
package server import "log" type Session struct { Id string Peer *Peer } type SessionManager struct { register chan Session unregister chan Session } func NewSessionManager() *SessionManager { sm := &SessionManager{ register: make(chan Session), unregister: make(chan Session), } go sm.run() return...