text
stringlengths
11
4.05M
package main import ( "fmt" "math" ) func main() { array := []int{3, 2, 1, 20, 5, 6, 42, -2, 4, 3} result := mergeSort(array) fmt.Println(result) } func mergeSort(subArray []int) []int { if len(subArray) == 1 { return subArray } if len(subArray) == 2 { return sort(subArray) } mid := int(math.Floor(fl...
/* MIT License Copyright (c) 2020-2021 Kazuhito Suda This file is part of NGSI Go https://github.com/lets-fiware/ngsi-go Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, inc...
package chatroom import ( "fmt" "net" "strings" "strconv" ) var JOIN_CHATROOM_RESPONSE_PROTOCOL = [5]string{"JOINED_CHATROOM", "SERVER_IP", "PORT", "ROOM_REF", "JOIN_ID"} var SEND_MESSAGE_REPSONSE_PROTOCOL = [3]string{"CHAT", "CLIENT_NAME", "MESSAGE"} var LEAVE_CHATROOM_RESPONSE_PROTOCOL = [2]string{"LEFT_CHATROO...
package main import ( "crypto/md5" "fmt" "html/template" "io" "log" "net/http" "os" "path/filepath" "regexp" "strconv" "strings" "time" ) func sayhelloName(w http.ResponseWriter, r *http.Request) { r.ParseForm() fmt.Println(r.Form) fmt.Println("path", r.URL.Path) fmt.Println(r.Form["url_long"]) for k...
package router import ( "github.com/gin-gonic/gin" "github.com/zhulinwei/go-dc/pkg/controller" ) type IUserRouter interface { InitRouter(r *gin.Engine) } type UserRouter struct { UserController controller.IUserController } func BuildUserRouter () IUserRouter { return UserRouter{ UserController: controller.Bu...
package main import ( "fmt" "log" ) const dimensions int = 32 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 // 0b1001011001101001 size :...
package main type list struct { first *list_node last *list_node } type list_node struct { prev *list_node next *list_node data interface{} } func (self *list) Append(x interface{}) { new_node := new(list_node) new_node.data = x if (*self).first == nil { self.first = new_node self.last = ne...
// // Title : Distinct // Author : Richie Varghese // Date : 24/12/2020 // // distict : given an array A consisting of N integers, returns the number of distinct values in array A. // For example, given array A consisting of six elements such that: // A[0] = 2 A[1] = 1 A[2] = 1 // ...
// Copyright 2014 The Cockroach 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 ag...
package message type IncomingMessage struct { Repository struct { Status string RepoUrl string `json:"repo_url"` Owner string IsPrivate bool `json:"is_private"` Name string StarCount int `json:"star_count"` RepoName string `json:"repo_name"` } Push_data struct { PushedAt int `json...
package main //133. 克隆图 //给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。 // //图中的每个节点都包含它的值 val(int) 和其邻居的列表(list[Node])。 // * Definition for a Node. type Node struct { Val int Neighbors []*Node } func cloneGraph(node *Node) *Node { if node == nil{ return nil } dic := make(map[*Node]*Node) var clone func(root *Node...
package docker import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/opspec-io/opctl/util/vruntime" ) var _ = Context("localPath", func() { Context("when runtime.GOOS == windows", func() { fakeRuntime := new(vruntime.Fake) fakeRuntime.GOOSReturns("windows") objectUnderTest := _containe...
package model import ( "gorm.io/datatypes" ) type SchedulerCluster struct { Model Name string `gorm:"column:name;size:256;uniqueIndex;not null" json:"name"` BIO string `gorm:"column:bio;size:1024" json:"bio"` Config datatypes.JSONMap `gorm:"column:config;not ...
package code import "github.com/pgavlin/warp/wasm" type StaticScope struct { module *wasm.Module ImportedFunctions []uint32 ImportedGlobals []wasm.GlobalVar Tables int Memories int Locals []wasm.ValueType } func NewStaticScope(m *wasm.Module) *StaticScope { s := StaticScope{module: m} if m.Import != ...
package giantbomb type Response struct { StatusCode int64 `json:"status_code"` Error string `json:"error"` TotalResults int64 `json:"number_of_total_results"` PageResults int64 `json:"number_of_page_results"` Limit int64 `json:"limit"` Offset int64 `json:"offset"` }
package main import ( "flag" "fmt" "log" "time" "gopkg.in/mgo.v2" ) type TestDoc struct { ID int `bson:"id"` } var mongourl string func main() { flag.StringVar(&mongourl, "mongourl", "", "") flag.Parse() log.Printf("start dial to %s", mongourl) // replSet initiate got NodeNotElectable: This node, mongo2...
package main import "fmt" import "time" func main() { //go-routines are functions that are executing concurrently with other code. //various ways to start go-routines go sayHello() // a normal function as defined below called with go keyword //Following construct is called as anonymous function //Look at the ()...
// Copyright (c) 2013 Mathieu Turcotte // Licensed under the MIT license. package browserchannel import ( "errors" "io" "log" "net/http" "strconv" ) const dataChannelCapacity = 128 // The back channel interface shared between the XHR and HTML implementations. type backChannel interface { getRequestId() string...
package state import ( "github.com/aergoio/aergo/types" ) // BlockInfo contains BlockHash and StateRoot type BlockInfo struct { BlockHash types.BlockID StateRoot types.HashID } // BlockState contains BlockInfo and statedb for block type BlockState struct { StateDB BpReward []byte //final bp reward, increment wh...
// This file was generated by data-gen. Do not edit. // CLDR version: 40.0 package locale import ( "reflect" "testing" ) func TestRanges(t *testing.T) { ranges := Ranges{1, 2, 3, 4} n := ranges.Len() if n != 2 { t.Errorf("unexpected length: %d", n) } for i := 0; i < n; i++ { rng := ranges.At(i) if rng....
package main import "fmt" type Stu struct { Name string Age int Address string } func main() { students := make(map[string]Stu) stu01 := Stu{ "tom", 18, "aaa", } stu02 := Stu{ "jerry", 19, "bbb", } students["001"] = stu01 students["002"] = stu02 fmt.Println(students) for k, v := ra...
package main import ( "fmt" ) /** * @brief { reads and integer ans checks for errors, an rune input is an error } * * @param name The name of the variable, for error log * * @return { the readed value } */ func readcheck(name string) int { var aux int _, err := fmt.Scanf("%d", &aux) if err !=...
package conf //应用端口 type AppConfig struct { Port string } //数据库配置信息 type MySqlConfig struct { Username string Password string FdnUrl string GtyUrl string } type LoggerConfig struct { LoggerPath string LoggerLevel string } type ProjectConfig struct { Mysql MySqlConfig LoggerInfo LoggerConfig AppConfig AppC...
package main import "fmt" func fact(x uint) uint{ if x == 0 { return 1 } return x * fact(x - 1) }
package controllers import ( "strconv" "github.com/itang/gotang" "github.com/revel/revel" "github.com/itang/yunshang/main/app/models" "github.com/itang/yunshang/modules/oauth" ) type socialAuther struct { } func (p *socialAuther) IsUserLogin(ctx *revel.Controller) (int64, bool) { us, ok := ctx.Session["uid"]...
package problem0056 import "math/rand" // Interval Definition for an interval. type Interval struct { Start int End int } func merge(its []Interval) []Interval { if len(its) <= 1 { return its } quickSort(its) res := make([]Interval, 0, len(its)) temp := its[0] for i := 1; i < len(its); i++ { if its[...
// Copyright 2015 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 ring import ( "fmt" "time" "github.com/cortexproject/cortex/pkg/ring" "github.com/cortexproject/cortex/pkg/ring/kv" "github.com/prometheus/client_golang/prometheus" ) // New creates a new distributed consistent hash ring. It shadows the cortex // ring.New method so we can use our own replication strate...
package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func max(a, b int) int { if a > b { return a } return b } func dfs(tr *TreeNode, d int, ans *[]int) { if tr == nil { return } if d > len(*ans) { *ans = append(*ans, tr.Val) } else { (*ans)[d-1] = max...
package crd import ( "fmt" "testing" "github.com/ghodss/yaml" "github.com/stretchr/testify/assert" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestMarshal(t *testing.T) { d := Database{ ObjectMeta: meta_v1.ObjectMeta{Name: "my_db", Namespace: "default"}, TypeMeta: meta_v1.TypeMeta{Kind: "Databa...
package image_classify import "github.com/kingjh/baidu-ai-go-sdk" type ImageClassifyClient struct { *gosdk.Client } func NewImageClassifyClient(apiKey, secretKey string) *ImageClassifyClient { return &ImageClassifyClient{ Client: gosdk.NewClient(apiKey, secretKey), } }
package plugins import( "reflect" ) type KubernetesPlugin struct { name string kubeconfig_path string } func NewKubernetesPlugin() Plugin { return &KubernetesPlugin{ kubeconfig_path: "~/.kube/config", } } func (k *KubernetesPlugin) Equal(p Plugin) bool { a, ok := p.(*KubernetesPlugin) if ok { ...
package main import "fmt" type Meter float64 type Foot float64 const lFactor float64 = 3.2808 func (m Meter) String() string { return fmt.Sprintf("%gM", m) } func (f Foot) String() string { return fmt.Sprintf("%gft", f) } // FToM converts Meter to Foot func FToM(f Foot) Meter { return Meter(f / Foot(lFactor)) } ...
package colors import "fmt" // RGBColor represents a custom 24-bit RGB color. type RGBColor struct { R, G, B uint8 } // Compress ... func (r RGBColor) Compress() string { return fmt.Sprintf(";2;%v;%v;%v", r.R, r.G, r.B) }
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package externaldata contains helpers to provide a http server for policies // that download their contents from an external source. package externaldata
package main import ( "fmt" "sort" ) type ddArr [][]int32 func (a ddArr) Len() int { return len(a) } func (a ddArr) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ddArr) Less(i, j int) bool { if a[i][1] != a[j][1] { return a[i][1] < a[j][1] } if a[i][1] == a[j][1] { return a[i][0] > a[j][0] } ...
package altrudos import ( "errors" "github.com/jmoiron/sqlx" "github.com/monstercat/pgnull" ) var ( ErrNilDonation = errors.New("submitted donation is nil") ) type SubmittedDonation struct { Amount string CharityId string Currency string DonorName string } func CreateDonation(ext sqlx.Ext, driveId stri...
package main import "github.com/yuriizinets/go-ssc" type ComponentSampleChild struct { Value string } func (c *ComponentSampleChild) Init(p ssc.Page) { c.Value = "Child's component value" }
package main // Leetcode 323. (medium) func countComponents(n int, edges [][]int) int { root, size := make([]int, n), make([]int, n) for i := range root { root[i] = i size[i] = 1 } for _, edge := range edges { n = unionOf323(edge[0], edge[1], root, size, n) } return n } func findOf323(x int, root []int) ...
package poller import ( "context" "fmt" "time" "github.com/gbolo/vsummary/common" "github.com/vmware/govmomi/view" "github.com/vmware/govmomi/vim25/mo" "github.com/vmware/govmomi/vim25/types" ) func (p *Poller) GetDVSPortgroups() (list []common.Portgroup, err error) { // log time on debug defer common.Exec...
package libMonitor import ( "github.com/pkg/errors" "time" ) var ScanInterval = time.Duration(30 * time.Second) var ScaningInterval = time.Duration(5 * time.Second) var AgainReportBaseInterval = time.Duration(60 * time.Second) var AgainReportMaxInterval = time.Duration(60 * 60 * time.Second) //1hour var ReportType...
package config import ( "fmt" "golang.org/x/sys/unix" "os" "path/filepath" "strings" ) func validateProcessSpec(spec *Process) error { if spec.Cwd == "" { return fmt.Errorf("Cwd property must not be empty") } if !filepath.IsAbs(spec.Cwd) { return fmt.Errorf("Cwd must be an absolute path") } if len(spec....
package main import ( "fmt" "sort" ) func main() { nums := []int{1, 0, -1, 0, -2, 2} target := 0 fmt.Println(fourSum(nums, target)) } func fourSum(nums []int, target int) [][]int { result := [][]int{} // 升序 sort.Ints(nums) // 固定第一个数 for first := 0; first < len(nums)-3; first++ { // 去重 if first > 0 && n...
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package arcappcompat will have tast tests for android apps on Chromebooks. package arcappcompat import ( "context" "strings" "time" "chromiumos/tast/common/android/u...
package memory import ( "fmt" "strconv" "formation.engineering/oauth2-jwt/store" "github.com/pkg/errors" ) type MemoryStore struct { identity int db map[store.KeyID]*store.KeyInfo } func NewMemoryStore() *MemoryStore { return &MemoryStore{ identity: 0, db: make(map[store.KeyID]*store.KeyInfo)...
package events import ( "encoding/json" "errors" "fmt" "log" "strings" "sync" ) //json hints helps while de-serialization from the struct type Event struct { Event string `json:"event"` Time int `json:"time"` } //struct for the serialization of json for output type AvgEvent struct { Event string `json:"...
package core import ( log "github.com/sirupsen/logrus" r "gopkg.in/rethinkdb/rethinkdb-go.v5" ) var ( DbName = "rma_subscribes" TableName_SubscribeTunnelRealFund = "SubscribeTunnelRealFund" TableName_SubscribeCorpHoldMon = "SubscribeCorpHoldMon" TableName_SubscribeQuoteMon ...
package house import ( "bytes" "encoding/gob" "fmt" ) func NewHouse(street, country string, houseNumber int) *house { return &house{ Street: street, Country: country, HouseNumber: houseNumber, Rooms: 4, Bathrooms: 2, Pool: false, Garden: false, } } type house struct { Rooms,...
package engine import ( "bytes" "encoding/json" "errors" "fmt" "gopkg.in/v1/yaml" "io/ioutil" "os" "path/filepath" ) var ( errNoManifestPathSpecified = errors.New("No manifest path provided. Please use [-m|--manifest] /path/to/manifest.") ) type ManifestLoader struct { data []byte } var defaultManifests =...
package ctx import ( "github.com/gin-gonic/gin" "go4eat-api/svc" ) // ContextData func func ContextData(container *svc.Container) gin.HandlerFunc { return func(c *gin.Context) { c.Set("data", &Data{container: container}) } } // GetData func func GetData(c *gin.Context) *Data { return c.MustGet("data").(*Da...
package main import ( "fmt" "io/ioutil" "net/http" "regexp" ) func main() { resp, err := http.Get("http://www.zhenai.com/zhenghun") if err != nil { panic(err) } fmt.Println(resp) defer resp.Body.Close() if resp.StatusCode != http.StatusOK{ fmt.Println("err:",resp.StatusCode) return } // resp.Body ...
package debug import ( "testing" ) func TestNewTrace(t *testing.T) { a := newTrace() if a == nil { t.Errorf("Error in newTrace()") } }
package recursion import ( "AlgorizmiGo/recursion" "github.com/stretchr/testify/assert" "testing" ) func TestSubsetSum(t *testing.T) { tests := []struct { input []int targetSum int expectedOutput bool }{ {[]int{2, 3, 4}, 4, true}, {[]int{2, 1, 3, 4}, 4, true}, {[]int{2, 1, 3, 4}, 2, tru...
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package hotel import ( "fmt" "jkt/gateway/websocket" ) const ( hotelDefaultCap = 256 ) type hotel struct { value int32 uidset []map[int32]*websocket.Session } // newHotel 用于创建一个新的hotel func newHotel() *hotel { pHotel := &hotel{ value: 1, uidset: make([]map[int32]*websocket.Session, 1), } for i := int3...
// 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 hash import ( "testing" ) func Test_Hash(t *testing.T) { msg := []byte("this is a test msg") sha256 := UsingSha256(msg) doubleSha256 := DoubleSha256(msg) ripemd160 := UsingRipemd160(msg) seed := []byte("this is seed") hmac512 := HashUsingHmac512(seed, msg) t.Logf("sha256=%v, doubleSha256=%v, ripemd...
//Collection functions package main import ( "fmt" "strings" ) func Index(vs []string, s string) int { for i, e := range vs { if e == s { return i } } return -1 } func Include(vs []string, s string) bool { return Index(vs, s) >= 0 } func Any(vs []string, f func(string) bool) bool { for _, e := range ...
package capability import ( "context" "reflect" dynatracev1beta1 "github.com/Dynatrace/dynatrace-operator/src/api/v1beta1" "github.com/Dynatrace/dynatrace-operator/src/controllers" "github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/activegate/capability" "github.com/Dynatrace/dynatrace-operator/s...
package avl import ( "fmt" ) //func ExampleLeftRotationAndRightRotationAVLTree() { // t := &Tree{} // for _, v := range []int{14, 8, 24, 2, 11, 1} { // t.Add(v) // } // // for v := range t.Preorder() { // fmt.Printf(" %d", v) // } // fmt.Println() // // t.rightRotation(t.root.Left) // for v := range t.Preorder() {...
package challenge_1 import ( "encoding/base64" "encoding/hex" "log" ) func DecodeHex(src []byte) []byte { dst := make([]byte, hex.DecodedLen(len(src))) _, err := hex.Decode(dst, src) if err != nil { log.Fatal(err) } return dst } func hexToBase64(src []byte) []byte { dst := DecodeHex(src) base64Dst := mak...
/* 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...
// 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 integration import ( "encoding/json" "fmt" "io" "log" "net" "net/http" "time" "github.com/gorilla/mux" "github.com/tilt-dev/wmclient/pkg/analytics" ) type MemoryStatsServer struct { ma *analytics.MemoryAnalytics ss StatsServer listener net.Listener } func StartMemoryStatsServer() (m...
// 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 request import "chromiumos/tast/errors" // DayStart is part of an Omaha Request. type DayStart struct { XMLName struct{} `xml:"daystart" json:"-"` ElapsedDays ...
// Copyright (C) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
package peerstore import ( "encoding/json" ma "gx/ipfs/QmSWLfmj5frN9xVLMMN846dMDriy5wN5jeghUm7aTW3DAG/go-multiaddr" "gx/ipfs/QmWUswjn261LSyVxWAEpMVtPdy8zmKBJJfBpG3Qdpa8ZsE/go-libp2p-peer" ) // PeerInfo is a small struct used to pass around a peer with // a set of addresses (and later, keys?). This is not meant to...
package postgres import ( "net/url" "time" "github.com/Alireza-Ta/goask/model" "github.com/go-pg/pg/urlvalues" ) // CreateQuestion persists a question in db. func (s *Store) CreateQuestion(q *model.Question) error { return s.DB.Insert(q) } // ListQuestion returns a list of questions. func (s *Store) ListQuesti...
// Copyright 2020 Ant Group. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 package cache import ( "strconv" "testing" "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/stretchr/testify/assert" "github.com/dragonflyoss/image-service/co...
package auth_test import ( "context" "strconv" "sync" "testing" "time" pb "github.com/SmitSheth/Mini-twitter/internal/auth/authentication" server "github.com/SmitSheth/Mini-twitter/internal/auth/service" ) func TestConcurrentCredential(t *testing.T) { var wg sync.WaitGroup numUsers := 100 wg.Add(numUsers) ...
package main import "testing" func TestNewCredential(t *testing.T) { credentials := "username:password" credential := NewCredential(credentials) if credential.Username != "username" { t.Error("Expected username, got", credential.Username) } if credential.Password != "password" { t.Error("Expected password,...
// Copyright 2021 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 saying import ( "fmt" "testing" ) func TestGreet(t *testing.T) { returnedString := Greet("Juan") if returnedString != "Hello my dear Juan" { t.Error("Got", returnedString, "Expected: Hello my dear Juan") } } func ExampleGreet() { fmt.Println(Greet("Juan")) // Output: // Hello my dear Juan } func B...
package diag import ( "os" pkgLog "github.com/kapitanov/natandb/pkg/log" "github.com/spf13/cobra" ) var log = pkgLog.New("") // Command is root for diagnostics commands var Command = &cobra.Command{ Use: "diag", Short: "Diagnostics tools", Hidden: true, TraverseChildren: tru...
package apiset import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" ) // A set of API Objects of different types. type ObjectSet map[string]TypedObjectSet func (s ObjectSet) GetSetForType(o Object) TypedObjectSet { return s[o.G...
package multimarshal type JsonMarshall map[string]string
package main import ( "fmt" "strconv" "sync" ) func main() { c1 := make(chan int) c2 := make(chan int) go func() { c1 <- 3 close(c1) }() go func() { c2 <- 1 close(c2) }() res := combine(c1, c2) for v := range res { fmt.Println(v) } } func combine(chs ...<-chan int) <-chan int { var wg sync.Wai...
package model type Role int const( Regular Role = iota Administrator Agent )
package gitlabClient import ( "fmt" "github.com/xanzy/go-gitlab" ) func (git *GitLab) GetMilestoneByProjectName(pid gitlab.Project, milestoune string) (*gitlab.Milestone, error) { opt := gitlab.ListMilestonesOptions{ Search: milestoune, ListOptions: gitlab.ListOptions{ PerPage: 100, Page: 1, }, } ...
/* -------------------------------------------------------------------------- */ /* https://leetcode.com/problems/3sum/ */ /* -------------------------------------------------------------------------- */ package main import ( "sort" ) func twoPointerSum(nums []int, target int,...
package middleware import ( "fmt" "github.com/gin-gonic/gin" ) func CORSMiddleware() gin.HandlerFunc { return func(c *gin.Context) { c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Max-Age", "86400") c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, ...
package format import ( "context" "testing" "github.com/ipfs/go-cid" mh "github.com/multiformats/go-multihash" ) type TestNode struct { links []*Link data []byte builder cid.Builder } var v0CidPrefix = cid.Prefix{ Codec: cid.DagProtobuf, MhLength: -1, MhType: mh.SHA2_256, Version: 0, } func I...
//go:generate go run github.com/golang/mock/mockgen -source logging.go -destination mock/logging_mock.go -package mock package utility import ( "os" log "github.com/sirupsen/logrus" prefixed "github.com/x-cray/logrus-prefixed-formatter" ) type LoggingInterface interface { LogError(err error) LogInfo(message str...
package Pair import ( "fmt" "io" "strings" "unicode" ) type Exchanger interface { Exchange() } func ExchangeThese(exchangers ...Exchanger) { for _, exchanger := range exchangers { exchanger.Exchange() } } //---------------------------------------- type LowerCaser interface { LowerCase() } type UpperCase...
// Package intset provides a specialized set for integers or runes package intset // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 func upTwo(v int) int { v-- v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 v++ return v }
// http://mattn.github.io/go-gtk/ // https://github.com/mattn/go-gtk // apt-get install libgtk2.0-dev libglib2.0-dev libgtksourceview2.0-dev // go get github.com/mattn/go-gtk/gdkpixbuf // go get github.com/mattn/go-pointer // go get https://github.com/mattn/go-gtk package lib import ( "fmt" "github.com/mattn/go-g...
package main import ( "fmt" "log" "net/http" "time" httputils "github.com/cascades-fbp/cascades-http/utils" uuid "github.com/nu7hatch/gouuid" ) const ( timeout = time.Duration(15) * time.Second ) type HandlerRequest struct { ResponseCh chan httputils.HTTPResponse Request *httputils.HTTPRequest } func r...
package fmap_test import ( "log" "math/rand" "os" "github.com/lleo/go-functional-collections/fmap" "github.com/lleo/go-functional-collections/key" "github.com/lleo/stringutil" "github.com/pkg/errors" ) func init() { log.SetFlags(log.Lshortfile) var logFileName = "test.log" var logFile, err = os.Create(log...
package pingrr const ( httpHeaderAuthorization = "Authorization" ) type Credentials interface { Headers() map[string]string } type oauthTokenCredentials struct { oauthToken string } func NewOauthTokenCredentials(oauthToken string) Credentials { return &oauthTokenCredentials{oauthToken: oauthToken} } func (c *o...
package handlers import ( "encoding/json" "net/http" "rest/model" ) // AddGarment - [Adds garment to list] func AddGarment(w http.ResponseWriter, r *http.Request) { garment := r.URL.Query().Get("garment") list := model.AddToList(garment) enableCors(&w) w.Header().Set("Content-Type", "application/json; chars...
package main import ( "sync" "time" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" ) var client *mongo.Client var lock sync.Mutex var Defaultskip = int64(0) var Defaultlimit = int64(10) var skip = Defaultskip var limit = Defaultlimit type participant struct { Name string ...
package label import ( "testing" "github.com/google/go-github/v47/github" ) func TestHasLabel(t *testing.T) { basicLabels := []*github.Label{ { Name: github.String("foo"), }, { Name: github.String("bar"), }, { Name: github.String("fii"), }, { Name: github.String("bir"), }, } testCas...
package session import ( "context" "gamesvr/manager" "shared/common" "shared/csv/static" "shared/protobuf/pb" "shared/statistic/logreason" "shared/utility/coordinate" "shared/utility/errors" "shared/utility/glog" ) //TryPushGraveyard 因为Graveyard公会互助,别人触发自己的推送,所以只放在timmerpush func (s *Session) TryPushGraveyar...
// 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, ...
package types_test import ( "testing" "github.com/go-jstmpl/go-jstmpl/types" hschema "github.com/lestrrat/go-jshschema" schema "github.com/lestrrat/go-jsschema" ) func TestNewRoot(t *testing.T) { s, err := types.NewRoot(&hschema.HyperSchema{ Schema: &schema.Schema{ Title: "title", Description: "de...
package main import ( "fmt" "github.com/go-redis/redis" ) func main(){ client := redis.NewClient(&redis.Options{ Addr: "127.0.0.1:6379", // redis地址 Password: "", // redis密码,没有则留空 DB: 0, // 默认数据库,默认是0 }) sub := client.Subscribe("result") fmt.Println(sub.Recei...
/* * @lc app=leetcode id=724 lang=golang * * [724] Find Pivot Index * * https://leetcode.com/problems/find-pivot-index/description/ * * algorithms * Easy (43.66%) * Likes: 1063 * Dislikes: 240 * Total Accepted: 130.7K * Total Submissions: 299.2K * Testcase Example: '[1,7,3,6,5,6]' * * Given an arr...
package main import ( "fmt" "log" "net/http" ) func main() { fmt.Printf("Server started and listening to port 8080.\n") router := NewRouter() log.Fatal(http.ListenAndServe(":8080", router)) }
package models type Node struct { ID string `storm:"id"` ConfigHash string PayoutAddress string Token string Cooldown int LastUsed int64 Active bool }
package tempo import ( "context" "fmt" "io" "net/http" "time" "github.com/opentracing/opentracing-go" ot_log "github.com/opentracing/opentracing-go/log" "github.com/weaveworks/common/user" "google.golang.org/grpc/metadata" jaeger "github.com/jaegertracing/jaeger/model" "github.com/jaegertracing/jaeger/sto...