text:
package models

import (
	"encoding/json"
	"github.com/WeBankPartners/go-common-lib/cipher"
	"github.com/toolkits/file"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"sync"
)

type LogConfig struct {
	Level            string `json:"level"`
	LogDir           string `json:"log_dir"`
	ArchiveMaxSize   int    `json:"archive_max_size"`
	ArchiveMaxBackup int    `json:"archive_max_backup"`
	ArchiveMaxDay    int    `json:"archive_max_day"`
	Compress         bool   `json:"compress"`
}

type LdapConfig struct {
	Enable     bool     `json:"enable"`
	Server     string   `json:"server"`
	Port       int      `json:"port"`
	BindDN     string   `json:"bindDN"`
	BaseDN     string   `json:"baseDN"`
	Filter     string   `json:"filter"`
	Attributes []string `json:"attributes"`
}

type SessionRedisConfig struct {
	Enable  bool   `json:"enable"`
	Server  string `json:"server"`
	Port    int    `json:"port"`
	Pwd     string `json:"pwd"`
	Db      int    `json:"db"`
	MaxIdle int    `json:"max_idle"`
}

type SessionConfig struct {
	Enable       string             `json:"enable"`
	Expire       int64              `json:"expire"`
	ServerEnable bool               `json:"server_enable"`
	ServerToken  string             `json:"server_token"`
	Redis        SessionRedisConfig `json:"redis"`
}

type HttpConfig struct {
	Port            string         `json:"port"`
	Swagger         bool           `json:"swagger"`
	Cross           bool           `json:"cross"`
	ReturnError     bool           `json:"return_error"`
	Alive           int64          `json:"alive"`
	Ldap            *LdapConfig    `json:"ldap"`
	Session         *SessionConfig `json:"session"`
	DefaultLanguage string         `json:"default_language"`
}

type StoreConfig struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	Server   string `json:"server"`
	Port     string `json:"port"`
	User     string `json:"user"`
	Pwd      string `json:"pwd"`
	DataBase string `json:"database"`
	MaxOpen  int    `json:"maxOpen"`
	MaxIdle  int    `json:"maxIdle"`
	Timeout  int    `json:"timeout"`
}

type DataSourceConfig struct {
	Env        string               `json:"env"`
	Servers    []*DatasourceServers `json:"servers"`
	DivideTime int64                `json:"divide_time"`
	WaitTime   int                  `json:"wait_time"`
}

type DependenceConfig struct {
	Name     string `json:"name"`
	Server   string `json:"server"`
	Username string `json:"username"`
	Password string `json:"password"`
	Expire   int    `json:"expire"`
}

type AgentConfig struct {
	AgentType  string `json:"agent_type"`
	AgentBin   string `json:"agent_bin"`
	Port       string `json:"port"`
	User       string `json:"user"`
	Password   string `json:"password"`
	ConfigFile string `json:"config_file"`
}

type DatasourceServers struct {
	Id    int    `json:"id"`
	Type  string `json:"type"`
	Env   string `json:"env"`
	Host  string `json:"host"`
	Token string `json:"token"`
}

type PrometheusConfig struct {
	SdConfigPath   string `json:"sd_config_path"`
	RuleConfigPath string `json:"rule_config_path"`
	ConfigReload   string `json:"config_reload"`
}

type AlertMailConfig struct {
	Enable   bool   `json:"enable"`
	Protocol string `json:"protocol"`
	Tls      bool   `json:"tls"`
	Sender   string `json:"sender"`
	User     string `json:"user"`
	Password string `json:"password"`
	Server   string `json:"server"`
	Token    string `json:"token"`
}

type AlertConfig struct {
	Enable bool            `json:"enable"`
	Mail   AlertMailConfig `json:"mail"`
}

type PeerConfig struct {
	Enable          bool     `json:"enable"`
	InstanceHostIp  string   `json:"instance_host_ip"`
	HttpPort        string   `json:"http_port"`
	OtherServerList []string `json:"other_server_list"`
}

type CronJobConfig struct {
	Enable   bool `json:"enable"`
	Interval int  `json:"interval"`
}

type SdFileConfig struct {
	Enable bool   `json:"enable"`
	Path   string `json:"path"`
}

type ArchiveMysqlConfig struct {
	Enable             string `json:"enable"`
	Type               string `json:"type"`
	Server             string `json:"server"`
	Port               string `json:"port"`
	User               string `json:"user"`
	Password           string `json:"password"`
	DataBase           string `json:"database"`
	DatabasePrefix     string `json:"database_prefix"`
	MaxOpen            int    `json:"maxOpen"`
	MaxIdle            int    `json:"maxIdle"`
	Timeout            int    `json:"timeout"`
	LocalStorageMaxDay int64  `json:"local_storage_max_day"`
	FiveMinStartDay    int64  `json:"five_min_start_day"`
}

type CapacityServerConfig struct {
	Server string `json:"server"`
	Port   string `json:"port"`
}

type GlobalConfig struct {
	IsPluginMode                 string              `json:"is_plugin_mode"`
	Http                         *HttpConfig         `json:"http"`
	Log                          LogConfig           `json:"log"`
	Store                        StoreConfig         `json:"store"`
	Datasource                   DataSourceConfig    `json:"datasource"`
	LimitIp                      []string            `json:"limitIp"`
	Dependence                   []*DependenceConfig `json:"dependence"`
	Prometheus                   PrometheusConfig    `json:"prometheus"`
	TagBlacklist                 []string            `json:"tag_blacklist"`
	Agent                        []*AgentConfig      `json:"agent"`
	Alert                        AlertConfig         `json:"alert"`
	Peer                         PeerConfig          `json:"peer"`
	CronJob                      CronJobConfig       `json:"cron_job"`
	SdFile                       SdFileConfig        `json:"sd_file"`
	ArchiveMysql                 ArchiveMysqlConfig  `json:"archive_mysql"`
	ProcessCheckList             []string            `json:"process_check_list"`
	DefaultAdminRole             string              `json:"default_admin_role"`
	AlarmAliveMaxDay             string              `json:"alarm_alive_max_day"`
	MonitorAlarmMailEnable       string              `json:"monitor_alarm_mail_enable"`
	MonitorAlarmCallbackLevelMin string              `json:"monitor_alarm_callback_level_min"`
}

var (
	ConfigFile           string
	config               *GlobalConfig
	lock                 = new(sync.RWMutex)
	CoreUrl              string
	CoreJwtKey           string
	FiringCallback       string
	RecoverCallback      string
	SubSystemCode        string
	SubSystemKey         string
	DefaultMailReceiver  []string
	DefaultLocalTimeZone string
	PluginRunningMode    bool
	SmsParamMaxLength    int
	AlarmMailEnable      bool
	AgentManagerRemoteIp string
)

func Config() *GlobalConfig {
	lock.RLock()
	defer lock.RUnlock()
	return config
}

func InitConfig(cfg string) {
	if cfg == "" {
		log.Fatalln("use -c to specify configuration file")
	}

	if !file.IsExist(cfg) {
		log.Fatalln("config file:", cfg, "is not existent. maybe you need `mv cfg.example.json cfg.json`")
	}

	ConfigFile = cfg

	configContent, err := file.ToTrimString(cfg)
	if err != nil {
		log.Fatalln("read config file:", cfg, "fail:", err)
	}

	var c GlobalConfig
	err = json.Unmarshal([]byte(configContent), &c)
	if err != nil {
		log.Fatalln("parse config file:", cfg, "fail:", err)
	}
	rsaPemByte, readRsaErr := ioutil.ReadFile(RsaPemPath)
	if readRsaErr != nil {
		log.Printf("Read rsa pem file fail,%s ", readRsaErr.Error())
	}
	c.Store.Pwd, _ = cipher.DecryptRsa(c.Store.Pwd, string(rsaPemByte))
	c.ArchiveMysql.Password, _ = cipher.DecryptRsa(c.ArchiveMysql.Password, string(rsaPemByte))
	if c.IsPluginMode == "yes" || c.IsPluginMode == "y" || c.IsPluginMode == "true" {
		PluginRunningMode = true
	} else {
		PluginRunningMode = false
	}
	lock.Lock()
	defer lock.Unlock()

	config = &c
	config.MonitorAlarmMailEnable = strings.ToLower(config.MonitorAlarmMailEnable)
	if config.MonitorAlarmMailEnable == "y" || config.MonitorAlarmMailEnable == "yes" || config.MonitorAlarmMailEnable == "true" {
		AlarmMailEnable = true
	} else {
		AlarmMailEnable = false
	}
	if config.MonitorAlarmCallbackLevelMin == "" {
		config.MonitorAlarmCallbackLevelMin = "high"
	}
	for _, v := range config.Dependence {
		if v.Name == "core" {
			CoreUrl = v.Server
			if strings.HasSuffix(CoreUrl, "/") {
				CoreUrl = CoreUrl[:len(CoreUrl)-1]
			}
			break
		}
	}
	CoreJwtKey, _ = cipher.DecryptRsa(os.Getenv("JWT_SIGNING_KEY"), string(rsaPemByte))
	SubSystemCode = os.Getenv("SUB_SYSTEM_CODE")
	SubSystemKey = os.Getenv("SUB_SYSTEM_KEY")
	FiringCallback = os.Getenv("ALARM_FIRING_CALLBACK")
	RecoverCallback = os.Getenv("ALARM_RECOVER_CALLBACK")
	agentMangerLocalMode := strings.ToLower(os.Getenv("MONITOR_AGENT_MANAGER_REMOTE_MODE"))
	if agentMangerLocalMode == "y" || agentMangerLocalMode == "yes" || agentMangerLocalMode == "true" {
		AgentManagerRemoteIp = os.Getenv("MONITOR_HOST_IP")
	}
	log.Println("read config file:", cfg, "successfully")
	if CoreUrl != "" && SubSystemCode != "" && SubSystemKey != "" {
		InitCoreToken()
	} else {
		log.Printf("Init core token fail,coreUrl & subSystemCode & subSystemKey can not empty")
	}
	SmsParamMaxLength, _ = strconv.Atoi(os.Getenv("MONITOR_SMS_PARAM_LENGTH"))
	initLocalTimeZone()
}

func initLocalTimeZone() {
	cmdOut, err := exec.Command("/bin/sh", "-c", "date|awk '{print $5}'").Output()
	if err != nil {
		log.Printf("init local time zone fail,%s \n", err.Error())
	} else {
		cmdOutString := strings.TrimSpace(string(cmdOut))
		if cmdOutString != "" {
			DefaultLocalTimeZone = cmdOutString
			log.Printf("init local time zone to %s \n", DefaultLocalTimeZone)
		} else {
			DefaultLocalTimeZone = "CST"
		}
	}
}

repository: WeBankPartners/open-monitor

repo_name: WeBankPartners/open-monitor


text:
package application

import (
	"context"
	"os"
	"strings"
	"sync"
	"testing"

	"lmm/api/clock"
	"lmm/api/pkg/pubsub/pubsubtest"
	testUtil "lmm/api/pkg/testing"
	"lmm/api/pkg/transaction"
	"lmm/api/service/user/application/command"
	"lmm/api/service/user/domain"
	"lmm/api/service/user/domain/model"
	"lmm/api/service/user/port/adapter/messaging"
	"lmm/api/service/user/port/adapter/service"
	"lmm/api/util/uuidutil"

	"github.com/google/uuid"
	"github.com/pkg/errors"
	"github.com/stretchr/testify/assert"
	"golang.org/x/crypto/bcrypt"
)

var (
	testAppService *Service
)

type InmemoryUserRepository struct {
	sync.RWMutex
	memory map[model.UserID]*model.User
}

func (repo *InmemoryUserRepository) NextID(tx transaction.Transaction) (model.UserID, error) {
	repo.Lock()
	defer repo.Unlock()

	return model.UserID(int64(len(repo.memory) + 1)), nil
}

func (repo *InmemoryUserRepository) Save(tx transaction.Transaction, user *model.User) error {
	repo.Lock()
	defer repo.Unlock()

	repo.memory[user.ID()] = user
	return nil
}

func (repo *InmemoryUserRepository) FindByName(tx transaction.Transaction, username string) (*model.User, error) {
	repo.RLock()
	defer repo.RUnlock()

	for _, user := range repo.memory {
		if user.Name() == username {
			return user, nil
		}
	}
	return nil, domain.ErrNoSuchUser
}

func (repo *InmemoryUserRepository) FindByToken(tx transaction.Transaction, token string) (*model.User, error) {
	repo.RLock()
	defer repo.RUnlock()

	for _, user := range repo.memory {
		if user.Token() == token {
			return user, nil
		}
	}
	return nil, domain.ErrNoSuchUser
}

