text stringlengths 11 4.05M |
|---|
package abcc
import (
"testing"
)
func TestTimestamp(t *testing.T) {
if info, err := GetInstance().Timestamp(nil); err != nil {
t.Fatal(err)
} else if info.Timestamp == 0 {
t.FailNow()
}
}
func TestMarkets(t *testing.T) {
if info, err := GetInstance().Markets(nil); err != nil {
t.Fatal(err)
} else if inf... |
package main
import (
"log"
"os"
"os/exec"
"strings"
)
func main() {
config, err := ReadConfig()
if err != nil {
log.Fatalf("Fatal error reading config file: %s\n", err)
}
protoc := GenProtoString(config)
if err := verifyDirectories(config); err != nil {
log.Fatalf("Could not create output directories:... |
package htmlrenderer
import (
"github.com/driusan/de/renderer"
)
func init() {
renderer.RegisterRenderer("html", &HTMLSyntax{})
renderer.RegisterRenderer("css", &HTMLSyntax{})
}
|
package main
import (
"fmt"
)
func main() {
var n int
fmt.Print("Enter a number: ")
fmt.Scan(&n)
fmt.Println(n)
fmt.Printf("the binary of %d is:", n)
fmt.Printf("%b\n", n) // 1111011
}
|
package main
import "fmt"
func main() {
// call a function with the same function and once you hit return in any function, the code bellow the return
// will not run again
fmt.Println(factorial(4))
}
func factorial(x int) int {
if x == 0 {
return 1
}
return x * factorial(x-1)
}
|
package server
import (
"log"
"net/http"
"os/exec"
"strings"
"encoding/json"
"net/http/httputil"
"bytes"
"time"
)
type BulkRequestAuth struct {
Username string `json:"username"`
Password string `json:"password"`
}
type BulkRequest struct {
Type string `json:"type"`
Auth BulkRequestAuth `json:"Auth"`
Sen... |
/*
Copyright 2020 The Tilt Dev 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, sof... |
package bitcoin_load_spike
// Assumptions
const BITCOIN_BLOCK_RATE float64 = 1.0 / 600.0 // 1 block every 10 minutes
const BITCOIN_TRANSACTION_SIZE float64 = (1024 * 1024) / 1200 // ~500 bytes
const BITCOIN_MAX_TPS float64 = 3.5 // maximum number of txns per sec
// Default sim... |
package main
import "fmt"
import "math"
type Circle struct {
x, y, r float64
}
type Android struct {
Person // don't have to declare a name
Model string
}
type Person struct {
Name string
}
func (p *Person) Talk() {
fmt.Println("Hi, my name is", p.Name)
}
func main() {
/*
defer func() { // run after fu... |
package xin
import (
"io"
"io/ioutil"
"strings"
)
type reader struct {
source string
index int
max int
position
}
func newReader(path string, r io.Reader) (*reader, error) {
allBytes, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
asString := string(allBytes)
rdr := reader{
source: ... |
// 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 accountmanager
import (
"context"
"path/filepath"
"time"
"chromiumos/tast/errors"
"chromiumos/tast/local/arc"
"chromiumos/tast/local/arc/optin"
"chromiumos/t... |
package main
type UpdateCommand struct {
Version string `short:"v" long:"version" description:"version of DhyveOS to install"`
}
func (c *UpdateCommand) Execute(args []string) error {
steps := Steps{
{
"Downloading OS",
func() error {
if c.Version == "" {
latest, err := GetLatestOSVersion()
if... |
package column
import (
"fmt"
"unsafe"
"github.com/vahid-sohrabloo/chconn/v2/internal/readerwriter"
)
// Column use for most (fixed size) ClickHouse Columns type
type Base[T comparable] struct {
column
size int
numRow int
values []T
params []interface{}
}
// New create a new column
func New[T comparable](... |
package main
//2379. 得到 K 个黑块的最少涂色次数
//给你一个长度为 n 下标从 0 开始的字符串 blocks ,blocks[i] 要么是 'W' 要么是 'B' ,表示第 i 块的颜色。字符 'W' 和 'B' 分别表示白色和黑色。
//
//给你一个整数 k ,表示想要 连续 黑色块的数目。
//
//每一次操作中,你可以选择一个白色块将它 涂成 黑色块。
//
//请你返回至少出现 一次 连续 k 个黑色块的 最少 操作次数。
//
//
//
//示例 1:
//
//输入:blocks = "WBBWWBBWBW", k = 7
//输出:3
//解释:
//一种得到 7 个连续黑色块的方法是... |
package main
import (
"flag"
"log"
"github.com/itsyouonline/identityserver/clients/go/itsyouonline"
)
var (
appID = flag.String("app_id", "", "application ID")
appSecret = flag.String("app_secret", "", "application secret")
)
func main() {
flag.Parse()
if *appID == "" || *appSecret == "" {
log.Fatalf("... |
package api
import "errors"
// ErrNotAvailable indicates that a feature is not available
var ErrNotAvailable = errors.New("not available")
// ErrMustRetry indicates that a rate-limited operation should be retried
var ErrMustRetry = errors.New("must retry")
// ErrSponsorRequired indicates that a sponsor token is req... |
package examples
import (
"fmt"
"log"
"github.com/kuaidaili/golang-sdk/api-sdk/kdl/auth"
"github.com/kuaidaili/golang-sdk/api-sdk/kdl/client"
"github.com/kuaidaili/golang-sdk/api-sdk/kdl/signtype"
)
// 私密代理使用示例
// 接口鉴权说明:
// 接口鉴权方式为必填项, 目前支持的鉴权方式有"simple" 和 "hmacsha1"两种
// 可选值为signtype.SIMPLE和signtype.HmacSha1... |
package handler
import (
"net/http"
"github.com/gorilla/mux"
"controller/model"
)
var LoginUserVars map[*http.Request]*model.User
var RepoVars map[*http.Request]*model.Repo
var NodeVars map[*http.Request]*model.Node
var GroupVars map[*http.Request]*model.Group
var GlobalRepoVars map[*h... |
package readers
import (
"strings"
)
type CSVParse struct {
Comma string
Comment string
}
func (c *CSVParse) Parse(line string) []string {
comma := c.Comma
if comma == "" {
comma = ","
}
comment := c.Comment
if comment != "" {
line = strings.Split(line, comment)[0]
}
return strings.Split(line, comma)... |
package gomc
import (
"fmt"
"io/ioutil"
"log"
"os"
)
const (
RED = "\033[31m"
END = "\033[0m"
)
func isPrintable(ch byte) bool {
return 0x20 <= ch && ch < 0x7F
}
func DmMain(args []string) {
var ab []byte
if len(args) > 0 {
var err error
ab, err = ioutil.ReadFile(args[0])
if err != nil {
log.Fatal... |
package server
import (
"d7y.io/dragonfly/v2/manager/handlers"
"d7y.io/dragonfly/v2/manager/middlewares"
"d7y.io/dragonfly/v2/manager/service"
"github.com/gin-gonic/gin"
ginprometheus "github.com/mcuadros/go-gin-prometheus"
)
func initRouter(verbose bool, service service.REST) (*gin.Engine, error) {
// Set mode... |
// Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package security
import (
"context"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"strings"
"chromiumos/tast/common/testexec"
"chromiumos/tast/local/sysutil"
"c... |
package main
import "testing"
func TestRollerCoaster(t *testing.T) {
for k, v := range map[string]string{
"To be, or not to be: that is the question.": "To Be, Or NoT tO bE: tHaT iS tHe QuEsTiOn.",
"Whether 'tis nobler in the mind to suffer": "WhEtHeR 'tIs NoBlEr In ThE mInD tO sUfFeR",
"The slings and ar... |
/*
This file implements decoding the modern (starting from 1.18) replay format.
*/
package repdecoder
import (
"bytes"
"compress/zlib"
"io"
)
// modernDecoder is the Decoder implementation for modern replays.
type modernDecoder struct {
decoder
}
var knownModernSectionIDSizeHints = map[int32]int32{
131342625... |
package lc
// Time: O(n)
// Benchmark: 12ms 5.2mb | 85%
// Implementation of Boyer-Moore algorithm to determine majority element.
func majorityElement(nums []int) []int {
var c1, c1Total int
var c2, c2Total int
for _, n := range nums {
if c1 == n {
c1Total++
} else if c2 == n {
c2Total++
} else if c1T... |
// Package batch accumulate elements in to a batch and then push it out
// batch is pushed out if the element limit is reached or timer expires
package batch
import (
"time"
)
// Batch object that holds the various state for batching
type Batch struct {
maxItems int
maxAge time.Duration
age ... |
package node
import (
"github.com/kyokan/plasma/db"
"github.com/kyokan/plasma/chain"
"github.com/pkg/errors"
"github.com/kyokan/plasma/eth"
"bytes"
"time"
"github.com/kyokan/plasma/util"
"strconv"
"github.com/kyokan/plasma/log"
"github.com/sirupsen/logrus"
)
type TransactionConfirmer struct {
storage db.P... |
package ga
import (
"sort"
"testing"
"github.com/pasqualesalza/amqpga/util"
)
// Utility function.
func benchmarkDataAdjustment(chromosomeSize int, individualsNumber int, b *testing.B) {
individuals := make([]*Individual, individualsNumber)
for i := 0; i < individualsNumber; i++ {
individuals[i] = new(Individ... |
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package auth
// Tokenizer specifies API for encoding and decoding between string and Key.
type Tokenizer interface {
// Issue converts API Key to its string representation.
Issue(Key) (string, error)
// Parse extracts API Key data from string token.... |
package main
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBin(t *testing.T) {
// ✅ Success
req, _ := http.NewRequest("GET", "/bin", nil)
q := req.URL.Query()
q.Add("platform", "linux")
req.URL.RawQuery = q.Encode()
w := httptest.NewRecorder()
router.S... |
package websteps
import (
"context"
"errors"
"net/url"
"testing"
"github.com/ooni/probe-cli/v3/internal/errorsx"
)
func TestMeasureSuccess(t *testing.T) {
req := &CtrlRequest{
URL: "https://example.com",
}
resp, err := Measure(context.Background(), req, &Config{})
if err != nil {
t.Fatal("unexpected err... |
/*
Go.geo is a geometry/geography libary in Go. Its purpose is to allow for
basic point, line and path operations in the context of online mapping.
*/
package geo
|
package haobtc
import (
. "config"
"crypto/md5"
"encoding/json"
"errors"
"fmt"
"io"
"logger"
"net/url"
"sort"
"strings"
"util"
)
type HaobtcTrade struct {
name string
api_key string
secret_key string
errno int64
}
func NewHaobtcTrade(name, api_key, secret_key string) *HaobtcTrade {
w :=... |
package math
type Spherical struct {
radius float32
phi float32 // polar angle
theta float32 // azimuthal angle
}
func NewDefaultSpherical() *Spherical {
return NewSpherical(1, 0, 0)
}
func NewSpherical(radius float32, phi float32, theta float32) *Spherical {
return &Spherical{
radius: radius,
phi: p... |
package discern
import (
"github.com/grd/statistics"
"github.com/hahnicity/go-discern/config"
"sort"
"time"
)
const FIVE_DAYS_AGO int64 = 60 * 60 * 24 * 5
// Find all companies with abnormally high activity within the last
// 5 days.
func FindRecentDates(wr *WikiResponse, f float64) (dates map[stri... |
// Code generated; DANGER ZONE FOR EDITS
package data
import (
"bytes"
"encoding/json"
"fmt"
"gopkg.in/yaml.v2"
)
const SandboxPatternDefinitionName = "sandbox-pattern"
type SandboxPatternDefinitions map[string]SandboxPatternDefinition
func (d SandboxPatternDefinitions) Keys() (out []string) {
for k := range ... |
// Copyright 2015 The Vanadium 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 main
import (
"golang.org/x/mobile/exp/sprite"
"hearts/logic/card"
"hearts/logic/player"
"hearts/logic/table"
"sort"
"testing"
)
var (
te... |
/*
Copyright 2020 Docker Compose CLI 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 a... |
package ui
import (
"fmt"
"image/color"
"engo.io/ecs"
"engo.io/engo"
"engo.io/engo/common"
)
var (
buttonFnt = &common.Font{
URL: "Roboto-Regular.ttf",
FG: color.Black,
Size: 20,
}
)
// Menu is a collection of UIElements arranged to build a menu
// It only sets the values of the elements
type Menu s... |
package leetcode_0173_二叉搜索树迭代器
/*
实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
示例:
7
/ \
3 15
/ \
9 20
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.ha... |
package main
// capturetime (datetime), temperature (string), mask (boolean), picture (base 64 string)
import (
"local/user-svc/_data"
"local/user-svc/_services"
"os"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
allowedHost := os.Getenv("ALLOWED")
_data.InitializeUserDataba... |
package main
import (
"fmt"
"regexp"
)
func extract(s string) string {
re := regexp.MustCompile(`tokopedia.com/discovery/(.*)/`)
matches := re.FindStringSubmatch(s)
if len(matches) == 0 {
return "no matches"
}
return matches[1]
}
func main() {
fmt.Println(extract("http://tokopedia.com/discovery/get-this-st... |
// Copyright (C) 2021 Storj Labs, Inc.
// See LICENSE for copying information.
package main
func main() { println("hello") }
|
package main
import (
"bufio"
"fmt"
"os"
)
var counts = make(map[string]int)
func main() {
in := bufio.NewScanner(os.Stdin)
in.Split(bufio.ScanWords)
for in.Scan() {
if in.Text() == "end" {
break
}
counts[in.Text()]++
}
for c, n := range counts {
fmt.Printf("%s\t%d\n", c, n)
}
}
|
// Copyright 2020 The VectorSQL Authors.
//
// Code is licensed under Apache License, Version 2.0.
package dataformats
import (
"io"
"sync"
"datablocks"
)
type TSVOutputFormat struct {
mu sync.RWMutex
writer io.Writer
withNames bool
}
func NewTSVOutputFormat(writer io.Writer) IDataBlockOutputFormat... |
package models
import (
"regexp"
"time"
vd "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// Device : Device model
type Device struct {
ID uint `gorm:"primary_key"`
UserID uint `gorm:"" json:"userId"`
Na... |
// Copyright (c) Liam Stanley <me@liamstanley.io>. All rights reserved. Use
// of this source code is governed by the MIT license that can be found in
// the LICENSE file.
package girc
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"... |
package calltracking
import (
"github.com/exitialis/workshop/homework/complex/internal/clients/calltracking"
)
type Client interface {
GetVirtual(request calltracking.GetPhoneIn) (*calltracking.CalltrackingResponse, error)
}
type GetPhoneIn struct {
RealPhone string
ItemID int64
UserID int64
}
|
package maxarraysum
import "testing"
type testCase struct {
name string
arr []int32
maxSum int32
}
var testCases = []testCase{
{"0", []int32{3, 7, 4, 6, 5}, 13},
{"1", []int32{2, 1, 5, 8, 4}, 11},
{"2", []int32{3, 5, -7, 8, 10}, 15},
}
func TestMaxSubsetSum(t *testing.T) {
for _, tc := range testCases {... |
package main
import (
"context"
"fmt"
"time"
)
func main() {
//设置deadline
d := time.Now().Add(4 * time.Second)
//初始化context
ctx, cancel := context.WithDeadline(context.Background(), d)
defer cancel()
select {
case <-time.After(5 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println... |
package main
import (
"log"
"os"
"os/signal"
"github.com/hfurubotten/eleetbot/tgbot"
)
func main() {
// Starting bot
bot, err := tgbot.NewTelegramBot(tgbot.EliteTimeBotToken)
if err != nil {
log.Fatal("Couldn't open the Telegram Bot. Error: " + err.Error())
}
err = bot.Start()
if err != nil {
log.Fata... |
package mysql_define
/** 4.INFIMUM && SUPREMUM **/
/* Number of extra bytes in a new-style record,
* in addition to the data and the offsets */
const REC_N_NEW_EXTRA_BYTES = 5 //new-style记录扩展字节
const InfoFlagsPlusNOwned = 1 // 1 byte
const HeapNoPlusRecordType = 2 // 2 byte
const NextRecord = 2 // 2 byte... |
package main
import (
"fmt"
"github.com/lukasbeckercode/HelloGo/03_packages/strutil" //my own package
"math"
) //more than 1 import NO COMMA
func main() {
fmt.Println(math.Floor(3.7))
fmt.Println(math.Ceil(3.4))
fmt.Println(math.Round(3.7))
fmt.Println(strutil.Reverse("Lukas"))
}
|
package v1
import (
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
/*
XXX: Ensure code generators are re-run anytime fields are added, removed, or
their types changed!
*/
// Variable is a named secret.
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type Variable struct {
meta_v1.Type... |
package JsProduct
import (
"JsGo/JsBench/JsComments"
"JsGo/JsBench/JsEvaluate"
)
type Color struct {
Color string
Text string
}
type ProductFormat struct { //产品规格
Format string //规格说明
Pic string //规格对应的图片
Price int //规格对应的价格
Inventory int //规格库存
//
}
type Product struct {
UID st... |
package context_rpc_client
import (
"fmt"
"github.com/grpc-example/api"
"log"
"net/rpc"
)
func DoClientWork(client *rpc.Client) {
defer client.Close()
var reply string
err := client.Call(api.HelloServiceName + ".Hello", "world!", &reply)
if err != nil {
fmt.Println(err.Error())
if err.Error() == "plea... |
package mail
import (
. "github.com/stretchr/testify/assert"
"io/ioutil"
_ "os"
"testing"
)
func Test_StoreBasicOperations(t *testing.T) {
dir, _ := ioutil.TempDir("", "")
//defer os.RemoveAll(dir)
println(dir)
store := NewStore()
NoError(t, store.Open(dir))
m := DBMailing{
ID: "theId",
Temp... |
package web
import "net/http"
func CusService() {
//文件服务器将当前目录作为根目录
http.Handle("/", http.FileServer(http.Dir(".")))
// 默认的 HTTP 服务侦听在本机 8080 端口
http.ListenAndServe(":8055", nil)
}
|
package jwt
import (
"crypto/rand"
"encoding/binary"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"log"
"net/http"
"strconv"
)
type UserInfo struct {
ID string `json: "id"`
Name string `json:"name"`
Pass string `json:"pass"`
jwt.StandardClaims
}
// ID発行済みかを判定してHOME画面に飛ばす
func LoginMyPag... |
// Copyright 2020 Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in complian... |
package 滑动窗口
func maxslidingWindow(nums []int, k int) []int {
if len(nums) == 0 {
return []int{}
}
queue := []int{}
result := []int{}
for i := range nums {
for i > 0 && len(queue) > 0 && nums[i] > queue[len(queue)-1] {
queue = queue[:len(queue)-1]
}
queue = append(queue, nums[i])
if i >= k && nums[... |
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package drivefs
import (
"context"
"fmt"
"time"
"golang.org/x/oauth2"
"chromiumos/tast/errors"
"chromiumos/tast/local/chrome"
"chromiumos/tast/testing"
)
const (
... |
package JsConfig
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
)
var g_cfg map[string]interface{}
func GetConfigString(keys []string) (string, error) {
ret := g_cfg
L := len(keys)
i := 0
for {
if i == L {
return "", errors.New(fmt.Sprintf("no relative key %v", keys))
}
tmp, ok := ret... |
// package shell contains check implementations that rely on utilizing
// shell commands directly through the use of cmd.Exec. This implies that the
// various shell tools are installed.
package shell
import (
"github.com/redhat-openshift-ecosystem/openshift-preflight/cli"
)
// Create a package-level podmanEngine va... |
/**
* Created by: Jianyi
* Date: 2019/1/4
* Time: 17:34
* Description:
**/
package api
import (
"official/models"
"fmt"
"github.com/astaxie/beego"
)
var CaseType = map[string]int{
"A":1,
"F":2,
"G":3,
"U":4,
"E":5,
}
type CasesApiController struct {
BaseController
}
func (self *CasesApiController)... |
package service
import (
"fmt"
"strings"
"time"
"github.com/globalsign/mgo/bson"
"intelliq/app/common"
utility "intelliq/app/common"
"intelliq/app/dto"
"intelliq/app/model"
"intelliq/app/repo"
)
//AddNewGroup adds new group
func AddNewGroup(group *model.Group) *dto.AppResponseDto {
group.Code = common.GRO... |
package firebase
import "github.com/sp0x/torrentd/storage/stats"
func (f *FirestoreStorage) GetStats(showDebug bool) *stats.Stats {
return nil
}
|
// Copyright 2019 Yunion
//
// 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 writi... |
package main
import(
"os"
"fmt"
"strings"
"net/http"
"html/template"
"runtime"
"reflect"
"net"
"log"
"flag"
"io/ioutil"
"strconv"
"path"
_ "github.com/go-sql-driver/mysql"
"database/sql"
)
var (
addr = flag.Bool("addr", false, "find open address and print to final-port.txt")
)
... |
package ginbro
import (
"fmt"
"github.com/fatih/color"
"os"
"os/exec"
"path"
"path/filepath"
)
type app struct {
ProjectPath string
ProjectPackage string
AppSecret string
AppListen string
Resources []Resource
AuthTable string
AuthPassword string
DbType string
DbAddr ... |
package operations
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/peterzhang41/petStore/models"
"io/ioutil"
"net/http"
"strconv"
)
func UpdatePet(w http.ResponseWriter, r *http.Request) {
newPet, err := readBodyAndUnmarshalPet(r)
if err != nil {
fmt.Println(err.Error())
http.Error(w,... |
// Copyright (c) 2018 The MATRIX Authors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php
package blkgenor
import (
"github.com/MatrixAINetwork/go-matrix/consensus/blkmanage"
"github.com/MatrixAINetwork/go-matrix/log"
"github.c... |
package main
import (
"bytes"
"encoding/json"
"fmt"
log "github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"io/ioutil"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
)
func init() {
customFormatter := new(log.TextFormatter)
customFormatter.FullTimestamp = true // 显示完整时间
customForma... |
package main
import "fmt"
func main() {
arr := [5]int{}
arr[0] = 23
arr[1] = 32
arr[2] = 45
arr[3] = 54
arr[4] = 67
for k,v := range arr {
fmt.Printf("Key = %d, Value = %v\n",k,v)
}
fmt.Printf("%T",arr)
}
|
// Copyright (c) 2016-2019 Uber Technologies, 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... |
package solutions
func nthUglyNumber(n int) int {
if n == 1 {
return n
}
fives, threes, twos := 0, 0, 0
dp := make([]int, n)
dp[0] = 1
for i := 1; i < n; i++ {
dp[i] = min(dp[twos] * 2, min(dp[threes] * 3, dp[fives] * 5))
if dp[i] == dp[twos] * 2 {
twos++
... |
package loggan
import (
"encoding/json"
"fmt"
"io"
"time"
)
// Formatter is an interface that formatter for a log entry.
type Formatter interface {
// Format formats a log entry.
// Format writes formatted entry to the w.
Format(w io.Writer, entry *Entry) error
}
// RawFormatter is a formatter that doesn't fo... |
package deeplinks
import (
"fmt"
"strings"
)
// matchPath extracting path variables with template.
// it returns nil, false, if path doesn't match template
// got example: matchPath("/joinchat/{chat_id}", "/joinchat/abcdefg") returns {"chat_id":"abcdefg"}, false
// spiced up implementaition from https://git.io/Jtcv... |
package openrtb_ext
type ExtImpSaLunamedia struct {
Key string `json:"key"`
Type string `json:"type"`
}
|
package game
import "testing"
func TestPushPlayer(t *testing.T) {
var ps Players
ps2, err := ps.PushPlayer('X')
if err != nil {
t.Fatal(err)
}
if len(ps2) == 0 || ps2[0] != 'X' {
t.Fatal("failed to add Player to Players list")
}
}
func TestPushMove(t *testing.T) {
g := Game{3, Players{'A', 'B', 'C'}, Hi... |
package auth
import (
"errors"
"fmt"
"net/http"
"time"
webTokens "github.com/dgrijalva/jwt-go"
)
// Jwt allow works with JWT
type Jwt interface {
AuthMember(w http.ResponseWriter, memberID string) error
VerifyTokenFromHeader(r *http.Request) (string, error)
GetSecret() string
}
// NewJwt creates new jwt ins... |
package main
import "fmt"
func main() {
// 001 Binary convert
a := 5
fmt.Printf("%d\t%b\n", a, a)
// 002 example
b := (42 == 42)
c := (42 <= 43)
d := (42 >= 43)
e := (42 != 43)
f := (42 < 43)
g := (42 > 43)
fmt.Println(b, c, d, e, f, g)
// 003 const example
const (
cnst1 = 42
cnst2 int = 43
)
... |
package logger
import (
"errors"
"os"
log "github.com/Sirupsen/logrus"
"github.com/latam-airlines/crane/configuration"
)
var logger *log.Logger
func Configure(config configuration.Loggging, debug bool) error {
if logger == nil {
logger = log.New()
}
var err error
if logger.Level, err = log.ParseLevel(co... |
package stringify
const (
IndentationSize = 4
)
|
//
// Copyright (c) SAS Institute 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 agre... |
// Copyright 2019 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, ... |
// Copyright 2018 The gVisor 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 agree... |
package Week_03
func combine(n int, k int) [][]int {
if n < k || k == 0 {
return nil
}
res := make([][]int, 0)
for i := 1; i <= n-k+1; i++ {
res = append(res, genNum(i, k))
}
return res
}
func genNum(start int, k int) (res []int) {
for i := 1; i <= k; i++ {
res = append(res, start+i-1)
}
return
}
|
package main
// Version of dbmate
const Version = "1.0.1"
|
package main
const sourceString = `package main
import (
"fmt"
"io"
"os"
)
var stdin io.Reader = os.Stdin
var stdout io.Writer = os.Stdout
var stderr io.Writer = os.Stderr
func main() {
fmt.Fprintln(stdout, "Hello World!")
}
`
const testString = `package main
import (
"bytes"
"strings"
"testing"
)
var tes... |
package main
import (
"html/template"
"net/http"
"github.com/satori/go.uuid"
)
type user struct {
UserName string
First string
Last string
}
var tpl *template.Template
var dbUsers = map[string]user{} // user ID, user
var dbSessions = map[string]string{} // session ID, user ID
func init() {
tpl =... |
package test
import (
"context"
"fmt"
_"io/fs"
_"io/ioutil"
"os"
"reflect"
"strings"
"testing"
"time"
_"strconv"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/draftms/go_librar... |
package coolmsg
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"sync"
"github.com/vmihailenco/msgpack"
"golang.org/x/sync/semaphore"
)
const (
// From spec
TYPE_ERR = 0x81aba3f7522edc6b
// From spec
TYPE_OK = 0xd4924862b91c639d
// From spec
TYPE_CLUNK = 0xcf3a... |
package pkginit
import (
"fmt"
"runtime"
)
func init() {
fmt.Printf("Map: %v\n", m)
fmt.Println(info)
info = fmt.Sprintf("Os: %s, Arch: %s", runtime.GOOS, runtime.GOARCH)
}
var m = map[int]string{1: "A", 2: "B", 3: "C"}
var info string
func main() {
fmt.Println(info)
}
|
package util
import (
"bytes"
"fmt"
pbcom "github.com/CSUNetSec/netsec-protobufs/common"
radix "github.com/armon/go-radix"
"net"
"strconv"
)
func GetIP(a *pbcom.IPAddressWrapper) []byte {
if a.IPv4 != nil {
return a.IPv4
} else if a.IPv6 != nil {
return a.IPv6
}
return nil
}
// IPToRadixkey creates a b... |
// 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... |
// Copyright (c) 2016-2019 Uber Technologies, 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... |
package recursion
import (
"AlgorizmiGo/recursion"
"github.com/stretchr/testify/assert"
"testing"
)
func TestIslandsCount(t *testing.T) {
tests := []struct {
grid [][]int
expectedCount int
}{
{grid: getGridWith4Islands(), expectedCount: 4},
{grid: getGridWith3Islands(), expectedCount: 3},
}
f... |
package privnets_test
import (
"context"
"fmt"
"github.com/exoscale/egoscale"
"github.com/janoszen/exoscale-account-wiper/plugin"
"github.com/janoszen/exoscale-account-wiper/privnets"
"github.com/janoszen/exoscale-account-wiper/terraform"
"github.com/stretchr/testify/assert"
"testing"
)
func TestRemovingPrivn... |
/*
* @Descripttion: Danmu api
* @version: 1.0
* @Author: Nickname4th
* @Date: 2021-05-10 14:34:32
* @LastEditors: Nickname4th
* @LastEditTime: 2021-05-12 09:55:05
*/
package api
import (
"down-date-server/src/danmu"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var upGrader = webs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.