text:
package tests

import (
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"github.com/ShoshinNikita/budget-manager/internal/db"
	"github.com/ShoshinNikita/budget-manager/internal/pkg/money"
	"github.com/ShoshinNikita/budget-manager/internal/web/api/models"
)

func TestBasicUsage(t *testing.T) {
	t.Parallel()

	RunTest(t, TestCases{
		{Name: "spend types", Fn: testBasicUsage_SpendTypes},
		{Name: "incomes", Fn: testBasicUsage_Incomes},
		{Name: "monthly payments", Fn: testBasicUsage_MonthlyPayments},
		{Name: "spends", Fn: testBasicUsage_Spends},
		{Name: "search spends", Fn: testBasicUsage_SearchSpends},
	})
}

func testBasicUsage_SpendTypes(t *testing.T, host string) {
	require := require.New(t)

	// Add
	for i, req := range []RequestCreated{
		{POST, SpendTypesPath, models.AddSpendTypeReq{Name: "f00d"}},                  // 1
		{POST, SpendTypesPath, models.AddSpendTypeReq{Name: "fastfood", ParentID: 1}}, // 2
		{POST, SpendTypesPath, models.AddSpendTypeReq{Name: "pizza", ParentID: 2}},    // 3
		{POST, SpendTypesPath, models.AddSpendTypeReq{Name: "travel"}},                // 4
		{POST, SpendTypesPath, models.AddSpendTypeReq{Name: "avia", ParentID: 4}},     // 5
		{POST, SpendTypesPath, models.AddSpendTypeReq{Name: "house"}},                 // 6
		{POST, SpendTypesPath, models.AddSpendTypeReq{Name: "entertainment"}},         // 7
	} {
		var resp models.AddSpendTypeResp
		req.Send(t, host, &resp)
		require.Equal(uint(i+1), resp.ID)
	}

	// Manage
	for _, req := range []RequestOK{
		{PUT, SpendTypesPath, models.EditSpendTypeReq{ID: 1, Name: ptrStr("food")}},
		{PUT, SpendTypesPath, models.EditSpendTypeReq{ID: 3, ParentID: ptrUint(1)}},
		{DELETE, SpendTypesPath, models.RemoveSpendTypeReq{ID: 5}},
	} {
		req.Send(t, host, nil)
	}

	// Check
	var resp models.GetSpendTypesResp
	RequestOK{GET, SpendTypesPath, nil}.Send(t, host, &resp)
	require.Equal(
		[]db.SpendType{
			{ID: 1, Name: "food"},
			{ID: 2, Name: "fastfood", ParentID: 1},
			{ID: 3, Name: "pizza", ParentID: 1},
			{ID: 4, Name: "travel"},
			{ID: 6, Name: "house"},
			{ID: 7, Name: "entertainment"},
		},
		resp.SpendTypes,
	)
}

func testBasicUsage_Incomes(t *testing.T, host string) {
	require := require.New(t)

	// Add
	for i, req := range []RequestCreated{
		{POST, IncomesPath, models.AddIncomeReq{MonthID: 1, Title: "salary", Income: 2500}},                // 1
		{POST, IncomesPath, models.AddIncomeReq{MonthID: 1, Title: "gifts", Income: 500}},                  // 2
		{POST, IncomesPath, models.AddIncomeReq{MonthID: 1, Title: "temp", Income: 100}},                   // 3
		{POST, IncomesPath, models.AddIncomeReq{MonthID: 1, Title: "cashback", Notes: "123", Income: 100}}, // 4
	} {
		var resp models.AddIncomeResp
		req.Send(t, host, &resp)
		require.Equal(uint(i+1), resp.ID)
	}

	// Manage
	for _, req := range []RequestOK{
		{PUT, IncomesPath, models.EditIncomeReq{ID: 2, Title: ptrStr("gift"), Notes: ptrStr("from friends")}},
		{PUT, IncomesPath, models.EditIncomeReq{ID: 4, Income: ptrFloat(50)}},
		{DELETE, IncomesPath, models.RemoveSpendTypeReq{ID: 3}},
	} {
		req.Send(t, host, nil)
	}

	// Check
	month := getCurrentMonth(t, host)

	expectedIncomes := []db.Income{
		{ID: 1, Title: "salary", Income: money.FromInt(2500)},
		{ID: 2, Title: "gift", Notes: "from friends", Income: money.FromInt(500)},
		{ID: 4, Title: "cashback", Notes: "123", Income: money.FromInt(50)},
	}
	for i := range expectedIncomes {
		expectedIncomes[i].Year = month.Year
		expectedIncomes[i].Month = month.Month
	}
	require.Equal(expectedIncomes, month.Incomes)

	checkMonth(require, 3050, 0, 0, month)
}

func testBasicUsage_MonthlyPayments(t *testing.T, host string) {
	require := require.New(t)

	// Add
	for i, req := range []RequestCreated{
		{POST, MonthlyPaymentsPath, models.AddMonthlyPaymentReq{MonthID: 1, Title: "rent", TypeID: 6, Cost: 800}},         // 1
		{POST, MonthlyPaymentsPath, models.AddMonthlyPaymentReq{MonthID: 1, Title: "patre0n", Cost: 50}},                  // 2
		{POST, MonthlyPaymentsPath, models.AddMonthlyPaymentReq{MonthID: 1, Title: "netflix", Notes: "remove", Cost: 20}}, // 3
		{POST, MonthlyPaymentsPath, models.AddMonthlyPaymentReq{MonthID: 1, Title: "temp", Notes: "123", Cost: 100}},      // 4
	} {
		var resp models.AddMonthlyPaymentResp
		req.Send(t, host, &resp)
		require.Equal(uint(i+1), resp.ID)
	}

	// Manage
	for _, req := range []RequestOK{
		{PUT, MonthlyPaymentsPath, models.EditMonthlyPaymentReq{ID: 1, TypeID: ptrUint(0)}},
		{PUT, MonthlyPaymentsPath, models.EditMonthlyPaymentReq{ID: 2, Title: ptrStr("patreon"), Notes: ptrStr("with VAT")}},
		{PUT, MonthlyPaymentsPath, models.EditMonthlyPaymentReq{ID: 3, TypeID: ptrUint(7), Notes: ptrStr(""), Cost: ptrFloat(30)}},
		{DELETE, MonthlyPaymentsPath, models.RemoveMonthlyPaymentReq{ID: 4}},
	} {
		req.Send(t, host, nil)
	}

	// Check
	month := getCurrentMonth(t, host)

	expectedMonthlyPayments := []db.MonthlyPayment{
		{ID: 1, Title: "rent", Cost: money.FromInt(800)},
		{ID: 2, Title: "patreon", Notes: "with VAT", Cost: money.FromInt(50)},
		{ID: 3, Title: "netflix", Type: &db.SpendType{ID: 7, Name: "entertainment"}, Cost: money.FromInt(30)},
	}
	for i := range expectedMonthlyPayments {
		expectedMonthlyPayments[i].Year = month.Year
		expectedMonthlyPayments[i].Month = month.Month
	}
	require.Equal(expectedMonthlyPayments, month.MonthlyPayments)

	checkMonth(require, 3050, -880, 0, month)
}

func testBasicUsage_Spends(t *testing.T, host string) {
	require := require.New(t)

	// Add
	for i, req := range []RequestCreated{
		{POST, SpendsPath, models.AddSpendReq{DayID: 1, Title: "bread", Notes: "fresh", TypeID: 1, Cost: 2}}, // 1
		{POST, SpendsPath, models.AddSpendReq{DayID: 1, Title: "grocery", TypeID: 1, Cost: 10}},              // 2
		{POST, SpendsPath, models.AddSpendReq{DayID: 1, Title: "milk", TypeID: 1, Cost: 2}},                  // 3
		//
		{POST, SpendsPath, models.AddSpendReq{DayID: 3, Title: "oil", TypeID: 1, Cost: 7}},            // 4
		{POST, SpendsPath, models.AddSpendReq{DayID: 3, Title: "dinner in KFC", TypeID: 2, Cost: 15}}, // 5
		//
		{POST, SpendsPath, models.AddSpendReq{DayID: 10, Title: "bicycle", Notes: "https://example.com", Cost: 500}}, // 6
		//
		{POST, SpendsPath, models.AddSpendReq{DayID: 11, Title: "meat", TypeID: 1, Cost: 20}}, // 7
		{POST, SpendsPath, models.AddSpendReq{DayID: 11, Title: "egg", TypeID: 1, Cost: 7}},   // 8
		//
		{POST, SpendsPath, models.AddSpendReq{DayID: 12, Title: "pizza", Cost: 100}}, // 9
		//
		{POST, SpendsPath, models.AddSpendReq{DayID: 15, Title: "book American Gods", Notes: "as a gift", Cost: 30}}, // 10
		//
		{POST, SpendsPath, models.AddSpendReq{DayID: 16, Title: "new mirror in the bathroom", TypeID: 6, Cost: 150}}, // 11
		{POST, SpendsPath, models.AddSpendReq{DayID: 16, Title: "new towels", TypeID: 6, Cost: 50}},                  // 12
		{POST, SpendsPath, models.AddSpendReq{DayID: 16, Title: "temp", Cost: 0}},                                    // 13
	} {
		var resp models.AddMonthlyPaymentResp
		req.Send(t, host, &resp)
		require.Equal(uint(i+1), resp.ID)
	}

	// Manage
	for _, req := range []RequestOK{
		{PUT, SpendsPath, models.EditSpendReq{ID: 4, TypeID: ptrUint(0)}},
		{PUT, SpendsPath, models.EditSpendReq{ID: 8, Title: ptrStr("eggs"), Notes: ptrStr("10 count"), Cost: ptrFloat(8)}},
		{PUT, SpendsPath, models.EditSpendReq{ID: 9, TypeID: ptrUint(3)}},
		{DELETE, SpendsPath, models.RemoveSpendReq{ID: 13}},
	} {
		req.Send(t, host, nil)
	}

	// Check
	month := getCurrentMonth(t, host)

	expectedDays := []db.Day{
		{ID: 1, Spends: []db.Spend{
			{ID: 1, Title: "bread", Type: &db.SpendType{ID: 1, Name: "food"}, Notes: "fresh", Cost: money.FromInt(2)},
			{ID: 2, Title: "grocery", Type: &db.SpendType{ID: 1, Name: "food"}, Cost: money.FromInt(10)},
			{ID: 3, Title: "milk", Type: &db.SpendType{ID: 1, Name: "food"}, Cost: money.FromInt(2)},
		}},
		{ID: 2, Spends: []db.Spend{}},
		{ID: 3, Spends: []db.Spend{
			{ID: 4, Title: "oil", Cost: money.FromInt(7)},
			{ID: 5, Title: "dinner in KFC", Type: &db.SpendType{ID: 2, Name: "fastfood", ParentID: 1}, Cost: money.FromInt(15)},
		}},
		{ID: 4, Spends: []db.Spend{}},
		{ID: 5, Spends: []db.Spend{}},
		{ID: 6, Spends: []db.Spend{}},
		{ID: 7, Spends: []db.Spend{}},
		{ID: 8, Spends: []db.Spend{}},
		{ID: 9, Spends: []db.Spend{}},
		{ID: 10, Spends: []db.Spend{
			{ID: 6, Title: "bicycle", Notes: "https://example.com", Cost: money.FromInt(500)},
		}},
		{ID: 11, Spends: []db.Spend{
			{ID: 7, Title: "meat", Type: &db.SpendType{ID: 1, Name: "food"}, Cost: money.FromInt(20)},
			{ID: 8, Title: "eggs", Type: &db.SpendType{ID: 1, Name: "food"}, Notes: "10 count", Cost: money.FromInt(8)},
		}},
		{ID: 12, Spends: []db.Spend{
			{ID: 9, Title: "pizza", Type: &db.SpendType{ID: 3, Name: "pizza", ParentID: 1}, Cost: money.FromInt(100)},
		}},
		{ID: 13, Spends: []db.Spend{}},
		{ID: 14, Spends: []db.Spend{}},
		{ID: 15, Spends: []db.Spend{
			{ID: 10, Title: "book American Gods", Notes: "as a gift", Cost: money.FromInt(30)},
		}},
		{ID: 16, Spends: []db.Spend{
			{ID: 11, Title: "new mirror in the bathroom", Type: &db.SpendType{ID: 6, Name: "house"}, Cost: money.FromInt(150)},
			{ID: 12, Title: "new towels", Type: &db.SpendType{ID: 6, Name: "house"}, Cost: money.FromInt(50)},
		}},
	}
	for i := len(expectedDays) + 1; i <= len(month.Days); i++ {
		expectedDays = append(expectedDays, db.Day{ID: uint(i), Spends: []db.Spend{}})
	}
	for i := range expectedDays {
		expectedDays[i].Year = month.Year
		expectedDays[i].Month = month.Month
		expectedDays[i].Day = int(expectedDays[i].ID)
		for j := range expectedDays[i].Spends {
			expectedDays[i].Spends[j].Year = expectedDays[i].Year
			expectedDays[i].Spends[j].Month = expectedDays[i].Month
			expectedDays[i].Spends[j].Day = expectedDays[i].Day
		}

		var prevSaldo money.Money
		if i > 0 {
			prevSaldo = expectedDays[i-1].Saldo
		}
		expectedDays[i].Saldo = prevSaldo.Add(month.DailyBudget)
		for _, s := range expectedDays[i].Spends {
			expectedDays[i].Saldo = expectedDays[i].Saldo.Sub(s.Cost)
		}
	}
	require.Equal(expectedDays, month.Days)

	checkMonth(require, 3050, -880, -894, month)
}