func (repo *InmemoryUserRepository) Begin(c context.Context, opts *transaction.Option) (transaction.Transaction, error) {
	return transaction.Nop(), nil
}

func (repo *InmemoryUserRepository) RunInTransaction(c context.Context, f func(tx transaction.Transaction) error, opts *transaction.Option) error {
	tx, err := repo.Begin(c, opts)
	if err != nil {
		panic("unexpected error: " + err.Error())
	}
	defer tx.Commit()

	return f(tx)
}

func TestMain(m *testing.M) {
	repo := &InmemoryUserRepository{memory: make(map[model.UserID]*model.User)}
	pubsubClient := pubsubtest.NewClient()
	pub := messaging.NewUserEventPublisher(pubsubClient)
	testAppService = NewService(
		&service.BcryptService{},
		testUtil.TokenService,
		repo, repo, pub)
	code := m.Run()
	pubsubClient.Close()
	os.Exit(code)
}

func TestRegisterNewUser(t *testing.T) {
	c := context.Background()

	t.Run("Success", func(t *testing.T) {
		username, password := "username", "~!@#$%^&*()-_=+{[}]|\\:;\"'<,>.?/"
		userID, err := testAppService.RegisterNewUser(c, command.Register{
			UserName:     username,
			EmailAddress: username + "@lmm.local",
			Password:     password,
		})
		assert.NoError(t, err)
		assert.NotZero(t, userID)

		user, err := testAppService.userRepository.FindByName(nil, "username")
		assert.NoError(t, err)
		assert.Equal(t, username, user.Name())
		assert.NoError(t, bcrypt.CompareHashAndPassword(
			[]byte(user.Password()),
			[]byte(password),
		))
		assert.NotPanics(t, func() {
			uuid.Must(uuidutil.ParseString(user.Token()))
		})
	})

	t.Run("Fail", func(t *testing.T) {
		cases := map[string]struct {
			UserName string
			Email    string
			Password string
			Err      error
		}{
			"UserNameTooShort": {
				"ur", "ur@lmm.local", "password1234", domain.ErrInvalidUserName,
			},
			"UserNameStartsWithoutLetter": {
				"1username", "1username@lmm.local", "password1234", domain.ErrInvalidUserName,
			},
			"EmptyPassword": {
				"username", "username@lmm.local", "", domain.ErrUserPasswordEmpty,
			},
			"PasswordIsTooShort": {
				"username", "username@lmm.local", "passwor", domain.ErrUserPasswordTooShort,
			},
			"PasswordIsTooWeak": {
				"username", "username@lmm.local", "password", domain.ErrUserPasswordTooWeak,
			},
			"PasswordIsTooLong": {
				"username", "username@lmm.local", strings.Repeat("s", 251), domain.ErrUserPasswordTooLong,
			},
			"DuplicateUserName": {
				"username", "username@lmm.local", "password1234", domain.ErrUserNameAlreadyUsed,
			},
		}

		for testName, testCase := range cases {
			t.Run(testName, func(t *testing.T) {
				userIDGot, err := testAppService.RegisterNewUser(c, command.Register{
					UserName:     testCase.UserName,
					EmailAddress: testCase.Email,
					Password:     testCase.Password,
				})
				assert.Error(t, testCase.Err, errors.Cause(err), testName)
				assert.Equal(t, int64(0), userIDGot, testName)
			})
		}
	})
}

func TestUserChangePassword(t *testing.T) {
	c := context.Background()

	username, password := "U"+uuidutil.NewUUID()[:8], "U$ErP@ssw0rD"
	userID, err := testAppService.RegisterNewUser(c, command.Register{
		UserName:     username,
		EmailAddress: username + "@lmm.local",
		Password:     password,
	})
	if !assert.NoError(t, err) || !assert.NotZero(t, userID) {
		t.Fatal("failed to create new user")
	}

	userBeforePasswordChanging, err := testAppService.userRepository.FindByName(nil, username)
	if !assert.NoError(t, err) {
		t.Fatal(err)
	}

	// record value since it's changed by pointer
	oldToken := userBeforePasswordChanging.Token()

	newPassword := uuidutil.NewUUID() + uuidutil.NewUUID()

	assert.NoError(t, testAppService.UserChangePassword(c, command.ChangePassword{
		User:        username,
		OldPassword: password,
		NewPassword: newPassword,
	}))

	userAfterPasswordChanging, err := testAppService.userRepository.FindByName(nil, username)
	if !assert.NoError(t, err) {
		t.Fatal(err)
	}

	assert.True(t, testAppService.encrypter.Verify(newPassword, userAfterPasswordChanging.Password()))
	assert.NotEqual(t, oldToken, userAfterPasswordChanging.Token())
}

func newAdmin() *model.User {
	return newUserWithRole(model.Admin)
}

func newOrdinary() *model.User {
	return newUserWithRole(model.Ordinary)
}

func newUserWithRole(role model.Role) *model.User {
	randomUserName := "u" + uuid.New().String()[:7]
	email := randomUserName + "@lmm.local"
	password := uuid.New().String()
	token := uuid.New().String()

	user, err := model.NewUser(0, randomUserName, email, password, token, role, clock.Now())
	if err != nil {
		panic(err)
	}

	return user
}

license: MIT

repository: akinaru-lu/lmm

license_type: permissive

repo_name: akinaru-lu/lmm

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: Go

extension: go


text:
package object

import (
	"testing"
)

func TestObject_Type(t *testing.T) {
	testcases := []struct {
		obj      Object
		expected string
	}{
		{&Integer{}, "INTEGER"},
		{&Boolean{}, "BOOLEAN"},
		{&String{}, "STRING"},
		{&Array{}, "ARRAY"},
		{&BRollCompResult{}, "B_ROLL_COMP_RESULT"},
		{&RRollCompResult{}, "R_ROLL_COMP_RESULT"},
		{&URollExprResult{}, "U_ROLL_EXPR_RESULT"},
		{&URollCompResult{}, "U_ROLL_COMP_RESULT"},
	}

	for _, test := range testcases {
		t.Run(test.expected, func(t *testing.T) {
			actual := test.obj.Type().String()
			if actual != test.expected {
				t.Errorf("got: %q, want: %q", actual, test.expected)
			}
		})
	}
}


text:
// Code generated by protoc-gen-go.
// source: protocol/serverload.proto
// DO NOT EDIT!

package protocol

import proto "code.google.com/p/goprotobuf/proto"
import json "encoding/json"
import math "math"

// Reference proto, json, and math imports to suppress error if they are not otherwise used.
var _ = proto.Marshal
var _ = &json.SyntaxError{}
var _ = math.Inf

type ServerLoad struct {
	SrvType          *int32 `protobuf:"varint,1,req" json:"SrvType,omitempty"`
	SrvId            *int32 `protobuf:"varint,2,req" json:"SrvId,omitempty"`
	CurLoad          *int32 `protobuf:"varint,3,req" json:"CurLoad,omitempty"`
	XXX_unrecognized []byte `json:"-"`
}

func (m *ServerLoad) Reset()         { *m = ServerLoad{} }
func (m *ServerLoad) String() string { return proto.CompactTextString(m) }
func (*ServerLoad) ProtoMessage()    {}

func (m *ServerLoad) GetSrvType() int32 {
	if m != nil && m.SrvType != nil {
		return *m.SrvType
	}
	return 0
}

func (m *ServerLoad) GetSrvId() int32 {
	if m != nil && m.SrvId != nil {
		return *m.SrvId
	}
	return 0
}

func (m *ServerLoad) GetCurLoad() int32 {
	if m != nil && m.CurLoad != nil {
		return *m.CurLoad
	}
	return 0
}

type ServerStateSwitch struct {
	SrvType          *int32 `protobuf:"varint,1,req" json:"SrvType,omitempty"`
	SrvId            *int32 `protobuf:"varint,2,req" json:"SrvId,omitempty"`
	XXX_unrecognized []byte `json:"-"`
}

func (m *ServerStateSwitch) Reset()         { *m = ServerStateSwitch{} }
func (m *ServerStateSwitch) String() string { return proto.CompactTextString(m) }
func (*ServerStateSwitch) ProtoMessage()    {}

func (m *ServerStateSwitch) GetSrvType() int32 {
	if m != nil && m.SrvType != nil {
		return *m.SrvType
	}
	return 0
}

func (m *ServerStateSwitch) GetSrvId() int32 {
	if m != nil && m.SrvId != nil {
		return *m.SrvId
	}
	return 0
}

func init() {
}

repository: konser/go-pack

repo_name: konser/go-pack


text:
@article{dong2021attention,
  title={Attention is not all you need: Pure attention loses rank doubly exponentially with depth},
  author={Dong, Yihe and Cordonnier, Jean-Baptiste and Loukas, Andreas},
  journal={arXiv preprint arXiv:2103.03404},
  year={2021}
}

url: https://raw.githubusercontent.com/rbt-c/DL-NLP-Readings/82ca76e9184a3b00ac87129d99391477c85cfcd2/Bibtex/Attention is not all you need - pure attention loses rank doubly exponentially with depth.bib

repository: rbt-c/DL-NLP-Readings

repo_name: rbt-c/DL-NLP-Readings

extension: bib


text:
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.

package restore

import (
	"context"
	"sync"
	"time"

	"github.com/pingcap/errors"
	backuppb "github.com/pingcap/kvproto/pkg/brpb"
	"github.com/pingcap/log"
	"github.com/pingcap/tidb/br/pkg/glue"
	"github.com/pingcap/tidb/br/pkg/logutil"
	"github.com/pingcap/tidb/br/pkg/metautil"
	"github.com/pingcap/tidb/br/pkg/rtree"
	"github.com/pingcap/tidb/br/pkg/summary"
	"github.com/pingcap/tidb/br/pkg/utils"
	"github.com/pingcap/tidb/parser/model"
	"go.uber.org/zap"
	"golang.org/x/sync/errgroup"
)

const (
	defaultChannelSize = 1024
)

// TableSink is the 'sink' of restored data by a sender.
type TableSink interface {
	EmitTables(tables ...CreatedTable)
	EmitError(error)
	Close()
}

type chanTableSink struct {
	outCh chan<- []CreatedTable
	errCh chan<- error
}

func (sink chanTableSink) EmitTables(tables ...CreatedTable) {
	sink.outCh <- tables
}

func (sink chanTableSink) EmitError(err error) {
	sink.errCh <- err
}

func (sink chanTableSink) Close() {
	// ErrCh may has multi sender part, don't close it.
	close(sink.outCh)
}

// ContextManager is the struct to manage a TiKV 'context' for restore.
// Batcher will call Enter when any table should be restore on batch,
// so you can do some prepare work here(e.g. set placement rules for online restore).
type ContextManager interface {
	// Enter make some tables 'enter' this context(a.k.a., prepare for restore).
	Enter(ctx context.Context, tables []CreatedTable) error
	// Leave make some tables 'leave' this context(a.k.a., restore is done, do some post-works).
	Leave(ctx context.Context, tables []CreatedTable) error
	// Close closes the context manager, sometimes when the manager is 'killed' and should do some cleanup
	// it would be call.
	Close(ctx context.Context)
}

// NewBRContextManager makes a BR context manager, that is,
// set placement rules for online restore when enter(see <splitPrepareWork>),
// unset them when leave.
func NewBRContextManager(client *Client) ContextManager {
	return &brContextManager{
		client: client,

		hasTable: make(map[int64]CreatedTable),
	}
}

type brContextManager struct {
	client *Client

	// This 'set' of table ID allow us to handle each table just once.
	hasTable map[int64]CreatedTable
	mu       sync.Mutex
}

func (manager *brContextManager) Close(ctx context.Context) {
	tbls := make([]*model.TableInfo, 0, len(manager.hasTable))
	for _, tbl := range manager.hasTable {
		tbls = append(tbls, tbl.Table)
	}
	splitPostWork(ctx, manager.client, tbls)
}

func (manager *brContextManager) Enter(ctx context.Context, tables []CreatedTable) error {
	placementRuleTables := make([]*model.TableInfo, 0, len(tables))
	manager.mu.Lock()
	defer manager.mu.Unlock()

	for _, tbl := range tables {
		if _, ok := manager.hasTable[tbl.Table.ID]; !ok {
			placementRuleTables = append(placementRuleTables, tbl.Table)
		}
		manager.hasTable[tbl.Table.ID] = tbl
	}

	return splitPrepareWork(ctx, manager.client, placementRuleTables)
}

