text
stringlengths
11
4.05M
package v3 import "github.com/cockroachdb/cockroach/pkg/util/treeprinter" func init() { registerOperator(projectOp, "project", projectClass{}) } func newProjectExpr(input *expr) *expr { return &expr{ op: projectOp, children: []*expr{input, nil /* projection */}, } } type projectClass struct{} var _ op...
// 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 main import ( "lib" "net/http" "strconv" ) var config lib.Config func init() { config = lib.InitConfig() } func main() { h := lib.Handler{ Conf: config, } http.ListenAndServe(config.Host+":"+strconv.Itoa(config.Port), h) }
package command import ( "fmt" "os" "path" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" ) var rootCmd = &cobra.Command{ Use: "torchprint", Short: "torchprint is a printjob manager for campus printing at NYU", Run: func(cmd *cobra.Command, args []string) { c...
package main import ( "fmt" "net" ) func main() { listener, err := net.Listen("tcp", ":8080") if err != nil { fmt.Println(err) return } defer listener.Close() fmt.Println("Server is listening...") for { conn, err := listener.Accept() if err != nil { fmt.Println(err) conn.Close() continue ...
package main import ( "fmt" "os" "time" proto "example/rpc/example" "example/internal/config" "example/internal/routers" "example/internal/service/hello" "github.com/gin-gonic/gin" "github.com/gmsec/goplugins/plugin" "github.com/gmsec/micro" "github.com/xxjwxc/public/mydoc/myswagger" "github.com/xxjwxc/...
package _019_remove_nth_node_from_end_of_list type ListNode struct { Val int Next *ListNode } func removeNthFromEnd(head *ListNode, n int) *ListNode { node:=&ListNode{0,head} prev,pn:=node,node for i:=1;i<=n+1;i++{ pn=pn.Next } for pn!=nil { prev=prev.Next pn=pn.N...
package domain import ( "github.com/plancks-cloud/plancks-cloud/model" ) const ServiceCollectionName = model.ServiceCollectionName type Service model.Service const RouteCollectionName = model.RouteCollectionName type Route model.Route
package main import "fmt" func main() { //var x float64 = 42 // Change this to see the result var result string if x := 42; x < 0 { result = "Less than zero" } else if x==0{ result = "Equal to zero" } else { result = "Greater than zero" } fmt.Println("Result:", result) }
package model import "gopkg.in/mgo.v2/bson" const ( // 保存集合名称 CollectionArticle = "article" ) type Article struct { Id bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"` // mongodb id Title string `json:"title" form:"title" binding:"required" bson:"title"` // 标题 Body string ...
package config import ( "github.com/spf13/viper" "time" ) /* Creation Time: 2019 - Oct - 06 Created by: (ehsan) Maintainers: 1. Ehsan N. Moosa (E2) Auditor: Ehsan N. Moosa (E2) Copyright Ronak Software Group 2018 */ func Set(key string, value interface{}) { viper.Set(key, value) } func Get...
package management //AppConfig is a type alias of the generated isApplication_AppConfig config //to make it public type AppConfig = isApplication_AppConfig
// Copyright 2019 - 2022 The Samply Community // // 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 ...
package validators import ( "math" "sync" "testing" ) func TestGetFuncMap(t *testing.T) { fm := GetFuncMap() if fm != CustomFuncMap { t.Fail() } } func Test_customFuncMap_Set_Get(t *testing.T) { type args struct { tag string validator Validator } tests := []struct { name string c *customF...
package cfs import ( "bazil.org/fuse" "bufio" "bytes" "errors" "fmt" "github.com/tigcode/containerfs/logger" dp "github.com/tigcode/containerfs/proto/dp" mp "github.com/tigcode/containerfs/proto/mp" //"github.com/tigcode/containerfs/utils" "golang.org/x/net/context" "google.golang.org/grpc" "io" //"io/iou...
package util import ( "fmt" mpaTypes "multidim-pod-autoscaler/pkg/apis/autoscaling/v1" containerUtil "multidim-pod-autoscaler/pkg/util/container" "multidim-pod-autoscaler/pkg/util/limitrange" recommendationUtil "multidim-pod-autoscaler/pkg/util/recommendation" corev1 "k8s.io/api/core/v1" "k8s.io/klog" ) // Re...
// Copyright (C) 2015 Miquel Sabaté Solà <mikisabate@gmail.com> // This file is licensed under the MIT license. // See the LICENSE file. package main import ( "bytes" "fmt" "io/ioutil" "os" "testing" "time" "github.com/stretchr/testify/assert" ) func checkDirExists(t *testing.T, dir, name, base string) { i,...
package configuration import "github.com/ftarlao/goblocksync/utils" // Hardcoded constants const MajorVersion = 0 const Version = 1 const PatchVersion = 0 // Number of hashes inside one HashGroupMessage const HashGroupMessageSize = 200 //Bytes for buffered hashes (64M) const HashMaxBytes = 64 * utils.MB //Bytes fo...
// Copyright 2019 Authors of Cilium // // 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 ...
// Copyright 2021 Red Hat, Inc. and/or its affiliates // // 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 applic...
package ebs import ( "github.com/openebs/mtest/driver" "github.com/openebs/mtest/util" ) const ( // Name of this executor // This executor will be known as this to the outside world EBS_SNAP_REMOVE_EXEC = "ebs.snapshot.remove.executor" ) // This is a EBS driver executor. type SnapshotRemover struct { d *EBSDri...
package plist // RawPlistValue is a raw encoded Plist object. It implements Marshaler and // Unmarshaler and can be used to delay Plist decoding or precompute a Plist // encoding using DecodeElement or EncodeElement respectively. type RawPlistValue plistValue func (r *RawPlistValue) UnmarshalPlist(p *Decoder, start *...
package variable_length // 可変長引数(interface{}のとき) // 正常系 type IVariableInterface interface { Invoke(a int, opt ...interface{}) string } type VariableInterface struct { } func (VariableInterface) Invoke(a int, opt ...interface{}) string { return "" } // 異常系 type NIVariableInterface interface { // want "not impleme...
package concepts import ( "errors" "io/ioutil" "net/http" "net/http/httptest" "net/url" "testing" fthealth "github.com/Financial-Times/go-fthealth/v1_1" uuid "github.com/google/uuid" "github.com/husobee/vestigo" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/t...
// Copyright 2016 Andreas Pannewitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package d import ( "github.com/GoLangsam/dk-7.2.2.1/internal/x" // all we need ) // ======================================================================...
package main import ( "fmt" "math" "os" "time" "github.com/c-14/grue/config" "github.com/mmcdole/gofeed" "gopkg.in/gomail.v2" ) type FeedFetcher struct { mailer gomail.Sender init bool sem chan int finished chan int } type RSSFeed struct { config config.AccountConfig LastFetched int64 ...
// Copyright (C) 2023 Storj Labs, Inc. // See LICENSE for copying information. package noise import ( "context" "crypto/rand" "crypto/subtle" "crypto/x509" "encoding/binary" "io" "time" "github.com/flynn/noise" "github.com/spacemonkeygo/monkit/v3" "github.com/zeebo/blake3" "github.com/zeebo/errs" "storj...
// Copyright (c) 2020 - for information on the respective copyright owner // see the NOTICE file and/or the repository at // https://github.com/hyperledger-labs/perun-node // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may...
// project euler (projecteuler.net) problem 17 // solution by Kevin Retzke (retzkek@gmail.com) // December 2012 package main import ( "fmt" "os" ) var ( digits = []string{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifte...
package goroutinePool type signal struct {} type f func() error type Pool struct { capacity int32 running int32 freeSignal chan signal }
// 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...
// Copyright 2020 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 controller import ( "encoding/json" "fmt" "time" "github.com/Brickchain/go-crypto.v2" "github.com/Brickchain/go-document.v2" jose "gopkg.in/square/go-jose.v1" ) // VerifyMandateToken is used to verify that a mandate-token is correctly signed func VerifyMandateToken(token string, mandateSigner *jose.Jso...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "os" ) type Objects struct { Objects []object `json:"Objects"` } type object struct { Topic string `json:"topic"` Inner inner `json:"inner"` } type inner struct { Inside1 int `json:"inside1"` Inside2 int `json:"inside2"` Inside3 int `json:"in...
package sleep import ( "testing" "time" ) func Test(t *testing.T) { const sec = 2 start := time.Now() Sleep(sec) stop := time.Since(start).Seconds() if stop < sec || stop > sec*1.05 { t.Error("Incorrect sleep function") } }
package main import ( "testing" ) func TestEncrypt(t *testing.T) { key := GetRandomName() encrypted, salt, iv := Encrypt([]byte("hello, world"), key) decrypted, err := Decrypt(encrypted, key, salt, iv) if err != nil { t.Error(err) } if string(decrypted) != "hello, world" { t.Error("problem decrypting") } ...
// SPDX-License-Identifier: ISC // Copyright (c) 2014-2020 Bitmark Inc. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package litecoin import ( "bytes" "crypto/sha256" "github.com/bitmark-inc/bitmarkd/fault" "github.com/bitmark-inc/bitmarkd/util" ) // Version...
package longest_repeating_character_replacement func characterReplacement(s string, k int) int { // find all [start,end] that tolerate k operations to make all characters the same // // Create two pointers: start and end. // // The `end` pointer starts at 0, try to find the right most position // // if end - st...
package math func Sum(intSliceParam []int)int { total:=0 for _,x := range intSliceParam{ total += x } return total }
package Lecture02 import ( "math/rand" "time" ) //Quick Sort Algothrims func QuickSort(inputs []int)([]int){ inputs = Shuffle(inputs) hi:=len(inputs)-1 sortforquick(0,hi,inputs) return inputs } func sortforquick(lo,hi int,inputs []int){ if hi<=lo{ return } j := partition(lo,hi,inputs) sortforquick(lo,j-1...
package verifier import ( "RSAverify2/myprime" "math/rand" ) type Verifier struct { P int Q int N int Nn int Orla int PublicKey int PrivateKey int A int B int C int Stext int Dtext int } func Gen_rand() int { return rand.In...
// 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...
// Copyright 2023 The gVisor 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 main // TODO Spit the source code to several directories (cmd, util, common, api, etc.) and files import ( // TODO Using github.com/spf13/{pflag,cobra,viper} for better parameter handling "flag" // TODO Using github.com/golang/glog for better logging "encoding/json" "fmt" "log" "math" "net/http" "n...
package main import ( "fmt" "runtime" "strconv" "sync" ) var wg sync.WaitGroup func main() { jobs := 10 //控制线程数量 pool := 3 jobChans := make(chan int, pool) for i := 0; i < pool; i++ { go func() { for ch := range jobChans { fmt.Println("hello" + strconv.Itoa(ch)) wg.Done() } }() } for i :...
package ulist import ( "net" "net/http" "os" "strings" "github.com/pirsquare/country-mapper" ) var infoClient *country_mapper.CountryInfoClient func init() { const ( ipport = "127.0.0.1:25688" loc = "vendor/github.com/pirsquare/country-mapper/files" ) l, err := net.Listen("tcp", ipport) if err != ni...
package goods import ( "flea-market/model/dialogModel" "flea-market/model/goodsModel" "fmt" "github.com/gin-gonic/gin" "net/http" "strconv" ) // 定义接收数据的结构体 type ListParams struct { CatId int `form:"cat_id" json:"cat_id" uri:"cat_id" xml:"cat_id"` UserId int `form:"shop_id" json:"shop_id" uri:"shop_id" xml:"sh...
package k8swatch import ( "context" "fmt" "net/url" "testing" "time" "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/stretchr/testify/assert" "k8s.io/apimachinery/pkg/types" "github.com/tilt-dev/tilt/internal/controllers/apis/cluster...
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package meta import ( "context" "github.com/google/go-cmp/cmp" "chromiumos/tast/rpc" "chromiumos/tast/services/cros/meta" "chromiumos/tast/testing" "chromiumos/tast/...
package parser import ( "errors" "strings" ) // ParseList parses and returns the full contents of a string. func (p *Parser) ParseList() (result []string, err error) { token := p.scnr.Peak() if !token.IsList() { return result, errors.New("called ParseList without the beginning token being a list start") } to...
package tiltfile import ( "context" dockertypes "github.com/docker/docker/api/types" "github.com/tilt-dev/tilt/internal/analytics" ) // reportDockerConnectionEvent records a metric about Docker connectivity. func (r *Reconciler) reportDockerConnectionEvent(ctx context.Context, success bool, serverVersion dockert...
package parsefb import ( "github.com/PuerkitoBio/goquery" "strings" ) type FBPostData struct { PostUrl string TimeStamp string ProfileLink *ProfileLink ImageUrl string Content string Summary string Title string Author string Tags string } func ParsePost(s, posturl string...
package problem0055 func canJump(nums []int) bool { if len(nums) == 1 { return true } reachable := make([]bool, len(nums)) end := len(nums) - 1 for i := len(nums) - 2; i >= 0; i-- { dist := end - i if nums[i]-dist >= 0 { reachable[i] = true end = i } } return reachable[0] }
package main import ( "bytes" "fmt" "github.com/madebymany/gowasd" "log" "strconv" "strings" ) type formatter interface { printResolvedInstances([]gowasd.InstanceResolution) printResolvedInstance(gowasd.InstanceResolution) canOutputList() bool } type terminalFormatter struct { output *log.Logger } type po...
package syslog import ( "log" "os" "os/signal" "regexp" "syscall" "time" "github.com/hpcloud/tail" ) const timeFormat = "Jan 2 15:04:05" var reply = regexp.MustCompile("^(.+) [a-z]+ dnsmasq.+: reply ([^ ]+) is ([^ ]+)") var query = regexp.MustCompile("^(.+) [a-z]+ dnsmasq.+: query.A. ([^ ]+) from ([^ ]+)") v...
package vmodel import ( "database/sql" "errors" "strings" "gopkg.in/mgo.v2" ) var ( // ErrCode is a config or an internal error ErrCode = errors.New("Case statement in code is not correct.") // ErrNoResult is a not results error ErrNoResult = errors.New("Result not found.") // ErrUnavailable is a database n...
package scanner import ( "github.com/bingo-lang/bingo/token" "io" ) type Scanner struct { source io.RuneReader char rune eof bool } func New(source io.RuneReader) *Scanner { scanner := &Scanner{source: source} scanner.advance() return scanner } func (s *Scanner) ScanToken() token.Token { s.removeSpace() ...
package cfg import ( "os" "strings" ) type Config struct { Host string Port string DBName string VerificationsCollection string ConfigBaseURL string ConsumeBaseURL string MongoAddr string } func New() *Config { // default values ...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package youtubemusic contains local Tast tests that exercise ytmusic. package youtubemusic import ( "context" "time" "chromiumos/tast/common/android/ui" "chromiumos/...
package historyentries import ( "bufio" "strconv" "strings" logrus "github.com/Sirupsen/logrus" "github.com/9seconds/ah/app/environments" "github.com/9seconds/ah/app/utils" ) var ( bashTimestampRegexp = utils.CreateRegexp(`^#\s*\d+$`) zshLineRegexp = utils.CreateRegexp(`^: (\d+):\d;(.*?)$`) fishCmdRegexp...
package storage import ( "math" "runtime" "sync" ) type Word struct { Word string Count int64 } var stringsChannel chan []string //var wordsStorage map[string]int64 var wordsStorage []*Word var mux sync.RWMutex func StartDispatching() { //wordsStorage = make(map[string]int64) stringsChannel = make(chan []s...
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/lib/pq" ) const ( host = "localhost" // email = "findme@scottlaing.ca" port = 5432 user = "postgres" dbname = "postgres" password = "password" ) type User struct { gorm.Model Name string Email string `gorm:"not null;unique...
package repository //go:generate go run github.com/golang/mock/mockgen -source=$GOFILE -destination=mock/${GOFILE} -package=mock import ( "context" "github.com/traPtitech/trap-collection-server/src/domain/values" ) type GameManagementRole interface { AddGameManagementRoles(ctx context.Context, gameID values.Game...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package cups provides methods to coordinate with CUPS for printer handling. package cups import ( "context" "chromiumos/tast/errors" "chromiumos/tast/local/printing/p...
package handler import ( "encoding/json" "github.com/gin-gonic/gin" "github.com/zhj0811/fabric-normal/apiserver/common" "github.com/zhj0811/fabric-normal/apiserver/sdk" "github.com/zhj0811/fabric-normal/common/logging" ) var logger = logging.NewLogger("debug", "handler") type Data struct{ Key string `json:"k...
package handlers import ( "encoding/json" "net/http" "strconv" database "../database" . "../helpers" . "../models" "github.com/gorilla/mux" ) func AllTodo(w http.ResponseWriter, r *http.Request) { respond, err := json.Marshal(database.All()) CheckErr(err) w.Header().Set("Content-Type", "application/json...
package integration import ( "net/http" "encoding/json" "fmt" "time" "strings" "strconv" "io" "io/ioutil" "errors" "openreplay/backend/pkg/messages" ) // Old name: asayerSessionId // QUERY: what can be modified? const RB_QUERY = "SELECT item.id, item.title,body.message.openReplaySessionToken,item.leve...
package viper import ( "github.com/spf13/viper" "reflect" "strings" ) // CreateEnvViper create a new instance of Viper that support Environment variables binding to Struct. // Example: // os.Setenv("NAME", "TestViper") // os.Setenv("APPLICATION_ID", "TestApp") // os.Setenv("NESTED_ASTRING", "nested string") // typ...
package downstream_adaptor import ( "github.com/robotic-framework/robotic-client/internal/constants/enums" "github.com/robotic-framework/robotic-client/internal/global" "github.com/sirupsen/logrus" "gobot.io/x/gobot" "time" ) var typeInitializer map[enums.DownstreamAdaptorType]initializer func init() { typeIni...
package snorlax import "errors" var ( ErrSubNoMessageType = errors.New("no message type") ErrSubUnknownMessageType = errors.New("unknown message type") ErrSubUnmarshaling = errors.New("failed to unmarshal message") )
package main import ( "os" "testing" "time" "github.com/cloudfoundry/jibber_jabber" "github.com/stretchr/testify/assert" ) func (result *BaseModel) zeroBaseModelDatesAndID() { result.ID = 0 result.CreatedAt = time.Unix(int64(0), int64(0)) result.UpdatedAt = time.Unix(int64(0), int64(0...
/* Copyright 2019 The Skaffold 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, sof...
package management import "github.com/emicklei/go-restful" func SetToken(request *restful.Request, token string) { request.SetAttribute("token", token) } func GetToken(request *restful.Request) string { token := request.Attribute("token") if token == nil { return "" } return token.(string) }
package write type Widget struct { Description string `json:"description"` Owner string `json:"owner"` Value int `json:"value"` }
// Copyright (c) 2018-present, MultiVAC Foundation. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. package wire import ( "bytes" "errors" "fmt" "github.com/prometheus/common/log" "io" "github.com/multivactech/MultiVAC/base/rlp" "gi...
package globals import ( "errors" "github.com/kr/pretty" "googlemaps.github.io/maps" ) var mapsClient *maps.Client //InitMapClient : intializes the MapsClient func InitMapClient(apiKey string) error { mapsCandidate, err := maps.NewClient(maps.WithAPIKey(apiKey)) if err != nil { pretty.Printf("fatal error: %...
package user import ( "fmt" "net/mail" "github.com/jrapoport/gothic/api/grpc/rpc/admin" "github.com/jrapoport/gothic/cmd/cli/root" "github.com/jrapoport/gothic/core/context" "github.com/spf13/cobra" ) var hard bool var deleteCmd = &cobra.Command{ Use: "delete [ID or EMAIL]", RunE: deleteUserRunE, Args: co...
/* Copyright 2020 The Skaffold 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, sof...
/* * Created on Sat Dec 15 2018 19:37:44 * Author: WuLC * EMail: liangchaowu5@gmail.com */ // two pointers func isAlienSorted(words []string, order string) bool { order_num := make(map[byte]int) for i, v := range order { order_num[byte(v)] = i } for i := 0; i < len(words)-1; i++ { p1, p2 := 0, 0 for p1 ...
package models import ( "database/sql" "fmt" "log" "os" _ "github.com/mattn/go-sqlite3" // Register SQLite3 driver "github.com/mitchellh/go-homedir" ) // List represents a to-do list type List struct { id int active bool name string } // Todo represents a to-do item that belongs to a list type Todo s...
package client import ( "fmt" "hash/adler32" "io/ioutil" "log" "net" "os" "sort" "time" errors "github.com/mohamedmahmoud97/Zuper-UDP/errors" socket "github.com/mohamedmahmoud97/Zuper-UDP/socket" "github.com/vmihailenco/msgpack" ) var ( //AckFileCheck is channel on receiving ack on file request AckFileC...
package models import ( "errors" "fmt" "time" "github.com/beego/beego/v2/client/orm" "github.com/mobilemindtec/go-utils/beego/db" ) type UserRole struct { Id int64 `form:"-" json:",string,omitempty"` CreatedAt time.Time `orm:"auto_now_add;type(datetime)" json:"-"` UpdatedAt time.Time `orm:"auto_no...
package hash import "math" func isPrime(n int) bool { nsqrt := math.Sqrt(float64(n)) for i := 2; float64(i) <= nsqrt; i++ { if n%i == 0 { return false } } return true } func firstNPrimes(n int) []int { primes := make([]int, n) for i, x := 0, 2; i < n; x++ { if isPrime(x) { primes[i] = x i++ }...
package models import ( "crypto/md5" "fmt" "io" ) // encrypt password func EncryptPasswd(name, pass, salt string) string { salt1 := "%$@w" h := md5.New() io.WriteString(h, salt1) io.WriteString(h, name) io.WriteString(h, salt) io.WriteString(h, pass) return fmt.Sprintf("%x", h.Sum(nil)) } func VerifyPasswd...
package main import ( "database/sql" "encoding/json" "fmt" "goutils" "log" "reflect" "time" _ "github.com/go-sql-driver/mysql" ) var ( db *sql.DB ) type AllDataType struct { ID int64 `gorm:"column:id;primary_key" json:"id"` Varchar string `gorm:"column:varchar" json:"varchar"` Tinyint ...
package gmb import "strings" const ( colon = ":" slash = "/" left = "{" right = "}" breaks = left + right ) var contractions = map[string]string{ "@uuid@": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", "@num@": "[0-9]+", "@alpha@": "[a-zA-Z]+", "@alphanum@": "[a-zA-Z0-9]+"...
package main //Valid //The inner scope of for can access the init variables that aslo can be shawdoed inside func f () { for a:= 0; a < 10; a ++ { print(a) } }
package server import ( "bufio" "os" "path/filepath" "strings" "log" ) // ReadSchemaFromPath reads a schema from path func ReadGraphQLSchemaFromPath(path string) string { var s strings.Builder files := []string{} err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error { if strings.Cont...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package policy import ( "context" "time" "chromiumos/tast/common/hwsec" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/tast/remote/rollback" "chromiu...
package pkggraph import ( "sort" "golang.org/x/tools/go/packages" ) func allImportsCache(pkgs map[string]*packages.Package) map[string][]string { cache := map[string][]string{} var fetch func(p *packages.Package) []string fetch = func(p *packages.Package) []string { if n, ok := cache[p.ID]; ok { return n ...
package almanack import ( "context" "encoding/json" "fmt" "html" "log" "regexp" "strconv" "strings" "github.com/spotlightpa/almanack/internal/stringutils" ) func (arcStory *ArcStory) ToArticle(ctx context.Context, svc Service, article *SpotlightPAArticle) (err error) { var body strings.Builder if article....
// Copyright (C) 2023 Storj Labs, Inc. // See LICENSE for copying information. package nodetag import ( "bytes" "context" "github.com/gogo/protobuf/proto" "github.com/zeebo/errs" "storj.io/common/pb" "storj.io/common/signing" ) var ( // SignatureErr means that the signature wash wrong. SignatureErr = errs....
// Copyright 2014 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 sham import ( "fmt" log "github.com/sirupsen/logrus" "testing" "time" ) func TestNoSchedulerNoop(t *testing.T) { shamOS := NewOS() shamOS.Boot() } func TestFCFSScheduler(t *testing.T) { shamOS := NewOS() shamOS.Scheduler = FCFSScheduler{} shamOS.ReadyProcs = []*Process{&Noop, &Noop} log.WithField(...
// SPDX-License-Identifier: MIT package ast import ( "reflect" "unicode" "github.com/caixw/apidoc/v7/core" "github.com/caixw/apidoc/v7/internal/node" ) var searcherType = reflect.TypeOf((*core.Searcher)(nil)).Elem() // Search 搜索符合条件的对象并返回 // // 从 doc 中查找符合符合 pos 定位的最小对象,且该对象必须实现了 t 类型。 // 如果不存在则返回 nil。t 必须是一个接...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package glbench manipulates the test flow of running glbench test binaries. package glbench import ( "context" "fmt" "io/ioutil" "os" "path/filepath" "regexp" "sor...
package fast import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestClient_GetUploadSpeed(t *testing.T) { c := NewClient() _, err := c.GetUploadSpeed() assert.ErrorIs(t, err, ErrMethodNotProvided) } // Not so good test because of external network dependencie...
package main import ( "io" "os" "github.com/yuyamada/atcoder/lib" ) func main() { solve(os.Stdin, os.Stdout) } func solve(stdin io.Reader, stdout io.Writer) { io := lib.NewIo(stdin, stdout) defer io.Flush() n := io.NextInt() a := io.NextInts(n) ans := solver(a) io.Println(ans) } func solver(a []int) (ans...
package storage import ( "fmt" "testing" "gin-msgboard/config" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type Msgboard struct { Id uint `gorm:"primary_key"` Name string Msg string Mtime string } const ( MSGBOARD_TAB = "msgboard" ) func TestInitDB(t *testing.T) { config...
package cmd import ( "testing" "os" "github.com/spf13/viper" ) func TestExecute(t *testing.T) { t.Run("Flag defaults", func(t *testing.T) { RootCmd.Execute() if cfgFile != "" { t.Errorf("expected config file to be blank by default; got %s", cfgFile) } if outputDir != "" { t.Errorf...