func testBasicUsage_SearchSpends(t *testing.T, host string) {
	// Prepare spends
	allSpends := []db.Spend{
		{ID: 1, Day: 1, Title: "bread", Type: &db.SpendType{ID: 1, Name: "food"}, Notes: "fresh", Cost: money.FromInt(2)},
		{ID: 2, Day: 1, Title: "grocery", Type: &db.SpendType{ID: 1, Name: "food"}, Cost: money.FromInt(10)},
		{ID: 3, Day: 1, Title: "milk", Type: &db.SpendType{ID: 1, Name: "food"}, Cost: money.FromInt(2)},
		{ID: 4, Day: 3, Title: "oil", Cost: money.FromInt(7)},
		{ID: 5, Day: 3, Title: "dinner in KFC", Type: &db.SpendType{ID: 2, Name: "fastfood", ParentID: 1}, Cost: money.FromInt(15)},
		{ID: 6, Day: 10, Title: "bicycle", Notes: "https://example.com", Cost: money.FromInt(500)},
		{ID: 7, Day: 11, Title: "meat", Type: &db.SpendType{ID: 1, Name: "food"}, Cost: money.FromInt(20)},
		{ID: 8, Day: 11, Title: "eggs", Type: &db.SpendType{ID: 1, Name: "food"}, Notes: "10 count", Cost: money.FromInt(8)},
		{ID: 9, Day: 12, Title: "pizza", Type: &db.SpendType{ID: 3, Name: "pizza", ParentID: 1}, Cost: money.FromInt(100)},
		{ID: 10, Day: 15, Title: "book American Gods", Notes: "as a gift", Cost: money.FromInt(30)},
		{ID: 11, Day: 16, Title: "new mirror in the bathroom", Type: &db.SpendType{ID: 6, Name: "house"}, Cost: money.FromInt(150)},
		{ID: 12, Day: 16, Title: "new towels", Type: &db.SpendType{ID: 6, Name: "house"}, Cost: money.FromInt(50)},
	}
	month := getCurrentMonth(t, host)
	for i := range allSpends {
		allSpends[i].Year = month.Year
		allSpends[i].Month = month.Month
	}

	getSpends := func(ids ...uint) []db.Spend {
		res := make([]db.Spend, 0, len(ids))
		for _, id := range ids {
			for _, spend := range allSpends {
				if spend.ID == id {
					res = append(res, spend)
					break
				}
			}
		}
		return res
	}
	newDate := func(day int) time.Time {
		return time.Date(month.Year, month.Month, day, 0, 0, 0, 0, time.UTC)
	}

	for _, tt := range []struct {
		name string
		req  models.SearchSpendsReq
		ids  []uint
	}{
		{
			name: "all spends",
			req:  models.SearchSpendsReq{},
			ids:  []uint{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		},
		{
			name: "filter by title",
			req:  models.SearchSpendsReq{Title: "il"},
			ids:  []uint{3, 4},
		},
		{
			name: "filter by type",
			req:  models.SearchSpendsReq{TypeIDs: []uint{1, 2}},
			ids:  []uint{1, 2, 3, 5, 7, 8},
		},
		{
			name: "filter by notes",
			req:  models.SearchSpendsReq{Notes: "gift"},
			ids:  []uint{10},
		},
		{
			name: "filter by notes (exactly)",
			req:  models.SearchSpendsReq{Notes: "gift", NotesExactly: true},
			ids:  []uint{},
		},
		{
			name: "filter by cost (min)",
			req:  models.SearchSpendsReq{MinCost: 200},
			ids:  []uint{6},
		},
		{
			name: "filter by cost (max)",
			req:  models.SearchSpendsReq{MaxCost: 7},
			ids:  []uint{1, 3, 4},
		},
		{
			name: "filter by cost (min and max)",
			req:  models.SearchSpendsReq{MinCost: 10, MaxCost: 30},
			ids:  []uint{2, 5, 7, 10},
		},
		{
			name: "filter by time (after)",
			req:  models.SearchSpendsReq{After: newDate(15)},
			ids:  []uint{10, 11, 12},
		},
		{
			name: "filter by time (before)",
			req:  models.SearchSpendsReq{Before: newDate(2)},
			ids:  []uint{1, 2, 3},
		},
		{
			name: "filter by time (after and before)",
			req:  models.SearchSpendsReq{After: newDate(2), Before: newDate(7)},
			ids:  []uint{4, 5},
		},
		{
			name: "sort by cost desc",
			req:  models.SearchSpendsReq{MinCost: 7, MaxCost: 15, Sort: "cost", Order: "desc"},
			ids:  []uint{5, 2, 8, 4},
		},
		{
			name: "sort by title asc",
			req:  models.SearchSpendsReq{TypeIDs: []uint{1}, Sort: "title"},
			ids:  []uint{1, 8, 2, 7, 3},
		},
	} {
		tt := tt
		t.Run(tt.name, func(t *testing.T) {
			require := require.New(t)

			var resp models.SearchSpendsResp
			RequestOK{GET, SearchSpendsPath, tt.req}.Send(t, host, &resp)
			require.Equal(getSpends(tt.ids...), resp.Spends)
		})
	}
}

func getCurrentMonth(t *testing.T, host string) db.Month {
	// It's very unlikely that tests were run at the last seconds of a month,
	// and time.Now() will return the next month
	year, month, _ := time.Now().Date()

	var resp models.GetMonthResp
	RequestOK{GET, MonthsPath, models.GetMonthByDateReq{Year: year, Month: month}}.Send(t, host, &resp)
	return resp.Month
}

func checkMonth(require *require.Assertions, incomes, monthlyPayments, spends float64, month db.Month) {
	inc := money.FromFloat(incomes)
	require.Equal(inc, month.TotalIncome)

	mp := money.FromFloat(monthlyPayments)
	sp := money.FromFloat(spends)
	total := mp.Add(sp)
	require.Equal(total, month.TotalSpend)

	res := inc.Add(total) // spends and monthlyPayments are < 0
	require.Equal(res, month.Result)

	dailyBudget := inc.Add(mp).Div(int64(len(month.Days)))
	require.Equal(dailyBudget, month.DailyBudget)
}

repository: ShoshinNikita/budget-manager

repo_name: ShoshinNikita/budget-manager


text:
package benchmarking

import (
	"context"
	"log"
	"os"
	"testing"
	"time"

	"github.com/mongodb/mongo-go-driver/bson"
	"github.com/mongodb/mongo-go-driver/mongo"

	"go.opencensus.io/trace"
)

var addr string
var client *mongo.Client
var coll *mongo.Collection

func TestMain(m *testing.M) {
	var err error
	client, err = mongo.NewClient("mongodb://localhost:27017")
	if err != nil {
		log.Fatalf("client failed: %v", err)
	}
	coll = client.Database("foo").Collection("bar")
	os.Exit(m.Run())
}

func BenchmarkDeleteOne(b *testing.B) {
	traceBenchmarker(b, func(b *testing.B) {
		b.ReportAllocs()
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			b.StopTimer()
			// Insert one element before
			_, err := coll.InsertOne(context.Background(), map[string]string{"db": "mongo"})
			if err != nil {
				b.Fatalf("Insert one failed: %v", err)
			}
			b.StartTimer()

			filters := []*bson.Document{
				bson.NewDocument(bson.EC.String("db", "mongo")),
				bson.NewDocument(bson.EC.String("db", "unknown")),
			}
			for _, filter := range filters {
				_, err := coll.DeleteOne(context.Background(), filter)
				if err != nil {
					b.Fatalf("DeleteOne failed: %v", err)
				}
			}
		}
	})
}

func BenchmarkDeleteMany(b *testing.B) {
	traceBenchmarker(b, func(b *testing.B) {
		b.ReportAllocs()
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			b.StopTimer()
			// Insert some elements element before
			_, err := coll.InsertMany(context.Background(), []interface{}{
				map[string]interface{}{"v": "a", "vowel": true, "i": "a"},
				map[string]interface{}{"v": "b", "vowel": false, "i": "a"},
				map[string]interface{}{"v": "e", "vowel": true, "i": "a"},
				map[string]interface{}{"v": "i", "vowel": true, "i": "a"},
				map[string]interface{}{"v": "z", "vowel": false, "i": "a"},
				map[string]interface{}{"v": "c", "vowel": false, "i": "a"},
			})
			if err != nil {
				b.Fatalf("Insert many failed: %v", err)
			}
			b.StartTimer()

			filters := []*bson.Document{
				bson.NewDocument(bson.EC.String("vowel", "true")),
				bson.NewDocument(bson.EC.String("foo", "unknown")),
			}
			for _, filter := range filters {
				ctx := context.Background()
				_, err := coll.DeleteMany(ctx, filter)
				if err != nil {
					b.Fatalf("DeleteMany failed: %v", err)
				}
			}
		}
		_, _ = coll.DeleteMany(context.Background(), bson.NewDocument(bson.EC.String("i", "a")))
	})
}

func BenchmarkFindOne(b *testing.B) {
	traceBenchmarker(b, func(b *testing.B) {
		b.ReportAllocs()
		// Insert one element before
		_, err := coll.InsertOne(context.Background(), map[string]string{"db": "mongo"})
		if err != nil {
			b.Fatalf("Insert one failed: %v", err)
		}

		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			filters := []*bson.Document{
				bson.NewDocument(bson.EC.String("db", "mongo")),
				bson.NewDocument(bson.EC.String("db", "unknown")),
			}
			for _, filter := range filters {
				res := bson.NewDocument()
				_ = coll.FindOne(context.Background(), filter).Decode(res)
			}
		}

		// Clean up
		_, _ = coll.DeleteMany(context.Background(), bson.NewDocument(bson.EC.String("db", "mongo")))
	})
}

func BenchmarkFindMany(b *testing.B) {
	traceBenchmarker(b, func(b *testing.B) {
		b.ReportAllocs()
		// Insert some elements element before
		_, err := coll.InsertMany(context.Background(), []interface{}{
			map[string]interface{}{"v": "a", "vowel": true, "i": "a"},
			map[string]interface{}{"v": "b", "vowel": false, "i": "a"},
			map[string]interface{}{"v": "e", "vowel": true, "i": "a"},
			map[string]interface{}{"v": "i", "vowel": true, "i": "a"},
			map[string]interface{}{"v": "z", "vowel": false, "i": "a"},
			map[string]interface{}{"v": "c", "vowel": false, "i": "a"},
		})
		if err != nil {
			b.Fatalf("Insert many failed: %v", err)
		}

		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			filters := []*bson.Document{
				bson.NewDocument(bson.EC.String("vowel", "true")),
				bson.NewDocument(bson.EC.String("foo", "unknown")),
			}
			for _, filter := range filters {
				ctx := context.Background()
				cursor, err := coll.Find(ctx, filter)
				if err != nil {
					b.Fatalf("Find error: %v", err)
				}
				for cursor.Next(ctx) {
					res := bson.NewDocument()
					if err := cursor.Decode(res); err != nil {
						b.Fatalf("Cursor.Decode error: %v", err)
					}
				}
				if err := cursor.Err(); err != nil {
					b.Fatalf("Cursor.Err(): %v", err)
				}
			}
		}

		// Clean up
		_, _ = coll.DeleteMany(context.Background(), bson.NewDocument(bson.EC.String("i", "a")))
	})
}

func BenchmarkInsertOne(b *testing.B) {
	traceBenchmarker(b, func(b *testing.B) {
		b.ReportAllocs()
		b.ResetTimer()
		nowUnix := time.Now().Unix()
		for i := int64(0); i < int64(b.N); i++ {
			_, err := coll.InsertOne(context.Background(), map[string]interface{}{"db": "mongo", "index": nowUnix + i})
			if err != nil {
				b.Fatalf("InsertOne failed: %v", err)
			}
		}

		// Clean up
		_, _ = coll.DeleteMany(context.Background(), bson.NewDocument(bson.EC.String("db", "mongo")))
	})
}

func BenchmarkInsertMany(b *testing.B) {
	traceBenchmarker(b, func(b *testing.B) {
		b.ReportAllocs()
		n := 1000
		contents := make([]interface{}, n)
		for i := 0; i < n; i++ {
			contents[i] = map[string]interface{}{"db": "mongo", "index": i}
		}
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			_, err := coll.InsertMany(context.Background(), contents)
			if err != nil {
				b.Fatalf("InsertMany failed: %v", err)
			}
		}

		// Clean up
		_, _ = coll.DeleteMany(context.Background(), bson.NewDocument(bson.EC.String("db", "mongo")))
	})
}

func traceBenchmarker(b *testing.B, fn func(*testing.B)) {
	trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})
	b.Run("AlwaysSample", fn)
	trace.ApplyConfig(trace.Config{DefaultSampler: trace.NeverSample()})
	b.Run("NeverSample", fn)
}

repository: opencensus-integrations/mongo-go-driver

license_type: permissive

repo_name: opencensus-integrations/mongo-go-driver

branch_name: refs/heads/master

gha_language: Go

extension: go