func (manager *brContextManager) Leave(ctx context.Context, tables []CreatedTable) error {
	manager.mu.Lock()
	defer manager.mu.Unlock()
	placementRuleTables := make([]*model.TableInfo, 0, len(tables))

	for _, table := range tables {
		placementRuleTables = append(placementRuleTables, table.Table)
	}

	splitPostWork(ctx, manager.client, placementRuleTables)
	log.Info("restore table done", ZapTables(tables))
	for _, tbl := range placementRuleTables {
		delete(manager.hasTable, tbl.ID)
	}
	return nil
}

func splitPostWork(ctx context.Context, client *Client, tables []*model.TableInfo) {
	err := client.ResetPlacementRules(ctx, tables)
	if err != nil {
		log.Warn("reset placement rules failed", zap.Error(err))
		return
	}
}

func splitPrepareWork(ctx context.Context, client *Client, tables []*model.TableInfo) error {
	err := client.SetupPlacementRules(ctx, tables)
	if err != nil {
		log.Error("setup placement rules failed", zap.Error(err))
		return errors.Trace(err)
	}

	err = client.WaitPlacementSchedule(ctx, tables)
	if err != nil {
		log.Error("wait placement schedule failed", zap.Error(err))
		return errors.Trace(err)
	}
	return nil
}

// CreatedTable is a table created on restore process,
// but not yet filled with data.
type CreatedTable struct {
	RewriteRule *RewriteRules
	Table       *model.TableInfo
	OldTable    *metautil.Table
}

func DefaultOutputTableChan() chan *CreatedTable {
	return make(chan *CreatedTable, defaultChannelSize)
}

// TableWithRange is a CreatedTable that has been bind to some of key ranges.
type TableWithRange struct {
	CreatedTable

	Range []rtree.Range
}

type TableIDWithFiles struct {
	TableID int64

	Files []*backuppb.File
}

// Exhaust drains all remaining errors in the channel, into a slice of errors.
func Exhaust(ec <-chan error) []error {
	out := make([]error, 0, len(ec))
	for {
		select {
		case err := <-ec:
			out = append(out, err)
		default:
			// errCh will NEVER be closed(ya see, it has multi sender-part),
			// so we just consume the current backlog of this channel, then return.
			return out
		}
	}
}

// BatchSender is the abstract of how the batcher send a batch.
type BatchSender interface {
	// PutSink sets the sink of this sender, user to this interface promise
	// call this function at least once before first call to `RestoreBatch`.
	PutSink(sink TableSink)
	// RestoreBatch will send the restore request.
	RestoreBatch(ranges DrainResult)
	Close()
}

// TiKVRestorer is the minimal methods required for restoring.
// It contains the primitive APIs extract from `restore.Client`, so some of arguments may seem redundant.
// Maybe TODO: make a better abstraction?
type TiKVRestorer interface {
	// SplitRanges split regions implicated by the ranges and rewrite rules.
	// After spliting, it also scatters the fresh regions.
	SplitRanges(ctx context.Context,
		ranges []rtree.Range,
		rewriteRules *RewriteRules,
		updateCh glue.Progress,
		isRawKv bool) error
	// RestoreSSTFiles import the files to the TiKV.
	RestoreSSTFiles(ctx context.Context,
		tableIDWithFiles []TableIDWithFiles,
		rewriteRules *RewriteRules,
		updateCh glue.Progress) error
}

type tikvSender struct {
	client TiKVRestorer

	updateCh glue.Progress

	sink TableSink
	inCh chan<- DrainResult

	wg *sync.WaitGroup

	tableWaiters *sync.Map
}

func (b *tikvSender) PutSink(sink TableSink) {
	// don't worry about visibility, since we will call this before first call to
	// RestoreBatch, which is a sync point.
	b.sink = sink
}

func (b *tikvSender) RestoreBatch(ranges DrainResult) {
	log.Info("restore batch: waiting ranges", zap.Int("range", len(b.inCh)))
	b.inCh <- ranges
}

// NewTiKVSender make a sender that send restore requests to TiKV.
func NewTiKVSender(
	ctx context.Context,
	cli TiKVRestorer,
	updateCh glue.Progress,
	splitConcurrency uint,
) (BatchSender, error) {
	inCh := make(chan DrainResult, defaultChannelSize)
	midCh := make(chan drainResultAndDone, defaultChannelSize)

	sender := &tikvSender{
		client:       cli,
		updateCh:     updateCh,
		inCh:         inCh,
		wg:           new(sync.WaitGroup),
		tableWaiters: new(sync.Map),
	}

	sender.wg.Add(2)
	go sender.splitWorker(ctx, inCh, midCh, splitConcurrency)
	go sender.restoreWorker(ctx, midCh)
	return sender, nil
}

func (b *tikvSender) Close() {
	close(b.inCh)
	b.wg.Wait()
	log.Debug("tikv sender closed")
}

type drainResultAndDone struct {
	result DrainResult
	done   func()
}

func (b *tikvSender) splitWorker(ctx context.Context,
	ranges <-chan DrainResult,
	next chan<- drainResultAndDone,
	concurrency uint,
) {
	defer log.Debug("split worker closed")
	eg, ectx := errgroup.WithContext(ctx)
	defer func() {
		b.wg.Done()
		if err := eg.Wait(); err != nil {
			b.sink.EmitError(err)
		}
		close(next)
		log.Info("TiKV Sender: split worker exits.")
	}()

	start := time.Now()
	defer func() {
		elapsed := time.Since(start)
		summary.CollectDuration("split region", elapsed)
	}()

	pool := utils.NewWorkerPool(concurrency, "split")
	for {
		select {
		case <-ectx.Done():
			return
		case result, ok := <-ranges:
			if !ok {
				return
			}
			// When the batcher has sent all ranges from a table, it would
			// mark this table 'all done'(BlankTablesAfterSend), and then we can send it to checksum.
			//
			// When there a sole worker sequentially running those batch tasks, everything is fine, however,
			// in the context of multi-workers, that become buggy, for example:
			// |------table 1, ranges 1------|------table 1, ranges 2------|
			// The batcher send batches: [
			//		{Ranges: ranges 1},
			// 		{Ranges: ranges 2, BlankTablesAfterSend: table 1}
			// ]
			// And there are two workers runs concurrently:
			// 		worker 1: {Ranges: ranges 1}
			//      worker 2: {Ranges: ranges 2, BlankTablesAfterSend: table 1}
			// And worker 2 finished its job before worker 1 done. Note the table wasn't restored fully,
			// hence the checksum would fail.
			done := b.registerTableIsRestoring(result.TablesToSend)
			pool.ApplyOnErrorGroup(eg, func() error {
				err := b.client.SplitRanges(ectx, result.Ranges, result.RewriteRules, b.updateCh, false)
				if err != nil {
					log.Error("failed on split range", rtree.ZapRanges(result.Ranges), zap.Error(err))
					return err
				}
				next <- drainResultAndDone{
					result: result,
					done:   done,
				}
				return nil
			})
		}
	}
}

// registerTableIsRestoring marks some tables as 'current restoring'.
// Returning a function that mark the restore has been done.
func (b *tikvSender) registerTableIsRestoring(ts []CreatedTable) func() {
	wgs := make([]*sync.WaitGroup, 0, len(ts))
	for _, t := range ts {
		i, _ := b.tableWaiters.LoadOrStore(t.Table.ID, new(sync.WaitGroup))
		wg := i.(*sync.WaitGroup)
		wg.Add(1)
		wgs = append(wgs, wg)
	}
	return func() {
		for _, wg := range wgs {
			wg.Done()
		}
	}
}

// waitTablesDone block the current goroutine,
// till all tables provided are no more ‘current restoring’.
func (b *tikvSender) waitTablesDone(ts []CreatedTable) {
	for _, t := range ts {
		wg, ok := b.tableWaiters.LoadAndDelete(t.Table.ID)
		if !ok {
			log.Panic("bug! table done before register!",
				zap.Any("wait-table-map", b.tableWaiters),
				zap.Stringer("table", t.Table.Name))
		}
		wg.(*sync.WaitGroup).Wait()
	}
}

func (b *tikvSender) restoreWorker(ctx context.Context, ranges <-chan drainResultAndDone) {
	eg, ectx := errgroup.WithContext(ctx)
	defer func() {
		log.Info("TiKV Sender: restore worker prepare to close.")
		if err := eg.Wait(); err != nil {
			b.sink.EmitError(err)
		}
		b.sink.Close()
		b.wg.Done()
		log.Info("TiKV Sender: restore worker exits.")
	}()
	for {
		select {
		case <-ectx.Done():
			return
		case r, ok := <-ranges:
			if !ok {
				return
			}
			files := r.result.Files()
			// There has been a worker in the `RestoreSSTFiles` procedure.
			// Spawning a raw goroutine won't make too many requests to TiKV.
			eg.Go(func() error {
				e := b.client.RestoreSSTFiles(ectx, files, r.result.RewriteRules, b.updateCh)
				if e != nil {
					log.Error("restore batch meet error", logutil.ShortError(e), zapTableIDWithFiles(files))
					r.done()
					return e
				}
				log.Info("restore batch done", rtree.ZapRanges(r.result.Ranges))
				r.done()
				b.waitTablesDone(r.result.BlankTablesAfterSend)
				b.sink.EmitTables(r.result.BlankTablesAfterSend...)
				return nil
			})
		}
	}
}

repository: pingcap/tidb

repo_name: pingcap/tidb


text:
SUMMARY = "C++ parsing library for Service Information (SI) in DVB systems"
AUTHOR = "Andreas Oberritter"
SECTION = "libs/multimedia"
LICENSE = "LGPLv2.1"
LIC_FILES_CHKSUM = "file://COPYING;md5=a6f89e2100d9b6cdffcea4f398e37343"
OPENDREAMBOX_PROJECT = "obi/libdvbsi++"
SRCREV = "${@opendreambox_srcrev('515a1b65618324198fbeb8a5c8e3bf1caad7ffa6', d)}"

inherit autotools pkgconfig opendreambox-git

repository: opendreambox/opendreambox

repo_name: opendreambox/opendreambox

branch_name: refs/heads/pyro

gha_license_id: NOASSERTION

gha_language: BitBake

extension: bb


text:
package dmuc

import (
	"log"
)

// ErrorHandler is a function that checks error values, logs errors
// and, if needed, exits the program
func ErrorHandler(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

repository: crazcalm/dmuc

repo_name: crazcalm/dmuc


text:
package main

import (
	"crypto/tls"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"sync"
	"syscall"
	"time"

	auth "github.com/heroku/lumbermill/Godeps/_workspace/src/github.com/heroku/authenticater"
	influx "github.com/heroku/lumbermill/Godeps/_workspace/src/github.com/influxdb/influxdb-go"
	metrics "github.com/heroku/lumbermill/Godeps/_workspace/src/github.com/rcrowley/go-metrics"
	librato "github.com/heroku/lumbermill/Godeps/_workspace/src/github.com/rcrowley/go-metrics/librato"
)

type shutdownChan chan struct{}

type clientFunc func() *http.Client

const (
	defaultClientTimeout = 20 * time.Second
	pointChannelCapacity = 500000
	hashRingReplication  = 46
	postersPerHost       = 6
)

var (
	connectionCloser = make(chan struct{})
	debug            = os.Getenv("DEBUG") == "true"
)

func (s shutdownChan) Close() error {
	s <- struct{}{}
	return nil
}

func createInfluxDBClient(host string, f clientFunc) influx.ClientConfig {
	return influx.ClientConfig{
		Host:       host,                       //"influxor.ssl.edward.herokudev.com:8086",
		Username:   os.Getenv("INFLUXDB_USER"), //"test",
		Password:   os.Getenv("INFLUXDB_PWD"),  //"tester",
		Database:   os.Getenv("INFLUXDB_NAME"), //"ingress",
		IsSecure:   os.Getenv("INFLUXDB_INSECURE") != "true",
		HttpClient: f(),
	}
}

// Creates clients which deliver to InfluxDB
func createClients(hostlist string, f clientFunc) []influx.ClientConfig {
	var clients []influx.ClientConfig

	for _, host := range strings.Split(hostlist, ",") {
		host = strings.Trim(host, "\t ")
		if host != "" {
			clients = append(clients, createInfluxDBClient(host, f))
		}
	}
	return clients
}

// Creates destinations and attaches them to posters, which deliver to InfluxDB
func createMessageRoutes(hostlist string, f clientFunc) (*hashRing, []*destination, *sync.WaitGroup) {
	var destinations []*destination
	posterGroup := new(sync.WaitGroup)
	hashRing := newHashRing(hashRingReplication, nil)

	influxClients := createClients(hostlist, f)
	if len(influxClients) == 0 {
		//No backends, so blackhole things
		destination := newDestination("null", pointChannelCapacity)
		hashRing.Add(destination)
		destinations = append(destinations, destination)
		poster := newNullPoster(destination)
		go poster.Run()
	} else {
		for _, client := range influxClients {
			name := client.Host
			destination := newDestination(name, pointChannelCapacity)
			hashRing.Add(destination)
			destinations = append(destinations, destination)
			for p := 0; p < postersPerHost; p++ {
				poster := newPoster(client, name, destination, posterGroup)
				posterGroup.Add(1)
				go func() {
					poster.Run()
					posterGroup.Done()
				}()
			}
		}
	}

	return hashRing, destinations, posterGroup
}

func awaitSignals(ss ...io.Closer) {
	sigCh := make(chan os.Signal)
	signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
	sig := <-sigCh
	log.Printf("Got signal: %q", sig)
	for _, s := range ss {
		s.Close()
	}
}

func awaitShutdown(shutdownChan shutdownChan, server *server, posterGroup *sync.WaitGroup) {
	<-shutdownChan
	log.Printf("waiting for inflight requests to finish.")
	server.Wait()
	posterGroup.Wait()
	log.Printf("Shutdown complete.")
}

func newClientFunc() *http.Client {
	if os.Getenv("INFLUXDB_INSECURE") == "true" {
		return &http.Client{Timeout: defaultClientTimeout}
	}

	return &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: os.Getenv("INFLUXDB_SKIP_VERIFY") == "true"},
		},
		Timeout: defaultClientTimeout,
	}
}

