text stringlengths 11 4.05M |
|---|
package main
import (
"fmt"
"log"
"net/url"
"github.com/go-playground/form/v4"
)
// <form method="POST">
// <input type="text" name="Name" value="joeybloggs"/>
// <input type="text" name="Age" value="3"/>
// <input type="text" name="Gender" value="Male"/>
// <input type="text" name="Address[0].Name" valu... |
package main
import (
"encoding/csv"
"fmt"
"io"
"os"
"github.com/labstack/gommon/log"
"github.com/zhenhuanlee/cqq/config"
)
const (
csvPath string = "./assets/1000.csv"
outPath string = "./assets/1000.json"
)
func main() {
db := config.DB()
file, err := os.Open(csvPath)
if err != ni... |
package validation
import (
"regexp"
"strconv"
"strings"
"github.com/google/uuid"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/openshift/installer/pkg/types/powervs"
)
// ValidateMachinePool checks that the specified ma... |
// 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 main
import (
"encoding/json"
"fmt"
"os"
"path"
"reflect"
"regexp"
"strings"
"github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
"github.com/opencontainers/specs"
)
var bundleValidateFlags = []cli.Flag{
cli.StringFlag{Name: "path", Usage: "path to a bundle"},
}
var (
defaultRlimits = []str... |
package texthash
import (
"fmt"
"time"
"golang.org/x/crypto/sha3"
)
type serviceImpl struct {
repo Repository
}
func (s *serviceImpl) Create(textHash *TextHash) (*TextHash, error) {
if textHash == nil || textHash.Token == "" {
return nil, fmt.Errorf("É necessário informar um objeto json com o campo 'token' p... |
package main
import (
"context"
"fmt"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"net/http"
"os"
"os/signal"
"regexp"
"strings"
"time"
)
func newRouter() *mux.Router {
r := mux.NewRouter()
staticFileDirectoryMain := http.Dir("./root/main")
staticFileDirectoryRu := http.Dir("./root/ru")
... |
package main
import (
"bytes"
"encoding/base64"
"fmt"
"image"
"image/color"
"image/png"
)
// copy paste to https://go-tour-de.appspot.com/methods/25
type Image struct {
w, h int
colorB, colorA uint8
}
func (i Image) ColorModel() color.Model {
return color.RGBAModel
}
func (i Image) Bounds() imag... |
package encrypt
import (
"fmt"
"testing"
)
func TestEncrypt(t *testing.T) {
password, err := StringEncrypt("KubeOperator@2019")
if err == nil {
fmt.Println(password)
password2, _ := StringDecrypt(password)
fmt.Println(password2)
}
}
|
package shortener
// Repository is an interface for a repository for the url package.
// It's made to have methods that expose Creating, Reading, Updating and deleting a url shortener.
type Repository interface {
// Create inserts a model in the repository.
Create(urlsh Model) error
// Remove removes a model from t... |
package httpd
import (
"bufio"
"fmt"
"net/http"
"github.com/Cloud-Foundations/Dominator/lib/html"
"github.com/Cloud-Foundations/Dominator/lib/image"
)
func (s state) listDirectoriesHandler(w http.ResponseWriter,
req *http.Request) {
writer := bufio.NewWriter(w)
defer writer.Flush()
directories := s.imageDat... |
// web server
package main
import (
"fmt"
"log"
"net"
"time"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal("listen error tcp :8080")
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
log.Println("ln.Accept error:", err)
}
go handleConnection(... |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package internal
import (
"golang.org/x/oauth2/google"
"google.golang.org/cloud/compute/metadata"
)
type gceTokenProvider struct {
oauthTokenProvider... |
package git
import (
"github.com/pkg/errors"
"gopkg.in/src-d/go-git.v4"
"os"
)
// GetHash retrieves the current HEADs hash
func GetHash(localPath string) (string, error) {
repo, err := git.PlainOpen(localPath)
if err != nil {
return "", errors.Wrap(err, "git open")
}
head, err := repo.Head()
if err != nil ... |
// Copyright 2018 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
// ===========================================================================
// Fmap establishes Head as Endo-Functor F<Head>.
// If a == ... |
package asset
// Store is a store for the states of assets.
type Store interface {
// Fetch retrieves the state of the given asset, generating it and its
// dependencies if necessary. When purging consumed assets, none of the
// assets in assetsToPreserve will be purged.
Fetch(assetToFetch Asset, assetsToPreserve ... |
package main
import "fmt"
func main() {
fmt.Printf("\ra")
fmt.Printf("\r")
fmt.Print("hola")
}
|
package searches
import (
"time"
"github.com/ion-channel/ionic/risk"
)
// Report represents all data in report from a search
// across multiple sources
type Report struct {
Name string `json:"name" xml:"name"`
Org string `json:"org" xml:"org"`
Version string... |
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package registry
import (
"context"
"fmt"
"log"
"math/rand"
"sync"
"time"
"go.etcd.io/etcd/api/v3/mvccpb"
clientv3 "go.etcd.io/etcd/client/v3"
)
type Discovery struct {
cli *clientv3.Client //etcd client
data map[string]map[string]string //services
lock sync.Mutex
names []string
}
//NewD... |
package evs
import (
"github.com/prometheus/client_golang/prometheus/promhttp"
"log"
"net/http"
"os"
)
var metrics_started = false
func CheckAndStartMetricsService() {
if metrics_started {
return
}
// Check if metrics port is specified. If not, do nothing.
metric_port, ok := os.LookupEnv("METRICS_PORT"... |
package bgControllers
import (
"github.com/astaxie/beego"
)
type BgIndexController struct {
beego.Controller
}
func (this *BgIndexController) Prepare() {
s := this.StartSession()
username = s.Get("login")
beego.Informational(username)
if username == nil {
this.Ctx.Redirect(302, "/login")
}
}
func (this *... |
package jsonenc
// Person type
type Person struct {
Firstname string `json:"first"`
Middlename string `json:"middle,omitempty"`
Lastname string `json:"last"`
SSID int64 `json:"-"`
City string `json:"city,omitempty"`
Country string `json:"country"`
Telephone int64 `json:"tel,string"`
}
|
package clickhousespanstore
import (
"context"
"database/sql"
"sync"
"time"
"github.com/hashicorp/go-hclog"
"github.com/prometheus/client_golang/prometheus"
"github.com/jaegertracing/jaeger/model"
"github.com/jaegertracing/jaeger/storage/spanstore"
)
type Encoding string
const (
// EncodingJSON is used fo... |
package client
import (
"bufio"
"encoding/json"
"fmt"
"os"
"reflect"
"sync"
"time"
"github.com/gorilla/websocket"
term "github.com/nsf/termbox-go"
"github.com/sirupsen/logrus"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong me... |
package curl
//curl
|
package tasks
import (
"fmt"
"github.com/EgorLyutov/Inventor/models"
"log"
"strconv"
"strings"
"time"
"gopkg.in/mgo.v2"
)
func TaskCheckConfigurationChange() {
session, err := models.InitDB()
if err != nil {
log.Fatal(err.Error())
}
defer session.Close()
err = checkChangeSystemUnit(session)
if err != n... |
package _66_Plus_One
func plusOne(digits []int) []int {
l := len(digits)
var isAdd bool
var ret []int
for i := l - 1; i >= 0; i-- {
v := digits[i]
if i == l-1 || isAdd {
v = v + 1
if v == 10 {
isAdd = true
v = 0
} else {
isAdd = false
}
}
ret = append([]int{v}, ret...)
}
if isAdd ... |
package oauthstore
import (
"context"
"reflect"
"testing"
"golang.org/x/oauth2"
)
func Test_storageTokenSource_Token(t *testing.T) {
conf := Config{&oauth2.Config{}, &FileStorage{}}
ctx := context.Background()
s := storageTokenSource{&conf, conf.Config.TokenSource(ctx, nil)}
tests := []struct {
name str... |
package main
import (
"flag"
"fmt"
"time"
meq "github.com/mafanr/meq/sdks/go-meq"
)
var topic = "/1234567890/22/chat/001"
var host = "localhost:"
var op = flag.String("op", "", "")
var port = flag.String("p", "", "")
var thread = flag.Int("t", 1, "")
var user = flag.String("u", "", "")
func main() {
flag.Pars... |
package redis
import (
"fmt"
"time"
"hash/fnv"
"sort"
"sync"
"github.com/dvirsky/go-pylog/logging"
"github.com/garyburd/redigo/redis"
"github.com/EverythingMe/meduza/errors"
"github.com/EverythingMe/meduza/query"
"github.com/EverythingMe/meduza/schema"
)
type changeType int
const (
//change types for en... |
package main
import "fmt"
func jobOffers(scores, lowerLimits, upperLimits []int) []int {
var result []int
for i := 0; i< len(lowerLimits); i++{
var count int
for _,score := range scores {
if score >= lowerLimits[i] && score <= upperLimits[i] {
count++
}
}
result = append(result, count)
}
return... |
package logbridge
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"testing"
"time"
"github.com/rcrowley/go-metrics"
"github.com/square/p2/pkg/logging"
"golang.org/x/time/rate"
)
const newLine = byte(10)
type TrackingWriter struct {
numWrites int
}
func (tw *TrackingWriter) Write(p []byte) (int, error) {
tw.... |
// Package reg provide a key-value data storage.
//
// the storage is actually a JSON tree
//
// keys are strings, can be separate into multiple level, like the path of filesystem.
// the separator is '/', leading and ending '/' is ignored, continious '/' is treat as
// single '/', so "/foo//bar/" is same as "foo/bar".... |
package deploy
import (
"github.com/devspace-cloud/devspace/cmd"
"github.com/devspace-cloud/devspace/cmd/flags"
"github.com/devspace-cloud/devspace/e2e/utils"
"github.com/devspace-cloud/devspace/pkg/util/log"
"github.com/pkg/errors"
)
//Test 4 - helm
//1. deploy & helm (see quickstart) (v1beta5 no tiller)
//2. p... |
package config
type IConfig interface {
Fill() error
}
|
package main
import "sync/atomic"
const (
statQueryCount = iota
statQueryFailed
statQuerySkipped
statConnCount
statConnOpen
statConnFailed
)
type stats map[int]*int32
func newStats() stats {
st := stats{}
for i := statQueryCount; i <= statConnFailed; i++ {
st[i] = new(int32)
}
return st
}
func (s stats... |
package wasm_test
import (
"context"
"fmt"
"time"
"github.com/solo-io/gloo/projects/gateway/pkg/defaults"
"github.com/solo-io/gloo/projects/gloo/pkg/api/v1/core/matchers"
"github.com/solo-io/gloo/projects/gloo/pkg/api/v1/options/wasm"
"github.com/solo-io/go-utils/kubeutils"
"github.com/solo-io/go-utils/testut... |
/*
Copyright 2020 The Knative 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 agreed to in writing, soft... |
package solution
/*
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
*/
// recursive visit sequence in tree: left -> current -> right
func inorderTraversal(root *TreeNode) []int {
var results []int
if root !=... |
package sand
import (
"encoding/json"
"fmt"
"net/http"
"regexp"
)
var urlMatch = regexp.MustCompile("/static/image/*")
func TesterMiddlewareFactory(testers map[string]bool) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *ht... |
package main
import (
"fmt"
"net/http"
"github.com/go-martini/martini"
"github.com/gorilla/securecookie"
"github.com/martini-contrib/sessions"
uuid "github.com/iris-contrib/go.uuid"
)
func main() {
martini.Env = martini.Prod
app := martini.New()
storeKey := securecookie.GenerateRandomKey(32)
store := ses... |
package main
import (
"fmt"
"math"
)
// 69. x 的平方根
// 实现 int sqrt(int x) 函数。
// 计算并返回 x 的平方根,其中 x 是非负整数。
// 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
// https://leetcode-cn.com/problems/sqrtx/
func main() {
fmt.Println(mySqrt2(4))
fmt.Println(mySqrt2(6))
}
// 法一:二分法
// O(logn)
func mySqrt(x int) (result int) {
if x <= 1 ... |
package trie
import (
"testing"
"github.com/kr/pretty"
"github.com/openacid/slim/encode"
"github.com/stretchr/testify/require"
)
type statCase struct {
keys []string
slimStr string
stat string
}
var statCases = map[string]statCase{
"empty": {
keys: []string{},
slimStr: trim(""),
stat: trim(`
... |
package client
import "github.com/elastic/go-elasticsearch/v8"
var EsClient *elasticsearch.Client
func init() {
var err error
config := elasticsearch.Config{}
config.Addresses = []string{"http://127.0.0.1:9200"}
EsClient, err = elasticsearch.NewClient(config)
if err != nil {
panic(err)
}
}
|
package git
/*
#include <git2.h>
int _go_git_opts_get_search_path(int level, git_buf *buf)
{
return git_libgit2_opts(GIT_OPT_GET_SEARCH_PATH, level, buf);
}
int _go_git_opts_set_search_path(int level, const char *path)
{
return git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, path);
}
int _go_git_opts_set_s... |
package yaas
import "fmt"
func Inverse(y YesString, err error) (YesString, error) {
err = fmt.Errorf("unable to invert string '%s'", y)
switch {
case yesConst == string(y):
y = YesString(noConst)
err = nil
case noConst == string(y):
y = YesString(yesConst)
err = nil
}
return y, err
}
|
package usda
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/google/go-querystring/query"
"net/http"
"net/url"
)
type Repository struct {
baseURL *url.URL
apiKey string
httpClient *http.Client
dataSource string
}
func CreateRepository(httpClient *http.Client) (*Repository, error) {
if... |
package main
import (
"encoding/binary"
"errors"
"fmt"
"io"
)
const MAGIC_FOUR_BYTES_V1 = uint32(0xFFFFFF01)
func writeHeader(w io.Writer, seqId int64) error {
if w == nil {
return errors.New("write to nil writer")
}
err := binary.Write(w, binary.BigEndian, uint32(MAGIC_FOUR_BYTES_V1))
if err != nil {
r... |
package main
import "fmt"
func main() {
num := 10
fmt.Println("[before] num:", num)
pointer(&num)
fmt.Println("[after] num:", num)
num2:=1.5
square(&num2)
fmt.Println(num2)
x:=1
y:=2
fmt.Println("[before] x:",x," y:",y)
swap(&x,&y)
fmt.Println("[after] x:",x," y:",y)
}
func pointer(num *int) {
... |
// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
/*
Copyright 2017 The Kubernetes 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 agreed to in writing, ... |
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Fprintf(w, "")
}
func createCommentHandler(w http.ResponseWriter, r *http.Request) {
type resultContainer struct {
Success boo... |
/*
Copyright 2022 The KubeVela 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 agreed to in writing, softw... |
package main
import "testing"
const NumCaptures = 20
func TestRegexBasicMatch(t *testing.T) {
testRegex := "aab*"
regexParse := regexParser{}
if parseRegex, err := regexParse.Parse(testRegex); err == nil {
inst := finalizeInst(parseRegex.compile())
t.Log(testRegex, " -> ", inst)
match := "aabbbbbbbbbbbbbbbb... |
// Copyright 2021 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package definition
import (
"fmt"
)
const (
// RegistryService const
RegistryService = "registry"
// RegistryPort const
RegistryPort = "5000"
// RegistryDockerIm... |
package main
import (
"gob/utils"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
// 定义服务端的rpc处理
type ServiceHandler struct {
}
func (service *ServiceHandler) GetName(id int, item *utils.Item) error {
log.Printf("receive GetName call, id: %d", id)
item.Id = id
item.Name = "Demo007"
return nil
}
// 服务响应
func (se... |
// Source : https://leetcode.com/problems/the-skyline-problem/
// Author : Austin Vern Songer
// Date : 2016-03-13
/**********************************************************************************
*
* A city's skyline is the outer contour of the silhouette formed by all the buildings
* in that city when ... |
package tools
import (
"encoding/json"
"fmt"
"github.com/KubeOperator/KubeOperator/pkg/constant"
"github.com/KubeOperator/KubeOperator/pkg/model"
)
const (
FluentedElasticsearchImageName = "fluentd_elasticsearch/fluentd"
FluentedElasticsearchTag = "v2.8.0"
ElasticSearchImageName = "elasticsearch/... |
package groups
import (
"docktor/server/storage"
"docktor/server/types"
"net/http"
"github.com/labstack/echo/v4"
log "github.com/sirupsen/logrus"
)
// getCAdvisorInfo get cadvisor info of container
func getCAdvisorInfo(c echo.Context) error {
group := c.Get("group").(types.Group)
db := c.Get("DB").(*storage... |
// SPDX-License-Identifier: Apache-2.0
// Copyright © 2019 Intel Corporation
package oauth2
import (
"encoding/json"
"errors"
"io/ioutil"
"path/filepath"
"time"
"github.com/dgrijalva/jwt-go/v4"
logger "github.com/open-ness/common/log"
)
var log = logger.DefaultLogger.WithField("oauth2", nil)
// Path for OA... |
package ds
import (
"fmt"
"net"
)
type Client struct {
IP net.IP `json:"ip"`
Fingerprint string `json:"fingerprint"`
Network string `json:"network"`
City string `json:"city"`
Country string `json:"country"`
Continent string `json:"continent"`
Proxy bool `json:"proxy"`
}
fun... |
package ports
import (
"testing"
assert "github.com/stretchr/testify/require"
)
func TestDividePorts(t *testing.T) {
testCases := []struct {
allPorts []string
concurrency int
expected [][]string
}{
{
[]string{"21", "80", "443"},
3,
[][]string{
{"21", "80", "443"},
},
},
// Small... |
package model
// Grants represents a permissions configuration for an imported remote schema
type Grants struct {
// Users is the list of users to apply the permissions to
Users []string `yaml:"users" json:"users"`
}
// Schema represents a foreign schema configuration
type Schema struct {
// ServerName is the name... |
package commit
// Reader provides readonly access to a commit.
type Reader struct {
ref Reference
nextState StateNum
}
// NewReader returns a commit reader for the given sequence number.
func NewReader(ref Reference) (*Reader, error) {
nextState, err := ref.States().Next()
if err != nil {
return nil, err
... |
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func main() {
response := make(chan *http.Response, 1)
errors := make(chan *error)
go func() {
resp, err := http.Get("http://matt.aimonetti.net/")
if err != nil {
errors <- &err
}
response <- resp
}()
for {
select {
case r := <-response:
... |
package pgsql
import (
"database/sql"
"database/sql/driver"
)
// TSVectorFromStringSlice returns a driver.Valuer that produces a PostgreSQL tsvector from the given Go []string.
func TSVectorFromStringSlice(val []string) driver.Valuer {
return tsVectorFromStringSlice{val: val}
}
// TSVectorToStringSlice returns an... |
package main
import (
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"path/filepath"
"runtime/pprof"
"sync"
"syscall"
"time"
"github.com/meshplus/bitxhub"
"github.com/meshplus/bitxhub-kit/log"
"github.com/meshplus/bitxhub/api/gateway"
"github.com/meshplus/bitxhub/api/grpc"
"github.com/meshplus/bi... |
package pgsql
// PostgreSQL `bytea` read/write natively supported with:
// - string
// - []byte
type _ native
|
package filestore
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"time"
"github.com/google/uuid"
)
// Package 'filestore' implements a filesystem that is responsible to store user's projects and files. For each
// direktiv namespace, a 'filestore.Root' should be created to host namespace files and dir... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package engine
import (
"strings"
"github.com/Azure/aks-engine/pkg/api"
"github.com/Azure/go-autorest/autorest/to"
)
func createKubernetesMasterResourcesVMAS(cs *api.ContainerService) []interface{} {
var masterResour... |
/*
Copyright IBM Corporation 2020
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
di... |
package two
import (
"fmt"
"os"
"strings"
)
func RunDay(filename string, part string) {
var file, _ = os.ReadFile("two/" + filename + ".txt")
var lines = strings.Split(string(file), "\n")
var parts = make(map[string]func(lines []string))
parts["one"] = runOne
parts["two"] = runTwo
parts[part](lines)
}
fun... |
package multipartuploader
import (
"fmt"
"github.com/alyakimenko/image-upload/internal/uploader"
"io/ioutil"
"log"
"net/http"
"path"
"strings"
)
type MultipartUploader struct {
r *http.Request
dir string
}
func New(r *http.Request, dir string) *MultipartUploader {
return &MultipartUploader{r, dir}
}
fun... |
/*
Copyright 2021 The KubeVela 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 agreed to in writing, so... |
package models
var (
CoffeeMachineList map[string]*CoffeeMachine
)
type CoffeeMachine struct {
ProductType ProductType
WaterLine bool
}
type ProductType int
const (
COFFEE_MACHINE_LARGE ProductType = iota
COFFEE_MACHINE_SMALL
ESPRESSO_MACHINE
)
type Profile struct {
Gender string
Age int
Address... |
package app
import (
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
const (
componentKubelet = "kubelet"
)
func WordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
if strings.Contains(name, "_") {
return pflag.NormalizedName(strings.Replace(name, "_", "... |
package client
import (
"encoding/json"
"errors"
"net/http"
"github.com/the-forges/sysdigexplorer/model"
)
type Dashboard struct {
model.Dashboard
}
const (
dashboardsEndPoint = "/api/v2/dashboards"
defaultDashboardsEndPoint = "/api/v2/defaultDashboards"
)
// NewDashboard instantiates a dashboard wit... |
package utils
import (
log "proximity/pkg/utils/logger"
"github.com/gin-gonic/gin"
"github.com/ralstan-vaz/go-errors"
"github.com/ralstan-vaz/go-errors/http"
)
// HandleError formats, logs and sets a http response for the error
func HandleError(c *gin.Context, errObj *error) {
if *errObj == nil {
return
}
... |
package media
import (
"github.com/jinzhu/gorm"
"github.com/satori/go.uuid"
"github.com/tppgit/we_service/log"
"github.com/tppgit/we_service/log/field"
"github.com/tppgit/we_service/pkg/errors"
)
type fileUploadRepository struct {
DB *gorm.DB `inject:"database"`
}
func CreateFileUploadRepository() FileUploadRe... |
/*
* Get the current and estimated charges for each server in a designated group hierarchy.
*/
package main
import (
"encoding/hex"
"flag"
"fmt"
"os"
"path"
"strings"
"github.com/grrtrr/clcv2/clcv2cli"
"github.com/grrtrr/exit"
"github.com/kr/pretty"
"github.com/olekukonko/tablewriter"
)
func main() {
va... |
// Copyright 2016 Matthew Endsley
// All rights reserved
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted providing that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions ... |
package consensus
import (
"encoding/hex"
drand2 "github.com/Secured-Finance/dione/beacon/drand"
"github.com/sirupsen/logrus"
"github.com/Secured-Finance/dione/blockchain"
types2 "github.com/Secured-Finance/dione/consensus/types"
)
type ConsensusValidator struct {
validationFuncMap map[types2.ConsensusMessag... |
package spider
import (
"bytes"
"net"
"github.com/zeebo/bencode"
)
type krpc struct{ dht *dht }
func newKrpc(dht *dht) *krpc { return &krpc{dht: dht} }
func (p *krpc) decode(data []byte, val map[string]interface{}, raddr *net.UDPAddr) error {
if err := bencode.DecodeBytes(data, &val); err != nil {
return err... |
package main
//import (
// "fmt"
// "log"
// "time"
//)
/**
* author: will fan
* created: 2019/5/7 21:30
* description:
*/
func main() {
}
|
package 位运算
func hasAlternatingBits(n int) bool {
return isMask(n ^ (n >> 1))
}
func isMask(mask int) bool {
nextValueOfMask := mask + 1
return isPowOfTwo(nextValueOfMask)
}
func isPowOfTwo(n int) bool {
return getValueOfLowestBit(n) == n
}
func getValueOfLowestBit(n int) int {
return n & (-n)
}
/*
题目链接: htt... |
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 2019 Broadcom. The term Broadcom refers to Broadcom Inc. and/or //
// its subsidiaries. ... |
package matcher
import (
"fmt"
"reflect"
"testing"
"github.com/sirupsen/logrus"
)
func TestMatcher_MatchGroups(t *testing.T) {
type TestCase struct {
name string
expr string
pairs map[string]map[string]string
f func(tc TestCase)
}
standard := func(tc TestCase) {
m, err := New(tc.expr)
if er... |
/**
* Copyright (c) 2018 ZTE Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and the Apache License 2.0 which both accompany this distribution,
* and are available at http://www.eclipse.org/legal/epl-v10.html
... |
package main
import (
"database/sql"
)
type recipe struct {
ID int `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
}
func (r *recipe) getRecipe(db *sql.DB) error {
return db.QueryRow("SELECT title, description FROM recipes WHERE id=$1", r.ID).Scan(&r.Title, &r.D... |
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/fblanco/talks/cool/scheduler"
"github.com/fblanco/talks/cool/utils"
)
var aduration utils.AtomicNotifiableDuration
func signalsHandler(wg *sync.WaitGroup, timeout time.Du... |
package access
import "github.com/kumahq/kuma/pkg/core/user"
type NoopGenerateDpTokenAccess struct {
}
var _ GenerateDataplaneTokenAccess = NoopGenerateDpTokenAccess{}
func (n NoopGenerateDpTokenAccess) ValidateGenerate(name string, mesh string, tags map[string][]string, tokenType string, user user.User) error {
r... |
package ibmcloud
import (
"net/http"
"strings"
"github.com/IBM/vpc-go-sdk/vpcv1"
"github.com/pkg/errors"
)
const imageTypeName = "image"
// listImages lists images in the vpc
func (o *ClusterUninstaller) listImages() (cloudResources, error) {
o.Logger.Debugf("Listing images")
ctx, cancel := o.contextWithTimeo... |
package strof
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"net/url"
"path/filepath"
"runtime"
"strings"
)
func Hash(v interface{}) (string, error) {
bytes, err := json.Marshal(v)
if err != nil {
return "", err
}
hash := md5.Sum(bytes)
return hex.EncodeToString(hash[:]), nil
}
// NonEmpty any o... |
package zfs
// #include <stdlib.h>
// #include <libzfs.h>
// #include "common.h"
// #include "zpool.h"
// #include "zfs.h"
import "C"
type ListOptions struct {
Types DatasetType
Recursive bool
Depth int32
Paths []string
}
func listChildren(d Dataset, opts ListOptions) (datasets []Dataset, err error) ... |
package sonar
import (
"fmt"
"sort"
"strings"
"sync"
)
type Result struct {
Domain string `json:"domain"`
Addrs []string `json:"addrs"`
}
func (r Result) String() string {
return fmt.Sprintf("%-50s %s", r.Domain, strings.Join(r.Addrs, ", "))
}
func NewResultSet() *ResultSet {
return &ResultSet{
results... |
package s3
import (
"log"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
func Download(bucket string, objectPath string, dir string) (string, error) {
sess := session.Mus... |
package main
import (
"context"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// TOKEN for selectel API
var TOKEN string
type selectelBillingResponce struct {
Status string ... |
package analyses
const (
// AnalysisGetAnalysisEndpoint returns a single raw analysis. Requires team id, project id and analysis id.
AnalysisGetAnalysisEndpoint = "v1/animal/getAnalysis"
// AnalysisGetAnalysesEndpoint returns multiple raw analyses. Requires team id and project id.
AnalysisGetAnalysesEndpoint = "v1... |
package items
// Currency is amount of money.
// P - Platinum
// G - Gold: 1000G -> 1P
// S - Silver: 100S -> 1G
// C - Copper: 100C -> 1S
type Currency struct {
P int64 `json:"p"`
G int64 `json:"g"`
S int64 `json:"s"`
C int64 `json:"c"`
}
// DieRoll represents a rolling of a die.
type DieRoll struct {
N int64... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.