text:
@article{biederman_recognition-by-components_1987,
	title = {Recognition-by-components: {A} theory of human image understanding},
	volume = {94},
	issn = {1939-1471(Electronic),0033-295X(Print)},
	shorttitle = {Recognition-by-components},
	doi = {10.1037/0033-295X.94.2.115},
	abstract = {The perceptual recognition of objects is conceptualized to be a process in which the image of the input is segmented at regions of deep concavity into an arrangement of simple geometric components. The fundamental assumption of the proposed theory, recognition-by-components (RBC), is that a modest set of generalized-cone components, called geons, can be derived from contrasts of five readily detectable properties of edges in a two-dimensional image. The detection of these properties is generally invariant over viewing position and image quality and consequently allows robust object perception when the image is projected from a novel viewpoint or is degraded. RBC thus provides a principled account of the heretofore undecided relation between the classic principles of perceptual organization and pattern recognition. The results from experiments on the perception of briefly presented pictures by human observers provide empirical support for the theory. (PsycINFO Database Record (c) 2019 APA, all rights reserved)},
	number = {2},
	journal = {Psychological Review},
	author = {Biederman, Irving},
	year = {1987},
	note = {Place: US
Publisher: American Psychological Association},
	keywords = {Pattern Discrimination, Perceptual Organization, Pictorial Stimuli, Spatial Imagery, Spatial Organization, Spatial Orientation (Perception)},
	pages = {115--147},
	file = {Full Text:/home/zubair/Zotero/storage/R4ZFMU5L/Biederman - 1987 - Recognition-by-components A theory of human image.pdf:application/pdf;Snapshot:/home/zubair/Zotero/storage/PAMAAA7M/1987-20898-001.html:text/html}
}

