text stringlengths 11 4.05M |
|---|
// 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 hwsec
import (
"context"
"strings"
"time"
"github.com/golang/protobuf/proto"
apb "chromiumos/system_api/attestation_proto"
"chromiumos/tast/common/hwsec"
"c... |
package mr
import (
"log"
"net"
"net/http"
"net/rpc"
"os"
"sync"
"time"
)
type State int
type Task struct {
State State
Filename string
}
const (
TaskStateIdle State = iota
TaskStateClaimed
TaskStateCompleted
)
type Master struct {
// Your definitions here.
mu sync.Mutex
mapTasks ... |
package config
import (
"fmt"
"path/filepath"
"runtime"
"github.com/spf13/viper"
)
var (
_, b, _, _ = runtime.Caller(0)
basepath = filepath.Dir(b)
)
func ReadConfig() {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath("./config/")
viper.AddConfigPath(basepath)
viper.AddConf... |
package solutions
func wordBreak(s string, wordDict []string) bool {
result := make([]bool, len(s) + 1)
result[0] = true
for i := 0 ; i < len(s); i++ {
if result[i] == false {
continue
}
for _, word := range wordDict {
j := i + len(word)
if j <... |
package autoconfig
import "go-gateway/pkg/httpgateway"
// 标准的配置文件示例
var GateWayC = `{
"spring": {
"application": {
"name": "xxxx"
},
"cloud": {
"consul": {
"host": "localhost",
"port": 8500,
"discovery": {
"enabled": true,
"instance-id": "",
"service-name": "xxxx",
"prefer... |
// Copyright (c) 2020 Target Brands, Inc. All rights reserved.
//
// Use of this source code is governed by the LICENSE file in this repository.
package native
import (
"flag"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/go-vela/types/pipeline"
"github.com/gin-gonic/gin"
"gith... |
package goheif
import (
"image"
"image/draw"
"io"
"io/ioutil"
"os"
)
// EncodeOptions is heif encode options
type EncodeOptions struct {
Quality int
Compression Compression
LosslessMode LosslessMode
LoggingLevel LoggingLevel
}
// EncodeOption ...
type EncodeOption func(opts *EncodeOptions)
// WithEnc... |
package net
import (
"net"
"os"
)
func InIpv4() ([]string, error) {
var ips []string
switch addrs, err := net.InterfaceAddrs(); {
case err != nil:
return nil, err
default:
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipnet, ok := address.(*net.IPNet); ok {
if ipnet.IP.To4() != nil && !ipne... |
package risserver
import (
"context"
"fmt"
"github.com/bio-routing/bio-rd/net"
"github.com/bio-routing/bio-rd/protocols/bgp/server"
"github.com/bio-routing/bio-rd/route"
"github.com/bio-routing/bio-rd/routingtable"
"github.com/bio-routing/bio-rd/routingtable/filter"
"github.com/bio-routing/bio-rd/routingtable... |
// Copyright 2020 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"strings"
)
type readWriter struct {
io.Reader
io.Writer
}
func newReadWriter(r io.Reader, w io.Writer) *readWriter {
return &readWriter{r, w}
}
// pipe reads from r, applies f, and writes to w.
func pipe(w io.Writer, f func(*readWriter)) io.Writer {
r... |
package main
import (
"os"
"bufio"
"strconv"
"strings"
"sort"
"fmt"
)
func main() {
inputSize := "large"
input, err := os.Open("A-" + inputSize + "-practice.in")
check(err)
defer input.Close()
scanner := bufio.NewScanner(input)
scanner.Scan()
T, _ := strconv.Atoi(scanner.Text())
result := ""
for i... |
package handlers_test
import (
"bytes"
"context"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/raba-jp/primus/pkg/cli/ui"
"github.com/raba-jp/primus/pkg/exec"
fakeexec "github.com/raba-jp/primus/pkg/exec/testing"
"github.com/raba-jp/primus/pkg/operations/packages/handlers"
"golang.org/x/xerrors"
)
fu... |
package main
import (
"fmt"
"log"
"os"
"github.com/ushmodin/criscross/game"
)
func main() {
err := criscross.StorageConnect(os.Getenv("MONGODB"))
if err != nil {
log.Fatal(err)
}
game, err := criscross.NewCrisCrossGame()
if err != nil {
log.Fatal(err)
}
defer criscross.StorageClose()
srv, err := cris... |
package main
import (
"bytes"
"fmt"
"github.com/adiabat/btcd/btcec"
"github.com/adiabat/btcd/chaincfg"
"github.com/adiabat/btcd/txscript"
"github.com/adiabat/btcd/wire"
"github.com/adiabat/btcutil"
"github.com/mit-dci/lit/portxo"
)
func (g *GDsession) move() error {
if *g.inFileName == "" {
return fmt.Err... |
package utils
import (
"fmt"
"net"
"encoding/json"
"go_code/restudy/netstudy/netstudy01/common/message"
)
var users map[string]net.Conn = make(map[string]net.Conn, 1)
//处理客户端发送的请求数据
func Process(conn net.Conn){
defer conn.Close()
var buf []byte = make([]byte, 1096)
n, err := conn.Read(buf)
if err != nil {
... |
// Copyright (c) 2020 - for information on the respective copyright owner
// see the NOTICE file and/or the repository at
// https://github.com/hyperledger-labs/perun-node
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may... |
package frame256x288
import (
"bytes"
"encoding/base64"
"fmt"
"image/png"
"strings"
)
// String returns frame serialized in “IMAGE:<base64-encoded-png>” format.
//
// The usefulness of this serialized format is, if you just output that on
// the Go Playground — https://play.golang.org/ — then it will display it
... |
package token
import (
"net/http"
"os"
"time"
"app/database"
"app/models"
"app/utils/response"
jwt "github.com/dgrijalva/jwt-go"
)
func Get(writer http.ResponseWriter, request *http.Request) {
jwtToken := jwt.New(jwt.SigningMethodHS256)
claims := jwtToken.Claims.(jwt.MapClaims)
claims["authorized"] = t... |
package common
import (
"fmt"
"os"
)
//判断文件是否存在
func FileExist(name string) bool {
_, err := os.Stat(name)
if err!=nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func CheckFileExists(path string) bool {
fmt.Println(path)
if _, err := os.Stat(path); err != nil {
if os.IsExist(err) {
... |
package gen
import (
"fmt"
"errors"
"gopkg.in/yaml.v2"
"path/filepath"
)
const AppTemplateFileMode = 0755
var (
ProjectPath string
TemplatePath string
)
var transactions AppTransactionStack
func CreateProject(template AppTemplate) error {
var err error
//Project section is required
if project, ok := temp... |
// Copyright 2017 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 ges_test
import (
"net/url"
"time"
. "gopkg.in/check.v1"
)
func (s *GesSuite) TestIndexCreation(c *C) {
err := s.conn.CreateIndex(indexName, nil)
c.Assert(err, IsNil)
}
func (s *GesSuite) TestIndexCreationWhenIndexExists(c *C) {
s.conn.CreateIndex(indexName, nil)
err := s.conn.CreateIndex(indexName, ... |
package handler
import (
"strconv"
"github.com/futurehomeno/fimpgo"
log "github.com/sirupsen/logrus"
sensibo "github.com/tskaard/sensibo/sensibo-api"
)
func (fc *FimpSensiboHandler) sendTemperatureMsg(addr string, temp float64, oldMsg *fimpgo.FimpMessage, channel int) { // channel; 0 = ch_0, 1 = ch_1, -1 = no ch... |
package gopay
import (
"encoding/json"
"github.com/parnurzeal/gorequest"
"log"
"time"
)
type aliPayClient struct {
AppId string
privateKey string
ReturnUrl string
NotifyUrl string
Charset string
SignType string
isProd bool
}
//初始化支付宝客户端
// appId:应用ID
// privateKey:应用私钥
// isProd:是... |
package goauth2
import (
"context"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"github.com/morikuni/failure"
"github.com/sters/neko/gclient"
)
const (
oauthURI = "https://accounts.google.com/o/oauth2/v2/auth"
authorizationURI = "https://www.googleapis.com/oauth2/v4/token"
re... |
package main
import "fmt"
type list struct {
e string
left *list
right *list
}
// insert adds the element e at index i in the list l
func (l *list) insert(i int, e string) {
node := new(list)
node.e = e
aux := l
for j := 0; l != nil && j <= i; l, j = l.right, j+1 {
aux = l
}
node.left, node.right =... |
package optioner
// Some[T] creates an Option[T] with the given value.
func Some[T any](v T) Option[T] {
var o Option[T]
o.v = &v
return o
}
// None[T] creates an Option[T] with no value.
func None[T any]() Option[T] {
var o Option[T]
return o
}
// Of[T] creates a Option[T] that may or may not have a value.
// ... |
package watcher
import (
"errors"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"math/big"
)
type EthereumTx interface {
Tx
Index() uint
EthereumTx() *types.Transaction
Gas() *big.Int
GasPrice() *big.Int
GasFeeCap() *big.Int
GasTipCap() *big.Int
}
type ethereumTx st... |
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
// https://www.hackerrank.com/challenges/largest-rectangle/problem
type area struct {
H int32
W int
}
func (a *area) c(j int) int32 {
return a.H * int32(j-a.W)
}
type stack struct {
Elements []area
Size int
}
func (s *stack) Push(x... |
package main
// Leetcode m13. (medium)
func movingCount(m int, n int, k int) int {
res := 0
visited := make([][]bool, m)
for i := range visited {
visited[i] = make([]bool, n)
}
queue := [][4]int{[4]int{0, 0, 0, 0}}
for len(queue) > 0 {
arr := queue[0]
queue = queue[1:]
x, y, sumX, sumY := arr[0], arr[1],... |
package main
import (
"fmt"
"math/rand"
)
func main() {
const ListSize = 100
channel := make(chan int)
for i := 0; i < ListSize; i++ {
go generateRandom(channel)
}
alist := []int{}
for i := 0; i < ListSize; i++ {
alist = append(alist, <-channel)
}
for i := 0; i < len(alist); i++ {
fmt.Println(alist[i... |
package alldebrid
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
)
//MagnetsUploadResponse is the response of the upload call
type MagnetsUploadResponse struct {
Status string `json:"status"`
Data magnetsUploadResponseData `json:"data,omitempty"`
Error alldebridError ... |
//
// Package - transpiled by c4go
//
// If you have found any issues, please raise an issue at:
// https://github.com/Konstantin8105/c4go/
//
package pkg
// init_cache - transpiled function from /home/istvan/packages/downloaded/cbuild/package/index.c:21
func init_cache() {
package_path_cache = kh_init_ptr()
pack... |
package main
import (
"flag"
//"fmt"
//"os"
//"os"
)
var (
batch = flag.Bool("b", false, "batch (non-interactive) mode")
printTokens = flag.Bool("tok", false, "print tokens")
printAst = flag.Bool("ast", false, "print abstract syntax tree")
printLLVMIR = flag.Bool("llvm", false, "print LLVM generated co... |
package main
import (
"fmt"
"github.com/sclevine/agouti"
"log"
)
func main() {
fmt.Println("Hello from Selenium sample.")
driver := agouti.PhantomJS()
if err := driver.Start(); err != nil {
log.Fatalf("Failed to start phantomjs driver: %v", err)
}
defer driver.Stop()
page, err := driver.NewPage(agouti.B... |
package ravendb
import (
"net/http"
"strings"
)
type OperationExecutor struct {
store *DocumentStore
databaseName string
requestExecutor *RequestExecutor
}
func NewOperationExecutor(store *DocumentStore, databaseName string) *OperationExecutor {
res := &OperationExecutor{
store: store,
... |
package models
// Book 书籍对象结构体
type Book struct {
ID int64 `db:"id"`
Title string `db:"title"`
Price float64 `db:"price"`
}
|
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// THIS IS OUR API SCAFFOLDING!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// H2DatabaseSpec defines the desired state of H2Database
// +k8s:openapi-gen=true
type H2DatabaseSp... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
var n int64
var k int64
var numbers []int64
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
s := scanner.Text()
args := strings.Fields(s)
n, _ = strconv.ParseInt(args[0], 10, 64)
k, _ = strconv.ParseInt(args[1],... |
package plot
import (
"fmt"
"os"
"code.google.com/p/plotinum/plot"
"code.google.com/p/plotinum/plotter"
"github.com/nictuku/latency"
)
// Plot saves an image of the latency histogram to filePath. The extension of filePath defines
// the format to be used - png, svg, etc.
func Plot(h *latency.Histogram, descript... |
package services
import (
"fmt"
"os"
"github.com/OrbitalbooKING/booKING/server/config"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var DB *gorm.DB
func ConnectDataBase() error {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
config... |
package utils
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestDoubleMapStringSet(t *testing.T) {
v := make(DoubleMapString)
assert.Nil(t, v["foo"])
assert.Empty(t, v["foo"]["bar"])
assert.Nil(t, v["foo"])
v.Set("foo", "bar", "xyz")
assert.NotNil(t, v["foo"])
assert.Equal(t, "xyz", v["foo"... |
package main
import "fmt"
// não tem operador ternario
func obterResultado(nota float64) string {
if nota >= 1.6 {
return "Aprovado"
}
return "Reprovado"
}
func main() {
fmt.Println(obterResultado((6.2)))
}
|
/*
Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus point... |
package main
import (
"log"
"os"
bot "github.com/curi0s/learning-go-twitch-bot"
)
func handleEvents(t *bot.Twitch, ch chan interface{}) error {
for event := range ch {
switch ev := event.(type) {
case bot.EventConnected:
log.Println("Connected!")
t.SendMessage(t.Options().DefaultChannel, "HeyGuys")
... |
// Copyright 2018 David Sansome
//
// 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 main
import "github.com/bjatkin/golf-engine/golf"
type collidable interface {
collide(vec2) bool
}
type character struct {
*interaction
n int
pos vec2
o golf.SOp
}
func (c *character) collide(player vec2) bool {
w, h := float64(c.o.W*8), float64(c.o.H*8)
// player is on the left or right
if pla... |
package core
import (
"fmt"
"time"
"github.com/praateekgupta3991/contraption/entities"
"github.com/praateekgupta3991/contraption/util"
)
type BlockService struct {
}
type BlockOperation interface {
CreateBlock(prevBid, prevProof int64, prevHash string) *entities.Block
}
func NewBlock(prevBid, prevProof int64,... |
package voxels
import (
"math"
v "github.com/pzsz/lin3dmath"
)
func DrawSphere(store VoxelField, x,y,z float32, radius float32, power int) {
startX,endX := int(x-radius),int(x+radius+1)
startY,endY := int(y-radius),int(y+radius+1)
startZ,endZ := int(z-radius),int(z+radius+1)
op := func (ix,iy,iz int) int {
... |
// +build darwin
/*
Copyright 2019 Adobe
All Rights Reserved.
NOTICE: Adobe permits you to use, modify, and distribute this file in
accordance with the terms of the Adobe license agreement accompanying
it. If you have received this file from a source other than Adobe,
then your use, modification, or distribution of i... |
package main
import "net/http"
import "log"
import "encoding/json"
import "strings"
type weatherData struct {
Name string `json:"name"`
Main struct {
Temp float64 `json:"temp"`
} `json:"main"`
}
func main2() {
http.HandleFunc("/weather/", weatherDataHandler)
http.HandleFunc("/", hello)
log.Fatal(http.ListenA... |
package notification
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"telebot/common"
"telebot/models"
)
type ZabbixNotification struct {
Date string `json: "date, omitempty"`
Alias string `json: "alias"`
Subject string `json: "subject"`
Message string `json: "message"`
EventId int `json: ... |
package goTezos
import "strconv"
//A function that retrieves a list of all currently delegated contracts for a delegate.
func GetDelegationsForDelegate(delegatePhk string) ([]string, error) {
var rtnString []string
getDelegations := "/chains/main/blocks/head/context/delegates/" + delegatePhk + "/delegated_contracts... |
package models
import (
"fmt"
"strings"
"github.com/markbates/pop/nulls"
)
type User struct {
Model
FirstName string `sql:"not null"`
LastName string
NickName string
Email string `json:",omitempty" sql:"not null;index;unique"`
Password []byte `json:"-" ... |
package gui
import (
"github.com/magicmonkey/go-streamdeck"
"github.com/magicmonkey/go-streamdeck/actionhandlers"
"github.com/magicmonkey/go-streamdeck/buttons"
"streamdeckOpenHab/openhab"
"streamdeckOpenHab/openhab/actionHandler"
"time"
)
const (
testSceneName = "TestScene"
mainSceneName = "MainScene... |
package helper
// return url for qrcode data
func Url() string {
return "http://127.0.0.1:3000" // modify this for your own url
}
|
//Copyright 2019 Chris Wojno
//
// 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, publish, distribut... |
package main
import (
"GoleGolas/socket-code/function"
"encoding/json"
"flag"
"fmt"
"github.com/astaxie/beego"
_ "github.com/go-sql-driver/mysql"
"github.com/gomodule/redigo/redis"
"github.com/mxi4oyu/MoonSocket/protocol"
"log"
"net"
"regexp"
"strings"
"sync"
)
//const (
// WHITE = "\x1b[37;1m"
// ... |
package sys
import (
"math/rand"
"time"
)
func Random(num int32) int32{
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
return int32(r1.Intn(int(num + 1)))
} |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
package display
import (
"reflect"
"strings"
"testing"
"github.com/AnuchitPrasertsang/roshambo/decide"
)
func TestSplitArtAscii(t *testing.T) {
a := splitArtAscii(PaperArt)
if !reflect.DeepEqual(a, strings.Split(PaperArt, "\n")) {
t.Error("split art ascii wrong")
}
}
func TestHightShouldBeEqual(t *testing... |
package file
import (
"io/ioutil"
plugin_v1 "github.com/cyberark/secretless-broker/internal/plugin/v1"
)
// Provider reads the contents of the specified file.
type Provider struct {
Name string
}
// ProviderFactory constructs a filesystem Provider.
// No configuration or credentials are required.
func ProviderFa... |
package main
import (
"log"
"net/http"
"time"
)
func Logger(httpHandler http.Handler, name string) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
start := time.Now()
httpHandler.ServeHTTP(res, req)
log.Printf(
"%s\t%s\t%s\t%s",
req.Method,
req.RequestURI... |
package core
import (
"sync"
"time"
"github.com/benbjohnson/clock"
)
const wakeupTimeout = 30 * time.Second
// Timer measures active time between start and stop events
type Timer struct {
sync.Mutex
clck clock.Clock
started time.Time
}
// NewTimer creates timer that can expire
func NewTimer() *Timer {
re... |
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information
package sync2_test
import (
"testing"
"time"
"github.com/stretchr/testify/require"
"storj.io/common/sync2"
)
func TestWaitGroup(t *testing.T) {
t.Parallel()
const Wait = 2 * time.Second
const TimeError = time.Second / 2
var gro... |
package systemtests
import (
"encoding/json"
"time"
"github.com/contiv/volplugin/config"
. "gopkg.in/check.v1"
)
func (s *systemtestSuite) TestVolpluginCrashRestart(c *C) {
c.Assert(s.createVolume("mon0", "tenant1", "test", nil), IsNil)
c.Assert(s.vagrant.GetNode("mon0").RunCommand("docker run -itd -v tenant1... |
package httpx
import (
"context"
"crypto/sha256"
"fmt"
)
// FetchResource fetches the specified resource and returns it.
func (c Client) FetchResource(ctx context.Context, URLPath string) ([]byte, error) {
request, err := c.NewRequest(ctx, "GET", URLPath, nil, nil)
if err != nil {
return nil, err
}
return c.... |
package locale
import (
"fmt"
"io/fs"
"github.com/BurntSushi/toml"
"github.com/cloudfoundry/jibber_jabber"
"github.com/evcc-io/evcc/server/assets"
"github.com/evcc-io/evcc/util/locale/internal"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
type Config = i18n.LocalizeConfig
var (
Lo... |
package main
import "fmt"
func main() {
a := 1
if a == 0 {
fmt.Println("first")
} else if a == 1 {
fmt.Println("second")
} else {
fmt.Println("third")
}
}
|
package sstats
import (
"testing"
)
func TestSumUpdate(t *testing.T) {
m, err := NewSum(5)
if err != nil {
t.Fatal(err)
}
vals := []float64{1, 2, 3, 4, 5, 6, 7, 8, 9}
expected := []float64{1, 3, 6, 10, 15, 20, 25, 30, 35}
for i, v := range vals {
m.Update(v)
val := m.Value()
if val != expected[i] {
... |
package generic
import (
"time"
"github.com/iotaledger/hive.go/kvstore/debug"
"github.com/iotaledger/hive.go/objectstorage"
)
type (
Option = objectstorage.Option
Options = objectstorage.Options
ReadOption = objectstorage.ReadOption
ReadOptions = objectstorage.ReadOptions
IteratorOp... |
package math
import (
"errors"
"reflect"
"strconv"
)
// i2float pretty like cast.ToFloat64E
func i2float(a interface{}) (float64, error) { // interface to number
aValue := reflect.ValueOf(a)
switch aValue.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
... |
package main
import "fmt"
func main() {
for i := 1; i < 100; i++ {
fmt.Printf("decimal : %d\tbinary : %b\thexadecimal : %#x\n", i, i, i)
}
}
|
package internal
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Generate_Run(t *testing.T) {
out, err := runCobraCmd(GenerateCmd)
assert.Nil(t, err)
assert.Contains(t, out, "generate")
}
|
package utils
import (
"reflect"
"strconv"
)
func InSlice(val interface{}, array interface{}) (exists bool, index int) {
exists = false
index = -1
switch reflect.TypeOf(array).Kind() {
case reflect.Slice:
s := reflect.ValueOf(array)
for i := 0; i < s.Len(); i++ {
if reflect.DeepEqual(val, s.Index(i).In... |
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"crd/pkg/apis/crd.com"
)
var SchemeGroupVersion = schema.GroupVersion{Group: crdcom.GroupName, Version: "v1alpha1"}
func Resource(resource string) schema.GroupResourc... |
package main
import (
// "fmt"
"github.com/emicklei/go-restful"
"net/http"
)
var (
Result string
)
type Response struct {
Code int `json:"Code"`
// Message string `json:"Message,omitempty"`
// Result interface{} `json:"Result,omitempty"`
// Count int `json:"Count,omitempty"`
// MD5 strin... |
// 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 storage
import (
"os"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
log "github.com/sirupsen/logrus"
)
// Database struct
type Database struct {
Conn *sqlx.DB
}
// NewConnection return database connection
func NewConnection() (*Database, error) {
var db Database
data, err := sqlx.Connect("postgres"... |
package httpserver
import (
"time"
"github.com/valyala/fasthttp"
)
const (
defaultReadTimeout = 5 * time.Second
defaultWriteTimeout = 5 * time.Second
defaultAddr = ":5500"
defaultShutdownTimeout = 3 * time.Second
)
type Server struct {
server *fasthttp.Server
notify chan ... |
package server
import (
"encoding/json"
"github.com/tidwall/gjson"
)
type Script struct {
Proto string `json:"proto"`
Data []gjson.Result `json:data`
HttpRequest *HttpRequest `json:"-"`
ScriptResponse []*ScriptResponse `json:"response"`
}
type ScriptResponse struct {
N... |
package server
import (
"github.com/julienschmidt/httprouter"
)
func middleware(h httprouter.Handle, middleware ...func(httprouter.Handle) httprouter.Handle) httprouter.Handle {
for _, mw := range middleware {
h = mw(h)
}
return h
}
|
package kail
import (
"fmt"
"io"
"github.com/fatih/color"
"encoding/json"
"bytes"
)
var (
prefixColor = color.New(color.FgHiWhite, color.Bold)
)
type Writer interface {
Print(event Event) error
Fprint(w io.Writer, event Event) error
}
func NewWriter(out io.Writer, jsonPP bool) Writer {
return &writer{
o... |
package cmds
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"github.com/google/go-github/v28/github"
"github.com/peterbourgon/diskv"
"github.com/spf13/cobra"
"github.com/alexec/github-toolkit/cmd/ght/util"
)
func NewReleaseNoteCmd() *cobra.Command {
... |
// Copyright 2015 go-swagger maintainers
//
// 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 agr... |
/*
Copyright 2018 Cai Gwatkin
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... |
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"strings"
"time"
"github.com/gorilla/mux"
)
var cache *string
func ProjectHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
GitHubWebHookHandler(w, r)
} else {
FetchReadMe... |
package lexers
import (
"strings"
. "github.com/alecthomas/chroma/v2" // nolint
)
// HTTP lexer.
var HTTP = Register(httpBodyContentTypeLexer(MustNewLexer(
&Config{
Name: "HTTP",
Aliases: []string{"http"},
Filenames: []string{},
MimeTypes: []string{},
NotMultiline: true,
DotAll: ... |
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package youtube contains the test code for VideoCUJ.
package youtube
import (
"context"
"path/filepath"
"strings"
"time"
"chromiumos/tast/common/perf"
"chromiumos/... |
package main
import (
"fmt"
"testing"
)
func TestCalc(t *testing.T) {
var op Operate
assertCorrectMessage := func(t *testing.T, got, want float64) {
t.Helper()
if got != want {
t.Errorf("got %.2f want %.2f", got, want)
}
}
t.Run("5 + 2", func(t *testing.T) {
fmt.Println("Testing... |
package sdplugin
import (
"encoding/json"
)
// Sender can send message to the StreamDeck app
type Sender interface {
SetState(context string, state int) error
ShowAlert(context string) error
ShowOk(context string) error
SetSettings(context string, payload interface{}) error
SendToPropertyInspector(context strin... |
package hoist_test
import (
"testing"
"github.com/hoistup/hoist-go/hoist"
"github.com/matryer/is"
)
func TestNewService(t *testing.T) {
is := is.New(t)
myName := "abc"
service := hoist.NewService(myName)
exported := service.Export()
expected := &hoist.ExportedService{
Name: myName,
Functions: make... |
// 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 DataLayer
import (
"encoding/json"
"fmt"
"testing"
"utils"
)
const tbinfo string = `[
{
"fieldname":"id",
"fieldlen":10,
"fieldtype":0,
"makeindex":true
},
{
"fieldname":"name",
"fieldlen":10,
"fieldtype":0,
"makeindex":true
}... |
package models
func (u *User) GetByUsernameAndPassword(email string, password string) error {
db, err := GetDatabase()
if err != nil {
return err
}
err = db.Where("email = ? AND password = ?", email, password).First(&u).Error
return err
}
func (u *User) GetByID() error {
db, err := GetDatabase()
if err != n... |
package configure
import (
"context"
"errors"
"fmt"
"mvdan.cc/sh/v3/expand"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"github.com/loft-sh/devspace/pkg/devspace/deploy/deployer/helm"
"github.com/loft-sh/devspace/pkg/devspace/pipeline/engine"
"github.com/sirupsen/logrus"
"github.com/loft... |
package carbonapi
import (
"expvar"
"net/http"
"net/http/pprof"
"github.com/dgryski/httputil"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func initHandlersInternal(app *App) http.Handler {
r := http.NewServeMux()
r.HandleFunc("/block-headers/", httputil.TimeHandler(app.blockHeaders, app.bucke... |
package lib
// Report uses for providing a struct for a report of executed task
type Report struct {
reqTarget string
reqCookies string
respBody string
respStatus string
}
// Execute uses for execute a test plan
func Execute(plan Plan, store APIStore) {
for _, task := range plan.Tasks {
target := store[tas... |
package confs
import (
"fmt"
"io/ioutil"
"time"
"encoding/json"
"net/http"
)
type Conference struct {
Name string
URL string
StartDate string
EndDate string
City string
Country string
CFPUrl string
CFPEndDate string
Twitter string
}
func GetConferences(topic string) ([... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.