func main() {
	hashRing, destinations, posterGroup := createMessageRoutes(os.Getenv("INFLUXDB_HOSTS"), newClientFunc)

	if os.Getenv("LIBRATO_TOKEN") != "" {
		go librato.Librato(
			metrics.DefaultRegistry,
			20*time.Second,
			os.Getenv("LIBRATO_OWNER"),
			os.Getenv("LIBRATO_TOKEN"),
			os.Getenv("LIBRATO_SOURCE"),
			[]float64{0.50, 0.95, 0.99},
			time.Millisecond,
		)
	} else if os.Getenv("DEBUG") == "true" {
		go metrics.Log(metrics.DefaultRegistry, 20e9, log.New(os.Stderr, "metrics: ", log.Lmicroseconds))
	}

	basicAuther, err := auth.NewBasicAuthFromString(os.Getenv("CRED_STORE"))
	if err != nil {
		log.Fatalf("Unable to parse credentials from CRED_STORE=%q: err=%q", os.Getenv("CRED_STORE"), err)
	}

	shutdownChan := make(shutdownChan)
	server := newServer(&http.Server{Addr: ":" + os.Getenv("PORT")}, basicAuther, hashRing)

	log.Printf("Starting up")
	go server.Run(5 * time.Minute)

	var closers []io.Closer
	closers = append(closers, server)
	closers = append(closers, shutdownChan)
	for _, cls := range destinations {
		closers = append(closers, cls)
	}

	go awaitSignals(closers...)
	awaitShutdown(shutdownChan, server, posterGroup)
}

repository: heroku/lumbermill

repo_name: heroku/lumbermill


text:
package main

import (
	"github.com/gossamer-irc/lib"
	"strings"
)

type PendingClient struct {
	Ircd   *Ircd
	Conn   *IrcConnection
	Subnet *lib.Subnet
	Nick   string
	Ident  string
	Gecos  string
	Host   string
}

func NewPendingClient(ircd *Ircd, conn *IrcConnection, subnet *lib.Subnet, host string) *PendingClient {
	return &PendingClient{
		Ircd:   ircd,
		Subnet: subnet,
		Conn:   conn,
		Host:   host,
	}
}

func (pc *PendingClient) Handle(raw IrcClientMessage) {
	switch msg := raw.(type) {
	case *InvalidIrcClientMessage:
		break
	case *NickIrcClientMessage:
		// Check whether this nick is taken.
		lnick := strings.ToLower(msg.Nick)
		_, found := pc.Subnet.Client[lnick]
		if found {
			pc.Conn.Send(&IrcNickInUse{msg.Nick})
			return
		}
		pc.Nick = msg.Nick
		pc.CheckReady()
		break
	case *UserIrcClientMessage:
		pc.Ident = msg.Ident
		pc.Gecos = msg.Gecos
		pc.CheckReady()
		break
	}
}

func (pc *PendingClient) CheckReady() {
	if pc.Nick == "" || pc.Ident == "" || pc.Gecos == "" {
		return
	}
	lnick := strings.ToLower(pc.Nick)
	_, found := pc.Subnet.Client[lnick]
	if found {
		pc.Conn.Send(&IrcNickInUse{pc.Nick})
		pc.Nick = ""
		return
	}
	pc.Ircd.AcceptPendingClient(pc)
}

repository: gossamer-irc/daemon

repo_name: gossamer-irc/daemon


text:
package main

import (
	"encoding/json"
	"net/http"
	"reflect"
	"strings"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/go-errors/errors"
)

func recoverHandler(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				log.WithField("error", err).Warn("Recovered from error")
				log.Error(errors.Wrap(err, 2).ErrorStack())
				writeError(w, ErrInternalServer)
			}
		}()

		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

type loggingResponseWriter struct {
	http.ResponseWriter
	status int
}

func (l *loggingResponseWriter) WriteHeader(status int) {
	l.status = status
	l.ResponseWriter.WriteHeader(status)
}

func loggingHandler(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		lw := &loggingResponseWriter{w, 200}
		t1 := time.Now()
		next.ServeHTTP(lw, r)
		t2 := time.Now()
		log.Infof("[%s] %q %v %v", r.Method, r.URL.String(), lw.status, t2.Sub(t1))
	}

	return http.HandlerFunc(fn)
}

func acceptHandler(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if !strings.Contains(r.Header.Get("Accept"), "application/json") {
			log.Warn("Request without accept header received")
			writeError(w, ErrNotAcceptable)
			return
		}

		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

func contentTypeHandler(next http.Handler, contentType string) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		ct := r.Header.Get("Content-Type")
		if !strings.Contains(ct, contentType) {
			log.Warnf("Request without proper content type received. Got: %s, Expected: %s", ct, contentType)
			writeError(w, ErrUnsupportedMediaType)
			return
		}

		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

func jsonContentTypeHandler(next http.Handler) http.Handler {
	return contentTypeHandler(next, "application/json")
}

func bodyHandler(v interface{}) func(http.Handler) http.Handler {
	t := reflect.TypeOf(v)

	m := func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			val := reflect.New(t).Interface()
			err := json.NewDecoder(r.Body).Decode(val)

			if err != nil {
				log.WithFields(log.Fields{"body": r.Body, "err": err}).Warn("Error handling body")
				writeError(w, ErrBadRequest)
				return
			}

			if next != nil {
				r = setRequestContext(r, contextBody, val)
				next.ServeHTTP(w, r)
			}
		}

		return http.HandlerFunc(fn)
	}

	return m
}

const (
	// xFrameOptionsHeader is the name of the x frame header
	xFrameOptionsHeader = `X-Frame-options`
)

// Handle Clickjacking protection
func clickjackingHandler(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set(xFrameOptionsHeader, "DENY")
		next.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}


text:
require recipes-bsp/u-boot/u-boot.inc

LICENSE = "GPL"

# No patches for other machines yet
COMPATIBLE_MACHINE = "allwinner-a10"

DEFAULT_PREFERENCE_allwinner-a10 = "1"

SRC_URI = "git://github.com/hno/uboot-allwinner.git;protocol=git;branch=sun4i \
          "

# 2012/05/31: Rename spl loader to sun4i-spl.bin for now
SRCREV = "e5eb03e7cd61ebcf552f6c809783d025786cdb24"
PR = "r1"

LIC_FILES_CHKSUM = "file://COPYING;md5=1707d6db1d42237583f50183a5651ecb"

S = "${WORKDIR}/git"

repository: baidala/meta-allwinner

repo_name: baidala/meta-allwinner


text:
// Copyright 2015 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package hack

import (
	"reflect"
	"unsafe"
)

// MutableString can be used as string via string(MutableString) without performance loss.
type MutableString string

// String converts slice to MutableString without copy.
// The MutableString can be converts to string without copy.
// Use it at your own risk.
func String(b []byte) MutableString {
	return *(*MutableString)(unsafe.Pointer(&b))
}

// Slice converts string to slice without copy.
// Use at your own risk.
func Slice(s string) (b []byte) {
	pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
	pbytes.Data = pstring.Data
	pbytes.Len = pstring.Len
	pbytes.Cap = pstring.Len
	return
}

repository: cosmtrek/tidb

repo_name: cosmtrek/tidb


text:
/*
** Copyright [2013-2017] [Megam Systems]
**
** 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
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
 */
package git

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

// DiscoverRepositoryPath finds the path of the repository from a given
// directory. It returns the path to the repository, or an an empty string and
// a non-nil error if it can't find the repository.
func DiscoverRepositoryPath(dir string) (string, error) {
	_, err := os.Stat(dir)
	if os.IsNotExist(err) {
		return "", errors.New("Repository not found.")
	}
	dir = filepath.Join(dir, ".git")
	for dir != "/.git" {
		fi, err := os.Stat(dir)
		if err == nil && fi.IsDir() {
			return dir, nil
		}
		dir = filepath.Join(dir, "..", "..", ".git")
	}
	return "", errors.New("Repository not found.")
}

// Repository represents a git repository.
type Repository struct {
	path string
}

// OpenRepository opens a repository by its filepath. You can use
// DiscoverRepositoryPath to discover the repository from any directory, and
// use the result of this call as parameter for OpenRepository.
//
// OpenRepository will return an error if the given path does not appear to be
// a git repository.
func OpenRepository(p string) (*Repository, error) {
	if !strings.HasSuffix(p, ".git") && !strings.HasSuffix(p, ".git/") {
		p = filepath.Join(p, ".git")
	}
	p = strings.TrimRight(p, "/")
	fi, err := os.Stat(filepath.Join(p, "config"))
	if err == nil && !fi.IsDir() {
		return &Repository{path: p}, nil
	}
	return nil, errors.New("Repository not found.")
}

// RemoteURL returns the URL of a remote by its name. Or an error, if the
// remote is not declared.
func (r *Repository) RemoteURL(name string) (string, error) {
	config, err := os.Open(filepath.Join(r.path, "config"))
	if err != nil {
		return "", err
	}
	defer config.Close()
	line := fmt.Sprintf("[remote %q]", name)
	scanner := bufio.NewScanner(config)
	scanner.Split(bufio.ScanLines)
	for scanner.Scan() {
		if scanner.Text() == line {
			scanner.Scan()
			return strings.Split(scanner.Text(), " = ")[1], nil
		}
	}
	return "", fmt.Errorf("Remote %q not found.", name)
}

repository: megamsys/vertice

repo_name: megamsys/vertice


text:
package service

import (
	"Miniprogram-server-Golang/model"
	"Miniprogram-server-Golang/serializer"

	"github.com/gin-gonic/gin"
)

//  管理用户注册服务
type CheckUserService struct {
	UserID string `form:"userid" json:"userid"`
	CorpID string `form:"corpid" json:"corpid"`
	UID    int    `form:"uid" json:"uid"`
	Token  string `form:"token" json:"token"`
}

// 用于检测用户标识是否已经被绑定
func (service *CheckUserService) CheckUser(c *gin.Context) serializer.Response {
	if !model.CheckToken(service.UID, service.Token) {
		return serializer.ParamErr("token验证错误", nil)
	}

	var depId int
	//	根据企业的标识码CorpID找到该企业信息对应的id
	if err := model.DB.QueryRow("select id from organization where corp_code = ?", service.CorpID).Scan(&depId); err != nil || depId == 0 {
		return serializer.Err(10006, "获取企业信息失败", nil)
	}

	var wxUid int
	//	根据企业id和用户信息，查找二者的绑定情况
	err := model.DB.QueryRow("select wx_uid from wx_mp_bind_info where org_id = ? and username = ? and isbind = ?", depId, service.UserID, 1).Scan(&wxUid)

	if err == nil {
		if wxUid == service.UID {
			//	待增加bind接口后修改isExist字段值
			return serializer.BuildUserCheckResponse(0, service.CorpID, service.UserID, 0)
		} else {
			return serializer.Err(100020, "该用户已被其他微信绑定，每个用户只能被一个微信绑定", nil)
		}
	}
	return serializer.BuildUserCheckResponse(0, service.CorpID, service.UserID, 0)
}


text:
package acl

import (
	"sync"
)

