text stringlengths 11 4.05M |
|---|
package main
import (
"net/http"
)
type Route struct {
Method string
Pattern string
Handler http.HandlerFunc
Name string
}
type Routes []Route
var routes = Routes{
Route{"GET", "/", Index, "index"},
Route{"GET", "/tasks", TaskIndex, "task.index"},
Route{"GET", "/tasks/{id}", TaskShow... |
package assets
import (
"os"
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
)
type testBindataFileInfo struct {
name string
size int64
mode os.FileMode
modTime time.Time
}
func (fi testBindataFileInfo) Name() string {
return fi.name
}
func (fi testBindataFileInfo) Size() int64 {
re... |
package outbound
import (
"database/sql"
"fmt"
"github.com/canmor/go_ms_clean_arch/pkg/domain/blog"
"github.com/canmor/go_ms_clean_arch/pkg/util"
)
type BlogRepositoryImpl struct {
db *sql.DB
}
func NewBlogRepository(db *sql.DB) blog.BlogRepository {
return BlogRepositoryImpl{db}
}
func (b BlogRepositoryImpl)... |
package main
import (
"flag"
"log"
"github.com/emcfarlane/starlarkrepl"
"go.starlark.net/repl"
"go.starlark.net/starlark"
)
func run() error {
flag.Parse()
thread := &starlark.Thread{Load: repl.MakeLoad()}
globals := make(starlark.StringDict)
options := starlarkrepl.Options{AutoComplete: true}
return sta... |
package main
import (
"database/sql"
"fmt"
_ "github.com/jinzhu/gorm/dialects/mysql"
"log"
)
type Record struct {
Id int64
UserId int64
Good int64
Type int64
Amount int64
Price float64
ToFrom sql.NullString
Time []uint8
}
func FindeRecords( id uint64,step uint64)[]*Record {
db,err:=sql.Open("mysq... |
package storage
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/naelyn/go-docker-registry/Godeps/_workspace/src/github.com/golang/glog"
"github.com/naelyn/go-docker-registry/types"
)
var ErrNotFound = errors.New("... |
package _058_最后一个单词的长度
func lengthOfLastWord(s string) int {
started := false
var count int
for i := len(s) - 1; i >= 0; i-- {
// 如果是空格
if s[i] == ' ' && started {
if started {
// 且已经开始数字母, 说明单词已经结束
return count
} else {
// 且未开始数字母, 忽略之
continue
}
} else {
// 如果不是空格,则计数,并标记已经开始数字母
... |
package jex
import (
"bytes"
"io/ioutil"
"reflect"
"testing"
"time"
)
type TestA struct {
Int8 int8
UInt8 uint8
Int int
UInt uint
Map map[string]TestA
Array [2]float32
Slice []float64
}
func TestMarshalStruct(t *testing.T) {
m := map[string]TestA{
"ASDF": TestA{1, 2, 3, 4, nil, [2]float32{}, nil... |
package effects
import "github.com/faiface/beep"
// Gain amplifies the wrapped Streamer. The output of the wrapped Streamer gets multiplied by
// 1+Gain.
//
// Note that gain is not equivalent to the human perception of volume. Human perception of volume is
// roughly exponential, while gain only amplifies linearly.
... |
// Copyright (c) 2018 Andreas Auernhammer. All rights reserved.
// Use of this source code is governed by a license that can be
// found in the LICENSE file.
package siv
import (
"bytes"
"testing"
"golang.org/x/sys/cpu"
)
func TestAESCMAC(t *testing.T) {
hasAES := cpu.X86.HasAES
defer func(hasAES bool) { cpu.X... |
package main
import (
"fmt"
"github.com/ksclouds/PowerNLP/Seg"
BaseTrie "github.com/ksclouds/PowerNLP/Seg/Collections"
)
func main() {
tree := BaseTrie.NewMapTrie()
tree.Insert("word.py")
tree.Insert("wor")
tree.Insert("wx")
tree.Insert("abastract")
tree.Insert("中国人")
tree.Insert("国足")
//tree.Insert("中国")... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package engine
import (
"github.com/Azure/azure-sdk-for-go/services/preview/msi/mgmt/2015-08-31-preview/msi"
"github.com/Azure/go-autorest/autorest/to"
)
func createUserAssignedIdentities() UserAssignedIdentitiesARM {
... |
package leetcode
func minCostToMoveChips(chips []int) int {
odds, evens := 0, 0
for _, v := range chips {
if v%2 == 0 {
evens++
} else {
odds++
}
}
if evens > odds {
return odds
}
return evens
}
|
package channels
import "time"
//Sender 함수는 done 채널에 데이터가 기록될 때까지
//ch 채널에 "tick"을 보내고, done 채널에 데이터가
//기록되면 "sender done"을 보내고 종료한다.
func Sender(ch chan string, done chan bool) {
t := time.Tick(100 * time.Millisecond)
for {
select {
case <-done:
ch <- "sender done."
return
case <-t:
ch <- "tick"
}... |
package ecr
import (
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ecr"
"github.com/aws/aws-sdk-go/service/ecr/ecriface"
)
var response ecr.GetAuthorizationTokenOutput
// Mocks ECR API calls for GetAuthorizationToken
type mockGetAuthorizationToken struct {
ecriface.ECRAPI
Resp e... |
package main
import (
"fmt"
"math/rand"
)
func biasedCoin() int {
n := rand.Intn(100)
if n < 60 {
return 0
}
return 1
}
func fairCoin() int {
for {
coin1 := biasedCoin()
coin2 := biasedCoin()
if coin1 != coin2 {
return coin1
}
}
}
type CoinFn func() int
func flip() {
zeros := 0
ones := 0
... |
package site
type Menu struct {
Name string `json:"name"`
Alias string `json:"alias"`
}
|
package hooks
import (
"testing"
)
// implementing the hook
func (h *Hook) execute(th *thing) *thing {
th.SetText(th.text + h.name)
return th
}
func TestHoox(t *testing.T) {
a := Hook{name: "foo"}
b := Hook{name: "bar"}
c := Hook{name: "baz"}
a.Sethook(b)
a.Sethook(c)
th := thing{text: "Hello"}
a.Process(... |
package pypwsh
import (
"github.com/hashicorp/terraform/helper/schema"
"github.com/rfalias/gopypwsh"
"os"
"time"
"math/rand"
)
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func waitForLock(client *P... |
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"runtime"
"time"
nats "github.com/nats-io/nats.go"
)
type JobOrder struct {
ID string `json:"ID"`
Name string `json:"name"`
}
type SalesItem struct {
ItemID string `json:"ID"`
Name string `json:"name"`
Qty float32... |
// Copyright © 2018 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: BSD-2-Clause
package processors
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/vmware/kube-fluentd-operator/config-reloader/fluentd"
)
func TestMakeRewriteTagFragment(t *testing.T) {
frag, err := makeRewriteTa... |
package main
import (
"fmt"
)
func main() {
c := make(chan int)
c <- 1
fmt.Println(<-c)
}
/*
This results in a deadlock.
Can you determine why?
And what would you do to fix it?
*/
// go run main.go
// fatal error: all goroutines are asleep - deadlock!
// goroutine 1 [chan send]:
// main.main()
// /home/... |
package main
import (
"context"
"flag"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gorilla/mux"
"github.com/matscus/Hamster/Mock/info_service/datapool"
"github.com/matscus/Hamster/Mock/info_service/handlers"
)
var (
pemPath string
keyPath string
proto string
listenport strin... |
package client
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/luno/moonbeam/models"
)
var debugRPC = flag.Bool("debug_rpc", true, "Debug RPC")
type Client struct {
endpoint string
c *http.Client
}
func NewClient(c *http.Client, endpoint ... |
package g2util
import (
"time"
)
// TimeoutExecFunc ...
func TimeoutExecFunc(fn func(), timeout time.Duration) {
ch1 := make(chan struct{}, 1)
go func() {
fn()
ch1 <- struct{}{}
}()
select {
case <-time.After(timeout):
return
case <-ch1:
return
}
}
|
package model
import (
"time"
)
type PlayerLicense struct {
// Id of the resource
Id string `json:"id,omitempty"`
// Name of the resource
Name string `json:"name,omitempty"`
// Creation timestamp formatted in UTC: YYYY-MM-DDThh:mm:ssZ
CreatedAt *time.Time `json:"createdAt,omitempty"`
// License Key
LicenseKey... |
package file
import (
"fmt"
"log"
"net/http"
"sync"
)
type FileUploadAPI struct{}
var lock sync.Mutex
func (f FileUploadAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
switch r.Method {
case http.MethodPost:
doPost(w, r)
defaul... |
package main
import (
"code.google.com/p/go-tour/pic"
)
func Pic(dx, dy int) [][]uint8 {
vals := make([][]uint8, dx)
for x := 0; x<dx; x++ {
inner := make([]uint8, dy)
for y := 0; y<dy; y++ {
inner[y] = uint8(100*x*(y*y)/(x+7))
}
vals[x] = inner
}
return... |
package helper
import (
"testing"
)
func TestColorForStatus(t *testing.T) {
tests := []struct {
name string
args int
want string
}{
{
name: "Testcase #1: Return Green",
args: 200,
want: Green,
},
{
name: "Testcase #2: Return White",
args: 300,
want: White,
},
{
name: "Testcase ... |
/*
* @lc app=leetcode.cn id=1370 lang=golang
*
* [1370] 上升下降字符串
*/
// @lc code=start
package main
func sortString(s string) string {
counter := make([]int, 26)
ret := make([]byte, len(s))
for i := 0; i < len(s); i++ {
counter[s[i]-'a']++
}
charsIndex := 0
index := 0
for index < len(s) {
realIndex := ch... |
package main
import (
"net/http"
_ "net/http/pprof"
"testing"
)
func Test_extractLang(t *testing.T) {
type args struct {
lang string
}
tests := []struct {
name string
args args
want string
}{
{"Handles default value lang parameter", args{""}, ""},
{"Handle language that is not real", args{"fakelang... |
package lib
// VersionNumber of the app
const VersionNumber = "1.1.2"
|
/*
Create a function which concantenates the number 7 to the end of every chord in an array. Ignore all chords which already end with 7.
Examples
jazzify(["G", "F", "C"]) ➞ ["G7", "F7", "C7"]
jazzify(["Dm", "G", "E", "A"]) ➞ ["Dm7", "G7", "E7", "A7"]
jazzify(["F7", "E7", "A7", "Ab7", "Gm7", "C7"]) ➞ ["F7", "E7", "A... |
package functions
import (
"go.mongodb.org/mongo-driver/bson"
"context"
"go.mongodb.org/mongo-driver/mongo"
// "fmt"
"rank-server-pikachu/app/models"
)
type Leaderboard struct {
Name string `json:"name"`
Score int64 `json:"score"`
HighScore int64 `json:"high_score"`
}
// func UpdateScoreUser(leve... |
package utils
import (
"fmt"
"os"
"strconv"
)
// load environment variable or return default value
func Getenv(key, defaultt string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return defaultt
}
// load environment variable or fail
func GetenvOrFail(envname string) string {
value := os.G... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//38. Count and Say
//The count-and-say sequence is the sequence of integers with the first five terms as following:
//1. 1
//2. 11
//3. 21... |
package main
import (
"bufio"
"compress/gzip"
"flag"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
"github.com/dgraph-io/dgraph/x"
)
var (
output = flag.String("output", "out.rdf.gz", "Output rdf.gz file")
genre = flag.String("genre", "ml-100k/u.genre", "")
users = flag.String("rating", "ml-100k/u.user", "... |
package provider
import (
"context"
"errors"
"fmt"
"github.com/alexzimmer96/eventing"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoEventGenerator func(cursor *mongo.Cursor) (eventing.Event, error)
type MongoProjectionGenerator fu... |
package btree
type BTree struct {
Top *Node
}
func NewBTree() *BTree {
return &BTree{Top: nil}
}
func (b *BTree) Insert(v int) {
if b.Top == nil {
b.Top = NewNode(v)
return
}
b.Top.Insert(v)
}
func (b *BTree) InsertMany(values []int) {
for _, v := range values {
b.Insert(v)
}
}
func (b *BTree) FindDe... |
package main
import (
"testing"
)
func TestStudentLearn(t *testing.T) {
teacher := Teacher{}
student := NewClassMate("Mario")
teacher.TeachesTo(student)
teacher.Spread("Message sent to everyone")
if student.Learned() != "Message sent to everyone" {
t.Error("Student should learn")
}
}
|
package css
type PseudoClass string
const FirstChild PseudoClass = "first-child"
const LastChild PseudoClass = "last-child"
const After PseudoClass = "after"
const Before PseudoClass = "before"
const Hover PseudoClass = "hover"
const Visited PseudoClass = "visited"
const Active PseudoClass = "active"
const Link Pseud... |
package schemas
type Scope int
// Table enumerator
const (
ScopeUndefined Scope = iota
Application
Execution
Metric
Planning
Prediction
Recommendation
Resource
)
type MetricType int
// Metric type enumerator
const (
MetricTypeUndefined MetricType = iota
CPUUsageSecondsPercentage
MemoryUsageBytes
PowerUs... |
/*
In a letter to Lord Bowden in 1837, Charles Babbage asked, "What is the smallest positive integer whose square ends in 269,696?". He thought the answer was 99,736 whose square is 9,947,269,696. Was he right?
Write a function that takes a positive integer n and returns the smallest number whose square ends with n.
... |
package service
import (
"github.com/godcong/role-manager-server/model"
"github.com/sirupsen/logrus"
)
// Seed ...
func Seed() {
//for _, v := range Permissions() {
// e := model.InsertOne(v)
// if e != nil {
// return
// }
//}
for _, v := range Menus() {
e := model.InsertOne(v)
if e != nil {
return
... |
package main
import (
"fmt"
"html"
)
//START OMIT
func main() {
// value recieved from query args
query_msg := "<b>Evil Hacker Script!</b>"
// Print as substitute for echoing message on Web Page
fmt.Printf("Dangerous: \n- %s\n\n", query_msg)
fmt.Printf("Save: \n- %s\n", html.EscapeString(query_msg)) // HL
}
... |
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
package main
... |
package bccsp
const (
ECDSA = "ECDSA"
ECDSAP256 = "ECDSAP256"
ECDSAP384 = "ECDSAP384"
ECDSAReRand = "ECDSA_RERAND"
RSA = "RSA"
RSA1024 = "RSA1024"
RSA2048 = "RSA2048"
RSA3072 = "RSA3072"
RSA4096 = "RSA4096"
AES = "AES"
AES128 = "AES128"
AES192 = "AES192"
AES256 = "AES256"
HMAC = ... |
package jsoniter
import (
"unsafe"
"reflect"
)
type mapDecoder struct {
mapType reflect.Type
elemType reflect.Type
elemDecoder Decoder
mapInterface emptyInterface
}
func (decoder *mapDecoder) decode(ptr unsafe.Pointer, iter *Iterator) {
// dark magic to cast unsafe.Pointer back to interface{} using ... |
// Copyright 2017 Vlad Didenko. All rights reserved.
// See the included LICENSE.md file for licensing information
package slops // import "go.didenko.com/slops"
// Merge returns a slice with a union of strings in slices.
// For duplicate entries, the resulting slice contains the
// maximum numbers of duplicate strin... |
package handlers
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"dream01/internal/intlog"
"github.com/gorilla/mux"
)
// RadioStation ...
type RadioStation struct {
ID int `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
Logo string `json:"logo"`
InfoURL st... |
// Copyright 2022 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 (c) 2017-2021 Uber Technologies Inc.
// Portions of the Software are attributed to Copyright (c) 2020 Temporal 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 Soft... |
package main
import (
"fmt"
"time"
)
// go channel concept is blocking
// <- c read from channel
// waiting for write channel
// if read only none data on channel program we call dead lock mode
// thread all sleep
// c <- 1 write to channel
func main() {
fmt.Println("with channel")
// channel1()
channelCaseBloc... |
package waktu_test
import (
"fmt"
"testing"
. "github.com/gomodul/waktu"
)
func TestTime_StartOfDay(t *testing.T) {
fmt.Println(now.StartOfDay())
}
func TestTime_StartOfWeek(t *testing.T) {
startOfWeek := now.StartOfWeek()
if int(startOfWeek.Weekday()) != int(Minggu) {
t.Fatal("invalid value")
}
}
func Te... |
package bind
import (
. "bytes"
. "github.com/rainmyy/easyDB/library/common"
. "github.com/rainmyy/easyDB/library/strategy"
)
type String struct {
value *Buffer
}
func (s *String) Bind(treeList []*TreeStruct) {
var buffer = NewBuffer([]byte{})
if len(treeList) > 1 {
buffer.WriteRune(LeftBracket)
}
BindStr... |
package main
import (
"fmt"
"github.com/mitsuhide1992/language/structUtil"
)
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
structUtil.Fibonacci(c, quit)
}
|
// Copyright 2022 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... |
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... |
package main
import "fmt"
type Rectangle struct {
x uint64
y uint64
}
//사각형 둘레
func RectanglePerimeter(r *Rectangle) uint64 {
return (2 * r.x) + (2 * r.y)
}
//사각형 넓이
func RectangleArea(r *Rectangle) uint64 {
return r.x * r.y
}
func main() {
rec := Rectangle{x: 10, y: 20}
fmt.Println("사각형의 둘레 : ", RectanglePe... |
package gogrep_test
import (
"context"
"errors"
"fmt"
"io"
"sort"
"strings"
"testing"
"time"
"github.com/berquerant/gogrep"
"github.com/stretchr/testify/assert"
)
func dupStrings(n int, seeds ...string) []string {
r := make([]string, len(seeds)*n)
for i := 0; i < len(r); i++ {
r[i] = seeds[i%len(seeds)... |
package main
import (
"flag"
"fmt"
"github.com/mattnappo/yearbook/api"
"github.com/mattnappo/yearbook/common"
"github.com/mattnappo/yearbook/database"
)
var (
createSchemaFlag = flag.Bool("create-schema", false, "create the database schema")
addSeniorsFlag = flag.Bool("add-seniors", false, "add the seniors ... |
package translator_test
import (
"testing"
"github.com/goropikari/psqlittle/core"
trans "github.com/goropikari/psqlittle/translator"
"github.com/stretchr/testify/assert"
)
func TestTranslateSelect(t *testing.T) {
var tests = []struct {
name string
expected trans.Statement
query string
}{
{
na... |
package main
import (
"net/http"
"log"
"Moodometer/Server/moodometer"
"io/ioutil"
"github.com/golang/protobuf/proto"
)
var howDay = 0
var moods = []moodometer.Mood{}
func main() {
http.HandleFunc("/", action)
http.ListenAndServe(":8008", nil)
}
func action(w http.ResponseWriter, r *http.Request) {
how := r... |
// This file was generated for SObject CaseTeamTemplate, API Version v43.0 at 2018-07-30 03:47:39.961302704 -0400 EDT m=+26.304896172
package sobjects
import (
"fmt"
"strings"
)
type CaseTeamTemplate struct {
BaseSObject
CreatedById string `force:",omitempty"`
CreatedDate string `force:",omitempty"`
... |
package main
import (
"fmt"
"math"
)
func main() {
x := float64(64)
fmt.Printf("Sqrt(%v) : %v\n", x, math.Sqrt(x))
}
|
package connection
import (
"errors"
"net"
"bufio"
"io"
"strconv"
)
const MaxMessageSize = 0x1FFFFFFF
type TCPConnection struct {
url string
}
type TCPConnectionInstance struct {
conn net.Conn
read *bufio.Reader
}
func NewTCPConnection(url string) *TCPConnection {
return &TCPConnection{url}
}
func writeM... |
package main
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/aws/aws-sdk-go-v2/service/sqs/types"
"github.com/aws/aws-sdk-go/aws"
"githu... |
package mhfpacket
import (
"github.com/Andoryuuta/Erupe/network"
"github.com/Andoryuuta/Erupe/network/clientctx"
"github.com/Andoryuuta/byteframe"
)
// MsgSysAck represents the MSG_SYS_ACK
type MsgSysAck struct {
AckHandle uint32
IsBufferResponse bool
ErrorCode uint8
AckData []byte
}
//... |
package main
import (
"bytes"
"fmt"
"strings"
"strconv"
)
func main() {
var str string
fmt.Scanf("%s", &str)
fmt.Print(formatToCurrenct(str))
}
func formatToCurrenct(str string) string{
var res []string
strTof, _ := strconv.ParseFloat(str, 64)
str = fmt.Sprintf("%.2f", strTof)
strs := strings.Split(str, "... |
package orm
import (
"database/sql"
"time"
"video_server/api/defs"
"video_server/api/utils"
)
func AddVideo(authorId int, name string) (video *defs.Video, errs error) {
videoId, err := utils.NewUUID()
if err != nil {
return nil, err
}
t := time.Now()
// Jan 02 2006, 15:04:05 时间原点
ctime := t.Format("Jan ... |
package main
import "fmt"
func main() {
var s []int
for i := range s {
fmt.Println(i)
}
fmt.Println("vim-go")
}
|
package authenticate
import (
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/identity"
"github.com/pomerium/pomerium/internal/identity/oauth"
"github.com/pomerium/pomerium/internal/urlutil"
)
func defaultGetIdentityProvider(options *config.Options, idpID string) (identity.Authenticat... |
package cfmysql
import "os"
//go:generate counterfeiter . OsWrapper
type OsWrapper interface {
LookupEnv(key string) (string, bool)
Name(file *os.File) string
Remove(name string) error
WriteString(file *os.File, s string) (n int, err error)
}
func NewOsWrapper() OsWrapper {
return new(osWrapper)
}
type osWrapp... |
package main
func BinarySearch(arr []int, t int) int {
l := 0
r := len(arr)
for l < r {
mid := (l + r) / 2
if arr[mid] == t {
return mid
} else if arr[mid] > t {
r = mid
} else {
l = mid + 1
}
}
return -1
}
|
package Collections
import "fmt"
//双数组Trie树
type DATrie struct {
Base []int //base数组
Check []int //check数组
Tail [][]rune // 存放尾串的数组
tailPosition int // 现在尾串的位置
RuneCodeMap map[rune]int //<字符,code码>hash表
}
//标记结束的字符
const EndRune = '#'
//初始化双数组Tire
func NewDAT... |
package app
import (
"fmt"
"github.com/blang/semver"
"github.com/rhysd/go-github-selfupdate/selfupdate"
"strings"
)
func DoSelfUpdate(currentVersion string) {
ver := semver.MustParse(strings.TrimPrefix(currentVersion, "v"))
slug := "Brialius/jira2trello"
latest, found, err := selfupdate.DetectLatest(slug)
i... |
package stdout
import (
"github.com/k0kubun/pp"
"github.com/cloudfly/ecenter/pkg/sender"
)
func init() {
sender.Register(Name, New)
}
// 发送器名称
const (
Name = "stdout"
)
// Sender represents a email sender
type Sender struct{}
// New create new sender
func New(setting map[string]string) (sender.Sender, error) ... |
package authproxy
import (
"net/http"
"time"
)
func createAccessTokenCookie(accessToken string) *http.Cookie {
return &http.Cookie{
Name: accessTokenCookieName,
Value: accessToken,
Path: "/",
HttpOnly: true,
Secure: false, // TODO
Expires: time.Time{}, // TODO
MaxAge: 0, ... |
package suite
import (
"benchmark/connection"
"fmt"
"errors"
"benchmark/helpers"
"math/rand"
)
const testPrefixSet = "set"
type SetCommand struct {
T GeoType
}
func (c *SetCommand) Fire(conn connection.ConnectorReadWriter) error {
var command string
switch c.T {
case Point:
lat, lon := helpers.RandomPoi... |
package terraform_kintone
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/naruta/terraform-provider-kintone/kintone"
"github.com/naruta/terraform-provider-kintone/kintone/raw_client"
)
func resourceKintoneRecord() *schema.Resource {
return &schema.Resource{
Creat... |
package main
import (
"flag"
"fmt"
"github.com/gotk3/gotk3/cairo"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/gtk"
"os"
"runtime/pprof"
)
var initialConfig = ""
const lowBits64 uint64 = 0x5555555555555555
const bitsPerCell = 4
const cellsPerInt = 64 / bitsPerCell
const cellMask uint64 = (1 << bitsPe... |
package nodenormal
import (
"fmt"
"time"
"github.com/fananchong/go-xserver/common"
nodecommon "github.com/fananchong/go-xserver/internal/components/node/common"
"github.com/fananchong/go-xserver/internal/protocol"
"github.com/fananchong/go-xserver/internal/utility"
)
// IntranetSession : 网络会话类( Gateway 客户端会话类 ... |
package prettyprint
import (
"fmt"
"testing"
)
func TestCanvas(t *testing.T) {
canvas := NewCanvas(4, 4)
canvas.DrawLine(0, 0, 1, 1, "foo")
canvas.DrawLine(2, 2, 1, 1, "t")
canvas.DrawLine(1, 1, 0, 2, "bar")
canvas.DrawLine(2, 0, 1, 1, "")
fmt.Print(canvas)
}
|
package alerting
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"github.com/square/p2/pkg/util"
)
type Urgency string
const (
pagerdutyURI = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
eventType = "trigger"
HighUrgency Urgency = "high_urgency"
LowUrgency Urgency ... |
package gomvc
import (
"fmt"
"strings"
)
// type HttpMethod int8
// const (
// ALL_METHOD HttpMethod = 0
// GET HttpMethod = 1
// POST HttpMethod = 2
// PUT HttpMethod = 4
// DELETE HttpMethod = 8
// HEAD HttpMethod = 16
// )
/**
Action实体类
*/
type ActionInfo struct {
Name ... |
package leetcode
func heightChecker(heights []int) int {
counter := make([]int, 101)
for _, n := range heights {
counter[n]++
}
offset := 0
ans := 0
for i := 1; i <= 100; i++ {
for j := 0; j < counter[i]; j++ {
if heights[offset] != i {
ans++
}
offset++
}
}
return ans
}
|
package repository
import (
"context"
"database/sql"
"fmt"
"github.com/lib/pq"
"github.com/rs/zerolog/log"
"github.com/go-sink/sink/internal/app/datastruct"
)
// LinkRepository data structure.
type LinkRepository struct {
database *sql.DB
}
// NewLinkRepository creates new LinkRepository instance.
func NewL... |
package api
import (
"github.com/PhongVX/taskmanagement/internal/app/user"
)
func newUserHandler() (*user.Handler, error) {
s, err := dialDefaultMongoDB()
if err != nil {
return nil, err
}
repo := user.NewMongoDBRepository(s)
srv := user.NewService(repo)
handler := user.NewHTTPHandler(*srv)
return handler, ... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package test
import (
"github.com/iotaledger/wasp/contracts/common"
"github.com/iotaledger/wasp/packages/solo"
"github.com/stretchr/testify/require"
"testing"
)
func setupTest(t *testing.T) *solo.Chain {
return common.DeployContract(t, ScNam... |
package main
import (
_"github.com/go-sql-driver/mysql"
"fmt"
"github.com/jmoiron/sqlx"
)
type Person struct {
UserId int `db:"userid"`
UserName string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
}
type Place struct {
Counttry string `db: "country"`
City string... |
// There has gotta be away around the nasty copypasta hacks
// TODO: FIX THAT SHIT
package libTransmission
import (
"net/http"
"encoding/json"
"log"
"bytes"
"io"
"errors"
"github.com/germ/geoip"
)
var (
ServerURL = "http://:9090/transmission/rpc"
ServerUser = "germ"
ServerPass = "hackersgonnahack"
)
func ... |
package evaluator
import (
"testing"
"github.com/stretchr/testify/assert"
e "github.com/optimizely/go-sdk/pkg/entities"
)
var stringFooCondition = e.Condition{
Type: "custom_attribute",
Match: "exact",
Name: "string_foo",
Value: "foo",
}
var boolTrueCondition = e.Condition{
Type: "custom_attribute",
Ma... |
package raw_client
import (
"context"
)
type GetAppSettingsRequest struct {
App string `json:"app"`
}
type GetAppSettingsResponse struct {
Name string `json:"name"`
Description string `json:"description"`
Theme string `json:"Theme"`
}
func GetAppSettings(ctx context.Context, apiClient *ApiClient, ... |
package cli
import (
"fmt"
"os"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
"github.com/usedepi/depi/pkg/config"
"github.com/usedepi/depi/pkg/datastore"
)
type App struct {
*cli.App
database datastore.Datastore
config *config.Config
}
// CLI application... |
package leetcode
import "fmt"
// 最清晰简洁
func moveZeroes(nums []int) {
zi := 0
for i := 0; i < len(nums); i++ {
if nums[i] != 0 {
nums[zi] = nums[i]
zi++
}
}
for i := zi; i < len(nums); i++ {
nums[i] = 0
}
}
// 大学 更清晰简洁
func moveZeroes4(nums []int) {
zi, nzi := -1, -1
for i := 0; i < len(nums); i++... |
package aria2
import (
"github.com/jlb0906/micro-movie/basic"
"github.com/jlb0906/micro-movie/basic/config"
"github.com/micro/go-micro/v2/logger"
"sync"
)
var (
c *Conf
m sync.RWMutex
inited bool
)
// 配置
type Conf struct {
Uri string `json:"uri"`
Token string `json:"token"`
Timeout ... |
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
simplejson "github.com/bitly/go-simplejson"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
/**
* 在脉脉网验证
**/
func validMaiMai(proxyURL string) bool {
proxy := func(_ *http.Request) (*url.URL, error) {
return url.Parse(proxyURL)
}
trans... |
// Copyright 2023 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 db
import (
"time"
"github.com/go-redis/redis"
"github.com/golang/glog"
"sub_account_service/finance/config"
)
var RedisClient *redis.Client
func InitRedis() {
RedisClient = redis.NewClient(&redis.Options{
Addr: config.Opts().RedisAddr,
Password: config.Opts().RedisPasswd, // no password set
... |
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package inttests
import (
"encoding/json"
"net/http"
"strings"
"testing"
types "github.com/openfaas/faas-provider/types"
requests "github.com/openfaas/faa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.