text stringlengths 11 4.05M |
|---|
package common
import (
"fmt"
"os"
"path"
"runtime"
"strings"
)
// These vars are set by the build script in scripts/build_partner_tools.rb
var (
Version string
BuildDate string
GitHash string
License string
WikiUrl string
RepoUrl string
Email string
)
// Current Pharos API Version
const Ph... |
package reflection
import "reflect"
func PopulateFunction(readerFuncType reflect.Type, readerFuncPtrValue reflect.Value, reflectedFunc func([]reflect.Value) []reflect.Value) {
newFuncValue := reflect.MakeFunc(readerFuncType, reflectedFunc)
readerFuncPtrValue.Elem().Set(newFuncValue)
}
|
package raftkv
import (
"bytes"
"encoding/gob"
"labrpc"
"log"
"raft"
"sync"
"time"
)
const Debug = -3
func DPrintf(level int, format string, a ...interface{}) (n int, err error) {
if Debug > level {
log.Printf(format, a...)
}
return
}
type Op struct {
// Your definitions here.
// Field names must star... |
package routes
import (
"net/http"
"ocg-be/controller"
"ocg-be/middlewares"
"github.com/gorilla/mux"
)
func Setup(r *mux.Router) {
routeAdmin := r.PathPrefix("/admin").Subrouter()
routeAdmin.Use(middlewares.IsAuthorized)
routesPublic(r)
routesAdmin(routeAdmin)
}
func routesPublic(r *mux.Router) {
//api-p... |
package router
import (
"fmt"
"io/ioutil"
"log"
"time"
"github.com/AsynkronIT/protoactor-go/actor"
"github.com/stretchr/testify/mock"
)
var nilPID *actor.PID
func init() {
// discard all logging in tests
log.SetOutput(ioutil.Discard)
}
func spawnMockProcess(name string) (*actor.PID, *mockProcess) {
p := &... |
package _13_Roman_to_Integer
import "testing"
func TestRomanToInt(t *testing.T) {
var (
roman string
)
roman = "III"
if num := romanToInt(roman); num != 3 {
t.Errorf("wrong num with %d", num)
}
}
|
package db
import (
"context"
"crypto/rand"
"crypto/sha1"
"errors"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"log"
)
const INSERT_USER = `INSERT INTO USERS(aud, email, password, salt, role)
VALUES ( $1,$2, $3, $4, $5 )`
const CHECK_AUD = `SELECT COUNT(*)
FROM USE... |
package models
import (
"errors"
"fmt"
"os"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres" //postgres driver
"github.com/joho/godotenv"
)
var conn *gorm.DB
func init() {
fmt.Println("connecting to database...")
err := godotenv.Load("conf.env")
if err != nil {
LogError(errors.New("e... |
package domain
import "time"
//AuthTokenResponse ...
type AuthTokenResponse struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
|
package lintcode
/**
* Definition for a binary tree node.
*
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
var treeMap map[int]int
/**
* @param inOrder: A list of integers that inorder traversal of a tree
* @param preOrder: A list of integers that preorder traversal of a tree
* @retur... |
// connected clients |
package controllers
import (
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
corev1 "k8s.io/api/core/v1"
)
func Test_podsStatusState_waitingOnPods(t *testing.T) {
type fields struct {
expectedRunningPods int
readyCount int
notReadyCount int
podRevisions []int
podErrors ... |
package api
import (
"encoding/json"
"net/http"
"testing"
"github.com/MarcelCode/ROWA/src/db"
"github.com/stretchr/testify/assert"
)
func TestPlantHandler(t *testing.T) {
mockStore := db.InitMockStore()
mockStore.On("Plant", &db.PlantType{}).Return(1, nil).Once()
c, rec := InitialiseTestServer(http.MethodPo... |
package inmemory
import (
"context"
"fmt"
"net"
"sort"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/test/bufconn"
pb "github.com/pomerium/... |
package mumgo
import (
"crypto/tls"
"fmt"
)
type Config struct {
Username string
Password string
Host string
Port int
CertFile string
KeyFile string
}
var zeroCnf, defaultCnf = Config{}, Config{
Username: "mumgo",
Host: "localhost",
Port: 64738,
CertFile: "~/.mumgo/mumgo.crt",
KeyFile: ... |
package main
import (
"fmt"
"github.com/jnewmano/advent2020/input"
"github.com/jnewmano/advent2020/output"
)
func main() {
sum := parta()
fmt.Println(sum)
}
func parta() interface{} {
// input.SetRaw(raw)
// var things = input.Load()
// var things = input.LoadSliceSliceString("")
var things = input.LoadSl... |
package main
import (
"flag"
"log"
"net/http"
"time"
"github.com/hoenn/ynab-metrics/pkg/accounts"
"github.com/hoenn/ynab-metrics/pkg/budgets"
"github.com/hoenn/ynab-metrics/pkg/categories"
"github.com/hoenn/ynab-metrics/pkg/config"
"github.com/hoenn/ynab-metrics/pkg/ratelimit"
"github.com/hoenn/ynab-metrics... |
package server
import (
"encoding/json"
"fmt"
"net/http"
"github.com/bryanl/dolb/entity"
"github.com/bryanl/dolb/kvs"
"github.com/bryanl/dolb/pkg/app"
"github.com/bryanl/dolb/pkg/lbfactory"
"github.com/bryanl/dolb/service"
"github.com/gorilla/mux"
"golang.org/x/net/context"
)
// LoadBalancerService is a s... |
package saver
import (
"fmt"
"github.com/ozonva/ova-track-api/internal/flusher"
"github.com/ozonva/ova-track-api/internal/utils"
"time"
)
type BufferedSaver struct {
flusher flusher.Flusher
bufferedTracks []utils.Track
}
func (bs * BufferedSaver) SaveToBuffer (tracks []utils.Track){
bs.FlushBuffer()
bs.buffe... |
package main
import (
"github.com/dgraph-io/badger"
"github.com/hashicorp/raft"
)
type BadgerStore struct {
store *badger.DB
}
type Options struct{
Path string
StorageOptions *badger.Options
}
// Create new badger store with default options
func NewStore(path string)(*BadgerStore, error){
return New(Options{P... |
package spot
import (
"testing"
"github.com/stretchr/testify/assert"
)
// TestNewRoute tests NewRoute method
func TestNewRoute(t *testing.T) {
tt := map[string]struct {
name string
level string
points int
information string
expectedRes Route
}{
"nominal case": {name: "Aline la malin... |
package main
func main() {
x := []int{100, 101, 102}
for k, v := range x {
println(k, ":", v)
}
}
|
/*
* @Descripttion:
* @Author: lly
* @Date: 2021-05-28 22:44:51
* @LastEditors: lly
* @LastEditTime: 2021-05-31 01:36:23
*/
package main
import (
"context"
"fmt"
"pb/user"
"github.com/micro/micro/v3/service"
)
const (
Address = "127.0.0.1:8899"
)
func main() {
// create a new service
service := servi... |
// Copyright 2017 Gruppe 12 IS-105. All rights reserved.
package main
import (
"fmt"
"net"
"./Crypt"
"bufio"
)
var key = Crypt.Randomkey()
func main() {
p := make([]byte, 2048)
conn, err := net.Dial("udp", "158.37.63.180:8009")
if err != nil {
fmt.Printf("Some error %v", err)
return
}
var msg, _ = Cry... |
package reconciler
import (
"context"
"testing"
"time"
"github.com/operator-framework/operator-lifecycle-manager/pkg/controller/install"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apima... |
package main
import (
"golab/packages-example/net/tcp_sticky_package/proto"
"log"
"net"
)
func main() {
conn, err := net.Dial("tcp", ":8080")
if err != nil {
log.Fatalf("Dial error:%v\n", err)
}
defer conn.Close()
for i := 0; i < 20; i++ {
msg := `Hello Golang`
data, err := proto.Encode(msg)
if err !... |
package gocrypt
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
)
//FillFiles ...
func FillFiles(path string, crypttype string) []string {
var files []string
root := path
err := filepath.Walk(root, func(path string, info ... |
package main
import (
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
resp, err := http.PostForm("http://www.vipidea.dd/api/v1/login", url.Values{"username": {"18611439826"}, "password": {"111111"}})
if err != nil {
log.Fatal(err)
}
var buf []byte
defer resp.Body.Close()
n, err := resp.Body.Read(buf)
... |
package http_handlers
import (
"github.com/go-martini/martini"
"net/http"
)
func GetSession() func(
martini.Context,
martini.Params,
http.ResponseWriter,
*http.Request,
) {
return HttpHandler(
[]string{
AUTH_REQUIRED,
},
func(h *Http) {
h.SetResponse(
map[string]interface{}{
"key": h.se... |
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
)
type Middleware func(http.HandlerFunc) http.HandlerFunc
type Error struct {
Message string `json:"message"`
Description string `json:"description"`
}
func applyMiddleware(h http.HandlerFunc, m ...... |
package hello
var BuildNum = "undefined"
|
package p2p
import (
"context"
)
type Context struct {
context.Context
Cancel context.CancelFunc
}
func newContext(context context.Context, cancel context.CancelFunc) Context {
return Context{
Context: context,
Cancel: cancel,
}
}
|
package transport
import (
"github.com/yekhlakov/gojsonrpc/common"
)
type Http struct {
Logged
PreProcessingStages []common.Stage
PostProcessingStages []common.Stage
}
func (t *Http) PerformRequest(rc *common.RequestContext) error {
rc.ApplyPipeline(&t.PreProcessingStages)
// TODO: http processing
rc.ApplyP... |
package main
import "fmt"
type Person struct {
First string
Last string
Age int
Phone Phone
}
type Phone struct {
AreaCode string
Prefix string
Suffix string
}
func main() {
pt := struct {
X int
Y int
}{
X: 10,
Y: 20,
}
fmt.Println(pt)
// p := Person{
// First: "John",
// Last: "Doe"... |
package main
import (
"fmt"
"github.com/igor-ferreira-almeida/goarea"
)
func main() {
fmt.Println(goarea.Circle(6.0))
}
|
package decoder
import (
"encoding/json"
"errors"
"time"
"github.com/Tanibox/tania-core/src/growth/storage"
"github.com/mitchellh/mapstructure"
)
type CropActivityTypeWrapper InterfaceWrapper
func (w *CropActivityTypeWrapper) UnmarshalJSON(b []byte) error {
wrapper := InterfaceWrapper{}
err := json.Unmarsha... |
/*
Copyright © 2020 David Hu <coolbor@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... |
package internal
import (
"fmt"
"io/ioutil"
"os/exec"
"strings"
)
type Terraform struct {
init *exec.Cmd
defaultArgs []string
workdir string
states string
InitError *strings.Builder
}
func CreateTerraform(workdir string, conf string) *Terraform {
terraform := new(Terraform)
terraform.InitError = new(str... |
package main
import "fmt"
type vertex struct {
lat, lon float64
}
func main() {
m := make(map[string]vertex)
m["Nokia Bell Labs"] = vertex{
40.68433, -74.39967,
}
fmt.Println(m["Nokia Bell Labs"])
}
|
package rest
import (
"net/http"
"github.com/parsaakbari1209/Chatapp-oauth-api/domain"
"github.com/gin-gonic/gin"
"github.com/parsaakbari1209/Chatapp-oauth-api/service"
"github.com/parsaakbari1209/Chatapp-oauth-api/utils"
)
var (
s = service.NewOAuth()
)
func create(c *gin.Context) {
// 1. Get user_id from ... |
package db
import (
"database/sql"
_ "fmt"
_ "github.com/go-sql-driver/mysql"
)
type mySQLDB struct {
db *sql.DB
}
func (d *mySQLDB) InitDB(params map[string]string) {
db, err := sql.Open("mysql", params["Username"]+":" + params["Password"] + "@tcp(" + params["Host"] + ")/"+params["Db"])
if er... |
package auth0
import (
"regexp"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
auth0 "github.com/yieldr/go-auth0"
"github.com/yieldr/go-auth0/management"
)
var ruleNameRegexp = regexp.MustCompile("^[^\\s-][\\w -]+[^\\s-]$")
func newRule() *schema.Resource {
r... |
package controller
import (
"github.com/therecipe/qt/core"
_ "github.com/therecipe/qt/internal/examples/showcases/wallet/files/dialog/controller"
)
var ButtonController *buttonController
type buttonController struct {
core.QObject
_ func() `constructor:"init"`
_ func(string) `signal:"clicked,-... |
package main
import (
"fmt"
"net/http"
)
func handleRoot(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hi there!!!")
}
func main() {
http.HandleFunc("/", handleRoot)
http.ListenAndServe(":3001", nil)
}
|
/*
It can be proven that there's exactly one string of infinite length that remain same after base64 encoding Vm0wd2QyUXlVWGxWV0d4V1YwZ...
Given a position, output the character on that position.
Your program would be run on AMD Ryzen 5 5500U@4GHz given 4GB memory and 1 minute (may decrease if RAM turns out to be ha... |
package main
import (
ec "crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"fmt"
"io"
"log"
)
/*
type Taction struct {
PrivateKey1 string //Payer
PrivateKey2 string //Payee
Amount float64
Timestamp string
}
*/
//yeah.. ill do something more secure later
//const privatekey = "5DB0633DDD... |
package leetcode
/**
* LeetCode T146. LRU缓存机制
* https://leetcode-cn.com/problems/lru-cache/
*
* 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。
* 它应该支持以下操作: 获取数据 get 和 写入数据 put 。
*/
// 参考题解 1:https://mp.weixin.qq.com/s/Q8Mg_EhDvPVRIaDv6m0Nlg
// 参考题解 2:https://leetcode-cn.com/problems/lru-cache/solution/lru-ce-lue-xiang... |
package ntp
import (
"encoding/binary"
"errors"
"fmt"
"net"
"time"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/logging"
)
// NewProvider instantiate a ntp provider given a configuration.
func NewProvider(config *schema.NTP) *Provider {
return &Pro... |
package lnksutils
import "syscall"
// UnameMachine return the `uname -m"
func UnameMachine() string {
var uname syscall.Utsname
syscall.Uname(&uname)
arr := uname.Machine[:]
b := make([]byte, 0, len(arr))
for _, v := range arr {
if v == 0x00 {
break
}
b = append(b, byte(v))
}
return string(b)
}
|
package main
import (
"fmt"
"strconv"
)
/*
an arguments passing tester
*/
func main() {
var nums=[]int{0,1,2}
i := 0
fmt.Printf("address of int : %p\n", &i)
fmt.Printf("value of int : %d\n",i)
updatePassingInt(i)
fmt.Printf("address of int : %p\n", &i)
fmt.Printf("value of int : %d\n",i)
fmt.Println("----... |
package stream
import (
"context"
"reflect"
)
func MergeChannels(ctx context.Context, bufferLen int, inCh ...chan Sample) chan []Sample {
mergedCh := make(chan []Sample, bufferLen)
go func() {
for {
v := make([]Sample, len(inCh))
selectMap := make([]int, len(inCh))
cases := make([]reflect.SelectCase, l... |
package main
import (
tl "github.com/JoelOtter/termloop"
)
// Bullet represents a bullet fired from the Ship
type Bullet struct {
*tl.Entity
IsTainted bool // If tainted, object will be removed during the next draw cycle
}
func newBullet(startX int, startY int) *Bullet {
const width, height = 1, 1
// Create th... |
package main
import "fmt"
type person struct {
firstName string
lastName string
}
type secretAgent struct {
person
ltk bool
}
type human interface {
speak()
}
func bar(h human) {
switch h.(type) {
case person:
fmt.Println("Person was passed through bar")
case secretAgent:
fmt.Println("SecretAgent was... |
package yadisk
import (
"net/http"
"net/url"
"strings"
)
// Get the status of an asynchronous operation.
func (yad *yandexDisk) GetOperationStatus(operationID string, fields []string) (s *OperationStatus, e error) {
values := url.Values{}
values.Add("fields", strings.Join(fields, ","))
req, e := yad.client.req... |
package main
import (
"encoding/json"
"fmt"
"github.com/hashicorp/go-version"
"github.com/pkg/errors"
"io"
"io/ioutil"
"net/http"
"os"
"sort"
)
const terraformReleaseUrl = "https://releases.hashicorp.com/terraform/index.json"
type terraformRelease struct {
Name string `json:"name"`
Versions map[string... |
package resources
import (
"github.com/caos/orbos/mntr"
"github.com/caos/orbos/pkg/kubernetes"
"github.com/caos/orbos/pkg/tree"
"github.com/pkg/errors"
)
type AdaptFuncToEnsure func(monitor mntr.Monitor, desired *tree.Tree, current *tree.Tree) (QueryFunc, error)
type AdaptFuncToDelete func(monitor mntr.Monitor, d... |
// shared structs between client wrappers and server
package rpc
// aka namespace for GO RPC
type PPTRpc string
// empty args (nil isn't good)
type EmptyArgs struct{}
// arg to describe remove node params
type RemoveNodeArgs struct {
// Host to remove
Host string
}
// arg to describe status node params
type GetSt... |
package main
import (
"github.com/jinxing3114/xtrie"
)
//创建XTrie
var XT = new(xtrie.XTrie)
//基本配置信息
var storeFile,dictFile = "data/dat.data", "data/darts.txt"
/**
入口函数
*/
func main(){
XT.InitHandle(storeFile, dictFile)
//example()
//开始监听请求
startServe(":8888")
}
/**
例子
*/
func example(){
//index, level, err ... |
package pocket2rm
// APIOriginPocket contains the destination
const APIOriginPocket = "pocket"
// APIOriginMercury is the origin host for the Mercury API
const APIOriginMercury = "mercury"
// APIOriginRemarkable is the origin host for the reMarkable API
const APIOriginRemarkable = "remarkable"
// APIOrigin maps eac... |
package db
import (
"strconv"
"strings"
"cloud.google.com/go/datastore"
"github.com/steam-authority/steam-authority/helpers"
)
type PlayerApp struct {
PlayerID int64 `datastore:"player_id"`
AppID int `datastore:"app_id,noindex"`
AppName string `datastore:"app_name"`
AppIcon string... |
package router
import (
"github.com/bearname/videohost/internal/common/infrarstructure/profile"
"github.com/bearname/videohost/internal/common/infrarstructure/transport/handler"
"github.com/bearname/videohost/internal/common/infrarstructure/transport/middleware"
"github.com/bearname/videohost/internal/stream-servi... |
package git
/*
#include <git2.h>
*/
import "C"
import (
"runtime"
)
type CherrypickOptions struct {
Mainline uint
MergeOptions MergeOptions
CheckoutOptions CheckoutOptions
}
func cherrypickOptionsFromC(c *C.git_cherrypick_options) CherrypickOptions {
opts := CherrypickOptions{
Mainline: uint(... |
package empop
import "interfaces/slcalc"
// EmployeeOperations interface
type EmployeeOperations interface {
slcalc.LeaveCalculator
slcalc.SalaryCalculator
} |
package aoc2020
import (
"fmt"
"strconv"
"strings"
aoc "github.com/janreggie/aoc/internal"
"github.com/pkg/errors"
)
// mask represents a bitmask that can force bits to be zero or one.
type mask struct {
ones uint64
zeroes uint64
}
// newMask generates a mask object from a string of length 32
func newMask(... |
package scraper
type (
Game struct {
ID string `json:"id"`
BasePrice float32 `json:"base_price"`
PricesURLs []price `json:"prices_urls"`
}
price struct {
From string `json:"from"`
URL string `json:"url"`
}
)
|
package runner
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
"github.com/dkorittki/loago/internal/pkg/worker/executor/browser"
"github.com/rs/zerolog/log"
)
const (
// CacheDirName is the name of the global directory used for runne... |
// Command whenchange monitors for changes on files, directories,
// and optionally watching sub-directories, and when a change
// happens, executes a command.
//
//
// Installation
//
// go get ronoaldo.gopkg.net/whenchange
//
//
// Usage
//
// whenchange -p source.go go build
//
// The above command will moni... |
package main
import (
"log"
"os/exec"
"runtime"
"github.com/atotto/clipboard"
"github.com/jroimartin/gocui"
"github.com/ryo-ma/coronaui/lib"
"github.com/ryo-ma/coronaui/ui"
)
var client *lib.Client
var countryPanel *ui.CountryPanel
var textPanel *ui.TextPanel
var statusPanel *ui.StatusPanel
var searchPanel *u... |
package lambdas_test
import (
"errors"
"testing"
"github.com/life4/genesis/lambdas"
"github.com/matryer/is"
)
func panics(is *is.I, f func()) {
defer func() {
r := recover()
is.True(r != nil)
}()
f()
}
func TestMust(t *testing.T) {
is := is.New(t)
f := func() (int, error) { return 13, nil }
res := lam... |
package main
import "fmt"
func RequestEbay(config conf) []string {
fmt.Println("Checking ebay ...")
results := []string{"www.ebay.de/0", "www.ebay.de/1"}
return results
}
|
package isaac
const (
eventsBasePath = "/api/v1/events"
)
type EventsService interface {
Add(NewEvent) (Event, error)
Get(ID) (Event, error)
List() ([]Event, error)
Remove(Event) error
Update(Event) (Event, error)
}
type EventsServiceOp struct {
client *Client
}
type NewEvent struct {
DisplayName string `js... |
package cmd
import (
"context"
"github.com/abilioesteves/metrics-generator/generator"
"github.com/abilioesteves/metrics-generator/hook"
"github.com/abilioesteves/metrics-generator/metrics"
"github.com/labbsr0x/goh/gohcmd"
)
func Run() {
ctx, cancel := context.WithCancel(context.Background())
g := generator.Ne... |
package main
import (
"context"
"encoding/json"
"io/ioutil"
"log"
"os"
"os/signal"
"strings"
"sync"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
)
func main() {
if len(os.Args) != 2 {
log.Fatalln("provide a url or JSON file to download")
}
ct... |
// Copyright 2016-2019 Alex Stocks, Wongoo
//
// 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 ... |
/*
Copyright 2018-2020, Arm Limited and affiliates.
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 main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"github.com/apex/log"
nginxFileReader "github.com/massmutual/go-filereader/nginx-filereader"
"github.com/newrelic/infra-integrations-sdk/data/metric"
"github.com/newrelic/infra-integrations-sdk/integration"
)
func readFile(file *... |
package main
import (
"fmt"
)
type Person struct {
name string
age uint
}
func main() {
var john Person
john.name = "John"
john.age = 23
tom := Person{
age: 31,
name: "Tom",
}
jane := Person{"Jane", 42}
mike := &Person{
name: "Mike",
age: 36,
}
fmt.Println(john, tom, jane, mike)
}
|
// +build !race
package dsstore
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/square/p2/pkg/audit"
"github.com/square/p2/pkg/logging"
"github.com/square/p2/pkg/manifest"
"github.com/square/p2/pkg/store/consul/auditlogstore"
"github.com/square/p2/pkg/store/consul/consulutil"
"github.com/sq... |
package internal
import (
"log"
"encoding/json"
"strings"
"strconv"
)
func CheckErrWithLog(err error, msg string) {
logger := log.Logger{}
if !CheckErr(err, msg) {
logger.Println(err)
}
}
func IndentedJson(v interface{}) []byte {
indentedJson, err := json.MarshalIndent(v, "", "\t")
CheckErr(err, "couldn'... |
package messaging
import (
lib "github.com/k8guard/k8guardlibs"
msg "github.com/k8guard/k8guardlibs/messaging"
"github.com/k8guard/k8guardlibs/messaging/types"
)
var MessageProducer types.MessageProducer
func InitBroker() {
s, err := msg.CreateMessageProducer(
types.MessageBrokerType(lib.Cfg.MessageBroker), ty... |
package crawler
import (
"errors"
"fmt"
"log"
"net/http"
"path/filepath"
"github.com/PuerkitoBio/goquery"
)
// LinkScrapeForHuobi .
func LinkScrapeForHuobi() ([]string, error) {
s := make([]string, 0)
doc, err := goquery.NewDocument("https://github.com/huobiapi/API_Docs/wiki")
if err != nil {
log.Println(... |
package lottery
// Config 抽奖程序配置
type Config struct {
PredictPerson int
MaxOnPerson int
Prizes map[int] Prize
} |
package pricingengine
// GeneratePricingRequest is used for generate pricing requests, it holds the
// inputs that are used to provide pricing for a given user.
type GeneratePricingRequest struct {
// TODO: populate me!
}
// GeneratePricingResponse - TODO: please document me :)
type GeneratePricingResponse struct {
... |
// An example of the pipeline pattern that I wrote as part of a training course.
package main
import (
"math/rand"
"time"
"golang.org/x/text/message"
)
func main() {
p := message.NewPrinter(message.MatchLanguage("en"))
for x := range pipe(gen(20, 100)) {
p.Printf("%42d\n", x)
}
// // Test the limits of wh... |
package md5_test
import (
"testing"
"github.com/danielfmelo/myhttphash/hash/md5"
)
func TestCreateMD5(t *testing.T) {
m := md5.New()
data := []byte("to.be.hashed")
expectedMd5 := "ff0c1b127f5e1170afb5d053b295d561"
result := m.CreateHash(data)
if result != expectedMd5 {
t.Errorf("expected %s but got %s", exp... |
package asset
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
type persistAsset struct{}
func (a *persistAsset) Name() string {
return "persist-asset"
}
func (a *persistAsset) Dependencies() []Asset {
return []Asset{}
}
func (a *persistAsset) Generate(Parents) error {
... |
package ranges
import "fmt"
func main() {
// Range on array
arr := [4]string{"AMar", "Jyoti", "Rekha"}
for k, v := range arr {
fmt.Println("range on array key: ", k, " value: ", v)
}
// Range on slice
slc := []string{"x", "y", "z"}
for k, v := range slc {
fmt.Println("key: ", k, " value: ", v)
}
// Ra... |
package main
var name = "John"
func init() {
println("Hi! " + name)
}
func main() {
println("Hello! " + name)
}
|
package main
import (
"log"
"github.com/sf1/go-card/smartcard"
)
var (
cardCtx *smartcard.Context
reader *smartcard.Reader
card *smartcard.Card
err error
)
func connectToCard() error {
cardCtx, err = smartcard.EstablishContext()
if err != nil {
return err
}
log.Println("Awaiting a card to be pr... |
package Interpreter
import "strings"
type Expression interface {
Interpret(variables map[string]Expression) int
}
type Integer struct {
interger int
}
func (n *Integer)Interpret(variables map[string]Expression) int {
return n.interger
}
type Plus struct {
leftOperand Expression
rightOperand Expression
}
func... |
package api
import (
"fmt"
"time"
)
//go:generate msgp
type LocalGetSet interface {
LocalGet(key []byte, includeValue bool) (ki *KeyInv, err error)
LocalSet(ki *KeyInv) error
}
type Peerface interface {
LocalGetSet
BcastGet(key []byte, includeValue bool, timeout time.Duration, who string) (kis []*KeyInv, err ... |
package db
import (
"github.com/pkg/errors"
m "github.com/thedevelopnik/netplan/pkg/models"
)
// VPC actions
func (r npRepo) CreateVPC(vpc *m.VPC) error {
// create in the db
if err := r.db.Create(&vpc).Error; err != nil {
return err
}
return nil
}
func (r npRepo) UpdateVPC(vpc *m.VPC) (*m.VPC, error) {
// ... |
package pkg
import "fmt"
// X ...
var X = "Hello World"
// Main will print stuff to stdout
func Main() {
fmt.Printf("%+v\n", X)
}
// Hello will return a string
func Hello() string {
return X
}
|
// Copyright 2019-2023 The sakuracloud_exporter 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 appl... |
package concurrent
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
// 生产者
func Producer(factor int, out chan<- int) {
for i := 0; ; i++ {
out <- i * factor
}
}
// 消费者
func Consumer(in <-chan int) {
for v := range in {
fmt.Println(v)
}
}
func main0() {
ch := make(chan int, 64)
go Producer(3, ch)
g... |
package styles
import (
//"data-manager/types"
"grm-service/common"
"github.com/emicklei/go-restful"
api "github.com/emicklei/go-restful-openapi"
"grm-service/geoserver"
. "grm-service/util"
"data-manager/dbcentral/etcd"
"data-manager/dbcentral/pg"
)
type StyleSvc struct {
SysDB *pg.SystemDB
DynamicD... |
package gstypes
type GSArrayDSE struct {
array GSArrayGeneric
}
func (arr *GSArrayDSE) Push(element DataStoreElement) {
arr.array.Push(element)
}
func (arr *GSArrayDSE) Empty() bool {
return arr.array.Empty()
}
func (arr *GSArrayDSE) Length() int {
return arr.array.Length()
}
func (arr *GSArrayDSE) Get(idx int... |
package api
import (
"InkaTry/warehouse-storage-be/internal/http/admin/dtos"
"InkaTry/warehouse-storage-be/internal/pkg/http/responder"
"context"
"net/http"
)
func ListWarehouses(handlerfunc func(ctx context.Context) (*dtos.ListWareshousesResponse, error)) http.HandlerFunc {
return func(w http.ResponseWriter, r ... |
/*
Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.
A string is represented by an array if the array elements concatenated in order forms the string.
Example 1:
Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
Output: true
Explanation:
word1 repre... |
package main
import (
"bufio"
"fmt"
"os"
"runtime"
"github.com/goldeneggg/ipcl/lib/parser"
"github.com/goldeneggg/ipcl/lib/writer"
"github.com/jessevdk/go-flags"
)
const (
Version = "0.3.0"
)
// element names need to Uppercase
type options struct {
Help bool `short:"h" long:"help" description:"Show he... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.