const (
	//RSA Super admin right
	RSA = 0
	//RUser auth user right
	RUser = 9
	//RGuest unauth user right
	RGuest = 99

	//ResGuestPages resource for guest
	ResGuestPages = 1
	//ResUserPages resource for auth user
	ResUserPages = 2

	//ACreate create access
	ACreate = 1
	//ARead read access
	ARead = 2
	//AUpdate update access
	AUpdate = 4
	//ADelete delete access
	ADelete = 8
)

type ActionAccess map[int]int

type ResourceAccess map[int][]int

type AccessRegister struct {
	mu             sync.RWMutex
	actionAccess   map[string]map[string]ActionAccess
	resourceAccess map[int]ResourceAccess
}

func (ar *AccessRegister) AddActionAccess(controllerName, actionName string, actionAccess ActionAccess) {
	ar.mu.Lock()
	defer ar.mu.Unlock()

	aa := make(map[string]ActionAccess)
	aa[actionName] = actionAccess
	ar.actionAccess[controllerName] = aa
}

func (ar *AccessRegister) AddResourceAccess(resourceType int, resourceAccess ResourceAccess) {
	ar.mu.Lock()
	defer ar.mu.Unlock()
	ar.resourceAccess[resourceType] = resourceAccess
}

func (ar *AccessRegister) GetActionAccesses() map[string]map[string]ActionAccess {
	ar.mu.RLock()
	defer ar.mu.RUnlock()
	return ar.actionAccess
}

func (ar *AccessRegister) GetResourceAccesses() map[int]ResourceAccess {
	ar.mu.RLock()
	defer ar.mu.RUnlock()
	return ar.resourceAccess
}

repository: vvasystem/go-acl

repo_name: vvasystem/go-acl


text:
@misc{konigsbergwikipedia,
    author    = "Wikipedia",
    title     = "Seven Bridges of Königsberg",
    url       = "https://en.wikipedia.org/wiki/Seven_Bridges_of_K%C3%B6nigsberg"
}

