text
stringlengths
11
4.05M
package dht import ( "context" "fmt" "github.com/libp2p/go-libp2p-kad-dht/internal" ci "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/routing" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" ) type pubkrs struct { pub...
// Copyright 2016 IBM Corporation // // 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...
package utils import ( "io/ioutil" "log" "path/filepath" "strings" ) func GetInputAsSlice(fileName string) []string { // Read file absPath, _ := filepath.Abs(fileName) inputAsByteArray, err := ioutil.ReadFile(absPath) if err != nil { log.Panicf("File %s not found. Exiting. \n", fileName) panic(err) } //...
// Copyright 2016 Walter Schulze // // 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...
package mongomodel import ( "time" ) func Item(key string, value int) item { return item{ Key: key, Value: value, } } type item struct { Key string Value int } type BuildVersionMapping struct { Date time.Time OnlineRobotCounts int BuildMapping []int } func NewBuildVersionMapping(d...
package config import ( "fmt" "log" "strings" "github.com/kekik/viper" ) type goFShareConfig struct { BasePath, BaseURI, Format string } type config struct { GoFShare goFShareConfig } // Init reads in config file and ENV variables if set. func Init(cfgFile string) { replacer := strings.NewReplacer(".", "_"...
// Copyright 2016 IBM Corporation // // 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...
package main import ( "fmt" "testRedis/util" ) func main() { var repos []string for i := 0; i < 100; i++ { repos = append(repos, util.GetRandomGit(10)) } var ips []string for i := 0; i < 100; i++ { ips = append(ips, util.GetRandomIp()) } fmt.Printf("repos=%v\n", repos) }
package main import ( "bytes" "encoding/json" "io/ioutil" "net/http/httptest" "testing" "github.com/stretchr/testify/require" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/plugin" "github.com/mattermost/mattermost-server/v6/plugin/plugintest" "github.com/ma...
package db import ( "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" ) func GetDbSession() *dynamodb.DynamoDB { // if running lambdas locally for developement use dynamodb instance // in docker container if os.Getenv("RUN_ENV") == "LOCA...
// Package ctcp implements helpers for IRC Client-To-Client messages package ctcp
package main import "fmt" func one(x int) { x = 1 } func onereal(x *int) { // デリファレンス *x = 1 } func arraychange(arr []int) { arr = append(arr, 100) } func main() { var n int = 100 fmt.Println(n, "n") fmt.Println(&n) var p *int = &n // &(アンパサンド)はアドレスをさす。型に*をつかうことで、アドレスを格納させる fmt.Println(p, "p") // アドレス...
package main import ( "context" "errors" "flag" "fmt" "os" "github.com/google/go-github/github" // "github.com/k0kubun/pp" "golang.org/x/oauth2" ) const ( // DefaultPerPage is GitHub's default pager value DefaultPerPage = 30 ) const ( // ExitOk returns when application ends without any errors ExitOk = 0...
package main import ( "fmt" "os" "strconv" "time" "github.com/cineplays/go-rpio" ) var protocols []Protocol; var pin uint8; var code int64; var length int64; var currProtocol Protocol; var pulseLength int64; var nRepeatTransmit int64; var gpio rpio.Pin; type Protocol struct { pulseLength int; syncFactor Hig...
package detect_cycle /** https://leetcode-cn.com/problems/linked-list-cycle-ii/s */ type ListNode struct { Val int Next *ListNode } func DetectCycle(head *ListNode) *ListNode { if head == nil { return nil } intersectionNode := getIntersectionNode(head) if intersectionNode == nil { return nil } for inter...
// Copyright 2018 Diego Bernardes. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package url import "net/url" // String transform a url.URL into a string and escape the result. func String(endpoint url.URL) (string, error) { return url.Q...
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "...
package model import ( "encoding/json" "fmt" "gorm.io/gorm" "time" "tpay_backend/utils" ) const TransferBatchOrderTableName = "transfer_batch_order" const ( // 处理状态 BatchStatusInit = 1 // 初始化 BatchStatusSuccess = 2 // 成功 BatchStatusFailed = 3 // 失败 BatchStatusPending = 4 // 处理中 // 是否已全部生成订单 Generate...
package app import ( "fmt" "reflect" "testing" "github.com/giantswarm/apiextensions-application/api/v1alpha1" "github.com/giantswarm/k8smetadata/pkg/label" "github.com/google/go-cmp/cmp" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func Test_NewCR(t *testing.T) { testCases := []struct { name string ...
package index import ( "context" "encoding/json" "errors" "net/http" "time" "github.com/gorilla/mux" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" ) func DeleteQuiz(response http.ResponseWriter, request *http.Request) { response.Header().Add("content-type", "application/jso...
package backend import ( "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("App", func() { It("should create a Note without crashing", func() { runApp := func() { NewNote("Test note", time.Now()) } Expect(runApp).ShouldNot(Panic()) }) })
package impl1 import ( "github.com/sko00o/leetcode-adventure/queue-stack/stack" ) // Stack is a LIFO Data Structure. type Stack struct { stack.SliceStack } // MyQueue is a queue using stack. type MyQueue struct { S [2]Stack } // Constructor return MyQueue object. func Constructor() MyQueue { return MyQueue{ S...
package model // Tariff - Defines the cost for a delivery type Tariff struct { From int To int CostPerUnit int MinCost int } func (t Tariff) CostFor(quantity int) (cost int) { cost = -1 if quantity >= t.From && quantity <= t.To { cost = t.CostPerUnit * quantity if cost < t.MinCost { c...
package dropbox import ( "fmt" "github.com/golang/glog" ) type dropbox struct { name string nodeID string version string endpoint string ids *identityServer ns *nodeServer cs *controllerServer } func NewDropboxDriver(driverName, nodeID, endpoint, version string) (*dropbox, error) { if driverName...
package main import ( "math" "sort" ) func main() { } func threeSumClosest(nums []int, target int) int { sort.Ints(nums) var ( n = len(nums) best = math.MaxInt32 ) // 根据差值的绝对值来更新答案 update := func(cur int) { if abs(cur-target) < abs(best-target) { best = cur } } // 枚举 a for i := 0; i < n; i+...
package main import ( "errors" "fmt" "github.com/google/uuid" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/driver/postgres" "strconv" ) type User struct { ID uint `gorm:"primary_key:true"` SlackID string Name string Tags []Tag `gorm:"many2many:user_tags;"...
package validation import ( "fmt" "k8s.io/apimachinery/pkg/util/validation/field" "github.com/openshift/installer/pkg/types" "github.com/openshift/installer/pkg/types/aws" awsvalidation "github.com/openshift/installer/pkg/types/aws/validation" "github.com/openshift/installer/pkg/types/azure" azurevalidation "...
package server import ( "chlorine/auth" "chlorine/cl" "chlorine/music" "chlorine/music/spotify" ) var ( // Music service binding musicService music.Service // Authentication provider binding authenticationProvider auth.SessionAuthentication songService cl.SongService memberService cl.MemberService room...
package recipe import "time" type Recipe struct { name string cookTime time.Duration cookTemp float32 ingredients []string } func NewRecipe(name string, cookTime time.Duration, temp float32, ingredients ...string) *Recipe { return &Recipe{ name:name, cookTime:cookTime, cookTemp:temp, ingred...
package util import ( "time" ) // Default Time Format var DeletedAt = "0000-01-01 00:00:00" var TimeFormat = "2006-01-02 15:04:05" // Default value of time type var DefaultTime, _ = time.Parse(TimeFormat, "0001-01-01 00:00:00")
// Copyright 2017 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 ( "database/sql" "fmt" "time" _ "github.com/godror/godror" ) // MedicalReport struct type MedicalReport struct { AccessionNumber string PatientId string PatientName string PatientExtId string PatientGender string PatientBirth string PatientEmail ...
package setr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00500102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.005.001.02 Document"` Message *RedemptionMultipleOrderCancellationInstructionV02 `xml:...
package main import ( "os" "time" log "github.com/Sirupsen/logrus" "github.com/DataDog/datadog-go/statsd" "github.com/satori/go.uuid" "github.com/urfave/cli" ) var ( app = cli.NewApp() stats *statsd.Client builddate string ) var globalFlags = struct { Brokers string Topic string Offset ...
package gsum import ( "gitlab.com/oiacow/nextfesl/network" "gitlab.com/oiacow/nextfesl/network/codec" ) // GameSummary probably stands for Game Summary type GameSummary struct { // } func (gsum *GameSummary) answer(client *network.Client, pnum uint32, payload interface{}) { client.WriteEncode(&codec.Answer{ Typ...
package sqlbatch import ( "reflect" "strings" "unsafe" ) func makeInterfacePtrGetter(offset uintptr) func(structPtr unsafe.Pointer, ifacePtr *interface{}) { return func(structPtr unsafe.Pointer, ifacePtr *interface{}) { p := unsafe.Pointer(uintptr(structPtr) + offset) *ifacePtr = (*interface{})(p) } } func ...
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package main // #cgo CFLAGS: -g -Wall // #cgo LDFLAGS: -lSoapySDR import "C" import ( "fmt" "github.com/pothosware/go-soapy-sdr/pkg/device" "github.com/pothosware/go-soapy-sdr/pkg/modules" "github.com/pothosware/go-soapy-sdr/pkg/sdrlogger" "github.com/pothosware/go-soapy-sdr/pkg/version" "log" ) func main() { ...
package router import ( "encoding/json" "errors" "net/http" interf "silverfish/router/interface" "silverfish/silverfish" "silverfish/silverfish/entity" "github.com/gorilla/mux" "github.com/sirupsen/logrus" ) // BlueprintAuth export type BlueprintAuth struct { auth *silverfish.Auth router interf.IRouter ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-07-07 10:19 # @File : _48_Rotate_Image.go # @Description : 既横的变成竖的并且顺序反一下, 1. 先 横的变成竖的,对角线交换 2. 顺序反一下 # @Attention : */ package main func rotate(matrix [][]int) { // diagonal symmetry change for i := 0; i < len(matrix); i++ { for j := i + 1; j < len(m...
package api import ( "bytes" "context" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "testing" "time" "github.com/gorilla/mux" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) func TestCreateSchedule(t *testing.T) { // create dummy db f, _ := ioutil.TempFil...
package main import ( "fmt" "time" ) func main() { go test() go sayHello() time.Sleep(time.Second) } func test() { //这里我们可以使用defer+recover进行错误处理 defer func() { if err := recover(); err != nil { fmt.Println(err) } }() var testMap map[int]string testMap[0] = "hell0" } func sayHello() { for i := 0; i ...
// TODO: complete this code package main func main() { }
package main import ( "sanjay/hangman/director" "log" ) // TODO add logger prints and stuff func main() { log.Println("Starting Hangman Server...") director.Start() }
package common import ( "strings" "github.com/go-xorm/xorm" ) func Webcodecheck(adminWebCode, targetWebcode string, Orm *xorm.Engine) bool { istrue := true if targetWebcode == "all" { weblist := []map[string]string{} Orm.Table("web_list").Cols("web_code").Find(&weblist) for index, _ := range weblist { i...
// Copyright 2011 The Go Authors. All rights reserved. // Copyright 2013-2016 Manpreet Singh ( junkblocker@yahoo.com ). 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 ( "flag" "fmt" "log" "os" "runtime/pprof" "...
package automerger import ( "crypto/hmac" "crypto/sha1" "encoding/hex" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "time" ) type PushEventHandler struct { Config *Config } func (p *PushEventHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() w.Header().Set("Conten...
package pgsql import ( "testing" "time" ) func TestTimeArray(t *testing.T) { testlist2{{ valuer: TimeArrayFromTimeSlice, scanner: TimeArrayToTimeSlice, data: []testdata{ {input: []time.Time(nil), output: []time.Time(nil)}, {input: []time.Time{}, output: []time.Time{}}, { input: []time.Time{tim...
// Package watcher contains a straightforward implementation of the "watch // value for changes" pattern. package watcher import ( "context" "sync" "sync/atomic" ) type Publisher[T any] struct { value atomic.Value m sync.RWMutex watchChans []chan struct{} } func (p *Publisher[T]) Publish(value T) { ...
package middleware import ( "net/http" "github.com/gin-gonic/gin" "purge/jwt" ) //AuthRequired middleware func AuthRequired() gin.HandlerFunc { //This part is executed once when you initalize your middleware return func(c *gin.Context) { //This part is executed on every request bearer := c.GetHeader("Auth...
package util import ( "encoding/json" "errors" "fmt" "os" "os/exec" "path/filepath" "github.com/google/uuid" rspecs "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-tools/generate" "github.com/opencontainers/runtime-tools/specerror" ) // Runtime represents the basic requ...
package types // 存储设备 type Device struct { Id int `json:"id"` Label string `json:"label"` StorageType string `json:"storage_type"` StorageOrg string `json:"storage_org"` DateType string `json:"data_types"` IpAddress string `json:"ip_address"` DBPort string `json:"db_port"` DBUser ...
package sgs import ( "er" "hlf" "strconv" "sync" ) var _serverID = 0x6000 var _serverIDMutex = sync.Mutex{} type clientMap map[int]int type sessionServer struct { id int param *SSrvParam lg hlf.Logger clients clientMap clientsMutex sync.RWMutex currentSession *session currentSessionMutex sync.Mut...
// SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company and Gardener contributors // // SPDX-License-Identifier: Apache-2.0 package markdown import ( "testing" ) func TestStripFrontMatter(t *testing.T) { testCases := []struct { in string wantFM string wantContent string wantErr ...
package main import ( "os" "github.com/therecipe/qt/core" "github.com/therecipe/qt/network" "github.com/therecipe/qt/qml" "github.com/therecipe/qt/quick" "github.com/therecipe/qt/widgets" ) func main() { widgets.NewQApplication(len(os.Args), os.Args) var view = quick.NewQQuickView(nil) ...
package core import "sync" // Service data type type Service struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` Address *Address `json:"address,omitempty"` } // Address data type type Address struct { AddressTy...
/* Copyright 2012 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 to in writing, software di...
package role import ( "time" "yj-app/app/yjgframe/db" ) type Entity struct { RoleId int64 `json:"role_id" xorm:"not null pk autoincr comment('角色ID') BIGINT(20)"` RoleName string `json:"role_name" xorm:"not null comment('角色名称') VARCHAR(30)"` RoleKey string `json:"role_key" xorm:"not null commen...
package bets import ( "context" "github.com/go-chi/render" "github.com/ivansukach/bets/internal/tools" log "github.com/sirupsen/logrus" "net/http" ) func (b *Bets) Process(w http.ResponseWriter, r *http.Request) { err := r.ParseMultipartForm(10 << 20) if err != nil { log.Error(err) render.Render(w, r, tool...
package versions // Default values var MAINTAINING string = "1.12.2" var CURRENT string = "1.13" func Version(branch string) string { if branch == "master" { return CURRENT } else { return MAINTAINING } }
package main import ( "flag" "fmt" "regexp" "strconv" "time" "github.com/PuerkitoBio/goquery" "github.com/jszwec/csvutil" ) type Transaction struct { CreatedAt string `csv:"CreatedAt"` Action string `csv:"Action"` Source string `csv:"Source"` Base string `csv:"Base"` Volume float64 `csv...
package v1 import ( "context" "fmt" "net/http" "github.o-in.dwango.co.jp/naari3/ingress-sg-validator/pkg" networkingv1 "k8s.io/api/networking/v1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" ) //+kubebuilder:webhook:path=/validate-v1-ingress,mutating=fals...
package main import ( "fmt" ) func main() { var mealCost float32 var tipPercent int32 var taxPercent int32 fmt.Scanf("%f\n%d\n%d\n", &mealCost, &tipPercent, &taxPercent) var tip float32 = mealCost * float32(tipPercent) / 100.0 var tax float32 = mealCost * float32(taxPercent) / 100.0 var totalCost int32 = int...
package mutex_map import "sync" type Set struct { mx sync.Mutex m map[int]float64 } func NewSet() *Set { return &Set{ m: map[int]float64{}, } } func (set *Set) Get(key int) (float64, bool) { set.mx.Lock() defer set.mx.Unlock() val, ok := set.m[key] return val, ok } func (set *Set) Has(key int) bool { s...
package main import ( "fmt" "os" "github.com/ahmadwaleed/cron-parser" ) func main() { p := new(cron.Parser) expr := "*/15 0 1,15 * 1-5 /usr/bin/find" entry, err := p.Parse(expr) if err != nil { fmt.Fprintf(os.Stderr, "%s", err) } entry.Print() } // Example Output // minute 0 15 30 45 // hour ...
package rhcos import ( "context" "github.com/coreos/stream-metadata-go/arch" "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/util/sets" "github.com/openshift/installer/pkg/types" ) // AMIRegions returns the AWS regions in which an RHCOS AMI for the specified architecture is published. func AMIRegions(arc...
package main // https://yourbasic.org/golang/format-parse-string-time-date-example/ import ( "fmt" "os" "strconv" "time" ) func restarMeses(num_mes_a_restar int, fecha_introducida string) string { fecha_parseada, _ := time.Parse("2006-01-02", fecha_introducida) fecha_final := fecha_parseada.Add(time.Duration(...
package tokenizer import ( "strings" ) // TokenizeCode separates the source code into different tokens. func TokenizeCode(in string) []Token { tokens := []Token{} line := 1 lineIndex := 0 for _, rawToken := range regex.FindAllStringSubmatchIndex(in, -1) { token := Token{ Value: in[rawToken[0]:rawToken[1]]...
package main import ( "io/ioutil" "strings" ) func main() {} func read() []string { data, err := ioutil.ReadFile("input.txt") if err != nil { panic(err) } return strings.Split((string(data[:len(data)-1])), "\n") }
package isogram import "strings" func IsIsogram(phrase string) bool { phrase = strings.Replace(phrase, " ", "", -1) phrase = strings.Replace(phrase, "-", "", -1) phrase = strings.ToLower(phrase) setOfLetters := map[rune]bool{} for _, r := range phrase { if setOfLetters[r] { return false } setOfLetters[...
package sqlc func Count() IntField { return &intField{name: "*", fun: FieldFunction{Name: "Count", Expr: "COUNT(*)"}} } func Trunc(field TimeField, format string) TimeField { return &timeField{ name: field.Name(), // TODO a lot of this is quite boilerplate, consider auto-generating selection: field.Parent(...
package utils func ContainsInt(target int, source []int) int { for i, n := range source { if target == n { return i } } return -1 } func ContainsString(target string, source []string) int { for i, n := range source { if target == n { return i } } return -1 } func ContainsUInt(target uint, source ...
package commonregex import ( "testing" "github.com/stretchr/testify/assert" ) func TestCommonRegex_Date(t *testing.T) { t.Parallel() assert := assert.New(t) tests := []string{ "3-23-17", "3.23.17", "03.23.17", "March 23th, 2017", "Mar 23th 2017", "Mar. 23th, 2017", "23 Mar 2017", } for _, test...
package main import "time" // Events type TrainWasAnnounced struct { ID string From string FromTime time.Time To string ToTime time.Time } type TrainHasLeft struct { When time.Time } type TrainHasMoved struct { Where Position When time.Time } type TrainHasArrived struct { When time.Time }
package bookForm //назначение var Business = "Business" var Study = "Study" var FreeTimeSpending = "FreeTimeSpending" //популярность var Famous = "Famous" //отзывы var NoReview = "NoReview" var BadReview = "BadReview" var GoodReview = "GoodReview" //формат var SeparateBook = "SeparateBook" var SeriesOfBooks = "SeriesO...
// Package awscommons contains routines for interacting with AWS. Meant to provide high level interfaces used throughout // various Gruntwork CLIs. // NOTE: The routines in this package are adapted for aws-sdk-go-v2, not V1. package awscommons
package server const ( PRIORITY_LOWEST = 100 PRIORITY_LOW = 200 PRIORITY_NORMAL = 300 PRIORITY_HIGH = 400 PRIORITY_HIGHEST = 500 ) type CalleeInfo struct { callee []Objecter priority []int } var ( callees = make(map[string]*CalleeInfo) ) func (c *CalleeInfo) Add(callee Objecter, priority int) { ...
package opcua_client import ( "context" "fmt" "log" "net/url" "strings" "time" "github.com/gopcua/opcua" "github.com/gopcua/opcua/ua" "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/inputs" ) // OpcUA type type OpcUA struct { Name ...
package main import "fmt" /* This exercise will reinforce our understanding of method sets: create a type person struct attach a method speak to type person using a pointer receiver *person create a type human interface to implicitly implement the interface, a human must have the speak method create func “sa...
package silk type Model struct { // db conn DB *Builder // table Table string } func (m *Model) Clean() { m.DB = Table(m.Table) } func (m *Model) Where(field string, op string, value interface{}) *Builder { return m.DB.Where(field, op, value) }
package github import ( "encoding/json" "net/http" ) func GetSingleIssue(url string) (*Issue, error) { req, _ := http.NewRequest("GET", url, nil) req.Header.Set("Content-Type", "application/json") client := new(http.Client) resp, _ := client.Do(req) var result Issue if err := json.NewDecoder(resp.Body).Decode...
package main import "fmt" func add(nums ...int) int { fmt.Println(nums) total := 0 for _, n := range nums { total += n } fmt.Println(total) return total } func main() { add(1, 2, 3, 5) add(1, 2) }
package main import "fmt" func main() { // 1 of 3 ways of initializing a Map value // var colors map[string]string // 2 of 3 ways of initializing a Map value // colors := make(map[string]string) // how to add a value to the map // there is no dot notation for keys for maps and have to use square brackets. //...
package testing import ( "context" "github.com/brigadecore/brigade/sdk/v3" ) type MockWorkersClient struct { StartFn func( ctx context.Context, eventID string, opts *sdk.WorkerStartOptions, ) error GetStatusFn func( ctx context.Context, eventID string, opts *sdk.WorkerStatusGetOptions, ) (sdk.Worke...
package models // Order status const ( APIPathOrder = "/orders" OrderStatusUnassigned = "UNASSIGNED" OrderStatusTaken = "TAKEN" ErrorOrderNotFound = "ORDER_NOT_FOUND" ErrorOrderAlreadyBeenTaken = "ORDER_ALREADY_BEEN_TAKEN" ErrorDescription = "ERROR_DESCRIPTION" ErrorInvalidParameters ...
package main import ( "fmt" ) func MoneyCount(options []int, total int) []int { totalRecords := make(map[int]bool, 0) itemRecords := make(map[int][]int, 0) optionLen := len(options) // init the records with only one item for i := 0; i < optionLen; i++ { itemRecords[options[i]] = append(itemRecords[options[i]...
package ssh import ( "io/ioutil" "log" "code.google.com/p/go.crypto/ssh" ) func Config() *ssh.ServerConfig { config := &ssh.ServerConfig{ PasswordCallback: func(conn *ssh.ServerConn, user, pass string) bool { return user == "test" && pass == "test123" }, } config.NoClientAuth = true pemBytes, err := io...
package main import "fmt" //diziler , sabit boyu olan elemanların durdugu bir taşıyıcı, 0 indeksli yani ilk elemanı almak için 0.'yı istiyoruz. func main() { var x [5]int //burda x bir array 5 boyutlu ve tipi int. default olarak 0 0 0 0 0 x[4] = 100 // 0 indeksli oldugu icin, aslında 5.elemanı 100 ya...
package slovnik import "testing" func TestDetectLanguage(t *testing.T) { cases := []struct { in string lang Language }{ {"hlavní", Cz}, {"привет", Ru}, {"sиniy", Ru}, } for _, c := range cases { got := DetectLanguage(c.in) if got != c.lang { t.Errorf("DetectLanguage(%q) == %q, want %q", c.in, ...
package thermometer import ( "sync" "github.com/muka/go-bluetooth/bluez" log "github.com/sirupsen/logrus" "reflect" "github.com/fatih/structs" "github.com/muka/go-bluetooth/util" "github.com/godbus/dbus" ) var ThermometerWatcher1Interface = "org.bluez.ThermometerWatcher1" // NewThermometerWatc...
package shuffle import ( "math/rand" "time" ) func init() { rand.Seed(time.Now().UTC().UnixNano()) } func String(str string) string { return string(Bytes([]byte(str))) } func Bytes(slice []byte) []byte { result := make([]byte, len(slice)) copy(result, slice) rand.Shuffle(len(result), func(i, j int) { resu...
// Package derivecert is used to deterministically generate TLS certificate authority and certificates out of pre-shared key package derivecert
package svc11 import ( "context" "fmt" "github.com/feng/future/go-kit/agfun/trace/middleware" opentracing "github.com/opentracing/opentracing-go" "io/ioutil" "net/http" "net/url" ) type client struct { baseURL string httpClient *http.Client tracer opentracing.Tracer traceRequest middleware.Req...
package resolver import ( "github.com/dalloriam/synthia/modular" "github.com/dalloriam/websynth/app/audio" ) type OscillatorResolver struct { sys *audio.System osc *modular.Oscillator } func (r *OscillatorResolver) Volume() *KnobResolver { return &KnobResolver{r.sys, r.osc.Volume} } func (r *OscillatorResolver...
package domain import "context" // TechBook is just []byte at this time. type TechBook []byte // TechBookRepository defines what should be implemented as repository. type TechBookRepository interface { SetTechBookURL(ctx context.Context, techBookURL string) error GetTechBookURL(ctx context.Context) (string, error)...
package types /* Copyright 2018 Bruno Moura <brunotm@gmail.com> 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...
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type CreateFdwStmt struct { Fdwname *string FuncOptions *ast.List Options *ast.List } func (n *CreateFdwStmt) Pos() int { return 0 }
package update /* import ( "io/ioutil" "os" "path/filepath" "testing" "github.com/devspace-cloud/devspace/cmd/flags" "github.com/devspace-cloud/devspace/pkg/devspace/config/loader" "github.com/devspace-cloud/devspace/pkg/devspace/config/constants" "github.com/devspace-cloud/devspace/pkg/devspace/config/versio...
package main import "testing" //func TestNewOverLoad(t *testing.T) { // o := NewOverLoad("Bobojon") // if o.Name != "Bobojon" { // t.Fail() // } // o = NewOverLoad(20) // if o.Age != 20 { // t.Fail() // } // o = NewOverLoad([]string{"Sitora", "safdasf", "asfsf"}) // if o.Wives[0] != "Sitora" { // t.Fail() // } //}...
package main import ( "bufio" "bytes" "code.google.com/p/go-sqlite/go1/sqlite3" "crypto/sha256" "database/sql" "encoding/base64" "fmt" "github.com/russross/blackfriday" "html/template" "io" "io/ioutil" "net/url" "os" "sort" "strings" "time" "flag" "encoding/json" ) type Configuration struct { Autho...