text
stringlengths
11
4.05M
// Based on: https://github.com/soupdiver/go-gitlab-webhook // Gitea SDK: https://godoc.org/code.gitea.io/sdk/gitea // Gitea webhooks: https://docs.gitea.io/en-us/webhooks package main import ( b64 "encoding/base64" "encoding/json" "errors" "fmt" "io/ioutil" "log" "net/http" "os" "os/exec" "os/signal" "str...
package main import ( "github.com/hashicorp/terraform-plugin-sdk/plugin" "github.com/vadimDidenko/terraform-provider-upwork/upwork" ) func main() { plugin.Serve(&plugin.ServeOpts{ ProviderFunc: upwork.Provider}) }
package utility import ( "Perekoter/models" "encoding/json" "errors" "io/ioutil" "net/http" "strconv" "strings" "time" "github.com/StefanSchroeder/Golang-Roman" "github.com/parnurzeal/gorequest" ) func Perekot(thread models.Thread) error { config := Config.Get() db := models.DB() defer db.Close() old...
package backtracking import ( "fmt" "testing" ) func Test_getPermutation(t *testing.T) { res := getPermutation2(3, 3) if res != "213" { t.Error(res) } fmt.Println(res) }
/* 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 bo //order 排序规则 type Order struct { Column string `json:"column"` Asc string `json:"asc"` } type MenuPermission struct { Permission string `json:"permission"` } type DeptCommon struct { ID int `json:"id"` Name string `json:"name"` } type Job struct { ID int `json:"id"` Name string `json:...
package main import ( "github.com/jmhobbs/wordpress-scanner/client/cmd" ) func main() { cmd.Execute() }
// 32. Break HMAC-SHA1 with a slightly less artificial timing leak package main import ( "bytes" "crypto/hmac" "crypto/rand" "crypto/sha1" "encoding/hex" "fmt" "hash" "io" "log" weak "math/rand" "mime/multipart" "net" "net/http" "os" "sync" "time" ) func init() { weak.Seed(time.Now().UnixNano()) } c...
package aliyun import ( "encoding/json" "fmt" "sync" "github.com/gogap/config" "github.com/gogap/context" "github.com/gogap/flow" "github.com/sirupsen/logrus" ) func init() { flow.RegisterHandler("devops.aliyun.rds.instance.create", CreateRDSInstance) flow.RegisterHandler("devops.aliyun.rds.instance.attribu...
// Copyright 2019 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 fileutil import ( "fmt" "os" ) // this module is here to check that only necessary modules (the ones that are actually imported are downloaded from the repository and not the whole repository) func Experiment() int { fmt.Println("You Should not use me") os.Exit(-1) return -1 }
package catm import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00300101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:catm.003.001.01 Document"` Message *AcceptorConfigurationUpdateV01 `xml:"AccptrCfgtnUpd"` } func (d *Document...
/* Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. */ package main import "fmt" func main() { ...
package processAvaatechSpe import () // Tests with bAxil on spectra from both instruments indicate that offset is // always << 20 eV, which is < 1 channel width. Thus, it can be // approximated as 0 eV for all fitting in this module. // Gain varies from ~20.0 eV/ch to ~20.4 eV/ch, which leads to channel differences o...
package shared import ( "context" "database/sql" "github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/gomatrixserverlib" ) type roomRecentEventsUpdater struct { transaction d *Database roomNID types.RoomNID latestEvents []types.StateAtEvent...
package main import . "../middleware" func main() { conn := Connection{} conn.CreateConnection("127.0.0.1", "8082", "tcp") conn.Start() session := TopicSession{} session.CreateSession(conn) topic := session.CreateTopic("perfumaria") topic2 := session.CreateTopic("eletronicos") publisher := session....
// Package geocoder provides an easy way to use the Google Geocoding API package geocoder import ( "encoding/json" "errors" "log" "net/http" "strconv" "strings" "github.com/kelvins/geocoder/structs" ) // The user should set the API KEY provided by Google var ApiKey string // Define the Geocode API URL as a c...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
package main import ( "encoding/json" "fmt" "github.com/BurntSushi/toml" "github.com/fsnotify/fsnotify" "learn_go/logger" "log" "os" "reflect" "strconv" "sync" "time" //"github.com/filecoin-project/go-state-types/dline" "github.com/spf13/viper" ) var ( faultLogFileName = " fault_sectors_" skipLog...
package virtual_security import ( "reflect" "testing" "time" ) type testStockContractComponent struct { iStockContractComponent isContractableTime1 bool confirmStockOrderContract1 *confirmContractResult confirmMarginOrderContract1 *confirmContractResult } func (t *testStockContractComponent) isContra...
package main import "fmt" var a , b int func main() { fmt.Printf("a, b ? ") fmt.Scanf("%d %d", &a, &b) fmt.Printf( "a=%d, b=%d\n", a, b ) a^=b b^=a a^=b fmt.Printf( "a=%d, b=%d\n", a, b ) }
package plugin import ( "archive/zip" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "strings" "github.com/grafana/plugin-validator/pkg/grafana" ) // checkContext contains useful paths and data available to checker. type checkContext struct { RootDir string DistDir strin...
package main import ( "crypto/md5" "crypto/rsa" "encoding/json" "hussain/thorium-go/requests" "net/http" "time" "github.com/dgrijalva/jwt-go" "github.com/go-martini/martini" ) import "os/exec" import "fmt" import "redis" import "bytes" import "crypto/rand" import "database/sql" import _ "github.com/lib/pq"...
package protocol_comm import ( "github.com/colefan/gsgo/netio/iobuffer" "github.com/colefan/gsgo/netio/packet" ) const ( CMD_S_C_ERROR_NT = 0x00D2 CMD_C_S_VCHECK_REQ = 0x00D3 CMD_C_S_VCHECK_RESP = 0x00D4 ) type ServerErrorNt struct { *packet.Packet ReqCmdID uint16 //请求命令号 ErrCode uint16 //错误码 } func (this *...
package jars import ( "testing" ) func TestStub(t *testing.T) { mf := Manifest{} mf.Parse("Hello: World") if mf.Map["Hello"] == "" { t.Fail() } if mf.Map["Hello"] != "World" { t.Fail() } mf.PrintHeaders() }
package main import ( "bufio" gproto "code.google.com/p/goprotobuf/proto" "encoding/json" "fmt" "io/ioutil" "libcleo" "log" "net" "net/http" "os" "proto" "query" "strings" "switchboard" ) type ChampionPageParam struct { Name string ImgURL string } type PageParams struct { Title string Matching ...
package render import ( "encoding/json" "net/http" ) const ContentJSON = "application/json" type jsonRender struct{} func (_ jsonRender) Render(rw http.ResponseWriter, code int, data ...interface{}) error { rw.Header().Set("Content-Type", ContentJSON+"; charset=utf-8") rw.WriteHeader(code) encoder := json.NewE...
package services import ( "github.com/andrewesteves/taskee-api/entities" "github.com/andrewesteves/taskee-api/utils" "github.com/andrewesteves/taskee-api/validations" "github.com/gofiber/fiber" "github.com/jinzhu/gorm" ) // UserService type type UserService struct { DB *gorm.DB } // Register new users func (u ...
/* Copyright © 2022 SUSE LLC 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 dist...
package baudot import ( "fmt" "testing" ) func TestITA2EncodeChar(t *testing.T) { tt := []struct { caseName string char rune charset Charset expectCode byte expectShift bool shouldFail bool failedText string }{ { caseName: "test regular char", char: '=', charset...
package main import ( "fmt" "github.com/gin-gonic/gin" "github.com/linkedlocked/webapp/database" "github.com/linkedlocked/webapp/models" ) type GatewayUpdate struct { GatewayID int PoleID int Locked bool LockedCardID string Token string } func routePostGatewayUpdate(c *gin.Context) { ...
package sudoku import ( "fmt" "math/rand" "strconv" ) type nakedSingleTechnique struct { *basicSolveTechnique } type hiddenSingleTechnique struct { *basicSolveTechnique } type obviousInCollectionTechnique struct { *basicSolveTechnique } func (self *obviousInCollectionTechnique) humanLikelihood(step *SolveSte...
package network import ( "encoding/json" "eos-network/crypto" ) type ChainIdType Sha256Type type GetChainResult struct { ServerVersion string `json:"server_version"` ChainId Sha256Type `json:"chain_id"` HeadBlockNum uint32 `json:"head_block_num"` LastIrreversi...
/* * @lc app=leetcode.cn id=8 lang=golang * * [8] 字符串转换整数 (atoi) */ package solution import ( "math" "strings" ) // @lc code=start func myAtoi(s string) int { s = strings.TrimLeft(s, " ") if len(s) == 0 { return 0 } i, sign := 0, 1 if s[0] == '-' || s[0] == '+' { i++ if s[0] == '-' { sign = -1 ...
package command import ( "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/yamil-rivera/flowit/internal/config" "github.com/yamil-rivera/flowit/internal/fsm" "github.com/yamil-rivera/flowit/internal/io" "github.com/yamil-rivera/flowit/internal/runtime" "github.com/yamil-rivera/flowit/internal/utils" ...
package main import "fmt" func funcao1() { fmt.Println("Função 1") } func funcao2(parametro1 string, parametro2 string) { fmt.Printf("Funcao 2: %s %s\n", parametro1, parametro2) } func funcao3() string { return "Funcao 3" } func funcao4(parametro1, parametro2 string) string { return fmt.Sprintf("Funcao 4: %s %...
package iirepo import ( "path/filepath" ) // Path returns the repo path. // // Note that Path does NOT create this directory itself. func Path(rootpath string) string { path := filepath.Join(rootpath, Name()) return path }
package command import ( "bytes" "errors" "io" "os" "strings" "testing" log "github.com/Sirupsen/logrus" logrusTestHook "github.com/Sirupsen/logrus/hooks/test" "github.com/fatih/color" "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" clientMock "github.com...
package datasetapi import ( "context" stypes "github.com/lexis-project/lexis-backend-services-interface-datasets.git/client/data_set_management" "github.com/lexis-project/lexis-backend-services-api.git/models" "github.com/lexis-project/lexis-backend-services-api.git/restapi/operations/data_set_management" "githu...
package player import ( "context" "google.golang.org/grpc" "google.golang.org/grpc/metadata" pb "gos_rpc_proto" "gosconf" "goslib/logger" "gslib/scene_mgr" "io" "net" "strconv" "sync" "sync/atomic" ) type StreamServer struct { ConnectAppId string } var accountConnectMap = sync.Map{} var onlinePlayers in...
package main import ( "errors" "gopkg.in/yaml.v2" "io/ioutil" "os" ) type manifestVersionCheck struct { Version int `yaml:"version"` } func checkManifestVersion(filename string) (err error) { var buf []byte if buf, err = ioutil.ReadFile(filename); err != nil { if os.IsNotExist(err) { err = nil } retu...
package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // APIServiceSpec defines the desired state of APIService type APIServiceSpe...
///usr/bin/env go run -ldflags "-X main.Version=shell.run" $0 "$@"; exit /* * Trident Setup (tsetup) * * tsetup is only meant for initial setup tasks. * It should be run as the 'postgres' user. * * For general use, use 'tcli' or the webinterface and log in. */ package main import ( "trident.li/pitchfork/cmd/...
package main import "math/rand" // 跳表 func main() { } const ( maxLevel = 16 p = 0.25 ) type Node struct { Val int Next []*Node } type Skiplist struct { level int header *Node // 头节点 } func Constructor() Skiplist { return Skiplist{ level: 0, // 默认层为0 header: &Node{ Next: make([]*Node, maxLe...
package hardcoded import ( "github.com/iotaledger/wasp/contracts" "github.com/iotaledger/wasp/packages/hashing" "github.com/iotaledger/wasp/packages/vm/core" ) func LocateHardcodedProgram(programHash hashing.HashValue) (string, bool) { if _, err := core.GetProcessor(programHash); err == nil { return core.VMType...
package transaction import ( "github.com/babyboy/core/types" "github.com/babyboy/common" ) type ResultBack struct { stable bool exist bool utxo types.UTXO } type UtxoHelper struct { Address common.Address UTXO types.UTXO IsStable bool }
package frida_go type PeerOptions struct { StunServer string Relays []*Relay }
/* * Copyright 2018, CS Systemes d'Information, http://www.c-s.fr * * 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 requir...
package io import ( "testing" ) var fileReader = FileReader{ FilePath: "../file-repository/base_teste.txt", } func TestReadFileSuccessfully(t *testing.T) { err := fileReader.Initialize() if err != nil { t.Errorf(err.Error()) } } func TestCloseUnopenedFileSuccessfully(t *testing.T) { fileReaderUnopened := F...
package recognizer import ( "time" ) // InferencesResult type type InferencesResult struct { Inferences []Inference `json:"inferences"` Page struct { TotalCount int `json:"total_count"` } `json:"page"` } // Inference type type Inference struct { ID int `json:"id"` Score float32 `json:"score"` F...
package helpers import ( // System "os/exec" // 3rd Party log "github.com/sirupsen/logrus" ) type BashCmd struct { Cmd string Args []string ExecPath string } // Executes CLI commands func ExecBashCmd(c *BashCmd) { // Set command and argument options cmd := c.Cmd cmdArgs := c.Args // Execute co...
package main import ( "bytes" "reflect" "testing" ) func TestPKCS7Pad(t *testing.T) { cases := []struct { buf []byte blockSize int want []byte }{ { []byte{0}, 3, []byte{0, 2, 2}, }, { []byte{0, 0}, 3, []byte{0, 0, 1}, }, { []byte{0, 0, 0}, 3, []byte{0, 0, 0, ...
package handler import ( "github.com/sundogrd/content-api/services/content" "github.com/gin-gonic/gin" ) // GetContent ... func GetContent(c *gin.Context) { content.ContentRepositoryInstance().FindOne(c, content.FindOneRequest{ID: 1}) c.JSON(200, gin.H{ "msg": "asd", }) } // ListContent ... func ListContent(c...
package git import ( "io/ioutil" "os" "testing" ) const ( REMOTENAME = "testremote" ) func TestClone(t *testing.T) { t.Parallel() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) seedTestRepo(t, repo) path, err := ioutil.TempDir("", "git2go") checkFatal(t, err) ref, err := repo.References.Looku...
package main import ( "fmt" "math" ) const ( //width, height = 300, 160 // canvas size in pixels //cells = 50 // number of grid cells //xyrange = 15.0 // axis ranges (-xyrange..+xyrange) //xyscale = width / 2 / xyrange * 5 // pixels per x or y unit widt...
package worker import ( "encoding/hex" ) // compact is 16-byte representation of 36-characters UUID, 56% smaller, still comparable type compact [16]byte // fromUUID returns Compact representation of `uuid` func fromUUID(uuid string) compact { c := compact{} bid := []byte(uuid) // We expect UUID to be always vali...
package main import ( "fmt" "io/ioutil" "strings" ) func activeToInactive(current map[[3]int]struct{}) map[[3]int]struct{} { next := make(map[[3]int]struct{}) for k := range current { k := k activeNeighbours := 0 for x := k[0] - 1; x <= k[0]+1; x++ { for y := k[1] - 1; y <= k[1]+1; y++ { for z := k[...
// Copyright 2020 Nokia // Licensed under the BSD 3-Clause License. // SPDX-License-Identifier: BSD-3-Clause package linux import ( "context" log "github.com/sirupsen/logrus" "github.com/srl-labs/containerlab/nodes" "github.com/srl-labs/containerlab/runtime" "github.com/srl-labs/containerlab/types" ) func init...
package _121_Best_Time_to_Buy_and_Sell_Stock import ( "math" ) func maxProfit(prices []int) int { return maxProfitOnce(prices) } func maxProfitOnce(prices []int) int { var max, maxSoFar int for i := 1; i < len(prices); i++ { max += prices[i] - prices[i-1] max = int(math.Max(0, float64(max))) maxSoFar = int...
package tags import () // type Tag defines a common interface for working with tag values. type Tag interface { // The raw user-defined string tag value. Raw() string // The URI-safe value of the raw tag value. Clean() string // A boolean flag indicating whether or not the tag can be parsed as a machine tag. Is...
package main import ( "fmt" "strings" "github.com/Quaqmre/mirjmessage/pb" "github.com/jroimartin/gocui" ) func (c *Client) Send(g *gocui.Gui, v *gocui.View) error { text := v.Buffer() if text == "" { return nil } sp := []string{text} if text[0] == '&' { sp = strings.Split(text, " ") } switch sp[0] { ...
package main import ( "fmt" "strings" ) func main(){ var x string fmt.Scan(&x) x=strings.ToLower(x) n :=len(x) if n<3{ fmt.Println("Not Found") }else{ flag:=0 if x[0]=='i' && x[n-1]=='n'{ for i:=1; i<n; i++{ if x[i]=='a'{ flag=1 break } } } if flag==0{ fmt.Println("No...
package core import ( "os" "testing" "github.com/stretchr/testify/assert" ) func TestExpandHomePath(t *testing.T) { HOME := os.Getenv("HOME") cases := []struct { in, want string }{ {"", ""}, {"~", HOME}, {"~username", "~username"}, {"~:/bin/~:/usr/local", HOME + ":/bin/~:/usr/local"}, {"/bin:~/bin:...
package limiter import "sync" // 限制上限 type LimitListener struct { sem chan struct{} // 当前数量(=上限 阻塞) done chan struct{} // 限流器关闭 closeOnce sync.Once } func NewLimitListener(n int) *LimitListener { return &LimitListener{ sem: make(chan struct{}, n), done: make(chan struct{}), } } func (limiter *L...
package main import "testing" func TestBinarySum(t *testing.T) { cases := []struct { name string A []int B []int want []int }{ {"0 + 0", []int{0}, []int{0}, []int{0, 0}}, {"0 + 1", []int{0}, []int{1}, []int{0, 1}}, {"1 + 0", []int{1}, []int{0}, []int{0, 1}}, {"1 + 1", []int{1}, [...
package shell import ( "bytes" "fmt" "path/filepath" "testing" "github.com/gruntwork-io/go-commons/logging" "github.com/stretchr/testify/assert" ) func TestRunShellCommand(t *testing.T) { t.Parallel() assert.NoError(t, RunShellCommand(NewShellOptions(), "echo", "hi")) } func TestRunShellCommandInvalidComma...
package main import ( "log" "os" ) func main() { //Exit /* os.Exit(1) fmt.Println("Start") */ /* //deferも実行されない defer func() { fmt.Println("defer") }() os.Exit(0) */ //log.Fatal() _, err := os.Open("A.txt") if err != nil { log.Fatalln(err) } }
package main import ( "fmt" "math/rand" "time" ) // 前提:ゲーム仕様の解釈 // ゲームの得点:プレイヤーごとに0~100点、ゲーム終了条件は余白部、全ゲーム終了でプレイヤーごとに点数集計 // 1ゲームの総得点数:32 const gamePoints int = 32 const totalraounds int = 10 type player struct { name string scores map[round]score } func (p *player) addScore(r round) { if p.getTotalScore() <...
package main import ( "fmt" "net" "os" pb "github.com/semi-technologies/contextionary/contextionary" core "github.com/semi-technologies/contextionary/contextionary/core" "github.com/semi-technologies/contextionary/extensions" "github.com/semi-technologies/contextionary/server/config" "github.com/sirupsen/logr...
package unity import ( "reflect" "testing" ) func TestVersionFromString(t *testing.T) { tests := []struct { name string input string want VersionData wantErr bool }{ { name: "no_hash", input: "2020.3.30f1", want: VersionData{ Major: 2020, Minor: 3, Update: 30, VerT...
package stemmer import ( "bufio" "os" "strings" "testing" ) func Test_stem(t *testing.T) { //read vocabulary fVoc, err := os.Open("voc.txt") if err != nil { panic(err) } vocab := bufio.NewReader(fVoc) //read output fOut, err := os.Open("output.txt") if err != nil { panic(err) } output := bufio.NewR...
package main import ( "fmt" // 需要处理json相关操作,则需要导入此包 "encoding/json" ) // 定义学生结构体 type Student1 struct { // 属性名称的首字母,只有大写才能被转到json中 Id string Name string Course []string Age int } type Student2 struct { // 属性名称的首字母,只有大写才能被转到json中 // 由于首字母是大写,导致json串中也是大写,这里可以通设置属性标签使其转换成小写 Id string `json:"i...
/****************************************************************************** Online Go Lang Compiler. Code, Compile, Run and Debug Go Lang program online. Write your code in this editor and press "Run" button to execute it. ***********************************************...
package processor import ( "github.com/vmware/govmomi/vim25/types" ) // Processor handles incoming vCenter events. This enables different FaaS // implementations for vCenter event processing. Note: in the case of processing // failure the current behavior is to log but return nil until at-least-once // semantics are...
package main import ( "fmt" ) //凱薩密碼 func main() { var offsetVal rune = -12 info := Encode("description more or less taken from Wikipedia", offsetVal) fmt.Println(string(info)) info1 := Decode(info, offsetVal) fmt.Println(string(info1)) } //凱薩密碼加密 func Encode(s string, offset rune) string { var word = []rune(s...
package main import ( "fmt" "regexp" "bufio" "os" ) func getNameFromConsole() string { reader := bufio.NewReader(os.Stdin) fmt.Print("Input name: ") input, _ := reader.ReadString('\n') return input } func getInitials(name string) string { re :=regexp.MustCompile("([a-z])|(\\s)") initials := re.ReplaceAllSt...
package rest import ( id "github.com/jinmukeji/go-pkg/v2/id-gen" "github.com/kataras/iris/v12" ) const ( // ContextCidKey 上下文中注入的 cid 的键 ContextCidKey = "cid" ) // CidMiddleware cid中间件 func CidMiddleware(ctx iris.Context) { cid := id.NewXid() ctx.Values().Set(ContextCidKey, cid) ctx.Next() } // GetCidFromCon...
/* Gaussian blur is a method used for blurring images smoothly. It involves creating a matrix which will be used by convolving it with the pixels of an image. In this challenge, your task is to construct that matrix used in Gaussian blur. You will take an input r which will be the radius of the blur and an input σ whi...
package main import ( "fmt" "sort" "strings" ) func main() { s := "OVGHK" t := "RPGUC" sMap := make(map[string]int) total := 0 strS := "" strT := "" for _, x := range s { sMap[string(x)] = 0 } for key, _ := range sMap { if !(strings.Contains(t, key)) { total += strings.Count(s, key) } else {...
package app import ( "sync" "time" ) type Appl interface { // GetNewestRecord returns newest or nil if there are no records. GetNewestRecord() *Record AddRecord(Record) error TopicInitialized TopicRecordAdded } type Record struct { ID int Start time.Time Duration time.Duration // 15m…23h45m, step ...
// Copyright 2016 Matthew Endsley // All rights reserved // // Redistribution and use in source and binary forms, with or without // modification, are permitted providing that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions ...
package mockingjay import ( "github.com/stretchr/testify/assert" "io/ioutil" "net/http" "net/http/httptest" "testing" ) func TestItCreatesHTTPRequests(t *testing.T) { headers := make(map[string]string) headers["foo"] = "bar" uri := "/hello" method := "PUT" body := "Body body body" baseURL := "http://localh...
package reverseStr import "fmt" func reverseStr(s string, k int) string { var str string if s == "" || k <= 1 { return s } for index := 0; index < len(s); { left, right := index, index+k-1 if right >= len(s) { right = len(s) - 1 } for i := right; i >= left; i-- { str = fmt.Sprintf("%s%c", str, s[i...
/* * randmat: random number generation * * input: * nrows, ncols: the number of rows and columns * s: the seed * * output: * martix: a nrows x ncols integer matrix * */ package main import ( "flag" "fmt" "math" "sort" ) type ByteMatrix struct { Rows, Cols int array []byte } func NewByteMat...
package adapter import ( "github.com/mingo-chen/wheel-minirpc/ext" ) func init() { ext.RegistCoder("minirpc", MiniRpcReqCoder{}, MiniRpcRspCoder{}) ext.RegistFramer("minirpc", MiniRpcFramer{}) }
package vm import ( "fmt" "os" "github.com/luciancaetano/arch-v/register" ) // RegisterMap ... type RegisterMap struct { regs [numRegs]*register.Register } // rw get register for read and write func (r *RegisterMap) rw(reg byte) *register.Register { if reg < 0 || int(reg) > len(r.regs) { fmt.Printf("Registe...
package slb import ( "context" "crypto/tls" "net" "net/http" "net/http/httputil" "net/url" "time" "github.com/pkg/errors" ) // Server is an interface for representing server load balancer implementation. type Server interface { ListenAndServe() error Shutdown(context.Context) error } type serverLoadBalanc...
package uploader import ( "errors" "fmt" "mime" "net/http" ) const MaxImageSize = 10 * 1024 * 1024 // ~10MB var allowedContentTypes = []string{"image/jpeg", "image/png"} func ValidateURLResponse(res *http.Response, url string) (string, error) { contentType, _, err := mime.ParseMediaType(res.Header.Get("Content...
package repositories import ( "context" "database/sql" "github.com/syncromatics/kafmesh/internal/graph/loaders" "github.com/syncromatics/kafmesh/internal/graph/model" "github.com/pkg/errors" ) var _ loaders.QueryRepository = &Query{} // Query is the repository for root queries type Query struct { db *sql.DB ...
package helpers import ( "github.com/veandco/go-sdl2/sdl" "github.com/veandco/go-sdl2/img" "io/ioutil" "math" "bytes" ) type Node struct { X int32 Y int32 Type NodeType Right *Node Left *Node Up *Node Down *Node Image *sdl.Surface } var Nodes []*Node func linkNode...
// Package process holds a Transport implementation that runs local, unsandboxed processes package process import ( "bufio" "errors" "fmt" "os/exec" "path" "sync" "time" "github.com/anmitsu/go-shlex" "awesome-dragon.science/go/goGoGameBot/internal/config/tomlconf" "awesome-dragon.science/go/goGoGameBot/int...
package ants import ( "errors" "math/rand" "strconv" "time" "github.com/radekwlsk/go-travel/gotravel/gotravelservice/trip" "gonum.org/v1/gonum/floats" ) var ( ErrPlaceClosed = errors.New("place closed at that day") ErrPlaceClosesTooEarly = errors.New("place closes too early") ErrTripEndsTooEarly ...
package main // escreva um programa que coloque na tela os numero de 1 a 10000 import "fmt" func main() { for x := 0; x <= 10000; x++ { fmt.Println(x) } }
package xlsx // xlsxWorksheet directly maps the worksheet element in the namespace // http://schemas.openxmlformats.org/spreadsheetml/2006/main - // currently I have not checked it for completeness - it does as much // as I need. type xlsxWorksheet struct { SheetFormatPr xlsxSheetFormatPr `xml:"sheetFormatPr"` D...
package smallNet import "net" type sessionError int16 const netLibErrNone = 0 const ( sessionErrStart = sessionError(iota) sessionCloseForce sessionCloseAllSession sessionCloseRecvGoroutineEnd sessionCloseForceTerminateRecvGoroutine sessionCloseCloseRemote sessionCloseSocketError sessionCloseSocketReadTime...
package dockerfile import ( "bytes" "testing" "github.com/mitchellh/packer/packer" "github.com/mitchellh/packer/post-processor/docker-import" ) func testConfig() map[string]interface{} { return map[string]interface{}{ "maintainer": "foo", "cmd": []interface{}{ "/foo/bar" }, "label": ...
package data type Data struct { Result interface{} `json: result` Infomation Infomation `json: infomation` } type Infomation struct { Profile string `json: profile` Region string `json: region` } type Infomations []Infomation
package types import ( "github.com/openshift/installer/pkg/types/alibabacloud" "github.com/openshift/installer/pkg/types/aws" "github.com/openshift/installer/pkg/types/azure" "github.com/openshift/installer/pkg/types/baremetal" "github.com/openshift/installer/pkg/types/gcp" "github.com/openshift/installer/pkg/ty...
package _303_Range_Sum_Query_Immutable type NumArray struct { result []int } func Constructor(nums []int) NumArray { na := NumArray{ result: nums, } for i := 1; i < len(nums); i++ { na.result[i] = na.result[i-1] + nums[i] } return na } func (this *NumArray) SumRange(i int, j int) int { if i > j { return...
package main import ( "errors" "log" "math" ) func main() { y := 9.0 i, err := sqrt(y) if err != nil { log.Fatalln(err) } log.Printf("Sqrt of %v = %f", y, i) } func sqrt(f float64) (float64, error) { if f < 0 { return 0, errors.New("Square root of negative number") } return math.Pow(f, 0.5), nil }