text
stringlengths
11
4.05M
package remove import "store" func RemoveEmployeesFromList(ids []int, employees *([]store.Employee)){ for _, id := range ids{ for i:=0; i < len(*employees); i++{ if ((*employees)[i]).GetID() == id{ ((*employees)[i]).There = false } } } } func RemoveEmployeesFromIdEmpMap(ids []int, idEmpMap ...
package main type department struct { jsonobj map[string]interface{} instructors map[string]bool courses map[string]bool rooms map[string]bool } func (dep *department) init(obj map[string]interface{}) { dep.jsonobj = obj dep.instructors = map[string]bool{} dep.courses = map[string]bool{} dep.roo...
package destinationrule import ( "encoding/json" "errors" "fmt" "github.com/gogo/protobuf/jsonpb" istio "istio.io/api/networking/v1alpha3" "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/client-go/dynamic" ) type destinationRuleValidator struct { destination...
package controllers import ( // "fmt" "openvpn/models" "github.com/astaxie/beego" ) type UpdateallController struct { beego.Controller } func (this *UpdateallController) Get() { //检测登录 if !checkAccount(this.Ctx) { this.Redirect("/login", 302) return } var err error err = models.UpdateAllUser() if err ...
package gbt36104 import ( "testing" "github.com/stretchr/testify/assert" "gorm.io/driver/sqlite" "gorm.io/gorm" ) func TestGormGen(t *testing.T) { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{ DisableForeignKeyConstraintWhenMigrating: true, }) assert.NoError(t, err) assert.NoError(t, db.AutoMi...
package runner import ( "fmt" "log" "os" "os/exec" "path/filepath" "sort" "strconv" "strings" "time" ) func Run(database string, bin string, dir string, backup int, verbose int) error { var log = func(text string) { // fmt.Sprintf("verbose:%d", verbose) // log. if verbose > 0 { // log.DefaultLogge...
package db import ( "fmt" "time" ) type PostgreSQLConfig struct { Server string `envconfig:"server"` Port string `envconfig:"port"` User string `envconfig:"user"` Password string `envconfig:"password"` DatabaseName string `envconfig:"d...
package rate import ( "math/rand" ) type RateValue struct { Rate float64 Value interface{} } type Rate struct { MaxRate float64 RateValues []RateValue RandFunc func() float64 // return number in [0.0,1.0) } func NewRate() *Rate { return &Rate{} } func (r *Rate) Add(rate float64, value interface{}) { ...
package main import ( "encoding/base64" "encoding/json" "errors" "flag" "fmt" "html/template" "io/ioutil" "log" "net/http" "path/filepath" "strconv" "strings" "github.com/gorilla/securecookie" "github.com/gorilla/sessions" ) var configFile = flag.String("config", "./config.json", "config file") var st...
package test import ( "bytes" "fmt" "io/ioutil" "log" "net/http" "net/url" "strings" "testing" "github.com/stretchr/testify/assert" ) func NewRequest( method, url string, ops ...func(*http.Request)) *http.Request { req, _ := http.NewRequest(method, url, nil) for _, op := range ops { op(req) } ret...
package clusterpipelinetemplate import ( "log" devopsv1alpha1 "alauda.io/devops-apiserver/pkg/apis/devops/v1alpha1" devopsclient "alauda.io/devops-apiserver/pkg/client/clientset/versioned" "alauda.io/diablo/src/backend/api" "alauda.io/diablo/src/backend/errors" "alauda.io/diablo/src/backend/resource/dataselect"...
package main import ( "fmt" "math/rand" "sync" "time" "../RateLimiter/client" "../RateLimiter/models" ) func main() { /*r, err := client.NewThrottleRateLimiter( &models.Config{ Throttle: 1 * time.Second, })*/ /*r, err := client.NewMaxConcurrencyLimiter(&models.Config{ Limit: 2, TokenResetAf...
package impl import "github.com/t-yuki/panick/internal" func init() { iface.GetPanic["go1.8"] = GetPanic } func GetPanic() iface.Panic { if p := getPanic(); p != uintptr(0) { return &Panic{p: p} } return nil } type Panic struct { p uintptr } func (p Panic) Recovered() bool { return panicRecovered(p.p) } f...
/* This file is a modified version of 1 file in Deepak Jois' golang usbdrivedetector Big thank you to him, you can view his original project here https://github.com/deepakjois/gousbdrivedetector */ package usbdrivedetector import ( "bufio" "bytes" "log" "os/exec" "regexp" "strings" ) // Detect returns a list...
package main import ( "encoding/json" "fmt" "github.com/gen2brain/beeep" "github.com/tardisgo/tardisgo/goroot/haxe/go1.4/src/strconv" "io/ioutil" "net/http" "os" "time" ) type CovidData struct { Centers []struct { CenterID int `json:"center_id"` Name string `json:"name"` StateName str...
package services import ( "fmt" "strings" "github.com/apulis/AIArtsBackend/configs" "github.com/apulis/AIArtsBackend/models" ) func CreateVisualJob(userName string, jobName string, logdir string, description string) error { //step1. create a background job relateJobId, err := createBackgroundJob(userName, jobN...
/** * Testing file for linked list **/ package linkedListTesting import ( "testing" // "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ll "linkedList/main.go/linkedlist" ) type appendSuite struct { suite.Suite } var alr ll.LinkedList func (s *appendSuite) BeforeTest(suiteName, testN...
package node import ( "context" "testing" "github.com/josetom/go-chain/core" "github.com/josetom/go-chain/db" "github.com/josetom/go-chain/test_helper" "github.com/josetom/go-chain/test_helper/test_helper_core" ) func TestMine(t *testing.T) { db.Config.Type = db.LEVEL_DB test_helper.SetTestDataDirs() tempDb...
package helper import ( "encoding/json" "net/http" ) // JSONError will hold the data that is responded to the client type Response struct { Code int Response interface{} Error error } func CreateResponse(rw http.ResponseWriter, req *http.Request, status int, response interface{}, incomingError error) err...
package models import "time" type User struct { Id int64 FirstName string LastName string Active bool CreatedAt *time.Time UpdatedAt *time.Time }
package main import ( "crypto/sha512" "encoding/base64" "log" "net/smtp" "strings" ) // sendEmail sends an email to an user. // XXX use several SMTP according to the destination email // provider to speed things up. func sendEmail(to, subject, msg string) error { body := "To: " + to + "\r\nSubject: " + subjec...
package main import ( "context" "os" "os/signal" "path/filepath" "strconv" "syscall" "time" log "github.com/sirupsen/logrus" apiv1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" kh "github.com/kuberhealthy/kuberhealthy/v2/pkg/checks/external/checkclient" "github.com/kuberhealthy/kuberhealthy/v2/pkg/c...
package main import ( "bytes" "encoding/hex" "io/ioutil" "os" ) var ( _VjsonConfig_need_save bool //_VC _Tconfig //_VjsonConfig_bytes []byte ) func _Fbase_104c__try_to_get_env_id128() { __Vstr := os.Getenv("id128") _FpfN(" 823813 01 read env id128 is (%d)[%s]", len(__Vstr), __Vstr) if "" == __Vstr |...
package cache import ( "github.com/despreston/vimlytics/redis" "log" "time" ) const ttl = 72 * time.Hour func Get(key string) (string, bool) { var val string val, err := redis.Client().Get(redis.Ctx, key).Result() if err == redis.Empty { return "", false } else if err != nil { log.Printf("Error @ redis ...
package main import ( "log" "shared/protobuf/pb" ) func (c *Client) GetGachaList(req *pb.C2SGetGachaList) (*pb.S2CGetGachaList, error) { gameResp, err := c.Request(1201, req) if err != nil { return nil, err } resp := &pb.S2CGetGachaList{} err = c.Handle(gameResp, resp) if err != nil { return nil, err } ...
package zhttp import ( "bufio" "fmt" "net" "net/http" "time" ) // Logger wraps a ResponseWriter and records the resulting status code // and how many bytes are written type Logger struct { http.ResponseWriter length int64 status int started time.Time Now func() time.Time } // Write implements Respons...
package benchs import ( "database/sql" "fmt" models "github.com/efectn/go-orm-benchmarks/benchs/sqlboiler" _ "github.com/jackc/pgx/v4/stdlib" "github.com/volatiletech/sqlboiler/v4/boil" "github.com/volatiletech/sqlboiler/v4/queries/qm" ) var sqlboiler *sql.DB func init() { st := NewSuite("sqlboiler") st.Ini...
package recurly import ( "encoding/json" "net/http" "strings" ) // Error contains basic information about the error type Error struct { recurlyResponse *ResponseMetadata Message string Class ErrorClass Type ErrorType Params []ErrorParam TransactionError *Transaction...
// Copyright 2021 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import ( "fmt" "rand" "time" . "sort" ) // sort modifies the slice s so that the integers are sorted in // place using quicksort func sort(s []int) { n := len(s) if n < 2 { return } pivot := rand.Intn(n) p := s[pivot] s[pivot] = s[n-1] k := partition(s[0:n-1], p) s[n-1] = s[k] s[k] = p ...
package main import ( "fmt" "time" ) func main() { fmt.Println(fmt.Println(time.Now().Format("060102-150405"))) }
package main import ( "log" console "github.com/AsynkronIT/goconsole" "github.com/AsynkronIT/protoactor-go/actor" "github.com/GuiltyMorishita/money-transfer-saga/saga" ) func main() { var ( numberOfTransfers = 1000 uptime = 99.99 refusalProbability = 0.01 busyProbability = 0.01 retryAt...
package tengo2lua_test import ( "fmt" "github.com/d5/tengo2lua" ) func ExampleTranspiler() { src := []byte(` each := func(x, f) { for k, v in x { f(k, v) } } sum := 0 each([1, 2, 3], func(i, v) { sum += v }) `) t := tengo2lua.NewTranspiler(src, nil) dst, err := t.Convert() if err != nil { panic(err) } fm...
package main import ( "fmt" "os" "path" "io" "strings" "path/filepath" "github.com/codegangsta/cli" ) func Extract(c *cli.Context) { if len(c.Args()) == 0 { fmt.Fprintln(os.Stderr, "Extract error: No outdir argument provided") return } // TODO: Verbose option verbose := true outdir := c.Args().G...
package models import ( "github.com/jinzhu/gorm" "time" "github.com/EthereumCommonwealth/go-callisto/common" ) type Block struct { gorm.Model Hash common.Hash `gorm:"unique_index:hash_block"` ParentHash common.Hash Miner common.Address TransactionRoot common.Hash Difficulty uin...
/* * Wire API * * Moov Wire implements an HTTP API for creating, parsing, and validating Fedwire messages. * * API version: v1 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package openapi // InputMessageAccountabilityData struct for InputMessageAccountabilityData type InputMessageAccou...
package e7_4 import ( "io" ) type stringReader struct { pos int str string } func NewReader(str string) io.Reader { return &stringReader{str: str, pos: 0} } func (sr *stringReader) Read(p []byte) (n int, err error) { n = copy(p, sr.str[sr.pos:]) sr.pos += n if n == 0 && sr.pos == len(sr.str) { err = io.E...
package models import ( "fmt" "gorm.io/driver/postgres" "gorm.io/gorm" ) var DB *gorm.DB func ConnectDataBase() { dsn := "host=localhost user=babu password=babu DB.name=babu port=5432 sslmode=disable" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) fmt.Println("db",db) fmt.Println("err",err) ...
package online import ( "bufio" "errors" "os" "github.com/Kurorororo/vector" ) //Model express online classifier type Model interface { Predict(*vector.Vector) (float64, error) Score(*vector.Vector) (float64, error) Update(*Data) error Fit(Dataset, int) error FitFromDisk(string, int) error Copy() (Model, e...
package main import ( "fmt" "log" "net/http" "strings" ) func sayHelloWorld(w http.ResponseWriter, r *http.Request) { // ParseForm解析URL中的查询字符串,并将解析结果更新到r.Form字段 r.ParseForm() // 解析参数 fmt.Println(r.Form) // 在服务端打印请求参数 //fmt.Println("URL:", r.URL.Path) // 请求 URL //fmt.Println("Scheme", r.URL.Scheme) f...
// Package main ... package main import ( "fmt" "os" ) func main() { fmt.Println("./chrome: error while loading shared libraries: libcairo.so.2: cannot open shared object file: No such file or directory") os.Exit(1) }
// Copyright (C) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
// Package chroma takes source code and other structured text and converts it into syntax highlighted HTML, ANSI- // coloured text, etc. // // Chroma is based heavily on Pygments, and includes translators for Pygments lexers and styles. // // For more information, go here: https://github.com/alecthomas/chroma package c...
package ditto import ( "encoding/json" "errors" "fmt" ) type Section struct { ID string `json:"id"` Type Type `json:"type"` Title string `json:"title"` Description *string `json:"description"` ChildSection []Section ...
package proto // go:generate make generate import ( "bytes" "encoding/gob" "encoding/json" "fmt" "runtime/debug" "time" "github.com/reconquest/karma-go" "github.com/MagalixCorp/magalix-agent/v2/watcher" "github.com/MagalixTechnologies/uuid-go" "github.com/golang/snappy" "github.com/kovetskiy/lorg" "k8s....
package main import "fmt" func main() { months := map[string]struct{}{ "January": struct{}{}, "February": struct{}{}, "March": struct{}{}, "April": struct{}{}, "May": struct{}{}, "June": struct{}{}, } if _, ok := months["March"]; ok { fmt.Println("Found!") } }
package sdk import ( "net/http" "log" "io/ioutil" ) type AuthorizeParam struct { ClientId string `json:"client_id"` RedirectUri string `json:"redirect_uri"` State string `json:"state,omitempty"` EnforceLogin string `json:"enforce_...
// Copyright 2014 Matthias Zenger. 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 appl...
package global import ( "context" "github.com/go-redis/redis/v8" ) type Set struct { client *redis.Client } func NewSet(client *redis.Client) *Set { return &Set{ client: client, } } func (s *Set) SAdd(ctx context.Context, key, val interface{}) (bool, error) { ret, err := s.client.SAdd(ctx, makeSetKey(key),...
package TapeEquilibrium import "testing" func TestTapeEquilibrium(t *testing.T) { entries := []struct { input []int result int }{ {[]int{3, 1, 2, 4, 3}, 1}, {[]int{1, 1}, 0}, {[]int{-3, 5, -2, 1, 0, -10}, 3}, } for _, entry := range entries { result := TapeEquilibrium(entry.input) // check if r...
package configfile import ( "log" "time" "github.com/fsnotify/fsnotify" ) var logFatal = log.Fatal // AttachWatcher adds a listener of chenge event to a filepath func AttachWatcher(filename string, runner func()) { watcher, err := fsnotify.NewWatcher() if err != nil { logFatal(err) } go func() { defer w...
package main import ( "fmt" "math" ) func main() { max, mult, n := 0, 10, 1 for i := 1; i < 9999999; i++ { if mult/i == 0 { mult *= 10 n++ } if isNPandigital(i, n) && isPrime(i) { max = i } } fmt.Println("max:", max) } func isNPandigital(i, n int) bool { valMap := make(map[int]bool) digits :...
package people import ( "database/sql" "encoding/json" "fmt" "github.com/gorilla/mux" "net/http" ) type Person struct { Id int `json:"Id"` FirstName string `json:"firstName"` LastName string `json:"lastName"` } type People []Person func ReturnAllPeople(w http.ResponseWriter, r *http.Request){ people := Peo...
package main import ( "bufio" "bytes" "errors" "fmt" "net" "strings" "time" "github.com/overflow3d/ts3_/database" ) const master = "master" //Bot , is a bot struct type Bot struct { ID string conn net.Conn output chan string err chan string notify chan string stop chan int stop...
package app import ( "errors" "sync" "github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar/internal/config" "github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar/internal/repository" "github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar/service" ) var ErrUnrecognizedServiceType = errors.New("cannot ...
package client type ErrorResponse struct { Error int Message string } type Country struct { Id string `json:"country_id"` Name string `json:"country_name"` } type League struct { CountryId string `json:"country_id"` CountryName string `json:"country_name"` Id string `json:"league_id"` Name ...
package zengarden import ( "strings" "text/template" "time" ) var funcMap = template.FuncMap{ "downcase": strings.ToLower, "upcase": strings.ToUpper, "date": date, "dateToString": dateToString, "filter": filter, "slice": slice, "trim": trim, } func date(format string,...
package pgo import ( "reflect" ) // InArray checks if a value exists in an array func InArray(needle interface{}, haystack interface{}) bool { return search(needle, haystack) } func search(needle interface{}, haystack interface{}) bool { switch reflect.TypeOf(haystack).Kind() { case reflect.Slice: s := reflect...
package server import ( "bufio" "errors" "fmt" "log" "net" "os" "strings" "github.com/eshyong/lettuce/db" "github.com/eshyong/lettuce/utils" ) type Server struct { // Server can either have a backup or a primary, but not both. master net.Conn store *db.Store // TODO: allow any arbitrary number of peers...
package main import ( "log" "net" "net/http" "net/rpc" "pub/service" ) func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) var rpcServer = new(service.RPC) err := rpc.Register(rpcServer) if err != nil { log.Fatal("Format of service rpc isn't correct. ", err) } rpc.HandleHTTP() listener, err := ne...
package requests import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "strings" "github.com/google/go-querystring/query" "github.com/atomicjolt/canvasapi" "github.com/atomicjolt/canvasapi/models" "github.com/atomicjolt/string_utils" ) // ListMembersOfCollaboration A paginated list of the collab...
package main import ( "fmt" "bytes" cmpio "github.com/unkcpz/gocmp/io" "github.com/unkcpz/gocmp/crystal" ) func GetCell(poscar string) (*crystal.Cell, error) { poscarCell, err := cmpio.ParsePoscar(poscar) if err != nil { return nil, err } lattice := poscarCell.Lattice positions := poscarCell.P...
package solutions type NumMatrix struct { sum [][]int } func Constructor(matrix [][]int) NumMatrix { if len(matrix) == 0 || len(matrix[0]) == 0 { return NumMatrix{} } rows, columns := len(matrix), len(matrix[0]) sum := make([][]int, rows + 1) for i := 0; i < len(sum); i++ { s...
package logic import ( "encoding/json" "jkt/gateway/global" "jkt/gateway/hotel" "jkt/gateway/websocket" "jkt/jktgo/log" "jkt/jktgo/message" "jkt/jktgo/redis" ) // FuncPong 处理ping响应的函数 func FuncPong(session *websocket.Session, args map[string]interface{}) { // 这里其实什么都不用做 log.Debug("pong 回调") } // FuncLogin 为...
package main import "fmt" import structPack "github.com/dcmrlee/first-git-proj/go-lang/funny/structPack" func main() { var s string = "abcdef" var b []byte b = []byte(s) fmt.Printf("%v\n", b) s1 := s[2:] fmt.Printf("%v\n", s1) fmt.Printf("%d\n", len(s1)) fmt.Printf("%v\n", s[1:4]) fmt.Printf("%v\n", s[1:2]) ...
package BLC type PHBInv struct { PHBAddrFrom string //自己的地址 PHBType string //类型 block tx PHBItems [][]byte //hash二维数组 }
/** * All Rights Reserved * This software is proprietary information of Akurey * Use is subject to license terms. * Filename: empty.model.go * * Author: rnavarro@akurey.com * Description: Declare the available properties * of an Empty struct */ package models import "github.com/nvellon/hal" type EmptyStruct struct {...
package main import ( "context" "log" "net" "net/http" "sync/atomic" "services/counter" "google.golang.org/grpc" ) type counterServer struct { count uint32 } func (s *counterServer) UpdateCount(context.Context, *counter.Empty) (*counter.Response, error) { var newCount = atomic.AddUint32(&s.count, 1) ret...
// Copyright (c) Mainflux // SPDX-License-Identifier: Apache-2.0 package coap import ( "github.com/gogo/protobuf/proto" "github.com/mainflux/mainflux/pkg/messaging" broker "github.com/nats-io/nats.go" ) // Observer represents an internal observer used to handle CoAP observe messages. type Observer interface { Ca...
package main import ( "os" "../ch0/encapsulated" "../ch0/public" ) func main() { t1 := public.Trace{F: os.Stdout} t1.On() t1.Print("X1") t1.Off() t1.Print("Y1") t2 := encapsulated.TraceCustom(os.Stderr) t2.On() t2.Print("X2") t2.Off() t2.Print("Y2") var t3 encapsulated.Trace t3 = encapsulated.TraceD...
package clnkserver import ( "encoding/json" "net/http" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/imflop/clnk/internal/app/serviceprovider" ) // server ... type server struct { router *mux.Router sp serviceprovider.IServiceProvider } // NewServer ... func NewServer(serviceprovider...
package dto import ( "fmt" "encoding/json" "strings" ) type VariableResponse struct { value string valueType string valueFormat string } func (response VariableResponse) GetValue() string { return response.value } func (response *VariableResponse) UnmarshalJSON(data []byte) error { var responseRaw s...
package database // This file contains wrappers for SQL queries import ( "crypto/sha256" "database/sql" "fmt" "math" "time" "capnproto.org/go/capnp/v3" "capnproto.org/go/capnp/v3/exc" "capnproto.org/go/capnp/v3/packed" "zenhack.net/go/tempest/capnp/grain" "zenhack.net/go/tempest/capnp/identity" spk "zenha...
//go:build !windows package watcher import ( "bufio" "os" "testing" "time" "github.com/stretchr/testify/assert" ) type mockNotifier struct { eventPath string } func (n *mockNotifier) WatcherItemDidChange(path string) { n.eventPath = path } func (n *mockNotifier) WatcherDidError(err error) { } func TestFil...
package gw import ( "context" "fmt" "github.com/oceanho/gw/conf" "github.com/oceanho/gw/libs/gwjsoner" "time" ) type DefaultSessionStateManagerImpl struct { store IStore storeName string storePrefix string expirationDuration time.Duration redisTimeout time.Duration cnf ...
// Package pager 分页工具 // 目前可使用具体实现 // var driver pager.Driver // driver = NewMongoDriver() // driver = NewGormDriver() // driver = NewMgoDriver() // // pager.New(ctx, driver).SetIndex(c.entity.TableName()).Find(c.entity).Result() package pager import ( "github.com/gin-gonic/gin" "reflect" "strconv" "strings"...
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
//go:build integration // +build integration package integration import ( "io/ioutil" "os" "strings" "syscall" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const cleanupTxt = "cleanup.txt" func TestLocalResource(t *testing.T) { f := newFixture(t, "local_res...
// Copyright 2020 The Tekton Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
package confluence import ( "testing" ) func TestContentRequestPayload(t *testing.T){ spaceId := "test" version := 1 title := "Hello!" html := "<p>Hello, World</p>" req := ContentRequestPayload(spaceId, version, title, html) if 2 != req.Version.Number { t.Errorf("Expected to increment the version n...
package xuperos import ( "fmt" "log" "os" "testing" // import要使用的内核核心组件驱动 _ "github.com/xuperchain/xupercore/bcs/consensus/pow" _ "github.com/xuperchain/xupercore/bcs/consensus/single" _ "github.com/xuperchain/xupercore/bcs/consensus/tdpos" _ "github.com/xuperchain/xupercore/bcs/consensus/xpoa" _ "github.co...
// challenge :: https://www.hackerrank.com/challenges/staircase package staircase import ( "fmt" "strings" ) func main() { var a int fmt.Scanf("%v\n", &a) for i := 0; i < a; i++ { hashes := i + 1 spaces := a - hashes fmt.Println(strings.Repeat(" ", spaces) + strings.Repeat("#", hashes)) } }
package retry import ( "errors" "fmt" "os" "testing" "time" "github.com/go-toolkit/slog" "github.com/go-toolkit/utils" "github.com/stretchr/testify/require" "go.uber.org/zap" ) var logger *zap.Logger func TestMain(m *testing.M) { cfg := slog.Conf{}.DefaultConf() logger = slog.NewLogger(&cfg, `test`) os...
package Sliding_Window_Maximum import "container/list" type Node struct { Index int Value int } func maxSlidingWindow2(nums []int, k int) []int { if len(nums) == 0 || k < 1 || k > len(nums) { return nil } l := list.New() result := make([]int, len(nums)) for i := range nums { if l.Front() != nil && i-k >...
package runtime import ( "fmt" "github.com/bdlm/log" xmpp "github.com/mattn/go-xmpp" ) func Start(client *xmpp.Client) { for { m, err := client.Recv() if err != nil { continue } switch v := m.(type) { case xmpp.Chat: if v.Type == "chat" { log.Debugf("from %s: %s", v.Remote, v.Text) } if...
package main import ( "fmt" "testing" "time" ) func main() { result := testing.Benchmark(func(b *testing.B) { b.ResetTimer() for i := 0 ; i <= b.N ; i++{ time.Sleep(1 * time.Millisecond) } }) fmt.Printf("%s", result) }
package starkit import ( "go.starlark.net/starlark" ) // LoadInterceptor allows an Plugin to intercept a load to set the contents based on the requested path. type LoadInterceptor interface { // LocalPath returns the path that the Tiltfile code should be read from. // Must be stable, because it's used as a cache k...
package to import "time" func CurrentTimezone(tz string, t time.Time) time.Time { loc, err := time.LoadLocation(tz) if err != nil { return t } return t.In(loc) }
package main import ( "io/ioutil" "fmt" "github.com/json-iterator/go" ) func tt1() { data, _ := ioutil.ReadFile("/root/github/go/src/newJson/test.json") fmt.Println(jsoniter.Get(data, "apiVersion").ToString()) fmt.Println(jsoniter.Get(data, "items", 0, "apiVersion").ToString()) fmt.Println(jsoniter.Get(data, "...
package prov import ( "fmt" "io" "strconv" ) type Run struct { RunID int64 RunName string } func NewRun(runId int64, runName string) Run { if runName == "" { runName = "run" + strconv.FormatInt(runId, 10) } return Run{runId, runName} } func WriteRunFacts(writer io.Writer, run Run) { printRowHeader(writ...
package controller import ( "encoding/json" "fmt" "net/http" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "github.com/sambragge/webserver/models" ) //CreateUser : func CreateUser(w http.ResponseWriter, r *http.Request, mango *mgo.Session) { var user models.User decoder := json.NewDecoder(r.Body) err := de...
package main import ( "encoding/csv" "os" "fmt" //"strconv" //"github.com/kr/pretty" ) func readFile(filePath string, delim rune) (records [][]string, err error) { file, err := os.Open(filePath) if err != nil { return } defer file.Close() r := csv.NewReader(file) r.Comma = delim r.Comment = '#' reco...
package entity //Product Товар type Product struct { Meta *Meta `json:"meta,omitempty"` // Метаданные Товара Id string `json:"id,omitempty"` // ID Товара (Только для чтения) AccountId string `json:"accountId,omitempty...
package cloudformation // AWSDynamoDBTable_SSESpecification AWS CloudFormation Resource (AWS::DynamoDB::Table.SSESpecification) // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-ssespecification.html type AWSDynamoDBTable_SSESpecification struct { // SSEEnabled AWS C...
package telepathy import ( "context" "sync" "testing" "time" "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/mongo" "github.com/stretchr/testify/assert" ) const ( testDBURL = "mongodb://mongo:27017/test" testDBName = "testDBName" ) type dbTester struct { handler *databaseHa...
package numbers import ( "math/rand" "fmt" "time" ) func FindQuestion() (int, int) { numberOfQuestionsByChapters := [17]int{9,8,6,12,8,10,12,14,8,11,6,11,8,7,7,26,26} sum := 0 for _, numberOfQuestions := range numberOfQuestionsByChapters { sum += numberOfQuestions } rand.Seed(time.Now().UnixNano()) ...
// 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
//Test cases for word list attack with different type of hashes package main import "github.com/karlek/gohash/attack" import "testing" func TestMD5(t *testing.T) { m := map[string]string{ "d41d8cd98f00b204e9800998ecf8427e": "", //Empty string "" "d41d8cd98f00b204e9800998ecf8427": "", //Invali...
package main import ( "context" "fmt" "io" "log" "time" "github.com/dfreilich/grpc-samples/greet/greetpb" "github.com/pkg/errors" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/status" ) const address = "localhost" const port = "50051"...
package anton import ( "bytes" "encoding/json" "fmt" "net/http" "strconv" ) func SendTelegram(msg, antonUserTelegram, antonBotTelegramTokenID string) { // Declare the helper struct to access the helper functions var helper Helper // This is the URI: postURL := "https://api.telegram.org/bot{tokenID}/sendMes...