text
stringlengths
11
4.05M
// Copyright 2018 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package main import ( //"path/filepath" "fmt" "io/ioutil" "os/exec" ) func main() { dir, err := ioutil.ReadDir("scanned-thread/") if err != nil { panic(err) } for _, fi := range dir { fileName := fi.Name() cmd := exec.Command("post-analyser", "scanned-thread/"+fileName) out, _ := cmd.Output() fmt....
package authn import ( "github.com/emicklei/go-restful" ) type Authenticator = restful.FilterFunction
/* * IP查找库 * 读入本地.csv文件,每行格式为: * * <起始ip,终止ip,省,市> * 或 * <起始ip,终止ip,国家/地区> * * 并通过http接口提供查询服务,查询方式为 * http://host:port/request_ip */ package main import ( "flag" "fmt" "log" "lookuptree" "net/http" "strconv" "strings" ) // ip查找树 var tree *lookuptree.LookUpTree // ip库本地文件组,.csv文件,以";"隔开 var...
package piscine func Join(strs []string, sep string) string { //empty string strJoin := "" for index, str := range strs { //except for the last element always add separator if index > 0 { strJoin = strJoin + sep + str } else { strJoin = strJoin + str } } return strJoin }
package main import ( "bufio" "flag" "fmt" "os" "strings" "sync" pb "github.com/gautamrege/gochat/api" ) var ( name = flag.String("name", "AshviniV", "The name you want to chat as") port = flag.Int("port", 12345, "Port that your server will run on.") host = flag.String("host", "test@com", "Host IP that your...
package cmd import ( "github.com/Files-com/files-cli/lib" "github.com/spf13/cobra" "fmt" "os" files_sdk "github.com/Files-com/files-sdk-go" "github.com/Files-com/files-sdk-go/clickwrap" ) var ( Clickwraps = &cobra.Command{ Use: "clickwraps [command]", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Co...
package main import "fmt" func main() { var mapTest = make(map[string]string) mapTest["str1"] = "test" //如果key还没有,就是增加 mapTest["str2"] = "test1" //如果key存在就是更新 mapTest["str1"] = "test2" fmt.Println(mapTest) //map删除,删除只能逐个遍历删除,没有一次性删除,或者重新分配空间 delete(mapTest, "str1") fmt.Println(mapTest) mapTest = make(map[s...
package v1 import ( "gopkg.in/yaml.v2" "log" "fmt" //"reflect" ) // Item represents an arbitrary YAML object. type Item interface{} // List represents a list of YAML objects. type List []interface{} // Map represents a YAML dictionary. type Map map[interface{}]interface{} func walkItem(i Item) { //log.Printf(...
package Problem0553 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { nums []int ans string }{ {[]int{1000, 100, 10, 2}, "1000/(100/10/2)"}, {[]int{2}, "2"}, {[]int{2, 1}, "2/1"}, {[]int{5, 2, 1}, "5/(2/1)"}, // 可以有多个 testcase } func Test_o...
package db import ( _ "database/sql" "fmt" "math/rand" "strconv" "time" ) func (store *Database) DbSetup() (err error) { //Creating PlantType DB statement, _ := store.Db.Prepare("CREATE TABLE IF NOT EXISTS PlantType (Name TEXT PRIMARY KEY, GrowthTime INTEGER)") // TODO Why no ID? statement.Exec() statement, ...
package worker import ( "bufio" "io" "log" "regexp" "strings" "time" ) // ReadUUIDs scans `r` for UUIDs, one per line func (w *Worker) ReadUUIDs(r io.Reader) error { rUUID := regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) scanner := bufio.NewScanner(r) skipped := 0 ...
package osbuild1 // A FixBLSStageOptions struct is empty, as the stage takes no options. // // The FixBLSStage fixes the paths in the Boot Loader Specification // snippets installed into /boot. grub2's kernel install script will // try to guess the correct path to the kernel and bootloader, and adjust // the boot load...
/* Copyright 2016 The Kubernetes Authors 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 ag...
package lintcode import ( "reflect" "testing" ) func Test_spiralOrder(t *testing.T) { type args struct { matrix [][]int } tests := []struct { name string args args want []int }{ { "[Test Case 1]", args{ [][]int{ { 1, 2, 3, }, { 4, 5, 6, }, { 7, 8, 9...
package leetcode import "testing" func TestReverseList(t *testing.T) { l := &ListNode{} h := l for i := 1; i < 6; i++ { l.Val, l.Next = i, &ListNode{} l = l.Next } l.Next = nil l = reverseList(h) for l.Next != nil { l = l.Next t.Log(l.Val) } }
package main import ( "fmt" "log" "net/http" "time" ) func index(w http.ResponseWriter, r *http.Request) { log.Println("hit index") fmt.Fprintf(w, "Welcome! The date is: %s", time.Now().Format(time.ANSIC)) } func handle() { http.HandleFunc("/", index) log.Println("serving on :8080") panic(http.ListenAndSe...
package drivers import ( "encoding/json" "fmt" "log" "github.com/kidoman/embd" "github.com/reef-pi/drivers/ezo" "github.com/reef-pi/drivers/file" "github.com/reef-pi/drivers/pca9685" "github.com/reef-pi/drivers/ph_board" "github.com/reef-pi/drivers/pico_board" "github.com/reef-pi/drivers/tplink" "github.c...
package server import ( dbutils "Go-Server/model/utils" "Go-Server/server/utils" "encoding/json" "fmt" "math/rand" "net/http" ) func (server *Server) handleSignUp(responseWriter http.ResponseWriter, request *http.Request) { conn := server.newConnection(utils.Post, "/signup") signedUpUser := dbutils.User{Usern...
/* * Copyright 2017 StreamSets 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...
package test import ( "encoding/json" "fmt" "testing" ) type Msg struct { Type int64 Content interface{} } type ContentTest struct { ID int64 Text string } func Test_json_unmashal(t *testing.T) { msg := &Msg{ Type: 1, Content: &ContentTest{ ID: 1, Text: "333333,,sss", }, } x := fmt.Spri...
package demo import ( "BearApp/internal/bootstrap" ) // Run 背景 func Run() error { bootstrap.WriteLog("INFO", "Demo Job") return nil }
package tbf import ( "context" "errors" "fmt" "time" "go.mercari.io/datastore" ) var _ datastore.PropertyTranslator = CircleID(0) var _ datastore.KeyLoader = &Circle{} const kindCircle = "Circle" // CircleID means ID of Circle kind. type CircleID int64 // Circle represents information on participating organi...
package messaging import "strconv" const ( maxReceivers = 255 maxBodySize = 1024 //KB (1 MB) ) // ValidateRequest - validates an incoming Relay message sub count and body size in line with requirements func ValidateRequest(subs []Subscription, body string) (okSubs bool, okBody bool, retMsg string) { if len(subs)...
package main import ( "encoding/json" "fmt" "log" "strconv" "strings" ) const ( POST_FIELDS = "id, post_date, post_author, post_name, post_title, post_content, post_excerpt, menu_order" ) func GetOptions() Options { var options Options cache_key := "options" cache_data, err := cache.Do("GET", cache_key) i...
package main import ( "bufio" "flag" "fmt" "os" "strconv" "strings" "text/template" "github.com/fatih/color" ) func main() { var template string var pf string var payloads []string flag.StringVar(&template, "t", "code_template.py", "Template for code.py generation") flag.StringVar(&pf, "p", "", "payload...
// firstPageParseInfo package DaeseongLib import ( "flag" "fmt" "io" "io/ioutil" "net/http" "os" "regexp" "strings" ) var ( PageIndex int ) func maxPage() int { sMaxPage := flag.Int("page", 16, "page") flag.Parse() return *sMaxPage } func writeString(sPath, sText string) { file, err := os.OpenFile(sPa...
package routers import ( "hello/controllers" "github.com/astaxie/beego" // "fmt" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/getUser", &controllers.MyController{}) // beego.Router("/getUser/:id", &controllers.MyController{}, "get:GetUser") beego.Router("/getAllUs...
// Copyright 2020, OpenTelemetry 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 main import ( "encoding/json" "flag" "fmt" "github.com/alex2108/trayhost" "github.com/toqueteos/webbrowser" "io/ioutil" "log" "net" "net/http" "crypto/tls" "os" "runtime" "time" ) var client = &http.Client{} var since_events = 0 type event struct { ID int `json:"id"` Type ...
package concurrentcache import ( "errors" "sync" "sync/atomic" "time" ) const pickNum = 3 // ConcurrentCache ... type ConcurrentCache struct { segment []*Segment sCount uint32 } // Segment .. type Segment struct { sync.RWMutex data map[string]*Node lfuPool map[string]*Node dCount uint32 dLen uint...
package main import ( "io" "log" "os" "os/exec" "sync" ) type command struct { dir string wg *sync.WaitGroup } func (c *command) run(w io.Writer) { defer c.wg.Done() // on linux cmd := exec.Command("sh", "-c", "pwd") //cmd := exec.Command("sh", "-c", "pwd; ls") cmd.Stdout = w cmd.Stderr = w cmd.Stdin ...
package engine import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "encoding/hex" "encoding/pem" "fmt" "log" "github.com/pkg/errors" "golang.org/x/crypto/acme" "orbit.sh/engine/docker" ) // Certificate is a TLS certificate. type Certificate st...
package packet import ( "bytes" ) var oid = map[string]string{ "2.5.4.3": "CN", "2.5.4.4": "SN", "2.5.4.5": "serialNumber", "2.5.4.6": "C", "2.5.4.7": "L", "2.5.4.8": "ST", "2.5.4.9": ...
package config const ( Manage_Inited_0 = 0 Manage_Runnig_1 = 1 Manage_Finished_2 = 2 Manage_Failed_3 = 3 Manage_Time_Out = 4 )
package main import "net/http" func SignupPageHandler(Writer http.ResponseWriter, Request *http.Request) { Session, _ := Store.Get(Request, "CCPassportSession") if Session.Values["Username"] != "" { print(Session.Values["Username"]) Writer.Header().Set("Location", "/") Writer.WriteHea...
// DO NOT EDIT. This file was generated by "github.com/frk/gosql". package testdata import ( "github.com/frk/gosql" ) func (q *SelectCoalesceTableQuery) Exec(c gosql.Conn) error { const queryString = `SELECT COALESCE(c."col_a", ''::text) , c."col_b" , COALESCE(c."col_c", 0::integer) , COALESCE(c."col_d", '0001...
package app import "interface-testing/api/controllers/weather_controller" func routes() { router.GET("/weather/:apiKey/:latitude/:longitude", weather_controller.GetWeather) }
package main import ( "fmt" "net/http" "github.com/codegangsta/negroni" "github.com/zbindenren/negroni-golog" ) func main() { r := http.NewServeMux() r.HandleFunc(`/`, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "success!\n") }) n := negroni.New() // examp...
package models import ( "gorm.io/gorm" ) type Book struct { gorm.Model Title string Author string } func DBMigrate(db *gorm.DB) { db.AutoMigrate(&Book{}) }
package main /* In the United Kingdom the currency is made up of pound (£) and pence (p). There are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made...
package tools import ( "fmt" // "github.com/buaazp/fasthttprouter" "github.com/valyala/fasthttp" // "time" "runtime" "log" ) // fasthttprouter.Params 是路由匹配得到的参数,如规则 /hello/:name 中的 :name // func httpHandle(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { // fmt.Fprintf(ctx, "hello fasthttp") // }...
package server import ( "github.com/sandro-h/prom_rest_exporter/spec" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" "os" "testing" "time" ) func TestMain(m *testing.M) { startup() retCode := m.Run() os.Exit(retCode) } func startup() { spec, _ := spec.ReadSpecFromYamlFile("testdata/server_tes...
package policies import ( "git.benfleming.nz/benfleming/gotasks/app/models" "github.com/jinzhu/gorm" "github.com/labstack/echo/v4" ) // TaskPolicy is the resource for the User model type TaskPolicy struct { DB *gorm.DB User *models.User Policy } // NewTaskPolicy returns a policy based on the given context fu...
// Copyright 2016 The etcd-operator 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...
package wordy import ( "fmt" "strconv" "strings" ) var newStrings = map[string]string { "What is ": "", "?": "", "plus": "+", "minus": "-", "multiplied by": "*", "divided by": "/", } var precedence = map[string]int { "*": 1, "/": 1, "+": 1, "-": 1, } func tokens(question string) []string { for key, va...
package main func NewSemaphore(size int) Semaphore { if size < 1 { panic("Size must be 1 or grater") } return make(Semaphore, size) } type Semaphore chan struct{} func (s Semaphore) Acquire() { s <- struct{}{} } func (s Semaphore) Release() { <-s }
package venom import ( "context" "encoding/json" "fmt" "regexp" "strconv" "strings" "time" "github.com/ovh/cds/sdk/interpolate" "github.com/pkg/errors" "github.com/rockbears/yaml" ) var varRegEx = regexp.MustCompile("{{.*}}") // Parse the testcase to find unreplaced and extracted variables func (v *Venom)...
package wikipage // WikiPage : a struct representing a Wiki page and its links type WikiPage struct { url string title string links []string isCrawled bool } // NewWikiPage : Creates a new wikipage object with the given url, title and links func NewWikiPage(url string, title string, links []string) ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-11-27 09:00 # @File : lt_1498_Number_of_Subsequences_That_Satisfy_the_Given_Sum_Condition.go # @Description : # @Attention : */ package slide_window /* 陷入一个误区, 以为是区间内的所有值 原来只是最小值和最大值相加即可 所以是排列组合问题即可 */ func numSubseq(nums []int, target int) int { if ...
package gotils_test import ( "log" "testing" "github.com/korovkin/gotils" . "github.com/onsi/gomega" ) type TestStruct struct { TSStart gotils.Time `json:"ts_start_sec,omitempty"` TSEnd gotils.Time `json:"ts_end_sec,omitempty"` } func init() { log.SetFlags(log.Ltime | log.Lshortfile | log.Lmicroseconds | l...
package open_im_sdk import ( "encoding/json" "errors" ) type Friend struct { friendListener OnFriendshipListener //ch chan cmd2Value } func (u *UserRelated) doFriendList() { friendsInfoOnServer, err := u.getServerFriendList() if err != nil { return } friendsInfoOnServerInterface := make([]diff,...
func isPowerOfFour(num int) bool { return num>0 && (num & (num-1))==0 && (num & 0x55555555) == num }
package main import ( "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func main(){ //paxinxicunshujuku() router:=gin.Default() router.Use(cors.Default()) router.POST("/KeBiao/xuehao",chaxunshuju) _ = router.Run(":8080") }
// Package medianheap implements a running median algorithm for integers // using 2 heaps. The provided operations are for adding elements and // retrieving the median. // // The time complexity for updating the median is O(logN), retrieving it O(1). // // The median value is equal to the k/2th element of a sorted arra...
package attrs import ( "testing" "github.com/stretchr/testify/require" ) func Test_Attr_GoType(t *testing.T) { tt := []struct { ct string gt string }{ {"timestamp", "time.Time"}, {"datetime", "time.Time"}, {"date", "time.Time"}, {"time", "time.Time"}, {"text", "string"}, {"Text", "string"}, {"...
package main type elemTree struct { added map[string]empty gld Guild } func (e *elemTree) addElem(name string) { _, exists := e.added[name] if exists { return } el, exists := e.gld.Elements[name] if !exists { return } for _, par := range el.Parents { e.addElem(par) } e.added[name] = empty{} } fun...
/* Copyright 2014 GoPivotal (UK) Limited. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agre...
package shift_test import ( "context" "math" "testing" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "williamfeng323/mooncake-duty/src/domains/account" "williamfeng323/mooncake-duty/src/domains/project" "william...
package types import ( sdk "github.com/irisnet/irishub/types" ) const ( // MsgRoute identifies transaction types MsgRoute = "rand" // DefaultBlockInterval is the default block interval DefaultBlockInterval = uint64(10) ) var _ sdk.Msg = &MsgRequestRand{} // MsgRequestRand represents a msg for requesting a ran...
package models import ( "fmt" "strconv" "time" "github.com/reechou/holmes" ) const ( ROBOT_GROUP_CHAT_TABLE_NUM = 10 ) const ( ROBOT_CHAT_SOURCE_FROM_USER = "来自用户" ROBOT_CHAT_SOURCE_FROM_WEB = "来自 web crm" ROBOT_CHAT_SOURCE_FROM_WEB_MASS = "来自 web crm 群发" ROBOT_CHAT_SOURCE_FROM_PHONE = "来自手机" )...
package urls import ( "github.com/go-chi/chi" "net/http" "os" "path/filepath" ) var store []func(r chi.Router) var storeStatic = [][]string{} // Register URLs as a router Group func Register(fn func(r chi.Router)) { store = append(store, fn) } // Register static files from path, accessible by url func Register...
package db import ( "os" "path" "testing" "time" "github.com/textileio/go-textile/wallet" ) var testDB *SQLiteDatastore var configAddress string func TestMain(m *testing.M) { setup() retCode := m.Run() teardown() os.Exit(retCode) } func setup() { os.RemoveAll(path.Join("./", "datastore")) os.MkdirAll(pa...
package create import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "crypto/x509/pkix" "encoding/json" "encoding/pem" "fmt" "math/big" "net" "os" "strconv" "strings" "time" sdkclient "github.com/cosmos/cosmos-sdk/client" sdkflags "github.com/cosmos/cosmos-sdk/client/flags" ...
package models import ( "fmt" "github.com/astaxie/beego/orm" "strconv" "strings" "tokensky_bg_admin/utils" ) // TableName 设置表名 func (a *AdminResource) TableName() string { return AdminResourceTBName() } // AdminResource 权限控制资源表 type AdminResource struct { Id int `orm:"pk"json:"id"form:"id"` //名称 Name ...
// Copyright 2020 Google 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
package main import ( "fmt" //"math/rand" "time" "math/rand" ) var a[25]int var x[25]int var t int func main() { for k :=0;k<=24;k++{ a[k]=rand.Intn(8)+8 //fmt.Println(a[k]) //random nos for random delays for each tourist } //x :=[8]int{rand.Intn(25)+1,rand.Intn(25)+1,rand.Intn(25)+1,rand.Intn(25)+...
/* Tests basic Gets. Tx1 gets 4 non existent keys, expect successful (but empty) Then tx1 puts the 4 keys, does not commit and gets them, expect successful with values Then tx1 commits and gets the 4 keys, expect successfull with values. Tx2 gets 4 keys it hasn't Put, (but Tx1 did put) expect success with previous val...
package main import f "fmt" func main() { msg := make(chan string) go func() { msg <- "ping" }() result := <-msg f.Println(result) }
package main import ( "encoding/json" "context" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-lambda-go/events" "fmt" ) // JsonHome is an implementation of // https://tools.ietf.org/html/draft-nottingham-json-home-04. type JsonHome struct { Resources map[string]Resource `json:"r...
package handlers import ( "github.com/authelia/authelia/v4/internal/middlewares" "github.com/authelia/authelia/v4/internal/session" ) // StateGET is the handler serving the user state. func StateGET(ctx *middlewares.AutheliaCtx) { var ( userSession session.UserSession err error ) if userSession, err...
package main import ( "fmt" "io/ioutil" "os" "strconv" "strings" "sync" ) func main() { var part int // part is defined as cmd argument if len(os.Args) > 1 && os.Args[1] == "part2" { part = 2 } else { //run part 1 as default part = 1 } var wg sync.WaitGroup input, _ := ioutil.ReadFile("input.txt") ...
package main import "fmt" type Blacklist func(string) bool func registerUser(name string, blacklist Blacklist) { if blacklist(name) { fmt.Println("You are Blocked", name) } else { fmt.Println("Welcome", name) } } //func blacklistAdmin(name string) bool { // return name == "Admin" //} // //func blacklistRoot(...
package handler import ( "context" "path/filepath" "testing" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // EchoTestSuite 是 Echo rpc 的单元测试的 Test Suite type EchoTestSuite struct { suite.Suite jinmuHealth *J...
package main import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" "log" "os" ) func main() { accessKey := "xxxxxxxxxxxxx" secretKey := "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" endpoint := "http://...
// TODO all the things! package main
// Copyright 2021 Google 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 ...
package vm import ( "fmt" "github.com/luciancaetano/arch-v/register" ) func (vm *VM) loadDSIntoReg(reg byte, addr uint64) { dataType := vm.ds.Seek(addr).ReadByte() switch register.DataType(dataType) { case register.NullType: vm.regs.rw(reg).SetNull() case register.StringType: vm.regs.rw(reg).SetString(...
package main import ( "fmt" "log" "net/http" "time" "gopkg.in/mgo.v2" ) type context struct { name string w http.ResponseWriter } // Periods hold the information of an activity // type Period struct { Type string `json:"type"` // pomodoro or rest Start time.Time End time.Time } // Periods holds an ...
package image import ( "context" "fmt" "io/fs" "os" "os/exec" "time" "github.com/coreos/stream-metadata-go/arch" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/openshift/installer/pkg/asset" "github.com/openshift/installer/pkg/asset/agent" "github.com/openshift/installer/pkg/asset/agent...
package crawler import ( "wallpager/lib" "net/http" "net/url" "strings" "encoding/json" "wallpager/db" "fmt" "strconv" "wallpager/download" "github.com/op/go-logging" ) var log = logging.MustGetLogger("crawler") func Crawl(count int) (error) { for i := 0; i <= count/21; i += 1 { err := Request(i * 21) ...
// golrn01 - Learning go // 2016-02-27 PV package main import "fmt" import "math" func main() { p := Point{3,4} d := p.Length() fmt.Println("Point Length =", d) origin := Point{} l := Line {origin, p} dl := l.Length() fmt.Println("Line Length =", dl) // Lambda quick-assigned to a variable average := fu...
package tasks import "fmt" // Run executes a task by name from a given config using the specified data func (c *Config) Run(name string, data map[string]interface{}) (interface{}, error) { t := c.Task(name) if t == nil { return nil, fmt.Errorf("unable to find task %s", name) } err := t.Validate(data) if err !...
package parked_domain import ( "fmt" "time" "sync" "net/http" "io/ioutil" log "github.com/sirupsen/logrus" "texas_real_foods/pkg/utils" "texas_real_foods/pkg/connectors" "texas_real_foods/pkg/notifications" apis "texas_real_foods/pkg/utils/api_accessors" ) type ParkedDomainC...
package main import ( "errors" "fmt" "os" "strings" "text/template" "github.com/goombaio/dag" ) // Templates are so fun. const todoTmpl = `{{range .Jobs}}{{range $n, $t := .Tags}}{{if $n}} {{end}}[{{$t}}]{{end}}:{{ $length := len .Requires}}{{if gt $length 0}} requires{{range .Requires}} [{{.}}]{{end}}{{end}} ...
//go:build !android // +build !android package main func logInit() { return }
package main import ( "fmt" "sort" "strconv" "strings" ) type node struct { val int j1 *node j2 *node j3 *node } func main() { ss := strings.Split(input, "\n") var adapters []int for _, s := range ss { i, _ := strconv.Atoi(s) adapters = append(adapters, i) } if adapters == nil { panic("nil ...
// Copyright 2023 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package main import ( "fmt" "math" ) func main() { sumsq := 0 sqsum := 0 for i := 1; i <= 100; i++ { sumsq += int(math.Pow(float64(i), 2)) sqsum += i } sqsum = int(math.Pow(float64(sqsum), 2)) diff := sqsum - sumsq fmt.Println(diff, sqsum, sumsq) }
package main import ( "fmt" "sync" ) type ChopS struct{ sync.Mutex } type Philo struct { leftCS, rightCS *ChopS } func (p Philo) eat() { for { p.leftCS.Lock() p.rightCS.Lock() fmt.Println("eating") p.rightCS.Unlock() p.leftCS.Unlock() } } func main() { CSticks := make([]*ChopS, 5) for i := 0; i <...
package main import ( "errors" "fmt" "net/http" "github.com/avaldevilap/greenlight/internal/data" "github.com/go-playground/validator/v10" ) var validate *validator.Validate func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Request) { var input struct { Title string `json:"ti...
package entity import "time" //Notification struct type NotificationTest struct { NotfDescription string NotfTitle string NotfLevel string NotfDate time.Time }
package cmd import ( "log" "github.com/naichadouban/learngrpc/grpc_gateway/server" "github.com/spf13/cobra" ) var serverCmd = &cobra.Command{ Use: "server", Short: "Run the grpc hello-word server", Run: func(cmd *cobra.Command, args []string) { defer func() { if err := recover(); err != nil { log.Pr...
package common import ( "encoding/json" errors2 "github.com/misgorod/co-dev/errors" "net/http" ) func RespondJSON(w http.ResponseWriter, status int, payload interface{}) { response, err := json.Marshal(payload) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) retur...
package routers import ( "fresh/Fresh-order/FreshOrder/controllers" "github.com/astaxie/beego" "github.com/astaxie/beego/context" ) func init() { //设置关卡 beego.InsertFilter("/goods/*",beego.BeforeExec,filterFunc) beego.Router("/", &controllers.GoodesControllers{},"get:ShowIndex") beego.Router("/register",...
package db import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) type MySqlRepository struct { } var con *sql.DB func init() { var err error con, err = sql.Open("mysql", "root:@/test") //defer con.Close() if err != nil { panic(err) } } func (r MySqlRepository) Get() []Page { rows, err := con....
package main import ( "errors" "fmt" "strconv" "encoding/json" "github.com/hyperledger/fabric/core/chaincode/shim" ) var cpPrefix = "cp:" var productPrefix = "productInfo:" var userPrefix = "user:" var cpNum = 0 type ProductInfo struct { Code string `json:"code"` //厂商编码 Name string `j...
package hitbtc import ( "encoding/json" "log" "strings" "github.com/ramezanius/crypex/exchange" ) // read redirects response to handler. func (h *HitBTC) read(event *exchange.Event, handler exchange.HandlerFunc) { var redirect = func(response interface{}) { err := json.Unmarshal(event.Params.([]byte), &respon...
package test import ( "context" "fmt" "math/rand" "sort" "testing" "time" ma "gx/ipfs/QmNTCey11oxhb1AxDnQBRHtdhap6Ctud872NjAYPYYXPuc/go-multiaddr" crypto "gx/ipfs/QmNiJiXwWE3kRhZrC5ej3kSjWHm337pYfhjLGSCDNKJP2s/go-libp2p-crypto" peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer" ps...
package main import "fmt" func main() { var n, count, max int fmt.Scan(&n) for _, v := range fmt.Sprintf("%b", n) { if v == '1' { count++ if count > max { max = count } } else { count = 0 } } fmt.Println(max) }