text stringlengths 11 4.05M |
|---|
/* main function */
/* file name: webcmd.go */
/* link: */
/* */
/* update: 20181122 */
package webdata
import (
"encoding/hex"
"fmt"
"log"
"loranet20181205/database"
"loranet20181205/exception"
"net"
_ "github.com/go-sql-driver/mysql"
)
func WebCm... |
package main
import (
"github.com/tiagorlampert/CHAOS/client/app"
"github.com/tiagorlampert/CHAOS/client/app/environment"
"github.com/tiagorlampert/CHAOS/client/app/ui"
)
var (
Version = "dev"
Port = ""
ServerAddress = ""
Token = ""
)
func main() {
ui.ShowMenu(Version, ServerAddress, P... |
package tests
import "testing"
func TestDirectoryListing(t *testing.T) {
testBuilder(t, defaultBuilder, "/directory-listing")
testBuilder(t, defaultBuilder, "/directory-listing/Files")
}
|
package main
import (
"context"
"encoding/json"
"flag"
"log"
"github.com/zaynjarvis/fyp/config/api"
"google.golang.org/grpc"
)
type Config struct {
Name string
Version int
Desc string
}
func main() {
var (
cfg = Config{Name: "service-name", Version: 1, Desc: "hello world"}
name ... |
package mapreduce
import (
"fmt"
)
func handleTask(worker string, args DoTaskArgs, successWorkerChan chan string, failWorkerChan chan string, taskChan chan DoTaskArgs) {
success := call(worker, "Worker.DoTask", &args, nil)
if success {
successWorkerChan <- worker
} else {
fmt.Println(worker, "executing task",... |
package main
//p173
import (
"fmt"
"math/rand"
"time"
)
func main() {
var arr [10]int
for i := 0; i < 10; i++ {
rand.Seed(time.Now().UnixNano())
var num int = rand.Intn(100)
fmt.Println(num)
time.Sleep(100 * time.Millisecond)
arr[i] = num + 1
}
fmt.Println(arr)
for index, value := range arr {
if v... |
package main
import (
"fmt"
)
func main() {
tamanhodocansaço := 2
switch {
case tamanhodocansaço == 0:
fmt.Println("que malandragem")
case tamanhodocansaço == 1:
fmt.Println("uma gelada ia bem")
case tamanhodocansaço == 2:
fmt.Println("ih já era, só nascendo denovo")
}
}
|
package _334_Increasing_Triplet_Subsequence
import (
"testing"
)
type testCase struct {
input []int
output bool
}
func TestIncreasingTriplet(t *testing.T) {
cases := []testCase{
{
input: []int{1, 2, 3, 4, 5},
output: true,
},
{
input: []int{5, 4, 3, 2, 1},
output: false,
},
{
input: ... |
package config
type Log struct {
File string `yaml:"file,omitempty"`
Level string `yaml:"level,omitempty"`
Formatter string `yaml:"formatter,omitempty"`
}
|
package etcd
import (
"context"
"fmt"
"github.com/coreos/etcd/clientv3"
"mall_server/store"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
type Wiper struct {
client *clientv3.Client
}
func NewClient() (*Wiper, error) {
cli, err := clientv3.New(clientv3.Config{
Endpoints: strings.Split(conf.Get().Etcd.... |
package opconf
// Default operation configuration
const defaultConfig = `0x10 BIPUSH byte
0x59 DUP
0xA7 GOTO label
0x60 IADD
0x7E IAND
0x99 IFEQ label
0x9B IFLT label
0x9F IF_ICMPEQ label
0x84 IINC var byte
0x15 ILOAD var
0xB6 INVOKEVIRTUAL method
0xB0 IOR
0xAC IRETURN
0x36 IS... |
package main
import (
"encoding/json"
"errors"
"strconv"
"github.com/clearmatics/autonity/rlp"
"github.com/ethereum/go-ethereum/common"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
// unmarshallState receives state in byte form and returns unmarshalled struct
func unmarshallState(state []byte) (Shares... |
/*
Copyright (c) 2020 Red Hat, 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 in writing, software... |
package repositories
import (
"blog/app/models"
"blog/database"
"github.com/jinzhu/gorm"
"github.com/mlogclub/simple"
"time"
)
type UserRepository struct {
db *gorm.DB
}
func NewUserRepository() *UserRepository {
return &UserRepository{
db: database.DB()}
}
func (this *UserRepository) List(paging *simple.P... |
// Copyright 2015 Simon HEGE. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package geodesic
import (
"bufio"
"compress/gzip"
"flag"
"fmt"
"math"
"os"
"testing"
"github.com/xeonx/geographic"
)
var (
deltaAz = flag.Float64("delt... |
package qingstor
import (
"context"
"net/http"
"github.com/sirupsen/logrus"
"github.com/yunify/qingstor-sdk-go/v3/config"
"github.com/yunify/qingstor-sdk-go/v3/service"
"gopkg.in/yaml.v2"
"github.com/yunify/qscamel/constants"
"github.com/yunify/qscamel/model"
)
// Client is the client to visit QingStor serv... |
package cache
import (
"blog/database"
"github.com/vmihailenco/msgpack/v4"
"github.com/go-redis/cache/v7"
)
var cached *cache.Codec
func GetCache() *cache.Codec {
if cached == nil {
cached = initCache()
}
return cached
}
// 初始化缓存模块 并注入缓存驱动
func initCache() *cache.Codec {
return &cache.Codec{
Redis: data... |
package main
import (
"bytes"
"crypto/tls"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"net/http"
"os"
"strconv"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/luno/moonbeam/address"
"git... |
package autonat
import (
pb "gx/ipfs/QmZgrJk2k14P3zHUAz4hdk1TnU57iaTWEk8fGmFkrafEMX/go-libp2p-autonat/pb"
ma "gx/ipfs/QmNTCey11oxhb1AxDnQBRHtdhap6Ctud872NjAYPYYXPuc/go-multiaddr"
logging "gx/ipfs/QmcuXC5cxs79ro2cUuHs4HQ2bkDLJUYokwL8aivcX6HW3C/go-log"
)
var log = logging.Logger("autonat-svc")
func newDialResponse... |
package web
import (
"testing"
"github.com/gin-gonic/gin"
"github.com/iGoogle-ink/gotil/xlog"
)
func TestInitServer(t *testing.T) {
// 需要测试请自行解开注释测试
//c := &Config{
// Port: ":2233",
// Limit: &limit.Config{
// Rate: 0, // 0 速率不限流
// BucketSize: 100,
// },
//}
//
//g := InitGin(c)
//g.Gin.Use(... |
package dynamic_programming
import "math"
func minDistance(word1 string, word2 string) int {
m := len(word1)
n := len(word2)
if m == 0 {
return n
}
if n == 0 {
return m
}
dp := make([][]int, m)
for i := range dp {
dp[i] = make([]int, n)
}
// 初始化第一行
for i := 0; i < n; i++ {
if word1[0] == word2[i]... |
package sql
/**
使用队列方式进行 sql 词组进行暂存
利用先进先出方式进行拼接 sql
*/
type SelectBuilder struct {
// 查询字段队列
Select *Select
// 查询表队列
From *From
// 查询条件队列
Where *Where
}
type ConditionFunc func(interface{}) bool
func NewSelectBuilder() *SelectBuilder {
sb := SelectBuilder{}
sb.Select = NewSelect()
sb.From = NewFrom()
sb.W... |
package main
import (
"path"
"regexp"
"strings"
)
var featureExtractors = []func(Tweet) Feature{
ExclamationMarks,
QuestionMarks,
DotMarks,
WordCount,
LetterCount,
BadWordCount,
GoodWordCount,
HappyEmoticon,
AngryEmoticon,
DCSList,
PositiveListCount,
NegativeListCount,
Posemo,
Negemo,
}
func Exclama... |
/*
Copyright 2021 CodeNotary, Inc. All rights reserved.
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 controllers
import (
"github.com/astaxie/beego"
"io/ioutil"
"os/exec"
"fmt"
"os"
"bytes"
"strings"
"github.com/bitly/go-simplejson"
)
// Operations about Ipfs
type IpfsController struct {
beego.Controller
}
var (
cmdOut []byte
err error
)
// @Title upload
// @Description upload json to IPFS
//... |
package main
import f "fmt"
func main() {
f.Println("beffered")
messages := make(chan string, 2)
messages <- "wisoft"
messages <- "lab"
f.Println(<-messages)
f.Println(<-messages)
}
|
package user
import (
"github.com/jinzhu/gorm"
"time"
"github.com/satori/go.uuid"
)
const (
SUPER_ADMIN = 0
ADMIN = 1
STAFF = 2
RESIDENT = 3
)
const (
RESET_PASSWORD_FROM_WEB = 1
RESET_PASSWORD_FROM_MOBILE = 2
)
const (
ScopesSuperAdmin = "supper_admin"
ScopesAdmin = "admin"
Scopes... |
// Copyright 2019 John Papandriopoulos. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package zydis
// CPUFlagAction is an enum of CPU action flags.
type CPUFlagAction int
// CPUFlagAction enum values.
const (
// The CPU flag is not tou... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/8/20 9:04 上午
# @File : lt_17_电话号码组合.go
# @Description :
# @Attention :
*/
package offer
var phoneMap map[byte]string = map[byte]string{
2: "abc",
3: "def",
4: "ghi",
5: "jkl",
6: "mno",
7: "pqrs",
8: "tuv",
9: "wxyz",
}
var ret []string
// 关键: 回溯法
fu... |
package main
import (
"fmt"
"net/http"
"net/http/httputil"
)
func main() {
request, err := http.NewRequest(http.MethodGet, "https://www.indiegogo.com/projects/cubo-ai-world-s-smartest-baby-monitor?secret_perk_token=d15cf19e#/", nil)
// request.Header.Add("User-Agent", "Mozilla/5.0 (iPhone)")
// res, err := http... |
package main
import "fmt"
func main() {
//main defer栈与sum的defer栈是独立的
defer fmt.Println("main defer1") //5
defer fmt.Println("main defer2") //4
fmt.Println("main res", sum(1, 2))
}
func sum(a int, b int) int {
var res int
//当执行到defer时,暂时不执行,会将defer后面的语句压入到独立的栈(defer栈)
//当函数执行完毕后(return后,defer在return后执行),再从def... |
package main
import (
"os"
"got/internal/cmd"
)
//var g = got.NewGot(disk.NewObjects(), file.ReadFromFile())
//var sum string
func main() {
if err := cmd.GotCmd.Execute(); err != nil {
os.Exit(1)
}
/*//fmt.Println(g.HashObject([]byte("test content"), true, objects.TypeBlob))
//fmt.Printf("[Objects]:\n%v\n",... |
package parametrs
import (
"reflect"
)
type IParamers interface {
ToMap() map[string]string
}
func TypeToMap(t interface{}) map[string]string {
retval := map[string]string{}
val := reflect.ValueOf(t).Elem()
for i := 0; i < val.NumField(); i++ {
valueField, ok := val.Field(i).Interface().(string)
if !ok ||... |
package timewheel
import (
"fmt"
"testing"
"time"
"github.com/lioneagle/goutil/src/test"
)
type record struct {
t1 time.Time
t2 time.Time
}
func TestTimeWheelAddOk(t *testing.T) {
testdata := []struct {
sceond int64
minute int64
hour int64
wheel int32
slot int32
}{
{1, 0, 0, 0, 1},
{59, 0... |
package goobj
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
)
const supportedGoObjVersion = 1
var magicHeader = []byte("\x00\x00go19ld")
var magicFooter = []byte("\xffgo19ld")
// File represents a go object file.
type File struct {
Symbols []Symbol
SymbolReferences []SymbolReference
DataBlock ... |
package config
import (
"net"
"net/url"
"strconv"
)
func getURLs(addr net.IP, port uint16, secret string) (urls URLs) {
values := url.Values{}
values.Set("server", addr.String())
values.Set("port", strconv.Itoa(int(port)))
values.Set("secret", secret)
urls.TG = makeTGURL(values)
urls.TMe = makeTMeURL(values... |
package day03
import (
"fmt"
)
type board struct {
terrain []bool
stride int
}
func (b *board) render() {
for i, v := range b.terrain {
if v {
fmt.Print("#")
} else {
fmt.Print(".")
}
if (i+1)%b.stride == 0 {
fmt.Println()
}
}
}
func (b *board) getCell(x, y int) (bool, error) {
x = x % b.s... |
package bmlog
import (
"github.com/sirupsen/logrus"
"os"
"testing"
)
func TestLogrus(t *testing.T) {
logrus.SetLevel(logrus.TraceLevel)
logrus.Trace("Trace msg")
logrus.Debug("Debug msg")
logrus.Info("Info msg")
logrus.Warn("Warn msg")
logrus.Error("Error msg")
//logrus.Fatal("Fatal msg")
//logrus.Panic("P... |
package models
import (
//"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"tokensky_bg_admin/conf"
)
// init 初始化
func init() {
//admin
orm.RegisterModel(new(AdminBackendUser), new(AdminResource), new(AdminRole), new(AdminRoleResourceRel), new(AdminRoleBackendUserRel))
orm.RegisterModel(new(AdminModelR... |
package typeutils
func Float32Ptr(f float32) *float32 {
return &f
}
|
// Copyright 2023 Google LLC. All Rights Reserved.
//
// 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 applica... |
package upstream
import (
"net/rpc"
"github.com/jonmorehouse/gatekeeper/gatekeeper"
)
type NotifyArgs struct{}
type NotifyResp struct{}
type AddUpstreamArgs struct {
Upstream *gatekeeper.Upstream
}
type AddUpstreamResp struct {
Err *gatekeeper.Error
}
type RemoveUpstreamArgs struct {
UpstreamID gatekeeper.Up... |
// 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... |
package main
import (
"fmt"
"os"
"time"
"github.com/fatih/color"
"github.com/piot/cli-screen/src/cliscreen"
"github.com/piot/cursor-go/src/cursor"
"github.com/piot/progressbar-go/src/progressbar"
)
func createDefaultCursor() cursor.Cursor {
writer := os.Stderr
c := cursor.NewAnsiCursor(writer)
const useDeb... |
// 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... |
package main
import "fmt"
type Creeper struct {
family string
id int
}
type Zombie struct {
family string
id int
}
type Skeleton struct {
family string
id int
}
type Enderman struct {
family string
id int
}
type Overworld struct {
creeper Creeper
zombie Zombie
husk ... |
package loader
import (
"io/ioutil"
"os"
"path/filepath"
homedir "github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
yaml "gopkg.in/yaml.v2"
"github.com/devspace-cloud/devspace/pkg/util/log"
"github.com/devspace-cloud/devspace/pkg/devspace/config/constants"
"github.com/devspace-cloud/devspace/pkg/dev... |
package kvdb
// IdealBatchSize defines the size of the data batches should ideally add in one
// write.
const IdealBatchSize = 100 * 1024
// Batch is a write-only database that commits changes to its host database
// when Write is called. A batch cannot be used concurrently.
type Batch interface {
KeyValueWriter
/... |
package test
import (
"dappapi/models"
config2 "dappapi/tools/config"
"encoding/json"
"fmt"
"github.com/spf13/cobra"
)
var (
secret string
api string
config string
StartCmd = &cobra.Command{
Use: "test",
Short: "initialize the database",
Run: func(cmd *cobra.Command, args []string) {
run... |
package main
import (
"fmt"
"os"
"github.com/wuiscmc/spotbot-cli/spotbot"
)
func control(option string, sp *spotbot.Spotbot, opts interface{}) {
switch option {
case "play":
sp.Play()
case "pause":
sp.Pause()
case "next":
sp.NextSong()
case "playlist":
//fmt.Println(sp.CurrentPlaylist())
case "curre... |
// Copyright 2015 by caixw, All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
// apidoc 是一个 RESTful API 文档生成工具。
package main
import (
"bytes"
"flag"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"strings"
"github.com/is... |
//go:generate msgp
package example
import (
"github.com/myitcv/neovim"
"github.com/tinylib/msgp/msgp"
)
// **************************
// DoSomethingAsync
func (n *Example) newDoSomethingAsyncResponder() neovim.AsyncDecoder {
return &doSomethingAsyncWrapper{
Example: n,
args: &DoSomethingAsyncArgs{},
}
}
f... |
package lang
import (
"fmt"
"testing"
)
func Test_Add(t *testing.T) {
var i I = 3
fmt.Println(i)
i.add(2)
fmt.Println(i)
}
|
package core
type Processor struct {
ProcessorChan chan string
ProcessorChanOut chan string
}
type MarketBeatStock struct {
Marker string
Today []string
Days30 []string
Days90 []string
Days180 []string
}
type SPBStock struct {
Id string
Marker string
Title string
Code1 string
Code2 ... |
package main
import (
"fmt"
"bufio"
"os"
"strconv"
)
type player struct{
xPosition int
yPosition int
}
func parsePlayersFromStdIn() (player, player){
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
gridSize, _ := strconv.Atoi(scanner.Text())
var hero player
var prince... |
package main
import (
"fmt"
"log"
"net/url"
"os"
"strings"
)
func main() {
if len(os.Args) < 2 {
log.Fatal("usage: urlencode <path fragment>")
}
u := &url.URL{Path: strings.Join(os.Args[1:], " ")}
fmt.Println(u.String())
}
|
package opts
import (
"errors"
"flag"
"fmt"
"local/notorious/logging"
"os"
"regexp"
"strings"
)
// raw CLI flags, only used to create an Opts during Parse()
var (
after = flag.Int("A", 0, "how many lines of context [A]fter the match to print")
before = flag.Int("B", 0, "how many lines of context [... |
package visagoapi
// BoundingPoly is used to store the
// vertexes marking the postition of the face.
type BoundingPoly struct {
Vertices []*Vertex `json:"vertices,omitempty"`
}
// Vertex is the x and y coordinates of a vertex
type Vertex struct {
X int64 `json:"x"`
Y int64 `json:"y"`
}
|
/*
Auto-Light let you control a led light by hands or any other objects.
It works with HCSR04, an ultrasonic distance meter, together.
The led light will light up when HCSR04 sensor get distance less then 40cm.
And the led will turn off after 45 seconds.
*/
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"l... |
package gogen
import (
"go/parser"
"go/token"
"go/ast"
"path/filepath"
"fmt"
)
// ParseDir will create a Build from the directory that
// was passed into the function.
func ParseDir(path string) (*Build, error) {
var fileSet token.FileSet
packages, err := parser.ParseDir(&fileSet, path, nil, parser.AllErrors)... |
// Used to show the landing page of the application
package requests
import (
"glsamaker/pkg/app/handler/authentication"
"glsamaker/pkg/app/handler/authentication/utils"
"glsamaker/pkg/database/connection"
"glsamaker/pkg/logger"
"glsamaker/pkg/models"
"net/http"
)
// Show renders a template to show the landing... |
package trea
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01200102 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:trea.012.001.02 Document"`
Message *ForeignExchangeOptionNotificationV02 `xml:"FXOptnNtfctnV02"`
}
func... |
/*
@File : test3.go
@Time : 2019/01/25 14:02:16
@Author : Bruce
@Version : 1.0
@Contact : bruce.he@patpat.com
@License : (C)Copyright 2019, patpat.com
@Desc : None
*/
package main
import (
"fmt"
)
func main() {
fmt.Println("hello2\n")
}
|
package oauth2
import (
"errors"
"github.com/dgrijalva/jwt-go"
"time"
)
func generateToken(client_id string, client_secret string, expire_time time.Duration) (string, error) {
param := map[string]string{
"client_id" : client_id,
}
return generateTokenWithParam(client_secret, expire_tim... |
package pipeline
import (
"io"
"log"
"sort"
)
func ArraySource(data ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range data {
out <- n
log.Println("write data to chan", n)
//time.Sleep(time.Second)
}
log.Println("end write data to chan")
close(out)
}()
return out
}
func ... |
/*
* @lc app=leetcode.cn id=42 lang=golang
*
* [42] 接雨水
*/
package main
import "fmt"
/*
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
*/
/* 按行求
func trap(height []int) int {
var (
max, heightLen, tmp, sum int
flag ... |
// Copyright © 2020 Attestant 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 agreed ... |
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package snapshotter
import (
"context"
"github.com/pkg/errors"
"github.com/dragonflyoss/image-service/contrib/nydus-snapshotter/config"
"github.com/dragonflyoss/image-service/contrib/nydus-snapshotter/pkg/uti... |
package dbserver
import (
"database/sql"
"github.com/labstack/echo"
)
type Db struct {
db *sql.DB
}
func (db Db) CreateTable(e echo.Context) error {
}
|
package bag
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewBag(t *testing.T) {
t.Run("Test create new bag", func(t *testing.T) {
bag := NewBag("vJrwpWtwJgWrhcsFMMfFFhFp")
assert.Equal(t, "vJrwpWtwJgWr", bag.FirstComp)
assert.Equal(t, "hcsFMMfFFhFp", bag.SecondComp)
})
}
func TestGet... |
package filters
import (
"fmt"
"math/rand"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stripe/unilog/clevels"
"github.com/stripe/unilog/json"
)
func TestCalculateSamplingRate(t *testing.T) {
type CalculateSamplingLevel struct {
Name string
Austerity clevels.AusterityLeve... |
package config_test
import (
"fmt"
"testing"
"github.com/debarshibasak/kubestrike/v1alpha1/config"
"github.com/ghodss/yaml"
)
func TestParsing(t *testing.T) {
kubeadm := `
apiVersion: kubestrike.debarshi.github.com/master/v1alpha1
kind: CreateClusterKind
provider: Multipass
multipass:
masterCount: 1
worke... |
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(storeWater([]int{1, 3}, []int{6, 8}))
//fmt.Println(storeWater([]int{9, 0, 1}, []int{0, 2, 2}))
fmt.Println(storeWater([]int{3, 2, 5}, []int{0, 0, 0}))
}
func storeWater(bucket []int, vat []int) int {
n := len(bucket)
maxk := 0
for _, v := rang... |
package main
import "fmt"
func max(a, b int) int {
if a > b {
return a
}
return b
}
func lengthOfLongestSubstringKDistinct(s string, k int) int {
if len(s) == 0 || k == 0 {
return 0
}
sChars := []rune(s)
start, end := -1, -1 // start is exclusive: (start, end]
maxLen := 0
currDistinctCount := 0
occMa... |
package staticrender
import (
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"testing"
"github.com/vugu/vugu/gen"
)
func TestRendererStaticTable(t *testing.T) {
debug := false
vuguDir, err := filepath.Abs("..")
if err != nil {
t.Fatal(err)
}
type tcase struct {
name string
opts ... |
package types
const TicketRandomnessLookback = 1
// DioneTask represents the values of task computation
type DioneTask struct {
OriginChain uint8
RequestType string
RequestParams string
Payload []byte
RequestID string
}
|
package ignoreme
import "fmt"
func Hello() {
fmt.Println(0b0001)
}
|
package controllers
import "bitbucket.org/waas_pro/api/middlewares"
func (s *Server) initializeRoutes() {
// Login Route
s.Router.HandleFunc("/login", middlewares.SetMiddlewareJSON(s.Login)).Methods("POST")
//Users routes
s.Router.HandleFunc("/users", middlewares.SetMiddlewareJSON(s.CreateUser)).Methods("POST")... |
package pkg
import (
"HttpBigFilesServer/MainApplication/internal/files/model"
"HttpBigFilesServer/MainApplication/internal/files/usecase"
"encoding/json"
)
func HandleDownLoadError(err error) int {
if err == usecase.ErrorSizesDoesNotMatch ||
err == usecase.ErrorCreateFile ||
err == usecase.ErrorWriteFile ||
... |
package ospafLib
import (
"fmt"
)
type Pool struct {
Accounts []Account
}
func InitPool() (pool Pool, err error) {
pool.Accounts, err = LoadAccounts("")
if err != nil {
fmt.Println("Cannot Using pool due to: ", err)
return pool, err
}
for index := 0; index < len(pool.Accounts); index++ {
pool.Accounts[i... |
package helper
import (
"github.com/astaxie/beego"
. "github.com/qiniu/api/conf"
qiuniu_io "github.com/qiniu/api/io"
"github.com/qiniu/api/rs"
"github.com/satori/go.uuid"
"io"
"strings"
)
func uptoken(bucketName string) string {
putPolicy := rs.PutPolicy{
Scope: bucketName,
}
return putPolicy.Token(nil)
}... |
package main
import (
"fmt"
"testing"
)
func Test_lastStoneWeight(t *testing.T) {
tts := []struct {
input []int
expected int
}{
{[]int{2, 7, 4, 1, 8, 1}, 1},
{[]int{1, 3}, 2},
}
for _, tt := range tts {
tt := tt
t.Run(fmt.Sprintf("input %v", tt.input), func(t *testing.T) {
t.Parallel()
a... |
// Copyright 2018 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 in wr... |
package mwords
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestEntropyBits(t *testing.T) {
t.Parallel()
// invalid entropy bits
for bits := uint(0); bits < entropyMinBits; bits++ {
if isValidEntropy(bits) {
t.Errorf("validated invalid number of bits %d\n", bits)
}
}
for bits := uint... |
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"strings"
v1 "github.com/idirall22/grpc_chat/api/pb"
"google.golang.org/grpc"
)
var id string
var toUserID string
func main() {
cc, err := grpc.Dial(":8080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer cc.Close()
client := v1.... |
package model
/*
https://rpki.apnic.net/repository/apnic-rpki-root-iana-origin.cer
rsync://rpki.apnic.net/repository/apnic-rpki-root-iana-origin.cer
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx9RWSL61YAAYumEiU8z8
qH2ETVIL01ilxZlzIL9JYSORMN5Cmtf8V2JblIealSqgOTGjvSjEsiV73s67zYQI
7C/iSOb96uf3/s86NqbxDiFQGN8qG7RNcdgVu... |
package editor
import (
"github.com/gdamore/tcell"
"github.com/jantb/olive/ds"
"github.com/rivo/tview"
)
type Gutter struct {
*tview.Box
*Editor
warning []ds.Position
error []ds.Position
cursorX, cursorY int
}
// NewView returns a new view view primitive.
func (e *Editor) NewGutter() *Gutter {
e.gutter_... |
/*
Chef has an integer sequence A1,A2,…,AN. For each index i (1≤i≤N), Chef needs to divide Ai into two positive integers x and y such that x+y=Ai, then place this as a point (x,y) in the infinite 2-dimensional coordinate plane.
Help Chef to find the maximum number of distinct points that can be put in the plane, if he... |
/*
Copyright 2019 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 s3
import (
"io"
"github.com/fastly/cli/pkg/common"
"github.com/fastly/cli/pkg/compute/manifest"
"github.com/fastly/cli/pkg/config"
"github.com/fastly/cli/pkg/errors"
"github.com/fastly/cli/pkg/text"
"github.com/fastly/go-fastly/fastly"
)
// UpdateCommand calls the Fastly API to update Amazon S3 loggi... |
package main
import "net/http"
const sessionCookie = "SESSION"
func setSession(w http.ResponseWriter, value string) {
c := http.Cookie{Name: sessionCookie, Value: value}
http.SetCookie(w, &c)
}
func (s *server) getUser(r *http.Request) string {
var visitingUser string
sess, err := r.Cookie(sessionCookie)
if er... |
package main
import "fmt"
const (
x = 1
y = "this"
z = true
)
type Weekday int
const (
Sunday Weekday = 0
Monday Weekday = 1
Tuesday Weekday = 2
Wednesday Weekday = 3
Thursday Weekday = 4
Friday Weekday = 5
Saturday Weekday = 6
)
func Weekend(day Weekday) bool {
switc... |
package quote
import (
"fmt"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/mmbros/quote/internal/quotegetter"
)
// TorCheck checks if a Tor connection is used,
// retrieving the "https://check.torproject.org" page.
// It returns:
// - bool: true if Tor is used, false otherwise
// - string: the messa... |
package main
import (
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// Enum types for contest state
const (
OPEN = iota
VOTING
CONCLUDED
)
// User collection in Mongo
type User struct {
Id primitive.ObjectID `bson:"_id"`
Username string `bson:"username"`
Password string `bson:"password"`
}
// Contes... |
package executor
import (
"fmt"
"io"
"os"
"os/exec"
"path"
"syscall"
"strings"
"io/ioutil"
log "github.com/sirupsen/logrus"
"github.com/virtru/cork/server/definition"
"github.com/virtru/cork/server/streamer"
)
func init() {
RegisterHandler("command", CommandStepHandler)
RegisterRunner("command", Comma... |
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Alpine ice climbing is the best sport!")
time.Sleep(time.Second * 1000)
}
|
package c31_hmac_sha1_timing_leak
import (
"bytes"
"github.com/vodafon/cryptopals/set1/c2_fixed_xor"
"github.com/vodafon/cryptopals/set4/c28_sha1_key_mac"
)
const (
blockSize = 64
outputSize = 20
)
type HMACSystem struct {
key []byte
hash *c28_sha1_key_mac.SHA1
}
func NewHMACSystem(key []byte) HMACSystem ... |
/**
* 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 test
import (
"encoding/json"
"fmt"
"github.com/davecgh/go-spew/spew"
"log"
"testing"
)
type Abc struct {
A string `json:"a,omitempty"`
B string `json:"b,omitempty"`
C string `json:"c,omitempty"`
}
func Test_aa(t *testing.T) {
k := int32(8008888)
fmt.Println(k)
}
func Test_map_r(t *testing.T) {
fm... |
package web
import (
"encoding/json"
"net/http"
"strings"
"github.com/cybozu-go/sabakan/v2"
)
func (s Server) handleLabels(w http.ResponseWriter, r *http.Request) {
args := strings.SplitN(r.URL.Path[len("/api/v1/labels/"):], "/", 2)
if len(args) == 0 || len(args[0]) == 0 {
renderError(r.Context(), w, APIErrB... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.