@article{euleroriginal,
    address = {http://www.math.dartmouth.edu/\~{}euler/docs/originals/E053.pdf},
    author = {Euler, Leonard},
    citeulike-article-id = {9589611},
    citeulike-linkout-0 = {http://www.math.dartmouth.edu/\~{}euler/pages/E053.html},
    journal = {Commentarii academiae scientiarum Petropolitanae},
    keywords = {theory},
    pages = {128--140},
    posted-at = {2011-07-27 22:24:46},
    priority = {2},
    title = {{Solutio problematis ad geometriam situs pertinentis}},
    url = {http://www.math.dartmouth.edu/\~{}euler/pages/E053.html},
    volume = {8},
    year = {1741}
}

repository: graph-theory/problem-konigsberg

repo_name: graph-theory/problem-konigsberg


text:
package xds

import (
	"context"
	"time"

	mesh_proto "github.com/kumahq/kuma/api/mesh/v1alpha1"
	core_mesh "github.com/kumahq/kuma/pkg/core/resources/apis/mesh"
	"github.com/kumahq/kuma/pkg/core/resources/model"
	core_xds "github.com/kumahq/kuma/pkg/core/xds"
	"github.com/kumahq/kuma/pkg/xds/secrets"
)

var TestSecretsInfo = &secrets.Info{
	Expiration: time.Unix(2, 2),
	Generation: time.Unix(1, 1),
	Tags: map[string]map[string]bool{
		"kuma.io/service": {
			"web": true,
		},
	},
	OwnMesh: secrets.MeshInfo{
		MTLS: &mesh_proto.Mesh_Mtls{
			EnabledBackend: "ca-1",
			Backends:       nil,
		},
	},
	IssuedBackend:     "ca-1",
	SupportedBackends: []string{"ca-1"},
}

type TestSecrets struct {
	GeneratedMeshCAs map[string]struct{}
}

func (ts *TestSecrets) get(meshes []*core_mesh.MeshResource) (*core_xds.IdentitySecret, map[string]*core_xds.CaSecret, *core_xds.CaSecret) {
	identitySecret := &core_xds.IdentitySecret{
		PemCerts: [][]byte{
			[]byte("CERT"),
		},
		PemKey: []byte("KEY"),
	}

	cas := map[string]*core_xds.CaSecret{}
	for _, mesh := range meshes {
		if ts.GeneratedMeshCAs == nil {
			ts.GeneratedMeshCAs = map[string]struct{}{}
		}
		ts.GeneratedMeshCAs[mesh.GetMeta().GetName()] = struct{}{}

		cas[mesh.GetMeta().GetName()] = &core_xds.CaSecret{
			PemCerts: [][]byte{
				[]byte("CA"),
			},
		}
	}

	allInOne := &core_xds.CaSecret{
		PemCerts: [][]byte{
			[]byte("combined"),
		},
	}

	return identitySecret, cas, allInOne
}

func (ts *TestSecrets) GetForZoneEgress(
	_ context.Context,
	_ *core_mesh.ZoneEgressResource,
	mesh *core_mesh.MeshResource,
) (*core_xds.IdentitySecret, *core_xds.CaSecret, error) {
	identity, cas, _ := ts.get([]*core_mesh.MeshResource{mesh})

	return identity, cas[mesh.GetMeta().GetName()], nil
}

func (ts *TestSecrets) GetForDataPlane(
	_ context.Context,
	_ *core_mesh.DataplaneResource,
	mesh *core_mesh.MeshResource,
	meshes []*core_mesh.MeshResource,
) (*core_xds.IdentitySecret, map[string]*core_xds.CaSecret, error) {
	identity, cas, _ := ts.get(append([]*core_mesh.MeshResource{mesh}, meshes...))
	return identity, cas, nil
}

func (ts *TestSecrets) GetAllInOne(
	_ context.Context,
	mesh *core_mesh.MeshResource,
	_ *core_mesh.DataplaneResource,
	meshes []*core_mesh.MeshResource,
) (*core_xds.IdentitySecret, *core_xds.CaSecret, error) {
	identity, _, allInOne := ts.get(append([]*core_mesh.MeshResource{mesh}, meshes...))
	return identity, allInOne, nil
}

func (*TestSecrets) Info(model.ResourceKey) *secrets.Info {
	return TestSecretsInfo
}

func (*TestSecrets) Cleanup(model.ResourceKey) {
}

var _ secrets.Secrets = &TestSecrets{}

repository: kumahq/kuma

repo_name: kumahq/kuma


text:
#ifndef OBJECTEXTRACTOR_H
#define OBJECTEXTRACTOR_H

#include <ros/ros.h>

#include <pcl_conversions/pcl_conversions.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/passthrough.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/keyboard_event.h>

#include <vtkRenderWindow.h>
#include <pcl/search/kdtree.h>
#include <pcl/segmentation/extract_clusters.h>
#include <pcl/common/time.h>

#include <pcl/cloud_iterator.h>
#include <pcl/common/centroid.h>
#include <pcl/common/distances.h>

#include <pcl_ros/point_cloud.h>
#include <sensor_msgs/Image.h>
#include <std_msgs/UInt32MultiArray.h>
#include <std_msgs/String.h>
#include <boost/thread/mutex.hpp>
#include <stdio.h>
#include <stdlib.h>

#include <tf/transform_datatypes.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <tf/transform_broadcaster.h>

#include<object_recognition.h>
#include <fileAPI.h>

class ObjectExtractor{
public:

    typedef pcl::PointXYZRGB PointT;

    //Methods
    ObjectExtractor(bool showViewer, ros::NodeHandle p_nh);
    void extraction_callback(const pcl::PCLPointCloud2ConstPtr& input);
    bool get_showUI();
    void set_showUI(bool show);
    void toggle_showUI();
    Eigen::Vector4f getGraspCentroid();
    pcl::PointCloud<PointT>::Ptr getObjectToGrasp();
    void setObjectToGrasp(pcl::PointCloud<PointT>::Ptr grasp_cloud);
    tf::StampedTransform getCentroidPositionRGBFrame();

    void callback_rgb_camera(const sensor_msgs::Image& p_input);
    Eigen::Matrix<float,4,1> compute_centroid_point(const pcl::PointCloud<PointT>& p_point_cloud);
    float compute_distance_from_kinect(Eigen::Matrix<float, 4, 1> p_matrix);
    void point_cloud_limit_finder (Eigen::Matrix<float, 4, 1> p_matrix, pcl::PointCloud<PointT>::Ptr p_ptr);
    void find_corner(const PointT& p_left, const PointT& p_right, const PointT& p_top, const PointT& p_bottom, pcl::PointCloud<PointT>::Ptr& p_point_cloud_output);
    Eigen::Matrix<float,4,1> projection2d_matrix(const Eigen::Matrix<float,4,1>& p_matrix);
    void projection2d_pointCloud(const pcl::PointCloud<PointT>& p_point_cloud, std::vector<pcl::PointCloud<PointT>::Ptr>& p_vector_output);
    void change_pixel_color(std::vector<unsigned char>& p_array, int p_x, int p_y, int p_b = 255, int p_g = 0, int p_r = 0);
    void draw_square(std::vector<unsigned char>& p_array, PointT p_top_left, PointT p_top_right, PointT p_bottom_left, PointT p_bottom_right);
    void paddingCorner(pcl::PointCloud<PointT>::Ptr p_memoryCloud_ptr, pcl::PointCloud<PointT>::Ptr p_cloud_ptr, int p_distance);
    void image_processing(pcl::PointCloud<PointT>::Ptr p_point_cloud_corner, sensor_msgs::Image& p_image_input);
    int position_finder_vector(const float p_coordinate[], const pcl::PointCloud<PointT>& p_point_cloud_corner, const std::vector<float> p_distance_vector);

    pcl::PointCloud<PointT>::Ptr coordinate_processing(const float p_coordinate[]);
    void point_cloud_processing();

    void spin_once();

    void publishToAndroidDevice(std::string message);

    void takeSnapshotAndScreenshot();

    // Variables
    boost::shared_ptr<pcl::visualization::PCLVisualizer> pclViewer;
    Object_recognition m_object_recognition;
    std::vector<pcl::PointCloud<PointT>::Ptr> object_vector;
    pcl::PointCloud<PointT>::Ptr m_transform_pc;

    bool save_object_to_DB_FLAG;

private:
    // Methods
    void printToPCLViewer();
    void keyboard_callback (const pcl::visualization::KeyboardEvent &event, void* viewer_void);
    std::vector<pcl::PointCloud<PointT>::Ptr> segment_objects(pcl::PointCloud<PointT>::Ptr cloud_input, double tolerance, int minClusterSize, int maxClusterSize);
    pcl::PointCloud<PointT>::Ptr extract_object_from_indices(pcl::PointCloud<PointT>::Ptr cloud_input,pcl::PointIndices object_indices);
    void setPCLViewer();
    void refreshObjectCentroid();

    bool distancePadding(PointT p_point, PointT p_mPoint, int p_distance);

    // Variables
    pcl::PointCloud<PointT>::Ptr cloud;

    pcl::PointCloud<PointT>::Ptr object_to_grasp;
    pcl::PointCloud<PointT>::Ptr tracked_object_centroid;
    int index_to_grasp;
    bool initialize_object_to_grasp;
    bool showUI;
    int l_count;

    ros::Publisher m_pub_image;
    ros::Publisher m_pub_android;

    std::vector<pcl::PointCloud<PointT>::Ptr> m_object_vector_2d;
    pcl::PointCloud<PointT> m_corner_cloud;
    pcl::PointCloud<PointT>::Ptr m_point_cloud_corner_ptr;

    std::vector<pcl::PointCloud<PointT>::Ptr> m_memory_point_cloud;
    pcl::PointCloud<PointT>::Ptr m_memory_point_cloud_corner_ptr;
    bool m_point_cloud_received;
    bool m_coordinate_received;
    float m_coordinate_user_sended[2];
    std::vector<float> m_memory_distance_vector;
    std::vector<float> m_distance_vector;
    sensor_msgs::Image m_image_received_input;
    sensor_msgs::Image m_image_memory;

    int NumberOfSnapshots;
    std::string directory;

};

#endif

extension: h


text:
package commands

import (
	"fmt"

	"github.com/talesmud/talesmud/pkg/mudserver/game/def"
	"github.com/talesmud/talesmud/pkg/mudserver/game/messages"
)

// ListCharactersCommand ... foo
type ListCharactersCommand struct {
}

// Key ...
func (command *ListCharactersCommand) Key() CommandKey { return &ExactCommandKey{} }

// Execute ... executes scream command
func (command *ListCharactersCommand) Execute(game def.GameCtrl, message *messages.Message) bool {

	if characters, err := game.GetFacade().CharactersService().FindAllForUser(message.FromUser.ID); err == nil {

		result := "Your Characters:\n"

		for _, character := range characters {
			result += fmt.Sprintf("- %v [LVL %v %v %vxp] %v - %v\n", character.Name, character.Level, character.Class.Name, character.XP, character.Race.Name, character.Description)
		}
		result += "To select character use: sc [charactername]"

		game.SendMessage() <- messages.Reply(message.FromUser.ID, result)

	} else {
		game.SendMessage() <- messages.Reply(message.FromUser.ID, "You have no characters.")
	}

	return true
}

repository: berkeleynerd/talesmud

repo_name: berkeleynerd/talesmud


text:
@article{Martin-2018-Prioritizing,
    title = "Prioritizing recovery funding to maximize conservation of endangered species",
    author = "Martin, Tara G.  and
      Kehoe, Laura  and
      Mantyka-Pringle, Chrystal  and
      Chades, Iadine  and
      Wilson, Scott  and
      Bloom, Robin G.  and
      Davis, Stephen K.  and
      Fisher, Ryan  and
      Keith, Jeff  and
      Mehl, Katherine  and
      Diaz, Beatriz Prieto  and
      Wayland, Mark E.  and
      Wellicome, Troy I.  and
      Zimmer, Karl P.  and
      Smith, Paul A.",
    journal = "Conservation Letters, Volume 11, Issue 6",
    volume = "11",
    number = "6",
    year = "2018",
    publisher = "Wiley",
    url = "https://aclanthology.org/G18-79001",
    doi = "10.1111/conl.12604",
    pages = "e12604",
}

repository: gwf-uwaterloo/gwf-publications

repo_name: gwf-uwaterloo/gwf-publications

branch_name: refs/heads/main

gha_language: Python


text:
require recipes-core/images/core-image-minimal.bb

SUMMARY = "A console-only image that fully supports the target device \
hardware."

LICENSE = "MIT"

IMAGE_INSTALL += "\
    useradd-ertza \
    base-files \
    ertza \
    opkg \
    opkg-config \
    ntp \
"
###     ertza

#IMAGE_INSTALL_remove = " packagegroup-base-extended psplash-default"

IMAGE_FEATURES_append = " package-management read-only-rootfs"

IMAGE_LINGUAS = " "

LICENSE = "MIT"

IMAGE_ROOTFS_SIZE ?= "2097152"

CORE_IMAGE_EXTRA_INSTALL += "kernel-modules kernel-devicetree dropbear"

DISTRO_FEATURES_remove = "alsa x11 nfs bluetooth wifi opengl pulseaudio 3g irda tk"
#MACHINE_FEATURES_remove = "alsa x11 nfs nfc bluetooth wifi opengl wayland pulseaudio 3g irda"

#DISTRO_FEATURES_append = " serial usbnet"
DISTRO_FEATURES_append = "tsp65217"

CONMANPKGS_remove = "connman-plugin-wifi"

IPK_FEED_URIS = "http://pkg.exmachina.fr/beaglebone"

ROOTFS_POSTPROCESS_COMMAND += "set_root_passwd;"

set_root_passwd() {
    _passwd='$6$ORUv90Oe$3uFnMJDJFskNrkQWVbh1nv5TGB7a8xM3BVNwrJDK0i6W7WkrzO9chWxWvPkmuaUo3vZqnFnpgUPeWSH/bjChD/'
    sed "s%^root:[^:]*:%root:${_passwd}:%" \
        < ${IMAGE_ROOTFS}/etc/shadow \
        > ${IMAGE_ROOTFS}/etc/shadow.new;
    mv ${IMAGE_ROOTFS}/etc/shadow.new ${IMAGE_ROOTFS}/etc/shadow ;

    sed "s%^root:[^:]*:%root:x:%" \
        < ${IMAGE_ROOTFS}/etc/passwd \
        > ${IMAGE_ROOTFS}/etc/passwd.new;
    mv ${IMAGE_ROOTFS}/etc/passwd.new ${IMAGE_ROOTFS}/etc/passwd ;
}

export IMAGE_BASENAME = "core-image-ertza"

repository: exmachina-dev/meta-exm-core

repo_name: exmachina-dev/meta-exm-core


text:
@article{Harrison2019,
 abstract = {Fall armyworm (FAW), a voracious agricultural pest native to North and South America, was first detected on the African continent in 2016 and has subsequently spread throughout the continent and across Asia. It has been predicted that FAW could cause up to \$US13 billion per annum in crop losses throughout sub-Saharan Africa, thereby threatening the livelihoods of millions of poor farmers. In their haste to respond to FAW governments may promote indiscriminate use of chemical pesticides which, aside from human health and environmental risks, could undermine smallholder pest management strategies that depend to a large degree on natural enemies. Agro-ecological approaches offer culturally appropriate low-cost pest control strategies that can be readily in- tegrated into existing efforts to improve smallholder incomes and resilience through sustainable intensification. Such approaches should therefore be promoted as a core component of integrated pest management (IPM) programmes for FAW in combination with crop breeding for pest resistance, classical biological control and selective use of safe pesticides. Nonetheless, the suitability of agro-ecological measures for reducing FAW densities and impact need to be carefully assessed across varied environmental and socio-economic conditions before they can be proposed for wide-scale implementation. To support this process, we review evidence for the efficacy of potential agro-ecological measures for controlling FAW and other pests, consider the associated risks, and draw attention to critical knowledge gaps. The evidence indicates that several measures can be adopted immediately. These include (i) sustainable soil fertility management, especially measures that maintain or re- store soil organic carbon; (ii) intercropping with appropriately selected companion plants; and (iii) diversifying the farm environment through management of (semi)natural habitats at multiple spatial scales. Nevertheless, we recommend embedding trials into upscaling programmes so that the costs and benefits of these interventions may be determined across the diverse biophysical and socio-economic contexts that are found in the invaded range.},
 author = {Harrison, Rhett D and Thierfelder, Christian and Baudron, Frédéric and Chinwada, Peter and Midega, Charles and Schaffner, Urs and van den Burg, Johnnei},
 file = {:C$\backslash$:/Users/FBaudron/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Harrison et al. - Unknown - Agro-ecological options for Fall Armyworm (Spodoptera frugiperda Smith) management in sub-Saharan Africa Pro.pdf:pdf},
 journal = {Journal of Environmental Management},
 keywords = {IPM,biodiversity,biological control,climate smart agriculture,conservation agriculture,corn,natural enemies,no-till,push-pull,sustainable development,sustainable land management},
 pages = {318--330},
 title = {Agro-ecological options for fall armyworm (Spodoptera frugiperda Smith) management in sub-Saharan Africa: Providing low-cost, smallholder friendly solutions to an invasive pest},
 volume = {243},
 year = {2019}
}

repository: FBaudron/starter-academic

repo_name: FBaudron/starter-academic


text:
package api_test

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math/big"
	"os"
	"reflect"
	"strconv"
	"strings"
	"testing"
	"time"

	"github.com/AlekSi/pointer"
	"github.com/DATA-DOG/go-sqlmock"
	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/crypto"
	"gopkg.in/reform.v1"

	"github.com/dzeckelev/geth-wrapper/api"
	"github.com/dzeckelev/geth-wrapper/data"
	"github.com/dzeckelev/geth-wrapper/db"
	"github.com/dzeckelev/geth-wrapper/eth"
	"github.com/dzeckelev/geth-wrapper/gen"
)

const gasLimit uint64 = 4700000

var (
	ethClient *eth.MockClient
	columns   = []string{"o_id", "o_hash", "o_from", "o_to", "o_amount",
		"o_status", "o_block", "o_timestamp", "o_marked", "o_confirmations"}
	network = big.NewInt(4)
)

func genNewAccount() *bind.TransactOpts {
	key, _ := crypto.GenerateKey()
	return bind.NewKeyedTransactor(key)
}

func newEthClient() *eth.MockClient {
	opts := genNewAccount()
	addr := strings.ToLower(opts.From.String())

	balance := "1000000000000000000000000000000000000000000000000000"
	b1 := new(big.Int)
	_, _ = fmt.Sscan(balance, b1)

	alloc := make(core.GenesisAlloc)
	alloc[opts.From] = core.GenesisAccount{Balance: b1}
	sim := backends.NewSimulatedBackend(alloc, gasLimit)

	return &eth.MockClient{
		Acc:     map[string]*bind.TransactOpts{addr: opts},
		NetID:   big.NewInt(4),
		Block:   nil,
		Backend: sim,
	}
}

func newDB(t *testing.T) (*reform.DB, sqlmock.Sqlmock) {
	sqlDB, sqlMock, err := sqlmock.New()
	if err != nil {
		t.Fatal(err)
	}

	dataBase, err := db.NewDB(sqlDB)
	if err != nil {
		t.Fatal(err)
	}
	return dataBase, sqlMock
}

func newTestTx() *data.Transaction {
	hash := "0x64e604787cbf194841e7b68d7cd28786f6c9a0a3ab9f8b0a0e87cb4387ab0107"
	from := "0xe7dc9fe68da458b54f648146a817126053eeef66"
	to := "0xa7dba6053a0d631177340e8061bc12f5009ba453"
	amount := strconv.Itoa(10000)
	status := pointer.ToString(data.TxSuccessful)
	block := pointer.ToUint64(123456)
	timestamp := pointer.ToUint64(777777)
	confirmations := uint64(1)

	return &data.Transaction{
		ID:            gen.NewUUID(),
		Hash:          hash,
		From:          from,
		To:            to,
		Amount:        amount,
		Status:        status,
		Block:         block,
		Timestamp:     timestamp,
		Confirmations: confirmations,
	}
}

func createTestTxs(num int) (result []*data.Transaction) {
	for i := 0; i < num; i++ {
		result = append(result, newTestTx())
	}
	return result
}

func toRow(tx *data.Transaction) (result []driver.Value) {
	result = make([]driver.Value, len(tx.Values()))

	for k, v := range tx.Values() {
		result[k] = v
	}

	return result
}

func checkFiled(t *testing.T, exp, got interface{}) {
	if !reflect.DeepEqual(exp, got) {
		t.Fatalf("expected %v, got %v", exp, got)
	}
}

func checkDate(t *testing.T, str string, timestamp *uint64) {
	if timestamp != nil {
		tm := time.Unix(int64(*timestamp), 0)
		if !reflect.DeepEqual(tm.Format(time.RFC3339), str) {
			t.Fatalf("expected %v, got %v", tm.Format(time.RFC3339), str)
		}
	}
}

func checkGetLast(t *testing.T, handler *api.Handler,
	limit uint64, expected int) []api.GetLastResult {
	result, err := handler.GetLast(limit)
	if err != nil {
		t.Fatal(err)
	}

	if len(result) != expected {
		t.Fatalf("expected %v, got %v", expected, len(result))
	}

	return result
}

func TestGetLast(t *testing.T) {
	dataBase, sqlMock := newDB(t)
	handler := api.NewHandler(network, dataBase, ethClient, nil)

	limit := uint64(100)
	confirmations := uint64(3)

	txs := createTestTxs(2)

	expSelectSQL := `SELECT (.+) FROM "transactions"`
	expUpdateSQL := `UPDATE "transactions"`

	// Empty result.
	sqlMock.ExpectQuery(expSelectSQL).
		WithArgs(confirmations, limit).WillReturnRows(sqlmock.NewRows(columns))

	checkGetLast(t, handler, limit, 0)

	// Normal test.
	sqlMock.ExpectQuery(expSelectSQL).
		WithArgs(confirmations, limit).WillReturnRows(sqlmock.NewRows(columns).
		AddRow(toRow(txs[0])...).AddRow(toRow(txs[1])...))

	for range txs {
		sqlMock.ExpectExec(expUpdateSQL).
			WillReturnResult(sqlmock.NewResult(1, 1))
	}

	result := checkGetLast(t, handler, limit, 2)

	for k := range result {
		checkFiled(t, result[k].Confirmations, txs[k].Confirmations)
		checkFiled(t, result[k].Amount, txs[k].Amount)
		checkFiled(t, result[k].Hash, txs[k].Hash)
		checkFiled(t, result[k].Address, txs[k].To)
		checkDate(t, result[k].Date, txs[k].Timestamp)
	}

	if err := sqlMock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expectations: %s", err)
	}
}

func TestHandlerSendETH(t *testing.T) {
	dataBase, sqlMock := newDB(t)
	handler := api.NewHandler(network, dataBase, ethClient, gen.NewUUID)

	accounts, err := ethClient.Accounts(context.Background())
	if err != nil {
		t.Fatal(err)
	}

	opts := genNewAccount()
	to := strings.ToLower(opts.From.String())

	expUpdateSQL := `UPDATE "outputs"`

	sqlMock.ExpectExec(expUpdateSQL).
		WillReturnResult(sqlmock.NewResult(1, 1))

	hash, err := handler.SendETH(accounts[0], to, "10000")
	if err != nil {
		t.Fatal(err)
	}

	if err := sqlMock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expectations: %s", err)
	}

	_, err = hexutil.Decode(*hash)
	if err != nil {
		t.Fatal(err)
	}
}

