text stringlengths 11 4.05M |
|---|
package solutions
type Deque struct {
indexes []int
}
func (deque *Deque) push(i int) {
deque.indexes = append(deque.indexes, i)
}
func (deque *Deque) getFirst() int {
return deque.indexes[0]
}
func (deque *Deque) popFirst() {
deque.indexes = deque.indexes[1:]
}
func (deque *Deque) getLast() int {
... |
package main
import "testing"
type tuple struct {
p, q string
}
func TestWithoutRepetitions(t *testing.T) {
for k, v := range map[tuple]tuple{
tuple{"a", "b"}: tuple{"b", "b"},
tuple{"a", "a"}: tuple{"a", ""},
tuple{"\n", " "}: tuple{" ", " "}} {
if rp, rq := withoutRepetitions(k.p, k.q); rp != v.p || rq... |
package app
import (
"fmt"
"time"
"bitbucket.com/barrettbsi/broadvid-adscoops-shared/structs"
)
var campaignsCache = make(map[uint]CacheCampaign)
type CacheCampaign struct {
LastUpdated time.Time
Campaigns []CacheCampaignLayout
ActiveCampaigns []CacheCampaignLayout
InactiveCampaigns []CacheCa... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package scanapp
import (
"context"
"chromiumos/tast/local/bundles/cros/scanapp/scanning"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/uiauto/scanapp"
"... |
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"strings"
"sync"
"time"
"github.com/nu7hatch/gouuid"
"github.com/surma/httptools"
)
const (
Width = 600
Height = 600
)
type jobMap struct {
Map map[string]*job
sync.RWMutex
}
var jobs = &jobMap{
Map: map[string]*job{},
}
func main() {
v... |
package limitrange
import (
"fmt"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/informers"
listers "k8s.io/client-go/listers/core/v1"
)
// Calculator 计算容器或POD的资源量限制
type Calculator interface {
// GetContainerLimitRangeItem 获取指定命令空间下的容器资源量限... |
/***** Partie messageDB.go : structure du message et gestion de la base de données *****/
package db
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3" // Importation de librairie permettant d'utiliser SQlite, To install : go get github.com/mattn/go-sqlite3
)
/*** Constantes pour l'utilisation de la ba... |
package ccaddrepo
import (
"embed"
"io/fs"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
//go:embed fixtures
var fixtureRootFS embed.FS
var fixtureFS, _ = fs.Sub(fixtureRootFS, "fixtures")
func TestPlaceHolder(t *testing.T) {
content, err := fs.ReadFile(fixtureFS, "placeholder")
if assert.NoError(t, ... |
package coerce
import (
"github.com/project-flogo/core/data/coerce"
"github.com/project-flogo/core/data/expression/function"
)
func init() {
function.Register(&fnToString{})
function.Register(&fnToInt{})
function.Register(&fnToInt32{})
function.Register(&fnToInt64{})
function.Register(&fnToFloat32{})
function... |
package main
import (
"github.com/GoAdminGroup/go-admin/context"
"github.com/GoAdminGroup/go-admin/modules/db"
"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
"github.com/GoAdminGroup/go-admin/template/types/form"
)
func GetBlogTagTable(ctx *context.Context) table.Table {
blogTag := table.NewDefa... |
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"time"
"yespider-go/settings"
"yespider-go/www/controller"
)
func init() {
// Init config
settings.Setup()
}
func main() {
gin.SetMode(settings.ServerSettings.RunMode)
// Init handler
routersHandler := controller.InitRouter()
HttpP... |
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"io"
"io/ioutil"
"os"
"strings"
"github.com/aclements/go-z3/internal/ops"
)
... |
package routers
import (
"fmt"
"log"
"net/http"
"github.com/fatih/color"
"github.com/gorilla/mux"
"github.com/pmqueiroz/http-advices/advice"
)
type User struct {
Email string `json:"Email"`
Password string `json:"Password"`
Bio string `json:"Bio"`
}
type Users []User
func docs(w http.ResponseWriter, r ... |
package util
import "time"
const (
ServerName = "Segaline"
ServerVersion = "0.1.0"
ServerNameVersion = ServerName + "/" + ServerVersion
)
const (
DefaultEmptyRequestTarget = "/index.html"
DefaultReadTimeout = 10 * time.Second
DefaultFallbackErrorTemplate = "{statusCode} - {serverInfo}"
... |
package productready
import (
"context"
"fmt"
"log"
"mraft/productready/config"
"mraft/productready/httpd"
"mraft/productready/storage"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
type Engine struct {
prefix string
server *http.Server
router *gin.Engine
raftStorage *storage.Storage
kvHandle *http... |
package mongodb
import (
"testing"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
"github.com/stretchr/testify/require"
)
var testProviders map[string]terraform.ResourceProvider
var testProvider *schema.Provider
func init() {
testProvider = Provider().(*schema.Provide... |
// Copyright (c) 2018 Uber Technologies, Inc.
//
// 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, merge... |
package host
import (
"context"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"gopkg.in/yaml.v2"
)
// AddFromFileOptions contains available options for adding from file.
type AddFromDockerOptions... |
package gevent
/* ================================================================================
* gevent
* qq group: 582452342
* email : 2091938785@qq.com
* author : 美丽的地球啊 - mliu
* ================================================================================ */
type (
IEventSource interface {
GetChan... |
package base
import (
"errors"
"fmt"
//jwt "github.com/gogf/gf-jwt"
jwt "github.com/gogf/gf-jwt"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/os/glog"
"github.com/zhwei820/gadmin/app/model"
"github.com/zhwei820/gadmin/utils/crypt"
"time"
)
var (
// The underlying JWT mi... |
package main
import (
"bufio"
"container/list"
"fmt"
"math"
"os"
"rand"
"regexp"
"strings"
"time"
)
var dict = map[string]*list.List{}
func soundex(word string) string {
word = strings.ToLower(word)
firstLetter := word[0:1]
word = word[1:]
//I need a better regexp lib. Could make this that much faster.
... |
// Package api defines the graw api for Reddit bots.
package api
// Actor defines methods for bots that do things (send messages, make posts,
// fetch threads, etc).
type Actor interface {
// TakeEngine is called when the engine starts; bots should save the
// engine so they can call its methods. This is only called... |
package entity
// 用户实体
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
CreateTime int64 `json:"createTime"`
}
|
package horenso
const version = "0.9.0"
var revision = "Devel"
|
package handler
import (
"context"
"net"
"net/http"
"github.com/caos/logging"
"github.com/gorilla/csrf"
"github.com/rakyll/statik/fs"
"golang.org/x/text/language"
"github.com/caos/zitadel/internal/api/authz"
"github.com/caos/zitadel/internal/api/http/middleware"
"github.com/caos/zitadel/internal/auth/repos... |
// 201.Hands-on-exercise#1
// test
// benchmarks
// coverage
// coverage net
// exsample
package main
import (
"fmt"
"udemy_golang/src/201.Hands-on-exercise-1/dog"
)
type canine struct {
name string
age int
}
func main() {
fido := canine{
name: "Fido",
age: dog.Years(10),
}
fmt.Println(fido)
fmt.Print... |
package main
import (
"fmt"
)
func main() {
var (
c string
n, level, valleys int
)
fmt.Scanf("%d\n", &n)
fmt.Scanf("%s\n", &c)
for _, r := range []rune(c) {
switch {
case r == 'U':
level++
case r == 'D':
level--
}
if level == 0 && r == 'U' {
valleys++
}
}
fmt.Print... |
package service
import (
"github.com/jinzhu/gorm"
"github.com/zzsds/micro-sms-service/consts"
"github.com/zzsds/micro-sms-service/models"
)
// TemplateRepo ...
type TemplateRepo struct {
}
func NewTemplateRepo() *TemplateRepo {
return &TemplateRepo{}
}
// Create ...
func (r *TemplateRepo) Create(templateModel *... |
/*
*
*/
package log
import (
"io"
"os"
"github.com/sirupsen/logrus"
)
var Logger *logrus.Logger = nil
type Level uint32
const (
PanicLevel Level = iota
FatalLevel
ErrorLevel
WarnLevel
InfoLevel
DebugLevel
TraceLevel
)
// case "json":
// formatter = &logrus.JSONFormatter{}
// default:
// formatter =... |
package lsifstore
import (
"context"
"database/sql"
"github.com/keegancsmith/sqlf"
"github.com/opentracing/opentracing-go/log"
"github.com/sourcegraph/sourcegraph/internal/database/basestore"
"github.com/sourcegraph/sourcegraph/internal/observation"
"github.com/sourcegraph/sourcegraph/lib/codeintel/semantic"
... |
package configure
import (
"log"
"net/http"
"github.com/gorilla/sessions"
)
var (
key = []byte(AppProperties.CookieSecretKey)
// Store : session store
Store = sessions.NewCookieStore(key)
)
const ssoSession = "sso_session"
// GetSession : get session from key store
func GetSession(r *http.Request) *sessions.... |
package business
import (
"finance/models"
models_driver "finance/models/driver"
plugins "finance/plugins/common"
"finance/validator"
forms "finance/validator/driver"
"github.com/gin-gonic/gin"
"strings"
)
// 添加驾驶员
func AddDriver(context *gin.Context) {
var form forms.DriverAddForm
context.ShouldBindJSON(&fo... |
package image
import (
"encoding/gob"
"errors"
"fmt"
"io"
"path/filepath"
"github.com/openshift/oc-mirror/pkg/api/v1alpha2"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
)
// Associations is a map for Association
// searching
type Associations map[string]v1alpha2.Association
// AssociationSet is a set of ... |
package test
import (
"blockchain/certdemo/certdb"
"fmt"
"github.com/syndtr/goleveldb/leveldb"
"log"
"time"
)
func main() {
fmt.Println("test expired ")
Expired()
}
func ExpiredSelect() {
for {
select {
//改成配置文件的 todo
case <-time.After(10 * time.Second):
log.Println("timeout: gen cert")
}
}
}
fun... |
package profile
import (
"github.com/evcc-io/evcc/util"
sc "github.com/lorenzodonini/ocpp-go/ocpp1.6/smartcharging"
)
type SmartCharging struct {
log *util.Logger
}
func NewSmartCharging(log *util.Logger) *SmartCharging {
return &SmartCharging{
log: log,
}
}
// OnSetChargingProfile handles the CS message
fun... |
package orm
import (
"github.com/muidea/magicOrm/builder"
"github.com/muidea/magicOrm/model"
)
func (s *impl) updateSingle(modelInfo model.Model) (err error) {
builder := builder.NewBuilder(modelInfo, s.modelProvider)
sqlStr, sqlErr := builder.BuildUpdate()
if sqlErr != nil {
err = sqlErr
return err
}
_, ... |
/*
* Unlocks PDF files, tries to decrypt encrypted documents with the given password,
* if that fails it tries an empty password as best effort.
*
* Run as: go run pdf_unlock.go input.pdf <password> output.pdf
*/
package main
import (
"fmt"
"os"
pdf "github.com/unidoc/unidoc/pdf/model"
"bufio"
"github.c... |
package server
import (
"fmt"
"github.com/20zinnm/entity"
"github.com/20zinnm/spac/common/net"
"github.com/20zinnm/spac/common/world"
"github.com/20zinnm/spac/server/bounding"
"github.com/20zinnm/spac/server/despawning"
"github.com/20zinnm/spac/server/health"
"github.com/20zinnm/spac/server/movement"
"github.... |
package main
var x []num
|
package main
import (
"fmt"
"strings"
)
var pow = []int{1, 2, 4, 8}
func main() {
// The range form of the for loop iterates over a slice or map.
// When ranging over a slice, two values are returned for each iteration. The
// first is the index, and the second is a copy of the element at that index.
for i, v ... |
package validate
import (
"github.com/pgavlin/warp/wasm"
"github.com/pgavlin/warp/wasm/code"
)
type validator struct {
module *wasm.Module
validateCode bool
importedFunctions []uint32
importedGlobals []wasm.GlobalVar
tables int
memories int
locals []wasm.ValueType
}
func ValidateModule(m *wasm.... |
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// 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 righ... |
package eden
import (
"bytes"
"crypto/tls"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"time"
)
// Checks the given Authorization header for an encoded
// JWT and verifies it is from a valid sender. Retrieves
// the employee NetId and area Guid and stores in... |
package websocket
import (
"testing"
"time"
)
func BenchmarkTimerNew(b *testing.B) {
for i := 0; i < b.N; i++ {
timer := time.NewTimer(0)
<-timer.C
}
}
func BenchmarkTimerReset(b *testing.B) {
timer := time.NewTimer(0)
if !timer.Stop() {
<-timer.C
}
for i := 0; i < b.N; i++ {
timer.Reset(0)
<-time... |
package webgl3d
// func (self *Scene) loadPendulum() *Scene {
// pendulum := NewSceneObject(NewGeometry().LoadCylinder(10, 38, 1, false).Translate(0, 0, +0.5), "FFFFFF", "base")
// pillar := NewSceneObject(NewGeometry().LoadCube(1, 1, 10, false).Translate(0, 9, 6), "FFFFFF", "pillar")
// arm := NewSceneObject(NewGe... |
package measurement
import q "github.com/yamakii/analysis_pattern/domain/quantity"
type PhenomenonType struct {
}
type Person struct {
}
type Measurement struct {
PhenomenonType
Person
q.Quantity
}
// 使用例
var (
John = Person{}
height = PhenomenonType{}
// Johnのheightの測定結果
JothnHeight = Measurement{height, J... |
package fmap
import (
"fmt"
"strings"
"github.com/lleo/go-functional-collections/key"
"github.com/lleo/go-functional-collections/key/hash"
)
// implements nodeI
// implements leafI
type collisionLeaf []KeyVal
func newCollisionLeaf(kvs []KeyVal) *collisionLeaf {
var lKvs collisionLeaf = make([]KeyVal, len(kvs))... |
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
// signal包实现了对输入信号的访问
func main() {
// 初始化一个信号channel
c := make(chan os.Signal, 1)
// 让signal包将输入信号转发到c。如果没有列出要传递的信号,会将所有输入信号传递到c;否则只传递列出的输入信号
// signal包不会为了向c发送信息而阻塞(就是说如果发送时c阻塞了,signal包会直接放弃)
// 调用者应该保证c有足够的缓存空间可以跟上期望的信号频率。对使用单一信号用于通知的通道,缓存为1就足够了
... |
package cmd
import (
"fmt"
"github.com/rancher/kontainer-engine/store"
"github.com/rancher/kontainer-engine/utils"
"github.com/urfave/cli"
)
// EnvCommand defines the env command
func EnvCommand() cli.Command {
return cli.Command{
Name: "env",
Usage: "Set cluster as current context",
Action: env,
}
}
... |
package log
import (
"github.com/astroflow/astroflow-go"
)
var logger = astroflow.NewLogger()
func Config(options ...astroflow.LoggerOption) error {
return logger.Config(options...)
}
func With(fields ...interface{}) astroflow.Logger {
return logger.With(fields...)
}
func Debug(message string) {
logger.Debug(m... |
package mapper
import (
"context"
dynatracev1beta1 "github.com/Dynatrace/dynatrace-operator/src/api/v1beta1"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// NamespaceMapper manages the mapping creation from the namespace's side
type NamespaceMapper struct {
... |
package db
import (
"testing"
"time"
ps "pitchfork-analysis/pitchforkscrapper"
"github.com/stretchr/testify/suite"
)
type DBTestSuite struct {
db *DBAccessor
suite.Suite
}
func (d *DBTestSuite) SetupSuite() {
var err error
d.db, err = NewDBAccessor("testPitchfork.db")
d.NoError(err)
}
func (d *DBTestSuit... |
//go:build darwin
package main
import (
"fmt"
"os"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
"github.com/cloudflare/cloudflared/logger"
)
const (
launchdIdentifier = "com.cloudflare.cloudflared"
)
func runApp(app *cli.App, graceShutdownC ... |
package most_common_word
import (
"strings"
)
func mostCommonWord(paragraph string, banned []string) string {
buf := make([]byte, len(paragraph))
for i, c := range paragraph {
switch c {
case ',', '!', '?', '\'', ';', '.':
buf[i] = ' '
default:
buf[i] = toLower(byte(c))
}
}
bannedMap := make(map[... |
package client
import (
"encoding/binary"
"encoding/json"
"io"
"time"
"github.com/lthibault/log"
"github.com/urfave/cli/v2"
"github.com/libp2p/go-libp2p-core/peer"
pubsub "github.com/libp2p/go-libp2p-pubsub"
)
func subscribe() *cli.Command {
return &cli.Command{
Name: "subscribe",
Aliases: []string{... |
// Funcao deveria retornar inteiro, porem retorna string
package main;
func retornoInteiro(a, b, c string) int {
return "123";
}; |
package main
import (
"encoding/json"
"testing"
"github.com/aws/aws-lambda-go/events"
)
func requestEvent(reqID, orgID, covID string) events.APIGatewayProxyRequest {
req := EligibilityRequest{
ResourceType: "EligibilityRequest",
ID: reqID,
Patient: ReferenceData{Reference: "deceased"},
Org... |
package main
import (
"fmt"
)
type Node struct {
val int
next *Node
}
type Link struct {
head *Node
}
func (l Link) String() (s string) {
p := l.head
s = fmt.Sprintf("%d -> ", p.val)
for p.next != nil {
s += fmt.Sprintf("%d -> ", p.next.val)
p = p.next
}
return s
}
func main() {
l := Link{
head: &... |
package internal
import (
"encoding/json"
"../pkg/device"
"../pkg/unit"
"net/http"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"strconv"
"log"
"os"
)
var Devices map[string]*device.Device = make(map[string]*device.Device)
var Units map[string]*unit.Unit = make(map[string]*unit.Unit)
func... |
package midware
import (
"sync"
)
type data struct {
Consumer, Method string
}
// easy to add, delete and iterate on channels
// (uses only keys)
type tunnels map[chan data]bool
type logmod struct {
sync.RWMutex
tunnels tunnels
}
func (l *logmod) share(consumer, method string) error {
logData := data{
Consu... |
package packet
import (
"bytes"
"compress/flate"
"compress/gzip"
"io"
)
const (
COMPRESS_LEVEL = flate.BestCompression
)
func Compress(baseData []byte) ([]byte, error) {
var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write(baseData)
w.Close()
return b.Bytes(), nil
}
func Decompress(compressed []byte) ([]byt... |
package main
import (
"fmt"
)
func main() {
g := "Google"
rg := reverse(g)
fmt.Println(rg)
}
func reverse(s string) string {
ss := []byte(s)
sl := len(ss)
for i := 0; i < sl/2; i++ {
ss[i], ss[sl-i-1] = ss[sl-i-1], ss[i]
}
return string(ss)
}
|
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"time"
"github.com/blang/semver"
mholt "github.com/mholt/archiver"
"github.com/mitchellh/go-homedir"
"github.com/olekukonko/tablewriter"
"github.com/rhysd/go-github-selfupdate/selfupdate"
"github.com/spf13/cobra"
)
func main() {
roo... |
package engine
import (
"bytes"
"container/list"
"encoding/gob"
"io/ioutil"
"log"
)
type HMMParser struct {
scanner *Scanner
TagCounts map[string]int64
WordCounts map[string]map[string]int64
TagBigramCounts map[string]map[string]int64
TagForWordCounts map[string]map[string]int64
Mos... |
// Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in complian... |
package mqtt
import (
mqttclient "github.com/bernardolm/iot/sensors-publisher-go/mqtt"
log "github.com/sirupsen/logrus"
)
type mqtt struct{}
func (a *mqtt) Publish(topic string, message interface{}) error {
if message == nil {
return nil
}
log.WithField("topic", topic).WithField("message", message).WithField... |
/*
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package p2p
import (
"github.com/aergoio/aergo/types"
"github.com/gofrs/uuid"
)
type V020Wrapper struct {
*types.P2PMessage
originalID string
}
func NewV020Wrapper(message *types.P2PMessage, originalID string) *V020Wrapper {
return &V020Wrapper{message... |
package utils
import (
"log"
"net"
"strconv"
"github.com/guoruibiao/ipservice/constants"
"net/http"
"io/ioutil"
"encoding/json"
"strings"
"github.com/pkg/errors"
)
func IpNToA(ip string) net.IP {
if len(ip) >= 18 {
runes := []rune(ip)
ip = string(runes[0:18])
}
ipInt64, err := strconv.ParseInt(ip, 10,... |
// Copyright (C) 2017 Google 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 t... |
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
)
// https://adventofcode.com/2019/day/11
type Op struct {
code, params int
}
func (op Op) String() string {
return fmt.Sprintf("Op{code: %d, params: %d}", op.code, op.params)
}
var OpAdd Op = Op{code: 1, params: 3}
var OpMlt Op = Op{code: 2, ... |
package daemon
import (
"github.com/hyperhq/hyper/engine"
"github.com/hyperhq/runv/lib/glog"
)
func (daemon *Daemon) CmdRename(job *engine.Job) error {
oldname := job.Args[0]
newname := job.Args[1]
cli := daemon.DockerCli
err := cli.SendContainerRename(oldname, newname)
if err != nil {
return err
}
daemon.... |
// 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 main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
)
func ToJSON(w io.Writer) error {
var result = json.NewEncoder(w).Encode(&struct {
Foo string `json:"foo"`
Bar string `json:"bar"`
}{
"Foo",
"Bar",
})
return result
}
func main() {
var b bytes.Buffer
w := bufio.NewWriter(&b)
... |
package main
import (
"fmt"
"os"
)
func main() {
file := os.Args[1]
err := os.Rename(file, "1.rename.txt")
if err != nil {
fmt.Println("not ok")
} else {
fmt.Println("ok")
}
}
|
package keepassrpc
import (
"encoding/json"
"fmt"
"log"
"strings"
"github.com/gorilla/websocket"
)
// MsgError represents an error in the KeePassRPC protocol
type MsgError struct {
Code string `json:"code"`
MessageParams []string `json:"messageParams"`
}
// MsgJSONRPC represents various stages of ... |
package database
import (
"database/sql"
"log"
// Wraps database/sql for postgres
_ "github.com/lib/pq"
"poker/connection"
"poker/gamelogic"
"poker/models"
)
func CreateDatabase(username string, password string, name string) (database *sql.DB, err error) {
log.Print("Connecting to the databas... |
package globe
import (
"os"
"fmt"
"io/ioutil"
"bytes"
"testing"
)
var data = []byte(`
version: 1234
translations:
PICKLES:
en.US: Pickles
de.DE: Gurken
es.ES: Pepinillos
TOMATO:
en.US: Tomato
de.DE: Tomate
es.ES: Tomate
FRUIT:
en.US: Fruit
de.DE: Frucht
es.ES: Fruta
`)
... |
package main
import (
"testing"
)
func TestCode(t *testing.T) {
var tests = []struct {
n int
a int
b int
output []int
}{
{
n: 3, a: 1, b: 2,
output: []int{2, 3, 4},
},
{
n: 4, a: 10, b: 100,
output: []int{30, 120, 210, 300},
},
}
for _, test := range tests {
got := m... |
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package platform
import (
"bytes"
"context"
"regexp"
"strings"
"chromiumos/tast/common/testexec"
"chromiumos/tast/shutil"
"chromiumos/tast/testing"
)
func init() {
... |
/*
*Copyright (c) 2019-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 may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*Unless required by applicable law or ... |
/*
* Copyright (c) 2016 Alex Yatskov <alex@foosoft.net>
* Author: Alex Yatskov <alex@foosoft.net>
*
* 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 withou... |
package goutils
import (
"fmt"
"github.com/dgrijalva/jwt-go"
)
func CreateToken(secret string, data string) (string, error) {
//time.Now().Add(time.Minute * 15)
var err error
//Creating Access Token
atClaims := jwt.MapClaims{}
atClaims["data"] = data
//atClaims["user_id"] = userid
//atClaims["exp"] = expir... |
package playdata
import (
"database/sql"
"sync"
"time"
)
// GCP Functions may keep global variables across frequent access
type GlobalCache struct {
mutex *sync.Mutex
playsCache *PayloadPlays
playsCacheTime time.Time
// Attempt to reuse database connection
dbPool *sql.DB
}
func withLock(g *Glob... |
package main
import (
"fmt"
"io/ioutil"
"time"
"github.com/bitly/go-simplejson"
"github.com/xuri/excelize"
)
func main() {
row := 1
dat, _ := ioutil.ReadFile("/Users/zhuxu/Documents/weekreport/test.json")
// fmt.Println(string(dat))
json, err := simplejson.NewJson(dat)
if ... |
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func multiples(x, n int) (r int) {
var c uint
r = n
for (r << 1) <= x {
r <<= 1
c++
}
for c > 0 {
c--
for r+(n<<c) <= x {
r += n << c
}
}
for r < x {
r += n
}
return r
}
func main() {
var x, n int
data, err := os.Open(os.Args[1])
if err ... |
package utils
import (
"path/filepath"
"os"
"fmt"
"io"
"io/ioutil"
)
// checkDirPath 会检查目录路径。
func CheckDirPath(dirPath string) (absDirPath string, err error) {
if dirPath == "" {
err = fmt.Errorf("invalid dir path: %s", dirPath)
return
}
if filepath.IsAbs(dirPath) {
absDirPath = dirPath
} else {
abs... |
package email
import (
"fmt"
"net/smtp"
)
type User struct {
Username string
Password string
Server string
Port int
}
func (u *User) SendMail(from string, content []byte, to ...string) error {
auth := smtp.PlainAuth("", u.Username, u.Password, u.Server)
return smtp.SendMail(fmt.Sprintf("%s:%d", u.Serve... |
package xredis
import (
"testing"
"time"
"fmt"
"os"
"io/ioutil"
"encoding/json"
"log"
)
func init() {
//f, _ := os.OpenFile("sample.json",os.O_RDONLY, 0777)
f, _ := os.OpenFile("sample.json",os.O_RDONLY, 0777)
defer f.Close()
configStr, _ := ioutil.ReadAll(f)
var co... |
package testbed
import (
"fmt"
"os"
"os/exec"
"path/filepath"
)
//findContrib tries to find gin-repo/contrib, needs to be
//called with a current work directory below gin-repo/
func findContrib() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", nil
}
for {
cd := filepath.Join(dir, "co... |
package raft
//
// RequestVote RPC arguments structure.
// field names must start with capital letters!
//
type RequestVoteArgs struct {
// Your data here (2A, 2B).
Term int
CandidateID int
LastLogIndex int
LastLogTerm int
}
//
// RequestVote RPC reply structure.
// field names must start with capital ... |
package conf
import "strconv"
type Redis struct {
Addr string `json:"addr"`
Auth string `json:"auth"`
DB int `json:"db"`
}
func (rc *Redis) String() string {
return rc.Addr + "@" + rc.Auth + "/" + strconv.Itoa(rc.DB)
}
|
package wb_util
func FindIntPos(s int, array []int) int {
for p, v := range array {
if v == s {
return p
}
}
return -1
}
func FindStrPos(s string, array []string) int {
for p, v := range array {
if v == s {
return p
}
}
return -1
}
|
package v7
import (
"code.cloudfoundry.org/cli/actor/actionerror"
"code.cloudfoundry.org/cli/actor/sharedaction"
"code.cloudfoundry.org/cli/actor/v7action"
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/flag"
"code.cloudfoundry.org/cli/command/v7/shared"
"code.cloudfoundry.org/clock"
)
... |
package main
import (
"bytes"
"flag"
"io/ioutil"
"testing"
"github.com/stretchr/testify/assert"
)
type intsArg struct {
rootModel string
title string
output string
project string
filter string
modules string
exclude []string
clustered bool
epa bool
}
func comparePUML(t *testing.T... |
package global
// 全局Flags
// 配置文件路径
var GFlagConf string
// 加密类型
var GFlagCrypto string
// 节点地址
var GFlagHost string
// 账户目录
var GFlagKeys string
// 链名
var GFlagBCName string
|
package handler
import (
req_model "github.com/caos/zitadel/internal/auth_request/model"
"github.com/caos/zitadel/internal/errors"
es_model "github.com/caos/zitadel/internal/user/repository/eventsourcing/model"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zita... |
package kitworker
import (
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/metrics"
"github.com/go-kit/kit/tracing/opentracing"
httptransport "github.com/go-kit/kit/transport/http"
stdopentracing "github.com/opentracing/opentracing-go"
)
// ServerOption holds the required par... |
package models
import (
//"errors"
//"fmt"
//"github.com/revel/revel"
//"github.com/revel/revel/cache"
//"time"
//"github.com/jinzhu/gorm"
)
type GameTemplate struct{
BaseModel
Name string `gorm:"not null"`
Type int
Subtype int
Subname ... |
package screen
import "github.com/go-gl/gl/v4.5-compatibility/gl"
type VAO struct {
handle uint32
vbo *VBO
ebo *EBO
}
func (v *VAO) Init(vertices []float32, indices []uint32) *VAO {
var vao uint32
gl.GenVertexArrays(1, &vao)
gl.BindVertexArray(vao)
v.handle = vao
v.vbo = new(VBO).Init(vertices, gl.STA... |
package configuration
import (
"fmt"
"strings"
"github.com/mohamed-gougam/kube-agent/internal/configuration/version1"
"github.com/mohamed-gougam/kube-agent/internal/nginx"
k8snginx_v1 "github.com/mohamed-gougam/kube-agent/pkg/apis/k8snginx/v1"
)
// Configurer configures NGINX
type Configurer struct {
nginxMana... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.