text
stringlengths
11
4.05M
package main import ( "os" "os/exec" ) func collect(verbose bool, corePath string) error { cmd := exec.Command("/usr/libexec/platform-python", "-m", "insights.collect", "--compress") if verbose { cmd.Args = append(cmd.Args, "--verbose") } cmd.Env = []string{ "PATH=" + os.Getenv("PATH"), "LANG=" + os...
package breaker import ( "errors" "sync" "testing" "time" ) func TestNew(t *testing.T) { b := NewBreaker(1) if b.threshold != 1 { t.Errorf("Unexpected threshold for new breaker: %d", b.threshold) } if b.failures != 0 { t.Errorf("Unexpected count for new breaker: %d", b.failures) } if b.IsOpen() { t...
package main import "fmt" func main() { printPattern(5) } func printPattern(num int) { if num%2 != 1 { fmt.Println("input harus berupa bilangan ganjil") } else { fmt.Println("====== Panjang ======") for i := 1; i < num+1; i++ { for j := 1; j < num+1; j++ { if j == 1 || j == num || i == (num+1)/2 { ...
package main type config struct { Port int `env:"DATASTASH_PORT" envDefault:"9999"` EurekaHost string `env:"DATASTASH_EUREKA_HOST" envDefault:"http://localhost:8761/eureka"` MongoURL string `env:"DATASTASH_MONGO_URL" envDefault:"mongodb://localhost:27017"` MongoAuthMechanism stri...
package logger // Logger handles log commands and generates the log string for a handler type Logger interface { NewLogger(subcomponent string) Logger Panic(str string, v ...interface{}) Error(str string, v ...interface{}) error Warn(str string, v ...interface{}) Info(str string, v ...interface{}) Verbose(level ...
package add var A int8 = 11 func Sum(a, b int) int { return a + b - 1 }
package format import ( "github.com/plandem/xlsx/internal/ml/primitives" ) //List of all possible values for FontVAlignType const ( FontVAlignBaseline primitives.FontVAlignType = "baseline" FontVAlignSuperscript primitives.FontVAlignType = "superscript" FontVAlignSubscript primitives.FontVAlignType = "subscr...
package main import "fmt" func main() { var a [2]string a[0] = "Hello" a[1] = "Oleg" fmt.Println(a[0], a[1]) fmt.Println(a) primes := [6]int{2, 3, 5, 7, 11, 13} fmt.Println(primes) x := [5]float64{ 98, 93, 77, 82, 83, } var...
package handler import ( "context" "fmt" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/subscription/v1" ) // GetUserCountOfSubscription 获取订阅下的用户数量 func (j *SubscriptionService) GetUserCountOfSubscription(ctx context.Context, req *proto.GetUserCountOfSubscriptionRequest, resp *proto.GetUserCoun...
package ghosts import "testing" func TestSpirit(t *testing.T) { result := new(Spirit) expectedName := "Spirit" expectedEvidence := [3]string{"Spirit Box", "Writing", "Fingerprints"} t.Run("Spirit.Name()", func(t *testing.T) { if result.Name() != expectedName { t.Errorf("Spirit.Name() should equal %v, but i...
package main import ( "flag" "fmt" "os" "path/filepath" "strings" "time" log "github.com/schollz/logger" "github.com/schollz/teoperator/src/download" "github.com/schollz/teoperator/src/ffmpeg" "github.com/schollz/teoperator/src/op1" "github.com/schollz/teoperator/src/server" ) func main() { var flagSynth...
package implwin import ( "draw" "win" ) type GeometricPenWin struct { hPen win.HPEN style draw.PenStyle brush draw.IBrush width int } func NewGeometricPenWin(style draw.PenStyle, width int, brush BrushWin) (*GeometricPenWin, error) { if brush == nil { return nil, draw.NewError("brush cannot be nil") } st...
// 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 levelOrder type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func levelOrder(root *TreeNode) [][]int { res := [][]int{} queue := []*TreeNode{root} for len(queue) != 0 { length := len(queue) level := []int{} for i := 0; i < length; i++ { if queue[i] == nil { continue } ...
package data import ( "caching-service/config" "errors" "time" "github.com/gomodule/redigo/redis" ) //RedisClientPool ... var RedisClientPool *redis.Pool //InitializeRedisClientPool ... func InitializeRedisClientPool() { RedisClientPool = &redis.Pool{ MaxIdle: 10, IdleTimeout: 240 * time.Second, Dial...
package main import ( "flag" "fmt" "log" "time" redis "gopkg.in/redis.v4" ) type redisWorker struct { chname string result chan results redis.Options } var ( workerNum = 1 chname = "test" chnameSerialize = false duration = time.Duration(1 * time.Second) redisOpt = redis.Opt...
package main import ( "fmt" "strings" "github.com/tealeg/xlsx/v3" ) var HEADERS = []string{ "NIVEAU HABILITATION", "ENTITES", "ACCES GEOGRAPHIQUE", "FONCTION", "SEGMENT", "PRENOM", "NOM", "ADRESSE MAIL", "GOUP", "SCOPE", "BOARDS", "TASKFORCE", } var NOM_PREMIERE_PAGE = "utilisateurs" func splitExcel...
package main type Str interface { toStr() add() } type user struct { a int b string } type manger struct { *user aa int bb string } func (u user) toStr() { println("IMY********user", u.a, " ", u.b) } func (u user) add() { println("IMY********user222", u.a, " ", u.b) } func (m manger) toStr() { println("...
package service import ( "fmt" "net/http" "github.com/go-ocf/cloud/cloud2cloud-connector/store" "github.com/gorilla/mux" ) func (rh *RequestHandler) deleteLinkedAccount(w http.ResponseWriter, r *http.Request) (int, error) { linkedAccountId, _ := mux.Vars(r)[linkedAccountIdKey] var h LinkedAccountHandler err...
package handler import ( "context" "errors" "fmt" "github.com/golang/protobuf/ptypes" "github.com/jinmukeji/jiujiantang-services/service/auth" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1" ) // JinmuLAccountLogin 用户登录 func (j *JinmuHealth) JinmuLAccountLogin(ctx context.Context, req...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-09-04 08:30 # @File : lt_6_ZigZag_Conversion.go # @Description : # @Attention : */ package v0 import "strings" /* 以z字的形状打印出这个字符串 通过 list + flag 来辅助即可 flag的作用在于使得 可以让索引下标 从 0->1->2..->n-1 ==> n-1->n-2->,,,->0 */ func convert(s string, numRows int) ...
package pgsql import ( "testing" ) func TestDate(t *testing.T) { testlist2{{ scanner: DateToTime, data: []testdata{ {input: dateval(1999, 1, 8), output: dateval(1999, 1, 8)}, {input: dateval(2001, 5, 5), output: dateval(2001, 5, 5)}, {input: dateval(2020, 3, 28), output: dateval(2020, 3, 28)}, }, },...
package ds /** * * Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Find the kth positive integer that is missing from this array. Example 1: Input: arr = [2,3,4,7,11], k = 5 Output: 9 Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5...
package water import ( "net" "os/exec" "testing" "time" "github.com/songgao/water/waterutil" ) func startPing(t *testing.T, dst net.IP) { if err := exec.Command("ping", "-c", "4", dst.String()).Start(); err != nil { t.Fatal(err) } } func setupIfce(t *testing.T, self net.IP, remote net.IP, dev string) { if...
package jobs import ( "encoding/json" "errors" "sync" "time" "fmt" "github.com/golang/glog" "github.com/hyperpilotio/blobstore" deployer "github.com/hyperpilotio/deployer/apis" "github.com/hyperpilotio/go-utils/log" "github.com/hyperpilotio/workload-profiler/clients" "github.com/hyperpilotio/workload-prof...
package export import ( "github.com/YFJie96/wx-mall/pkg/setting" ) const EXT = ".xlsx" // GetExcelFullUrl 获取Excel文件的完整访问路径 func GetExcelFullUrl(name string) string { return setting.AppSetting.PrefixUrl + "/" + GetExcelPath() + name } // GetExcelPath 获取Excel文件的相对保存路径 func GetExcelPath() string { return setting.Ap...
package main import ( "encoding/json" "fmt" "log" "net/http" "github.com/chasekaylee/gawkbox-mobile/twitch" ) /* 1) search for live creators based on username GET - with query as body /api/search 2) deliever top 10 featured streamers when req made GET /api/featured */ func main() { fmt.Println("Bo...
package main import "fmt" func main() { // var aprovados map[int]String //Maps devem ser inicializados aprovados := make(map[int]string) aprovados[123] = "Maria Madalena" aprovados[345] = "João Batista" fmt.Println(aprovados) for key, value := range aprovados { fmt.Printf("Nome: %s, CPF: %d\n", value, key...
package template type Element struct { Title string `json:"title"` Url string `json:"item_url,omitempty"` ImageUrl string `json:"image_url,omitempty"` Subtitle string `json:"subtitle,omitempty"` DefaultAction *Button `json:"default_action,omitempty"` Buttons []Button `j...
package webhooks import ( "context" "errors" "fmt" "reflect" "sync" "time" "github.com/go-logr/logr" networkaddonsv1 "github.com/kubevirt/cluster-network-addons-operator/pkg/apis/networkaddonsoperator/v1" vmimportv1beta1 "github.com/kubevirt/vm-import-operator/pkg/apis/v2v/v1beta1" corev1 "k8s.io/api/core/v...
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2019 Datadog, Inc. package utils import ( "testing" "github.com/stretchr/testify/assert" corev...
package router import ( "encoding/hex" "gopkg.in/macaron.v1" ) func IdFilter(ctx *macaron.Context) { id := ctx.Query("id") if id != "" { h, err := hex.DecodeString(id) if err != nil && len(h) != 12 { ctx.Data["status_code"] = 404 ctx.Data["status"] = "fail" ctx.Data["message"] = "404 not found" } ...
package language import ( "bytes" "fmt" "reflect" "strconv" "strings" "github.com/qlova/script" ) //Javascript returns a script formatted as Javascript source code. func Javascript(f func(q script.Ctx)) []byte { var q = script.NewCtx() var language = new(javascript) language.imports = make(map[string]bool) ...
package leetcode import "testing" func TestFreqAlphabets(t *testing.T) { if freqAlphabets("10#11#12") != "jkab" { t.Fatal() } if freqAlphabets("1326#") != "acz" { t.Fatal() } if freqAlphabets("25#") != "y" { t.Fatal() } if freqAlphabets("12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#") != "...
package sugar import ( "bytes" "fmt" "strconv" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/swf" ) //error code constants const ( ErrorTypeUnknownResourceFault = "UnknownResourceFault" ErrorTypeWorkflowExecutionAlreadyStartedFault = "WorkflowExecutionAlreadyStartedFault"...
package main import ( "fmt" "runtime" "sync" ) var wg1 sync.WaitGroup func main() { runtime.GOMAXPROCS(1) //设置GO运行时调度器可用逻辑CPU数: 把该逻辑CPU分配到某个物理CPU: 给每个物理CPU分配一个逻辑CPU runtime.GOMAXPROCS(runtime.NumCPU()) wg1.Add(2) //设置WaitGroup计数=2 go printPrime1("A") go printPrime1("B") wg1.Wait() //阻塞, 直到WaitGroup计数=0, 即...
// Implementation of item category enumeration. // // @author TSS package domain import ( "strings" ) var ( ItemCategoryEnum = newItemCategoryRegistry() ) type ItemCategory struct { code string name string } type itemCategoryRegistry struct { BankAccount *ItemCategory CreditCard *ItemCategory Datab...
package postgres import ( "context" core "github.com/Qalifah/aboki-africa-assessment" ) type UserRepository struct { client *Client } func NewUserRepository(client *Client) *UserRepository { return &UserRepository{client: client} } func(u *UserRepository) CreateUser(ctx context.Context, user *core.User) error ...
package main import ( "bufio" "fmt" "strings" "testing" ) const verboseTestOutput = `=== RUN Test_sayHi --- PASS: Test_sayHi (0.00s) === RUN Example_sayHi --- PASS: Example_sayHi (0.00s) === RUN Example_replaceLineEndings --- FAIL: Example_replaceLineEndings (0.00s) got: "a\n\nb\n\nc" "a\nb\nc" "a\nb\nc" "a...
package logger import ( "bufio" "fmt" "os" "path/filepath" "strings" "time" ) // Logger - ロガー。 type Logger struct { tracePath string debugPath string infoPath string noticePath string warnPath string errorPath string fatalPath string printPath string traceFile *os.File debugFile *os.File ...
package unarchive import ( "fmt" "github.com/myProj/scaner/new/include/appStruct" "sync" "time" ) var counter = 1 func setTimeEverySecond(guiC *appStruct.GuiComponent,st chan bool) { //set zero time t := time.Time{} for { select { case <-st: guiC.ScanningTimeInfo.UpdateTextFromGoroutine("") gu...
package test import ( "testing" ) // TestWatcher TestWatcher func TestWatcher(t *testing.T) { }
// Copyright 2013 Beego Samples 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 agr...
package consul import ( "encoding/json" "path" "github.com/geniuscirno/smg/registrator" "github.com/hashicorp/consul/api" ) func init() { registrator.Register(&builder{}) } type builder struct{} func (b *builder) Build(target registrator.Target) (registrator.Registrator, error) { cli, err := api.NewClient(&a...
package clouddatastore import ( "context" "fmt" "github.com/qnib/metahub/pkg/storage" "cloud.google.com/go/datastore" ) type accountService struct { ctx context.Context client *datastore.Client } func (s *accountService) Upsert(name string, a storage.Account) error { k := datastore.NameKey(accountEntityK...
package tlvconverter import ( "log" "sync" "sync/atomic" "time" ) // MonitoredQueue contains the implementation of the struct a monitored queue. type MonitoredQueue struct { in int64 out int64 base chan PacketType lastCheck time.Time mu sync.RWMutex readDelay time.Duration wr...
package apiserver_test import ( "github.com/bolshagin/xsolla-be-2020/internal/apiserver" "github.com/stretchr/testify/assert" "testing" ) // Тестирование функции по проверке номера карты func TestIsCreditCard(t *testing.T) { testCases := []struct { name string cardNumber string isValid bool }{ {...
// Package config reads, writes and edits the config file and deals with command line flags package fcrypto import ( "bufio" "bytes" "crypto/rand" "crypto/sha256" "encoding/base64" "fmt" "io" "io/ioutil" "log" "os" "strings" "unicode/utf8" "github.com/pkg/errors" "golang.org/x/crypto/nacl/secretbox" "g...
/* Challenge: Given the input number n. It should give me nested sublists of n layers with the power of two numbers for each level. Each power of two value will be in separate sublists. Notes: n will always be greater than 0 I am using the example output with Python Lists. You can use any type of sequence in your ow...
// 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 Mark import ( "errors" "github.com/imroc/biu" "strconv" ) //分割ip段位以.为分割标志 func SplitPoint(IP string) []string { var IPS []string j := 0 for i, s := range IP { if s == 46 { IPS = append(IPS, IP[j:i]) j = i + 1 } } IPS = append(IPS, IP[j:]) return IPS } //获得掩码位数 func GetMarkNum(mark string) ...
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" "regexp" smartling "github.com/Smartling/api-sdk-go" "github.com/reconquest/hierr-go" "github.com/tcnksm/go-input" ) func doInit(config Config, args map[string]interface{}) error { fmt.Printf("Generating %s...\n\n", config.path) prompt := func...
package main import ( "fmt" ) func main() { fmt.Println(sum(10, 5)) fmt.Println(odd(sum(10, 5))) } func sum(a, b int) int { return a + b } func odd(x int) (int, string) { if x%2 == 0 { return x, "is odd" } return x, "is not odd" }
/* * @lc app=leetcode id=4 lang=golang * * [4] Median of Two Sorted Arrays */ package main func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { popLeft, popRight := 0, 0 i, j := 0, len(nums1)-1 m, n := 0, len(nums2)-1 for i <= j || m <= n { // pop from left if m > n || i <= j && nums1[i] < nums2...
package libdiscover import ( "encoding/json" "io/ioutil" "log" "strconv" "strings" "time" "github.com/hashicorp/memberlist" "github.com/hashicorp/serf/serf" "github.com/sirupsen/logrus" ) type Discover struct { name string bindAddr string advertiseAddr string joinAddr stri...
package display import ( "html/template" "strconv" "github.com/GoAdminGroup/go-admin/template/types" ) type Carousel struct { types.BaseDisplayFnGenerator } func init() { types.RegisterDisplayFnGenerator("carousel", new(Carousel)) } func (c *Carousel) Get(args ...interface{}) types.FieldFilterFn { return fun...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2022/1/4 8:48 上午 # @File : lt_40_组合总和2.go # @Description : # @Attention : */ package hot100 func combinationSum2(candidates []int, target int) [][]int { if len(candidates) == 0 { return nil } var ( single []int ret [][]int dfs func(left, index int...
/* Copyright 2021 The KubeVela 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, so...
package log import ( "context" "sfgo/core/log/base" "sfgo/core/log/zap" ) var ( // 确保不为空 DefaultLogger base.ILogger = zap.New() ) func init() { DefaultLogger = zap.New() } // 以下为log模块的输出方法。 func Debug(ctx context.Context, format string, args ...interface{}) { GetLogger().WithFields(Caller()).Debug(ctx, forma...
package context import ( "time" ) type DeadlineReason string func (r DeadlineReason) String() string { return string(r) } func (r DeadlineReason) Error() string { return string(r) } var deadlineKey = &struct{ bool }{} type deadlineValue struct { end time.Time timer *time.Timer } func (c *ctx) deadlineExce...
package config import ( "errors" "flag" "github.com/spf13/viper" ) // Config holds all application configurations type Config struct { Env string `json:"env"` Application *ApplicationSetting `json:"application"` Database *DatabaseSetting `json:"database"` Auth *AuthSetting ...
package problem0871 func minRefuelStops(target int, startFuel int, stations [][]int) int { n := len(stations) dp := make([]int, n+1) dp[0] = startFuel // 对于每个车站 for i := 0; i < n && stations[i][0] < target; i++ { for j := i + 1; j > 0; j-- { // 如果 j-1 次可以经过stations[i],那么第j次就可以经过dp[j-1] + stations[i].fuel ...
package jarviscore import ( "context" "strconv" "sync" jarvisbase "github.com/zhs007/jarviscore/base" "go.uber.org/zap" jarviscorepb "github.com/zhs007/jarviscore/proto" ) // FuncOnRangeProcMsgResult - onRangeProcMsgResult type FuncOnRangeProcMsgResult func(prmd *ProcMsgResultData) // procMsgResultMgr - proc...
package main import ( "fmt" "github.com/ant0ine/go-urlrouter" ) func main() { router := urlrouter.Router{ Routes: []urlrouter.Route{ urlrouter.Route{ PathExp: "/resources/:id", Dest: "one_resource", }, urlrouter.Route{ PathExp: "/resources", Dest: "all_resources", }, }, } ...
package node import ( "context" "fmt" "io/ioutil" "net" "os" "github.com/projecteru2/cli/cmd/utils" "github.com/projecteru2/cli/describe" corepb "github.com/projecteru2/core/rpc/gen" "github.com/urfave/cli/v2" ) type addNodeOptions struct { client corepb.CoreRPCClient opts *corepb.AddNodeOptions } fun...
package math import "fmt" func Fibonacci(n int) { FmtFibonacci(n, "%d\n") } func FmtFibonacci(n int, fmtString string) { if n == 0 { return } var currentNumber, prevNumber int = 1, 1 fmt.Printf(fmtString, currentNumber) if n > 1 { fmt.Printf(fmtString, currentNumber) } for i := 3; i <= n; i++ { var...
// Copyright © 2018 Inanc Gumus // Learn Go Programming Course // License: https://creativecommons.org/licenses/by-nc-sa/4.0/ // // For more tutorials : https://learngoprogramming.com // In-person training : https://www.linkedin.com/in/inancgumus/ // Follow me on twitter: https://twitter.com/inancgumus package main ...
package eliza import ( // "fmt" "reflect" "testing" ) func TestCheckForQuit(t *testing.T) { no_quit := []string{"this", "is", "a", "string"} if CheckForQuit(no_quit) { t.Errorf("Found a quit statement in a string without one.") } quit := []string{"this", "bye", "a", "string"} if !CheckForQuit(quit) { t...
package main import "fmt" var helloworld = "helloword" func print(s string) { fmt.Println(s) } func main()
package model import ( "encoding/json" "fmt" "github.com/ahmetb/go-linq" ) type TypeData struct { Define *TypeDefine Tab *DataTable // 类型引用的表 Row int // 类型引用的原始数据(DataTable)中的行 } type TypeTable struct { fields []*TypeData } func (self *TypeTable) ToJSON(all bool) []byte { data, _ := json.Marsh...
// Package httpd provides the HTTP server for accessing the distributed key-value store. // It also provides the endpoint for other nodes to join an existing cluster. package httpd import ( "encoding/json" "fmt" "io" "log" "net" "net/http" "os" "strings" "github.com/hashicorp/raft" "raftdb/pkg/store" ) //...
package example import ( "bytes" ) // Buffer is an example for Element for refpool type Buffer struct { bytes.Buffer count int64 } // Counter implement Element interface: func (b *Buffer) Counter() *int64 { return &b.count }
package main //import "fmt" // //func main() { // fmt.Println([...]string{"1"} == [...]string{"1"}) //true // fmt.Println([]string{"1"} == []string{"1"}) // // Invalid operation: []string{"1"}==[]string{"1"} (operator == is not defined on []string) // //}
package main import "fmt" func main() { var name string = "Ankit"; fmt.Println(name); var a,b int = 3,4; //sum fmt.Println("Sum",a+b); var bool = true; fmt.Println("Boolean",bool); var t float32 = 3.2; fmt.Println("Float -",t); }
package ffmpeg import ( "context" "encoding/json" "os/exec" ) type FFprobe struct { cmd string v string // loglevel print_format string show_format bool show_streams bool input string probe *Probe Sentence string } func DefaultProbe() *FFprobe { return &FFprobe{ cmd: ...
package opencontainer import "os" func int64ToPointer(i int64) *int64 { return &i } func fileModeToPointer(fileMode os.FileMode) *os.FileMode { return &fileMode } func uint32ToPointer(u uint32) *uint32 { return &u } // DefaultRuntimeSpec is the default template for running Linux containers. // NOTE: runtime.jso...
package com type ServiceError struct { ErrorCode int `json:"error_code"` StatusCode int `json:"-"` Message string `json:"message"` } func (se *ServiceError) Error() string { return se.Message } var ( ParameterError = &ServiceError{ErrorCode: 400000 , StatusCode: 400, Message: "invalid parameters"} InternalErr...
package main import ("fmt" ) func main() { x := 15 a := &x //memory adress fmt.Println(a, *a) *a = 5 // указатель на объект в ячейке памяти x = 16 fmt.Println(a, x) *a = *a**a fmt.Println(a, x) }
package core import ( "fmt" "io/ioutil" "os" ) // Save metrics in a file func Save(path, name, metrics string) error { if err := os.MkdirAll(path, 0755); err != nil { return err } return ioutil.WriteFile(fmt.Sprintf("%s/%s", path, name), []byte(metrics), 0744) }
/* 实验返回html, 需在当前路径下,建一个templates文件夹,然后新建index.html 失败 */ package main import ( "net/http" "path" "html/template" ) type DataHtml struct { Name string Hobbies []string } func main(){ mux := http.NewServeMux() mux.HandleFunc("/html",htmlHandle) http.ListenAndServe(":123456",mux) } func htmlHandle(w http.R...
/* Input The input is a single positive integer n Output The output is n with its most significant bit set to 0. Test Cases 1 -> 0 2 -> 0 10 -> 2 16 -> 0 100 -> 36 267 -> 11 350 -> 94 500 -> 244 For example: 350 in binary is 101011110. Setting its most significant bit (i.e. the leftmost 1 bit) to 0 turns it into 00...
package main import ( "fmt" "time" ) func worker(id string, work chan string) { for s := range work { fmt.Println(id, "received", s) } } func main() { workers := make(map[string]chan string) for i := 0; i < 4; i++ { id := fmt.Sprint("worker", i) ch := make(chan string) go worker(id, ch) workers[id] =...
package _009_palindrome_number func isPalindrome(x int) bool { if x < 0 || (x%10 == 0 && x != 0) { return false } rn := 0 for x > rn { rn = rn*10 + x%10 x = x / 10 } return x == rn || rn/10 == x }
package 二叉树 // -------------------- 错误写法 -------------------- func isSubPath(head *ListNode, anyRoot *TreeNode) bool { if head == nil { return true } if anyRoot == nil { return false } if head.Val == anyRoot.Val { return isSubPath(head.Next, anyRoot.Left) || isSubPath(head.Next, anyRoot.Right) } else { r...
package main func main() { const x, y int = 123, 0x22 const s = "hello, world!" const c = '我' println(x, y) println(s, c) const ( i, f = 1, 0.123 b = false ) println(i, f) println(b) }
package profilopedia import ( "github.com/spf13/viper" ) var appConfig *Config type Config struct { Port string GithubApiUrl string DefaultPage int DefaultPerPage int TwitterConsumerKey string TwitterConsumerSecret string TwitterAccessToken ...
package arrays func urlify(s string, l int) string { sarr := []rune(s) current := l - 1 insertAt := len(s) - 1 for current >= 0 { if sarr[current] != ' ' { sarr[insertAt] = sarr[current] insertAt-- } else { sarr[insertAt] = '0' sarr[insertAt-1] = '2' sarr[insertAt-2] = '%' insertAt -= 3 } ...
package main import ( "fmt" "github.com/little-go/little-gin/pkg/setting" ) func init() { setting.Setup() } func main() { fmt.Println("done") }
/* Copyright 2020 The Kubernetes 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, ...
package pgsql import ( "database/sql" "database/sql/driver" ) // VarCharArrayFromStringSlice returns a driver.Valuer that produces a PostgreSQL varchar[] from the given Go []string. func VarCharArrayFromStringSlice(val []string) driver.Valuer { return textArrayFromStringSlice{val: val} } // VarCharArrayToStringSl...
package version const ( Maj = "1" Min = "0" Fix = "0" ) var ( GitCommit string )
package namespaceclaim import ( "context" "fmt" clusterv1 "github.com/appvia/hub-apis/pkg/apis/clusters/v1" configv1 "github.com/appvia/hub-apis/pkg/apis/config/v1" core "github.com/appvia/hub-apis/pkg/apis/core/v1" orgv1 "github.com/appvia/hub-apis/pkg/apis/org/v1" kubev1 "github.com/appvia/kube-operator/pkg/...
package main import ( "fmt" "github.com/jnewmano/advent2020/input" ) func main() { // input.SetRaw(raw) // var things = input.Load() // var things = input.LoadSliceSliceString("") sum := parta() fmt.Println(sum) } // find the two entries that sum to 2020 and then multiply those two numbers together. func p...
package validate import "reflect" // some default value settings. const ( filterTag = "filter" filterError = "_filter" validateTag = "validate" validateError = "_validate" // sniff Length, use for detect file mime type sniffLen = 512 // 32 MB defaultMaxMemory int64 = 32 << 20 ) // M is short name for...
package handler import ( "context" "errors" "path/filepath" "testing" "github.com/stretchr/testify/assert" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1" "github.com/stretchr/testify/suite" ) // AccountLoginTestSuite 账户登录的单元测试的 Test Suite type AccountLoginTestSuite struct { suite.S...
package user import ( "encoding/json" "errors" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" ) // DynaClient Dynamodb c...
package resolver import ( "context" "fmt" "cloudfreexiao/ant-graphql/backend-go/graphql/model" "cloudfreexiao/ant-graphql/backend-go/graphql/scalar" "cloudfreexiao/ant-graphql/backend-go/lib/network" ) const procNetDevPath = "/proc/net/dev" type ifaceArgs struct { Name string } func (r *Resolver) Iface(ctx c...
package token import ( "bufio" "bytes" "fmt" "io" "strings" "unicode" ) type Lexer struct { input io.RuneReader pos int last int lahError error lahRune rune lahN int } func (self *Lexer) InitWithRuneReader(input io.RuneReader) { self.input = input self.lahRune, self.lahN, self.lahError...
package utils import ( "sync" ) // https://blog.golang.org/go-maps-in-action#TOC_6. type single struct { mu sync.Mutex values map[string]string } var globalmap = single{ values: make(map[string]string), } func GlobalCacheGetExistence(key string) bool { globalmap.mu.Lock() defer globalmap.mu.Unlock() // d...
//geometry.go package main import ( "fmt" "geometry/rectangle" ) func main() { fmt.Println("Geometrical shape properties") var rectLength, rectWidth = 6.0, 7.0 fmt.Printf("Area is %.2f", rectangle.Area(rectLength, rectWidth)) fmt.Printf("Diagonal is %.2f", rectangle.Diagonal(rectLength, rectWidth)) } func init...