text stringlengths 11 4.05M |
|---|
// Copyright (c) 2019, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the LICENSE.md file
// distributed with the sources of this project regarding your rights to use or distribute this
// software.
package client
import (
"io/ioutil"
"net/http"
"strings"... |
package management
import (
"context"
"github.com/golang/protobuf/ptypes/empty"
"github.com/caos/zitadel/pkg/grpc/management"
)
func (s *Server) GetOrgMemberRoles(ctx context.Context, _ *empty.Empty) (*management.OrgMemberRoles, error) {
return &management.OrgMemberRoles{Roles: s.org.GetOrgMemberRoles()}, nil
}... |
package hud
import (
"encoding/json"
"fmt"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/tilt-dev/tilt/internal/container"
"github.com/tilt-dev/tilt/internal/hud/view"
"github.com/tilt-dev/tilt/internal/rty"
"github.com/tilt-dev/tilt/internal/store"
"github.com/tilt-d... |
package storage
import (
"github.com/mradile/rssfeeder"
"github.com/stretchr/testify/assert"
"testing"
)
func Test_userStorage(t *testing.T) {
db, err := getDB()
assert.Nil(t, err)
defer db.Close()
s := NewUserStorage(db)
//add user1
user1 := &rssfeeder.User{
Login: "bla",
Password: "blub",
}
asser... |
package config
import (
"excho-job/migration"
"fmt"
"os"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func Connection() *gorm.DB {
dbUser := os.Getenv("DB_USERNAME")
dbPass := os.Getenv("DB_PASSWORD")
dbHost := os.Getenv("DB_HOST")
dbPort := os.Getenv("DB_PORT")
dbName := os.Getenv("DB_NAME")
dsn := fmt.Spri... |
package main
import (
"fmt"
"os"
"strings"
)
func main() {
p := NewParser(os.Stdout, strings.NewReader("9-5+2"))
if err := p.Parse(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println()
}
|
package main
import (
"os"
"log"
"github.com/kniren/gota/dataframe"
"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/vg"
)
func main() {
advertisingCsv,err:=os.Open("linearregression/data/Advertising.csv")
if err!=nil{
log.Fatal(err)
}
defer advertisingCsv.Close()
advertisingDF:=dat... |
/*
* Lean tool - hypothesis testing application
*
* https://github.com/MikaelLazarev/willie/
* Copyright (c) 2020. Mikhail Lazarev
*
*/
package middlewares
import (
"context"
"github.com/MikaelLazarev/willie/server/core"
"github.com/MikaelLazarev/willie/server/errors/sentry"
"github.com/gin-gonic/gin"
uuid... |
package core
import (
"encoding/json"
"reflect"
"testing"
"github.com/davecgh/go-spew/spew"
)
func TestVariationMatrixMarshalJSON(t *testing.T) {
for _, test := range []struct {
name string
matrix *VariationMatrix
expected string
}{
{
"recursive",
&VariationMatrix{
Children: map[string]... |
package ravendb
import "reflect"
// ConcurrencyCheckMode describes concurrency check
type ConcurrencyCheckMode int
const (
// ConcurrencyCheckAuto is automatic optimistic concurrency check depending on UseOptimisticConcurrency setting or provided Change Vector
ConcurrencyCheckAuto ConcurrencyCheckMode = iota
// C... |
package leetcode
func isValid(s string) bool {
if len(s)%2 == 1 {
return false
}
dicts := make(map[byte]byte)
stack := []byte{}
dicts[')'] = '('
dicts[']'] = '['
dicts['}'] = '{'
for i := 0; i < len(s); i++ {
if dicts[s[i]] > 0 {
if len(stack) == 0 || stack[len(stack)-1] != dicts[s[i]] {
return fal... |
/*-------------------------------------------------------------------------
*
* export_runner.go
* Export Runner
*
*
* Copyright (c) 2021, Alibaba Group Holding Limited
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You ... |
package main
import (
"log"
"main/utils"
)
/**
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 ... |
package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
)
var in = bufio.NewScanner(os.Stdin)
var ab [3001]int
func init() {
in.Split(bufio.ScanWords)
}
func main() {
n, v := readInt(), readInt()
for i := 0; i < n; i++ {
a, b := readInt(), readInt()
ab[a-1] += b
}
remain, col := 0, 0
for i := 0; ... |
package core
import (
"reflect"
"testing"
)
func TestSpotifyID_ToBase62(t *testing.T) {
tests := []struct {
name string
s SpotifyID
want string
}{
{
s: SpotifyID([]byte{0x00, 0x0d, 0x53, 0x65, 0x35, 0x86, 0x4e, 0x0f, 0x99, 0x76, 0x1f, 0x9d, 0xa9, 0x00, 0xb1, 0xc1}),
want: "0065zxtT6XKaQww7cLne... |
package main
import (
"fmt"
"math"
)
func main() {
n :=1011
v :=0
i :=0
for n >0 {
l := n%10;
v += int(math.Pow(2.0, float64(i)))*l
n = n/10
i++
}
fmt.Println(v)
}
|
package zk
import (
"net"
"sync"
"sync/atomic"
)
const (
DefaultPort = 2181 // 默认端口号
RecvTimeout = 1 // 接收消息超时,单位:秒
SessionTimeout = 4000 // 客户端会话超时,单位:毫秒
PingInterval = 2000 // Ping超时,单位:毫秒
BufferSize = 2 * 1024 // 1K
SentChanSize = 16 // 发送请求队列大小
RecvC... |
package api
import (
"net/http"
"sort"
"github.com/gin-gonic/gin"
"github.com/pegasus-cloud/iam_client/iam"
"github.com/pegasus-cloud/iam_client/utility"
)
func listPermissionActions(c *gin.Context) {
getActions := iam.Actions.GetActions()
sort.Strings(getActions)
utility.ResponseWithType(c, http.StatusOK, &... |
package user
import (
log "github.com/sirupsen/logrus"
)
func Name() {
log.Info("Logging from user package")
} |
// Copyright 2020 The gVisor 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 agree... |
package server
import (
"net"
"time"
"github.com/iotaledger/hive.go/autopeering/peer"
"github.com/iotaledger/hive.go/crypto/identity"
)
const (
packetExpiration = 20 * time.Second
)
// Protocol provides a basis for server protocols handling incoming messages.
type Protocol struct {
Sender Sender // interface ... |
package cli
import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/klog/v2"
)
func TestResourceVersionTooOldWarningsSilenced(t *testing.T) {
out := bytes.NewBuffer(nil)
initKlog(out)
PrintWatchEndedV4()
klog.Flush()
assert.Equal(t, "", out.String())
PrintWatchEndedWarning()
klog.Flush()... |
package zermelo
import (
"github.com/shawnsmithdev/zermelo/v2/internal"
"slices"
"testing"
)
const (
// Const int size thanks to kostya-sh@github
intSize uint = 1 << (5 + (^uint(0))>>32&1)
testSize = 2 * compSortCutoff64
)
func TestSort(t *testing.T) {
testSort[int8](t, internal.RandInteger[int8](), fal... |
package repositories
import "gopkg.in/go-playground/validator.v9"
type (
Taxes struct {
ID string `json:"-"`
TaxName string `json:"tax_name", valid:"required"`
TaxCode string `json:"tax_code", valid:"required,min:1,max:3"`
Amount float64 `json:"amount", valid:"required,numeric"`
}
CustomValidator ... |
// +build ignore
/*
只能发送的通道类型为chan<-,只能接收的通道类型为<-chan
单向通道有利于代码接口的严谨性
*/
package main
func main() {
ch := make(chan int)
// 声明一个只能发送的通道类型, 并赋值为ch
var chSendOnly chan<- int = ch
//声明一个只能接收的通道类型, 并赋值为ch
var chReadOnly <-chan int = ch
// 当然,使用 make 创建通道时,也可以创建一个只发送或只读取的通道:
// ch := make(<-chan int)
// var ch... |
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package power
import (
"bufio"
"context"
"fmt"
"regexp"
"strings"
"time"
"chromiumos/tast/common/servo"
"chromiumos/tast/common/usbutils"
"chromiumos/tast/ctxutil"... |
package grpchandler
import (
pbwallet "WalletPOC/apidoc/grpc/gen"
"WalletPOC/internal/core/application"
"context"
)
type walletHandler struct {
walletSvc application.WalletService
}
func NewWalletHandler(walletSvc application.WalletService) pbwallet.WalletServer {
return walletHandler{
walletSvc: walletSvc,
... |
// Copyright (c) 2016-2019 Uber Technologies, 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... |
package wyrand
import (
"testing"
"time"
)
func BenchmarkNext(b *testing.B) {
b.ReportAllocs()
w := New(uint64(time.Now().UnixNano()))
for i := 0; i < b.N; i++ {
w.Next()
}
}
|
package pack
import (
"bytes"
"math/rand"
"testing"
"unsafe"
"github.com/stretchr/testify/assert"
)
func makeIndex() IndexFile {
idx := make(IndexFile, 1000)
for i := range idx {
idx[i].Offset = rand.Uint32()
idx[i].Length = rand.Uint32()
idx[i].Type = rand.Uint32()
for j := range idx[i].Sum {
idx... |
package models
type Tree struct {
Id string `json:"id"`
ParentId string `json:"parentId"`
Name string `json:"name"`
Type string `json:"type"`
CatalogItemId string `json:"catalogItemId"`
Children []Tree `json:"children"`
GroupIds []string `json:"groupIds"`
... |
// Copyright © 2019 Kerem Karatal
//
// 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... |
package glubcms
import (
"net/http"
"path/filepath"
)
// The StaticHandler behaves like http.ServeContent without directoy listings.
// It also implements the http.Filesystem interface.
type StaticHandler struct {
fs http.FileSystem
prefix string
}
// Serve the file requestet by r. Error 404 on directory acc... |
package todo
import (
"context"
"database/sql"
"fmt"
"time"
pb "github.com/qclaogui/golang-api-server/pkg/api/todopb/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
// MysqlRepository fulfills the Repository interface
type MysqlReposit... |
package main
//Valid
//Checks how append instruction returns slice type is given the samee type to LHS variables in Short Declarations
func f () {
var a1 []int
a1 = append(a1, 2)
a2, _ := append(a1, 1), append (a1, 3)
} |
package util
// Filter removes matching strings from a string slice
func Filter(strings []string, predicate func(int, string) bool) (ret []string) {
for i, s := range strings {
if predicate(i, s) {
ret = append(ret, s)
}
}
return
}
|
package main
import (
"fmt"
"strconv"
)
func processMain2(codes [][]string) {
ship := &Robot{
RestingChar: "S",
}
ship.Init()
waypoint := &Robot{
RestingChar: "W",
}
waypoint.Init()
waypoint.X = 10
waypoint.Y = 1
m := &Map{}
m.Init()
m.AddRobot(ship)
m.AddRobot(waypoint)
fmt.Println("---")
fmt.... |
package main
import "fmt"
// User struct, since it Capitalized, this will be eported from this package
// Custom types with member attributes
// So any variable of type User would have one of these members defined?
type User struct {
ID int
FirstName string
LastName string
Email string
}
// Group str... |
package cmd
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"os"
_ "github.com/lib/pq"
"github.com/spf13/cobra"
)
type Post struct {
ID string `json:"post-id"`
Body string `json:"post-body"`
Ts string `json:"time-stamp"`
}
var (
globalDB *sql.D... |
// Copyright 2016 Granitic. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license that can be found in the LICENSE file at the root of this project.
package rdbms
// A function able execute an insert statement and return an RDBMS generated ID as an int64.
// If your implementation requi... |
package main
import "fmt"
func main() {
//missing switch expression defaults to 'true'
switch {
case false:
fmt.Println("the false case")
case true:
fmt.Println("the true case")
} //END - switch
//* -------------------
//switch on value:
//And multiple cases per case
//v := "Bond"
//switch v {
//cas... |
package scaler
import (
"strconv"
"strings"
"time"
)
type Expression string
func (e Expression) Match(t time.Time) bool {
a := strings.Split(string(e), " ")
if len(a) != 6 {
return false
}
minute := pattern(a[0])
hour := pattern(a[1])
day := pattern(a[2])
month := pattern(a[3])
year := pattern(a[4])
... |
package config
import (
"fmt"
"github.com/google/logger"
"github.com/spf13/viper"
)
type DbConfig interface {
GetUser() string
GetDatabase() string
GetPort() string
GetHost() string
GetPassword() string
GetConnectionString() string
}
type dbConfig struct {
user string
database string
port string... |
package actions
import (
"errors"
"github.com/LiveSocket/bot/command-service/models"
"github.com/LiveSocket/bot/conv"
"github.com/LiveSocket/bot/service"
"github.com/LiveSocket/bot/service/socket"
"github.com/gammazero/nexus/v3/wamp"
)
type getInput struct {
Channel string
}
// Get Get a list of commands for... |
package errorsx
import (
"context"
"net"
)
// Dialer establishes network connections.
type Dialer interface {
// DialContext behaves like net.Dialer.DialContext.
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
// ErrorWrapperDialer is a dialer that performs error wrapping. The conne... |
package com
import (
"regexp"
"strconv"
"strings"
)
const (
// Movie type
Movie byte = 0
// SeasonTV is TV has season
SeasonTV byte = 1
// NoSeasonTV is TV has no season
NoSeasonTV byte = 2
// UnknownType x
UnknownType byte = 255
)
const (
minTargetKeywordSize = 3
minPrimaryK... |
package handle
import (
"github.com/valyala/fasthttp"
"mygo/model"
"mygo/service"
"strconv"
)
func OrderList(ctx *fasthttp.RequestCtx) {
var order model.OrderList
req := ctx.Request.Body()
order.UnmarshalJSON(req)
result := service.GetOrderList(order)
resp.Data = result
CommonWriteSuccess(ctx, resp)
}
//生... |
package list
import ("store"
)
func ListAllEmployees(employees *([]store.Employee)) []store.Employee {
list := make([]store.Employee, 0)
for _, empl:= range *employees{
if empl.There == true {list = append(list, empl)}
}
return list
}
func ListEmployeesByDept(dept string, deptEmpMap *(map[string]... |
package main
import "time"
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
)
const IssuesURL = "https://api.github.com/search/issues"
type IssuesSearchResult struct {
TotalCount int `json:"total_count"`
Items []*Issue
}
type Issue struct {
Number int
HTMLURL string ... |
// Copyright 2019 Yunion
//
// 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 writi... |
package main
import (
"Round2_two/yep"
"log"
"net/http"
)
func main() {
//路由
//访问前面的路径/ --》执行后面的方法
http.HandleFunc("/", yep.Interesting)
http.HandleFunc("/init", yep.Build_up)
http.HandleFunc("/delete", yep.Delete_one)
http.HandleFunc("/query", yep.Query_one)
http.HandleFunc("/response", yep.Response)
e... |
package _2_defer
import (
"sync"
)
var (
mutex = &sync.Mutex{}
counter int
)
func LockWithDefer() {
mutex.Lock()
defer mutex.Unlock()
doSomething(counter)
doSomethingElse()
}
func LockNoDefer(mutex *sync.Mutex) {
mutex.Lock()
doSomething(counter)
mutex.Unlock()
doSomethingElse()
}
func UseCopy(mutex... |
package number
type BitNumber uint32
func NewBitNumber() *BitNumber {
return new(BitNumber)
}
func (n *BitNumber) Get() uint32 {
return uint32(*n)
}
func (n *BitNumber) Set(i uint32) {
*n = BitNumber(i)
}
func (n *BitNumber) Clear() {
n.Set(0)
}
func (n *BitNumber) Mark(i int) {
*n |= 1 << i
}
func (n *BitN... |
package domain
type ConfigurationRequest struct {
AppName string `json:"appName"`
Namespace string `json:"namespace"`
Data []Configuration `json:"data"`
}
|
package main
import (
"crypto/aes"
"crypto/sha256"
"flag"
"io/ioutil"
"log"
"os"
)
var key = flag.String("k", "", "key: the key used to encrypt/decrypt the message")
var encrypt = flag.Bool("e", false, "encrypt: ecrypt mode (default)")
var decrypt = flag.Bool("d", false, "decrypt: decrypt mode")
var verbose = f... |
// Package kafka provides producer and consumer to work with kafka topics
package kafka
import (
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
// TestIntegrationNewConsumer will be passed only if kafka broker is started on localhost:9092
func TestIntegrationNewConsumer(t *testing.T) {
config := &Config... |
package main
import (
"fmt"
"testing"
)
/*Our assert library*/
func AssertEqual(t *testing.T, message string, item1, item2 interface{}) {
if item1 != item2 {
t.Error("FAILED:", message, "- item1:", item1, "item2:", item2)
} else {
fmt.Println("PASS:", message)
}
}
func AssertNotEqual(t *testing.T, message st... |
package plug
import (
"mqtts/core"
"mqtts/utils"
"strings"
)
// token errors: paho.mqtt.golang@v1.3.4/packets/packets.go
// error types
// unacceptable protocol version
// identifier rejected
// server Unavailable
// bad user name or password
// not Authorized
// network Error
// protocol Violation
func ClientId... |
/*
Implements a console logger for stdout/stderr.
*/
package console
import (
"fmt"
"github.com/rightscale/rlog/common"
"os"
)
// Console logger (type exported for deprecated stdout module but fields are private).
type ConsoleLogger struct {
removeNewlines bool
outputFile *os.File
}
// Creates a logger for ... |
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package lib
import (
"database/sql"
"fmt"
"strings"
"gylib/common"
"gylib/common/datatype"
)
type Mysqlcon struct {
Tablename string
Sql_where string
Sql_order string
Sql_fields string
Sql_limit string
Db_perfix string
Join_arr map[string]string
LastSqltext string
}
/**
初始化结构
*/
func (this... |
package stars
import (
"github.com/faiface/pixel"
"github.com/faiface/pixel/imdraw"
"golang.org/x/image/colornames"
"math"
)
const (
Seed = 0x9d2c5681
)
func Static(imd *imdraw.IMDraw, bounds pixel.Rect) {
imd.Color = colornames.Darkgray
Draw(imd, pixel.ZV, bounds, 4)
imd.Color = colornames.Gray
Draw(imd, p... |
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func SendGetRequest(r *http.Request) (APIResponse, error) {
if CONFIGS.Debug {
log.Printf("SendGetRequest Host:%s,Header:%v,URI:%v\n", r.Host, r.Header, r.URL.RequestURI())
}
var data APIResponse
data.Type = "origin"
client := &http.Client{}
url :... |
package graph
import (
"fmt"
"io/ioutil"
"os"
"testing"
)
func TestLargeGraph(t *testing.T) {
var err error
g := NewWithLossCombined(NewGraph())
g.Iter = 10000
g.Lambda = 1e-8
g.L2 = 1e-3
g.AnnW = 1e4
g.Repw = 1e3
g.DistTargt = 0.1
g.DistTargtW = 10.
for i := 0; i < 80; i++ {
g.Add(0, 0, fmt.Sprintf... |
package iteration
const repeatCount int = 5
// Repeat ...
func Repeat(character string) (repeated string) {
for i := 0; i < repeatCount; i++ {
repeated += "a"
}
return repeated
}
|
package dist
import (
"fmt"
"testing"
)
func Test_Erlang(t *testing.T) {
var numbers []float64
lambda := float64(2)
k := 1
d := ErlangDistribution{
DistributionType: "Erlang",
}
for i := 1; i < 100000; i++ {
n, _ := d.RandVar(k, lambda)
numbers = append(numbers, n)
// fmt.Println(n)
}
m := ArrayM... |
// Copyright 2019 Yunion
//
// 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 writi... |
package main
// Leetcode 457. (medium)
func circularArrayLoop(nums []int) bool {
for i, num := range nums {
if num == 0 {
continue
}
slow, fast := i, nextCircularArrayLoop(i, nums)
for num*nums[fast] > 0 && num*nums[nextCircularArrayLoop(fast, nums)] > 0 {
if slow == fast {
if slow == nextCircularAr... |
package storage
import (
"strings"
"testing"
_ "github.com/lib/pq"
"github.com/spf13/viper"
)
const (
postgresHost = "postgres.HOST"
postgresPort = "postgres.PORT"
postgresUser = "postgres.USER"
postgresPass = "postgres.PASS"
postgresDB = "postgres.DB"
)
func TestConnect(t *testing.T) {
v := viper.New()... |
package traceconfig
import (
"fmt"
"io"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/config"
)
func TraceInit(serviceName string, samplerType string, samplerParam float64) (opentracing.Tracer, io.Closer) {
cfg := &config.Configuration{
ServiceNa... |
package field
import (
"fmt"
"reflect"
"github.com/spf13/cast"
)
// ToInt64SliceE casts an interface to a []int64 type.
func ToInt64SliceE(i interface{}) ([]int64, error) {
if i == nil {
return nil, fmt.Errorf("unable to cast %#v of type %T to []int64", i, i)
}
switch v := i.(type) {
case []int64:
return... |
package app
import (
"github.com/fatmalabidi/bookstore_users_api/controllers/ping"
"github.com/fatmalabidi/bookstore_users_api/controllers/users"
)
func mapUrls() {
router.GET("/ping", ping.Ping)
router.POST("/users", users.CreateUser)
router.GET("/users:userID", users.GetUser)
router.PUT("/users:userID", user... |
package internal
import (
"framework/cluster"
"framework/gate"
"framework/log"
"proto/gameproto"
"github.com/golang/protobuf/proto"
)
//GameMsgHandler 消息handler
type GameMsgHandler func([]interface{})
var (
//Game模块消息处理
gameMsgHandlers = make(map[gameproto.MsgID]GameMsgHandler)
)
func init() {
//集群相关消息
re... |
package box
import (
"cloud-box-backend/source/meta/models"
"github.com/jmoiron/sqlx"
)
const (
getAccountBoxesQuery = `select trim(tunnel_domain) tunnel_domain, trim(uuid) uuid from box where account_hash = $1`
setAccountHashToBoxQuery = `update box set account_hash = $1 where uuid = $2`
addBoxQuery = `
inse... |
package main
import (
"fmt"
)
func main() {
dd := make(map[string]int)
dd["x"] = 1
dd["y"] = 2
dd["z"] = 3
fmt.Println(dd)
fmt.Println(dd["x"])
delete(dd, "y")
fmt.Println(dd)
_, re := dd["y"]
fmt.Println(re)
hh := map[string]int{
"aa": 2,
"bb": 3,
}
fmt.Println(hh["bb"])
for k, nn := range h... |
package roleplay
import (
"bytes"
"fmt"
)
func GetCities(ctx Context) {
buffer := bytes.NewBufferString("Cidades disponíveis: \n")
buffer.WriteString("```")
for _, city := range ctx.Config.GetEnvConfStringSlice("cities") {
msg := fmt.Sprintf("- %s \n", city)
buffer.WriteString(msg)
}
buffer.WriteString("`... |
package util
import (
"fmt"
"os"
"k8s.io/apimachinery/pkg/util/yaml"
)
func BindJsonOrYaml(filePath string, obj interface{}) error {
reader, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("Failed opening file %s due to %s", filePath, err)
}
err = yaml.NewYAMLOrJSONDecoder(reader, 128).Decode(obj... |
// Copyright (C) 2019 Michael J. Fromberger. All Rights Reserved.
package otp_test
import (
"testing"
"github.com/creachadair/otp"
)
var googleTests = []struct {
key string
counter uint64
otp string
}{
// Manually generated compatibility test vectors for Google authenticator.
//
// To verify these t... |
package tcp
import (
"sync"
)
type MsgQueue struct {
list []interface{}
listGuard sync.Mutex
listCond *sync.Cond
}
func (self *MsgQueue) Add(msg interface{}) {
self.listGuard.Lock()
self.list = append(self.list, msg)
self.listGuard.Unlock()
self.listCond.Signal()
}
func (self *MsgQueue) Reset() {
se... |
package main
import "fmt"
// func main() {
// done := make(chan bool)
// values := []string{"a", "b", "c"}
// for _, v := range values {
// go func() {
// fmt.Println(v)
// done <- true
// }()
// }
// // wait for all goroutines to complete before exiting
/... |
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "eic",
Short: "Ensure import comment",
Run: rootRun,
}
var (
_dirpath string
_filepath string
_dryrun bool
)
func init() {
rootCmd.Flags().StringVarP(&_dirpath, "dir", "d", "", "transfer directory")
roo... |
package main
import "fmt"
func main() {
var x string = "Hello, world"
var y string
y = "Hello, world"
fmt.Println(x == y)
z := "Hello, world"
var h = 5
}
|
package manifestsecrets
import (
"log"
"github.com/pivotal-cf/on-demand-service-broker/boshdirector"
"github.com/pivotal-cf/on-demand-service-broker/broker"
)
type NoopSecretManager struct{}
func (r *NoopSecretManager) ResolveManifestSecrets(manifest []byte, deploymentVariables []boshdirector.Variable, logger *l... |
package Sieve
import (
"reflect"
"testing"
)
func TestSieve(t *testing.T) {
var tests = []struct {
n int
want []int
}{
{25, []int{2, 3, 5, 7, 11, 13, 17, 19, 23}},
{3, []int{2, 3}},
{9, []int{2, 3, 5, 7, 8}},
}
for _, test := range tests {
got := Sieve(test.n)
if !reflect.DeepEqual(got, test.... |
/*
* Insert an image to a PDF file.
*
* Adds image to a specific page of a PDF. xPos and yPos define the upper left corner of the image location, and width
* is the width of the image in PDF coordinates (height/width ratio is maintained).
*
* Example go run pdf_add_image_to_page.go /tmp/input.pdf 1 /tmp/image.jp... |
package algorithms
import "math/big"
type Sieve struct {
internalBaseStringRef string
internalBigIntRef *big.Int
}
// Takes a new base 10 string of integers to sift through to factorize. Will use all available processors.
func NewQuadraticSieve(s string) *Sieve {
i := new(big.Int)
i.SetString(s, 10)
return &Sie... |
package control
import (
"encoding/json"
"github.com/PuerkitoBio/goquery"
"github.com/playgrunge/monicore/core/api"
"github.com/playgrunge/monicore/core/scrape"
"log"
"net/http"
"regexp"
"strings"
)
type HydroApi struct {
api.ApiRequest
scrape.ScrapeRequest
}
func (h *HydroApi) Scrape(doc *goquery.Document... |
/**
* 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 sync
import (
"testing"
"time"
"github.com/multivactech/MultiVAC/configs/config"
"github.com/multivactech/MultiVAC/m... |
package common
import (
"fmt"
"image"
)
type Bus interface {
Read(uint16) uint8
Write(uint16, uint8)
}
type Ticker interface {
OnTick()
}
type Router interface {
AddMapping(uint16, uint16, Bus, bool)
}
type Cartridge interface {
SetCPURouter(Router)
SetPPURouter(Router)
IRQ()
SetIRQ(func())
}
type Compl... |
package mapper
import (
"bytes"
"fmt"
"github.com/kataras/golog"
"goiris/admin/app/web/vo"
"goiris/common"
"goiris/common/model"
"goiris/common/storage"
)
type RoleMapper struct {}
func (rm *RoleMapper) Insert(vo *vo.AcceptRoleVO) error {
return rm.createOrUpdate(vo, true)
}
func (rm *RoleMapper) FindOne(co... |
package main
import (
"fmt"
"github.com/FactomProject/factom"
"time"
)
var ESKey string = "Es3gZoQbNd2p2nDDRtULkUaneoSJY1WTCQ7LSyNqHWZ2UkttuS1o"
var FSKey string = "Fs2DNirmGDtnAZGXqca3XHkukTNMxoMGFFQxFA3bAjJnKzzsZBMH"
func main() {
factom.SetFactomdServer("localhost:8088")
f... |
/**
* @description: 切片初始化
* @author Administrator
* @date 2020/7/11 0011 10:44
*/
package main
import "fmt"
func main() {
//声名切片类型
var a []string //声明一个字符串切片
var b = []int{} //生命一个整形的切片并初始化
var c = []bool{true, false} //生命一个bool型的切片并初始化
//var d = []bool{true,false} //生命一个bool型的切片并初始化... |
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
)
var (
ca = "/tmp/myCA.pem"
cert = "/tmp/myCA.cert"
key = "/tmp/myCA.key"
)
func main() {
go HttpServer()
HttpClient()
}
func HttpServer() {
http.HandleFunc("/hello", HelloServer)
if err := http.ListenAndServeTLS(":9191", ... |
package main
import (
"net/http"
"fmt"
"os"
)
func main() {
fileServer := http.FileServer(http.Dir("./www"))
err := http.ListenAndServe(":8000", fileServer)
checkError(1, err)
}
func checkError(code int, err error) {
if err != nil {
fmt.Println("error")
os.Exit(code)
}
}
|
package views
import (
"net/http"
"satellity/internal/models"
"time"
"github.com/decred/base58"
"github.com/gofrs/uuid"
)
// ProductView is the response body of product
type ProductView struct {
Type string `json:"type"`
ProductID string `json:"product_id"`
ShortID string `json:"short_id"`... |
// Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package example
import (
"context"
"time"
"chromiumos/tast/local/a11y"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/browser"
"chromiumos/tast/local/ch... |
package handlers
import (
"github.com/benbarron/golang-auth-server/services"
"github.com/gofiber/fiber/v2"
)
type AuthRoutes struct {
AuthService *services.AuthService
Logger *services.LoggingService
LocalsService *services.LocalsStorage
JwtService *services.JwtService
}
type LoginRequest struct {
Username s... |
package leetcode
import "sort"
func searchMatrix(matrix [][]int, target int) bool {
m, n := len(matrix), len(matrix[0])
x, y := 0, n-1
for x < m && y >= 0 {
if matrix[x][y] == target {
return true
}
if matrix[x][y] > target {
y--
} else {
x++
}
}
return false
}
func searchMatrix1(matrix [][]... |
// 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-2020 Datadog, Inc.
package secrets
import (
"bytes"
"context"
"encoding/json"
"errors"
"f... |
package util
import (
"encoding/binary"
"fmt"
"hash/fnv"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
v1alpha1 "github.com/jetstack/navigator/pkg/apis/navigator/v1alpha1"
hashutil "github.com/jetstack/navigator/pkg/util/hash"
)
const (
NodePoolNameLabelKey = "navigator.jetstack.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.