text
stringlengths
11
4.05M
package main import ( "github.com/funkygao/gobench/util" "strconv" "testing" ) func main() { b := testing.Benchmark(benchmarkStrconvAtoi) util.ShowBenchResult("Atoi", b) } func benchmarkStrconvAtoi(b *testing.B) { b.ReportAllocs() s := "1212" for i := 0; i < b.N; i++ { strconv.Atoi(s) } }
package ingest import ( "context" "encoding/json" "fmt" "io/ioutil" "math/rand" "os" "path/filepath" "sort" "testing" "time" "github.com/dgraph-io/dgo/v200" "github.com/dgraph-io/dgo/v200/protos/api" "github.com/dylanratcliffe/sdp-go" "github.com/nats-io/nats.go" "github.com/spf13/viper" "google.golan...
// Copyright 2023 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 algorithm import "testing" func TestQuick(t *testing.T){ t.Log("test quick sort") quickSort(s1, 0, len(s1)-1) t.Logf("after quick sort, s1:%v\n", s1) }
package cli var CurrencyEmojis = map[string]string{ "USD": "💵", "EUR": "💶", "JPY": "💴", "GBP": "💷", }
package twitter // TwInfo : Data for twitter oauth type TwInfo struct { ConsumerKey string ConsumerSecret string AccessToken string AccessTokenSecret string }
package calendar import ( "github.com/sirupsen/logrus" "github.com/spf13/pflag" "github.com/spf13/viper" ) type config struct { Database struct { Host string Port string User string Password string Name string } App struct { Host string Port string Type string } GRPC struct { ...
// Copyright 2015 The Chromium 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 bf import ( "fmt" ) // BitField is a AppEngine-serializable bit field implementation. It should // be nice and fast for non-AppEngine use as we...
package main import ( "bytes" "flag" "log" "net/http" "net/http/httptest" "os" "regexp" "text/template" "github.com/gorilla/handlers" ) var ( laddr = flag.String("p", ":8080", "listen address") expanded = regexp.MustCompile(`(.*\.repo|metalink.xml)$`) ) // the expander middleware expands the response of...
package format import ( "strings" "gollum/core" ) // Replace formatter // // This formatter replaces all occurrences in a string with another. // // Parameters // // - Search: Defines the string to search for. When left empty, the target will // be completely replaced by ReplaceWith. // By default this is set to "...
// Copyright 2023 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package rest_test import ( "encoding/json" "github.com/go-martini/martini" "github.com/xo/rest" "net/http" "net/http/httptest" "testing" ) func TestRestError(t *testing.T) { err := &rest.RestError{-100, "test rest error"} if err.ErrorCode != -100 { t.Errorf("error code %d != -100", err.ErrorCo...
package oidc import ( "context" "github.com/ory/fosite" "github.com/ory/fosite/handler/oauth2" "github.com/ory/fosite/token/jwt" "github.com/ory/x/errorsx" ) // StatelessJWTValidator is a stateless introspect for the JWT Access Tokens. type StatelessJWTValidator struct { jwt.Signer Config interface { fosite...
// Copyright 2014 The Cockroach 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 ag...
package lottery // Prize 表示一个奖品 type Prize struct{ Index int Name string Amount int Remain int }
package main import ( "fmt" "com/pdool/Core" ) func main() { mgr := Core.GetModuleMgr() mgr.RegistModule("TimeMgr",Core.GetTimeMgr()) mgr.RegistModule("SceneMgr",Core.GetSceneMgr()) //mgr.RegistModule("FriendModule",new(TestHandler)) manager := mgr.GetModule("SceneMgr").(*Core.SceneManager) scene := manager...
package controller import ( "github.com/goadesign/goa" "github.com/yogihardi/guestbook/rest/app" "github.com/yogihardi/guestbook/version" ) // VersionController implements the version resource. type VersionController struct { *goa.Controller } // NewVersionController creates a version controller. func NewVersion...
package main import ( "errors" "fmt" "golang.org/x/crypto/ssh" "io" "math/rand" "net" "time" ) var MDeviceList = make(map[string]Device) var MLocalPort = make(map[uint16]string) func SshForwardNewDevice(parent Device, child Device) Device { child.LogDebug("SshForwardNewDevice: Get new address", child.Name) ...
package session import ( "github.com/gomodule/redigo/redis" "time" ) type MyRedisConf struct { RedisHost string RedisMaxIdle int RedisMaxActive int RedisIdleTimeout int RedisDB int RedisPass string } func NewRedis(redisConf *MyRedisConf) (pool *redis.Pool, err error) { pool = &r...
package graphql_test import ( "testing" "github.com/graphql-go/graphql" "github.com/graphql-go/graphql/gqlerrors" "github.com/graphql-go/graphql/testutil" ) func TestValidate_ArgValuesOfCorrectType_ValidValue_GoodIntValue(t *testing.T) { testutil.ExpectPassesRule(t, graphql.ArgumentsOfCorrectTypeRule, ` ...
package main import "fmt" func test(x, y int) { fmt.Println(x, y) if x > 0 { z := 100 fmt.Println(z) } } func main() { test(10,20) }
/* A regular dodecahedron is one of the five Platonic solids. It has 12 pentagonal faces, 20 vertices, and 30 edges. https://i.stack.imgur.com/vx9WU.png Your task is to output the vertex coordinates of a regular dodecahedron. The size, orientation, and position of the dodecahedron are up to you, as long as it is reg...
package main import "fmt" func maxtrixRotation(a [][]int) [][]int { // TODO NxN matrix b := [][]int{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}} for i, y := range a { for j, x := range y { b[j][3-i] = x } } for _, bb := range b { fmt.Println(bb) } return b } func maxtrixRotation2(a [][]int...
package txutil import ( "bytes" "fmt" "sort" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance" valuetransaction "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/transaction" ) func BalancesToString(outs map[valuetransaction.ID][]*balance.Balance) string { if outs == nil { ...
package types import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" ) // ParamSubspace defines the expected Subspace interface for parameters (noalias) type ParamSubspace interface { Get(ctx sdk.Context, key []byte, ptr interface{}) Set(ctx sdk.Context, key []byte, param in...
package fsdb_test import ( "testing" "github.com/fishy/fsdb" ) func TestString(t *testing.T) { expect := "foobar" key := fsdb.Key(expect) actual := key.String() if expect != actual { t.Errorf("(%v).String() expected %q, got %q", key, expect, actual) } key = fsdb.Key{0xff, 0xfe, 0xfd} expect = "[255 254 2...
// Copyright (c) 2019 IoTeX // This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no // warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent // permitted by law, all liability for your use of the cod...
/*** package controllers implement the controller for router */ package controllers import ( "encoding/json" "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "github.com/guowenshuai/apiproject/models" ) type JobController struct { beego.Controller } func (j *JobController) recoverHandler() { if err...
package types type Type string
package k8sml type Target interface { GetTargetID() string GetVariableValue(variable string) interface{} }
package validator import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/authelia/authelia/v4/internal/configuration/schema" ) func TestValidateDuo(t *testing.T) { testCases := []struct { desc string have *schema.Configuration expected sch...
package types import ( "github.com/openshift/installer/pkg/types/gcp" ) // ClusterQuota contains the size, in cloud quota, of // the cluster that was created by installer. type ClusterQuota struct { GCP *gcp.Quota `json:"gcp,omitempty"` }
package awskinesis import ( "context" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/kinesis" "github.com/aws/aws-sdk-go/service/kinesis/kinesisiface" "github.com/pkg/errors" "github.com/sirupsen/logrus" ...
package table import ( //"fmt" "errors" "github.com/inazo1115/toydb/lib/util" ) // Schema type Schema struct { cols []*Column } func NewSchema(cols []*Column) *Schema { return &Schema{cols} } func (s *Schema) Columns() []*Column { return s.cols } func (s *Schema) Type(colName string) (ToyDBType, error) { ...
package base import ( "bytes" luar "layeh.com/gopher-luar" "unicode/utf8" "unsafe" ) type Buffer []byte type BufferFactory struct{} func (f BufferFactory) New(length int) Buffer { return make(Buffer, length) } func (BufferFactory) Alloc(length int, args ...int) Buffer { return __allocBuffer(length, args...) ...
/* Copyright (c) 2015 Eric Knapik, 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 and the followi...
package packet import ( "bytes" "errors" "github.com/cpusoft/goutil/asn1util" "github.com/cpusoft/goutil/belogs" "github.com/cpusoft/goutil/convert" ) func ExtractAkiOid(oidPackets *[]OidPacket, fileByte []byte) (aki string, err error) { for _, oidPacket := range *oidPackets { if oidPacket.Oid == oidAuthorit...
package controllers import ( "time" "github.com/devplayg/ipas-mcs/objs" "github.com/devplayg/ipas-mcs/models" log "github.com/sirupsen/logrus" ) type StatuslogController struct { baseController } func (c *StatuslogController) CtrlPrepare() { // 추가 언어 키워드 //c.addToFrontLang("ipas.start,shock,speeding,proximity...
package services import ( "github.com/solrac97gr/cryptoAPI/database" "github.com/solrac97gr/cryptoAPI/models" "github.com/solrac97gr/cryptoAPI/util" ) func DecryptTextMessage(encryptedMessage models.ReturnedMsg) (bool, models.ReturnedMsg) { error, encryptedMsgFromDB := database.GetEncryptMessage(encryptedMessage....
package main import ( "bytes" "testing" ) func TestRandomBytes(t *testing.T) { var bufs [][]byte for i := 0; i < 5; i++ { bufs = append(bufs, RandomBytes(16)) for j := 0; j < i; j++ { if bytes.Equal(bufs[i], bufs[j]) { t.Errorf("identical buffers %v and %v", bufs[i], bufs[j]) } } } } func TestRa...
package stringer import ( "testing" "github.com/google/go-cmp/cmp" ) var stringerStudentTests = []struct { in Student want string }{ {Student{ ID: 42, FirstName: "John", LastName: "Doe", Age: 25, }, "Student ID: 42. Name: Doe, John. Age: 25."}, {Student{ ID: 1490, FirstName:...
package util import ( "bytes" "encoding/base64" "strconv" ) func ToHex(b []byte) string { hex := ByteToHex(b) if len(hex) == 0 { hex = "0" } return "0x" + hex } // FromHex returns the bytes represented by the hexadecimal string s. // s may be prefixed with "0x". func FromHex(s string) []byte { if len(s) > ...
package controllers import ( "ginDemo/models" "ginDemo/process" "ginDemo/utils" "github.com/gin-gonic/gin" "net/http" ) type Credential struct { Username string `json:"username" binding:"required"` Password string `json:"password" binding:"required"` } var up = process.UserProcess{} func Auth(c *gin.Context)...
package services import ( "testing" "github.com/ne7ermore/gRBAC/models" ) func Test_build(t *testing.T) { models.Get().Build() p := models.Get().GetPermissionPools() err := initPerm(p) if err != nil { t.Fatal(err) } r := models.Get().GetRolePools() err = initRole(r) if err != nil { t.Fatal(err) } }
package main import ( "fmt" "math" ) func check(x float64) (string,float64) { if math.Mod(x,2)==0 { x = x/2 return "Ce nombre est pair",x }else { x = x*3 + 1 return "Ce nombre n'est pas pair",x } } func main() { fmt.Println(check...
package main import ( "os" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello World Go!", }) }) router.GET("/users", getUsers) router.GET("/users/:username", getUser) router.POST("/users", postUsers) router...
package main import ( "encoding/json" "fmt" ) type Company struct { ID int `orm:"column(id)" form:"-" json:"id"` Name string `orm:"column(name)" form:"name" json:"name"` State string `orm:"column(state)" form:"state" json:"state"` Point...
package test import ( "golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // UnimplementedPingServer implements pb.PingServiceServer only for test. type UnimplementedPingServer struct{} // Send returns Unimplemented. func (*UnimplementedPingServer) Send(_ context.Context, m...
package attacher import ( "errors" "fmt" "github.com/Huawei/eSDK_K8S_Plugin/src/connector" _ "github.com/Huawei/eSDK_K8S_Plugin/src/connector/fibrechannel" _ "github.com/Huawei/eSDK_K8S_Plugin/src/connector/iscsi" _ "github.com/Huawei/eSDK_K8S_Plugin/src/connector/nvme" _ "github.com/Huawei/eSDK_K8S_Plugin/src...
package bufio1 func BufioMain() { StringReader() BufioReader() }
package db import ( "database/sql" "sync" "github.com/textileio/go-textile/pb" "github.com/textileio/go-textile/repo" "github.com/textileio/go-textile/util" ) type CafeClientNonceDB struct { modelStore } func NewCafeClientNonceStore(db *sql.DB, lock *sync.Mutex) repo.CafeClientNonceStore { return &CafeClient...
package core import ( "bytes" "fmt" "github.com/callumj/weave/remote/uptypes" "gopkg.in/yaml.v1" "io/ioutil" "log" "regexp" "strings" ) type Configuration struct { Name string Disabled bool Except []string ExceptReg *regexp.Regexp Only []string OnlyReg *regexp.Regexp } type Instruction ...
package services import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "sync" ) var once sync.Once const dialect = "postgres" const url = "postgresql://go_web_dev:go_web_dev@localhost/go_web_dev?sslmode=disable" func InitDB() *gorm.DB { var DB *gorm.DB var err error once.Do(fu...
package errors import ( "bytes" "fmt" "regexp" "runtime" ) const MaxCallStackLength = 30 var ( componentPattern = "[A-Za-z]{3}" reasonPattern = "[0-9]{3}" ) type CallStackError interface { error GetStack() string GetErrorCode() string GetComponentCode() string GetReasonCode() string Message() string ...
package fs import ( "log" "regexp" "github.com/hanwen/go-mtpfs/mtp" ) func SelectStorages(dev *mtp.Device, pat string) ([]uint32, error) { sids := mtp.Uint32Array{} if err := dev.GetStorageIDs(&sids); err != nil { return nil, err } re, err := regexp.Compile(pat) if err != nil { return nil, err } filt...
package tests import ( "fmt" "testing" "time" ) func TestParallelization1(t *testing.T) { t.Parallel() fmt.Println(fmt.Sprintf("Test in Parallel #1 started at : %s", time.Now().String())) time.Sleep(5 * time.Second) fmt.Println(fmt.Sprintf("Test in Parallel #1 ended at : %s", time.Now().String())) }
package main import ( "fmt" "io" ) type DataWriter interface { WriteData(data interface{}) error CanWrite() bool } // 定义文件结构, 用于实现DataWriter type file struct { } func (d *file) WriteData(data interface{}) error { fmt.Println("WriteData: ", data) return nil } func (d *file) CanWrite() bool { return true }...
package xlsx import ( "github.com/stretchr/testify/require" "testing" "github.com/plandem/xlsx/format" "github.com/plandem/xlsx/internal/ml" ) func addNewStyles(xl *Spreadsheet, t *testing.T) format.DirectStyleID { require.NotNil(t, xl) require.Equal(t, 1, len(xl.styleSheet.directStyleIndex)) require.Equal(t...
package v1 import ( "net/http" "github.com/gin-gonic/gin" ) func Demon(c *gin.Context) { c.JSON(http.StatusOK, "demon api") }
package api import ( utils "github.com/kevinbarbary/go-lms/utils" "log" ) func Auth(site, username, password, useragent string, retry bool) (string, string) { return authenticate(useragent, site, username, password, "", retry) } func Unauth(site, token, useragent string) (string, string) { // i.e. sign out - rem...
package main import ( "fmt" "strconv" ) func main() { string1 := "aaabbbccc" string2 := "aaabbbccc" string1Map := make(map[string]int) string2Map := make(map[string]int) string1Build := "" string2Build := "" count := 1 for _, x := range string1 { _, ok := string1Map[string(x)] if ok { continue ...
package main; import ( "log" "net/http" "github.com/guidiego/gocket/test" ) func main() { gocket.On("Connect", func (conn gocket.Conn, data interface{}) { conn.ConnectOnRoom("test") }) http.Handle("/ws", gocket.Handler()) log.Fatal(http.ListenAndServe(":8888", nil)) }
package neo4j // Now this is for Neo4J. var queries = map[string]string{ // Auth: "touchDevice": ` MERGE (device:Device { uid: {uid} }) ON CREATE SET device.deviceToken = {maybeDeviceToken}, device.uid = {uid}, device.name = {name}, device.platform = {platform}, device.capacity = {capacity}, ...
package main import ( "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" "os" "strconv" "time" ) type dbEng struct{ id int // порядковый номер в таблице englishWord string // английское слово russianWord string // русское слово - перевод timeInit string // дата создания записи timeCheck string // последн...
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "...
package ch1 import ( "fmt" "io" "os" ) // EchoOSArgs 输出命令行参数 func EchoOSArgs(w io.Writer, sep string) error { for idx, arg := range os.Args[1:] { if _, err := w.Write([]byte(fmt.Sprintf("args %d: %s%s", idx+1, arg, sep))); err != nil { return err } } return nil }
package database import ( "database/sql" "fmt" "os" "github.com/joho/godotenv" _ "github.com/lib/pq" ) func ConnectDB() (*sql.DB, error) { if err := godotenv.Load(); err != nil { return nil, err } psqlInfo := fmt.Sprintf("host=%s port=%s user=%s "+ "password=%s dbname=%s sslmode=disable", os.Getenv("DB...
package cmd import ( "github.com/spf13/cobra" ) // Create the stop command var cmdStop = &cobra.Command{ Use: "stop WORKFLOW", Short: "Stop (pause) a workflow", Long: `Stop (pause) a Swif workflow.`, Example: `1. sw stop my-workflow 2. sw stop ana`, Run: runStop, } var now bool func init() { cmdSW.AddComm...
package main import ( "sync/Database" "log" "github.com/widuu/goini" ) type option struct { tablename string dbname string host string port string user string password string sslmode string schema string } var Opt option func main() { Opt.tablename = "adjustments" conf := goini...
package stopwatch import ( "fmt" "strconv" "sync" "time" ) const ( // STARTNAME is name of the time which Stopwatch start from STARTNAME = "0-Start" // ENDNAME is name of the time which Stopwatch end in ENDNAME = "(LastLap)" ) type lap struct { name string time time.Time } // Stopwatch struct record the l...
package sqs_test import ( "strings" "testing" awsSQS "github.com/aws/aws-sdk-go/service/sqs" "github.com/pkg/errors" pubSQS "github.com/utilitywarehouse/go-pubsub/sqs" ) func Test_PutMessageMissingClient_Fail(t *testing.T) { _, err := pubSQS.NewMessageSink(pubSQS.MessageSinkConfig{}) if err == nil { t.Fatal...
package main import ( "io/ioutil" "os" "path/filepath" "strings" "testing" ) const ( RESULTS = `tmp/1, 70c881d4a26984ddce795f6f71817c9cf4480e79, 4 tmp/2, 8aed1322e5450badb078e1fb60a817a1df25a2ca, 4 tmp/4/1, 01464e1616e3fdd5c60c0cc5516c1d1454cc4185, 4 ` ) func createDir(name string) { os.MkdirAll(name, 0777) }...
package model // Novel is. type Novel struct { ID uint64 `gorm:"AUTO_INCREMENT"` UserID uint64 `gorm:"index"` User User Title string `gorm:"size:255"` Description string `gorm:"size:255"` Script string `gorm:"type:text"` IsPrivate bool `gorm:""` Emojis []Emoji // On...
package cron import ( "bytes" "encoding/json" "github.com/coraldane/dns-agent/g" "github.com/toolkits/logger" "github.com/toolkits/net/httplib" "io/ioutil" "net/http" "net/url" "sort" "strconv" "strings" "time" ) func ModifyRecord(domainId int, recordId, subDomain, strIp string) bool { data := url.Values...
package main import ( "fmt" "syscall" "unsafe" "github.com/lxn/win" ) type window struct { hwnd win.HWND pid uint32 name, class string process string r win.RECT visible bool hasChild bool } func dump() { l := listWindows(win.HWND(0)) for _, win := range l { fmt.Pri...
// Copyright 2019 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
package models type TestResponse struct { Data string Result string }
package main import ( "net/http" "github.com/gin-gonic/gin" ) type User struct { Name string } func main() { r := gin.Default() r.LoadHTMLGlob("views/*.html") r.GET("/", func(c *gin.Context) { user := User{ Name: "konojunya", } c.HTML(http.StatusOK, "index.html", user) }) r.Run(":4000") }
// Copyright (C) 2019 rameshvk. All rights reserved. // Use of this source code is governed by a MIT-style license // that can be found in the LICENSE file. package router import ( "strings" "go/ast" "github.com/tvastar/gogo/pkg/code" ) func New(pkgName, structName string) *Config { if structName == "" { str...
package admin import ( admin "github.com/hxangel/bot/libs/admin" models "github.com/hxangel/bot/models" "strings" ) type Group struct { AdminBase } func (c *Group) Index() { mgroup := models.NewGroupModel() groups, err := mgroup.Gets() if err == nil { c.Assign("groups", groups) } } func (c *Group) Add() {...
package arbitrageur import ( "time" "github.com/Reidmcc/rockfish/modules" "github.com/interstellar/kelp/api" "github.com/interstellar/kelp/support/logger" "github.com/interstellar/kelp/support/utils" "github.com/nikhilsaraf/go-tools/multithreading" "github.com/stellar/go/build" ) // Arbitrageur is the bot str...
/* Copyright © 2020 Denis Rendler <connect@rendler.me> 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...
/* * @lc app=leetcode.cn id=406 lang=golang * * [406] 根据身高重建队列 */ package solution import "math" // @lc code=start func reconstructQueue(people [][]int) [][]int { n := len(people) cnt, checkin := 0, make([]bool, n) people = append(people, []int{math.MaxInt64, 0}) getMin := func() int { min := n for i, b ...
package Plugins import ( "../Misc" "../Parse" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "net" "net/http" "sync" "time" ) func Apache(info Misc.HostInfo, ch chan int, wg *sync.WaitGroup, client *http.Client) { auth := fmt.Sprintf("%s:%s", info.Username, info.Password) b64auth := base64.StdEncodin...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/11/22 10:18 上午 # @File : lt_189_轮转数组_test.go.go # @Description : # @Attention : */ package v2 import ( "fmt" "testing" ) func Test_rotateReverse(t *testing.T) { arrs := []int{1, 2, 3, 4, 5, 6, 7} rotateReverse(arrs) fmt.Println(arrs) }
package server import ( "server/data/datatype" "server/libs/rpc" ) type Apper interface { //当前是否是base服务 IsBase() bool //自主控制socket RawSock() bool //系统准备回调,底层已经初始化完成 OnPrepare() bool //系统启动回调 OnStart() //其它应用就绪回调 OnReady(app string) //其它应用断开连接回调 OnLost(app string) //关键应用已经准备好 OnMustAppReady() //系统关闭回调...
package dp import ( "testing" ) func TestFibonacci(t *testing.T) { assertion := func(t *testing.T, expect, got int) { if expect != got { t.Fatalf("expected %d got %d", expect, got) } } t.Run("test fibonacci with recursive approach only", func(t *testing.T) { expect := 5 got := FibonacciRecursive(5) a...
package customer import ( "fmt" "github.com/gin-gonic/gin" "log" "net/http" "strconv" "github.com/Khamontip/finalexam/database" ) type Customers struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` Status string `json:"status"` } func PostCustomersHandler(c *gin.Con...
package functions import ( "errors" "gonum.org/v1/gonum/floats" "gonum.org/v1/gonum/mat" ) // sumAlongAxis sums a matrix along a // particular dimension, preserving the // other dimension. func SumAlongAxis(axis int, m *mat.Dense) (*mat.Dense, error) { numRows, numCols := m.Dims() var output *mat.Dense swit...
package main import ( "flag" "net/http" "net/http/httputil" "github.com/golang/glog" "github.com/liuzl/goutil/rest" ) var ( serverAddr = flag.String("addr", ":8080", "bind address") ) func EchoHandler(w http.ResponseWriter, r *http.Request) { dump, err := httputil.DumpRequest(r, true) if err != nil { rest...
/* Description Stan and Ollie play the game of Odd Brownie Points. Some brownie points are located in the plane, at integer coordinates. Stan plays first and places a vertical line in the plane. The line must go through a brownie point and may cross many (with the same x-coordinate). Then Ollie places a horizontal li...
package transformer import ( "github.com/golang/protobuf/ptypes" "github.com/satori/go.uuid" "github.com/tppgit/we_service/core" "github.com/tppgit/we_service/entity/order" "github.com/tppgit/we_service/pkg/errors" ) type WeCommentTransformer struct { CreateComment *core.CreateComment } func (m *WeCommentTrans...
package repository import ( "github.com/bearname/videohost/internal/common/db" dto2 "github.com/bearname/videohost/internal/videoserver/domain/dto" "github.com/bearname/videohost/internal/videoserver/domain/model" ) type VideoRepository interface { Create(userId string, videoId string, title string, description s...
package ebpf import ( "errors" "testing" "github.com/cilium/ebpf/asm" "github.com/cilium/ebpf/btf" "github.com/cilium/ebpf/internal" "github.com/cilium/ebpf/internal/testutils" qt "github.com/frankban/quicktest" ) func TestFindReferences(t *testing.T) { progs := map[string]*ProgramSpec{ "entrypoint": { ...
package main import "fmt" func main() { ch := make(chan struct{}, 10) fmt.Println("======") for i := 0; i < 10; i++ { go func() { fmt.Printf("without binding: %d\n", i) ch <- struct{}{} }() } for i := 0; i < 10; i++ { <-ch } fmt.Println("======") for i := 0; i < 10; i++ { go func(i int) { f...
package core import ( "babyboy/common" "babyboy/core/types" "babyboy/crypto" "encoding/json" "fmt" "log" ) type Signer struct { } func NewSigner() *Signer { signer := &Signer{} return signer } func (s *Signer) VerifyUnit(unit types.Unit) bool { var newUnit = types.Unit{} newUnit = unit originalAddr := n...
package background import ( "image" "image/png" "os" "path/filepath" ) // Create the background at a given path. func createFile(img image.Image, absPath string) error { // Create the directory if it doesn't exist. if err := os.MkdirAll(filepath.Dir(absPath), 0777); err != nil { return err } // Get the han...
package sleepytcp import ( "errors" "sync" "time" ) const ( DefaultMaxConnsPerHost = 512 DefaultMaxIdleConnDuration = 10 * time.Second DefaultMaxIdempotentCallAttempts = 5 DefaultReadBufferSize = 4096 DefaultWriteBufferSize = 4096 ) var ( ErrConnectionClosed = errors.New("connection closed...
package job import ( "sort" "strings" bpreljob "github.com/cppforlife/bosh-provisioner/release/job" ) const ( templateBinRun = "bin/run" templateBinPrefix = "bin/" templateConfigPrefix = "config/" ) type Template struct { SrcPathEnd string DstPathEnd string } type TemplateSorting []Template func ...
package main func prefixesDivBy5(A []int) []bool { ans := make([]bool, len(A)) sum := 0 for i := 0; i < len(A); i++ { sum = (sum << 1) | A[i] ans[i] = (sum%5 == 0) sum = sum % 5 } return ans } /* 总结 1. 这里用到了取模运算的性质 (a * b + c) % m == ((a%m) * b + c) % m */