@article{blakemore_development_1970,
	title = {Development of the {Brain} depends on the {Visual} {Environment}},
	volume = {228},
	copyright = {1970 Nature Publishing Group},
	issn = {1476-4687},
	url = {https://www.nature.com/articles/228477a0},
	doi = {10.1038/228477a0},
	abstract = {IN a normal cat, neurones of the visual cortex are selective for the orientation of lines and edges in the visual field, and the preferred orientations of different cells are distributed all around the clock1. Hirsch and Spinelli2 have recently reported that early visual experience can change this organization. They reared kittens with one eye viewing vertical stripes, the other horizontal, and found that out of twenty-one neurones with elongated receptive fields all were monocularly driven, and in all but one case the orientation of the receptive field closely matched the pattern experienced by that eye.},
	language = {en},
	number = {5270},
	urldate = {2020-10-15},
	journal = {Nature},
	author = {Blakemore, Colin and Cooper, Grahame F.},
	month = oct,
	year = {1970},
	note = {Number: 5270
Publisher: Nature Publishing Group},
	pages = {477--478},
	file = {Snapshot:/home/zubair/Zotero/storage/2HXUJEWD/228477a0.html:text/html}
}

@article{todorovic_gestalt_2008,
	title = {Gestalt principles},
	volume = {3},
	issn = {1941-6016},
	url = {http://www.scholarpedia.org/article/Gestalt_principles},
	doi = {10.4249/scholarpedia.5345},
	language = {en},
	number = {12},
	urldate = {2020-10-15},
	journal = {Scholarpedia},
	author = {Todorovic, Dejan},
	month = dec,
	year = {2008},
	pages = {5345},
	file = {Snapshot:/home/zubair/Zotero/storage/CNBKJZTW/Gestalt_principles.html:text/html}
}

@article{rizzolatti_premotor_1996,
	title = {Premotor cortex and the recognition of motor actions},
	abstract = {In area F5 of the monkey premotor cortex there are neurons that discharge both when the monkey performs an action and when he observes a similar action made by another monkey or by the experimenter. We report here some of the properties of these 'mirror' neurons and we propose that their activity 'represents ' the observed action. We posit, then, that this motor epresentation is at the basis of the understanding of motor events. Finally, on the basis of some recent data showing that, in man, the observation of motor actions activate the posterior part of inferior frontal gyrus, we suggest that the development of the lateral verbal communication system in man derives from a more ancient communication system based on recognition of hand and face gestures.},
	journal = {Cognitive Brain Research},
	author = {Rizzolatti, Giacomo and Fadiga, Luciano and Gallese, Vittorio and Fogassi, Leonardo},
	year = {1996},
	pages = {131--141},
	file = {Citeseer - Full Text PDF:/home/zubair/Zotero/storage/N2VT5JSL/Rizzolatti et al. - 1996 - Premotor cortex and the recognition of motor actio.pdf:application/pdf;Citeseer - Snapshot:/home/zubair/Zotero/storage/K3BHJVH3/summary.html:text/html}
}

@article{pascolo_mirror-neuron_2009,
	series = {Xth {Congress} of the {Italian} {Society} of {Clinical} {Movement} {Analysis}},
	title = {The {Mirror}-{Neuron} {System} {Paradigm} and its consistency},
	volume = {30},
	issn = {0966-6362},
	url = {http://www.sciencedirect.com/science/article/pii/S0966636209002938},
	doi = {10.1016/j.gaitpost.2009.07.064},
	language = {en},
	urldate = {2020-10-15},
	journal = {Gait \& Posture},
	author = {Pascolo, P. B. and Ragogna, P. and Rossi, R.},
	month = oct,
	year = {2009},
	pages = {S65},
	annote = {According to scientists such as Hickok, Pascolo, and Dinstein, it is not clear whether mirror neurons really form a distinct class of cells (as opposed to an occasional phenomenon seen in cells that have other functions)},
	file = {ScienceDirect Snapshot:/home/zubair/Zotero/storage/JT4YYYXP/S0966636209002938.html:text/html}
}

@article{hickok_eight_2009,
	title = {Eight {Problems} for the {Mirror} {Neuron} {Theory} of {Action} {Understanding} in {Monkeys} and {Humans}},
	volume = {21},
	issn = {0898-929X},
	url = {https://doi.org/10.1162/jocn.2009.21189},
	doi = {10.1162/jocn.2009.21189},
	abstract = {The discovery of mirror neurons in macaque frontal cortex has sparked a resurgence of interest in motor/embodied theories of cognition. This critical review examines the evidence in support of one of these theories, namely, that mirror neurons provide the basis of action understanding. It is argued that there is no evidence from monkey data that directly tests this theory, and evidence from humans makes a strong case against the position.},
	number = {7},
	urldate = {2020-10-15},
	journal = {Journal of Cognitive Neuroscience},
	author = {Hickok, Gregory},
	month = jan,
	year = {2009},
	note = {Publisher: MIT Press},
	pages = {1229--1243},
	annote = {and whether mirror activity is a distinct type of response or simply an artifact of an overall facilitation of the motor system},
	file = {Accepted Version:/home/zubair/Zotero/storage/4J4TPVID/Hickok - 2009 - Eight Problems for the Mirror Neuron Theory of Act.pdf:application/pdf;Snapshot:/home/zubair/Zotero/storage/QMJBG3LV/jocn.2009.html:text/html}
}

@book{king_max_2005,
	title = {Max {Wertheimer} and {Gestalt} {Theory}},
	isbn = {978-1-4128-2826-0},
	abstract = {The ideas of Max Wertheimer (1880-1943), a founder of Gestalt theory, are discussed in almost all general books on the history of psychology, and in most introductory textbooks on psychology. This intellectual biography of Wertheimer is the first book-length treatment of a scholar whose ideas are recognized as of central importance to fields as varied as social psychology, cognitive neuroscience, problem solving, art, and visual neuroscience. King and Wertheimer trace the origins of Gestalt thought, demonstrating its continuing importance in fifteen chapters and several supplements to these chapters. They begin by reviewing Wertheimer\&\#39;s ancestry, family, and childhood in central Europe, and his formal education. They elaborate on his activities during the period in which he developed the ideas that were later to become central to Gestalt psychology, documenting the formal emergence of this school of thought and tracing its development during World War I. The maturation of the Gestalt school at the University of Berlin during 1922-29 is discussed in detail. Wertheimer\&\#39;s everyday life in America during his last decade is well documented, based in part on his son\&\#39;s recollections. The early reception of Gestalt theory in the United States is examined, with extensive references to articles in professional journals and periodicals. Wertheimer\&\#39;s relationships and interaction with three prominent psychologists of the time, Edwin Boring, Clark Hull, and Alexander Luria, are discussed, based on previosly unpublished correspondence. The final chapters discuss Wertheimer\&\#39;s essays on democracy, freedom, ethics, and truth, detail personal challenges Wertheimer faced during his last years. His major work, published after his death, is Productive Thinking. Its reception is examined, and a concluding chapter considers recent responses to Max Wertheimer and Gestalt theory.This intellectual biography will be of interest to psychologists and readers interested in science, modern European history, and the Holocaust. D. Brett King is senior instructor of psychology, Department of Psychology, University of Colorado at Boulder. Michael Wertheimer is Professor Emeritus of Psychology, University of Colorado at Boulder.},
	language = {en},
	publisher = {Transaction Publishers},
	author = {King, D. Brett and Wertheimer, Michael},
	month = jan,
	year = {2005},
	note = {Google-Books-ID: 44JwxvHnL40C},
	keywords = {Biography \& Autobiography / Social Scientists \& Psychologists}
}

@article{alluri_connectivity_2017,
	title = {Connectivity patterns during music listening: {Evidence} for action-based processing in musicians},
	volume = {38},
	copyright = {© 2017 Wiley Periodicals, Inc.},
	issn = {1097-0193},
	shorttitle = {Connectivity patterns during music listening},
	url = {https://onlinelibrary.wiley.com/doi/abs/10.1002/hbm.23565},
	doi = {10.1002/hbm.23565},
	abstract = {Musical expertise is visible both in the morphology and functionality of the brain. Recent research indicates that functional integration between multi-sensory, somato-motor, default-mode (DMN), and salience (SN) networks of the brain differentiates musicians from non-musicians during resting state. Here, we aimed at determining whether brain networks differentially exchange information in musicians as opposed to non-musicians during naturalistic music listening. Whole-brain graph-theory analyses were performed on participants' fMRI responses. Group-level differences revealed that musicians' primary hubs comprised cerebral and cerebellar sensorimotor regions whereas non-musicians' dominant hubs encompassed DMN-related regions. Community structure analyses of the key hubs revealed greater integration of motor and somatosensory homunculi representing the upper limbs and torso in musicians. Furthermore, musicians who started training at an earlier age exhibited greater centrality in the auditory cortex, and areas related to top-down processes, attention, emotion, somatosensory processing, and non-verbal processing of speech. We here reveal how brain networks organize themselves in a naturalistic music listening situation wherein musicians automatically engage neural networks that are action-based while non-musicians use those that are perception-based to process an incoming auditory stream. Hum Brain Mapp 38:2955–2970, 2017. © 2017 Wiley Periodicals, Inc.},
	language = {en},
	number = {6},
	urldate = {2020-10-15},
	journal = {Human Brain Mapping},
	author = {Alluri, Vinoo and Toiviainen, Petri and Burunat, Iballa and Kliuchko, Marina and Vuust, Peter and Brattico, Elvira},
	year = {2017},
	note = {\_eprint: https://onlinelibrary.wiley.com/doi/pdf/10.1002/hbm.23565},
	keywords = {fMRI, functional connectivity, graph theory, music, musical training},
	pages = {2955--2970},
	file = {Full Text PDF:/home/zubair/Zotero/storage/5PNW57D3/Alluri et al. - 2017 - Connectivity patterns during music listening Evid.pdf:application/pdf;Snapshot:/home/zubair/Zotero/storage/5762U63E/hbm.html:text/html}
}

@misc{chen_aphasia_nodate,
	title = {Aphasia rehabilitation based on mirror neuron theory: a randomized-block-design study of neuropsychology and functional magnetic resonance imaging},
	shorttitle = {Aphasia rehabilitation based on mirror neuron theory},
	url = {https://www.nrronline.org/article.asp?issn=1673-5374;year=2019;volume=14;issue=6;spage=1004;epage=1012;aulast=Chen},
	abstract = {Neural Regen Res, Official publication of Publishing House of Neural Regeneration Research China Association of Rehabilitation Medicine,China},
	urldate = {2020-10-15},
	author = {Chen},
	file = {Snapshot:/home/zubair/Zotero/storage/EGKC6XDL/article.html:text/html}
}

@article{behme_role_2014,
	title = {The role of mirror neurons in language acquisition and evolution},
	volume = {37},
	issn = {0140-525X, 1469-1825},
	url = {https://www.cambridge.org/core/journals/behavioral-and-brain-sciences/article/role-of-mirror-neurons-in-language-acquisition-and-evolution/50D8E6901D874E1E228968C3DEE0B941},
	doi = {10.1017/S0140525X13002203},
	abstract = {I argue that Cook et al.'s attack of the genetic hypothesis of mirror neurons misses its target because the authors miss the point that genetics may specify how neurons may learn, not what they learn. Paying more attention to recent work linking mirror neurons to language acquisition and evolution would strengthen Cook et al.'s arguments against a rigid genetic hypothesis.},
	language = {en},
	number = {2},
	urldate = {2020-10-15},
	journal = {Behavioral and Brain Sciences},
	author = {Behme, Christina},
	month = apr,
	year = {2014},
	note = {Publisher: Cambridge University Press},
	pages = {192--193}
}

@article{hickok_role_2010,
	title = {The {Role} of {Mirror} {Neurons} in {Speech} and {Language} {Processing}},
	volume = {112},
	issn = {0093-934X},
	url = {https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2813993/},
	doi = {10.1016/j.bandl.2009.10.006},
	number = {1},
	urldate = {2020-10-15},
	journal = {Brain and language},
	author = {Hickok, Gregory},
	month = jan,
	year = {2010},
	pmid = {19948355},
	pmcid = {PMC2813993},
	pages = {1},
	file = {PubMed Central Full Text PDF:/home/zubair/Zotero/storage/VGBBPSW9/Hickok - 2010 - The Role of Mirror Neurons in Speech and Language .pdf:application/pdf}
}

license: MIT

extension: bib


text:
import BaseLayoutColumns from '@/components/BaseLayoutColumns';
import BaseHeading from '@/components/BaseHeading';

export default {
	title: 'Base/Layout/Columns',
	component: BaseLayoutColumns,
};

export const Columns = (args) => ({
	components: {
		BaseLayoutColumns,
		BaseHeading,
	},
	props: Object.keys(args),
	template: `
		<BaseLayoutColumns :layout="layout" :align="align" :gap="gap" :element="element">

				<BaseHeading :heading-level="2" class="mb-4">Primary Content</BaseHeading>

						Lorem ipsum dolor sit amet, consectetur adipisicing elit. A aliquam architecto at autem
						delectus deserunt doloremque doloribus explicabo iure maiores molestias mollitia numquam
						odit officia, perspiciatis quas, saepe, sequi vel?

						Adipisci, aliquam amet atque corporis doloremque hic impedit ipsum iste laboriosam magnam
						magni provident quia quidem quisquam quo repellat suscipit vitae. Odit?

			<template v-slot:aside>

					<BaseHeading :heading-level="4" class="mb-4">Aside Content</BaseHeading>

						Lorem ipsum dolor sit amet, consectetur adipisicing elit.
						Aspernatur eius illum nobis. Aliquam dolor dolorum earum fugiat hic,
						molestias nesciunt officia perspiciatis quod soluta? Dignissimos esse excepturi
						maxime placeat voluptas?

			</template>
		</BaseLayoutColumns>
  `,
});

Columns.argTypes = {
	layout: {
		control: {
			type: 'select',
			options: ['halves', 'thirds', 'quarters'],
		},
	},
	align: {
		control: {
			type: 'select',
			options: ['left', 'right'],
		},
	},
	gap: {
		control: {
			type: 'select',
			options: ['none', 'small', 'medium', 'large'],
		},
	},
	element: {
		control: {
			type: 'select',
			options: ['div', 'section', 'article', 'header', 'footer'],
		},
	},
};

Columns.args = {
	layout: 'thirds',
	align: 'left',
	gap: 'medium',
	element: 'section',
};

branch_name: refs/heads/main

extension: js


text:
SRC_URI = "file://jffs2boot.sh"
PR = "r1"

do_install() {
        install -m 0755 ${WORKDIR}/jffs2boot.sh ${D}/init
}

FILES_${PN} += " /init "

repository: jdegges/gumstix-pip-oe

repo_name: jdegges/gumstix-pip-oe

extension: bb


text:
@article{slupianek_bcr-abl_2011,
 abstract = {BCR/ABL-transformed chronic myeloid leukemia (CML) cells accumulate numerous DNA double-strand breaks (DSB) induced by reactive oxygen species (ROS) and genotoxic agents. To repair these lesions BCR/ABL stimulate unfaithful DSB repair pathways, homologous recombination repair (HRR), nonhomologous end-joining (NHEJ), and single-strand annealing (SSA). Here, we show that BCR/ABL enhances the expression and increase nuclear localization of WRN (mutated in Werner syndrome), which is required for processing DSB ends during the repair. Other fusion tyrosine kinases (FTK), such as TEL/ABL, TEL/JAK2, TEL/PDGFβR, and NPM/ALK also elevate WRN. BCR/ABL induces WRN mRNA and protein expression in part by c-MYC-mediated activation of transcription and Bcl-xL-dependent inhibition of caspase-dependent cleavage, respectively. WRN is in complex with BCR/ABL resulting in WRN tyrosine phosphorylation and stimulation of its helicase and exonuclease activities. Activated WRN protects BCR/ABL-positive cells from the lethal effect of oxidative and genotoxic stresses, which causes DSBs. In addition, WRN promotes unfaithful recombination-dependent repair mechanisms HRR and SSA, and enhances the loss of DNA bases during NHEJ in leukemia cells. In summary, we postulate that BCR/ABL-mediated stimulation of WRN modulates the efficiency and fidelity of major DSB repair mechanisms to protect leukemia cells from apoptosis and to facilitate genomic instability.},
 author = {Slupianek, Artur and Poplawski, Tomasz and Jozwiakowski, Stanislaw K. and Cramer, Kimberly and Pytel, Dariusz and Stoczynska, Ewelina and Nowicki, Michal O. and Blasiak, Janusz and Skorski, Tomasz},
 doi = {10.1158/0008-5472.CAN-10-1066},
 issn = {1538-7445},
 journal = {Cancer Research},
 keywords = {Animals, Cell Line, Tumor, Chromosome Aberrations, Disease Progression, DNA Breaks, Double-Stranded, DNA, Neoplasm, DNA Repair, Exodeoxyribonucleases, Fusion Proteins, bcr-abl, Genomic Instability, Humans, Leukemia, Myelogenous, Chronic, BCR-ABL Positive, Mice, Oxidative Stress, Phosphorylation, Protein-Tyrosine Kinases, Recombinant Fusion Proteins, RecQ Helicases},
 language = {eng},
 month = {feb},
 number = {3},
 pages = {842--851},
 pmcid = {PMC3032814},
 pmid = {21123451},
 title = {{BCR}/{ABL} stimulates {WRN} to promote survival and genomic instability},
 volume = {71},
 year = {2011}
}

repository: naraoia/cv

repo_name: naraoia/cv


text:
@article{MR1058433,
 author = {López, Francisco J.},
 doi = {10.2307/2153972},
 fjournal = {Transactions of the American Mathematical Society},
 issn = {0002-9947},
 journal = {Trans. Amer. Math. Soc.},
 mrclass = {53A10},
 mrnumber = {1058433},
 mrreviewer = {Kichoon Yang},
 number = {1},
 pages = {49--74},
 title = {The classification of complete minimal surfaces with total
curvature greater than $-12π$},
 url = {https://doi.org/10.2307/2153972},
 volume = {334},
 year = {1992}
}

repository: torralbofco/geometric-analysis-fork

repo_name: torralbofco/geometric-analysis-fork


text:
#!/usr/bin/env node
import chalk from 'chalk';
import esMain from 'es-main';
import process from 'node:process';
import { Command } from 'commander';
import { withCompatibilityCheck } from '../src/compatibility.js';
import { nonEmptyStringParser } from '../src/parsers.js';
import {
    ExternalGroupAssignCommand,
    ExternalGroupDeleteCommand,
    ExternalGroupDescribeCommand,
    ExternalGroupListCommand,
    RoleAssignCommand,
    RoleCreateCommand,
    RoleDeleteCommand,
    RoleDescribeCommand,
    RoleGrantCommand,
    RoleListCommand,
    RoleProjectAssignCommand,
} from '../src/commands/roles.js';
import { LIST_JSON_HELP_TEXT, QUERY_JSON_HELP_TEXT } from '../src/constants.js';

export function create() {
    const program = new Command();

    program.name('cortex roles');
    program.description('Work with Cortex Roles');
    program.command('list')
        .description('List roles by project and user')
        .alias('l')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--json [searchQuery]', LIST_JSON_HELP_TEXT)
        .option('--query <query>', `[DEPRECATION WARNING] ${QUERY_JSON_HELP_TEXT}`)
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .option('--project <project>', 'Project to list roles for')
        .action(withCompatibilityCheck((options) => {
            try {
                return new RoleListCommand(program).execute(options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    program.command('describe <role>')
        .alias('get')
        .description('Describe role grants and users')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .option('--users', 'List users associated with role')
        .option('--no-grants', 'Ignore grants associated with role')
        .action(withCompatibilityCheck((role, options) => {
            try {
                return new RoleDescribeCommand(program).execute(role, options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    program.command('delete <role>')
        .description('Delete a role and remove grants/assignments')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .action(withCompatibilityCheck((role, options) => {
            try {
                return new RoleDeleteCommand(program).execute(role, options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    program.command('create <role>')
        .description('Create a role with the given grant')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .requiredOption('--project <project>', 'Grant project')
        .requiredOption('--resource <resource>', 'Grant resource')
        .requiredOption('--actions <actions...>', 'Grant actions read | write | execute | *')
        .option('--deny', 'Explicit deny of action(s)')
        .action(withCompatibilityCheck((role, options) => {
            try {
                return new RoleCreateCommand(program).execute(role, options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    program.command('grant <role>')
        .description('Manage grants on an existing role')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .requiredOption('--project <project>', 'Grant project')
        .requiredOption('--resource <resource>', 'Grant resource')
        .requiredOption('--actions <actions...>', 'Grant actions read | write | execute | *')
        .option('--delete', 'Remove grant from role')
        .option('--deny', 'Explicit deny of action(s)')
        .action(withCompatibilityCheck((role, options) => {
            try {
                return new RoleGrantCommand(program).execute(role, options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    program.command('assign <role>')
        .description('Manage a list of user assignments on a role')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .requiredOption('--users <users...>', 'Users to add/remove to/from a role', nonEmptyStringParser({
            message: 'user names must not be empty',
            variadic: true,
        }))
        .option('--delete', 'Unassign users from role')
        .action(withCompatibilityCheck((role, options) => {
            try {
                return new RoleAssignCommand(program).execute(role, options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    program.command('project <project>')
        .description('Manage a list of role assignments on a project')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .requiredOption('--roles <roles...>', 'Roles to add/remove on project')
        .option('--delete', 'Unassign roles from project')
        .action(withCompatibilityCheck((project, options) => {
            try {
                return new RoleProjectAssignCommand(program).execute(project, options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    program.command('list-external')
        .description('List external groups')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--json [searchQuery]', LIST_JSON_HELP_TEXT)
        .option('--query <query>', `[DEPRECATION WARNING] ${QUERY_JSON_HELP_TEXT}`)
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .action(withCompatibilityCheck((options) => {
            try {
                return new ExternalGroupListCommand(program).execute(options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    program.command('describe-external <externalGroup>')
        .alias('get-external')
        .description('Describe external group roles and users')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .option('--users', 'List users associated with external group')
        .option('--roles', 'List roles associated with external group')
        .action(withCompatibilityCheck((externalGroup, options) => {
            try {
                return new ExternalGroupDescribeCommand(program).execute(externalGroup, options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    program.command('delete-external <externalGroup>')
        .description('Delete an external group and remove assignments')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .action(withCompatibilityCheck((externalGroup, options) => {
            try {
                return new ExternalGroupDeleteCommand(program).execute(externalGroup, options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    program.command('assign-external')
        .description('Manage an external group assignment on a role')
        .option('--no-compat', 'Ignore API compatibility checks')
        .option('--color [boolean]', 'Turn on/off colors for JSON output.', 'true')
        .option('--profile <profile>', 'The profile to use')
        .requiredOption('--role <role>', 'Role to add/remove assignment')
        .requiredOption('--externalGroup <externalGroup>', 'External group to add/remove on role')
        .option('--delete', 'Unassign external group from role')
        .action(withCompatibilityCheck((options) => {
            try {
                return new ExternalGroupAssignCommand(program).execute(options);
            } catch (err) {
                return console.error(chalk.red(err.message));
            }
        }));
    return program;
}
if (esMain(import.meta)) {
    create().showHelpAfterError().parseAsync(process.argv);
}
export default create();

repository: CognitiveScale/cortex-cli

repo_name: CognitiveScale/cortex-cli

branch_name: refs/heads/develop

gha_language: JavaScript


text:
FILESEXTRAPATHS:append := ":${THISDIR}/${PN}"

inherit allarch systemd

LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI += " \
    file://99-nv-wifibt.rules \
    file://nvwifibt.service \
    file://nvwifibt-pre.sh \
    file://nvwifibt.sh \
    file://nvwifibt-unblock.service \
"

FILES:${PN} = " \
    /lib/udev/rules.d/99-nv-wifibt.rules \
    /lib/systemd/nvwifibt.sh \
    /lib/systemd/nvwifibt-pre.sh \
"

SYSTEMD_SERVICE:${PN} = "nvwifibt.service nvwifibt-unblock.service"

RDEPENDS:${PN} = " bash systemd"

do_install:append() {
    install -d ${D}/${systemd_unitdir}/system
    install -d ${D}/${base_libdir}/udev/rules.d
    install -m 644 ${WORKDIR}/99-nv-wifibt.rules ${D}/${base_libdir}/udev/rules.d
    install -m 644 ${WORKDIR}/nvwifibt.service ${D}/${systemd_unitdir}/system
    install -m 644 ${WORKDIR}/nvwifibt-unblock.service ${D}/${systemd_unitdir}/system
    install -m 755 ${WORKDIR}/nvwifibt.sh  ${D}/${systemd_unitdir}/
    install -m 755 ${WORKDIR}/nvwifibt-pre.sh  ${D}/${systemd_unitdir}/
}

COMPATIBLE_MACHINE="(jetson-tx1|jetson-tx2)"

repository: balena-os/balena-jetson

repo_name: balena-os/balena-jetson

gha_language: BitBake


text:
package grains

import (
	"testing"
)

func TestSquare(t *testing.T) {
	for _, test := range squareTests {
		actualVal, actualErr := Square(test.input)

		// check actualVal only if no error expected
		if !test.expectError && actualVal != test.expectedVal {
			t.Fatalf("FAIL: %s\nSquare(%d) expected %d, Actual %d", test.description, test.input, test.expectedVal, actualVal)
		}

		// if we expect an error and there isn't one
		if test.expectError && actualErr == nil {
			t.Fatalf("FAIL: %s\nSquare(%d) expected an error, but error is nil", test.description, test.input)
		}
		// if we don't expect an error and there is one
		if !test.expectError && actualErr != nil {
			var _ error = actualErr
			t.Fatalf("FAIL: %s\nSquare(%d) expected no error, but error is: %s", test.description, test.input, actualErr)
		}
		t.Logf("PASS: %s", test.description)
	}
}

func TestTotal(t *testing.T) {
	var expected uint64 = 18446744073709551615
	if actual := Total(); actual != expected {
		t.Errorf("Total() expected %d, Actual %d", expected, actual)
	}
}

func BenchmarkSquare(b *testing.B) {

	for i := 0; i < b.N; i++ {

		for _, test := range squareTests {
			Square(test.input)
		}

	}
}

func BenchmarkTotal(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Total()
	}
}

repository: rootulp/exercism

repo_name: rootulp/exercism

gha_license_id: MIT


text:
#
#   Copyright (C) 2017 Pelagicore AB
#   SPDX-License-Identifier: MIT
#

SUMMARY = "A template C/C++ library"
DESCRIPTION = "A C/C++ shared library blueprint"
AUTHOR = "Gordan Markuš <gordan.markus@pelagicore.com>"
HOMEPAGE = "https://github.com/Pelagicore/template-library"
LICENSE = "MPL-2.0"
LIC_FILES_CHKSUM = "file://LICENSE;md5=815ca599c9df247a0c7f619bab123dad"
PV = "1.0+git${SRCREV}"
PR = "r0"

SRCREV = "29d6dbd859d725ee6d10686ee5449069412de2c6"
SRC_URI = "git://github.com/Pelagicore/template-library.git;protocol=https;branch=master"

S = "${WORKDIR}/git/"

inherit cmake pkgconfig

PACKAGES = " \
    ${PN}     \
    ${PN}-dbg \
    ${PN}-dev \
"

FILES_${PN} += " \
    ${libdir}/libtemplate-library.so \
"

repository: Pelagicore/meta-template

repo_name: Pelagicore/meta-template

gha_language: Groovy


text:
##########################
UNSET(MUMPS_FOUND)
IF (NOT MUMPS_ROOT)
	SET(MUMPS_ROOT "C:/Program Files/Mumps" CACHE PATH "Mumps root directory" FORCE)
ENDIF()
SET(MUMPS_USE_MPI FALSE CACHE BOOL "Select if MPI is needed" FORCE)
SET(MUMPS_USE_DEFAULT_ORDERINGS TRUE CACHE BOOL "Select if default ordering library should be used" FORCE)

UNSET(MUMPS_ONLY_LIBRARY_COMMON CACHE)
UNSET(MUMPS_ONLY_LIBRARY_ARITHMETIC_SPECIFIC CACHE)
UNSET(MUMPS_ONLY_INCLUDE_DIRS CACHE)
UNSET(MUMPS_ONLY_LIBRARIES CACHE)
UNSET(MUMPS_MPI_INCLUDE_DIRS CACHE)
UNSET(MUMPS_MPI_LIBRARIES CACHE)
UNSET(MUMPS_ORDERINGS_INCLUDE_DIRS CACHE)
UNSET(MUMPS_ORDERINGS_LIBRARIES CACHE)
UNSET(MUMPS_INCLUDE_DIRS CACHE)
UNSET(MUMPS_LIBRARIES CACHE)
UNSET(MUMPS_SHARED_LIBRARIES CACHE)

################# Mumps library itself #####################
UNSET(MUMPS_ONLY_FOUND)
find_library(MUMPS_ONLY_LIBRARY_COMMON
			 "libmumps_common"
			 PATHS ${MUMPS_ROOT}
			 PATH_SUFFIXES "lib" "lib64" "libraries"
         )

find_library(MUMPS_ONLY_LIBRARY_ARITHMETIC_SPECIFIC
			 "lib${MUMPS_ARITH_PREFIX}mumps"
			 PATHS ${MUMPS_ROOT}
			 PATH_SUFFIXES "lib" "lib64" "libraries"
         )

find_file (MUMPS_SHARED_LIBRARIES
          "lib${MUMPS_ARITH_PREFIX}mumps${CMAKE_SHARED_LIBRARY_SUFFIX}"
          PATHS ${MUMPS_ROOT}
	      PATH_SUFFIXES "bin"
         )

find_path(MUMPS_ONLY_INCLUDE_DIRS
          NAMES "${MUMPS_ARITH_PREFIX}mumps_c.h"
          PATHS ${MUMPS_ROOT}
          PATH_SUFFIXES "include" "inc"
         )

IF (MUMPS_ONLY_LIBRARY_ARITHMETIC_SPECIFIC AND MUMPS_ONLY_INCLUDE_DIRS)
	SET(MUMPS_ONLY_LIBRARIES ${MUMPS_ONLY_LIBRARY_ARITHMETIC_SPECIFIC})
	IF ((MUMPS_IS_SHARED_LIB AND MUMPS_SHARED_LIBRARIES) OR MUMPS_ONLY_LIBRARY_COMMON)
		SET(MUMPS_ONLY_FOUND TRUE)
		IF (MUMPS_ONLY_LIBRARY_COMMON)
			SET(MUMPS_ONLY_LIBRARIES ${MUMPS_ONLY_LIBRARY_COMMON} ${MUMPS_ONLY_LIBRARY_ARITHMETIC_SPECIFIC})
		ENDIF()
	ENDIF()
endif()

################# MPI library #####################
UNSET(MUMPS_MPI_FOUND)
IF (MUMPS_USE_MPI)
	MESSAGE("MPI search is WIP.")
	find_path(MUMPS_MPI_INCLUDE_DIRS
				mpi.h
	)

	find_library(MUMPS_MPI_LIBRARIES
				libmpi
	)
	SET(MUMPS_MPI_FOUND TRUE)
ELSE (MUMPS_USE_MPI)

	# TODO: have they to be included?
	find_path(MUMPS_MPI_INCLUDE_DIRS
				mpi.h
				PATHS ${MUMPS_ROOT}
				PATH_SUFFIXES "include" "libseq" "libseqmpi" "libseq/include" "libseqmpi/include"
				NO_DEFAULT_PATH
			    NO_SYSTEM_ENVIRONMENT_PATH
	)

	find_library(MUMPS_MPI_LIBRARIES
				libmpiseq
				PATHS ${MUMPS_ROOT}
				PATH_SUFFIXES "libseq" "libseqmpi" "lib" "lib64"
				NO_DEFAULT_PATH
			    NO_SYSTEM_ENVIRONMENT_PATH
	)

ENDIF (MUMPS_USE_MPI)

IF (MUMPS_MPI_INCLUDE_DIRS AND (MUMPS_IS_SHARED_LIB OR MUMPS_MPI_LIBRARIES))
	SET(MUMPS_MPI_FOUND TRUE)
endif()

################# Ordering library #####################
UNSET(MUMPS_ORDERINGS_FOUND)
IF (MUMPS_USE_DEFAULT_ORDERINGS)
	# TODO: have they to be included?
	# find_path(MUMPS_ORDERINGS_INCLUDE_DIRS
				# protos.h
				# PATHS ${MUMPS_ROOT}
				# PATH_SUFFIXES "PORD/include" "PORD" "include"
	# )

	find_library(MUMPS_ORDERINGS_LIBRARIES
				libpord
				PATHS ${MUMPS_ROOT}
				PATH_SUFFIXES "PORD/lib" "PORD" "PORD/libraries" "lib" "lib64"
	)

ELSE (MUMPS_USE_DEFAULT_ORDERINGS)
	MESSAGE("Non-default orderings is not implemented yet.")
	# SET(MUMPS_ORDERINGS_LIBRARIES "" CACHE PATH "Path to ordering library" FORCE)
ENDIF (MUMPS_USE_DEFAULT_ORDERINGS)

IF (MUMPS_ORDERINGS_LIBRARIES)
	SET(MUMPS_ORDERINGS_FOUND TRUE)
ENDIF()

################# Clean up #####################
MARK_AS_ADVANCED(FORCE MUMPS_ONLY_LIBRARY_COMMON)
MARK_AS_ADVANCED(FORCE MUMPS_ONLY_LIBRARY_ARITHMETIC_SPECIFIC)
MARK_AS_ADVANCED(FORCE MUMPS_ONLY_INCLUDE_DIRS)
MARK_AS_ADVANCED(FORCE MUMPS_ONLY_LIBRARIES)
MARK_AS_ADVANCED(FORCE MUMPS_MPI_INCLUDE_DIRS)
MARK_AS_ADVANCED(FORCE MUMPS_MPI_LIBRARIES)
MARK_AS_ADVANCED(FORCE MUMPS_ORDERINGS_INCLUDE_DIRS)
MARK_AS_ADVANCED(FORCE MUMPS_ORDERINGS_LIBRARIES)
MARK_AS_ADVANCED(FORCE MUMPS_INCLUDE_DIRS)
MARK_AS_ADVANCED(FORCE MUMPS_LIBRARIES)
MARK_AS_ADVANCED(FORCE MUMPS_SHARED_LIBRARIES)

################# Exported variables #####################
IF (MUMPS_ONLY_FOUND)
	SET(MUMPS_INCLUDE_DIRS ${MUMPS_ONLY_INCLUDE_DIRS} ${MUMPS_MPI_INCLUDE_DIRS} ${MUMPS_ORDERINGS_INCLUDE_DIRS})
    list(REMOVE_DUPLICATES MUMPS_INCLUDE_DIRS)
	IF (MUMPS_IS_SHARED_LIB AND MUMPS_SHARED_LIBRARIES)
		SET(MUMPS_LIBRARIES ${MUMPS_ONLY_LIBRARIES})
		SET(MUMPS_FOUND TRUE)
		MESSAGE(STATUS "Mumps found as shared library.")
	ELSEIF (MUMPS_MPI_FOUND AND MUMPS_ORDERINGS_FOUND)
		SET(MUMPS_LIBRARIES ${MUMPS_ONLY_LIBRARIES} ${MUMPS_MPI_LIBRARIES} ${MUMPS_ORDERINGS_LIBRARIES})
		SET(MUMPS_FOUND TRUE)
		MESSAGE(STATUS "Mumps found as static library.")
	ELSE ()
		MESSAGE(STATUS "Mumps found, but other required libraries are missing.")
		SET(MUMPS_FOUND "MUMPS-NOTFOUND")
	ENDIF()
ELSE()
	MESSAGE(STATUS "Mumps not found.")
    SET(MUMPS_FOUND "MUMPS-NOTFOUND")
ENDIF()

if(MUMPS_FOUND)
	MARK_AS_ADVANCED(FORCE MUMPS_ROOT)
	MARK_AS_ADVANCED(FORCE MUMPS_USE_MPI)
	MARK_AS_ADVANCED(FORCE MUMPS_USE_DEFAULT_ORDERINGS)
endif()

repository: cecilysunday/chrono

repo_name: cecilysunday/chrono

extension: cmake


text:
#=============================================================================
# Copyright (c) 2020-2021, NVIDIA CORPORATION.
#
# 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.
#=============================================================================

function(find_and_configure_thrust VERSION)
    # We only want to set `UPDATE_DISCONNECTED` while
    # the GIT tag hasn't moved from the last time we cloned
    set(cpm_thrust_disconnect_update "UPDATE_DISCONNECTED TRUE")
    set(CPM_THRUST_CURRENT_VERSION ${VERSION} CACHE STRING "version of thrust we checked out")
    if(NOT VERSION VERSION_EQUAL CPM_THRUST_CURRENT_VERSION)
        set(CPM_THRUST_CURRENT_VERSION ${VERSION} CACHE STRING "version of thrust we checked out" FORCE)
        set(cpm_thrust_disconnect_update "")
    endif()

    # We currently require cuDF to always build with a custom
    # version of thrust. This is needed so that build times of
    # of cudf are kept reasonable, without this CI builds
    # of cudf will be killed as some source file can take
    # over 45 minutes to build
    #
    set(CPM_DOWNLOAD_ALL TRUE)
    rapids_cpm_find(
        Thrust ${VERSION}
        BUILD_EXPORT_SET cudf-exports
        INSTALL_EXPORT_SET cudf-exports
        CPM_ARGS
        GIT_REPOSITORY https://github.com/NVIDIA/thrust.git
        GIT_TAG ${VERSION}
        GIT_SHALLOW TRUE
        ${cpm_thrust_disconnect_update}
        PATCH_COMMAND   patch --reject-file=- -p1 -N < ${CUDF_SOURCE_DIR}/cmake/thrust.patch || true
        OPTIONS "THRUST_INSTALL TRUE")

    if(NOT TARGET cudf::Thrust)
        thrust_create_target(cudf::Thrust FROM_OPTIONS)
    endif()

    if(Thrust_SOURCE_DIR) # only install thrust when we have an in-source version
        include(GNUInstallDirs)
        install(DIRECTORY "${Thrust_SOURCE_DIR}/thrust"
            DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/libcudf/Thrust/"
            FILES_MATCHING
                PATTERN "*.h"
                PATTERN "*.inl")
        install(DIRECTORY "${Thrust_SOURCE_DIR}/dependencies/cub/cub"
            DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/libcudf/Thrust/dependencies/"
            FILES_MATCHING
                PATTERN "*.cuh")

        install(DIRECTORY "${Thrust_SOURCE_DIR}/thrust/cmake"
            DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/libcudf/Thrust/thrust/")
        install(DIRECTORY "${Thrust_SOURCE_DIR}/dependencies/cub/cub/cmake"
            DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/libcudf/Thrust/dependencies/cub/")

        # Store where CMake can find our custom Thrust install
        include("${rapids-cmake-dir}/export/find_package_root.cmake")
        rapids_export_find_package_root(INSTALL Thrust [=[${CMAKE_CURRENT_LIST_DIR}/../../../include/libcudf/Thrust/]=] cudf-exports)
    endif()
endfunction()

set(CUDF_MIN_VERSION_Thrust 1.12.0)

find_and_configure_thrust(${CUDF_MIN_VERSION_Thrust})

repository: db-extreme/cudf

repo_name: db-extreme/cudf


text:
@Article{ganesh:scir:2014,
  author    = {Ganesh, Gowrishankar and Takagi, Atsushi and Osu, Rieko and Yoshioka, Takahito and Kawato, Mitsuo and Burdet, Etienne},
  title     = {Two is better than one: Physical interactions improve motor performance in humans},
  journal   = {Scientific Reports},
  year      = {2014},
  volume    = {4},
  number    = {3824},
  month     = {January},
  doi       = {10.1038/srep03824},
  url       = {https://www.nature.com/articles/srep03824.pdf},
  abstract  = {How do physical interactions with others change our own motor behavior? Utilizing a novel motor learning paradigm in which the hands of two - individuals are physically connected without their conscious awareness, we investigated how the interaction forces from a partner adapt the motor behavior in physically interacting humans. We observed the motor adaptations during physical interactions to be mutually beneficial such that both the worse and better of the interacting partners improve motor performance during and after interactive practice. We show that these benefits cannot be explained by multi-sensory integration by an individual, but require physical interaction with a reactive partner. Furthermore, the benefits are determined by both the interacting partner\textquotesingle s performance and similarity of the partner\textquotesingle s behavior to one\textquotesingle s own. Our results demonstrate the fundamental neural processes underlying human physical interactions and suggest advantages of interactive paradigms for sport-training and physical rehabilitation.},
  publisher = {Nature Publishing Group},
  address   = {MACMILLAN BUILDING, 4 CRINAN ST, LONDON N1 9XW, ENGLAND}
}

gha_language: TeX


text:
% Encoding: UTF-8

@Conference{WillbergC2018,
  author    = {C. Willberg and M. R\"adel},
  title     = {An energy based peridynamic state-based failure criterion},
  booktitle = {89th Annual Meeting of the International Association of Applied Mathematics and Mechanics (GAMM 2018), March 19-23, 2018 Munich Germany},
  year      = {2018},
  keywords  = {own},
}

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

repository: PeriDoX/PeriDoX

repo_name: PeriDoX/PeriDoX


text:
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by 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 controllers

import (
	"encoding/json"

	"github.com/casdoor/casdoor/object"
)

// @Title GetGlobalUsers
// @Description get global users
// @Success 200 {array} object.User The Response object
// @router /get-global-users [get]
func (c *ApiController) GetGlobalUsers() {
	c.Data["json"] = object.GetGlobalUsers()
	c.ServeJSON()
}

// @Title GetUsers
// @Description
// @Param   owner     query    string  true        "The owner of users"
// @Success 200 {array} object.User The Response object
// @router /get-users [get]
func (c *ApiController) GetUsers() {
	owner := c.Input().Get("owner")

	c.Data["json"] = object.GetUsers(owner)
	c.ServeJSON()
}

// @Title GetUser
// @Description get user
// @Param   id     query    string  true        "The id of the user"
// @Success 200 {object} object.User The Response object
// @router /get-user [get]
func (c *ApiController) GetUser() {
	id := c.Input().Get("id")

	c.Data["json"] = object.GetUser(id)
	c.ServeJSON()
}

// @Title UpdateUser
// @Description update user
// @Param   id     query    string  true        "The id of the user"
// @Param   body    body   object.User  true        "The details of the user"
// @Success 200 {object} controllers.Response The Response object
// @router /update-user [post]
func (c *ApiController) UpdateUser() {
	id := c.Input().Get("id")

	var user object.User
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
	if err != nil {
		panic(err)
	}

	c.Data["json"] = wrapActionResponse(object.UpdateUser(id, &user))
	c.ServeJSON()
}

// @Title AddUser
// @Description add user
// @Param   body    body   object.User  true        "The details of the user"
// @Success 200 {object} controllers.Response The Response object
// @router /add-user [post]
func (c *ApiController) AddUser() {
	var user object.User
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
	if err != nil {
		panic(err)
	}

	c.Data["json"] = wrapActionResponse(object.AddUser(&user))
	c.ServeJSON()
}

// @Title DeleteUser
// @Description delete user
// @Param   body    body   object.User  true        "The details of the user"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-user [post]
func (c *ApiController) DeleteUser() {
	var user object.User
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
	if err != nil {
		panic(err)
	}

	c.Data["json"] = wrapActionResponse(object.DeleteUser(&user))
	c.ServeJSON()
}


text:
package journal

import (
	"context"
	"io"
	"os"
	"sync"
	"time"

	utils "github.com/Laisky/go-utils"
	"github.com/Laisky/zap"
	"github.com/coreos/etcd/pkg/fileutil"
	"github.com/pkg/errors"
)

var Logger *utils.LoggerType

func init() {
	var err error
	if Logger, err = utils.NewConsoleLoggerWithName("go-journal", "info"); err != nil {
		utils.Logger.Panic("new journal logger", zap.Error(err))
	}
}

// Journal redo log consist by msgs and committed ids
type Journal struct {
	// RWMutex journal rwlock.
	// acquire write lock when flush/rotate journal legacy.
	// acquire read lock when read/write journal legacy.
	sync.RWMutex
	*option

	stopChan               chan struct{}
	rotateLock, legacyLock *utils.Mutex
	dataFp, idsFp          *os.File // current writting journal file
	fsStat                 *bufFileStat
	legacy                 *LegacyLoader
	dataEnc                *DataEncoder
	idsEnc                 *IdsEncoder
	lastRotateAt           time.Time
}

// NewJournal create new Journal
func NewJournal(opts ...OptionFunc) (j *Journal, err error) {
	j = &Journal{
		stopChan:   make(chan struct{}),
		rotateLock: utils.NewMutex(),
		legacyLock: utils.NewMutex(),
		option:     newOption(),
	}

	for _, optf := range opts {
		if err = optf(j.option); err != nil {
			return nil, err
		}
	}

	j.logger.Info("new journal",
		zap.String("bufDirPath", j.bufDirPath),
		zap.Int64("bufSizeBytes", j.bufSizeBytes),
		zap.Bool("isAggresiveGC", j.isAggresiveGC),
		zap.Bool("isCompress", j.isCompress),
		zap.Duration("flushInterval", j.flushInterval),
		zap.Duration("rotateDuration", j.rotateDuration),
		zap.Duration("rotateCheckInterval", j.rotateCheckInterval),
		zap.Duration("committedIDTTL", j.committedIDTTL),
	)
	return j, nil
}

func (j *Journal) Start(ctx context.Context) (err error) {
	if err = j.initBufDir(ctx); err != nil {
		return errors.Wrap(err, "init buf directory")
	}

	go j.startFlushTrigger(ctx)
	go j.startRotateTrigger(ctx)
	return
}

func (j *Journal) Close() {
	j.logger.Info("close Journal")

	j.Lock()
	j.Flush()
	j.stopChan <- struct{}{}
	j.Unlock()
}

// initBufDir initialize buf directory and create buf files
func (j *Journal) initBufDir(ctx context.Context) (err error) {
	if err = fileutil.IsDirWriteable(j.bufDirPath); err != nil {
		return errors.Wrapf(err, "cannot write to `%s`", j.bufDirPath)
	}

	if err = j.Rotate(ctx); err != nil { // manually first run
		return errors.Wrapf(err, "init rotate in `%s`", j.bufDirPath)
	}

	return
}

// Flush flush journal files buffer to file
func (j *Journal) Flush() (err error) {
	if j.idsEnc != nil {
		// j.logger.Debug("flush ids")
		if err = j.idsEnc.Flush(); err != nil {
			err = errors.Wrap(err, "flush ids encoder")
		}
	}

	if j.dataEnc != nil {
		// j.logger.Debug("flush data")
		if dataErr := j.dataEnc.Flush(); dataErr != nil {
			err = errors.Wrap(err, "flush data encoder")
		}
	}

	return err
}

// flushAndClose flush journal files then close
func (j *Journal) flushAndClose() (err error) {
	j.logger.Debug("flushAndClose")
	if j.idsEnc != nil {
		if err = j.idsEnc.Close(); err != nil {
			err = errors.Wrap(err, "flush ids encoder")
		}
	}

	if j.dataEnc != nil {
		if dataErr := j.dataEnc.Close(); dataErr != nil {
			err = errors.Wrap(err, "flush data encoder")
		}
	}

	return err
}

func (j *Journal) startFlushTrigger(ctx context.Context) {
	j.logger.Info("start flush trigger", zap.Duration("interval", j.flushInterval))
	defer j.logger.Info("journal flush exit")

	defer j.Flush()
	var err error
	ticker := time.NewTicker(j.flushInterval)
	defer ticker.Stop()
	for {
		select {
		case <-j.stopChan:
			return
		case <-ctx.Done():
			return
		case <-ticker.C:
			j.Lock()
			if err = j.Flush(); err != nil {
				j.logger.Error("flush journal", zap.Error(err))
			}
			j.Unlock()
		}
	}
}

func (j *Journal) startRotateTrigger(ctx context.Context) {
	j.logger.Info("start rotate trigger", zap.Duration("interval", j.rotateCheckInterval))
	defer j.logger.Info("journal rotate exit")

	ticker := time.NewTicker(j.rotateCheckInterval)
	defer ticker.Stop()
	var err error
	for {
		select {
		case <-j.stopChan:
			return
		case <-ctx.Done():
			return
		case <-ticker.C:
			if j.isReadyToRotate() {
				if err = j.Rotate(ctx); err != nil {
					j.logger.Error("trigger rotate", zap.Error(err))
				}
			}
		}
	}
}

// LoadMaxId load max id from journal ids files
func (j *Journal) LoadMaxId() (int64, error) {
	return j.legacy.LoadMaxId()
}

// WriteData write data to journal
func (j *Journal) WriteData(data *Data) (err error) {
	j.RLock() // will blocked by flush & rotate
	defer j.RUnlock()

	if j.legacy.CheckAndRemove(data.ID) {
		return
	}

	// j.logger.Debug("write data", zap.Int64("id", GetId(*data)))
	return j.dataEnc.Write(data)
}

// WriteId write id to journal
func (j *Journal) WriteId(id int64) error {
	j.RLock() // will blocked by flush & rotate
	defer j.RUnlock()

	j.legacy.AddID(id)
	return j.idsEnc.Write(id)
}

// isReadyToRotate check whether is ready to start rotate.
// file size bigger `bufSizeBytes` or existing time logger than `rotateDuration`
func (j *Journal) isReadyToRotate() (ok bool) {
	j.RLock()
	defer j.RUnlock()

	if j.dataFp == nil {
		return true
	}

	if fi, err := j.dataFp.Stat(); err != nil {
		j.logger.Error("try to get file stat got error", zap.Error(err))
		ok = false
	} else if fi.Size() > j.bufSizeBytes ||
		utils.Clock.GetUTCNow().Sub(j.lastRotateAt) > j.rotateDuration {
		ok = true
	}

	j.logger.Debug("check isReadyToRotate",
		zap.Bool("ready", ok),
		zap.String("old_file", j.dataFp.Name()),
	)
	return
}

// Rotate create new data and ids buf file.
// this function is not threadsafe.
func (j *Journal) Rotate(ctx context.Context) (err error) {
	j.logger.Debug("call Rotate")
	// make sure no other rorate is running
	if !j.rotateLock.TryLock() {
		return nil
	}

	defer j.rotateLock.ForceRelease()
	// stop legacy processing
	j.Lock()
	defer j.Unlock()
	j.logger.Debug("starting to rotate")

	select {
	case <-j.stopChan:
		return
	case <-ctx.Done():
		return
	default:
	}

	if err = j.flushAndClose(); err != nil {
		return errors.Wrap(err, "flush and close journal")
	}

	j.lastRotateAt = utils.Clock.GetUTCNow()
	// scan and create files
	// acquired legacy lock means that there is no one reading legacy
	if j.LockLegacy() {
		j.logger.Debug("acquired legacy lock, create new file and refresh legacy loader",
			zap.String("dir", j.bufDirPath))
		// need to refresh legacy, so need scan=true
		if j.fsStat, err = PrepareNewBufFile(j.bufDirPath, j.fsStat, true, j.isCompress, j.bufSizeBytes); err != nil {
			j.UnLockLegacy()
			return errors.Wrap(err, "prepare new buf file")
		}

		j.refreshLegacyLoader(ctx)
		j.UnLockLegacy()
	} else {
		j.logger.Debug("not acquired legacy lock, so only create new file",
			zap.String("dir", j.bufDirPath))
		// no need to scan old buf files
		if j.fsStat, err = PrepareNewBufFile(j.bufDirPath, j.fsStat, false, j.isCompress, j.bufSizeBytes); err != nil {
			return errors.Wrap(err, "prepare new buf file")
		}
	}

	// create & open data file
	if j.dataFp != nil {
		j.dataFp.Close()
	}
	j.dataFp = j.fsStat.NewDataFp
	if j.dataEnc, err = NewDataEncoder(j.dataFp, j.isCompress); err != nil {
		return errors.Wrapf(err, "create new data encoder `%s`", j.dataFp.Name())
	}

	// create & open ids file
	if j.idsFp != nil {
		j.idsFp.Close()
	}
	j.idsFp = j.fsStat.NewIDsFp
	if j.idsEnc, err = NewIdsEncoder(j.idsFp, j.isCompress); err != nil {
		return errors.Wrapf(err, "create new ids encoder `%s`", j.idsFp.Name())
	}

	return nil
}

// refreshLegacyLoader create or reset legacy loader
func (j *Journal) refreshLegacyLoader(ctx context.Context) {
	j.logger.Debug("call refreshLegacyLoader")
	if j.legacy == nil {
		j.logger.Debug("create new LegacyLoader",
			zap.Strings("data_files", j.fsStat.OldDataFnames),
			zap.Strings("ids_files", j.fsStat.OldIDsDataFnames),
		)
		j.legacy = NewLegacyLoader(
			ctx,
			j.logger,
			j.fsStat.OldDataFnames,
			j.fsStat.OldIDsDataFnames,
			j.isCompress,
			j.committedIDTTL,
		)
	} else {
		j.legacy.Reset(j.fsStat.OldDataFnames, j.fsStat.OldIDsDataFnames)
		if j.isAggresiveGC {
			utils.TriggerGC()
		}
	}
}

// LockLegacy lock legacy to prevent rotate, clean
func (j *Journal) LockLegacy() bool {
	j.logger.Debug("call LockLegacy")
	return j.legacyLock.TryLock()
}

// IsLegacyRunning check whether running legacy loading
func (j *Journal) IsLegacyRunning() bool {
	j.logger.Debug("call IsLegacyRunning")
	return j.legacyLock.IsLocked()
}

// UnLockLegacy release legacy lock
func (j *Journal) UnLockLegacy() bool {
	j.logger.Debug("call UnLockLegacy")
	return j.legacyLock.TryRelease()
}

// GetMetric monitor inteface
func (j *Journal) GetMetric() map[string]interface{} {
	return map[string]interface{}{
		"idsSetLen": j.legacy.GetIdsLen(),
	}
}

// LoadLegacyBuf load legacy data one by one
// ⚠Warn: should call `j.LockLegacy()` before invoke this method
func (j *Journal) LoadLegacyBuf(data *Data) (err error) {
	if !j.IsLegacyRunning() {
		j.logger.Panic("should call `j.LockLegacy()` first")
	}

	j.RLock()
	defer j.RUnlock()

	if j.legacy == nil {
		j.UnLockLegacy()
		return io.EOF
	}

	if err = j.legacy.Load(data); err == io.EOF {
		j.logger.Debug("load all legacy data")
		if err = j.legacy.Clean(); err != nil {
			j.logger.Error("clean legacy", zap.Error(err))
		}

		j.UnLockLegacy()
		return io.EOF
	} else if err != nil {
		j.UnLockLegacy()
		return errors.Wrap(err, "load legacy data")
	}

	return nil
}

repository: Laisky/go-journal

repo_name: Laisky/go-journal


text:
@inproceedings{aptoula:hal-00998256,
 address = {Paris, France},
 author = {Aptoula, Erchan and Courty, Nicolas and Lefèvre, Sébastien},
 booktitle = {IEEE International Conference on Image Processing (ICIP)},
 hal_id = {hal-00998256},
 hal_version = {v1},
 keywords = {Index Terms-Mathematical morphology ; vector order- ing ; hyperspectral images ; end-members ; classification},
 month = {October},
 pages = {to appear},
 pdf = {https://hal.archives-ouvertes.fr/hal-00998256/file/icip2014.pdf},
 title = {An end-member based ordering relation for the morphological description of hyperspectral images},
 url = {https://hal.archives-ouvertes.fr/hal-00998256},
 year = {2014}
}

repository: ncourty/academic-kickstart

repo_name: ncourty/academic-kickstart


text:
/*
Copyright © 2020 ConsenSys

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 twistededwards

import (
	"math/bits"

	"github.com/consensys/gurvy/bn256/fr"
)

// Point point on a twisted Edwards curve
type Point struct {
	X, Y fr.Element
}

// PointProj point in projective coordinates
type PointProj struct {
	X, Y, Z fr.Element
}

// Set sets p to p1 and return it
func (p *PointProj) Set(p1 *PointProj) *PointProj {
	p.X.Set(&p1.X)
	p.Y.Set(&p1.Y)
	p.Z.Set(&p1.Z)
	return p
}

// NewPoint creates a new instance of Point
func NewPoint(x, y fr.Element) Point {
	return Point{x, y}
}

// IsOnCurve checks if a point is on the twisted Edwards curve
func (p *Point) IsOnCurve() bool {

	ecurve := GetEdwardsCurve()

	var lhs, rhs, tmp fr.Element

	tmp.Mul(&p.Y, &p.Y)
	lhs.Mul(&p.X, &p.X).
		Mul(&lhs, &ecurve.A).
		Add(&lhs, &tmp)

	tmp.Mul(&p.X, &p.X).
		Mul(&tmp, &p.Y).
		Mul(&tmp, &p.Y).
		Mul(&tmp, &ecurve.D)
	rhs.SetOne().Add(&rhs, &tmp)

	// TODO why do we not compare lhs and rhs directly?
	lhsreg := lhs.ToRegular()
	rhsreg := rhs.ToRegular()

	return rhsreg.Equal(&lhsreg)
}

// Add adds two points (x,y), (u,v) on a twisted Edwards curve with parameters a, d
// modifies p
func (p *Point) Add(p1, p2 *Point) *Point {

	ecurve := GetEdwardsCurve()

	var xu, yv, xv, yu, dxyuv, one, denx, deny fr.Element
	pRes := new(Point)
	xv.Mul(&p1.X, &p2.Y)
	yu.Mul(&p1.Y, &p2.X)
	pRes.X.Add(&xv, &yu)

	xu.Mul(&p1.X, &p2.X).Mul(&xu, &ecurve.A)
	yv.Mul(&p1.Y, &p2.Y)
	pRes.Y.Sub(&yv, &xu)

	dxyuv.Mul(&xv, &yu).Mul(&dxyuv, &ecurve.D)
	one.SetOne()
	denx.Add(&one, &dxyuv)
	deny.Sub(&one, &dxyuv)

	p.X.Div(&pRes.X, &denx)
	p.Y.Div(&pRes.Y, &deny)

	return p
}

// Double doubles point (x,y) on a twisted Edwards curve with parameters a, d
// modifies p
func (p *Point) Double(p1 *Point) *Point {
	p.Add(p1, p1)
	return p
}

// FromProj sets p in affine from p in projective
func (p *Point) FromProj(p1 *PointProj) *Point {
	p.X.Div(&p1.X, &p1.Z)
	p.Y.Div(&p1.Y, &p1.Z)
	return p
}

// FromAffine sets p in projective from p in affine
func (p *PointProj) FromAffine(p1 *Point) *PointProj {
	p.X.Set(&p1.X)
	p.Y.Set(&p1.Y)
	p.Z.SetOne()
	return p
}

// Add adds points in projective coordinates
// cf https://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
func (p *PointProj) Add(p1, p2 *PointProj) *PointProj {

	var res PointProj

	ecurve := GetEdwardsCurve()

	var A, B, C, D, E, F, G, H, I fr.Element
	A.Mul(&p1.Z, &p2.Z)
	B.Square(&A)
	C.Mul(&p1.X, &p2.X)
	D.Mul(&p1.Y, &p2.Y)
	E.Mul(&ecurve.D, &C).Mul(&E, &D)
	F.Sub(&B, &E)
	G.Add(&B, &E)
	H.Add(&p1.X, &p1.Y)
	I.Add(&p2.X, &p2.Y)
	res.X.Mul(&H, &I).
		Sub(&res.X, &C).
		Sub(&res.X, &D).
		Mul(&res.X, &p1.Z).
		Mul(&res.X, &F)
	H.Mul(&ecurve.A, &C)
	res.Y.Sub(&D, &H).
		Mul(&res.Y, &p.Z).
		Mul(&res.Y, &G)
	res.Z.Mul(&F, &G)

	p.Set(&res)
	return p
}

// Double adds points in projective coordinates
// cf https://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
func (p *PointProj) Double(p1 *PointProj) *PointProj {

	var res PointProj

	ecurve := GetEdwardsCurve()

	var B, C, D, E, F, H, J, tmp fr.Element

	B.Add(&p1.X, &p1.Y).Square(&B)
	C.Square(&p1.X)
	D.Square(&p1.Y)
	E.Mul(&ecurve.A, &C)
	F.Add(&E, &D)
	H.Square(&p1.Z)
	tmp.Double(&H)
	J.Sub(&F, &tmp)
	res.X.Sub(&B, &C).
		Sub(&res.X, &D).
		Mul(&res.X, &J)
	res.Y.Sub(&E, &D).Mul(&res.Y, &F)
	res.Z.Mul(&F, &J)

	p.Set(&res)
	return p
}

// ScalarMul scalar multiplication of a point
// p1 points on the twisted Edwards curve
// c parameters of the twisted Edwards curve
// scal scalar NOT in Montgomery form
// modifies p
func (p *Point) ScalarMul(p1 *Point, scalar fr.Element) *Point {

	var resProj, p1Proj PointProj
	resProj.X.SetZero()
	resProj.Y.SetOne()
	resProj.Z.SetOne()

	p1Proj.FromAffine(p1)

	const wordSize = bits.UintSize

	for i := 4 - 1; i >= 0; i-- {
		for j := 0; j < wordSize; j++ {
			resProj.Double(&resProj)
			b := (scalar[i] & (uint64(1) << uint64(wordSize-1-j))) >> uint64(wordSize-1-j)
			if b == 1 {
				resProj.Add(&resProj, &p1Proj)
			}
		}
	}

	p.FromProj(&resProj)

	return p
}


text:
@inproceedings{ishino2008extraction,
  title={Extraction of road markings from aerial images},
  author={Ishino, Yuichi and Saji, Hitoshi},
  booktitle={SICE Annual Conference, 2008},
  pages={2180--2183},
  year={2008},
  organization={IEEE}
}

@inproceedings{senlet2012segmentation,
  title={Segmentation of occluded sidewalks in satellite images},
  author={Senlet, Turgay and Elgammal, Ahmed},
  booktitle={Pattern Recognition (ICPR), 2012 21st International Conference on},
  pages={805--808},
  year={2012},
  organization={IEEE}
}

@misc{MapRoulette,
  title = {{MapRoulette}},
  author = {Martijn van Exel},
  howpublished = {\url{http://maproulette.org/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{NEBIS,
  title = {{NEBIS}},
  author = {Dr. Rafael Ball, Direktor der ETH-Bibliothek},
  howpublished = {\url{http://recherche.nebis.ch/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{IEEXplore,
  title = {{IEEXplore}},
  author = {IEEE},
  howpublished = {\url{http://ieeexplore.ieee.org/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{GoogleScholar,
  title = {{Google Scholar}},
  author = {Google},
  howpublished = {\url{http://scholar.google.ch/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{OpencvHaar,
  title = {{TRAIN YOUR OWN OPENCV HAAR CLASSIFIER}},
  author = {Thorsten Ball},
  howpublished = {\url{http://coding-robin.de/2013/07/22/train-your-own-opencv-haar-classifier.html}},
  year = {Aufgerufen Dezember 2015},
}

@misc{To-Fix,
  title = {{To-Fix}},
  author = {OSM Lab},
  howpublished = {\url{http://osmlab.github.io/to-fix/#/task/tigerdelta}},
  year = {Aufgerufen Dezember 2015},
}

@misc{Mapquest,
  title = {{Mapquest}},
  author = {MapQuest Inc.},
  howpublished = {\url{http://www.mapquest.com/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{Keras,
  title = {{Keras}},
  author = {François Chollet},
  howpublished = {\url{https://github.com/fchollet/keras}},
  year = {Aufgerufen Dezember 2015},
}

@misc{BingMapsRest,
  title = {{Bing Maps REST Services}},
  author = {Microsoft},
  howpublished = {\url{https://msdn.microsoft.com/en-us/library/ff701713.aspx}},
  year = {Aufgerufen Dezember 2015},
}

@misc{Tiles,
  title = {{Tiles à la Google Maps: Coordinates, Tile Bounds and Projection}},
  author = {Klokan Petr Přidal},
  howpublished = {\url{http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{Redis,
  title = {{Redis}},
  author = {Salvatore Sanfilippo},
  howpublished = {\url{http://redis.io/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{RQ,
  title = {{RQ}},
  author = {Vincent Driessen},
  howpublished = {\url{http://python-rq.org/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{mapquestapi,
  title = {{Xapi Service Developer's Guide}},
  author = {MapQuest Inc.},
  howpublished = {\url{http://open.mapquestapi.com/xapi/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{quadtree,
  title = {{Bing Maps Tile System}},
  author = {Microsoft},
  howpublished = {\url{https://msdn.microsoft.com/en-us/library/bb259689.aspx}},
  year = {Aufgerufen Dezember 2015},
}

@misc{Convolutional,
  title = {{Convolutional Neural Networks}},
  author = {Andrej Karpathy},
  howpublished = {\url{http://cs231n.github.io/convolutional-networks/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{Deep,
  title = {{Very Deep Convolutional Networks for Large-Scale Image Recognition}},
  author = {Karen Simonyan, Andrew Zisserman},
  howpublished = {\url{http://arxiv.org/abs/1409.1556}},
  year = {Aufgerufen Dezember 2015},
}

@misc{CircleCI,
  title = {{CircleCI}},
  author = {CircleCI},
  howpublished = {\url{https://circleci.com/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{CLOC,
  title = {{Count Lines of Code}},
  author = {AlDanial},
  howpublished = {\url{https://github.com/AlDanial/cloc}},
  year = {Aufgerufen Dezember 2015},
}

@misc{RUP,
  title = {{Rational Unified Process}},
  author = {Fantasma300580},
  howpublished = {\url{https://de.wikipedia.org/wiki/Rational_Unified_Process}},
  year = {Aufgerufen Dezember 2015},
}

@misc{Tutorial,
  title = {{MapRoulette Challenge Tutorial}},
  author = {Martijn van Exel},
  howpublished = {\url{https://gist.github.com/mvexel/b5ad1cb0c91ac245ea3f}},
  year = {Aufgerufen Dezember 2015},
}

@misc{DokerKeras,
  title = {{keras\_cuda image for the nvidia-docker project}},
  author = {Severin Bühler},
  howpublished = {\url{https://hub.docker.com/r/sebu/keras_cuda/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{DokerCrosswalk,
  title = {{Dockercontainer to run the workers of the OSM-Crosswalk-Detection project}},
  author = {Samuel Kurath},
  howpublished = {\url{https://hub.docker.com/r/murthy10/osm-crosswalk-detection/}},
  year = {Aufgerufen Dezember 2015},
}

@misc{CartoDB,
  title = {{CartoDB is the Easiest Way to Map and Analyze Your Location Data}},
  author = {CartoDB},
  howpublished = {\url{https://cartodb.com/}},
  year = {Aufgerufen Dezember 2015},
}

repository: frodrigo/OSMDeepOD

repo_name: frodrigo/OSMDeepOD


text:
inherit kernel
require recipes-kernel/linux/linux.inc

LINUX_VERSION = "${PV}"

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

SRC_URI = "${KERNELORG_MIRROR}/linux/kernel/v3.0/linux-${PV}.tar.xz;name=kernel \
           git://git.code.sf.net/p/aufs/aufs3-standalone;protocol=http;branch=aufs3.10.x;name=aufs \
           file://i82365-work-fix-v2.patch \
	   file://platform_driver_probe.patch \
	   file://pd6729.patch \
           file://defconfig \
"

SRCREV_aufs = "24279ba05aacd107d09e171fffc6881bfd007d8b"

COMPATIBLE_MACHINE = "cocon486"

do_configure_prepend() {
        install ${WORKDIR}/defconfig ${WORKDIR}/linux-${PV}/.config
        cd ${WORKDIR}/linux-${PV}
        oe_runmake oldconfig
}

# apply patches without quilt
do_patch() {
        # Extract aufs tree to Linux tree

	cd ${WORKDIR}/linux-${PV}
        patch -p1 <${WORKDIR}/git/aufs3-kbuild.patch
	patch -p1 <${WORKDIR}/git/aufs3-base.patch
        patch -p1 <${WORKDIR}/git/aufs3-mmap.patch
	patch -p1 <${WORKDIR}/git/aufs3-standalone.patch

	cp -R ${WORKDIR}/git/fs/* ./fs/
        cp -R ${WORKDIR}/git/include/uapi/linux/aufs_type.h ./include/uapi/linux/

        patch -p1 <${WORKDIR}/i82365-work-fix-v2.patch
	patch -p1 <${WORKDIR}/pd6729.patch
	patch -p1 <${WORKDIR}/platform_driver_probe.patch
}

SRC_URI[kernel.md5sum] = "ef927e91cf8b8c4ddf98847341ccf2c8"
SRC_URI[kernel.sha256sum] = "95f9be5a26f6c15d21528ecdb2cd3307fc99c715cfb3bce13843de8393f67028"

repository: gitter-badger/meta-cocon

repo_name: gitter-badger/meta-cocon


text:
package certificates

import (
	"errors"
	"testing"

	"github.com/kyma-project/kyma/components/connectivity-certs-controller/internal/secrets/mocks"

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

var (
	crtChain  = []byte("certificateChain")
	clientCRT = []byte("clientCertificate")
	caCRT     = []byte("caCertificate")
	clientKey = []byte("clientKey")
)

func TestCertificatePreserver_PreserveCertificates(t *testing.T) {

	certificates := Certificates{
		CRTChain:  crtChain,
		ClientCRT: clientCRT,
		CaCRT:     caCRT,
		ClientKey: clientKey,
	}

	t.Run("should preserve certificates", func(t *testing.T) {
		// given
		clusterSecretData := map[string][]byte{
			clusterCertificateSecretKey: clientCRT,
			clusterKeySecretKey:         clientKey,
			certificateChainSecretKey:   crtChain,
		}
		caSecretData := map[string][]byte{caCertificateSecretKey: caCRT}

		secretsRepository := &mocks.Repository{}
		secretsRepository.On("UpsertWithMerge", clusterCertSecretNamespaceName, clusterSecretData).Return(nil)
		secretsRepository.On("UpsertWithMerge", caCertSecretNamespaceName, caSecretData).Return(nil)

		certificatePreserver := NewCertificatePreserver(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository)

		// when
		err := certificatePreserver.PreserveCertificates(certificates)

		// then
		require.NoError(t, err)
		secretsRepository.AssertExpectations(t)
	})

	t.Run("should return error when failed to save cluster secret", func(t *testing.T) {
		// given
		clusterSecretData := map[string][]byte{
			clusterCertificateSecretKey: clientCRT,
			clusterKeySecretKey:         clientKey,
			certificateChainSecretKey:   crtChain,
		}

		secretsRepository := &mocks.Repository{}
		secretsRepository.On("UpsertWithMerge", clusterCertSecretNamespaceName, clusterSecretData).Return(errors.New("error"))

		certificatePreserver := NewCertificatePreserver(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository)

		// when
		err := certificatePreserver.PreserveCertificates(certificates)

		// then
		require.Error(t, err)
		secretsRepository.AssertExpectations(t)
	})

	t.Run("should return error when failed to save ca secret", func(t *testing.T) {
		// given
		clusterSecretData := map[string][]byte{
			clusterCertificateSecretKey: clientCRT,
			clusterKeySecretKey:         clientKey,
			certificateChainSecretKey:   crtChain,
		}
		caSecretData := map[string][]byte{caCertificateSecretKey: caCRT}

		secretsRepository := &mocks.Repository{}
		secretsRepository.On("UpsertWithMerge", clusterCertSecretNamespaceName, clusterSecretData).Return(nil)
		secretsRepository.On("UpsertWithMerge", caCertSecretNamespaceName, caSecretData).Return(errors.New("error"))

		certificatePreserver := NewCertificatePreserver(clusterCertSecretNamespaceName, caCertSecretNamespaceName, secretsRepository)

		// when
		err := certificatePreserver.PreserveCertificates(certificates)

		// then
		require.Error(t, err)
		secretsRepository.AssertExpectations(t)
	})

}

repository: razine-bensari/kyma

repo_name: razine-bensari/kyma


text:
# Copyright (C) 2015 Shanghai Zhixing Information Technology Co.Ltd

require recipes-bsp/u-boot/u-boot-curie.inc

LICENSE = "GPLv2+"
LIC_FILES_CHKSUM = "file://Licenses/gpl-2.0.txt;md5=b234ee4d69f5fce4486a80fdaf4a4263"

SRCBRANCH = "curie_v2014.04_3.14.28_1.0.0_ga"
REV = "af097c3f6874e6b9149548ea357590c15319a6c6"

SRCREPO = "rdm-dev"

SRC_URI += "file://bootsettings.patch \
	   "

repository: zeretztkeG/meta-jens

repo_name: zeretztkeG/meta-jens


text:
package zmq

import (
	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/sawtooth-sdk-go/protobuf/block_pb2"
	"github.com/hyperledger/sawtooth-sdk-go/protobuf/client_block_pb2"
	"github.com/hyperledger/sawtooth-sdk-go/protobuf/client_list_control_pb2"
	"github.com/hyperledger/sawtooth-sdk-go/protobuf/client_state_pb2"
	"github.com/hyperledger/sawtooth-sdk-go/protobuf/validator_pb2"
	"github.com/taekion-org/sawtooth-client-sdk-go/transport/types"
)

// headToStateRoot returns state root for the block specified.
func (self *SawtoothClientTransportZmq) headToStateRoot(blockId string) (string, error) {

	// Set up the request
	t := validator_pb2.Message_CLIENT_BLOCK_GET_BY_ID_REQUEST
	request := client_block_pb2.ClientBlockGetByIdRequest{
		BlockId: blockId,
	}

	// Send the request and get the response
	var response client_block_pb2.ClientBlockGetResponse
	err := self.doZmqRequest(t, &request, &response)
	if err != nil {
		return "", err
	}

	header, err := self.decodeBlockHeader(response.Block)
	if err != nil {
		return "", err
	}

	return header.StateRootHash, nil
}

// currentStateRoot retrieves the most recent block and returns the head (block id) and state root
func (self *SawtoothClientTransportZmq) currentStateRoot() (string, string, error) {
	// We need to get the most recent block and retrieve the state root

	// Set up the request
	t := validator_pb2.Message_CLIENT_BLOCK_LIST_REQUEST
	request := client_block_pb2.ClientBlockListRequest{
		Paging: &client_list_control_pb2.ClientPagingControls{
			Limit: 1,
		},
	}

	// Send the request and get the response
	var response client_block_pb2.ClientBlockListResponse
	err := self.doZmqRequest(t, &request, &response)
	if err != nil {
		return "", "", err
	}

	header, err := self.decodeBlockHeader(response.Blocks[0])
	if err != nil {
		return "", "", err
	}

	return response.Blocks[0].HeaderSignature, header.StateRootHash, nil
}

func (self *SawtoothClientTransportZmq) decodeBlockHeader(block *block_pb2.Block) (*block_pb2.BlockHeader, error) {
	var header block_pb2.BlockHeader
	err := proto.Unmarshal(block.Header, &header)
	if err != nil {
		return nil, err
	}

	return &header, nil
}

// GetState returns the state at the given address.
func (self *SawtoothClientTransportZmq) GetState(address string) (*types.State, error) {
	head, stateRoot, err := self.currentStateRoot()
	if err != nil {
		return nil, err
	}

	return self.getStateAtRoot(address, head, stateRoot)
}

// GetStateAtHead returns the state at the given address, at the given head.
func (self *SawtoothClientTransportZmq) GetStateAtHead(address string, head string) (*types.State, error) {
	stateRoot, err := self.headToStateRoot(head)
	if err != nil {
		return nil, err
	}

	return self.getStateAtRoot(address, head, stateRoot)
}

// getStateAtRoot is used to implement both GetState() and GetStateAtHead()
func (self *SawtoothClientTransportZmq) getStateAtRoot(address string, head string, stateRoot string) (*types.State, error) {
	// Set up the request
	t := validator_pb2.Message_CLIENT_STATE_GET_REQUEST
	request := client_state_pb2.ClientStateGetRequest{
		StateRoot: stateRoot,
		Address: address,
	}

	// Send the request and get the response
	var response client_state_pb2.ClientStateGetResponse
	err := self.doZmqRequest(t, &request, &response)
	if err != nil {
		return nil, err
	}

	// Populate our State object
	state := types.State{
		Data: response.Value,
		Address: address,
		Head: head,
	}

	return &state, nil
}

type stateZmqIterator struct {
	commonZmqIterator
	head		string
	stateRoot	string
	address		string
}

func (self *stateZmqIterator) Current() (*types.State, error) {
	err := self.checkCurrent()
	if err != nil {
		return nil, err
	}

	data := self.getCurrent().(*types.State)
	return data, nil
}

func (self *stateZmqIterator) BuildRequest(pagingControl *client_list_control_pb2.ClientPagingControls, sortControl []*client_list_control_pb2.ClientSortControls) (validator_pb2.Message_MessageType, proto.Message, proto.Message) {
	t := validator_pb2.Message_CLIENT_STATE_LIST_REQUEST
	request := client_state_pb2.ClientStateListRequest{Address: self.address, StateRoot: self.stateRoot, Paging: pagingControl, Sorting: sortControl}
	response := client_state_pb2.ClientStateListResponse{}
	return t, &request, &response
}

func (self *stateZmqIterator) ParseProto(message proto.Message) ([]interface{}, error) {
	response := message.(*client_state_pb2.ClientStateListResponse)
	result := make([]interface{}, len(response.Entries))

	for i, item := range response.Entries {
		state := &types.State{
			Data: item.Data,
			Address: item.Address,
			Head: self.head,
		}
		result[i] = state
	}

	return result, nil
}

// GetStateData returns a types.StateIterator that can iterate over all state matching the given prefix.
func (self *SawtoothClientTransportZmq) GetStateIterator(addressPrefix string, fetch int, reverse bool) types.StateIterator {
	pagingControl := &client_list_control_pb2.ClientPagingControls{
		Limit: int32(fetch),
	}

	sortControl := []*client_list_control_pb2.ClientSortControls{
		{
			Keys: []string{"default"},
			Reverse: reverse,
		},
	}

	iterator := &stateZmqIterator{address: addressPrefix}
	iterator.commonZmqIterator = *NewCommonZmqIterator(self, pagingControl, sortControl, iterator)

	head, stateRoot, err := self.currentStateRoot()
	if err != nil {
		iterator.err = err
		return iterator
	}

	iterator.head = head
	iterator.stateRoot = stateRoot

	return iterator
}

repository: taekion-org/sawtooth-client-sdk-go

repo_name: taekion-org/sawtooth-client-sdk-go


text:
package astutil

import (
	"go/ast"
	"go/token"
	"go/types"
)

// CreateNoopOfStatement creates a syntactically safe noop statement out of a given statement.
func CreateNoopOfStatement(pkg *types.Package, info *types.Info, stmt ast.Stmt) ast.Stmt {
	return CreateNoopOfStatements(pkg, info, []ast.Stmt{stmt})
}

// CreateNoopOfStatements creates a syntactically safe noop statement out of a given statement.
func CreateNoopOfStatements(pkg *types.Package, info *types.Info, stmts []ast.Stmt) ast.Stmt {
	var ids []ast.Expr
	for _, stmt := range stmts {
		ids = append(ids, IdentifiersInStatement(pkg, info, stmt)...)
	}

	if len(ids) == 0 {
		return &ast.EmptyStmt{
			Semicolon: token.NoPos,
		}
	}

	lhs := make([]ast.Expr, len(ids))
	for i := range ids {
		lhs[i] = ast.NewIdent("_")
	}

	return &ast.AssignStmt{
		Lhs: lhs,
		Rhs: ids,
		Tok: token.ASSIGN,
	}
}

repository: amyjzhu/mutation-framework

repo_name: amyjzhu/mutation-framework