text stringlengths 11 4.05M |
|---|
//go:build darwin
// +build darwin
package darwin
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Foundation -framework Cocoa -framework WebKit -framework AppKit
#import <Foundation/Foundation.h>
#include <AppKit/AppKit.h>
#include <stdlib.h>
#import "Application.h"
#import "WailsContext.h"
typedef struct S... |
package gui
import (
"fmt"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazynpm/pkg/commands"
"github.com/jesseduffield/lazynpm/pkg/gui/presentation"
)
// list panel functions
func (gui *Gui) getSelectedTarball() *commands.Tarball {
tarballs := gui.State.Tarballs
if len(tarballs) == 0 {
return... |
//
// 插入排序
// 空间复杂度: O(1)
// 时间复杂度: O(n^2)
// https://zh.wikipedia.org/wiki/%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F
//
// cloud@txthinking.com
//
package main
import (
"fmt"
)
var a []int = []int{8,3,4,2,8,5,10}
func main(){
fmt.Println(a)
var i,j int
for i=1;i<len(a);i++{
tmp := a[i]
f... |
package main
import (
"bytes"
"flag"
"fmt"
"strings"
res "github.com/antlr/antlr4/doc/resources"
"github.com/antlr/antlr4/runtime/Go/antlr"
gen "github.com/er1c-zh/sql-to-gorm/antlr4_gen"
)
var (
path string
_package string
)
func Init() {
flag.StringVar(&path, "file", "", "path to sql file")
flag.St... |
package cmd
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"github.com/brainicorn/skelp/skelputil"
)
func TestSkelpCmdError(t *testing.T) {
code := Execute([]string{"badcommand"}, nil)
if code == 0 {
t.Errorf("execute should have errored ")
}
}
func TestSkelpCmdUserError... |
package objectstorage
import (
"sync/atomic"
)
type StorableObjectFlags struct {
persist atomic.Bool
delete atomic.Bool
modified atomic.Bool
}
func (of *StorableObjectFlags) SetModified(modified ...bool) (wasSet bool) {
return of.modified.Swap(len(modified) == 0 || modified[0])
}
func (of *StorableObjectFla... |
package service
import (
"time"
"errors"
"github.com/gpmgo/gopm/modules/log"
)
type Manager struct {
Match_que chan interface{}
Clear_que chan interface{}
Sequence_que chan interface{}
Source_data_que chan interface{}
}
// global singleton instance
var manager *Manager
// 饿汉单例模式
func init() {
manager = &Man... |
package api
import (
"log"
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/tuyentv96/go-cloudfunction/handler"
)
var e *echo.Echo
func init() {
// Echo instance
e = echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
log.Println("initi... |
// Copyright (c) 2018 The MATRIX Authors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php
package reelection
import (
"github.com/MatrixAINetwork/go-matrix/common"
"github.com/MatrixAINetwork/go-matrix/core/matrixstate"
"github... |
// Package block implements efficient storage and transfer of arbitrary blocks of data.
package block
/*
TODO(refactor): package name `block` is easily confused with github.com/ipfs/go-block-format.
*/
import (
"context"
"io"
"go.uber.org/fx"
"github.com/ipfs/go-bitswap"
"github.com/ipfs/go-bitswap/network"
... |
package odoo
import (
"fmt"
)
// MailTestSimple represents mail.test.simple model.
type MailTestSimple struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
CreateDate *Time `xmlrpc:"create_date,omptempty"`
CreateUid *Many2One `xmlrpc:"create_uid,omptempty... |
package octo
/**
* Storing team logs and other team state.
*/
import (
"appengine"
"appengine/datastore"
// "log"
"time"
)
// Basic info about each team. There is one of these records per team.
type TeamRecord struct {
ID string
Created time.Time
LastSeen time.Time
EmailList []string
... |
package kata
import (
"fmt"
"strconv"
"strings"
)
// StockList kata: https://www.codewars.com/kata/help-the-bookseller/train/go
func StockList(listArt []string, listCat []string) string {
if len(listCat) == 0 || len(listArt) == 0 {
return ""
}
res := map[string]int{}
out := ""
for _, cat := range listCat {
... |
package main
import "fmt"
//数组
//存放元素的容器
//必须指定存放的元素的类型和容量
//数组的长度书数组类型的一部分
func main() {
var a1 [3]bool //长度为3的数组[true fales true]
var a2 [4]bool //[true true fales fales]
fmt.Printf("a1:%T a2:%T\n", a1, a2)
//数组的初始化
//如果不初始化:默认元素都是零值(布尔值的默认flase,整型和浮点型都是0,字符串:“控制”)
fmt.Println(a1, a2)
//1.初始化方式1
a1 = [3... |
package Variables
import (
"fmt"
"github.com/sodhigagan/MyPractice/I/Constants"
)
func Old() {
fmt.Print(", so that makes me ", 2017-Constants.Year, " years and ", 5-Constants.Month, " month(s) old")
}
|
package stl
type Solid struct {
Name string
Facets []Facet
}
type Facet struct {
Normal Vec3
Vertices [3]Vec3
}
type Vec3 struct {
X, Y, Z float64
}
|
package gopaxos
import (
"fmt"
"github.com/buptmiao/gopaxos/paxospb"
"io/ioutil"
"os"
"strings"
)
type checkpointReceiver struct {
conf *config
logStorage LogStorage
senderNodeID uint64
uuid uint64
sequence uint64
hasInitDirMap map[string]bool
}
func newCheckpointReceiver(conf *... |
package main
import (
"fmt"
"sort"
)
type Food struct {
Name string
Price int
}
type Foods []Food
func (t Foods) Len() int {
return len(t)
}
func (t Foods) Less(i, j int) bool {
return t[i].Price >= t[j].Price
}
func (t Foods) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
func main() {
var foods =... |
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"
)
// GetUsersMostRecentlyGradedSubmissions
// https://canvas.i... |
package main
import (
"code.google.com/p/gcfg"
"flag"
"github.com/op/go-logging"
"os/user"
"path/filepath"
)
// Command ling flags
var configFlag = flag.String("c", "", "Use alternative config file")
var verboseFlag = flag.Bool("v", false, "Show verbose debug information")
// Config
var Config struct {
Databas... |
package main
import "fmt"
func main() {
for i := 1; i <= 2; i++ {
for j := 1; j <= 5; j++ {
fmt.Println("On day ", i, " kiss Pidhu ", j, " times")
}
}
}
|
package routes
import (
"os"
"fmt"
"strings"
"net/http"
"path/filepath"
"github.com/go-chi/chi"
"github.com/robert-hansen/goapp/controller"
)
func NewRouter() *chi.Mux {
router := chi.NewRouter()
workDir, _ := os.Getwd()
filesDir := filepath.Join(workDir, "public")
FileServer(router, "/static", http.Dir(f... |
package groupingobjects
import (
"context"
"fmt"
)
type NSGroup struct {
client groupingObjectsAPI
ctx context.Context
id string
name string
}
func NewNSGroup(client groupingObjectsAPI, ctx context.Context, name, id string) NSGroup {
return NSGroup{
client: client,
ctx: ctx,
name: name,
... |
package main
import (
"fmt"
"time"
)
func main() {
number := make(chan int)
go func() {
number <- 42
}()
time.Sleep(time.Millisecond * 100)
select {
case n := <-number:
fmt.Println(n)
default:
fmt.Println("ничего, пусто, completle nothing")
}
}
|
// Copyright 2020 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
package remt_v02
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNestedTypes(t *testing.T) {
assert.NotNil(t, AddressType3Choice{}.Validate())
asser... |
// Copyright © 2016 Benjamin Martensson <benjamin.martensson@nrk.no>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to u... |
package utils
import "math/rand"
// generate a number between >=0 && > max
func Random(max int) int {
return int(rand.Float64() * float64(max))
}
|
package src
import "github.com/gomodule/redigo/redis"
type Config struct {
Source string
SourcePassword string
Target string
TargetPassword string
Output string
Count int
}
// 默认的Redis连接配置
func defaultRedisOpts(password string) []redis.DialOption {
var options []redis.DialOpti... |
package main
import (
"context"
"fmt"
"io"
"log"
"time"
"google.golang.org/grpc"
client "github.com/notsu/grpc-playground/01-basic/ping-service/proto"
)
var (
method = "lotsOfReplies"
)
func main() {
fmt.Println("Run ping-service")
ctx := context.Background()
conn, err := grpc.Dial("pong:9000", grpc.Wi... |
package controllers
import (
"github.com/astaxie/beego"
"smartapp/helper"
"strings"
)
type PluginController struct {
BaseController
}
func (c *PluginController) Show(tplName... string){
//c.TplName=tplName
file := helper.GetControllerStackFile(1)
file= (strings.SplitN(file,"/plugins/",2))[1]
file=(strings.Sp... |
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package utility
import (
"strings"
"github.com/mattermost/mattermost-cloud/model"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
type nodeProblemDetector struct {
kubeconfigPath string... |
package utils
import (
"bufio"
"os"
"strconv"
)
func ReadLines(filename string) []string {
file, err := os.Open(filename)
Check(err)
defer file.Close()
scanner := bufio.NewScanner(file)
var lines []string
for scanner.Scan() {
line := scanner.Text()
lines = append(lines, line)
}
Check(scanner.Err())
... |
package service
import (
"fmt"
"log"
"sync"
"time"
dto "../dto"
m "../model"
repo "../repository"
u "../utils"
)
//EmailService service
type EmailService struct{}
//Emails Repository against each email id
var Emails = repo.Emails
var isSendGridActive = true
var mu sync.Mutex
//SendEmail service
func (emai... |
package migrate
import (
"github.com/bendrucker/terraform-cloud-migrate/configwrite"
"github.com/hashicorp/hcl/v2"
)
func New(path string, config Config) (*Migration, hcl.Diagnostics) {
writer, diags := configwrite.New(path)
steps := configwrite.NewSteps(writer, configwrite.Steps{
&configwrite.RemoteBackend{Con... |
package gorm
import (
"github.com/porter-dev/porter/internal/models"
ints "github.com/porter-dev/porter/internal/models/integrations"
"gorm.io/gorm"
)
func AutoMigrate(db *gorm.DB) error {
return db.AutoMigrate(
&models.Project{},
&models.Role{},
&models.User{},
&models.Release{},
&models.Session{},
... |
// 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, ... |
// Copyright 2021 The Perses 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 ... |
package controllers
import (
"net/http"
"github.com/astaxie/beego"
"github.com/gorilla/websocket"
models "../models"
)
// https://github.com/gorilla/websocket
// http://learn.javascript.ru/websockets
type WSController struct {
beego.Controller
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
Write... |
package lc49
// 字母异位词分组
// https://leetcode-cn.com/problems/group-anagrams/
import "sort"
// GroupAnagrams .
// 每一个元素按照字符排序,看排序后的值是否再一个hashmap中存在
// 不存在,作为一个数组存入,存在则append到数组中
// 最后便利hashMap, 得到结果
// 时间复杂度O(K * nlog(n)), 空间复杂度O(n)
func GroupAnagrams(strs []string) [][]string {
stringMap := map[string][]string{}
re... |
package config
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type Config struct {
MysqlAdmin MysqlAdmin
CourseConfig CourseConfig
Qiniu Qiniu
CasbinConfig CasbinConfig
RedisAdmin RedisAdmin
System System
Mongodb Mongodb
Tomongodb... |
/*
* Copyright (c) 2020. Uriel Márquez All Rights Reserved
* https://umarquez.c0d3.mx
*/
package day3
import (
"strings"
)
type Vector [2]int
func (v Vector) Add(vec Vector) Vector {
return Vector{v[0] + vec[0], v[1] + vec[1]}
}
func CountTreesUntilTheBottom(pattern string, start Vector, steps Vector) int {
... |
package book
// Volume represents a book that consists of chapters
type Volume struct {
Chapters []Chapter `json:"chapters"`
Metadata Metadata `json:"metadata"`
}
|
package utils
import (
"fmt"
"regexp"
"strconv"
"strings"
)
func FromTextSize(size string) (int64, error) {
size = strings.Replace(strings.TrimSpace(strings.ToUpper(size)), " ", "", -1)
re := regexp.MustCompile("^([1-9][0-9]*)(B|KB|MB|GB)$")
strs := re.FindStringSubmatch(size)
typeMap := map[string]int64{
... |
package files
import (
"github.com/gin-gonic/gin"
"github.com/sunil-bansiwal/file_download_manager/model/downloads"
"net/http"
)
func GetDownloadedFiles(c *gin.Context) {
fileDB := downloads.FilesDB
for id, _ := range fileDB {
c.JSON(http.StatusOK, id)
}
}
|
package employee
import "fmt"
type Employee struct {
FirstName string
LastName string
Age int
Gender bool
}
func (e Employee) ToString() {
fmt.Printf("Employee: {firstName:%s, lastName:%s, age:%d, gender:%v}\n", e.FirstName, e.LastName, e.Age, e.Gender)
}
|
// 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 nearbyfixture
import (
"context"
"strconv"
"time"
nearbycommon "chromiumos/tast/common/cros/nearbyshare"
"chromiumos/tast/ctxutil"
"chromiumos/tast/errors"
"... |
package cafe
import "internetCafe/tourist"
// Computer struct defines a computer from the internet cafe
type Computer struct {
// User occupying the computer
User *tourist.Tourist
}
// IsFree tells if a computer is currently used by a tourist
func (c *Computer) IsFree() bool {
if c.User != nil {
return false
... |
package services
var presetStack = map[string][]serviceConstructor{
"blockchain": {
NewDiscoveryService,
NewHeartbeatService,
NewBlockChainService,
},
}
|
package lc
import "github.com/phea/leetcode-go/types"
// Time: O(n)
// Benchmark: 108ms 7.5mb | 90%
func walk(node *types.TreeNode, stack *[]int) {
if node == nil {
return
}
walk(node.Left, stack)
*stack = append(*stack, node.Val)
walk(node.Right, stack)
}
func getAllElements(root1 *types.TreeNode, root2 *t... |
package addsubcommands
import (
"fmt"
"os"
snmpsimclient "github.com/inexio/snmpsim-restapi-go-client"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// UserToEngineCmd represents the userToEngine command
var UserToEngineCmd = &cobra.Command{
Use: "user-to-engine",
Args: c... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type Rule [2]int
func (r *Rule) Validate(v int) bool {
return v >= r[0] && v <= r[1]
}
type Rules []Rule
func (r *Rules) Validate(v int) bool {
for _, ru := range *r {
if ru.Validate(v) {
return true
}
}
return false
}
type Ticket []in... |
package main
import "fmt"
var number = [] int {1, 2, 3, 4, 5, 6}
func main() {
// i := 0
// for i < 6 {
// fmt.Println(number[i])
// i++
// }
// for i := 0; i < 6; i++ {
// fmt.Println(number[i])
// }
for i,x := range number {
fmt.Println("第", i, "个数为", x)
}
} |
package main
import (
"flag"
"fmt"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/client"
_ "github.com/emersion/go-message/charset"
"github.com/emersion/go-message/mail"
"io"
"io/ioutil"
"log"
"os"
"regexp"
"strconv"
)
func init() {
log.SetFlags(log.Llongfile|log.LstdFlags)
}
var (
server,... |
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func Print(list *ListNode) {
for list != nil {
fmt.Print(list.Val)
list = list.Next
if list != nil {
fmt.Print("->")
}
}
fmt.Println()
}
func swapPairs(head *ListNode) *ListNode {
var h, now *ListNode
for head != nil {
i... |
package main
import "fmt"
type person struct {
first string
last string
age int
}
type secretAgent struct {
person // embedded type, promoted to the outer type; also known as anonymous field
license bool
}
func main() {
sa1 := secretAgent{
person: person{ // unqualified type name ACTS as the field name
... |
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/99designs/gqlgen/graphql/handler/lru"
"github.com/99designs/gqlgen/graphql/handler/transport"
"github.com/99designs/gqlgen/graph... |
package res
// Code inspired, and partly borrowed, from SubList in nats-server
// https://github.com/nats-io/nats-server/blob/master/server/sublist.go
// Common byte variables for wildcards and token separator.
const (
pmark = '$'
pwild = '*'
fwild = '>'
btsep = '.'
)
const invalidPattern = "res: invalid pattern... |
package encoding
import (
"bytes"
"context"
"github.com/grafana/tempo/tempodb/encoding/common"
)
type recordAppender struct {
records []common.Record
}
// NewRecordAppender returns an appender that stores records only.
func NewRecordAppender(records []common.Record) Appender {
return &recordAppender{
records... |
package cookie
// Copyright 2016-2017 MediaMath
//
// 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 l... |
// Copyright 2018 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
import (
"bufio"
"log"
"strings"
)
type item struct {
Name string
Children []*item
}
func parse(data string) item {
scanner := bufio.NewScanner(strings.NewReader(data))
var rootItem item
var currentLevelItem *item
lastLevel := 0
lineNumber := 0
for scanner.Scan() {
lineNumber++
line ... |
package assertion
import (
"fmt"
"reflect"
)
const panicFormatWithType = "expected %v (type %v) bot got %v (type %v)"
const panicFormat = "expected %v bot got %v"
func Equals(expected, actual interface{}) {
if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
panic(fmt.Sprintf(panicFormatWithType, expected, ... |
package internal
import (
"context"
"database/sql"
pb "github.com/lucasantarella/business-profiles-grpc-golib"
"log"
"lucasantarella.com/businesscards/models"
"lucasantarella.com/businesscards/utils"
"time"
)
type Server struct {
Db *sql.DB
}
func (s *Server) GetProfileSocialLinks(ctx context.Context, in *pb... |
package transformer
import (
"expvar"
"flag"
"fmt"
"log"
"os"
"sort"
"strings"
"github.com/dustin/go-humanize"
"github.com/sburnett/transformer/store"
)
// A pipeline stage is a single step of data processing, which reads data from
// Reader, sends each record to Transformer, and writes the resulting Record... |
package forest_test
import (
"testing"
forest "git.sr.ht/~whereswaldon/forest-go"
"git.sr.ht/~whereswaldon/forest-go/fields"
"golang.org/x/crypto/openpgp"
)
func MakeIdentityOrSkip(t *testing.T) (*forest.Identity, forest.Signer) {
privkey, err := openpgp.NewEntity("forest-test", "comment", "email@email.io", nil... |
package main
import (
"flag"
"fmt"
"log"
"os"
"text/tabwriter"
"upspin.io/client"
"upspin.io/config"
_ "upspin.io/dir/remote"
"upspin.io/flags"
_ "upspin.io/key/transports"
"upspin.io/subcmd"
"upspin.io/transports"
"upspin.io/upspin"
)
type state struct {
*subcmd.State
client *client.Client
entries ... |
package main
import "strings"
//125. 验证回文串
//给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
//
//说明:本题中,我们将空字符串定义为有效的回文串。
//
//示例 1:
//
//输入: "A man, a plan, a canal: Panama"
//输出: true
//示例 2:
//
//输入: "race a car"
//输出: false
func isPalindrome(s string) bool {
s = strings.ToLower(s)
n := len(s)
l := 0
r := n - 1
fo... |
package article_service
import (
"hanxiaolin/gin-demo/logging"
"hanxiaolin/gin-demo/models"
"hanxiaolin/gin-demo/pkg/gredis"
"hanxiaolin/gin-demo/service/cache_service"
"encoding/json"
"fmt"
)
type Article struct {
ID int
TagID int
Title string
Desc string
Content ... |
// Copyright 2017 The Aiicy Team.
//
// 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... |
package util
import (
"crypto/md5"
"fmt"
"io"
"github.com/lib/pq"
"github.com/pganalyze/collector/setup/query"
)
type PGHelperFn struct {
// function name
name string
// everything before prosrc in function definition sql, including
// the opening quote before the function source content starts
head string... |
package styles
// Present for backwards compatibility.
//
// Deprecated: use styles.Get(name) instead.
var (
Abap = Registry["abap"]
Algol = Registry["algol"]
AlgolNu = Registry["algol_nu"]
Arduino = Registry["arduino"]
Autumn = Registry["autumn"]
... |
package storage
import (
"fmt"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/operations"
"github.com/lxc/lxd/lxd/state"
"github.com/lxc/lxd/lxd/storage/drivers"
"github.com/lxc/lxd/shared/api"
log "github.com/lxc/lxd/shared/log15"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/logging"
)... |
// 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 middleware
import (
"github.com/forease/i18n/v2/i18n"
"github.com/gin-gonic/gin"
)
var (
DefaultLang = "zh_CN"
lang = DefaultLang
)
func I18N(args ...string) gin.HandlerFunc {
if len(args) > 0 {
lang = args[0]
}
return func(c *gin.Context) {
}
}
func LoadLocales(dir string) error {
retur... |
package middleware
import (
"movie-app/auth"
"movie-app/helper"
"movie-app/user"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
func AdminMiddleware(authService auth.Service, userService user.Service) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorizat... |
package config
import (
"github.com/joho/godotenv"
"log"
"os"
)
var (
// 数据库参数
DatabaseURI string
DatabaseName string
JwtKey string
)
func init() {
// 加载配置文件
err := godotenv.Load("./config/.env")
if err != nil {
log.Fatal("Error loading config.env file", err)
}
// 加载配置文件
DatabaseURI = os.Geten... |
package generator
import (
"bufio"
"fmt"
"html/template"
"io/ioutil"
"math"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/RomanosTrechlis/blog-generator/config"
"gopkg.in/yaml.v2"
)
// siteGenerator object
type siteGenerator struct {
Sources []string
SiteInfo *config.SiteInformation
}
//... |
package main
import (
"chatroom/server/model"
"fmt"
"net"
"time"
)
//处理客户端的通讯
func process(conn net.Conn) {
//这里需要延时关闭conn
defer conn.Close()
//这里调用总控,创建一个
processor := &Processor{
Conn: conn,
}
err := processor.process2()
if err != nil {
fmt.Println("客户端和服务器通讯协程错误,err=", err)
return
}
}
//这里我们编写一... |
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package cassandra
import "github.com/gocql/gocql"
const (
table = `CREATE TABLE IF NOT EXISTS messages (
id uuid,
channel text,
subtopic text,
publisher text,
protocol text,
name text,
unit text,... |
package main
import (
"errors"
"fmt"
"os"
"strings"
"github.com/pepabo/undocker"
"github.com/urfave/cli"
)
var version = "unknown"
func main() {
u := undocker.Undocker{
Out: os.Stdout,
Err: os.Stderr,
}
opts := undocker.Options{}
app := cli.NewApp()
app.Name = "undocker"
app.Usage = "Decompose doc... |
package model
import (
mgo "github.com/globalsign/mgo"
"github.com/simplejia/namesrv/mongo"
)
type Stat struct {
Name string
}
func (stat *Stat) Regular() (ok bool) {
if stat == nil {
return
}
ok = true
return
}
// Db 返回db name
func (stat *Stat) Db() (db string) {
return "stat"
}
// Table 返回table name
f... |
package dbctl
import (
"github.com/SuperTikuwa/mission-techdojo/model"
)
func InsertNewUser(newUser model.User) error {
db := gormConnect()
defer db.Close()
if result := db.Create(&newUser); result.Error != nil {
writeLog(failure, result.Error)
return result.Error
}
return nil
}
func SelectUserByToken(to... |
package helper
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"reflect"
"strings"
)
func StripPrefix(path string, handler http.Handler) http.Handler {
return http.StripPrefix(path,
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "" {
r.URL.Path = "/"
}
handl... |
package asptr
// Int returns a pointer to the input value
func Int(v int) *int {
return &v
}
// Int8 returns a pointer to the input value
func Int8(v int8) *int8 {
return &v
}
// Int16 returns a pointer to the input value
func Int16(v int16) *int16 {
return &v
}
// Int32 returns a pointer to the input value
func... |
package network_test
import (
"fmt"
"testing"
"github.com/wheatevo/wslroutesvc/network"
)
type missingNewIfaceRunner struct{}
func (e *missingNewIfaceRunner) Run(name string, arg ...string) ([]byte, error) {
return []byte(""), fmt.Errorf("Could not run command")
}
type foundNewIfaceRunner struct {
cmdCount in... |
package services
import (
"fmt"
"github.com/apulis/AIArtsBackend/configs"
"github.com/apulis/AIArtsBackend/models"
urllib "net/url"
)
func GetAllTraining(userName string, page, size int, jobStatus, searchWord, orderBy, order string) ([]*models.Training, int, int, error) {
//把传输过来的searchword空格改为%20urlencode
url ... |
package main
import (
"encoding/json"
"errors"
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"sort"
"strings"
"sync"
"time"
)
var apiKey = os.Getenv("PREDICT_API_KEY")
var myLog = log.New(os.Stderr, "app: ", log.LstdFlags | log.Lshortfile)
var tagMap TagMap
type PredictResp struct {
Status struct{
Code i... |
package awstest_test
import (
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/kms"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/stretchr/testify/assert"
"github.com/socialpoint-labs/bsk/aws... |
package repository
import (
"fmt"
"time"
"github.com/meso-org/meso/config"
"github.com/beevik/guid"
)
//TODO: make this live in global somewhere
type JSONTime time.Time
func (t JSONTime) MarshalJSON() ([]byte, error) {
//do your serializing here
stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format(config.Datef... |
package p_01001_01100
// 1022. Sum of Root To Leaf Binary Numbers, https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type TreeNode struct {
Val int
Left *TreeNo... |
package cmd
//Mock game config
type game struct {
Name string
Target string
}
|
package object
import (
"ganymede/vector"
"math"
)
// Type defines an objects collision type
type collisionType = int
const (
collisionCircle = iota
collisionBoundingBox
)
type collider interface {
GetCollisionType() collisionType
GetPosition() vector.Vector
}
type boundingBoxCollider interface {
GetDimensi... |
package dao
import (
"mall/app/api/web/groups/conf"
"mall/app/api/web/groups/model"
"mall/lib/database/nosql/mongo"
"mall/lib/database/orm"
"mall/lib/database/redis"
"github.com/jinzhu/gorm"
)
type Dao struct {
orm *gorm.DB
mgo *mongo.Mongo
redigo *redis.Redis
}
func New(c *conf.Config) *Dao {
db :=... |
package logger
import (
"fmt"
"runtime"
"strings"
"sync"
"time"
"github.com/fatih/color"
"github.com/mattn/go-colorable"
)
// LogLevel = uint
type LogLevel uint
const (
// ErrorLevel = 1
ErrorLevel LogLevel = 1
// WarnLevel = 2
WarnLevel LogLevel = 2
// InfoLevel = 3
InfoLevel LogLevel = 3
// DebugLev... |
// Copyright 2018 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 instance
import (
"fmt"
"os"
)
type Backend string
const (
Node Backend = "node"
Npm Backend = "npm"
Python Backend = "python"
Web Backend = "web"
Flask Backend = "flask"
)
func IsBackendValid(bkend Backend) bool {
switch bkend {
case Npm, Node, Python, Web, Flask:
return true
}
_, _ =... |
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
)
// Class data mobil (melakukan pemodelan data moobil dengan member(info detail) ID, Merk, dan Tahun)
type mobil struct {
ID int `json:"id"`
Merk string `json:"merk"`
Tahun int `json:"tahun"`
}
// Variable database in memory "sementara"
va... |
package alipay
import (
"time"
"errors"
"net/http"
"net/url"
"io/ioutil"
"github.com/acupple/alipay/enums"
"github.com/acupple/alipay/models/refund"
)
type Refunds struct {
Component
}
func NewRefunds(alipay Alipay) Refunds {
return Pays{
Component.Alipay: alipay,
}
}
func (r *Refunds)Refund(detail refu... |
package main
import (
"github.com/yuwe1/pgim/api/logic"
"github.com/yuwe1/pgim/pkg/client/dbpool"
"github.com/yuwe1/pgim/pkg/logger"
"github.com/yuwe1/pgim/pkg/util"
common "github.com/yuwe1/pgim/pkg"
)
func main() {
common.Init()
session, err, p, c := dbpool.GetSession()
defer func() {
if session != nil {... |
// Copyright 2018 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.