func TestMain(m *testing.M) {
	ethClient = newEthClient()
	os.Exit(m.Run())
}

repository: dzeckelev/geth-wrapper

repo_name: dzeckelev/geth-wrapper


text:
SUMMARY = "FreeRADIUS Server"
HOMEPAGE = "http://wiki.freeradius.org"
LICENSE = "GPLv2"

LIC_FILES_CHKSUM = "file://COPYRIGHT;md5=8271badacbbc8d1e3c62027d15cd176d"

SRC_URI = "ftp://ftp.freeradius.org/pub/freeradius/${PN}-${PV}.tar.bz2 \
           file://0001-Fix-cross-compile.patch \
           "

SRC_URI[md5sum] = "59427bd3cc2ebd5ad62ee9dcc7d943c5"
SRC_URI[sha256sum] = "b89721c609e5a106936112fe8122e470f02a5197bb614e202d2c386f4821d902"

DEPENDS = "talloc libpcre libpcap openssl"

EXTRA_OECONF += "--disable-static --with-pcre-include-dir=${STAGING_INCDIR} \
"

CACHED_CONFIGUREVARS = "ax_cv_cc_builtin_choose_expr=yes \
 ax_cv_cc_builtin_types_compatible_p=yes ax_cv_cc_builtin_bswap64=yes \
 ax_cv_cc_bounded_attribute=yes \
 ac_cv_lib_collectdclient_lcc_connect=no \
 ac_cv_lib_execinfo_backtrace_symbols=yes \
"

do_configure_append() {
    cd ${B}
    make reconfig

    parentdir=`pwd`
    mysubdirs="$mysubdirs `find src/modules/ -name configure.ac -print | sed 's%/configure.ac%%'`"
    mysubdirs=`echo $mysubdirs`

    for F in $mysubdirs
    do
            echo "Configuring in $F..."
            (cd $F && grep "^AC_CONFIG_HEADER" configure.ac > /dev/null || exit 0; autoheader -I$parentdir)
            (cd $F && autoconf -I$parentdir)
    done
}

inherit autotools-brokensep systemd

repository: billyjbryant/ops-build

repo_name: billyjbryant/ops-build


text:
@inproceedings{zhou2020vlp,
  title={Unified Vision-Language Pre-Training for Image Captioning and VQA},
  author={Luowei Zhou, Hamid Palangi, Lei Zhang, Houdong Hu, Jason J. Corso, Jianfeng Gao},
  booktitle={AAAI},
  year={2020}
}

url: https://raw.githubusercontent.com/Hugh-Shi/DL-NLP-Readings/924e4d189e5660c5b5d4854278f3df755ae2231d/Bibtex/Unified Vision-Language Pre-Training for Image Captioning and VQA.bib

repository: Hugh-Shi/DL-NLP-Readings

repo_name: Hugh-Shi/DL-NLP-Readings


text:
@article{Jones:1998,
    title={Efficient global optimization of expensive black-box functions},
    author={Jones, Donald R and Schonlau, Matthias and Welch, William J},
    journal={Journal of Global optimization},
    volume={13},
    number={4},
    pages={455--492},
    year={1998},
    publisher={Springer}
}

@inproceedings{Srinivas:2010,
    author = "Srinivas, Niranjan and Krause, Andreas and Seeger, Matthias and Kakade, Sham M.",
    booktitle = "{Proceedings of the 27th International Conference on Machine Learning (ICML-10)}",
    editor = "F{\"u}rnkranz, Johannes and Joachims, Thorsten",
    pages = "1015--1022",
    publisher = "Omnipress",
    title = "{Gaussian Process Optimization in the Bandit Setting: No Regret and Experimental Design}",
    year = "2010"
}

