text stringlengths 11 4.05M |
|---|
package main
import (
"fmt"
"net/http"
"time"
)
const numJobs = 3
func main(){
var urls = []string{
"http://ozon.ru",
"https://ozon.ru",
"http://google.com",
"http://somesite.com",
"http://non-existent.domain.tld",
"https://ya.ru",
"http://ya.ru",
"http://ёёёё",
}
result:=make(chan string, len(... |
package user
import (
"encoding/json"
"log"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/jmoiron/sqlx"
)
// Update - update
func Update(db *sqlx.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c := r.Header.Get("Authorization")
if c == "" {
w.WriteHeader(h... |
// https://blog.golang.org/error-handling-and-go
//
// In Go it's idiomatic to communicate errors via an explicit, separate
// return value. This makes it easy to see which functions return
// errors and to handle them using the same language constructs
// employed for any other, non-error tasks.
//
// A co... |
package main
import (
"fmt"
)
/*
Задача 2. Три числа
Напишите программу, которая запрашивает у пользователя три числа и сообщает, есть ли среди них число, большее, чем 5.
*/
func main() {
var total, examScore int
cntNumber := 3
contolNumber := 5
arr := make([]int, cntNumber)
fmt.Println("Программа Три числа"... |
package cache
import (
"container/list"
"errors"
"sync"
)
// a cache can hold special num ID:Data pairs for quick use, like map, but will drop oldest ID:Data when full
// each R/W operation will set the ID:Data to newest
// ID is a type which can be used in map index, Data is interface{}
type CacheProvider struct ... |
package db
import "github.com/boltdb/bolt"
import "strconv"
func openDB() *bolt.DB {
db, err := bolt.Open("tasks.db", 0777, nil)
if err != nil {
panic(err)
}
return db
}
// Init bold for storage
func Init() {
db := openDB()
defer db.Close()
err := db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBu... |
package user
import (
"fmt"
"gopkg.in/mgo.v2/bson"
)
//
type User struct {
ID bson.ObjectId `bson:"_id,omitempty" json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password,omitempty" bson:"-"`
HashedPassword []byt... |
// Package gb11643 GB 11643-1999 公民身份号码 / Citizen identification number
package gb11643
|
package main
import "sort"
//1894. 找到需要补充粉笔的学生编号
//一个班级里有n个学生,编号为 0到 n - 1。每个学生会依次回答问题,编号为 0的学生先回答,然后是编号为 1的学生,以此类推,直到编号为 n - 1的学生,然后老师会重复这个过程,重新从编号为 0的学生开始回答问题。
//
//给你一个长度为 n且下标从 0开始的整数数组chalk和一个整数k。一开始粉笔盒里总共有k支粉笔。当编号为i的学生回答问题时,他会消耗 chalk[i]支粉笔。如果剩余粉笔数量 严格小于chalk[i],那么学生 i需要 补充粉笔。
//
//请你返回需要 补充粉笔的学生 编号。
//
//
//
/... |
package priority_queue
import (
"container/heap"
"errors"
)
// Package pq implements a priority queue data structure on top of container/heap.
// As an addition to regular operations, it allows an update of an items priority,
// allowing the queue to be used in graph search algorithms like Dijkstra's algorithm.
// ... |
package main
import (
"fmt"
"time"
)
type User struct {
username string
}
func (this *User) Close() {
fmt.Println(this.username, "Closed!!!")
}
func main() {
user := &User{"liuruichao"}
defer user.Close()
user2 := &User{"liuruichao2"}
defer user2.Close()
time.Sleep(10 * time.Second)
fmt.Println("done")
... |
package solutions
func searchInsert(nums []int, target int) int {
if target < nums[0] {
return 0
}
for index, value := range nums {
if target <= value {
return index
}
}
return len(nums)
} |
package gosqs
import (
"fmt"
"reflect"
"testing"
"github.com/aws/aws-sdk-go/service/sns"
"github.com/aws/aws-sdk-go/service/sqs"
)
type sample struct {
Val string `json:"val"`
}
func (s *sample) ModelName() string {
return "sample"
}
func TestNewPublisher(t *testing.T) {
t.Run("with_arn", func(t *testing.T... |
package quark
import (
"fmt"
"net/http"
)
func defaultRecovery(hc *Context) {
if hc.Written() {
return
}
switch err := hc.Error().(type) {
case int:
hc.WriteText(err, fmt.Sprintf("ERROR %d", err))
case error:
hc.WriteText(http.StatusInternalServerError, err.Error())
case string:
hc.WriteText(http.Stat... |
package user_active_record
import (
"context"
"github.com/rs/xid"
"hero/database/ent"
tableUserActiveRecord "hero/database/ent/useractiverecord"
"hero/pkg/db/mysql"
"hero/pkg/logger"
"time"
)
type SelectScoreCounts struct {
ScoreCounts []struct {
UserID string `json:"user_id"`
}
}
func Create(ctx context.... |
package utils
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
type TlsStruct struct {
TlsVerify bool
TlsCaCert string
TlsCert string
TlsKey string
}
func NewTlsStruct(params map[string]interface{}) (*TlsStruct, error) {
tlsverify := false
if tlsv, ok := params["tlsverify"... |
package day5
import (
"bufio"
"fmt"
"os"
)
func main() {
result := GetMaxSeatID()
fmt.Println("Highest seat ID is :", result)
missingID := FindMissingSeatID()
fmt.Println("Your seat ID is :", missingID)
}
func parseInput(fileName string) []string {
file, err := os.Open(fileName)
handleError(err)
var s... |
package routers
import (
"HeartBolg/controllers"
"HeartBolg/models"
"HeartBolg/models/utils"
"encoding/json"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/orm"
"io"
"log"
"os"
"strconv"
"time"
)
func init() {
// /admin and /index is static resource path
b... |
package odoo
import (
"fmt"
)
// BaseLanguageImport represents base.language.import model.
type BaseLanguageImport struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
Code *String `xmlrpc:"code,omptempty"`
CreateDate *Time `xmlrpc:"create_date,omptempty"`
CreateUid *Many2One `xmlrpc... |
package middlewares
import (
"fmt"
"net/http"
"time"
"github.com/fatih/color"
"github.com/juliotorresmoreno/unravel-server/helper"
)
func Cors(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
helper.Cors(w, r)
w.Write... |
package ffmpeg
import "C"
type Rational struct {
Num,
Den int
}
func (rational Rational) ctype() C.struct_AVRational {
return C.struct_AVRational{C.int(rational.Num), C.int(rational.Den)}
}
|
package interfaces
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"pocket-organize-app/entity"
)
func Get_access_token(w http.ResponseWriter, r *http.Request) {
access_token_param := new(entity.AccessTokenParam)
access_token_param.ConsumerKey = os.Getenv(("POCKET_COSUMER_K... |
package main
import (
"fmt"
"log"
"net/http"
"github.com/JieeiroSst/LapTRWeb/controllers/admin"
"github.com/gorilla/mux"
)
func main() {
route := mux.NewRouter()
files := http.FileServer(http.Dir("./public"))
route.Handle("/", files)
route.HandleFunc("/admin", admin.HomeAdmin)
route.HandleFunc("/admin/a... |
package config
var TCPport = ":54809"
var UDPport = ":54810"
|
package main
import "fmt"
import "os"
import "bufio"
import "strings"
type Name struct {
fname string;
lname string;
}
func main() {
fmt.Printf("Please enter the name file: ")
name_slice := make([]Name, 0, 0)
var file_path string
_, err := fmt.Scan(&file_path)
file, err := os.Open(file_path)
if err != nil {
... |
package main
import (
"path/filepath"
"os"
"fmt"
"strings"
)
func getCurrentDirectory() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
panic(err)
}
return strings.Replace(dir, "\\", "/", -1)
}
func main() {
fmt.Println(getCurrentDirectory())
}
|
package backend
import (
"fmt"
"os"
"github.com/lidouf/gst"
)
const (
srcName = "src"
decoderName = "decoder"
converterName = "converter"
sinkName = "sink"
)
// Pipeline Pipeline
type Pipeline struct {
*gst.Pipeline
src *gst.Element
decoder *gst.Element
converter *gst.Element
sink ... |
package main
import "fmt"
var a = "包级别的变量a" //包范围
var b, c string = "包级别的变量b", "包级别变量c" //包范围
var d string
func main() {
d = "函数级别变量d" //以上声明;此处分配;包范围
var e = 42 //函数作用域-后续变量具有函数作用域:
f := 42
g := "函数变量g"
h, i := "函数变量h", "函数变量i"
j, k, l, m := 1, true, 22.2, 'm' //single quotes 单引号
n :=... |
package main
import (
"bufio"
"fmt"
"os"
"runtime/pprof"
"sort"
)
var stdin *bufio.Reader
var stdout *bufio.Writer
func init() {
stdin = bufio.NewReader(os.Stdin)
stdout = bufio.NewWriter(os.Stdout)
}
func scan(args ...interface{}) (int, error) {
return fmt.Fscan(stdin, args...)
}
func printf(format string... |
// Copyright (C) 2018 Satoshi Konno. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package echonet
const (
NodeManufacturerUnknown = ObjectManufacturerUnknown
)
// Node is an interface for Echonet node.
type Node interface {
// GetObjec... |
// 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 arc
import (
"context"
"strings"
"time"
"chromiumos/tast/local/arc"
"chromiumos/tast/local/bundles/cros/arc/storage"
"chromiumos/tast/local/chrome/mtp"
"chro... |
package utils
import (
"fmt"
"io"
"net/http"
"os"
log "github.com/sirupsen/logrus"
)
// Static URL for retrieving the bootloader
const iPXEURL = "https://boot.ipxe.org/undionly.kpxe"
// This header is used by all configurations
const iPXEHeader = `#!ipxe
dhcp
echo .
echo .
echo .
echo .
echo +-----------------... |
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package iio
import (
"context"
"encoding/binary"
"os"
"path"
"reflect"
"sync"
"testing"
"time"
"golang.org/x/sys/unix"
)
func TestNewBuffer(t *testing.T) {
defer... |
package controller
import (
"net/http"
"github.com/Oxynger/JournalApp/httputils"
"github.com/Oxynger/JournalApp/model"
"github.com/gin-gonic/gin"
)
// GetItemSchemes Получить все схемы объектов
// @Summary Список схем объектов
// @Description Метод, который получает все списки объектов
// @Tags ItemScheme
// @Ac... |
package kafka
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/Shopify/sarama"
"github.com/project-flogo/core/data/metadata"
"github.com/project-flogo/core/support/log"
"github.com/project-flogo/core/trigger"
)
var triggerMd = trigger.NewMetadata(&Settings{}, &HandlerSettings{}, &Output{})
f... |
// 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 profiler
import (
"context"
"os"
"path/filepath"
"strings"
"time"
"chromiumos/tast/errors"
"chromiumos/tast/testing"
)
func init() {
testing.AddFixture(&te... |
package kafka2
func NewClient() {
}
|
package commonservice
import (
"errors"
"fmt"
//"github.com/astaxie/beego"
"github.com/astaxie/beego/validation"
"net/http"
"tripod/convert"
"webserver/common"
"webserver/controllers"
"webserver/models/maccount"
)
type PublishListController struct {
controllers.BaseController
orderType int
count int
... |
package satokencerts
import (
"github.com/openshift/cluster-kube-apiserver-operator/pkg/operator/operatorclient"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"github.com/openshift/library-go/pkg/operator/configobserver"
"github.... |
package main
import (
"flag"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
)
var addr string
func main() {
flag.StringVar(&addr, "addr", ":9090", "The address to listen on for HTTP requests.")
flag.Parse()
const endpointEnv = "ECS_CONTAINER_METADATA_URI_V4"
endpoint := os.Getenv(endpointEnv)
if end... |
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* 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 applicab... |
package binfiles
import (
"bytes"
"net/source/proto/repe"
"errors"
"fmt"
"net/source/proto/pools"
"sync"
bytes2 "net/source/utils/bytes"
"net/source/userapi"
)
type ProtoBinPack struct {
Ver int32
len int32 //设想发送长度
Rlen int32 //实际获得长度
Bytes []byte
refPoolBytes []byte //B... |
package main
import (
"fmt"
"net/http"
"strings"
"time"
_ "net/http/pprof"
"github.com/uber/makisu/lib/log"
)
func main44() {
go func() {
ch := make(chan string, 0)
go func() {
fmt.Println("pp")
time.Sleep(2 * time.Second)
ch <- "wwwww"
// close(ch)
}()
go func() {
for e := range c... |
// Copyright 2015 The etcd 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 t... |
package stormpathweb
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"net/http"
"github.com/jarias/stormpath-sdk-go"
)
type loginHandler struct {
preLoginHandler UserHandler
postLoginHandler UserHandler
application *stormpath.Application
}
func (h loginHandler) serveHTTP(w http.ResponseWriter,... |
package dbschedules
// A ConflictGraph is a transaction conflict graph.
// An entry in a ConflictGraph stores, for a given node n,
// all of the nodes with edges pointing to n.
type ConflictGraph map[string]map[string]bool
// BuildConflictGraph builds a conflict graph for a
// schedule.
func BuildConflictGraph(s Sche... |
package lib
import (
"bufio"
"os"
"strings"
)
type Word struct {
Value string
Part string
}
func streamWords(path string, max int, stream chan Word) {
file, err := os.Open(path)
if err != nil {
panic("Couldn't open " + path)
}
reader := bufio.NewReader(file)
scanner := bufio.NewScanner(reader)
scanne... |
package lbclient
import (
"encoding/json"
"fmt"
)
type updatePart interface {
fmt.Stringer
GetMap() map[string]interface{}
}
// Represents a {$set:{field:rvalue}} operation
type SetOperation struct {
field string
value RValue
}
func (s SetOperation) GetMap() map[string]interface{} {
return map[string]interfa... |
package main
type Entry struct {
Id uint
Status string
Value string
Votes []*Vote
}
type Vote struct {
EntryID uint
UserID uint
User *User
Weight int
}
type User struct {
Id uint
Votes []*Vote
Name string
} |
package main
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
)
var (
ErrUnrecognizedToken = errors.New("Lex: unrecognized token")
ErrIncompleteExpression = errors.New("Parse: incomplete expression")
ErrOvercompleteExpression = errors.New("Parse: overcomplete expression")
)
func Lex(src string) ([... |
package cmd
import (
"os"
"strings"
"github.com/pkg/errors"
)
func exportedEnvVar(envVar string) (string, string, error) {
export := strings.SplitN(envVar, "=", 2)
if len(export) != 2 {
return "", "", errors.Errorf("environment variable %q cannot be splitted", envVar)
}
return export[0], export[1], nil
}
f... |
package tokens
type TokenType int
type Token struct {
Typ TokenType
Value string
}
const (
NONE TokenType = iota
NUMBER
NAME
SYMBOL
STRING
DOT
EOF
COMMENT
LPAREN
RPAREN
LBRACKET
RBRACKET
LBRACER
RBRACER
)
func New(typ TokenType, value string) Token {
return Token{typ, value}
}
var typeNames = []... |
package events
import (
"github.com/bwmarrin/discordgo"
)
func (config *Events) ChannelUpdate(session *discordgo.Session, event *discordgo.ChannelUpdate) {
log := config.Log.WithField("GuildID", event.GuildID)
widget, ok := config.Widgets[event.GuildID]
if !ok {
log.Errorln("Could not find widget for guild")
... |
// SPDX-License-Identifier: MIT OR Unlicense
package main
import (
"bytes"
str "github.com/boyter/go-string"
"sort"
"unicode"
)
const (
SnipSideMax int = 10 // Defines the maximum bytes either side of the match we are willing to return
// The below are used for adding boosts to match conditions of snippets to ... |
package dashboard
import (
"fmt"
"github.com/keptn-contrib/dynatrace-service/internal/adapter"
"github.com/keptn-contrib/dynatrace-service/internal/common"
"github.com/keptn-contrib/dynatrace-service/internal/dynatrace"
"github.com/keptn-contrib/dynatrace-service/internal/sli/metrics"
keptnv2 "github.com/keptn/g... |
package models
import (
"github.com/jinzhu/gorm"
"time"
)
type Poll struct {
gorm.Model
Title string `json:"title"`
Start time.Time `json:"start"`
End time.Time `json:"end"`
UserID int `json:"user_id"`
}
|
package response_factory
type defaultResponse struct {
data interface{}
}
func (r defaultResponse) IsServerError() bool {
return false
}
func (r defaultResponse) IsClientError() bool {
return false
}
func (r defaultResponse) GetStatus() string {
return statusOk
}
func (r defaultResponse) HasData() bool {
retu... |
package main
import (
"fmt"
"strconv"
"sync"
)
// 如果用 共享内存 或 队列(因协程竞争 产生 所用 互斥锁 衍生问题),造成性能问题
// channel 先入先出 (水管) 但是 设定缓冲长度 就不能改,一旦关闭 就不能再放入,但还可以取走
var wg sync.WaitGroup
var ar01 []int //声明一个 切片(引用类型 必须 初始化 才能用)
var ch01 chan int //声明变量类型 channel 是 引用类型,必须初始化才能用
var ch02 chan *string
func main() {
// chan... |
/*
Copyright 2019 Baidu, 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 in writing, software
dis... |
package golang_blockchain
import sha "crypto/sha256"
func bytes(block *Block, difficulty byte, nonce Nonce) []byte {
parentsum := Hash{}
if block.Parent != nil {
parentsum = block.Parent.Sum
}
difficultylen := 1
parentsumlen := len(parentsum)
noncelen := len(nonce)
datalen := len((block.Data))
bytes := make... |
package FindCoordinator
type Response struct {
ThrottleTimeMs int32
ErrorCode int16
ErrorMessage string
NodeId int32
Host string
Port int32
}
|
package main
import "fmt"
func main() {
s := "abcaaaa"
fmt.Println(firstUniqChar(s))
}
func firstUniqChar(s string) int {
lens := len(s)
if lens <= 0 {
return -1
}
m := make(map[uint8]int, lens)
for i := range s {
m[s[i]]++
}
for i := range s {
if m[s[i]] == 1 {
return i
}
}
return -1
}
|
// reference and dereferece operator
// check pointer type
// declare a pointer
package main
import "fmt"
func main() {
ans := 42
fmt.Println(&ans) // location in the memory
// dereference operator
add := &ans
fmt.Println(*add)
// pointer type
fmt.Printf("address is a %T\n", add)
// declare a pointer
cana... |
// 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 2016-present Datadog, Inc.
package usm
import (
"testing"
apicommon "github.com/DataDog/datadog-... |
package dao
import (
"github.com/luxingwen/secret-game/model"
)
func (d *Dao) AddWxUser(user *model.WxUser) (err error) {
err = d.DB.Table(TableWxUser).Create(user).Error
return
}
func (d *Dao) GetByOpenId(openId string) (wxUser *model.WxUser, err error) {
wxUser = new(model.WxUser)
err = d.DB.Table(TableWxUser... |
package main
import (
"log"
"os"
"path/filepath"
"sync"
)
func traverseDir(roots []string) []os.FileInfo {
var wg sync.WaitGroup
var fileInfoCh = make(chan os.FileInfo)
var filesInfo = make([]os.FileInfo, 0, filesAmount)
for _, root := range roots {
wg.Add(1)
go walkDir(root, &wg, fileInfoCh)
}
go fun... |
package temple
import (
"errors"
"html/template"
"os"
"sync"
)
var (
ErrNotADirectory = errors.New("Not a directory")
)
// Type Temple allows you to read a directory of templates and either cache them (in production mode) or discard them
// to be re-read (in development mode).
type Temple struct {
Dir string... |
package helm
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/loft-sh/devspace/pkg/devspace/config/versions"
"github.com/loft-sh/devspace/pkg/devspace/config/loader/variable/legacy"
runtimevar "github.com/loft-sh/devspace/pkg/devspace/config/loader/variable/runtime"
"github.com/loft-sh/devspace/pkg/devsp... |
package main
import (
"fmt"
)
func main() {
a1 := [5]int{1, 2, 3, 4, 5}
sum := 0
//求数组总和
for _, v := range a1 {
sum += v
}
fmt.Println("sum=", sum)
//打印出数组总2个元素之和=6的下标
for key1, _ := range a1 {
for key2, _ := range a1 {
if a1[key1]+a1[key2] == 6 && key1 < key2 {
fmt.Printf("key1=%v,key2=%v\n",... |
package app
import (
"encoding/json"
"errors"
"html/template"
"io/ioutil"
"math"
"net/http"
"time"
"github.com/gorilla/mux"
"muun-paradise/model"
)
// App holds the HTTP server as well as the trained model.
type App struct {
server http.Server
model model.Modeler
}
// New generates a new web app with a... |
package main
import (
"io"
"os"
"net"
"fmt"
"os/exec"
"strings"
"net/http"
"strconv"
"github.com/robfig/cron"
"sync"
"flag"
)
var (
Name = "rabbitmq_exporter"
listenAddress = flag.String("unix-sock", "/dev/shm/rabbitmq_exporter.sock", "Address to listen on for unix sock access and telemetry.")... |
package sort
type BubbleSort struct {
}
func (s BubbleSort) Sort(data []interface{}, comparable Comparable) {
dataLen := len(data)
if dataLen < 2 {
return
}
for j := dataLen - 1; j >= 0; j-- {
flag := false
for i := 0; i < j; i++ {
if comparable.Compare(data[i], data[i+1]) > 0 {
data[i], data[i+1] = ... |
package com
//在文章或产品的下面有文章和产品标签
//不同文章产品显示它自己的标签,
//点击标签跳转到列表页面,文章或产品列表
import (
"JsGo/JsHttp"
"JsGo/JsLogger"
"fmt"
)
func Find() {
JsHttp.Http("/tagquerylinkap", TagQueryLinkAP) //通过标签查询文章或产品
}
//由前端查询调用网络接口
//by tag query article product标签查询对应的文章或产品链接返回内容或列表
func TagQueryLinkAP(s *JsHttp.Session) {
type Pa... |
// Package pangram implements a solution for the exercise titled `Pangram'.
package pangram
// IsPangram determines a given sentence is a pangram.
func IsPangram(sentence string) bool {
seen, count := [26]bool{}, 0
for _, letter := range sentence {
switch {
case 'a' <= letter && letter <= 'z':
if !seen[letter... |
package domain
import (
"errors"
"time"
"github.com/rpagliuca/serverless-book-reading-tracker/pkg/entity"
"github.com/rpagliuca/serverless-book-reading-tracker/pkg/persistence"
)
func ListOneEntry(username, UUID string) (entity.Entry, error) {
entry, err := persistence.ListOneEntry(username, UUID)
return entry... |
package spanner
import (
"cloud.google.com/go/spanner"
"context"
"errors"
"fmt"
"os"
"time"
)
const healthCheckIntervalMins = 50
const numChannels = 4
func NewClient(ctx context.Context, projectID, instance, db string) (*spanner.Client, error) {
dbPath := fmt.Sprintf("projects/%s/instances/%s/databases/%s", p... |
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5/middleware"
"github.com/sirupsen/logrus"
)
// structuredLogger holds our application's instance of our logger
type structuredLogger struct {
logger *logrus.Logger
}
// newLogEntry wi... |
package main
import (
"io"
"os"
"time"
"strings"
"testing"
"io/ioutil"
"path/filepath"
)
type TestFile struct {
Name, Contents, Date string
}
var testFiles = []*TestFile{
{".ssync-test", ".ssync-test\ndir1\ndir1/dir2\ndir1/dir2/file3\n", ""},
{"file1", "file1Contents", "2018-01-01"},
{"dir1/fil... |
// Copyright 2015 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 datasource
type WritableDataSource interface {
DataSource
Store(key string, value interface{}) error
}
|
package math
import "fmt"
func Add(a int64, b int64) {
fmt.Println(a + b)
}
func Sub(a int64, b int64) {
fmt.Println(a - b)
}
|
package tests
import (
"testing"
"reflect"
. "github.com/go-dash/slice/tests/types"
"github.com/go-dash/slice/_string"
"github.com/go-dash/slice/_int"
"github.com/go-dash/slice/_Person" // github.com/go-dash/slice/tests/types
"strings"
)
var tableFilterString = []struct {
input []string
output []string
}{
... |
// Copyright 2016 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 (
"os"
gobzip "github.com/shaban/kengal/gobzip"
"time"
)
type Articles []*Article
type Rubrics []*Rubric
type Blogs []*Blog
type Themes []*Theme
type Resources []*Resource
type Globals []*Global
func (ser Articles)Len()int{
return len(ser)
}
func (ser Articles)Less(i, j int) bool{
it,_ := ti... |
package main
import (
"context"
"os"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
func SetDownloadTask(path string) chromedp.Tasks {
return chromedp.Tasks{
page.SetAdBlockingEnabled(true),
page.SetDownloadBehavior(page.SetDownloadBehaviorBehaviorAllow).WithDownloadPath(path),
}
}
fu... |
package bannerController
import (
"github.com/gin-gonic/gin"
"hd-mall-ed/packages/admin/models/staticModel"
"hd-mall-ed/packages/common/pkg/adminApp"
"hd-mall-ed/packages/common/pkg/e"
)
// 获取所有 banner
func GetBannerList(c *gin.Context) {
api := adminApp.ApiInit(c)
model := &staticModel.Static{}
query := map[s... |
package flapjack
import "testing"
func TestDialFails(t *testing.T) {
address := "localhost:55555" // non-existent Redis server
database := 0
_, err := Dial(address, database)
if err == nil {
t.Error("Dial should fail")
}
}
// TODO(auxesis): add test for sending and receiving Events
|
package transparent
import "errors"
type layerSource struct {
Storage BackendStorage
}
// NewLayerSource returns LayerSource.
// LayerSource wraps BackendStorage.
// It Get/Set key-value to BackendStorage.
// This layer must be the bottom of Stack.
func NewLayerSource(storage BackendStorage) (Layer, error) {
if st... |
package graph
// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
import (
"context"
"github.com/vrppaul/training-app/graph/generated"
"github.com/vrppaul/training-app/graph/model"... |
package config
var(
KEY string = "cHNta15AJioxMTA1IygpSw=="
ServerKEY string = "K8Ff3KY4gSjGstf%"
SEPARATE_CHAR string = "_"
LF byte = 10
CR byte = 13
SecretLen = 17
VersionSplit string = "."
)
|
// Copyright 2019 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 (
"encoding/json"
"fmt"
"log"
Maps "api/maps"
Services "api/services"
)
const ratingFileGz = "./rating.gz"
const titlesFileGz = "./titles.gz"
const ratingUrl = "https://datasets.imdbws.com/title.ratings.tsv.gz"
const titlesUrl = "https://datasets.imdbws.com/title.basics.tsv.gz"
const ratin... |
package validator
import (
"encoding/json"
"fmt"
"html/template"
"io"
"os"
"strings"
"github.com/go-wyvern/leego"
)
var AppApis []Api
const codeTag = "```"
type Api struct {
Description string
Method string
Path string
Handler leego.HandlerFunc
SuccessStdOut interface{}
Success... |
/*
Copyright 2021 The KodeRover 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, s... |
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package utility
import (
"strings"
"github.com/mattermost/mattermost-cloud/internal/tools/aws"
"github.com/mattermost/mattermost-cloud/model"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus... |
package commands
import "strings"
func gitLineEnding(git env) string {
value, _ := git.Get("core.autocrlf")
switch strings.ToLower(value) {
case "input", "true", "t", "1":
return "\r\n"
default:
return osLineEnding()
}
}
type env interface {
Get(string) (string, bool)
}
|
package main
import (
"fmt"
"os"
)
func main() {
/*
panic("Some error happened")
fmt.Println("It will not get printed")
*/
// Permisssion denied error
res, err := os.Create("/etc/akilan.txt")
if err != nil {
panic(err)
} else {
fmt.Println(res)
}
}
|
package zxcrpc
import (
"context"
"net"
"google.golang.org/grpc"
log "github.com/sirupsen/logrus"
)
type SimpleZxcRPCServer struct{}
func (server *SimpleZxcRPCServer) DidStartJob(ctx context.Context, job *JobMessage) (*Server, error) {
log.Info("DidStartJob", job)
return &Server{
Name: "foo",
}, nil
}
fu... |
package main
import "fmt"
func main0301() {
var a int = 10
//fmt.Printf("%p\n", &a)
// 定义指针变量存储变量的地址
var p *int = &a
//fmt.Printf("%p\n", p)
//通过指针间接修改变量的值
//写操作
*p = 123
//fmt.Println(a)
//读操作
fmt.Println(*p)
}
func main0302() {
//声明指针变量 默认值为0x0 (nil)
//内存地址编号为0 0-255的空间为系统占用 不允许用户访问(读写)
//空指针
... |
/*
Package shuffler shuffles arrays of integers with anchoring.
Array entries can be free or anchored.
The former type is shuffled and the latter type is not.
An entry anchored by position retains the same position after shuffling.
An entry anchored relative its previous or next entry retains the same relative positio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.