text:
// Copyright 2022 TiKV Project Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, 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 schedulers

import (
	"testing"

	"github.com/docker/go-units"
	"github.com/stretchr/testify/require"
	"github.com/tikv/pd/pkg/mock/mockcluster"
	"github.com/tikv/pd/pkg/schedule/operator"
	"github.com/tikv/pd/pkg/statistics"
	"github.com/tikv/pd/pkg/statistics/utils"
	"github.com/tikv/pd/pkg/storage"
	"github.com/tikv/pd/pkg/utils/operatorutil"
	"github.com/tikv/pd/pkg/versioninfo"
)

func TestHotWriteRegionScheduleWithRevertRegionsDimSecond(t *testing.T) {
	// This is a test that searchRevertRegions finds a solution of rank -1.
	re := require.New(t)
	cancel, _, tc, oc := prepareSchedulersTest()
	defer cancel()
	statistics.Denoising = false
	statisticsInterval = 0

	sche, err := CreateScheduler(utils.Write.String(), oc, storage.NewStorageWithMemoryBackend(), nil, nil)
	re.NoError(err)
	hb := sche.(*hotScheduler)
	hb.conf.SetDstToleranceRatio(0.0)
	hb.conf.SetSrcToleranceRatio(0.0)
	hb.conf.SetRankFormulaVersion("v1")
	tc.SetClusterVersion(versioninfo.MinSupportedVersion(versioninfo.Version4_0))
	tc.SetHotRegionCacheHitsThreshold(0)
	tc.AddRegionStore(1, 20)
	tc.AddRegionStore(2, 20)
	tc.AddRegionStore(3, 20)
	tc.AddRegionStore(4, 20)
	tc.AddRegionStore(5, 20)
	hb.conf.WritePeerPriorities = []string{utils.BytePriority, utils.KeyPriority}

	tc.UpdateStorageWrittenStats(1, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(2, 16*units.MiB*utils.StoreHeartBeatReportInterval, 20*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(3, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(4, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(5, 14*units.MiB*utils.StoreHeartBeatReportInterval, 10*units.MiB*utils.StoreHeartBeatReportInterval)
	addRegionInfo(tc, utils.Write, []testRegionInfo{
		{6, []uint64{3, 2, 4}, 2 * units.MiB, 3 * units.MiB, 0},
		{7, []uint64{1, 4, 5}, 2 * units.MiB, 0.1 * units.MiB, 0},
	})
	// No operators can be generated when RankFormulaVersion == "v1".
	ops, _ := hb.Schedule(tc, false)
	re.Empty(ops)
	re.False(hb.searchRevertRegions[writePeer])

	hb.conf.SetRankFormulaVersion("v2")
	// searchRevertRegions becomes true after the first `Schedule`.
	ops, _ = hb.Schedule(tc, false)
	re.Empty(ops)
	re.True(hb.searchRevertRegions[writePeer])
	// Two operators can be generated when RankFormulaVersion == "v2".
	ops, _ = hb.Schedule(tc, false)
	/* The revert region is currently disabled for the -1 case.
	re.Len(ops, 2)
	operatorutil.CheckTransferPeer(re, ops[0], operator.OpHotRegion, 2, 5)
	operatorutil.CheckTransferPeer(re, ops[1], operator.OpHotRegion, 5, 2)
	*/
	re.Empty(ops)
	re.True(hb.searchRevertRegions[writePeer])
	clearPendingInfluence(hb)
	// When there is a better solution, there will only be one operator.
	addRegionInfo(tc, utils.Write, []testRegionInfo{
		{8, []uint64{3, 2, 4}, 0.5 * units.MiB, 3 * units.MiB, 0},
	})
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 1)
	operatorutil.CheckTransferPeer(re, ops[0], operator.OpHotRegion, 2, 5)
	re.False(hb.searchRevertRegions[writePeer])
	clearPendingInfluence(hb)
}

func TestHotWriteRegionScheduleWithRevertRegionsDimFirst(t *testing.T) {
	// This is a test that searchRevertRegions finds a solution of rank -3.
	re := require.New(t)
	cancel, _, tc, oc := prepareSchedulersTest()
	defer cancel()
	statistics.Denoising = false

	sche, err := CreateScheduler(utils.Write.String(), oc, storage.NewStorageWithMemoryBackend(), nil, nil)
	re.NoError(err)
	hb := sche.(*hotScheduler)
	hb.conf.SetDstToleranceRatio(0.0)
	hb.conf.SetSrcToleranceRatio(0.0)
	hb.conf.SetRankFormulaVersion("v1")
	tc.SetClusterVersion(versioninfo.MinSupportedVersion(versioninfo.Version4_0))
	tc.SetHotRegionCacheHitsThreshold(0)
	tc.AddRegionStore(1, 20)
	tc.AddRegionStore(2, 20)
	tc.AddRegionStore(3, 20)
	tc.AddRegionStore(4, 20)
	tc.AddRegionStore(5, 20)
	hb.conf.WritePeerPriorities = []string{utils.BytePriority, utils.KeyPriority}

	tc.UpdateStorageWrittenStats(1, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(2, 20*units.MiB*utils.StoreHeartBeatReportInterval, 14*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(3, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(4, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(5, 10*units.MiB*utils.StoreHeartBeatReportInterval, 16*units.MiB*utils.StoreHeartBeatReportInterval)
	addRegionInfo(tc, utils.Write, []testRegionInfo{
		{6, []uint64{3, 2, 4}, 3 * units.MiB, 1.8 * units.MiB, 0},
		{7, []uint64{1, 4, 5}, 0.1 * units.MiB, 2 * units.MiB, 0},
	})
	// One operator can be generated when RankFormulaVersion == "v1".
	ops, _ := hb.Schedule(tc, false)
	re.Len(ops, 1)
	operatorutil.CheckTransferPeer(re, ops[0], operator.OpHotRegion, 2, 5)
	re.False(hb.searchRevertRegions[writePeer])
	clearPendingInfluence(hb)

	hb.conf.SetRankFormulaVersion("v2")
	// searchRevertRegions becomes true after the first `Schedule`.
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 1)
	re.True(hb.searchRevertRegions[writePeer])
	clearPendingInfluence(hb)
	// Two operators can be generated when RankFormulaVersion == "v2".
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 2)
	operatorutil.CheckTransferPeer(re, ops[0], operator.OpHotRegion, 2, 5)
	operatorutil.CheckTransferPeer(re, ops[1], operator.OpHotRegion, 5, 2)
	re.True(hb.searchRevertRegions[writePeer])
	clearPendingInfluence(hb)
}

func TestHotWriteRegionScheduleWithRevertRegionsDimFirstOnly(t *testing.T) {
	// This is a test that searchRevertRegions finds a solution of rank -2.
	re := require.New(t)
	statistics.Denoising = false
	statisticsInterval = 0

	cancel, _, tc, oc := prepareSchedulersTest()
	defer cancel()
	sche, err := CreateScheduler(utils.Write.String(), oc, storage.NewStorageWithMemoryBackend(), nil, nil)
	re.NoError(err)
	hb := sche.(*hotScheduler)
	hb.conf.SetDstToleranceRatio(0.0)
	hb.conf.SetSrcToleranceRatio(0.0)
	hb.conf.SetRankFormulaVersion("v1")
	tc.SetClusterVersion(versioninfo.MinSupportedVersion(versioninfo.Version4_0))
	tc.SetHotRegionCacheHitsThreshold(0)
	tc.AddRegionStore(1, 20)
	tc.AddRegionStore(2, 20)
	tc.AddRegionStore(3, 20)
	tc.AddRegionStore(4, 20)
	tc.AddRegionStore(5, 20)
	hb.conf.WritePeerPriorities = []string{utils.BytePriority, utils.KeyPriority}

	tc.UpdateStorageWrittenStats(1, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(2, 20*units.MiB*utils.StoreHeartBeatReportInterval, 14*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(3, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(4, 15*units.MiB*utils.StoreHeartBeatReportInterval, 16*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageWrittenStats(5, 10*units.MiB*utils.StoreHeartBeatReportInterval, 18*units.MiB*utils.StoreHeartBeatReportInterval)
	addRegionInfo(tc, utils.Write, []testRegionInfo{
		{6, []uint64{3, 2, 4}, 3 * units.MiB, 3 * units.MiB, 0},
		{7, []uint64{1, 4, 5}, 0.1 * units.MiB, 0.1 * units.MiB, 0},
	})
	// One operator can be generated when RankFormulaVersion == "v1".
	ops, _ := hb.Schedule(tc, false)
	re.Len(ops, 1)
	operatorutil.CheckTransferPeer(re, ops[0], operator.OpHotRegion, 2, 5)
	re.False(hb.searchRevertRegions[writePeer])
	clearPendingInfluence(hb)

	hb.conf.SetRankFormulaVersion("v2")
	// searchRevertRegions becomes true after the first `Schedule`.
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 1)
	re.True(hb.searchRevertRegions[writePeer])
	clearPendingInfluence(hb)
	// There is still the solution with one operator after that.
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 1)
	operatorutil.CheckTransferPeer(re, ops[0], operator.OpHotRegion, 2, 5)
	re.True(hb.searchRevertRegions[writePeer])
	clearPendingInfluence(hb)
	// Two operators can be generated when there is a better solution
	addRegionInfo(tc, utils.Write, []testRegionInfo{
		{8, []uint64{1, 4, 5}, 0.1 * units.MiB, 3 * units.MiB, 0},
	})
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 2)
	operatorutil.CheckTransferPeer(re, ops[0], operator.OpHotRegion, 2, 5)
	operatorutil.CheckTransferPeer(re, ops[1], operator.OpHotRegion, 5, 2)
	re.True(hb.searchRevertRegions[writePeer])
	clearPendingInfluence(hb)
}

func TestHotReadRegionScheduleWithRevertRegionsDimSecond(t *testing.T) {
	// This is a test that searchRevertRegions finds a solution of rank -1.
	re := require.New(t)
	statistics.Denoising = false
	statisticsInterval = 0

	cancel, _, tc, oc := prepareSchedulersTest()
	defer cancel()
	sche, err := CreateScheduler(utils.Read.String(), oc, storage.NewStorageWithMemoryBackend(), nil, nil)
	re.NoError(err)
	hb := sche.(*hotScheduler)
	hb.conf.SetDstToleranceRatio(0.0)
	hb.conf.SetSrcToleranceRatio(0.0)
	hb.conf.SetRankFormulaVersion("v1")
	tc.SetClusterVersion(versioninfo.MinSupportedVersion(versioninfo.Version4_0))
	tc.SetHotRegionCacheHitsThreshold(0)
	tc.AddRegionStore(1, 20)
	tc.AddRegionStore(2, 20)
	tc.AddRegionStore(3, 20)
	tc.AddRegionStore(4, 20)
	tc.AddRegionStore(5, 20)
	hb.conf.ReadPriorities = []string{utils.BytePriority, utils.KeyPriority}

	tc.UpdateStorageReadStats(1, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(2, 16*units.MiB*utils.StoreHeartBeatReportInterval, 20*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(3, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(4, 15*units.MiB*utils.StoreHeartBeatReportInterval, 15*units.MiB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(5, 14*units.MiB*utils.StoreHeartBeatReportInterval, 10*units.MiB*utils.StoreHeartBeatReportInterval)
	addRegionInfo(tc, utils.Read, []testRegionInfo{
		{6, []uint64{2, 1, 5}, 2 * units.MiB, 3 * units.MiB, 0},
		{7, []uint64{5, 4, 2}, 2 * units.MiB, 0.1 * units.MiB, 0},
	})
	// No operators can be generated when RankFormulaVersion == "v1".
	ops, _ := hb.Schedule(tc, false)
	re.Empty(ops)
	re.False(hb.searchRevertRegions[readLeader])

	hb.conf.SetRankFormulaVersion("v2")
	// searchRevertRegions becomes true after the first `Schedule`.
	ops, _ = hb.Schedule(tc, false)
	re.Empty(ops)
	re.True(hb.searchRevertRegions[readLeader])
	// Two operators can be generated when RankFormulaVersion == "v2".
	ops, _ = hb.Schedule(tc, false)
	/* The revert region is currently disabled for the -1 case.
	re.Len(ops, 2)
	operatorutil.CheckTransferLeader(re, ops[0], operator.OpHotRegion, 2, 5)
	operatorutil.CheckTransferLeader(re, ops[1], operator.OpHotRegion, 5, 2)
	*/
	re.Empty(ops)
	re.True(hb.searchRevertRegions[readLeader])
	clearPendingInfluence(hb)
	// When there is a better solution, there will only be one operator.
	addRegionInfo(tc, utils.Read, []testRegionInfo{
		{8, []uint64{2, 1, 5}, 0.5 * units.MiB, 3 * units.MiB, 0},
	})
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 1)
	operatorutil.CheckTransferLeader(re, ops[0], operator.OpHotRegion, 2, 5)
	re.False(hb.searchRevertRegions[readLeader])
	clearPendingInfluence(hb)
}

func TestSkipUniformStore(t *testing.T) {
	re := require.New(t)
	statistics.Denoising = false
	statisticsInterval = 0

	cancel, _, tc, oc := prepareSchedulersTest()
	defer cancel()
	hb, err := CreateScheduler(utils.Read.String(), oc, storage.NewStorageWithMemoryBackend(), nil, nil)
	re.NoError(err)
	hb.(*hotScheduler).conf.SetSrcToleranceRatio(1)
	hb.(*hotScheduler).conf.SetDstToleranceRatio(1)
	hb.(*hotScheduler).conf.SetRankFormulaVersion("v2")
	hb.(*hotScheduler).conf.ReadPriorities = []string{utils.BytePriority, utils.KeyPriority}
	tc.SetHotRegionCacheHitsThreshold(0)
	tc.AddRegionStore(1, 20)
	tc.AddRegionStore(2, 20)
	tc.AddRegionStore(3, 20)
	tc.AddRegionStore(4, 20)
	tc.AddRegionStore(5, 20)

	// Case1: two dim are both enough uniform
	tc.UpdateStorageReadStats(1, 10.05*units.MB*utils.StoreHeartBeatReportInterval, 10.05*units.MB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(2, 9.15*units.MB*utils.StoreHeartBeatReportInterval, 9.15*units.MB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(3, 10.0*units.MB*utils.StoreHeartBeatReportInterval, 10.0*units.MB*utils.StoreHeartBeatReportInterval)
	addRegionInfo(tc, utils.Read, []testRegionInfo{
		{1, []uint64{1, 2, 3}, 0.3 * units.MB, 0.3 * units.MB, 0},
	})
	// when there is no uniform store filter, still schedule although the cluster is enough uniform
	stddevThreshold = 0.0
	ops, _ := hb.Schedule(tc, false)
	re.Len(ops, 1)
	operatorutil.CheckTransferLeader(re, ops[0], operator.OpHotRegion, 1, 2)
	clearPendingInfluence(hb.(*hotScheduler))
	// when there is uniform store filter, not schedule
	stddevThreshold = 0.1
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 0)
	clearPendingInfluence(hb.(*hotScheduler))

	// Case2: the first dim is enough uniform, we should schedule the second dim
	tc.UpdateStorageReadStats(1, 10.15*units.MB*utils.StoreHeartBeatReportInterval, 10.05*units.MB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(2, 9.25*units.MB*utils.StoreHeartBeatReportInterval, 9.85*units.MB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(3, 9.85*units.MB*utils.StoreHeartBeatReportInterval, 16.0*units.MB*utils.StoreHeartBeatReportInterval)
	addRegionInfo(tc, utils.Read, []testRegionInfo{
		{1, []uint64{1, 2, 3}, 0.3 * units.MB, 0.3 * units.MB, 0},
		{2, []uint64{3, 2, 1}, 0.3 * units.MB, 2 * units.MB, 0},
	})
	// when there is no uniform store filter, still schedule although the first dim is enough uniform
	stddevThreshold = 0.0
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 1)
	operatorutil.CheckTransferLeader(re, ops[0], operator.OpHotRegion, 1, 2)
	clearPendingInfluence(hb.(*hotScheduler))
	// when there is uniform store filter, schedule the second dim, which is no uniform
	stddevThreshold = 0.1
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 1)
	operatorutil.CheckTransferLeader(re, ops[0], operator.OpHotRegion, 3, 2)
	clearPendingInfluence(hb.(*hotScheduler))

	// Case3: the second dim is enough uniform, we should schedule the first dim, although its rank is higher than the second dim
	tc.UpdateStorageReadStats(1, 10.05*units.MB*utils.StoreHeartBeatReportInterval, 10.05*units.MB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(2, 9.85*units.MB*utils.StoreHeartBeatReportInterval, 9.45*units.MB*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(3, 16*units.MB*utils.StoreHeartBeatReportInterval, 9.85*units.MB*utils.StoreHeartBeatReportInterval)
	addRegionInfo(tc, utils.Read, []testRegionInfo{
		{1, []uint64{1, 2, 3}, 0.3 * units.MB, 0.3 * units.MB, 0},
		{2, []uint64{3, 2, 1}, 2 * units.MB, 0.3 * units.MB, 0},
	})
	// when there is no uniform store filter, schedule the first dim, which is no uniform
	stddevThreshold = 0.0
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 1)
	operatorutil.CheckTransferLeader(re, ops[0], operator.OpHotRegion, 3, 2)
	clearPendingInfluence(hb.(*hotScheduler))
	// when there is uniform store filter, schedule the first dim, which is no uniform
	stddevThreshold = 0.1
	ops, _ = hb.Schedule(tc, false)
	re.Len(ops, 1)
	operatorutil.CheckTransferLeader(re, ops[0], operator.OpHotRegion, 3, 2)
	clearPendingInfluence(hb.(*hotScheduler))
}

func TestHotReadRegionScheduleWithSmallHotRegion(t *testing.T) {
	// This is a test that we can schedule small hot region,
	// which is smaller than 20% of diff or 2% of low node. (#6645)
	// 20% is from `firstPriorityPerceivedRatio`, 2% is from `firstPriorityMinHotRatio`.
	// The byte of high node is 2000MB/s, the low node is 200MB/s.
	// The query of high node is 2000qps, the low node is 200qps.
	// There are all small hot regions in the cluster, which are smaller than 20% of diff or 2% of low node.
	re := require.New(t)
	emptyFunc := func(*mockcluster.Cluster, *hotScheduler) {}
	highLoad, lowLoad := uint64(2000), uint64(200)
	bigHotRegionByte := uint64(float64(lowLoad) * firstPriorityMinHotRatio * 10 * units.MiB * utils.StoreHeartBeatReportInterval)
	bigHotRegionQuery := uint64(float64(lowLoad) * firstPriorityMinHotRatio * 10 * utils.StoreHeartBeatReportInterval)

	// Case1: Before #6827, we only use minHotRatio, so cannot schedule small hot region in this case.
	// Because 10000 is larger than the length of hotRegions, so `filterHotPeers` will skip the topn calculation.
	origin := topnPosition
	topnPosition = 10000
	ops := checkHotReadRegionScheduleWithSmallHotRegion(re, highLoad, lowLoad, emptyFunc)
	re.Empty(ops)
	topnPosition = origin

	// Case2: After #6827, we use top10 as the threshold of minHotPeer.
	ops = checkHotReadRegionScheduleWithSmallHotRegion(re, highLoad, lowLoad, emptyFunc)
	re.Len(ops, 1)
	ops = checkHotReadRegionScheduleWithSmallHotRegion(re, lowLoad, highLoad, emptyFunc)
	re.Len(ops, 0)

	// Case3: If there is larger hot region, we will schedule it.
	hotRegionID := uint64(100)
	ops = checkHotReadRegionScheduleWithSmallHotRegion(re, highLoad, lowLoad, func(tc *mockcluster.Cluster, _ *hotScheduler) {
		tc.AddRegionWithReadInfo(hotRegionID, 1, bigHotRegionByte, 0, bigHotRegionQuery, utils.StoreHeartBeatReportInterval, []uint64{2, 3})
	})
	re.Len(ops, 1)
	re.Equal(hotRegionID, ops[0].RegionID())

	// Case4: If there is larger hot region, but it need to cool down, we will schedule small hot region.
	ops = checkHotReadRegionScheduleWithSmallHotRegion(re, highLoad, lowLoad, func(tc *mockcluster.Cluster, _ *hotScheduler) {
		// just transfer leader
		tc.AddRegionWithReadInfo(hotRegionID, 2, bigHotRegionByte, 0, bigHotRegionQuery, utils.StoreHeartBeatReportInterval, []uint64{1, 3})
		tc.AddRegionWithReadInfo(hotRegionID, 1, bigHotRegionByte, 0, bigHotRegionQuery, utils.StoreHeartBeatReportInterval, []uint64{2, 3})
	})
	re.Len(ops, 1)
	re.NotEqual(hotRegionID, ops[0].RegionID())

	// Case5: If there is larger hot region, but it is pending, we will schedule small hot region.
	ops = checkHotReadRegionScheduleWithSmallHotRegion(re, highLoad, lowLoad, func(tc *mockcluster.Cluster, hb *hotScheduler) {
		tc.AddRegionWithReadInfo(hotRegionID, 1, bigHotRegionByte, 0, bigHotRegionQuery, utils.StoreHeartBeatReportInterval, []uint64{2, 3})
		hb.regionPendings[hotRegionID] = &pendingInfluence{}
	})
	re.Len(ops, 1)
	re.NotEqual(hotRegionID, ops[0].RegionID())

	// Case6: If there are more than topnPosition hot regions, but them need to cool down,
	// we will schedule large hot region rather than small hot region, so there is no operator.
	topnPosition = 2
	ops = checkHotReadRegionScheduleWithSmallHotRegion(re, highLoad, lowLoad, func(tc *mockcluster.Cluster, _ *hotScheduler) {
		// just transfer leader
		tc.AddRegionWithReadInfo(hotRegionID, 2, bigHotRegionByte, 0, bigHotRegionQuery, utils.StoreHeartBeatReportInterval, []uint64{1, 3})
		tc.AddRegionWithReadInfo(hotRegionID, 1, bigHotRegionByte, 0, bigHotRegionQuery, utils.StoreHeartBeatReportInterval, []uint64{2, 3})
		// just transfer leader
		tc.AddRegionWithReadInfo(hotRegionID+1, 2, bigHotRegionByte, 0, bigHotRegionQuery, utils.StoreHeartBeatReportInterval, []uint64{1, 3})
		tc.AddRegionWithReadInfo(hotRegionID+1, 1, bigHotRegionByte, 0, bigHotRegionQuery, utils.StoreHeartBeatReportInterval, []uint64{2, 3})
	})
	re.Len(ops, 0)
	topnPosition = origin

	// Case7: If there are more than topnPosition hot regions, but them are pending,
	// we will schedule large hot region rather than small hot region, so there is no operator.
	topnPosition = 2
	ops = checkHotReadRegionScheduleWithSmallHotRegion(re, highLoad, lowLoad, func(tc *mockcluster.Cluster, hb *hotScheduler) {
		tc.AddRegionWithReadInfo(hotRegionID, 1, bigHotRegionByte, 0, bigHotRegionQuery, utils.StoreHeartBeatReportInterval, []uint64{2, 3})
		hb.regionPendings[hotRegionID] = &pendingInfluence{}
		tc.AddRegionWithReadInfo(hotRegionID+1, 1, bigHotRegionByte, 0, bigHotRegionQuery, utils.StoreHeartBeatReportInterval, []uint64{2, 3})
		hb.regionPendings[hotRegionID+1] = &pendingInfluence{}
	})
	re.Len(ops, 0)
	topnPosition = origin
}

func checkHotReadRegionScheduleWithSmallHotRegion(re *require.Assertions, highLoad, lowLoad uint64,
	addOtherRegions func(*mockcluster.Cluster, *hotScheduler)) []*operator.Operator {
	cancel, _, tc, oc := prepareSchedulersTest()
	defer cancel()
	statistics.Denoising = false
	sche, err := CreateScheduler(utils.Read.String(), oc, storage.NewStorageWithMemoryBackend(), nil, nil)
	re.NoError(err)
	hb := sche.(*hotScheduler)
	hb.conf.SetSrcToleranceRatio(1)
	hb.conf.SetDstToleranceRatio(1)
	hb.conf.SetRankFormulaVersion("v2")
	hb.conf.ReadPriorities = []string{utils.QueryPriority, utils.BytePriority}
	tc.SetHotRegionCacheHitsThreshold(0)
	tc.AddRegionStore(1, 40)
	tc.AddRegionStore(2, 10)
	tc.AddRegionStore(3, 10)

	tc.UpdateStorageReadQuery(1, highLoad*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadQuery(2, lowLoad*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadQuery(3, (highLoad+lowLoad)/2*utils.StoreHeartBeatReportInterval)
	tc.UpdateStorageReadStats(1, highLoad*units.MiB*utils.StoreHeartBeatReportInterval, 0)
	tc.UpdateStorageReadStats(2, lowLoad*units.MiB*utils.StoreHeartBeatReportInterval, 0)
	tc.UpdateStorageReadStats(3, (highLoad+lowLoad)/2*units.MiB*utils.StoreHeartBeatReportInterval, 0)

	smallHotPeerQuery := float64(lowLoad) * firstPriorityMinHotRatio * 0.9             // it's a small hot region than the firstPriorityMinHotRatio
	smallHotPeerByte := float64(lowLoad) * secondPriorityMinHotRatio * 0.9 * units.MiB // it's a small hot region than the secondPriorityMinHotRatio
	regions := make([]testRegionInfo, 0)
	for i := 10; i < 50; i++ {
		regions = append(regions, testRegionInfo{uint64(i), []uint64{1, 2, 3}, smallHotPeerByte, 0, smallHotPeerQuery})
		if i < 20 {
			regions = append(regions, testRegionInfo{uint64(i), []uint64{2, 1, 3}, smallHotPeerByte, 0, smallHotPeerQuery})
			regions = append(regions, testRegionInfo{uint64(i), []uint64{3, 1, 2}, smallHotPeerByte, 0, smallHotPeerQuery})
		}
	}
	addRegionInfo(tc, utils.Read, regions)
	tc.SetHotRegionCacheHitsThreshold(1)
	addOtherRegions(tc, hb)
	ops, _ := hb.Schedule(tc, false)
	return ops
}

repository: tikv/pd

repo_name: tikv/pd


text:
@article{kim_ultrasensitive_2017,
 abstract = {Biosensors, which harness the unique specific binding properties of biomaterials such as proteis, are increasingly recognized as a powerful tool for chemical sensing. In this context, the detection of nucleic acids DNA and RNA will take on ever more},
 author = {Kim, Ju-Hyung and Smit, Jochem H. and Prusty, Deepak K. and Musser, Andrew J. and Tombros, Nikolaos and Lee, Peter C. W. and Herrmann, Andreas and Kwak, Minseok},
 issn = {1533-4880},
 journal = {Journal of Nanoscience and Nanotechnology},
 language = {en},
 month = {August},
 number = {8},
 pages = {5175--5180},
 shorttitle = {Ultrasensitive Detection of Oligonucleotides},
 title = {Ultrasensitive Detection of Oligonucleotides: Single-Walled Carbon Nanotube Transistor Assembled by DNA Block Copolymer},
 url = {https://www.academia.edu/33792602/Ultrasensitive_Detection_of_Oligonucleotides_Single-Walled_Carbon_Nanotube_Transistor_Assembled_by_DNA_Block_Copolymer},
 urldate = {2019-05-21},
 volume = {17},
 year = {2017}
}

license: MIT

repository: Jhsmit/academic-kickstart

license_type: permissive

repo_name: Jhsmit/academic-kickstart

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: TeX

extension: bib


text:
SUMMARY = "Iotivity middleware components"
LICENSE = "MIT"

inherit packagegroup

# TODO: are all of these really needed in a minimal image?
RDEPENDS_${PN} = " \
    iotivity \
    iotivity-simple-client \
    iotivity-resource \
    iotivity-resource-samples \
"

repository: ostroproject/meta-ostro

repo_name: ostroproject/meta-ostro

gha_language: Python

extension: bb


text:
// Package rooms contains auto-generated files. DO NOT MODIFY
package rooms

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

	"github.com/RJPearson94/twilio-sdk-go/client"
)

// CreateRoomInput defines the input fields for creating a new room
type CreateRoomInput struct {
	MaxParticipants             *int      `form:"MaxParticipants,omitempty"`
	MediaRegion                 *string   `form:"MediaRegion,omitempty"`
	RecordParticipantsOnConnect *bool     `form:"RecordParticipantsOnConnect,omitempty"`
	StatusCallback              *string   `form:"StatusCallback,omitempty"`
	StatusCallbackMethod        *string   `form:"StatusCallbackMethod,omitempty"`
	Type                        *string   `form:"Type,omitempty"`
	UniqueName                  *string   `form:"UniqueName,omitempty"`
	VideoCodecs                 *[]string `form:"VideoCodecs,omitempty"`
}

// CreateRoomResponse defines the response fields for the created room
type CreateRoomResponse struct {
	AccountSid                   string     `json:"account_sid"`
	DateCreated                  time.Time  `json:"date_created"`
	DateUpdated                  *time.Time `json:"date_updated,omitempty"`
	Duration                     *int       `json:"duration,omitempty"`
	EndTime                      *time.Time `json:"end_time,omitempty"`
	MaxConcurrentPublishedTracks *int       `json:"max_concurrent_published_tracks,omitempty"`
	MaxParticipants              int        `json:"max_participants"`
	MediaRegion                  *string    `json:"media_region,omitempty"`
	RecordParticipantsOnConnect  bool       `json:"record_participants_on_connect"`
	Sid                          string     `json:"sid"`
	Status                       string     `json:"status"`
	StatusCallback               *string    `json:"status_callback,omitempty"`
	StatusCallbackMethod         string     `json:"status_callback_method"`
	Type                         string     `json:"type"`
	URL                          string     `json:"url"`
	UniqueName                   string     `json:"unique_name"`
	VideoCodecs                  *[]string  `json:"video_codecs,omitempty"`
}

// Create creates a new room
// See https://www.twilio.com/docs/video/api/rooms-resource#create-room for more details
// Context is defaulted to Background. See https://golang.org/pkg/context/#Background for more information
func (c Client) Create(input *CreateRoomInput) (*CreateRoomResponse, error) {
	return c.CreateWithContext(context.Background(), input)
}

// CreateWithContext creates a new room
// See https://www.twilio.com/docs/video/api/rooms-resource#create-room for more details
func (c Client) CreateWithContext(context context.Context, input *CreateRoomInput) (*CreateRoomResponse, error) {
	op := client.Operation{
		Method:      http.MethodPost,
		URI:         "/Rooms",
		ContentType: client.URLEncoded,
	}

	if input == nil {
		input = &CreateRoomInput{}
	}

	response := &CreateRoomResponse{}
	if err := c.client.Send(context, op, input, response); err != nil {
		return nil, err
	}
	return response, nil
}

branch_name: refs/heads/main

gha_language: Go

extension: go


text:
@article{signac_commat,
  author        = {Carl S. Adorf and
                   Paul M. Dodd and
                   Vyas Ramasubramani and
                   Sharon C. Glotzer},
  title         = {Simple data and workflow management with the signac framework},
  journal       = {Comput. Mater. Sci.},
  volume        = {146},
  number        = {C},
  year          = {2018},
  pages         = {220-229},
  archivePrefix = {arXiv},
  eprint        = {1611.03543 [cs.DB]},
  note          = {(in press)}
}
@misc{signac_0_9_2,
  author       = {Carl S. Adorf and
                  Paul M. Dodd and
                  Vyas Ramasubramani and
                  Benjamin Swerdlow and
                  Jens Glaser and
                  Bradley Dice},
  title        = {csadorf/signac v0.9.2},
  month        = {dec},
  year         = {2017},
  doi          = {10.5281/zenodo.1117952},
  url          = {https://doi.org/10.5281/zenodo.1117952}
}

repository: csadorf/signac

repo_name: csadorf/signac


text:
package bgp

import (
	"github.com/golang/glog"
	"github.com/sbezverk/gobmp/pkg/tools"
)

// InformationalTLV defines BGP informational TLV object
type InformationalTLV struct {
	Type   byte
	Length byte
	Value  []byte
}

// UnmarshalBGPTLV builds a slice of Informational TLVs
func UnmarshalBGPTLV(b []byte) ([]InformationalTLV, error) {
	glog.V(6).Infof("BGPTLV Raw: %s", tools.MessageHex(b))
	tlvs := make([]InformationalTLV, 0)
	for p := 0; p < len(b); {
		t := b[p]
		p++
		l := b[p]
		p++
		v := make([]byte, l)
		copy(v, b[p:p+int(l)])
		tlvs = append(tlvs, InformationalTLV{
			Type:   t,
			Length: l,
			Value:  v,
		})
		p += int(l)
	}

	return tlvs, nil
}

repository: SergeKrier/gobmp

repo_name: SergeKrier/gobmp


text:
DESCRIPTION = "OmniORB High Performance ORB"
SECTION = "devel"
PRIORITY = "optional"
LICENSE = "LGPL"
DEPENDS += "omniorb-native"
DEPENDS_virtclass-native += "python-native"
PR = "r2"

SRC_URI = "http://downloads.sourceforge.net/omniorb/omniORB-4.1.4.tar.gz;name=omniORB414targz \
file://omniorb_4.1.4.patch \
file://omniORB.cfg \
file://omniORB-cross.patch \
file://omniORB_embedded_appl.patch \
file://rm_LongDouble.patch \
"
SRC_URI_virtclass-native = "http://downloads.sourceforge.net/omniorb/omniORB-4.1.4.tar.gz;name=omniORB414targz \
	  file://omniorb_4.1.4.patch \
"

SRC_URI[omniORB414targz.md5sum] = "1f6070ff9b6339876976d61981eeaa6a"
SRC_URI[omniORB414targz.sha256sum] = "84fb9790c25d6e46248c9773747e393b429573190da2150850d4a49debda4e8e"

S = "${WORKDIR}/omniORB-${PV}"

FILES_${PN}-dev += "${datadir}/idl/omniORB/* ${datadir}/idl/omniORB/cos/*
TARGET_CC_ARCH += ${LDFLAGS}

inherit autotools pkgconfig

do_compile () {
        export EmbeddedSystem=1
        export TOOLBINDIR=${STAGING_BINDIR_NATIVE}
	oe_runmake

}

do_compile_virtclass-native() {
        oe_runmake
}

do_install () {
        # Set a variable that the Makefiles obey for install.
        export EmbeddedSystem=1
        autotools_do_install
        install -d ${D}${sysconfdir}
        install -m 0644 ${WORKDIR}/omniORB.cfg ${D}${sysconfdir}
        install -d ${D}${localstatedir}/omninames

	#only executable libraries are stripped by the stripper
	chmod +x ${WORKDIR}/image/usr/lib/lib*
}

do_install_virtclass-native() {
        autotools_do_install

	# Ugly hack so libtool does not find native libs when building cross
	# packages We really only build this package for omniidl anyway
        rm -f  ${D}${libdir}/libomni*
}

BBCLASSEXTEND = "native"

NATIVE_INSTALL_WORKS = "1"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
@article{test2010,
  keywords   = {own},
  title     = "A two authors paper",
  author    = "Dupond, Jean and Dupont, Jacques R.",
  year      = "2010",
  journal   = "Random journal",
  volume    = "2",
  pages     = "16-45"
}

@article{test2013,
  title     = "A three authors citation",
  author    = "Dupond, Jean and Dupont, Jacques R. and Durant, Charles",
  year      = "2013",
  journal   = "Random journal",
  volume    = "1",
  pages     = "16-34"
}

@article{test2011,
  title     = "A single author article",
  author    = "Durant, Charles",
  year      = "2011",
  journal   = "Random journal",
  volume    = "1",
  pages     = "35-44"
}

@article{test2011b,
  title     = "A same author article same year",
  author    = "Durant, Charles",
  year      = "2011",
  journal   = "Alternative journal",
  volume    = "4",
  pages     = "10-22"
}

@misc{misc2002,
  keywords	= {own,talk,unbib},
  author		= "Dupont, Jacques R.",
  title			= "Misc {E}ntry",
  year			= "2002"
}

@phdthesis{phdthesis1999,
  author	= "Dupont, Jacques R.",
  title		= {Phd Thesis},
  school	=	{UPMC},
  year		=	{1999}
}

@techreport{techreport1995,
  author			= {Martin, Henri},
  title				= {Technical report entry},
  year				= {1995},
  institution = {UPMC},
  number			= {1}
}

@book{book1998,
  author 		= {Th{\'e}o, Ren{\'e}},
  title 		= {Le bouquin en fran{\c{c}}ais avec des accents},
  year 			= {1998},
  publisher	= {Publisher}
}

repository: deleron/latextb

repo_name: deleron/latextb


text:
package main

// func main() {
// 	fmt.Println("a")
// 	if err := recover(); err != nil {
// 		fmt.Println(err)
// 	}

// 	panic("panic")
// 	fmt.Println("b")
// 	if err := recover(); err != nil {
// 		fmt.Println(err)
// 	}
// 	fmt.Println("c")
// }

// func main() {
// 	fmt.Println("a")
// 	defer func() {
// 		func() {
// 			if err := recover(); err != nil {
// 				fmt.Println("b")
// 				fmt.Println(err)
// 			}
// 			fmt.Println("c")
// 		}()
// 	}()

// 	panic("panic")

// 	fmt.Println("d")
// }

// func main() {
// 	fmt.Println("a")
// 	defer func() {
// 		fmt.Println("m")
// 	}()

// 	defer func() {
// 		defer func() {
// 			fmt.Println("n")
// 		}()

// 		if err := recover(); err != nil {
// 			fmt.Println("b")
// 			fmt.Println(err)
// 		}
// 		fmt.Println("c")

// 		defer func() {
// 			fmt.Println("o")
// 		}()
// 	}()

// 	defer func() {
// 		fmt.Println("x")
// 	}()

// 	panic("panic")

// 	fmt.Println("d")
// }

// func main() {
// 	fmt.Println("a")
// 	defer func() {
// 		defer func() {
// 			if err := recover(); err != nil {
// 			fmt.Println("b")
// 			fmt.Println(err)
// 			}
// 		}()
// 	}()

// 	panic("panic")

// 	fmt.Println("d")
// }

// func main() {
// 	fmt.Println("a")
// 	defer func() {
// 		func() {
// 			if err := recover(); err != nil {
// 				fmt.Println("b")
// 				fmt.Println(err)
// 			}
// 			fmt.Println("c")
// 		}()
// 	}()

// 	panic("panic")

// 	fmt.Println("d")
// }

// func main() {
// 	// 无法捕获异常
// 	defer recover()
// 	panic(1)
// }

func myfunc() {
	recover()
}

func main() {

	defer myfunc()

	panic("errrrrrrrrror")

}

repository: youngqqcn/QBlockChainNotes

repo_name: youngqqcn/QBlockChainNotes

gha_language: JavaScript


text:
PD = "A relatively small SSH server and client"
PV = "2014.66"

HOMEPAGE = "http://matt.ucc.asn.au/dropbear/"
LICENSE = "custom"

SRC_URI = " \
  ${HOMEPAGE}/releases/${S}.tar.bz2;md5sum=c21a01111aa5015db038c6efdb85717d \
"

HOST_DEPENDS = "dropbear"
DEPENDS = "crosstool-ng"
RDEPENDS = "zlib"

step_build() {
  cd "${SRCDIR}"/${S}

  ./configure \
    --host=${TARGET_SYS} \
    --prefix=/usr \
    --disable-wtmp \
    --disable-lastlog

  export PROGRAMS="dropbear dbclient scp"
  make
}

step_install() {
  cd "${SRCDIR}"/${S}
  make DESTDIR="${RESULT}"/pkg install

  cd "${RESULT}"/pkg
  install -D usr/sbin/dropbear -t "${FILES_PKG}"/bin
  install -D usr/bin/dbclient -t "${FILES_PKG}"/usr/bin

  install -d "${FILES_PKG}"/etc/dropbear
  dropbearkey -t rsa -f "${FILES_PKG}"/etc/dropbear/dropbear_rsa_host_key

  install -D /dev/null "${FILES_PKG}"/etc/neoinit/net.dropbear/run
  touch "${FILES_PKG}"/etc/neoinit/net.dropbear/respawn
  {
    echo "#!/bin/sh"
    echo "exec /bin/dropbear -F -B"
  } > "${FILES_PKG}"/etc/neoinit/net.dropbear/run

  install_license "${SRCDIR}"/${S}/LICENSE "${FILES_PKG}"
}

repository: typedivision/pacstage

repo_name: typedivision/pacstage


text:
package trade_knife

import (
	"fmt"

	"github.com/markcheno/go-talib"
)

type BollingerBandsB struct {
	Tag IndicatorTag      `mapstructure:"tag"`
	Std StandardDeviation `mapstructure:"standardDeviation"`
}

func (bbb *BollingerBandsB) Add(q *Quote, c *Candle) bool {
	if c != nil {
		candle, i := q.Find(c.Opentime.Unix())
		if candle == nil {
			return false
		}

		startIndex := i - bbb.Std.InTimePeriod
		if startIndex < 0 {
			return false
		}

		quote := Quote{
			Market:   q.Market,
			Currency:   q.Currency,
			Interval: q.Interval,
			Candles:  q.Candles[startIndex : i+1],
		}

		deviation, ok := c.Get(Source(bbb.Std.Tag))
		if !ok {
			if !bbb.Std.Add(&quote, c) {
				return false
			}

			deviation, ok = c.Get(Source(bbb.Std.Tag))
			if !ok {
				return false
			}
		}

		sma := &Ma{
			Tag:          IndicatorTag(fmt.Sprintf("bbb:sma:%s:%d", bbb.Std.Source, bbb.Std.InTimePeriod)),
			Source:       bbb.Std.Source,
			Type:         talib.SMA,
			InTimePeriod: bbb.Std.InTimePeriod,
		}
		basis, ok := c.Get(Source(sma.Tag))
		if !ok {
			if !sma.Add(&quote, c) {
				return false
			}
			basis, ok = c.Get(Source(sma.Tag))
			if !ok {
				return false
			}
		}

		upper := basis + deviation
		lower := basis - deviation
		bbr, ok := c.Get(bbb.Std.Source)
		if !ok {
			return false
		}
		bbr = (bbr - lower) / (upper - lower)
		candle.AddIndicator(bbb.Tag, bbr)
		q.Candles[i] = candle

		return true
	}

	if len(q.Candles) < bbb.Std.InTimePeriod {
		return false
	}

	for _, candle := range q.Candles {
		if !bbb.Add(q, candle) {
			return false
		}
	}

	return true
}

func (bbb *BollingerBandsB) Is(tag IndicatorTag) bool {
	return bbb.Tag == tag
}

repository: amir-the-h/trade-knife

repo_name: amir-the-h/trade-knife


text:
% Encoding: UTF-8

@article{anselinLi2019,
  title={Operational local join count statistics for cluster detection},
  author={Anselin, Luc and Li, Xun},
  journal={Journal of geographical systems},
  volume={21},
  number={2},
  pages={189--210},
  year={2019},
  publisher={Springer}
}

@book{upton1985,
  title={Spatial data analysis by example: categorical and directional data},
  author={Upton, Graham JG and Fingleton, Bernard},
  year={1985},
  publisher={Wiley}
}

@article{Ruiz2012,
  doi = {10.1080/13658816.2011.586327},
  year = {2012},
  month = mar,
  publisher = {Informa {UK} Limited},
  volume = {26},
  number = {3},
  pages = {413--439},
  author = {Manuel Ruiz and Fernando L{\'{o}}pez and Antonio P{\'{a}}ez},
  title = {Comparison of thematic maps using symbolic entropy},
  journal = {International Journal of Geographical Information Science}
}

@article{Farber2014,
  doi = {10.1111/gean.12044},
  year = {2014},
  publisher = {Wiley},
  volume = {47},
  number = {2},
  pages = {97--120},
  author = {Steven Farber and Manuel Ruiz Marin and Antonio P{\'{a}}ez},
  title = {Testing for Spatial Independence Using Similarity Relations},
  journal = {Geographical Analysis}
}

@article{Ruiz2012b,
  doi = {10.1080/13658816.2011.586327},
  year = {2012},
  month = mar,
  publisher = {Informa {UK} Limited},
  volume = {26},
  number = {3},
  pages = {413--439},
  author = {Manuel Ruiz and Fernando L{\'{o}}pez and Antonio P{\'{a}}ez},
  title = {Comparison of thematic maps using symbolic entropy},
  journal = {International Journal of Geographical Information Science}
}

@article{lopez2012,
  title={Distribution-free inference for q (m) based on permutational bootstrapping: an application to the spatial co-location pattern of firms in madrid},
  author={L{\'o}pez, Fernando A and P{\'a}ez, Antonio},
  journal={Estad{\'\i}stica Espa{\~n}ola},
  volume={54},
  number={177},
  pages={135--156},
  year={2012}
}

@article{ruiz2021,
  year = {2021},
  author = {Manuel Ruiz and Fernando L{\'{o}}pez and Antonio P{\'{a}}ez},
  title = {A test for global and local homogeneity of categorical data based on spatial runs},
  journal = {Working paper}
}

@article{pebesma2018,
    author = {Edzer Pebesma},
    title = {{Simple Features for R: Standardized Support for Spatial Vector Data}},
    year = {2018},
    journal = {{The R Journal}},
    doi = {10.32614/RJ-2018-009},
    pages = {439--446},
    volume = {10},
    number = {1},
  }

@article{paez2021,
  title={A spatio-temporal analysis of the environmental correlates of COVID-19 incidence in Spain},
  author={Paez, Antonio and Lopez, Fernando A and Menezes, Tatiane and Cavalcanti, Renata and Pitta, Maira Galdino da Rocha},
  journal={Geographical analysis},
  volume={53},
  number={3},
  pages={397--421},
  doi = {10.1111/gean.12241},
  year={2021},
  publisher={Wiley Online Library}
}

@article{ruiz2010,
  title={Testing for spatial association of qualitative data using symbolic dynamics},
  author={Ruiz, Manuel and L{\'o}pez, Fernando and P{\'a}ez, Antonio},
  journal={Journal of Geographical Systems},
  volume={12},
  number={3},
  pages={281--309},
  year={2010},
  doi = {10.1007/s10109-009-0100-1},
  publisher={Springer}
}

@book{Kanaroglou2016,
  doi = {10.4324/9781315610252},
  year = {2016},
  month = mar,
  publisher = {Routledge},
  author = {Pavlos Kanaroglou},
  title = {Spatial Analysis in Health Geography}
}

@Comment{jabref-meta: databaseType:bibtex;}


text:
#
# Copyright (c) 2019 Sung Ho Park and CSOS
#
# SPDX-License-Identifier: Apache-2.0
#

set_cache(UBINOS__BSP__BOARD_MODEL "STM32F769IDISCO" STRING)

set_cache(UBINOS__BSP__OPENOCD_CONFIG_FILE "${PROJECT_UBINOS_DIR}/resource/ubinos/bsp/arch/arm/cortexm/stm32f769idisco/openocd.cfg" PATH)

include(${CMAKE_CURRENT_LIST_DIR}/../stm32f769ieval/stm32f769ieval.cmake)

repository: ubinos/ubinos

repo_name: ubinos/ubinos

extension: cmake


text:
package assert

import "reflect"

// Ter represent a *testing.T
type Ter interface {
	Fail()
	Errorf(format string, args ...interface{})
}

// Fail will call t.Fail if msg is empty, else call t.Errorf
func Fail(t Ter, msg ...string) {
	if len(msg) > 0 {
		t.Errorf(msg[0])
	} else {
		t.Fail()
	}
}

// Equal will compare obj1 and obj2, and will fail if obj1 != obj2 or obj1 has different type with obj2
func Equal(t Ter, obj1, obj2 interface{}, msg ...string) {
	if !reflect.DeepEqual(obj1, obj2) {
		Fail(t, msg...)
	}
}

// NotEqual will compare obj1 and obj2, and will fail if obj1 == obj2
func NotEqual(t Ter, obj1, obj2 interface{}, msg ...string) {
	if reflect.DeepEqual(obj1, obj2) {
		Fail(t, msg...)
	}
}

// Nil will compare obj1 and nil, and will fail if obj1 != nil
func Nil(t Ter, obj1 interface{}, msg ...string) {
	if !isNil(obj1) {
		Fail(t, msg...)
	}
}

// NotNil will compare obj1 and nil, and will fail if obj1 == nil
func NotNil(t Ter, obj1 interface{}, msg ...string) {
	if isNil(obj1) {
		Fail(t, msg...)
	}
}

// LessThan will compare obj1 and obj2, and will fail if obj1 >= obj2 or obj1 has different type with obj2
func LessThan(t Ter, obj1, obj2 interface{}, msg ...string) {
	if !lessThan(obj1, obj2) {
		Fail(t, msg...)
	}
}

// LessThanOrEqual will compare obj1 and obj2, and will fail if obj1 > obj2 or obj1 has different type with obj2
func LessThanOrEqual(t Ter, obj1, obj2 interface{}, msg ...string) {
	if !lessThanOrEqual(obj1, obj2) {
		Fail(t, msg...)
	}
}

// GreaterThan will compare obj1 and obj2, and will fail if obj1 <= obj2 or obj1 has different type with obj2
func GreaterThan(t Ter, obj1, obj2 interface{}, msg ...string) {
	if !greaterThan(obj1, obj2) {
		Fail(t, msg...)
	}
}

// GreaterThanOrEqual will compare obj1 and obj2, and will fail if obj1 < obj2 or obj1 has different type with obj2
func GreaterThanOrEqual(t Ter, obj1, obj2 interface{}, msg ...string) {
	if !greaterThanOrEqual(obj1, obj2) {
		Fail(t, msg...)
	}
}

// True wil fail if obj1 is not true
func True(t Ter, obj1 bool, msg ...string) {
	if !obj1 {
		Fail(t, msg...)
	}
}

// False wil fail if obj1 is true
func False(t Ter, obj1 bool, msg ...string) {
	if obj1 {
		Fail(t, msg...)
	}
}

// lessThan will compare obj1 and obj2, and will return false if obj1 >= obj2 or obj1 has different type with obj2
func lessThan(obj1, obj2 interface{}) bool {
	t1 := reflect.TypeOf(obj1)
	t2 := reflect.TypeOf(obj2)
	if t1 != t2 {
		return false
	}
	switch v1 := obj1.(type) {
	case int:
		return v1 < obj2.(int)
	case int8:
		return v1 < obj2.(int8)
	case int16:
		return v1 < obj2.(int16)
	case int32:
		return v1 < obj2.(int32)
	case int64:
		return v1 < obj2.(int64)
	case float32:
		return v1 < obj2.(float32)
	case float64:
		return v1 < obj2.(float64)

	}
	return false
}

// lessThanOrEqual will compare obj1 and obj2, and will return false if obj1 > obj2 or obj1 has different type with obj2
func lessThanOrEqual(obj1, obj2 interface{}) bool {
	t1 := reflect.TypeOf(obj1)
	t2 := reflect.TypeOf(obj2)
	if t1 != t2 {
		return false
	}
	switch v1 := obj1.(type) {
	case int:
		return v1 <= obj2.(int)
	case int8:
		return v1 <= obj2.(int8)
	case int16:
		return v1 <= obj2.(int16)
	case int32:
		return v1 <= obj2.(int32)
	case int64:
		return v1 <= obj2.(int64)
	case float32:
		return v1 <= obj2.(float32)
	case float64:
		return v1 <= obj2.(float64)

	}
	return false
}

// greaterThan will compare obj1 and obj2, and will return false if obj1 <= obj2 or obj1 has different type with obj2
func greaterThan(obj1, obj2 interface{}) bool {
	t1 := reflect.TypeOf(obj1)
	t2 := reflect.TypeOf(obj2)
	if t1 != t2 {
		return false
	}
	switch v1 := obj1.(type) {
	case int:
		return v1 > obj2.(int)
	case int8:
		return v1 > obj2.(int8)
	case int16:
		return v1 > obj2.(int16)
	case int32:
		return v1 > obj2.(int32)
	case int64:
		return v1 > obj2.(int64)
	case float32:
		return v1 > obj2.(float32)
	case float64:
		return v1 > obj2.(float64)

	}
	return false
}

// greaterThanOrEqual will compare obj1 and obj2, and will return false if obj1 < obj2 or obj1 has different type with obj2
func greaterThanOrEqual(obj1, obj2 interface{}) bool {
	t1 := reflect.TypeOf(obj1)
	t2 := reflect.TypeOf(obj2)
	if t1 != t2 {
		return false
	}
	switch v1 := obj1.(type) {
	case int:
		return v1 >= obj2.(int)
	case int8:
		return v1 >= obj2.(int8)
	case int16:
		return v1 >= obj2.(int16)
	case int32:
		return v1 >= obj2.(int32)
	case int64:
		return v1 >= obj2.(int64)
	case float32:
		return v1 >= obj2.(float32)
	case float64:
		return v1 >= obj2.(float64)

	}
	return false
}

func isNil(i interface{}) (isnil bool) {
	defer func() {
		if r := recover(); r != nil {
			isnil = false
		}
	}()
	return i == nil || reflect.ValueOf(i).IsNil()
}

repository: philchia/gotest

repo_name: philchia/gotest


text:
INHIBIT_AUTOTOOLS_DEPS = "1"
include gawk_${PV}.bb

inherit native

DEPENDS = ""
PATCH_DEPENDS = ""
PATCHCLEANCMD = ""
PATCHCMD = "num='%s'; name='%s'; file='%s'; patch -p "$num" -i "$file""

S = "${WORKDIR}/gawk-${PV}"

do_stage() {
	install -d ${STAGING_BINDIR}
	install -m 755 gawk ${STAGING_BINDIR}
}

repository: Terentyev/familiar-linux

repo_name: Terentyev/familiar-linux


text:
// Package bezier2 contains functions for 2D cubic Bezier splines.
// See: http://en.wikipedia.org/wiki/B%C3%A9zier_curve
package bezier2

import (
	"fmt"

	"github.com/ungerik/go3d/float64/vec2"
)

// T holds the data to define a cubic bezier spline.
type T struct {
	P0, P1, P2, P3 vec2.T
}

// Parse parses T from a string. See also String()
func Parse(s string) (r T, err error) {
	_, err = fmt.Sscan(s,
		&r.P0[0], &r.P0[1],
		&r.P1[0], &r.P1[1],
		&r.P2[0], &r.P2[1],
		&r.P3[0], &r.P3[1],
	)
	return r, err
}

// String formats T as string. See also Parse().
func (bez *T) String() string {
	return fmt.Sprintf("%s %s %s %s",
		bez.P0.String(), bez.P1.String(),
		bez.P2.String(), bez.P3.String(),
	)
}

// Point returns a point on a cubic bezier spline at t (0,1).
func (bez *T) Point(t float64) vec2.T {
	return Point(&bez.P0, &bez.P1, &bez.P2, &bez.P3, t)
}

// Tangent returns a tangent on a cubic bezier spline at t (0,1).
func (bez *T) Tangent(t float64) vec2.T {
	return Tangent(&bez.P0, &bez.P1, &bez.P2, &bez.P3, t)
}

// Length returns the length of a cubic bezier spline from A.Point to t (0,1).
func (bez *T) Length(t float64) float64 {
	return Length(&bez.P0, &bez.P1, &bez.P2, &bez.P3, t)
}

// Point returns a point on a cubic bezier spline at t (0,1).
func Point(p0, p1, p2, p3 *vec2.T, t float64) vec2.T {
	t1 := 1.0 - t

	f := t1 * t1 * t1
	result := p0.Scaled(f)

	f = 3.0 * t1 * t1 * t
	p1f := p1.Scaled(f)
	result.Add(&p1f)

	f = 3.0 * t1 * t * t
	p2f := p2.Scaled(f)
	result.Add(&p2f)

	f = t * t * t
	p3f := p3.Scaled(f)
	result.Add(&p3f)

	return result
}

// Tangent returns a tangent on a cubic bezier spline at t (0,1).
func Tangent(p0, p1, p2, p3 *vec2.T, t float64) vec2.T {
	t1 := 1.0 - t

	f := 3.0 * t1 * t1
	p1f := vec2.Sub(p1, p0)
	result := p1f.Scaled(f)

	f = 6.0 * t1 * t
	p2f := vec2.Sub(p2, p1)
	p2f.Scale(f)
	result.Add(&p2f)

	f = 3.0 * t * t
	p3f := vec2.Sub(p3, p2)
	p3f.Scale(f)
	result.Add(&p3f)

	if result[0] == 0 && result[1] == 0 {
		fmt.Printf("zero tangent!  p0=%v, p1=%v, p2=%v, p3=%v, t=%v\n", p0, p1, p2, p3, t)
		panic("zero tangent of bezier2")
	}

	return result
}

// Length returns the length of a cubic bezier spline from p0 to t (0,1).
func Length(p0, p1, p2, p3 *vec2.T, t float64) float64 {
	sqrT := t * t
	t1 := sqrT * 0.5
	t2 := sqrT * t * 1.0 / 3.0
	t3 := sqrT*sqrT + 1.0/4.0

	f := 2*t3 - 3*t2 + t
	result := p0.Scaled(f)

	f = t3 - 2*t2 + t1
	tAf := p1.Scaled(f)
	result.Add(&tAf)

	f = t3 - t2
	tBf := p3.Scaled(f)
	result.Add(&tBf)

	f = -2*t3 + 3*t2
	pBf := p2.Scaled(f)
	result.Add(&pBf)

	return result.Length()
}


text:
SUMMARY = "Parser of the C language, written in pure Python"
LICENSE = "BSD-3-Clause"
LIC_FILES_CHKSUM = "file://LICENSE;md5=8fb364772b1441821d391591f340c35a"

SRC_URI[md5sum] = "a2bc8d28c923b4fe2b2c3b4b51a4f935"
SRC_URI[sha256sum] = "7959b4a74abdc27b312fed1c21e6caf9309ce0b29ea86b591fd2e99ecdf27f73"

inherit pypi setuptools

BBCLASSEXTEND = "native"

repository: reMarkable/meta-openembedded

repo_name: reMarkable/meta-openembedded

branch_name: refs/heads/zero-gravitas

gha_language: BitBake


text:
package decoders

import (
	"time"
)

func parseTime(vals []string) (time.Time, error) {
	var t time.Time
	var err error

	// don't try to parse empty time values, it will raise an error
	if len(vals) == 0 || vals[0] == "" {
		return t, nil
	}

	for _, layout := range timeFormats {
		t, err = time.Parse(layout, vals[0])
		if err == nil {
			return t, nil
		}
	}

	if err != nil {
		return t, err
	}

	return t, nil
}

repository: gobuffalo/buffalo

repo_name: gobuffalo/buffalo


text:
include ti-compat-bluetooth.inc
COMPAT_BLUETOOTH_VERSION = "2011-11-29-r4-11"
MACHINE_KERNEL_PR_append = "a"

SRC_URI = "https://gforge.ti.com/gf/download/frsrelease/741/5238/compat-bluetooth-wl12xx-2011-11-29-r4-11.tar.gz"

SRC_URI[md5sum] = "ddfddf57cb4aa7f0f37305dbecc28d0c"
SRC_URI[sha256sum] = "f81c82b02b9ca7024b2314b9ab5cd43208bea510e7774b9d0ff33fde7d79a49d"


text:
package issues

import (
	"testing"

	"github.com/m-lab/go/prometheusx/promtest"
)

func TestMetrics(t *testing.T) {
	rateLimit.WithLabelValues("x")
	rateRemaining.WithLabelValues("x")
	rateResetTime.WithLabelValues("x")
	operationCount.WithLabelValues("x")
	promtest.LintMetrics(t)
}

repository: m-lab/alertmanager-github-receiver

repo_name: m-lab/alertmanager-github-receiver


text:
// Package addons gather all the command handlers related to addons in general
// Some specific treatment are done for database addons (like displaying
// database feature status)
package addons

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/olekukonko/tablewriter"
	"gopkg.in/errgo.v1"

	"github.com/Scalingo/cli/config"
	"github.com/Scalingo/cli/utils"
)

// Info is the command handler displaying static information about one given addon
func Info(ctx context.Context, app, addon string) error {
	c, err := config.ScalingoClient(ctx)
	if err != nil {
		return errgo.Notef(err, "fail to get Scalingo client")
	}

	addonInfo, err := c.AddonShow(ctx, app, addon)
	if err != nil {
		return errgo.Notef(err, "fail to get addon information")
	}

	dbInfo, err := c.DatabaseShow(ctx, app, addon)
	if err != nil {
		return errgo.Notef(err, "fail to get database information")
	}

	forceSsl, internetAccess := "disabled", "disabled"
	for _, feature := range dbInfo.Features {
		if feature.Name == "force-ssl" {
			forceSsl = strings.ToLower(string(feature.Status))
		} else if feature.Name == "publicly-available" {
			internetAccess = strings.ToLower(string(feature.Status))
		}
	}

	t := tablewriter.NewWriter(os.Stdout)
	t.Append([]string{"Database Type", fmt.Sprintf("%v", dbInfo.TypeName)})
	t.Append([]string{"Version", fmt.Sprintf("%v", dbInfo.ReadableVersion)})
	t.Append([]string{"Status", fmt.Sprintf("%v", addonInfo.Status)})
	t.Append([]string{"Plan", fmt.Sprintf("%v", addonInfo.Plan.Name)})
	t.Append([]string{"Force TLS", forceSsl})
	t.Append([]string{"Internet Accessibility", internetAccess})
	t.Append([]string{"Maintenance window", utils.FormatMaintenanceWindowWithTimezone(dbInfo.MaintenanceWindow, time.Local)})

	t.Render()

	return nil
}

repository: Scalingo/cli

repo_name: Scalingo/cli

gha_license_id: NOASSERTION


text:
DESCRIPTION = "A library for displaying a TV-like on-screen display in X."
SECTION = "libs/x11"
DEPENDS = "virtual/libx11 libxext"
LICENSE = "LGPL"
SRCREV = "627"
PV = "2.2.15+svnr${SRCPV}"
PR = "r6"

SRC_URI = "svn://libxosd.svn.sourceforge.net/svnroot/libxosd/source;module=current;proto=https \
           file://autofoo.patch \
           file://use-sane-default-font.patch \
           file://fix_duplicate_xosd_is_onscreen.patch \
           "

S = "${WORKDIR}/current"

inherit autotools binconfig

PACKAGES =+ "${PN}-examples-dbg ${PN}-examples"
FILES_${PN}-examples = "${bindir}/osd_cat"
FILES_${PN}-examples-dbg += "${bindir}/.debug/"
FILES_${PN}-dev += "${bindir}/xosd-config"
FILES_${PN} = "${libdir}/libxosd.so.*"


text:
package book

//Metadata stores metadata for books
type Metadata struct {
	Website     ScrapingWebsite `json:"website" yaml:"Website"`
	Title       string          `json:"title" yaml:"Title"`
	Author      string          `json:"author" yaml:"Author"`
	Language    string          `json:"language" yaml:"Language"`
	Year        string          `json:"year" yaml:"Year"`
	Cover       string          `json:"cover" yaml:"CoverImageURL"`
	ChapterURLs []string        `json:"chapterURLs" yaml:"ChapterURLs"`
	Format      Exporters       `json:"exportFormat" yaml:"ExportFormat"`
}


text:
SECTION = "unknown"
DESCRIPTION = "SWIG - Simplified Wrapper and Interface Generator"
LICENSE = "BSD"
#SRC_URI = "${SOURCEFORGE_MIRROR}/swig/swig-${PV}.tar.gz"
SRC_URI = "http://heanet.dl.sourceforge.net/sourceforge/swig/swig-1.3.21.tar.gz"
S = "${WORKDIR}/SWIG-${PV}"

inherit autotools

EXTRA_OECONF = "--with-python=${STAGING_BINDIR} --with-swiglibdir=${STAGING_DIR}/${BUILD_SYS}/swig"

do_configure() {
	oe_runconf
}

repository: BackupTheBerlios/openslug-svn

repo_name: BackupTheBerlios/openslug-svn