@inproceedings{gardner14,
    title={Bayesian Optimization with Inequality Constraints},
    author={Jacob Gardner and Matt Kusner and Zhixiang and Kilian Weinberger and John Cunningham},
    booktitle={Proceedings of the 31st International Conference on Machine Learning},
    year={2014},
    volume={32},
    number={2},
    series={Proceedings of Machine Learning Research},
    month={22--24 Jun},
    publisher={PMLR},
    url={http://proceedings.mlr.press/v32/gardner14.html},
}

@article{schonlau1998global,
    title={Global versus local search in constrained optimization of computer models},
    author={Schonlau, Matthias and Welch, William J and Jones, Donald R},
    journal={Lecture Notes-Monograph Series},
    pages={11--25},
    year={1998},
    publisher={JSTOR}
}

@Inbook{Ginsbourger2010,
    author="Ginsbourger, David and Le Riche, Rodolphe and Carraro, Laurent",
    editor="Tenne, Yoel and Goh, Chi-Keong",
    title="Kriging Is Well-Suited to Parallelize Optimization",
    bookTitle="Computational Intelligence in Expensive Optimization Problems",
    year="2010",
    publisher="Springer Berlin Heidelberg",
    address="Berlin, Heidelberg",
    pages="131--162",
    isbn="978-3-642-10701-6",
    doi="10.1007/978-3-642-10701-6_6",
    url="https://doi.org/10.1007/978-3-642-10701-6_6"
}

@article{Picheny2013,
    author = {Picheny, Victor and Wagner, Tobias and Ginsbourger, David},
    year = {2013},
    month = {09},
    pages = {},
    title = {A benchmark of kriging-based infill criteria for noisy optimization},
    volume = {48},
    journal = {Structural and Multidisciplinary Optimization},
    doi = {10.1007/s00158-013-0919-4}
}

repository: icouckuy/trieste

repo_name: icouckuy/trieste

branch_name: refs/heads/develop


text:
Summanry = "Red Hat Cluster"
DESCRIPTION = "Red Hat Cluster"
SECTION = "libs"
HOMEPAGE = "https://fedorahosted.org/cluster/wiki/HomePage"

SRC_URI = "https://releases.pagure.org/linux-cluster/cluster/${BP}.tar.xz \
           file://0001-Fix-the-kernel-source-patch.patch"

SRC_URI[md5sum] = "300d83dbbc525c3da21c2e961271c84b"
SRC_URI[sha256sum] = "4d340338c2376d369cb223469fa1a3356cce9ab5b2a0a0a33256ade2dbbe02d1"

LICENSE = "GPL-2.0 & LGPL-2.0"
LIC_FILES_CHKSUM = "file://doc/README.licence;md5=ee8ae43af5ea09f12ca7f7a649764cb0"

PR = "r1"

DEPENDS = "corosync dbus openldap libxml2 ncurses perl zlib"

FILES_${PN} += "/lib/udev/rules.d/51-dlm.rules \
    ${localstatedir}/run "
FILES_${PN}-doc += "/usr/share/man3/* /usr/share/man8/*"

do_configure () {
    CFLAGS="${TARGET_CFLAGS}"       \
    CCFLAGS="${TARGET_CFLAGS}"      \
    CXXFLAGS="${TARGET_CFLAGS}"     \
    ./configure \
        --without_rgmanager \
        --disable_kernel_check \
        --without_cman \
        --without_fence \
        --without_bindings \
        --without_group \
        --without_config \
        --without_common \
        --without_dlm \
        2>&1
}

do_compile () {
    pwd
    CFLAGS="${TARGET_CFLAGS}" \
    make libdir=${STAGING_LIBDIR} incdir=${STAGING_INCDIR}          \
    CC=${TARGET_SYS}-gcc
}
do_install () {
    rm -rf ${D}
    make install DESTDIR=${D} libdir=${D}/usr/lib sbindir=${D}/usr/sbin \
                 mandir=${D}/usr/share docdir=${D}/usr/share/doc

    ## tree fix up
    # /etc/sysconfig/cman
    mkdir -p ${D}/etc/sysconfig

    # logrotate name
    mv ${D}/etc/logrotate.d/cluster ${D}/etc/logrotate.d/cman
    # fix library permissions or strip helpers won't work.
    find ${D} -name "lib*.so.*" -exec chmod 0755 {} \;
    # fix lcrso permissions or strip helpers won't work.
    find ${D} -name "*.lcrso" -exec chmod 0755 {} \;
    # remove docs
    rm -rf ${D}${datadir}/doc/cluster
    rm -rf ${D}${localstatedir}/run
    rm -rf ${D}${localstatedir}/lib
    rm -rf ${D}${localstatedir}/log
    rmdir --ignore-fail-on-non-empty ${D}${localstatedir}
}

repository: Joleme/meta-cgl

repo_name: Joleme/meta-cgl


text:
package noko

import (
	"context"
	"fmt"
	"net/http"
	"time"
)

// ProjectSummary represents a abbreviated Noko project struct
type ProjectSummary struct {
	ID               int    `json:"id"`
	Name             string `json:"name"`
	BillingIncrement int    `json:"billing_increment"`
	Enabled          bool   `json:"enabled"`
	Billable         bool   `json:"billable"`
	Color            string `json:"color"`
	URL              string `json:"url"`
}

// Project represents a Noko project
type Project struct {
	ID                int           `json:"id"`
	Name              string        `json:"name"`
	BillingIncrement  int           `json:"billing_increment"`
	Enabled           bool          `json:"enabled"`
	Billable          bool          `json:"billable"`
	Color             string        `json:"color"`
	URL               string        `json:"url"`
	Group             Group         `json:"group"`
	Minutes           int           `json:"minutes"`
	BillableMinutes   int           `json:"billable_minutes"`
	UnbillableMinutes int           `json:"unbillable_minutes"`
	InvoicedMinutes   int           `json:"invoiced_minutes"`
	RemainingMinutes  int           `json:"remaining_minutes"`
	BudgetedMinutes   int           `json:"budgeted_minutes"`
	Import            Import        `json:"import"`
	Invoices          []Invoice     `json:"invoices"`
	Participants      []Participant `json:"participants"`
	Entries           int           `json:"entries"`
	EntriesURL        string        `json:"entries_url"`
	Expenses          int           `json:"expenses"`
	ExpensesURL       string        `json:"expenses_url"`
	CreatedAt         time.Time     `json:"created_at"`
	UpdatedAt         time.Time     `json:"updated_at"`
	MergeURL          string        `json:"merge_url"`
	ArchiveURL        string        `json:"archive_url"`
	UnarchiveURL      string        `json:"unarchive_url"`
}

// GetProjects will get all Noko projects
func (c *Client) GetProjects(ctx context.Context) ([]Project, error) {
	req, err := http.NewRequest("GET", fmt.Sprintf("%s/projects", c.BaseURL), nil)
	if err != nil {
		return nil, err
	}

	var projects []Project
	err = c.sendRequest(ctx, req, &projects)
	if err != nil {
		return nil, err
	}

	return projects, nil
}

repository: Raphexion/nina

repo_name: Raphexion/nina


text:
SUMMARY = "Simple wrapper script which proxies signals to a child"
HOMEPAGE = "https://github.com/Yelp/dumb-init/"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE;md5=5940d39995ea6857d01b8227109c2e9c"

SRC_URI = "https://github.com/Yelp/dumb-init/archive/v${PV}.tar.gz"
SRC_URI[md5sum] = "4eb7f43d7823686723ff7ac1bad097cb"
SRC_URI[sha256sum] = "74486997321bd939cad2ee6af030f481d39751bc9aa0ece84ed55f864e309a3f"

EXTRA_OEMAKE = "CC='${CC}' CFLAGS='${CFLAGS} ${LDFLAGS}'"

do_install() {
    install -d ${D}${base_sbindir}
    install ${S}/dumb-init ${D}${base_sbindir}/
}

repository: astarche/meta-openembedded

repo_name: astarche/meta-openembedded

branch_name: refs/heads/nilrt/master/sumo


text:
#include "material_component.h"
#include <fstream>
#include "../rabbit_profile.h"
#include "../rabbit_behaviour.h"
#include <qstring.h>
#include <quuid>
#include <octoon/game_base_features.h>
#include <filesystem>
#include <fstream>
#include <qimage.h>

namespace rabbit
{
	MaterialComponent::MaterialComponent() noexcept
	{
	}

	MaterialComponent::~MaterialComponent() noexcept
	{
	}

	void
	MaterialComponent::setActive(bool active) noexcept
	{
	}

	bool
	MaterialComponent::getActive() const noexcept
	{
		return true;
	}

	void
	MaterialComponent::onEnable() noexcept
	{
		try
		{
			std::ifstream ifs(this->getModel()->path + "/material.json");
			if (ifs)
			{
				auto uuids = nlohmann::json::parse(ifs);
				for (auto& uuid : uuids)
				{
					try
					{
						auto path = this->getModel()->path + "/" + uuid.get<nlohmann::json::string_t>() + "/data.json";
						this->initMaterials(path);
					}
					catch (...)
					{
					}
				}
			}
		}
		catch (...)
		{
		}
	}

	void
	MaterialComponent::onDisable() noexcept
	{
		std::ofstream ifs(this->getModel()->path + "/material.json");
		if (ifs)
		{
			nlohmann::json uuids;
			for (auto& mat : this->materialList_)
				uuids.push_back(mat.first);

			auto data = uuids.dump();
			ifs.write(data.c_str(), data.size());
		}
	}

	const std::map<std::string, nlohmann::json, std::less<>>&
	MaterialComponent::getMaterialList() const noexcept
	{
		return this->materialList_;
	}

	void
	MaterialComponent::loadMaterial(std::string_view mtlPath) noexcept(false)
	{
		std::ifstream stream(QString::fromStdString(std::string(mtlPath)).toStdWString());
		if (stream)
		{
			std::map<std::string, int> materialMap;
			std::vector<tinyobj::material_t> materials;
			auto err = tinyobj::LoadMtl(materialMap, materials, stream);
			auto dirpath = mtlPath.substr(0, mtlPath.find_last_of("/") + 1);

			this->initMaterials(materials, dirpath);
		}
	}

	const std::shared_ptr<octoon::material::Material>
	MaterialComponent::getMaterial(std::string_view uuid) noexcept
	{
		auto material = this->materials_.find(uuid);
		if (material == this->materials_.end())
		{
			auto it = this->materialList_.find(uuid);
			if (it != this->materialList_.end())
			{
				auto mat = (*it).second;

				auto standard = std::make_shared<octoon::material::MeshStandardMaterial>();
				standard->setName(mat["name"].get<nlohmann::json::string_t>());
				standard->setColor(octoon::math::float3::One);
				standard->setColorTexture(octoon::TextureLoader::load(mat["map"].get<nlohmann::json::string_t>()));

				this->materials_[std::string(uuid)] = standard;

				return standard;
			}
			else
			{
				return nullptr;
			}
		}
		else
		{
			return (*material).second;
		}
	}

	void
	MaterialComponent::initMaterials(std::string_view path)
	{
		std::ifstream ifs(path);
		if (ifs)
		{
			auto json = nlohmann::json::parse(ifs);
			this->materialList_[json["uuid"]] = json;
		}
	}

	void
	MaterialComponent::initMaterials(const std::vector<tinyobj::material_t>& materials, std::string_view rootPath)
	{
		for (auto& it : materials)
		{
			auto id = QUuid::createUuid().toString();
			auto uuid = id.toStdString().substr(1, id.length() - 2);
			auto path = this->getModel()->path + "/" + uuid;

			if (std::filesystem::create_directory(path))
			{
				try {
					auto from = QString::fromStdString(std::string(rootPath) + it.diffuse_texname).toStdWString();
					auto to = QString::fromStdString(path + "/" + it.diffuse_texname).toStdWString();
					std::filesystem::copy_file(from, to);
				}
				catch (std::filesystem::filesystem_error & e) {
					std::cout << "Could not copy sandbox/abc: " << e.what() << '\n';
				}

				std::ofstream ifs(path + "/data.json");
				if (ifs)
				{
					nlohmann::json item;
					item["uuid"] = uuid;
					item["name"] = it.name;
					item["color"] = { 1.0, 1.0, 1.0 };
					item["map"] = path + "/" + it.diffuse_texname;

					if (!item["map"].is_null()) {
						auto image = QImage();
						image.load(QString::fromStdString(std::string(rootPath) + it.diffuse_texname));
						image.scaled(QSize(130, 130)).save(QString::fromStdString(path + "/preview.jpeg"));

						item["preview"] = path + "/preview.jpeg";
					}

					auto data = item.dump();
					ifs.write(data.c_str(), data.size());

					this->materialList_[uuid] = item;
				}
			}
		}
	}

	void
	MaterialComponent::onDrop(std::string_view path) noexcept
	{
		auto ext = path.substr(path.find_last_of("."));
		if (ext == ".mtl")
			this->loadMaterial(path);
	}
}

extension: cpp


text:
@article{driscollAlgorithm756MATLAB1996,
 author = {Driscoll, Tobin A},
 doi = {10.1145/229473.229475},
 journal = {ACM Transactions on Mathematical Software (TOMS)},
 number = {2},
 pages = {168--186},
 title = {Algorithm 756: A MATLAB Toolbox for Schwarz-Christoffel Mapping},
 volume = {22},
 year = {1996}
}

repository: tobydriscoll/academic-kickstart

repo_name: tobydriscoll/academic-kickstart


text:
#----------------------------------------------------------------
# Generated CMake target import file for configuration "Debug".
#----------------------------------------------------------------

# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)

# Import target "bzrtp-static" for configuration "Debug"
set_property(TARGET bzrtp-static APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG)
set_target_properties(bzrtp-static PROPERTIES
  IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
  IMPORTED_LOCATION_DEBUG "${_IMPORT_PREFIX}/lib/libbzrtp.a"
  )

list(APPEND _IMPORT_CHECK_TARGETS bzrtp-static )
list(APPEND _IMPORT_CHECK_FILES_FOR_bzrtp-static "${_IMPORT_PREFIX}/lib/libbzrtp.a" )

# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)

repository: WorkerHuan/myTestLin

repo_name: WorkerHuan/myTestLin

extension: cmake


text:
package ts

import (
	"fmt"
	"math"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

type testSample struct {
	input       Datapoints
	expected    []float64
	start       time.Time
	end         time.Time
	interval    time.Duration
	hasNans     bool
	description string
}

func generateDatapoints(start time.Time, interval time.Duration, num int) Datapoints {
	dps := make(Datapoints, num)
	for i := 0; i < num; i++ {
		dps[i] = Datapoint{
			Timestamp: start.Add(interval * time.Duration(i)),
			Value:     float64(i),
		}
	}
	return dps
}

func createExamples() []testSample {
	now := time.Time{}
	samples := []testSample{
		{
			input:       generateDatapoints(now.Add(-5*time.Second), time.Second, 5),
			expected:    []float64{0, 1, 2, 3, 4},
			start:       now.Add(-5 * time.Second),
			end:         now,
			interval:    time.Second,
			description: "same resolution and times",
		},
		{
			input:       generateDatapoints(now.Add(-5*time.Second), 2*time.Second, 5),
			expected:    []float64{0, 0, 1, 1, 2},
			start:       now.Add(-5 * time.Second),
			end:         now,
			interval:    time.Second,
			description: "half interval than resolution, some datapoints would be repeated",
		},
		{
			input:       generateDatapoints(now.Add(-5*time.Second), time.Second, 5),
			expected:    []float64{0, 2},
			start:       now.Add(-5 * time.Second),
			end:         now,
			interval:    2 * time.Second,
			description: "twice interval than resolution, since datapoints are generated faster, we would skip some",
		},
		{
			input:       generateDatapoints(now.Add(time.Second), 2*time.Second, 5),
			expected:    []float64{1},
			start:       now.Add(3 * time.Second),
			end:         now.Add(3 * time.Second),
			interval:    time.Second,
			description: "when start and end are the same, take the value closest to start",
		},
		{
			input: generateDatapoints(now.Add(time.Second), 2*time.Second, 5),
			// start time after end time of datapoints so we get NaNs
			expected:    []float64{math.NaN(), math.NaN()},
			start:       now.Add(10 * time.Second),
			end:         now.Add(12 * time.Second),
			interval:    time.Second,
			hasNans:     true,
			description: "start time after end time of datapoints so we get NaNs",
		},
		{
			input:       generateDatapoints(now.Add(time.Second), 10*time.Second, 10),
			expected:    []float64{0, 0},
			start:       now,
			end:         now.Add(20 * time.Second),
			interval:    10 * time.Second,
			hasNans:     true,
			description: "first datapoint after start",
		},
	}
	return samples
}

func TestRawPointsToFixedStep(t *testing.T) {
	samples := createExamples()
	for idx, sample := range samples {
		fixdRes, err := RawPointsToFixedStep(sample.input, sample.start, sample.end, sample.interval)
		require.NoError(t, err)
		if !sample.hasNans {
			assert.Equal(t, fixdRes.(*fixedResolutionValues).values, sample.expected, "Datapoints: %s, description: %s", sample.input, sample.description)
			continue
		}

		// Need to handle nan case separately since assert cant compare nans, we prefer comparing the whole thing whenever possible since debugging is easier
		fixResValues := fixdRes.(*fixedResolutionValues)
		debugMsg := fmt.Sprintf("index: %d, converted %v, expected %v, description: %s", idx, fixResValues.values, sample.expected, sample.description)
		require.Len(t, fixResValues.values, len(sample.expected), debugMsg)
		for i, v := range sample.expected {
			if math.IsNaN(v) {
				require.True(t, math.IsNaN(fixResValues.values[i]), debugMsg)
			} else {
				require.Equal(t, v, fixResValues.values[i], debugMsg)
			}
		}
	}
}


text:
package ast

type Export struct {
	WithRange
	Value Node
	Name  string
}

func (n *Export) walkChildNodes(cb internalWalkFunc) {
	cb(n.Value)
}

repository: cirbo-lang/cirbo

repo_name: cirbo-lang/cirbo


text:
DESCRIPTION = "Rockchip RGA 2D graphics acceleration library"
SECTION = "libs"

LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://COPYING;md5=89aea4e17d99a7cacdbeed46a0096b10"

DEPENDS = "libdrm"

SRC_URI = " git://${EXTRA}/linux-rga;protocol=file;usehead=1"
SRCREV = "${AUTOREV}"
S = "${WORKDIR}/git"

inherit meson pkgconfig

EXTRA_OEMESON = "-Dlibdrm=true"

repository: ponmadasamy/meta-dealcore

repo_name: ponmadasamy/meta-dealcore


text:
// Copyright 2020 Anapaya Systems
//
// 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
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package xtest

import (
	"crypto"
	"crypto/x509"
	"encoding/pem"
	"os"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/scrypto/cppki"
)

// LoadChain loads a certificate chain from a file. The file must be PEM encoded.
func LoadChain(t *testing.T, file string) []*x509.Certificate {
	t.Helper()
	chain, err := cppki.ReadPEMCerts(file)
	require.NoError(t, err)
	return chain
}

// LoadSigner loads a private key from a file. The file must be PEM encoded.
func LoadSigner(t *testing.T, file string) crypto.Signer {
	t.Helper()
	raw, err := os.ReadFile(file)
	require.NoError(t, err)
	if block, _ := pem.Decode(raw); block != nil {
		raw = block.Bytes
	}

	key, err := x509.ParsePKCS8PrivateKey(raw)
	require.NoError(t, err)

	priv, ok := key.(crypto.Signer)
	require.True(t, ok)
	return priv
}

// LoadTRC loads a signed TRC from a file.
func LoadTRC(t *testing.T, file string) cppki.SignedTRC {
	t.Helper()
	raw, err := os.ReadFile(file)
	require.NoError(t, err)
	if block, _ := pem.Decode(raw); block != nil {
		raw = block.Bytes
	}
	trc, err := cppki.DecodeSignedTRC(raw)
	require.NoError(t, err)
	return trc
}

// MustExtractIA extracts the IA from the cert's subject and verifies it is
// non-nil. It is the callers responsibility to make sure that this is a cert
// that always contains an IA.
func MustExtractIA(t *testing.T, cert *x509.Certificate) addr.IA {
	ia, err := cppki.ExtractIA(cert.Subject)
	require.NoError(t, err)
	require.NotNil(t, ia)
	return ia
}

repository: netsec-ethz/scion

repo_name: netsec-ethz/scion

branch_name: refs/heads/scionlab


text:
@inproceedings{ICDM17,
 address = {},
 author = {Jingchao Ni and Wei Cheng and Kai Zhang and Dongjin Song and Tan Yan and Haifeng Chen and Xiang Zhang},
 booktitle = {Proceedings  of  IEEE International Conference on Data Mining (ICDM)},
 editor = {},
 month = {November},
 pages = {1,003-1,008},
 publisher = {},
 title = {Identifying  Multiple  Causal  Anomalies  by  Modeling  Local  Propagations},
 year = {2017}
}