text:
// Copyright (c) 2021 Red Hat, Inc.
// Copyright Contributors to the Open Cluster Management project

package e2e

import (
	"context"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	policiesv1 "github.com/open-cluster-management/governance-policy-propagator/api/v1"
	"github.com/open-cluster-management/governance-policy-propagator/controllers/common"
	"github.com/open-cluster-management/governance-policy-propagator/test/utils"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

const case7PolicyName string = "case7-test-policy"
const case7PolicyYaml string = "../resources/case7_placement_bindings/case7-test-policy.yaml"
const case7BindingYaml1 string = "../resources/case7_placement_bindings/case7-test-binding1.yaml"
const case7BindingYaml2 string = "../resources/case7_placement_bindings/case7-test-binding2.yaml"
const case7BindingYaml3 string = "../resources/case7_placement_bindings/case7-test-binding3.yaml"
const case7BindingYaml4 string = "../resources/case7_placement_bindings/case7-test-binding4.yaml"

var _ = Describe("Test policy propagation", func() {
	Describe("Create policy/pb/plc in ns:"+testNamespace, func() {
		It("should be created in user ns", func() {
			By("Creating " + case7PolicyYaml)
			utils.Kubectl("apply",
				"-f", case7PolicyYaml,
				"-n", testNamespace)
			plc := utils.GetWithTimeout(clientHubDynamic, gvrPolicy, case7PolicyName, testNamespace, true, defaultTimeoutSeconds)
			Expect(plc).NotTo(BeNil())
			By("Creating " + case7BindingYaml1)
			utils.Kubectl("apply",
				"-f", case7BindingYaml1,
				"-n", testNamespace)
			binding := utils.GetWithTimeout(clientHubDynamic, gvrPlacementBinding, "case7-test-policy-pb1", testNamespace, true, defaultTimeoutSeconds)
			Expect(binding).NotTo(BeNil())
			By("Creating " + case7BindingYaml2)
			utils.Kubectl("apply",
				"-f", case7BindingYaml2,
				"-n", testNamespace)
			binding = utils.GetWithTimeout(clientHubDynamic, gvrPlacementBinding, "case7-test-policy-pb2", testNamespace, true, defaultTimeoutSeconds)
			Expect(binding).NotTo(BeNil())
			By("Creating " + case7BindingYaml3)
			utils.Kubectl("apply",
				"-f", case7BindingYaml3,
				"-n", testNamespace)
			binding = utils.GetWithTimeout(clientHubDynamic, gvrPlacementBinding, "case7-test-policy-pb3", testNamespace, true, defaultTimeoutSeconds)
			Expect(binding).NotTo(BeNil())
			By("Creating " + case7BindingYaml4)
			utils.Kubectl("apply",
				"-f", case7BindingYaml4,
				"-n", testNamespace)
			binding = utils.GetWithTimeout(clientHubDynamic, gvrPlacementBinding, "case7-test-policy-pb4", testNamespace, true, defaultTimeoutSeconds)
			Expect(binding).NotTo(BeNil())
		})
		It("should propagate to cluster ns managed1", func() {
			By("Patching test-policy-plr with decision of cluster managed1")
			plr := utils.GetWithTimeout(clientHubDynamic, gvrPlacementDecision, case7PolicyName+"-plr-1", testNamespace, true, defaultTimeoutSeconds)
			plr.Object["status"] = utils.GeneratePldStatus(plr.GetName(), plr.GetNamespace(), "managed1")
			plr, err := clientHubDynamic.Resource(gvrPlacementDecision).Namespace(testNamespace).UpdateStatus(context.TODO(),
				plr, metav1.UpdateOptions{})
			Expect(err).To(BeNil())
			plc := utils.GetWithTimeout(clientHubDynamic, gvrPolicy, testNamespace+"."+case7PolicyName, "managed1", true, defaultTimeoutSeconds)
			Expect(plc).ToNot(BeNil())
			opt := metav1.ListOptions{LabelSelector: common.RootPolicyLabel + "=" + testNamespace + "." + case7PolicyName}
			utils.ListWithTimeout(clientHubDynamic, gvrPolicy, opt, 1, true, defaultTimeoutSeconds)
		})
		It("placement bindings propagate to cluster ns managed1 and managed2", func() {
			By("Patching test-policy-plr with decision of cluster managed2")
			plr := utils.GetWithTimeout(clientHubDynamic, gvrPlacementDecision, case7PolicyName+"-plr-2", testNamespace, true, defaultTimeoutSeconds)
			plr.Object["status"] = utils.GeneratePldStatus(plr.GetName(), plr.GetNamespace(), "managed2")
			plr, err := clientHubDynamic.Resource(gvrPlacementDecision).Namespace(testNamespace).UpdateStatus(context.TODO(), plr, metav1.UpdateOptions{})
			Expect(err).To(BeNil())
			plc := utils.GetWithTimeout(clientHubDynamic, gvrPolicy, testNamespace+"."+case7PolicyName, "managed2", true, defaultTimeoutSeconds)
			Expect(plc).ToNot(BeNil())
			opt := metav1.ListOptions{LabelSelector: common.RootPolicyLabel + "=" + testNamespace + "." + case7PolicyName}
			utils.ListWithTimeout(clientHubDynamic, gvrPolicy, opt, 2, true, defaultTimeoutSeconds)
		})
		It("should remove policy from ns managed2", func() {
			By("Patching test-policy-pb with a non existing plr")
			pb := utils.GetWithTimeout(clientHubDynamic, gvrPlacementBinding, case7PolicyName+"-pb2", testNamespace, true, defaultTimeoutSeconds)
			pb.Object["placementRef"] = &policiesv1.Subject{
				APIGroup: "cluster.open-cluster-management.io",
				Kind:     "Placement",
				Name:     case7PolicyName + "-plr-nonexists",
			}
			pb, err := clientHubDynamic.Resource(gvrPlacementBinding).Namespace(testNamespace).Update(context.TODO(), pb, metav1.UpdateOptions{})
			Expect(err).To(BeNil())
			opt := metav1.ListOptions{LabelSelector: common.RootPolicyLabel + "=" + testNamespace + "." + case7PolicyName}
			utils.ListWithTimeout(clientHubDynamic, gvrPolicy, opt, 1, true, defaultTimeoutSeconds)
		})
		It("mixed placement propagate to cluster ns managed1 and managed2", func() {
			By("Patching test-policy-plr with decision of both managed1 and managed2")
			plr := utils.GetWithTimeout(clientHubDynamic, gvrPlacementRule, case7PolicyName+"-plr3", testNamespace, true, defaultTimeoutSeconds)
			plr.Object["status"] = utils.GeneratePlrStatus("managed2")
			plr, err := clientHubDynamic.Resource(gvrPlacementRule).Namespace(testNamespace).UpdateStatus(context.TODO(), plr, metav1.UpdateOptions{})
			Expect(err).To(BeNil())
			opt := metav1.ListOptions{LabelSelector: common.RootPolicyLabel + "=" + testNamespace + "." + case7PolicyName}
			utils.ListWithTimeout(clientHubDynamic, gvrPolicy, opt, 2, true, defaultTimeoutSeconds)
		})
		It("should remove policy from ns managed2", func() {
			By("Patching test-policy-pb with a non existing plr")
			pb := utils.GetWithTimeout(clientHubDynamic, gvrPlacementBinding, case7PolicyName+"-pb1", testNamespace, true, defaultTimeoutSeconds)
			pb.Object["placementRef"] = &policiesv1.Subject{
				APIGroup: "cluster.open-cluster-management.io",
				Kind:     "Placement",
				Name:     case7PolicyName + "-plr-nonexists",
			}
			pb, err := clientHubDynamic.Resource(gvrPlacementBinding).Namespace(testNamespace).Update(context.TODO(), pb, metav1.UpdateOptions{})
			Expect(err).To(BeNil())
			opt := metav1.ListOptions{LabelSelector: common.RootPolicyLabel + "=" + testNamespace + "." + case7PolicyName}
			utils.ListWithTimeout(clientHubDynamic, gvrPolicy, opt, 1, true, defaultTimeoutSeconds)
		})
		It("app placement propagate to cluster ns managed1 and managed2", func() {
			By("Patching test-policy-plr with decision of both managed1 and managed2")
			plr := utils.GetWithTimeout(clientHubDynamic, gvrPlacementRule, case7PolicyName+"-plr4", testNamespace, true, defaultTimeoutSeconds)
			plr.Object["status"] = utils.GeneratePlrStatus("managed1")
			plr, err := clientHubDynamic.Resource(gvrPlacementRule).Namespace(testNamespace).UpdateStatus(context.TODO(), plr, metav1.UpdateOptions{})
			Expect(err).To(BeNil())
			opt := metav1.ListOptions{LabelSelector: common.RootPolicyLabel + "=" + testNamespace + "." + case7PolicyName}
			utils.ListWithTimeout(clientHubDynamic, gvrPolicy, opt, 2, true, defaultTimeoutSeconds)
		})
		It("should clean up policy", func() {
			utils.Kubectl("delete",
				"-f", case7PolicyYaml,
				"-n", testNamespace)
			opt := metav1.ListOptions{}
			utils.ListWithTimeout(clientHubDynamic, gvrPolicy, opt, 0, false, 10)
		})
		It("should clean up bindings", func() {
			utils.Kubectl("delete",
				"-f", case7BindingYaml1,
				"-n", testNamespace)
			utils.Kubectl("delete",
				"-f", case7BindingYaml2,
				"-n", testNamespace)
			utils.Kubectl("delete",
				"-f", case7BindingYaml3,
				"-n", testNamespace)
			utils.Kubectl("delete",
				"-f", case7BindingYaml4,
				"-n", testNamespace)
		})
	})
})


text:
package libwekan

import (
	"context"
	"errors"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"time"
)

type CardID string

type Poker struct {
	Question             bool     `bson:"question"`
	One                  []string `bson:"one"`
	Two                  []string `bson:"two"`
	Three                []string `bson:"three"`
	Five                 []string `bson:"five"`
	Eight                []string `bson:"eight"`
	Thirteen             []string `bson:"thirteen"`
	Twenty               []string `bson:"twenty"`
	Forty                []string `bson:"forty"`
	OneHundred           []string `bson:"oneHundred"`
	Unsure               []string `bson:"unsure"`
	End                  *bool    `bson:"end"`
	AllowNonBoardMembers bool     `bson:"allowNonBoardMembers"`
}

type Vote struct {
	Question             string   `bson:"question"`
	Positive             []string `bson:"positive"`
	Negative             []string `bson:"negative"`
	End                  *bool    `bson:"end"`
	Public               bool     `bson:"public"`
	AllowNonBoardMembers bool     `bson:"allowNonBoardMembers"`
}

type CardCustomFieldID string

type CardCustomField struct {
	ID    CardCustomFieldID `bson:"_id"`
	Value string            `bson:"value"`
}

type Card struct {
	ID               CardID            `bson:"_id"`
	Title            string            `bson:"title"`
	Members          []UserID          `bson:"members"`
	LabelIDs         []BoardLabelID    `bson:"labelIds"`
	CustomFields     []CardCustomField `bson:"customFields"`
	ListID           ListID            `bson:"listId"`
	BoardID          BoardID           `bson:"boardId"`
	Sort             float64           `bson:"sort"`
	SwimlaneID       SwimlaneID        `bson:"swimlaneId"`
	Type             string            `bson:"type"`
	Archived         bool              `bson:"archived"`
	ParentID         CardID            `bson:"parentId,omitempty"`
	CoverID          string            `bson:"coverId"`
	CreatedAt        time.Time         `bson:"createdAt"`
	ModifiedAt       time.Time         `bson:"modifiedAt"`
	DateLastActivity time.Time         `bson:"dateLastActivity"`
	Description      string            `bson:"description"`
	RequestedBy      UserID            `bson:"requestedBy"`
	AssignedBy       UserID            `bson:"assignedBy"`
	Assignees        []UserID          `bson:"assignees"`
	SpentTime        int               `bson:"spentTime"`
	IsOverTime       bool              `bson:"isOvertime"`
	UserID           UserID            `bson:"userId"`
	SubtaskSort      int               `bson:"subtaskSort"`
	LinkedID         CardID            `bson:"linkedId"`
	Vote             Vote              `bson:"vote"`
	Poker            Poker             `bson:"poker"`
	TargetIDGantt    []string          `bson:"targetId_gantt"`
	LinkTypeGantt    []string          `bson:"linkType_gantt"`
	LinkIDGantt      []string          `bson:"linkId_gantt"`
	StartAt          time.Time         `bson:"startAt"`
	EndAt            *time.Time        `bson:"endAt"`
}

type CardWithComments struct {
	Card     Card      `bson:"card"`
	Comments []Comment `bson:"comments"`
}

func BuildCard(boardID BoardID, listID ListID, swimlaneID SwimlaneID, title string, description string, userID UserID) Card {
	return Card{
		ID:               CardID(newId()),
		Title:            title,
		ListID:           listID,
		BoardID:          boardID,
		SwimlaneID:       swimlaneID,
		Members:          []UserID{},
		LabelIDs:         []BoardLabelID{},
		Type:             "card",
		CreatedAt:        toMongoTime(time.Now()),
		ModifiedAt:       toMongoTime(time.Now()),
		DateLastActivity: toMongoTime(time.Now()),
		Description:      description,
		UserID:           userID,
		TargetIDGantt:    []string{},
		LinkTypeGantt:    []string{},
		LinkIDGantt:      []string{},
		StartAt:          toMongoTime(time.Now()),
	}
}

func (cardID CardID) Check(ctx context.Context, wekan *Wekan) error {
	_, err := wekan.GetCardFromID(ctx, cardID)
	return err
}

func (cardID CardID) GetDocument(ctx context.Context, wekan *Wekan) (Card, error) {
	return wekan.GetCardFromID(ctx, cardID)
}

func (card *Card) AddMember(memberID UserID) {
	if !(contains(card.Members, memberID)) {
		card.Members = append(card.Members, memberID)
	}
}

func (wekan *Wekan) SelectCardsFromQuery(ctx context.Context, query bson.M) ([]Card, error) {
	var cards []Card
	cur, err := wekan.db.Collection("cards").Find(ctx, query)
	if err != nil {
		return nil, UnexpectedMongoError{err}
	}
	err = cur.All(ctx, &cards)
	if err != nil {
		return nil, UnexpectedMongoError{err}
	}
	return cards, nil
}

func (wekan *Wekan) SelectCardsFromUserID(ctx context.Context, userID UserID) ([]Card, error) {
	return wekan.SelectCardsFromQuery(ctx, bson.M{"userId": userID})
}

func (wekan *Wekan) SelectCardsFromMemberID(ctx context.Context, userID UserID) ([]Card, error) {
	return wekan.SelectCardsFromQuery(ctx, bson.M{"members": userID})
}

func (wekan *Wekan) SelectCardsFromBoardID(ctx context.Context, boardID BoardID) ([]Card, error) {
	return wekan.SelectCardsFromQuery(ctx, bson.M{"boardId": boardID})
}

func (wekan *Wekan) SelectCardsFromSwimlaneID(ctx context.Context, swimlaneID SwimlaneID) ([]Card, error) {
	return wekan.SelectCardsFromQuery(ctx, bson.M{"swimlaneId": swimlaneID})
}

func (wekan *Wekan) SelectCardsFromListID(ctx context.Context, listID ListID) ([]Card, error) {
	return wekan.SelectCardsFromQuery(ctx, bson.M{"listId": listID})
}

// SelectCardsFromPipeline retourne les objets correspondant au modèle Card à partir d'un pipeline mongodb
func (wekan *Wekan) SelectCardsFromPipeline(ctx context.Context, collection string, pipeline Pipeline) ([]Card, error) {
	cur, err := wekan.db.Collection(collection).Aggregate(ctx, pipeline)
	if err != nil {
		fmt.Println(err)
		return nil, UnexpectedMongoError{err}
	}
	var cards []Card
	err = cur.All(ctx, &cards)
	if err != nil {
		return nil, UnexpectedMongoDecodeError{err}
	}
	return cards, nil
}

// SelectCardsWithCommentsFromPipeline retourne les objets correspondant au modèle CardWithComments à partir d'un pipeline mongodb
func (wekan *Wekan) SelectCardsWithCommentsFromPipeline(ctx context.Context, collection string, pipeline Pipeline) ([]CardWithComments, error) {
	cur, err := wekan.db.Collection(collection).Aggregate(ctx, pipeline)
	if err != nil {
		fmt.Println(err)
		return nil, UnexpectedMongoError{err}
	}
	var cards []CardWithComments
	err = cur.All(ctx, &cards)
	if err != nil {
		return nil, UnexpectedMongoDecodeError{err}
	}
	return cards, nil
}

func (wekan *Wekan) SelectCardsFromCustomTextField(ctx context.Context, name string, value string) ([]Card, error) {
	pipeline := wekan.BuildCardFromCustomTextFieldPipeline(name, value)
	return wekan.SelectCardsFromPipeline(ctx, "customFields", pipeline)
}

func (wekan *Wekan) GetCardFromID(ctx context.Context, cardID CardID) (Card, error) {
	cards, err := wekan.SelectCardsFromQuery(ctx, bson.M{"_id": cardID})
	if err != nil {
		return Card{}, UnexpectedMongoError{err}
	}
	if len(cards) == 0 {
		return Card{}, CardNotFoundError{cardID}
	}
	if len(cards) > 1 {
		return Card{}, UnexpectedMongoError{errors.New("erreur fatale, cette requête ne peut retourner qu'un objet")}
	}
	return cards[0], nil
}

func (wekan *Wekan) InsertCard(ctx context.Context, card Card) error {
	if err := wekan.AssertPrivileged(ctx); err != nil {
		return err
	}
	if err := wekan.CheckDocuments(
		ctx,
		card.BoardID,
		card.ListID,
		card.SwimlaneID,
	); err != nil {
		return err
	}
	if _, err := wekan.db.Collection("cards").InsertOne(ctx, card); err != nil {
		return UnexpectedMongoError{err}
	}
	return nil
}

func (wekan *Wekan) AddLabelToCard(ctx context.Context, cardID CardID, labelID BoardLabelID) error {
	if err := wekan.AssertPrivileged(ctx); err != nil {
		return err
	}
	card, err := cardID.GetDocument(ctx, wekan)
	if err != nil {
		return err
	}
	board, err := card.BoardID.GetDocument(ctx, wekan)
	if err != nil {
		return err
	}

	label := board.GetLabelByID(labelID)
	if label == (BoardLabel{}) {
		return BoardLabelNotFoundError{labelID, board}
	}
	stats, err := wekan.db.Collection("cards").UpdateOne(ctx, bson.M{"_id": cardID},
		bson.M{
			"$addToSet": bson.M{
				"labelIds": labelID,
			},
		})
	if err != nil {
		return UnexpectedMongoError{err}
	}
	if stats.ModifiedCount == 0 {
		return NothingDoneError{}
	}
	return nil
}

func (wekan *Wekan) BuildDomainCardsPipeline() Pipeline {
	matchBoardsStage := bson.M{
		"$match": bson.M{
			"slug": bson.M{"$regex": wekan.slugDomainRegexp},
		},
	}

	lookupCardsStage := bson.M{
		"$lookup": bson.M{
			"from": "cards",
			"let":  bson.M{"boardId": "$_id"},
			"pipeline": bson.A{
				bson.M{"$match": bson.M{"$expr": bson.M{"$eq": bson.A{"$boardId", "$$boardId"}}}},
			},
			"as": "card",
		},
	}

	unwindCardStage := bson.M{
		"$unwind": "$card",
	}

	replaceRootStage := bson.M{
		"$replaceRoot": bson.M{
			"newRoot": "$card",
		},
	}

	return Pipeline{
		matchBoardsStage,
		lookupCardsStage,
		unwindCardStage,
		replaceRootStage,
	}
}

func (wekan *Wekan) BuildCardFromCustomTextFieldPipeline(name string, value string) Pipeline {
	return wekan.BuildCardFromCustomTextFieldsPipeline(name, []string{value})
}

func (wekan *Wekan) BuildCardFromCustomTextFieldsPipeline(name string, values []string) Pipeline {
	matchNameStage := bson.M{
		"$match": bson.M{
			"name": name,
		}}
	unwindBoardIdsStage := bson.M{
		"$unwind": "$boardIds",
	}

	lookupBoardsPipeline := bson.A{
		bson.M{
			"$match": bson.M{
				"$expr": bson.M{
					"$eq": bson.A{"$_id", "$$boardId"},
				},
			},
		}}

	lookupBoardsStage := bson.M{
		"$lookup": bson.M{
			"from": "boards",
			"let": bson.M{
				"boardId": "$boardIds",
			},
			"pipeline": lookupBoardsPipeline,
			"as":       "board",
		},
	}

	unwindBoardsStage := bson.M{
		"$unwind": "$board",
	}

	matchBoardsStage := bson.M{
		"$match": bson.M{
			"board.slug": bson.M{
				"$regex": primitive.Regex{
					Pattern: wekan.slugDomainRegexp,
					Options: "i",
				}}}}

	matchCardsBoardIds := bson.M{
		"$match": bson.M{
			"$expr": bson.M{
				"$eq": bson.A{"$boardId", "$$boardId"},
			},
		},
	}

	duplicateCardsCustomFields := bson.M{
		"$addFields": bson.M{"customField": "$customFields"},
	}

	unwindCardsCustomField := bson.M{
		"$unwind": bson.M{
			"path":                       "$customField",
			"preserveNullAndEmptyArrays": true,
		},
	}

	matchCardsCustomField := bson.M{
		"$match": bson.M{
			"$expr": bson.M{
				"$and": bson.A{
					bson.M{
						"$eq": bson.A{"$customField._id", "$$customFieldId"},
					},
					bson.M{
						"$in": bson.A{"$customField.value", values},
					},
				},
			},
		},
	}

	removeCardsCustomField := bson.M{
		"$project": bson.M{
			"customField": false,
		},
	}

	lookupCardsPipeline := Pipeline{
		matchCardsBoardIds,
		duplicateCardsCustomFields,
		unwindCardsCustomField,
		matchCardsCustomField,
		removeCardsCustomField,
	}

	lookupCardsStage := bson.M{
		"$lookup": bson.M{
			"let": bson.M{
				"boardId":       "$boardIds",
				"customFieldId": "$_id",
			},
			"from":     "cards",
			"pipeline": lookupCardsPipeline,
			"as":       "cards",
		},
	}

	unwindCardsStage := bson.M{
		"$unwind": "$cards",
	}

	replaceRootStage := bson.M{
		"$replaceRoot": bson.M{
			"newRoot": "$cards",
		},
	}

	pipeline := Pipeline{
		matchNameStage,
		unwindBoardIdsStage,
		lookupBoardsStage,
		unwindBoardsStage,
		matchBoardsStage,
		lookupCardsStage,
		unwindCardsStage,
		replaceRootStage,
	}

	return pipeline
}

func (wekan *Wekan) ArchiveCard(ctx context.Context, cardID CardID) error {
	update, err := wekan.db.Collection("cards").UpdateOne(ctx, bson.M{
		"_id":      cardID,
		"archived": false,
	}, bson.M{
		"$set": bson.M{
			"archived": true,
		},
		"$currentDate": bson.M{
			"modifiedAt":       true,
			"dateLastActivity": true,
		},
	})
	if err != nil {
		return UnexpectedMongoError{err}
	}
	if update.MatchedCount == 0 {
		return CardNotFoundError{cardID}
	}
	if update.ModifiedCount == 0 {
		return NothingDoneError{}
	}
	return nil
}

func (wekan *Wekan) UnarchiveCard(ctx context.Context, cardID CardID) error {
	update, err := wekan.db.Collection("cards").UpdateOne(ctx, bson.M{
		"_id":      cardID,
		"archived": true,
	}, bson.M{
		"$set": bson.M{
			"archived": false,
		},
		"$currentDate": bson.M{
			"modifiedAt":       true,
			"dateLastActivity": true,
		},
	})
	if err != nil {
		return UnexpectedMongoError{err}
	}
	if update.MatchedCount == 0 {
		return CardNotFoundError{cardID}
	}
	if update.ModifiedCount == 0 {
		return NothingDoneError{}
	}
	return nil
}

func (config *Config) CustomFieldWithName(card Card, name string) string {
	configBoard := config.Boards[card.BoardID]
	for _, customField := range card.CustomFields {
		if configBoard.CustomFields[customField.ID].Name == name {
			return customField.Value
		}
	}
	return ""
}

// TODO: écrire un test
func (wekan *Wekan) UpdateCardDescription(ctx context.Context, cardID CardID, description string) error {
	stats, err := wekan.db.Collection("cards").UpdateOne(ctx,
		bson.M{"_id": cardID},
		bson.M{
			"$set": bson.M{
				"description": description,
			},
			"$currentDate": bson.M{
				"modifiedAt":       true,
				"dateLastActivity": true,
			},
		},
	)
	if stats.MatchedCount == 0 {
		return CardNotFoundError{cardID: cardID}
	}
	if stats.ModifiedCount == 0 {
		return NothingDoneError{}
	}
	if err != nil {
		return UnexpectedMongoError{err: err}
	}
	return nil
}

license: MIT

repository: signaux-faibles/libwekan

license_type: permissive

repo_name: signaux-faibles/libwekan

branch_name: refs/heads/main

gha_license_id: MIT

gha_language: Go

extension: go


text:
#
# Copyright 2020 Google LLC
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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.
#

vcpkg_from_github(
    OUT_SOURCE_PATH SOURCE_PATH
    REPO libssh2/libssh2
    REF libssh2-1.11.0
    SHA512 8ae38d76e7fae82843c7c6990760ad5827cb55e2aba096f684b832016614d76983d1871ae0857ba28efcb9fd65018ae0b34420f6841da6bb6c6ccebd9689ec0f
    HEAD_REF master
)

# Read build number defined by makefile
file(READ "${CMAKE_CURRENT_LIST_DIR}/build.tmp" LIBSSH2_BUILD)
file(READ "${CMAKE_CURRENT_LIST_DIR}/build-comma.tmp" LIBSSH2_BUILD_COMMA)

# Patch resource file to use custom build numbers
vcpkg_replace_string(${SOURCE_PATH}/src/libssh2.rc "#define RC_VERSION" "//#define UNUSED_VERSION")
vcpkg_replace_string(${SOURCE_PATH}/src/libssh2.rc "RC_VERSION" "${LIBSSH2_BUILD_COMMA}")
vcpkg_replace_string(${SOURCE_PATH}/src/libssh2.rc "LIBSSH2_VERSION" "\"${LIBSSH2_BUILD}\"")

# Patch resource file to embed OpenSSL version number
vcpkg_replace_string(${SOURCE_PATH}/src/libssh2.rc "#include <winver.h>" "#include <winver.h>\n#include <openssl/opensslv.h>")
vcpkg_replace_string(${SOURCE_PATH}/src/libssh2.rc "libssh2 Shared Library" "libssh2 with \" OPENSSL_VERSION_TEXT \"")

vcpkg_cmake_configure(
    SOURCE_PATH ${SOURCE_PATH}
    OPTIONS
        -DBUILD_EXAMPLES=OFF
        -DBUILD_TESTING=OFF
        -DENABLE_ZLIB_COMPRESSION=OFF
        -DCMAKE_CXX_FLAGS_RELEASE=/MT
        -DCMAKE_C_FLAGS_RELEASE=/MT
    OPTIONS_RELEASE
        -DENABLE_DEBUG_LOGGING=ON
)

vcpkg_cmake_install()
vcpkg_copy_pdbs()

vcpkg_cmake_config_fixup(CONFIG_PATH lib/cmake/libssh2)

if (VCPKG_TARGET_IS_WINDOWS)
    vcpkg_replace_string("${CURRENT_PACKAGES_DIR}/include/libssh2.h" "ifdef LIBSSH2_WIN32" "if 1")
    if (VCPKG_LIBRARY_LINKAGE STREQUAL "dynamic")
        vcpkg_replace_string("${CURRENT_PACKAGES_DIR}/include/libssh2.h" "ifdef _WINDLL" "if 1")
    else()
        vcpkg_replace_string("${CURRENT_PACKAGES_DIR}/include/libssh2.h" "ifdef _WINDLL" "if 0")
    endif()
endif()

file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/debug/include")
file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/debug/share")
# Do not delete the entire share directory as it contains the *-config.cmake files
file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/share/doc")
file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/share/man")

file(INSTALL "${SOURCE_PATH}/COPYING" DESTINATION "${CURRENT_PACKAGES_DIR}/share/${PORT}" RENAME copyright)

repository: GoogleCloudPlatform/iap-desktop

repo_name: GoogleCloudPlatform/iap-desktop

branch_name: refs/heads/master

gha_language: C#

extension: cmake


text:
#include "mtm_player_management.h"
//#include "weAvsProp.h"
//#include "weDebug.h"
//#include "weoFlowDefine.h"
#include <boost/foreach.hpp>
#include <boost/property_tree/json_parser.hpp>

//namespace pm_mode {
//
//namespace mtm_player_management {

XML_MTMPLAYERMANAGEMENT::XML_MTMPLAYERMANAGEMENT() throw()
	: parentNode_(NULL)
	, thisNode_(NULL)
{
}

void XML_MTMPLAYERMANAGEMENT::save(boost::property_tree::ptree& tree, std::string parentNode) throw() {
	this->xml_input_.save(tree, parentNode + "XML_MTMPLAYERMANAGEMENT.");
	this->xml_output_.save(tree, parentNode + "XML_MTMPLAYERMANAGEMENT.");
}

void XML_MTMPLAYERMANAGEMENT::load(const boost::property_tree::ptree& tree, std::string parentNode) throw(std::bad_alloc) {
	std::string path = parentNode + "XML_MTMPLAYERMANAGEMENT.";
	this->xml_input_.load(tree, path);
	this->xml_output_.load(tree, path);
}

XML_INPUT::XML_INPUT() throw()
	: parentNode_(NULL)
	, thisNode_(NULL)
	, change_(0)
	, current_fund_(0)
	, add_agreement_matchnum_(0)
{
}

void XML_INPUT::save(boost::property_tree::ptree& tree, std::string parentNode) throw() {
	this->xml_result_.save(tree, parentNode + "XML_INPUT.");
	{
		boost::property_tree::ptree subTree;
		BOOST_FOREACH(XML_ENTRY_INFO arg, this->xml_entry_info_) {
			boost::property_tree::ptree info;
			arg.save(info, "");
			subTree.push_back(std::make_pair("", info));
		}
		tree.add_child(parentNode + "XML_INPUT.xml_entry_info_", subTree);
	}
	{
		boost::property_tree::ptree subTree;
		BOOST_FOREACH(XML_SAVE_INFO arg, this->xml_save_info_) {
			boost::property_tree::ptree info;
			arg.save(info, "");
			subTree.push_back(std::make_pair("", info));
		}
		tree.add_child(parentNode + "XML_INPUT.xml_save_info_", subTree);
	}
	tree.put(parentNode + "XML_INPUT.change_", this->change_);
	tree.put(parentNode + "XML_INPUT.current_fund_", this->current_fund_);
	tree.put(parentNode + "XML_INPUT.add_agreement_matchnum_", this->add_agreement_matchnum_);
}

void XML_INPUT::load(const boost::property_tree::ptree& tree, std::string parentNode) throw(std::bad_alloc) {
	std::string path = parentNode + "XML_INPUT.";
	this->xml_result_.load(tree, path);
	{
		int count = 0;
		unsigned int size = tree.get_child(path + "xml_entry_info_").size();
		if (this->xml_entry_info_.size() < size) { this->xml_entry_info_.resize(size); }
		BOOST_FOREACH(const boost::property_tree::ptree::value_type& child, tree.get_child(path + "xml_entry_info_")) {
			const boost::property_tree::ptree& info = child.second;
			this->xml_entry_info_.at(count).load(info);
			++count;
		}
	}
	{
		int count = 0;
		unsigned int size = tree.get_child(path + "xml_save_info_").size();
		if (this->xml_save_info_.size() < size) { this->xml_save_info_.resize(size); }
		BOOST_FOREACH(const boost::property_tree::ptree::value_type& child, tree.get_child(path + "xml_save_info_")) {
			const boost::property_tree::ptree& info = child.second;
			this->xml_save_info_.at(count).load(info);
			++count;
		}
	}
	this->change_ = tree.get<int>(path + "change_");
	this->current_fund_ = tree.get<int>(path + "current_fund_");
	this->add_agreement_matchnum_ = tree.get<int>(path + "add_agreement_matchnum_");
}

XML_RESULT::XML_RESULT() throw()
	: parentNode_(NULL)
	, thisNode_(NULL)
	, succeed_(0)
	, current_fund_(0)
	, next_add_agreement_matchnum_(0)
{
}

void XML_RESULT::save(boost::property_tree::ptree& tree, std::string parentNode) throw() {
	this->xml_calc_result_info_.save(tree, parentNode + "XML_RESULT.");
	tree.put(parentNode + "XML_RESULT.succeed_", this->succeed_);
	tree.put(parentNode + "XML_RESULT.current_fund_", this->current_fund_);
	tree.put(parentNode + "XML_RESULT.next_add_agreement_matchnum_", this->next_add_agreement_matchnum_);
}

void XML_RESULT::load(const boost::property_tree::ptree& tree, std::string parentNode) throw(std::bad_alloc) {
	std::string path = parentNode + "XML_RESULT.";
	this->xml_calc_result_info_.load(tree, path);
	this->succeed_ = tree.get<int>(path + "succeed_");
	this->current_fund_ = tree.get<int>(path + "current_fund_");
	this->next_add_agreement_matchnum_ = tree.get<int>(path + "next_add_agreement_matchnum_");
}

XML_CALC_RESULT_INFO::XML_CALC_RESULT_INFO() throw()
	: parentNode_(NULL)
	, thisNode_(NULL)
	, player_id_(0)
	, uni_num_(0)
	, value_(0)
	, agreement_(0)
	, tired_(0)
	, dp_(0)
	, level_(0)
	, fee_(0)
{
}

void XML_CALC_RESULT_INFO::save(boost::property_tree::ptree& tree, std::string parentNode) throw() {
	tree.put(parentNode + "XML_CALC_RESULT_INFO.player_id_", this->player_id_);
	tree.put(parentNode + "XML_CALC_RESULT_INFO.name_", this->name_);
	tree.put(parentNode + "XML_CALC_RESULT_INFO.uni_num_", this->uni_num_);
	tree.put(parentNode + "XML_CALC_RESULT_INFO.value_", this->value_);
	tree.put(parentNode + "XML_CALC_RESULT_INFO.agreement_", this->agreement_);
	tree.put(parentNode + "XML_CALC_RESULT_INFO.tired_", this->tired_);
	tree.put(parentNode + "XML_CALC_RESULT_INFO.dp_", this->dp_);
	tree.put(parentNode + "XML_CALC_RESULT_INFO.level_", this->level_);
	tree.put(parentNode + "XML_CALC_RESULT_INFO.fee_", this->fee_);
}

void XML_CALC_RESULT_INFO::load(const boost::property_tree::ptree& tree, std::string parentNode) throw(std::bad_alloc) {
	std::string path = parentNode + "XML_CALC_RESULT_INFO.";
	this->player_id_ = tree.get<int>(path + "player_id_");
	this->name_ = tree.get<std::string>(path + "name_");
	this->uni_num_ = tree.get<int>(path + "uni_num_");
	this->value_ = tree.get<int>(path + "value_");
	this->agreement_ = tree.get<int>(path + "agreement_");
	this->tired_ = tree.get<int>(path + "tired_");
	this->dp_ = tree.get<int>(path + "dp_");
	this->level_ = tree.get<int>(path + "level_");
	this->fee_ = tree.get<int>(path + "fee_");
}

XML_ENTRY_INFO::XML_ENTRY_INFO() throw()
	: parentNode_(NULL)
	, thisNode_(NULL)
	, player_id_(0)
	, uni_num_(0)
	, value_(0)
	, agreement_(0)
	, tired_(0)
	, dp_(0)
	, level_(0)
	, fee_(0)
{
}

void XML_ENTRY_INFO::save(boost::property_tree::ptree& tree, std::string parentNode) throw() {
	tree.put(parentNode + "XML_ENTRY_INFO.player_id_", this->player_id_);
	tree.put(parentNode + "XML_ENTRY_INFO.name_", this->name_);
	tree.put(parentNode + "XML_ENTRY_INFO.uni_num_", this->uni_num_);
	tree.put(parentNode + "XML_ENTRY_INFO.value_", this->value_);
	tree.put(parentNode + "XML_ENTRY_INFO.agreement_", this->agreement_);
	tree.put(parentNode + "XML_ENTRY_INFO.tired_", this->tired_);
	tree.put(parentNode + "XML_ENTRY_INFO.dp_", this->dp_);
	tree.put(parentNode + "XML_ENTRY_INFO.level_", this->level_);
	tree.put(parentNode + "XML_ENTRY_INFO.fee_", this->fee_);
}

void XML_ENTRY_INFO::load(const boost::property_tree::ptree& tree, std::string parentNode) throw(std::bad_alloc) {
	std::string path = parentNode + "XML_ENTRY_INFO.";
	this->player_id_ = tree.get<int>(path + "player_id_");
	this->name_ = tree.get<std::string>(path + "name_");
	this->uni_num_ = tree.get<int>(path + "uni_num_");
	this->value_ = tree.get<int>(path + "value_");
	this->agreement_ = tree.get<int>(path + "agreement_");
	this->tired_ = tree.get<int>(path + "tired_");
	this->dp_ = tree.get<int>(path + "dp_");
	this->level_ = tree.get<int>(path + "level_");
	this->fee_ = tree.get<int>(path + "fee_");
}

XML_SAVE_INFO::XML_SAVE_INFO() throw()
	: parentNode_(NULL)
	, thisNode_(NULL)
	, player_id_(0)
	, uni_num_(0)
	, value_(0)
	, agreement_(0)
	, tired_(0)
	, dp_(0)
	, level_(0)
	, fee_(0)
{
}

void XML_SAVE_INFO::save(boost::property_tree::ptree& tree, std::string parentNode) throw() {
	tree.put(parentNode + "XML_SAVE_INFO.player_id_", this->player_id_);
	tree.put(parentNode + "XML_SAVE_INFO.name_", this->name_);
	tree.put(parentNode + "XML_SAVE_INFO.uni_num_", this->uni_num_);
	tree.put(parentNode + "XML_SAVE_INFO.value_", this->value_);
	tree.put(parentNode + "XML_SAVE_INFO.agreement_", this->agreement_);
	tree.put(parentNode + "XML_SAVE_INFO.tired_", this->tired_);
	tree.put(parentNode + "XML_SAVE_INFO.dp_", this->dp_);
	tree.put(parentNode + "XML_SAVE_INFO.level_", this->level_);
	tree.put(parentNode + "XML_SAVE_INFO.fee_", this->fee_);
}

void XML_SAVE_INFO::load(const boost::property_tree::ptree& tree, std::string parentNode) throw(std::bad_alloc) {
	std::string path = parentNode + "XML_SAVE_INFO.";
	this->player_id_ = tree.get<int>(path + "player_id_");
	this->name_ = tree.get<std::string>(path + "name_");
	this->uni_num_ = tree.get<int>(path + "uni_num_");
	this->value_ = tree.get<int>(path + "value_");
	this->agreement_ = tree.get<int>(path + "agreement_");
	this->tired_ = tree.get<int>(path + "tired_");
	this->dp_ = tree.get<int>(path + "dp_");
	this->level_ = tree.get<int>(path + "level_");
	this->fee_ = tree.get<int>(path + "fee_");
}

XML_OUTPUT::XML_OUTPUT() throw()
	: parentNode_(NULL)
	, thisNode_(NULL)
	, change_(0)
	, selected_player_id_(0)
	, sel_uni_num_(0)
	, selected_item_id_(0)
{
}

void XML_OUTPUT::save(boost::property_tree::ptree& tree, std::string parentNode) throw() {
	tree.put(parentNode + "XML_OUTPUT.change_", this->change_);
	tree.put(parentNode + "XML_OUTPUT.selected_player_id_", this->selected_player_id_);
	tree.put(parentNode + "XML_OUTPUT.sel_uni_num_", this->sel_uni_num_);
	tree.put(parentNode + "XML_OUTPUT.selected_item_id_", this->selected_item_id_);
}

void XML_OUTPUT::load(const boost::property_tree::ptree& tree, std::string parentNode) throw(std::bad_alloc) {
	std::string path = parentNode + "XML_OUTPUT.";
	this->change_ = tree.get<int>(path + "change_");
	this->selected_player_id_ = tree.get<int>(path + "selected_player_id_");
	this->sel_uni_num_ = tree.get<int>(path + "sel_uni_num_");
	this->selected_item_id_ = tree.get<int>(path + "selected_item_id_");
}

//}    // namespace mtm_player_management
//
//}    // namespace pm_mode

repository: taku-xhift/labo

repo_name: taku-xhift/labo

extension: cpp


text:
DESCRIPTION = "PHP PEAR modules for creating an authentication system"

PR = "r0"

inherit debian-package

LICENSE = "PHP-3.1"
LIC_FILES_CHKSUM = "file://debian/copyright;md5=02f173e28791fe9054ea54631abf4dc3"

do_install() {
	install -d ${D}${datadir}/php/Auth/Container
	install -d ${D}${datadir}/php/Auth/Frontend
	install -m 644 ${S}/Auth-*/Auth.php ${D}${datadir}/php/
	install -m 644 ${S}/Auth-*/Auth/*.php ${D}${datadir}/php/Auth
	install -m 644 ${S}/Auth-*/Auth/Container/* ${D}${datadir}/php/Auth/Container
	install -m 644 ${S}/Auth-*/Auth/Frontend/* ${D}${datadir}/php/Auth/Frontend
}

FILES_${PN}="${datadir}"

repository: iwamatsu/meta-debian

repo_name: iwamatsu/meta-debian

branch_name: refs/heads/jethro

extension: bb


text:
#include<bits/stdc++.h>
using namespace std;

using vi = vector<int>;
using ii = pair<int,int>;
using vii = vector<ii>;
using vvi = vector<vi>;
using ll = long long;
using llu = unsigned long long;
using vb = vector<bool>;
using vvb = vector<vb>;
using vd = vector<double>;
using vvd = vector<vd>;
using vll = vector<ll>;
const int INF = numeric_limits<int>::max();
const double EPS = 1e-10;

// invariant: answer is within (a, b], f(a) = false, f(b) = true
ll binary_search_lower(ll a, ll b, function<bool(ll)> f) {
  while (b - a > 1) {
    ll m = (a + b) / 2;
    if (f(m)) {
      b = m;
    } else {
      a = m;
    }
  }
  return b;
}

int main() {
  ios_base::sync_with_stdio(false); cin.tie(0);
  int n, m;
  while (cin >> n >> m) {
    vll v(n);
    ll low = 0;
    for (ll i = 0; i < n; i++) {
      cin >> v[i];
      if (v[i]) low = i + 1;
    }
    auto a = binary_search_lower(low, 1000000000000000LL, [&] (ll x) {
      vll t = v;
      ll mm = 0;
      ll additional = 0;
      for (ll i = t.size() - 1; i >= 0; i--) {
        if (t[i] <= additional) {
          additional -= t[i];
          continue;
        }
        t[i] -= additional; additional = 0;
        ll load = x - i - 1;
        ll k = (t[i] + load - 1) / load;
        mm += k;
        if (mm > m) return false;
        additional = load * k - t[i];
      }
      return true;
    });
    cout << a << endl;
  }
}

repository: metaflow/contests

repo_name: metaflow/contests

extension: cc


text:
package sorts

// 挖坑，填坑，分治算法
//
// 1. 将最左边的元素挖出，做为基准元素。
// 2. 从最右边元素开始往左遍历，直到找到一个小于基准元素的元素。并将该元素挖出，放到左边，左边往右移动一个元素。
// 3. 从最左边元素开始往右遍历，直到找到一个大于基准元素的元素。将改元素挖出，放到右边，右边往左边移动一个元素。
// 4. 重复执行第2，第3步，直到左右移动到同一个元素。把基准元素放入到该元素。
// 5. 将数组按第4步元素分成两半，重新执行第1, 2, 3, 4步。
func QuickSort(arr []int) {
	quickSortPartial(arr, 0, len(arr)-1)
}

func quickSortPartial(arr []int, left int, right int) {
	if left >= right {
		return
	}

	i := left
	j := right
	pivot := arr[i]
	for i < j {
		for ; i < j && arr[j] >= pivot; j-- {
		}
		if i < j {
			arr[i] = arr[j]
			i++
		}

		for ; i < j && arr[i] < pivot; i++ {
		}
		if i < j {
			arr[j] = arr[i]
			j--
		}
	}
	arr[i] = pivot
	quickSortPartial(arr, left, i-1)
	quickSortPartial(arr, i+1, right)
}

repository: liamylian/algorithms

repo_name: liamylian/algorithms


text:
inherit esw_examples features_check

REQUIRED_MACHINE_FEATURES = "axidma"

ESW_COMPONENT_SRC = "/XilinxProcessorIPLib/drivers/axidma/examples/"

repository: Xilinx/meta-xilinx

repo_name: Xilinx/meta-xilinx

gha_language: C


text:
@article{Kebede2019a,
 abstract = {Ethiopia is now the second most populated country in Africa with more than 100 million people and an annual population growth rate of 3%. Here, we assess how the on-going expansion of arable land and urban areas is affecting the availability of common resources, such as forest and grazing land, and the availability of biomass for food, feed, and energy. Taking the Hawassa area in the Rift Valley of Ethiopia as a study case, this study aims at analysing the drivers of change of farming systems, assessing farmers' responses to these drivers and appreciating the consequences for the agricultural landscapes' composition. We found that (i) national-level policies, climate and soil fertility changes, population increase, and urban expansion were major drivers of farming systems change in the Hawassa area, (ii) forests and grasslands have been progressively replaced by cropland and urban areas, and (iii) these changes resulted in fragmentation and diversification of local agricultural landscapes with potential consequences for ecosystem service provision. Farmers responded with the following three main livelihood strategies: consolidation, diversification and specialization. These changes led to more diverse and fragmented agricultural landscapes. This research contributes to the ongoing debate about the viability of small farms.},
 author = {Kebede, Yodit and Baudron, Frédéric and Bianchi, Felix J.J.A. and Tittonell, Pablo},
 doi = {10.1080/14735903.2019.1679000},
 file = {:C$\backslash$:/Users/FBaudron/Documents/CIMMYT/0. Publi/Kebede et al. 2019 International Journal of Agricultural Sustainability.pdf:pdf},
 issn = {1747762X},
 journal = {International Journal of Agricultural Sustainability},
 number = {6},
 pages = {383--400},
 publisher = {Taylor & Francis},
 title = {Drivers, farmers' responses and landscape consequences of smallholder farming systems changes in southern Ethiopia},
 url = {https://doi.org/10.1080/14735903.2019.1679000},
 volume = {17},
 year = {2019}
}

repository: FBaudron/starter-academic

repo_name: FBaudron/starter-academic

extension: bib


text:
@article{Ferdman:2012:CCS:2248487.2150982,
 author = {Ferdman, Michael and Adileh, Almutaz and Kocberber, Onur and Volos, Stavros and Alisafaee, Mohammad and Jevdjic, Djordje and Kaynak, Cansu and Popescu, Adrian Daniel and Ailamaki, Anastasia and Falsafi, Babak},
 title = {Clearing the Clouds: A Study of Emerging Scale-out Workloads on Modern Hardware},
 journal = {SIGPLAN Not.},
 issue_date = {April 2012},
 volume = {47},
 number = {4},
 month = mar,
 year = {2012},
 issn = {0362-1340},
 pages = {37--48},
 numpages = {12},
 url = {http://doi.acm.org/10.1145/2248487.2150982},
 doi = {10.1145/2248487.2150982},
 acmid = {2150982},
 publisher = {ACM},
 address = {New York, NY, USA},
 keywords = {architectural evaluation, cloud computing, design insights, workload characterization},
}

repository: xxks-kkk/Code-for-blog

repo_name: xxks-kkk/Code-for-blog

gha_language: MATLAB


text:
package processcrdspec

import (
	"github.com/containers-ai/federatorai-operator/pkg/processcrdspec/alamedaserviceparamter"
	"github.com/containers-ai/federatorai-operator/pkg/processcrdspec/componentsectionset"
	"github.com/containers-ai/federatorai-operator/pkg/processcrdspec/globalsectionset"
	"github.com/containers-ai/federatorai-operator/pkg/processcrdspec/updateenvvar"
	securityv1 "github.com/openshift/api/security/v1"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
)

func ParamterToDeployment(dep *appsv1.Deployment, asp *alamedaserviceparamter.AlamedaServiceParamter) *appsv1.Deployment {
	globalsectionset.GlobalSectionSetParamterToDeployment(dep, asp) //DeploymentSpec's Global Section Set
	componentsectionset.SectionSetParamterToDeployment(dep, asp)    //DeploymentSpec's Component Section Set
	return dep
}
func ParamterToDaemonSet(ds *appsv1.DaemonSet, asp *alamedaserviceparamter.AlamedaServiceParamter) *appsv1.DaemonSet {
	globalsectionset.GlobalSectionSetParamterToDaemonSet(ds, asp) //DaemonSet's Global Section Set
	componentsectionset.SectionSetParamterToDaemonSet(ds, asp)    //DaemonSet's Component Section Set
	return ds
}
func ParamterToSecurityContextConstraints(scc *securityv1.SecurityContextConstraints, asp *alamedaserviceparamter.AlamedaServiceParamter) *securityv1.SecurityContextConstraints {
	updateenvvar.AssignServiceAccountsToSecurityContextConstraints(scc, asp.NameSpace)
	return scc
}

func ParamterToPersistentVolumeClaim(pvc *corev1.PersistentVolumeClaim, asp *alamedaserviceparamter.AlamedaServiceParamter) *corev1.PersistentVolumeClaim {
	globalsectionset.GlobalSectionSetParamterToPersistentVolumeClaim(pvc, asp)
	componentsectionset.SectionSetParamterToPersistentVolumeClaim(pvc, asp) //PersistentVolumeClaim's Component Section Set
	return pvc
}
func ParamterToStatefulset(ss *appsv1.StatefulSet, asp *alamedaserviceparamter.AlamedaServiceParamter) *appsv1.StatefulSet {
	globalsectionset.GlobalSectionSetParamterToStatefulset(ss, asp)
	componentsectionset.SectionSetParamterToStatefulSet(ss, asp) //StatefulSet's Component Section Set
	return ss
}


text:
@article{Smith_Brown_2018,
author = {Smith, Stephen A. and Brown, Joseph W.},
title = {Constructing a broadly inclusive seed plant phylogeny},
journal = {American Journal of Botany},
volume = {105},
number = {3},
pages = {302-314},
keywords = {clustering, divergence-time estimation, diversification, GenBank, Open Tree of Life, phylogenetics, phylogenetic methods, plant tree of life, seed plants},
doi = {10.1002/ajb2.1019},
url = {https://bsapubs.onlinelibrary.wiley.com/doi/abs/10.1002/ajb2.1019},
eprint = {https://bsapubs.onlinelibrary.wiley.com/doi/pdf/10.1002/ajb2.1019},
abstract = {Premise of the Study Large phylogenies can help shed light on macroevolutionary patterns that inform our understanding of fundamental processes that shape the tree of life. These phylogenies also serve as tools that facilitate other systematic, evolutionary, and ecological analyses. Here we combine genetic data from public repositories (GenBank) with phylogenetic data (Open Tree of Life project) to construct a dated phylogeny for seed plants. Methods We conducted a hierarchical clustering analysis of publicly available molecular data for major clades within the Spermatophyta. We constructed phylogenies of major clades, estimated divergence times, and incorporated data from the Open Tree of Life project, resulting in a seed plant phylogeny. We estimated diversification rates, excluding those taxa without molecular data. We also summarized topological uncertainty and data overlap for each major clade. Key Results The trees constructed for Spermatophyta consisted of 79,881 and 353,185 terminal taxa; the latter included the Open Tree of Life taxa for which we could not include molecular data from GenBank. The diversification analyses demonstrated nested patterns of rate shifts throughout the phylogeny. Data overlap and inference uncertainty show significant variation throughout and demonstrate the continued need for data collection across seed plants. Conclusions This study demonstrates a means for combining available resources to construct a dated phylogeny for plants. However, this approach is an early step and more developments are needed to add data, better incorporating underlying uncertainty, and improve resolution. The methods discussed here can also be applied to other major clades in the tree of life.},
year = {2018},
}

@article{Brown_et_al_2017,
    author = {Brown, Joseph W and Walker, Joseph F and Smith, Stephen A},
    title = "{Phyx: phylogenetic tools for unix}",
    journal = {Bioinformatics},
    volume = {33},
    number = {12},
    pages = {1886-1888},
    year = {2017},
    month = {02},
    abstract = "{The ease with which phylogenomic data can be generated has drastically escalated the computational burden for even routine phylogenetic investigations. To address this, we present phyx: a collection of programs written in C ++ to explore, manipulate, analyze and simulate phylogenetic objects (alignments, trees and MCMC logs). Modelled after Unix/GNU/Linux command line tools, individual programs perform a single task and operate on standard I/O streams that can be piped to quickly and easily form complex analytical pipelines. Because of the stream-centric paradigm, memory requirements are minimized (often only a single tree or sequence in memory at any instance), and hence phyx is capable of efficiently processing very large datasets.phyx runs on POSIX-compliant operating systems. Source code, installation instructions, documentation and example files are freely available under the GNU General Public License at https://github.com/FePhyFoFum/phyxSupplementary data are available at Bioinformatics online.}",
    issn = {1367-4803},
    doi = {10.1093/bioinformatics/btx063},
    url = {https://doi.org/10.1093/bioinformatics/btx063},
    eprint = {http://oup.prod.sis.lan/bioinformatics/article-pdf/33/12/1886/25155575/btx063.pdf},
}

@article{Kembel_et_al_2010,
    author = {Kembel, Steven W. and Cowan, Peter D. and Helmus, Matthew R. and Cornwell, William K. and Morlon, Helene and Ackerly, David D. and Blomberg, Simon P. and Webb, Campbell O.},
    title = "{Picante: R tools for integrating phylogenies and ecology}",
    journal = {Bioinformatics},
    volume = {26},
    number = {11},
    pages = {1463-1464},
    year = {2010},
    month = {04},
    abstract = "{Summary: Picante is a software package that provides a comprehensive set of tools for analyzing the phylogenetic and trait diversity of ecological communities. The package calculates phylogenetic diversity metrics, performs trait comparative analyses, manipulates phenotypic and phylogenetic data, and performs tests for phylogenetic signal in trait distributions, community structure and species interactions.Availability: Picante is a package for the R statistical language and environment written in R and C, released under a GPL v2 open-source license, and freely available on the web (http://picante.r-forge.r-project.org) and from CRAN (http://cran.r-project.org).Contact:skembel@uoregon.edu}",
    issn = {1367-4803},
    doi = {10.1093/bioinformatics/btq166},
    url = {https://doi.org/10.1093/bioinformatics/btq166},
    eprint = {http://oup.prod.sis.lan/bioinformatics/article-pdf/26/11/1463/526145/btq166.pdf},
}

@Article{Jetz2012,
author={Jetz, W.
and Thomas, G. H.
and Joy, J. B.
and Hartmann, K.
and Mooers, A. O.},
title={The global diversity of birds in space and time},
journal={Nature},
year={2012},
month={Oct},
day={31},
publisher={Nature Publishing Group, a division of Macmillan Publishers Limited. All Rights Reserved. SN  -},
volume={491},
pages={444 EP  -},
url={https://doi.org/10.1038/nature11631},
}

@article {Harvey2017,
	author = {Harvey, Michael G. and Seeholzer, Glenn F. and Smith, Brian Tilston and Rabosky, Daniel L. and Cuervo, Andr{\'e}s M. and Brumfield, Robb T.},
	title = {Positive association between population genetic differentiation and speciation rates in New World birds},
	volume = {114},
	number = {24},
	pages = {6328--6333},
	year = {2017},
	doi = {10.1073/pnas.1617397114},
	publisher = {National Academy of Sciences},
	abstract = {The causes of differentiation among populations are well circumscribed, but it remains unclear if they impact the proliferation of organisms over deep time. If, as some recent theory and observations suggest, population differentiation is not a rate-limiting control on species diversification, then the causes of population differentiation are unlikely to have macroevolutionary effects. We provide a large-scale test of the link between standardized estimates of rates of differentiation from population genetic data and speciation rates. Population differentiation rates predict speciation rates across New World birds, confirming the potential macroevolutionary importance of causes of differentiation. We also find that population differentiation and speciation rates are more tightly linked in the Tropics, which may help explain latitudinal differences in diversification dynamics.An implicit assumption of speciation biology is that population differentiation is an important stage of evolutionary diversification, but its significance as a rate-limiting control on phylogenetic speciation dynamics remains largely untested. If population differentiation within a species is related to its speciation rate over evolutionary time, the causes of differentiation could also be driving dynamics of organismal diversity across time and space. Alternatively, geographic variants might be short-lived entities with rates of formation that are unlinked to speciation rates, in which case the causes of differentiation would have only ephemeral impacts. By pairing population genetics datasets from 173 New World bird species (\>17,000 individuals) with phylogenetic estimates of speciation rate, we show that the population differentiation rates within species are positively correlated with their speciation rates over long timescales. Although population differentiation rate explains relatively little of the variation in speciation rate among lineages, the positive relationship between differentiation rate and speciation rate is robust to species-delimitation schemes and to alternative measures of both rates. Population differentiation occurs at least three times faster than speciation, which suggests that most populations are ephemeral. Speciation and population differentiation rates are more tightly linked in tropical species than in temperate species, consistent with a history of more stable diversification dynamics through time in the Tropics. Overall, our results suggest that the processes responsible for population differentiation are tied to those that underlie broad-scale patterns of diversity.},
	issn = {0027-8424},
	URL = {https://www.pnas.org/content/114/24/6328},
	eprint = {https://www.pnas.org/content/114/24/6328.full.pdf},
	journal = {Proceedings of the National Academy of Sciences},
}

@article{clark_loss_2008,
    title = {Loss of plant species after chronic low-level nitrogen deposition to prairie grasslands},
    volume = {451},
    copyright = {© 2008 Nature Publishing Group},
    issn = {0028-0836},
    url = {http://www.nature.com/nature/journal/v451/n7179/full/nature06503.html},
    doi = {10.1038/nature06503},
    abstract = {Rates of atmospheric deposition of biologically active nitrogen (N) are two to seven times the pre-industrial rates in many developed nations because of combustion of fossil fuels and agricultural fertilization. They are expected to increase similarly over the next 50 years in industrializing nations of Asia and South America. Although the environmental impacts of high rates of nitrogen addition have been well studied, this is not so for the lower, chronic rates that characterize much of the globe. Here we present results of the first multi-decadal experiment to examine the impacts of chronic, experimental nitrogen addition as low as 10 kg N ha-1 yr-1 above ambient atmospheric nitrogen deposition (6 kg N ha-1 yr-1 at our site). This total input rate is comparable to terrestrial nitrogen deposition in many industrialized nations. We found that this chronic low-level nitrogen addition rate reduced plant species numbers by 17\% relative to controls receiving ambient N deposition. Moreover, species numbers were reduced more per unit of added nitrogen at lower addition rates, suggesting that chronic but low-level nitrogen deposition may have a greater impact on diversity than previously thought. A second experiment showed that a decade after cessation of nitrogen addition, relative plant species number, although not species abundances, had recovered, demonstrating that some effects of nitrogen addition are reversible.},
    language = {en},
    number = {7179},
    urldate = {2014-05-13},
    journal = {Nature},
    author = {Clark, Christopher M. and Tilman, David},
    year = {2008},
    note = {00275},
    pages = {712--715},
    file = {clark_tilman_2008_nature_loss of plant species after chronic low-level nitrogen deposition to prairie.pdf:/home/dli/.zotero/zotero/ne70mnrx.default/zotero/storage/RXCFN59J/clark_tilman_2008_nature_loss of plant species after chronic low-level nitrogen deposition to prairie.pdf:application/pdf},
}

@article{eriksson_seed_1993,
    title = {Seed and microsite limitation of recruitment in plant populations},
    volume = {92},
    url = {http://dx.doi.org/10.1007/BF00317624},
    abstract = {Availability of seed and microsites, respectively, are two factors that potentially may limit recruitment in plant populations. Microsites are small-scale sites suitable for germination and survival of seedlings. We discuss this dichotomy of recruitment limitation both from a theoretical and empirical point of view. Investigations of recruitment in 14 woodland species showed that 3 species were seed limited, 6 species were limited by a combination of seed and microsite availability, and 5 species were found not to be seed limited, but the limiting factor was not identified. A “combination of seed and microsite limitation” implies that recruitment is promoted by increasing both seed and microsite availability. We suggest that the importance of seed limitation in plant populations has been underestimated, and that the operating limiting factors may be dependent on spatial and temporal scale. We expect that many species, if adequately studied, will turn out to be both seed and microsite limited. Experimental field studies that incorporate a range of seed and microsite “densities” in various spatial and temporal scales are needed to examine the extent to which plant populations are seed and microsite limited.},
    number = {4},
    journal = {Oecologia},
    author = {Eriksson, O and Ehrlén, J},
    year = {1993},
    pages = {361--366},
}

@article{williamson_dissolved_1999,
    title = {Dissolved organic carbon and nutrients as regulators of lake ecosystems: resurrection of a more integrated paradigm},
    volume = {44},
    issn = {0024-3590},
    number = {3},
    journal = {Limnology and Oceanography},
    author = {Williamson, C E and Morris, D P and Pace, M L and Olson, O G},
    year = {1999},
    pages = {795--803},
}

gha_language: TeX


text:
/*
Copyright 2020 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package clustersnapshot

import (
	"errors"

	apiv1 "k8s.io/api/core/v1"
	"k8s.io/klog/v2"
	schedulerframework "k8s.io/kubernetes/pkg/scheduler/framework"
)

// ClusterSnapshot is abstraction of cluster state used for predicate simulations.
// It exposes mutation methods and can be viewed as scheduler's SharedLister.
type ClusterSnapshot interface {
	schedulerframework.SharedLister
	// AddNode adds node to the snapshot.
	AddNode(node *apiv1.Node) error
	// AddNodes adds nodes to the snapshot.
	AddNodes(nodes []*apiv1.Node) error
	// RemoveNode removes nodes (and pods scheduled to it) from the snapshot.
	RemoveNode(nodeName string) error
	// AddPod adds pod to the snapshot and schedules it to given node.
	AddPod(pod *apiv1.Pod, nodeName string) error
	// RemovePod removes pod from the snapshot.
	RemovePod(namespace string, podName string, nodeName string) error
	// AddNodeWithPods adds a node and set of pods to be scheduled to this node to the snapshot.
	AddNodeWithPods(node *apiv1.Node, pods []*apiv1.Pod) error
	// IsPVCUsedByPods returns if the pvc is used by any pod, key = <namespace>/<pvc_name>
	IsPVCUsedByPods(key string) bool

	// Fork creates a fork of snapshot state. All modifications can later be reverted to moment of forking via Revert().
	// Use WithForkedSnapshot() helper function instead if possible.
	Fork()
	// Revert reverts snapshot state to moment of forking.
	Revert()
	// Commit commits changes done after forking.
	Commit() error
	// Clear reset cluster snapshot to empty, unforked state.
	Clear()
}

// ErrNodeNotFound means that a node wasn't found in the snapshot.
var ErrNodeNotFound = errors.New("node not found")

// WithForkedSnapshot is a helper function for snapshot that makes sure all Fork() calls are closed with Commit() or Revert() calls.
// The function return (error, error) pair. The first error comes from the passed function, the second error indicate the success of the function itself.
func WithForkedSnapshot(snapshot ClusterSnapshot, f func() (bool, error)) (error, error) {
	var commit bool
	var err, cleanupErr error
	snapshot.Fork()
	defer func() {
		if commit {
			cleanupErr = snapshot.Commit()
			if cleanupErr != nil {
				klog.Errorf("Got error when calling ClusterSnapshot.Commit(), will try to revert; %v", cleanupErr)
			}
		}
		if !commit || cleanupErr != nil {
			snapshot.Revert()
		}
	}()
	commit, err = f()
	return err, cleanupErr
}

repository: kubernetes/autoscaler

repo_name: kubernetes/autoscaler


text:
LICENSE = "GPL"
SECTION = "unknown"
DEPENDS = "elftoaout-native"

SRC_URI = "http://www.sparc-boot.org/pub/silo/silo-${PV}.tar.bz2 \
	file://cross.patch"

do_compile() {
	oe_runmake CC="${CC} -m32" LD="${LD}" HOSTCC="${BUILD_CC}" HOSTCFLAGS="${BUILD_CFLAGS}" OECFLAGS="${CFLAGS}" OELDFLAGS="-L${STAGING_LIBDIR} -rpath-link ${STAGING_LIBDIR}" NM="${TARGET_SYS}-nm"
}

# Should this package be installing into native? - not good... RP
do_stage() {
	install tilo/maketilo ${STAGING_BINDIR_NATIVE}
	install tilo/tilo.sh ${STAGING_BINDIR_NATIVE}
}

SRC_URI[md5sum] = "badc27616dc92ad42f5e30751a6b322c"
SRC_URI[sha256sum] = "2c5e3a832662aa962f700e64ce3c1fc8c77e801000c47b8d66feeb03e66d95de"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
@article{ObservationGravitationalWaves2016,
  title = {Observation of Gravitational Waves from a  Binary Black Hole Merger},
  author = {{LIGO Scientific Collaboration and Virgo Collaboration} and Abbott, B. P. and et~al},
  year = {2016},
  month = feb,
  journal = {Physical Review Letters},
  volume = {116},
  number = {6},
  pages = {061102},
  publisher = {American Physical Society}
}

@article{LISALaserInterferometer1998,
  title = {{LISA Laser Interferometer Space Antenna} for the Detection and Observation of Gravitational Waves},
  author = {Bender, P. and Brillet, A. and Ciufolini, I. and et~al},
  year = {1998},
  journal = {Max-Planck Institut f\"ur Quantenoptik}
}

@article{SubFemtogFreeFall2016,
  title = {Sub-{{Femto-g Free Fall}} for {{Space-Based Gravitational Wave Observatories}}: {{LISA Pathfinder Results}}},
  author = {Armano, M. and Audley, H. and Auger, G. and et~al},
  year = {2016},
  month = jun,
  journal = {Physical Review Letters},
  volume = {116},
  number = {23},
  pages = {231101}
}

repository: iChunyu/LearnLaTeX

repo_name: iChunyu/LearnLaTeX


text:
/*
 * TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
 * Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://opensource.org/licenses/MIT
 * 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 dao

//go:generate mockgen -source=$GOFILE -destination=./mock/$GOFILE -package=mock

import (
	"database/sql"
	"errors"

	"iam/pkg/database"

	"github.com/jmoiron/sqlx"
)

// Action 操作
type Action struct {
	PK     int64  `db:"pk"`
	System string `db:"system_id"`
	ID     string `db:"id"`
}

// ActionManager ...
type ActionManager interface {
	GetPK(system string, id string) (int64, error)
	Get(pk int64) (Action, error)
	ListByPKs(pks []int64) ([]Action, error)
	ListBySystem(system string) ([]Action, error)

	BulkCreateWithTx(tx *sqlx.Tx, actions []Action) error
	BulkDeleteWithTx(tx *sqlx.Tx, system string, ids []string) error
}

type actionManager struct {
	DB *sqlx.DB
}

// NewActionManager ...
func NewActionManager() ActionManager {
	return &actionManager{
		DB: database.GetDefaultDBClient().DB,
	}
}

// GetPK ...
func (m *actionManager) GetPK(system, id string) (int64, error) {
	var pk int64
	err := m.selectPK(&pk, system, id)
	return pk, err
}

// Get ...
func (m *actionManager) Get(pk int64) (action Action, err error) {
	err = m.selectByPK(&action, pk)
	return
}

// ListByPKs ...
func (m *actionManager) ListByPKs(pks []int64) (actions []Action, err error) {
	if len(pks) == 0 {
		return
	}
	err = m.selectByPKs(&actions, pks)
	if errors.Is(err, sql.ErrNoRows) {
		return actions, nil
	}
	return
}

// ListBySystem ...
func (m *actionManager) ListBySystem(system string) (actions []Action, err error) {
	err = m.selectBySystem(&actions, system)
	if errors.Is(err, sql.ErrNoRows) {
		return actions, nil
	}
	return
}

// BulkCreateWithTx ...
func (m *actionManager) BulkCreateWithTx(tx *sqlx.Tx, actions []Action) error {
	if len(actions) == 0 {
		return nil
	}
	return m.bulkInsertWithTx(tx, actions)
}

// BulkDeleteWithTx ...
func (m *actionManager) BulkDeleteWithTx(tx *sqlx.Tx, system string, ids []string) error {
	if len(ids) == 0 {
		return nil
	}
	return m.bulkDeleteWithTx(tx, system, ids)
}

func (m *actionManager) selectPK(pk *int64, system, id string) error {
	query := `SELECT
		pk
		FROM action
		WHERE system_id = ?
		AND id = ?
		LIMIT 1`
	return database.SqlxGet(m.DB, pk, query, system, id)
}

func (m *actionManager) selectByPK(action *Action, pk int64) error {
	query := `SELECT
		pk,
		system_id,
		id
		FROM action
		WHERE pk = ?`
	return database.SqlxGet(m.DB, action, query, pk)
}

func (m *actionManager) selectByPKs(actions *[]Action, pks []int64) error {
	query := `SELECT
		pk,
		system_id,
		id
		FROM action
		WHERE pk in (?)`
	return database.SqlxSelect(m.DB, actions, query, pks)
}

func (m *actionManager) selectBySystem(actions *[]Action, system string) error {
	query := `SELECT
		pk,
		system_id,
		id
		FROM action
		WHERE system_id=?`
	return database.SqlxSelect(m.DB, actions, query, system)
}

func (m *actionManager) bulkInsertWithTx(tx *sqlx.Tx, actions []Action) error {
	query := `INSERT INTO action (system_id, id) VALUES (:system_id, :id)`
	return database.SqlxBulkInsertWithTx(tx, query, actions)
}

func (m *actionManager) bulkDeleteWithTx(tx *sqlx.Tx, system string, ids []string) error {
	query := `DELETE FROM action WHERE system_id = ? AND id IN (?)`
	return database.SqlxDeleteWithTx(tx, query, system, ids)
}


text:
package golexa

const resolutionSuccessCode = "ER_SUCCESS_MATCH"

// Slots represents a set of runtime values that the Alexa interaction model parsed out for you.
type Slots map[string]Slot

// Slot is one of placeholder for the important data used in an utterance/query. It can be a very
// open-ended bit of text as you'd have in an AMAZON.SearchQuery slot or one of the phrases w/
// synonyms you set up in a custom slot.
type Slot struct {
	Name        string      `json:"name"`
	Value       string      `json:"value"`
	Resolutions resolutions `json:"resolutions"`
}

// Clone creates a copy of all of the slots and their RESOLVED values. Typically you use this when you
// want to include a set of slots in your response w/o modifying the map in the request. Be aware that
// while it preserves the resolved value, you will lose the resolution authority data from the original.
func (s Slots) Clone() Slots {
	slots := Slots{}
	for slotName, slot := range s {
		slots[slotName] = Slot{Name: slot.Name, Value: slot.Resolve()}
	}
	return slots
}

// Resolve locates the specified slot entry and returns its resolved value.
func (s Slots) Resolve(slotName string) string {
	if slot, ok := s[slotName]; ok {
		return slot.Resolve()
	}
	return ""
}

// Resolve takes into account the synonyms and resolutions, returning the mapped value that
// the Alexa API thinks we want. If there was no resolution data, you'll simply get back the
// transcribed text from what the user actually said.
func (slot Slot) Resolve() string {
	// They spoke a synonym for your custom slot or they said something like "this month" and it
	// resolved to the ISO date string.
	if resolvedValue := slot.Resolutions.ResolutionPerAuthority.resolvedValue(); resolvedValue != "" {
		return resolvedValue
	}

	// There was no synonym/mapping for what the user spoke, so use their exact word(s)
	return slot.Value
}

type resolutions struct {
	ResolutionPerAuthority resolutionAuthorities `json:"resolutionsPerAuthority"`
}

type resolutionAuthorities []resolutionPerAuthority

func (resolutions resolutionAuthorities) resolvedValue() string {
	if len(resolutions) == 0 {
		return ""
	}

	resolution := resolutions[0]
	if resolution.Status.Code == resolutionSuccessCode && len(resolution.Values) > 0 {
		return resolution.Values[0].Value.Name
	}
	return ""
}

type resolutionPerAuthority struct {
	Authority string             `json:"authority"`
	Status    resolutionStatus   `json:"status"`
	Values    []resolutionValues `json:"values"`
}

type resolutionStatus struct {
	Code string `json:"code"`
}

type resolutionValues struct {
	Value resolutionValue `json:"value"`
}

type resolutionValue struct {
	Name string `json:"name"`
	ID   string `json:"id"`
}

// NewResolvedSlot is mainly used for faking test data to create a slot that
// has an uttered value as well as a resolution value.
func NewResolvedSlot(name, value, resolvedValue string) Slot {
	return Slot{
		Name:  name,
		Value: value,
		Resolutions: resolutions{
			ResolutionPerAuthority: resolutionAuthorities{
				resolutionPerAuthority{
					Status: resolutionStatus{
						Code: resolutionSuccessCode,
					},
					Values: []resolutionValues{
						{Value: resolutionValue{Name: resolvedValue}},
					},
				},
			},
		},
	}
}

// NewSlot is used primarily for faking data in tests. It creates a simple slot/value with
// no alternate resolution info.
func NewSlot(name, value string) Slot {
	return Slot{
		Name:  name,
		Value: value,
	}
}

// NewSlots creates a Slots map containing entries for all of the individual slot values.
func NewSlots(values ...Slot) Slots {
	slots := Slots{}
	for _, value := range values {
		slots[value.Name] = value
	}
	return slots
}

repository: robsignorelli/golexa

repo_name: robsignorelli/golexa


text:
@PACKAGE_INIT@

include(CMakeFindDependencyMacro)

#### Required dependencies  ####
find_dependency(nlohmann_json 3.2.0 REQUIRED)
find_dependency(Doxygen)

get_filename_component(DFA_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
if (NOT TARGET dfa)
    include("${DFA_CMAKE_DIR}/dfaTargets.cmake")
endif ()

repository: aokellermann/dfa

repo_name: aokellermann/dfa

extension: in


text:
@inproceedings{molamohammadi2020jacobian,
  title={Jacobian of generative models for sensitivity analysis of photovoltaic device processes},
  author={Molamohammadi, Maryam and Rezaei-Shoshtari, Sahand and Quitoriano, N},
  booktitle={Machine Learning for Engineering Workshop at NeurIPS},
  volume={2020},
  year={2020}
}

gha_language: HTML


text:
@article{iacucci2017p275,
 author = {Iacucci, M and Daperno, M and Lazarev, M and Arsenescu, R and Tontini, GE and Lethebe, BC and Lowerison, MW and Gui, X and Villanacci, V and Akinola, O and others},
 journal = {Journal of Crohn's \& colitis},
 number = {suppl\_1},
 pages = {S217--S218},
 title = {P275 Development and reliability of the new endoscopic virtual chromoendoscopy score: the Picasso score (the Paddington International Virtual Chromoendoscopy Score) in ulcerative colitis.},
 volume = {11},
 year = {2017}
}


text:
// Copyright (c) 2015 Vivaldi Technologies AS. All rights reserved

#ifndef EXTENSIONS_API_AUTO_UPDATE_AUTO_UPDATE_API_H_
#define EXTENSIONS_API_AUTO_UPDATE_AUTO_UPDATE_API_H_

#include <memory>

#include "base/version.h"
#include "build/build_config.h"
#include "extensions/browser/extension_function.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

#include "extensions/api/auto_update/auto_update_status.h"
#include "vivaldi/extensions/schema/autoupdate.h"

namespace extensions {

class AutoUpdateAPI {
 public:
  static void Init() {
#if BUILDFLAG(IS_WIN)
    InitUpgradeDetection();
#endif
  }

  static void Shutdown() {
#if BUILDFLAG(IS_WIN)
    ShutdownUpgradeDetection();
#endif
  }

  static void SendDidFindValidUpdate(const std::string& url,
                                     const base::Version& version);
  static void SendUpdaterDidNotFindUpdate();
  static void SendWillDownloadUpdate(const base::Version& version);
  static void SendDidDownloadUpdate(const base::Version& version);
  static void SendWillInstallUpdateOnQuit(const base::Version& version);
  static void SendUpdaterWillRelaunchApplication();
  static void SendUpdaterDidRelaunchApplication();
  static void SendDidAbortWithError(const std::string& error,
                                    const std::string& reason);

 private:
#if BUILDFLAG(IS_WIN)
  static void InitUpgradeDetection();
  static void ShutdownUpgradeDetection();
#endif
};

class AutoUpdateCheckForUpdatesFunction : public ExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("autoUpdate.checkForUpdates",
                             AUTOUPDATE_CHECKFORUPDATES)
  AutoUpdateCheckForUpdatesFunction() = default;

 private:
  ~AutoUpdateCheckForUpdatesFunction() override = default;
  void DeliverResult();

  ResponseAction Run() override;
};

class AutoUpdateIsUpdateNotifierEnabledFunction : public ExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("autoUpdate.isUpdateNotifierEnabled",
                             AUTOUPDATE_ISUPDATENOTIFIERENABLED)
  AutoUpdateIsUpdateNotifierEnabledFunction() = default;

 private:
  ~AutoUpdateIsUpdateNotifierEnabledFunction() override = default;
  void DeliverResult(bool enabled);

  ResponseAction Run() override;
};

class AutoUpdateEnableUpdateNotifierFunction : public ExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("autoUpdate.enableUpdateNotifier",
                             AUTOUPDATE_ENABLEUPDATENOTIFIER)
  AutoUpdateEnableUpdateNotifierFunction() = default;

 private:
  ~AutoUpdateEnableUpdateNotifierFunction() override = default;
  void DeliverResult(bool success);

  ResponseAction Run() override;
};

class AutoUpdateDisableUpdateNotifierFunction : public ExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("autoUpdate.disableUpdateNotifier",
                             AUTOUPDATE_DISABLEUPDATENOTIFIER)
  AutoUpdateDisableUpdateNotifierFunction() = default;

 private:
  ~AutoUpdateDisableUpdateNotifierFunction() override = default;
  void DeliverResult(bool success);

  ResponseAction Run() override;
};

class AutoUpdateInstallUpdateAndRestartFunction : public ExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("autoUpdate.installUpdateAndRestart",
                             AUTOUPDATE_INSTALLUPDATEANDRESTART)
  AutoUpdateInstallUpdateAndRestartFunction() = default;

 private:
  ~AutoUpdateInstallUpdateAndRestartFunction() override = default;
  ResponseAction Run() override;
};

class AutoUpdateGetAutoInstallUpdatesFunction : public ExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("autoUpdate.getAutoInstallUpdates",
                             AUTOUPDATE_GETAUTOINSTALLUPDATES)
  AutoUpdateGetAutoInstallUpdatesFunction() = default;

 private:
  ~AutoUpdateGetAutoInstallUpdatesFunction() override = default;
  ResponseAction Run() override;
};

class AutoUpdateSetAutoInstallUpdatesFunction : public ExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("autoUpdate.setAutoInstallUpdates",
                             AUTOUPDATE_SETAUTOINSTALLUPDATES)
  AutoUpdateSetAutoInstallUpdatesFunction() = default;

 private:
  ~AutoUpdateSetAutoInstallUpdatesFunction() override = default;
  ResponseAction Run() override;
};

class AutoUpdateGetLastCheckTimeFunction : public ExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("autoUpdate.getLastCheckTime",
                             AUTOUPDATE_GETLASTCHECKTIME)
  AutoUpdateGetLastCheckTimeFunction() = default;

 private:
  ~AutoUpdateGetLastCheckTimeFunction() override = default;
  ResponseAction Run() override;
};

class AutoUpdateGetUpdateStatusFunction : public ExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("autoUpdate.getUpdateStatus",
                             AUTOUPDATE_GETUPDATESTATUS)

  AutoUpdateGetUpdateStatusFunction() = default;

  // Wrap the status for delivery to JS. Use nullopt for status on errors.
  void SendResult(absl::optional<AutoUpdateStatus> status,
                  std::string version,
                  std::string release_notes_url);

 private:
  ~AutoUpdateGetUpdateStatusFunction() override = default;
  ResponseAction Run() override;
};

class AutoUpdateHasAutoUpdatesFunction : public ExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("autoUpdate.hasAutoUpdates",
                             AUTOUPDATE_HASAUTOUPDATES)
  AutoUpdateHasAutoUpdatesFunction() = default;

 private:
  ~AutoUpdateHasAutoUpdatesFunction() override = default;
  ResponseAction Run() override;

  bool HasAutoUpdates();
};

}  // namespace extensions
#endif  // EXTENSIONS_API_AUTO_UPDATE_AUTO_UPDATE_API_H_

extension: h


text:
add_library(Qt5::QGeoPositionInfoSourceFactoryGeoclue MODULE IMPORTED)

_populate_Positioning_plugin_properties(QGeoPositionInfoSourceFactoryGeoclue RELEASE "position/qtposition_geoclue.dll")
_populate_Positioning_plugin_properties(QGeoPositionInfoSourceFactoryGeoclue DEBUG "position/qtposition_geoclued.dll")

list(APPEND Qt5Positioning_PLUGINS Qt5::QGeoPositionInfoSourceFactoryGeoclue)

repository: timi-liuliang/echo

repo_name: timi-liuliang/echo


text:
@article{RN1093,
 author = {Heriot, G. S. and Tong, S. Y. C. and Cheng, A. C. and Liew, D.},
 doi = {10.1093/ofid/ofy303},
 issn = {2328-8957 (Print)
2328-8957 (Linking)},
 journal = {Open Forum Infect Dis},
 number = {12},
 pages = {ofy303},
 title = {Benefit of Echocardiography in Patients With Staphylococcus aureus Bacteremia at Low Risk of Endocarditis},
 type = {Journal Article},
 url = {https://www.ncbi.nlm.nih.gov/pubmed/30555848},
 volume = {5},
 year = {2018}
}


text:
require optee-client-fio.inc

SRCREV = "dd2d39b49975d2ada7870fe2b7f5a84d0d3860dc"

SRC_URI += " \
	file://0001-FIO-extras-pkcs11-change-UUID-to-avoid-conflict-with.patch \
"

repository: foundriesio/meta-lmp

repo_name: foundriesio/meta-lmp

gha_language: BitBake


text:
require python-efl.inc
SRCREV = "${EFL_SRCREV}"
DEPENDS += "python-evas ecore"
RDEPENDS_${PN} += "python-evas"


text:
package agent

import (
	"fmt"
	"time"

	"github.com/cilium/cilium/pkg/k8s/client/clientset/versioned"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v14/internal/module/cilium_alert"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v14/internal/module/modagent"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v14/internal/tool/retry"
)

const (
	getFlowsPollInterval = 10 * time.Second
	informerResyncPeriod = 30 * time.Minute

	pollingInitBackoff   = 10 * time.Second
	pollingMaxBackoff    = 5 * time.Minute
	pollingResetDuration = 10 * time.Minute
	pollingBackoffFactor = 2.0
	pollingJitter        = 1.0
)

type Factory struct {
}

func (f *Factory) New(cfg *modagent.Config) (modagent.Module, error) {
	restConfig, err := cfg.K8sUtilFactory.ToRESTConfig()
	if err != nil {
		return nil, err
	}
	ciliumClient, err := versioned.NewForConfig(restConfig)
	if err != nil {
		return nil, fmt.Errorf("client set for Cilium: %w", err)
	}
	return &module{
		log:          cfg.Log,
		api:          cfg.Api,
		ciliumClient: ciliumClient,
		pollConfig: retry.NewPollConfigFactory(getFlowsPollInterval, retry.NewExponentialBackoffFactory(
			pollingInitBackoff,
			pollingMaxBackoff,
			pollingResetDuration,
			pollingBackoffFactor,
			pollingJitter,
		)),
		informerResyncPeriod: informerResyncPeriod,
	}, nil
}

func (f *Factory) Name() string {
	return cilium_alert.ModuleName
}


text:
package cmd

import (
	"github.com/bvinc/go-sqlite-lite/sqlite3"
	"net/url"
	"time"
	"github.com/aws/aws-sdk-go/aws"
	"log"
	"bufio"
	"os"
	"github.com/json-iterator/go"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)

//ParseAWSCloudWatchLogEvent - Input from os.stdin as a json string with the format describe in aws cloudwatch logevent. It is the output of command such as aws logs get-log-events --log-group-name /aws/ecs/int --log-stream-name errcd-wa-int/errcd-wa-task/1bd0169e-2013-4964-96fa-8c18819ffa62 --profile errcd_wa --region ap-southeast-2
//We parse it and ship it to out log server.
func ParseAWSCloudWatchLogEvent(appNameStr string) {
	reader := bufio.NewReader(os.Stdin)
	//1048576 Maxium aws cloudwatch event size
	buff := make([]byte, 1048576)
	reader.Read(buff)

	awsLog := cloudwatchlogs.FilterLogEventsOutput{}

	var json = jsoniter.ConfigCompatibleWithStandardLibrary
	if e := json.Unmarshal(buff, &awsLog); e != nil {
		log.Fatalf("ERROR parsing awslog event data - %v\n", e)
	}
	SendAWSLogEvents(awsLog.Events, appNameStr, 0, nil)
}

func StartAllAWSCloudwatchLogPolling(c chan os.Signal) {
	for _, cfg := range(Config.AWSLogs) {
		log.Printf("Start parsing aws log config %v\n", cfg)
		go StartAWSCloudwatchLogPolling(&cfg)
		time.Sleep(5 * time.Second)
	}
	s := <-c
	log.Printf("StartAllAWSCloudwatchLogPolling - Signal captured. Do cleaning up\n")
	c<- s
}

//StartAWSCloudwatchLogOnePrefix -
func StartAWSCloudwatchLogOnePrefix(logGroupName string, cl *cloudwatchlogs.CloudWatchLogs, filterEvtInput cloudwatchlogs.FilterLogEventsInput, sleepDuration time.Duration) {
	var lastEndTime int64

	var conn *sqlite3.Conn

	u, err := url.Parse(Config.Serverurl)
	if err != nil {
		log.Fatal(err)
	}

	if u.Hostname() == Config.Serverdomain {
		conn = GetDBConn()
		defer conn.Close()
	}

	for {
		if lastEndTime > 0 {
			filterEvtInput.SetStartTime(lastEndTime)
			now := time.Now().UnixNano() / NanosPerMillisecond
			filterEvtInput.SetEndTime(now)
		} else {
			nowT := time.Now()
			now := nowT.UnixNano() / NanosPerMillisecond
			filterEvtInput.SetEndTime(now)
			startT := nowT.Add(-1 * sleepDuration)
			start := startT.UnixNano() / NanosPerMillisecond
			filterEvtInput.SetStartTime(start)
		}
		out, e := cl.FilterLogEvents(&filterEvtInput)
		if e != nil {
			log.Printf("ERROR can not FilterLogEvent. Maybe api throttling. Sleep 15 minutes - %v\n", e)
			time.Sleep(15 * time.Minute)
		}
		events := out.Events
		evtCounts := len(events)
		log.Printf("%s - %s - Events count: %d\n", logGroupName, *filterEvtInput.LogStreamNamePrefix, evtCounts)
		if evtCounts > 0 {
			lastEndTime = SendAWSLogEvents(events, logGroupName, lastEndTime, conn)
		}
		log.Printf("Sleep %v\n", sleepDuration)
		time.Sleep(sleepDuration)
	}
}

//StartAWSCloudwatchLogPolling -
func StartAWSCloudwatchLogPolling(cfg *AWSLogConfig) {
	region := cfg.Region
	if region == "" { region = "ap-southeast-2" }
	ses, e := session.NewSessionWithOptions(session.Options{
		Profile: cfg.Profile,
		// Provide SDK Config options, such as Region.
		Config: aws.Config {
			Region: &region,
			// Credentials: cred,
		},
	})
	if e != nil {
		log.Fatalf("ERROR can not create session - %v\n", e)
	}

	start, end := ParseTimeRange(cfg.Period, CurrentZone)
	startInMs := start.UnixNano() / NanosPerMillisecond
	endInMs := end.UnixNano() / NanosPerMillisecond

	sleepDuration := end.Sub(start)
	logGroupName := cfg.LoggroupName

	for _, streamPrefix := range(cfg.StreamPrefix) {
		clog := cloudwatchlogs.New(ses)
		filterEvtInput := cloudwatchlogs.FilterLogEventsInput{
			StartTime: &startInMs,
			EndTime: &endInMs,
			LogGroupName: &logGroupName,
			LogStreamNamePrefix: &streamPrefix,
			FilterPattern: &cfg.FilterPtn,
		}
		log.Printf("Launch filterlog process for loggroup %s - prefix %s\n",logGroupName, streamPrefix)
		go StartAWSCloudwatchLogOnePrefix(logGroupName, clog, filterEvtInput, sleepDuration)
		time.Sleep(5 * time.Second) //Prevent aws throttle us
	}
}


text:
@article{handcock2022,
  author={Duncan A. Clark and Mark S. Handcock},
  title={{Comparing the real‐world performance of exponential‐family random graph models and latent order logistic models for social network analysis}},
  journal={Journal of the Royal Statistical Society Series A},
  year=2022,
  volume={185},
  number={2},
  pages={566-587},
  month={April},
  keywords={},
  doi={10.1111/rssa.12788},
  abstract={Exponential‐family random graph models (ERGMs) are widely used in social network analysis when modelling data on the relations between actors. ERGMs are typically interpreted as a snapshot of a network at a given point in time or in a final state. The recently proposed Latent Order Logistic model (LOLOG) directly allows for a latent network formation process. We assess the real‐world performance of these models when applied to typical networks modelled by researchers. Specifically, we model data from an ensemble of articles in the journal Social Networks with published ERGM fits, and compare the ERGM fit to a comparable LOLOG fit. We demonstrate that the LOLOG models are, in general, in qualitative agreement with the ERGM models, and provide at least as good a model fit. In addition, they are typically faster and easier to fit to data, without the tendency for degeneracy that plagues ERGMs. Our results support the general use of LOLOG models in circumstances where ERGMs are considered.},
  url={https://ideas.repec.org/a/bla/jorssa/v185y2022i2p566-587.html}
}

@article{macinko2022,
author = {Clark, Duncan A. and Macinko, James and Porfiri, Maurizio},
year = {2022},
month = {06},
pages = {115103},
title = {What factors drive state firearm law adoption? An application of exponential-family random graph models},
volume = {305},
journal = {Social Science & Medicine},
doi = {10.1016/j.socscimed.2022.115103}
}

"The diffusion of punitive firearm preemption laws across US states," has been accepted for publication in a forthcoming issue of the American Journal of Preventive Medicine.

@article{macinko_punitive,
author = {Macinko, James and Pomeranz, Jennifer L. and Clark, Duncan A. and Porfiri, Maurizio},
title = {The diffusion of punitive firearm preemption laws across US states},
journal = {American Journal of Preventive Medicine},
year = {2023}
}

@misc{handcock2023,
  doi = {10.48550/ARXIV.2106.14145},

  url = {https://arxiv.org/abs/2106.14145},

  author = {Clark, Duncan A. and Handcock, Mark S.},

  keywords = {Methodology (stat.ME), Applications (stat.AP), FOS: Computer and information sciences, FOS: Computer and information sciences},

  title = {An Approach to Causal Inference over Stochastic Networks},

  publisher = {arXiv},

  year = {2021},

  copyright = {Creative Commons Attribution 4.0 International}
}

@misc{handcock_BLOLOG,
  author = {Clark, Duncan A. and Handcock, Mark S.},
  title = {Bayesian Inference for Latent Order Logistic Network Models},
  year = {2022}
}

@misc{macinko_STERGM,
  author = {Clark, Duncan A. and Macinko, James and Porfiri, Maurizio},
  title = {A framework for credible prediction of state firearm legislative activity with dynamic network models},
  year = {2022}
}

gha_license_id: NOASSERTION


text:
DESCRIPTION = "The URDF (U-Robot Description Format) headers provides core \
data structure headers for URDF."
SECTION = "devel"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://LICENSE;md5=b441202ba2d6b14d62026cb18bb960ed"

ROS_BPN = "urdfdom_headers"

SRC_URI = "https://salsa.debian.org/science-team/urdfdom-headers/-/archive/debian/${PV}/urdfdom-headers-debian-${PV}.tar.gz"

SRC_URI[md5sum] = "9101c3c3e942e262a6a95094813a22c1"
SRC_URI[sha256sum] = "2837029360405719fc16d0b156ce3972074b34977d7dc407fa94260410abe801"
S = "${WORKDIR}/urdfdom-headers-debian-${PV}"

# Taken from https://salsa.debian.org/science-team/urdfdom-headers/blob/debian/1.0.0-1/debian/control:
DEPENDS = " \
    cmake \
"

# This component puts its cmake files under libdir instead of datadir.
FILES_${PN}-dev_prepend = " \
    ${libdir}/${ROS_BPN}/cmake \
"

ALLOW_EMPTY_${PN} = "1"

inherit cmake
# This recipe is generated for ROS 2 distros.
inherit ros_recipe_now_generated

repository: jianchangfeng/meta-ros

repo_name: jianchangfeng/meta-ros


text:
SECTION = "devel/chicken"
DESCRIPTION = "SRFI-34: Exception Handling for Programs"
LICENSE = "SRFI"
LIC_FILES_CHKSUM = "file://srfi-34.meta;md5=2cb268728a87a863a14d6a5ea3fc1536"

SRC_URI = "http://code.call-cc.org/egg-tarballs/4/srfi-34/srfi-34-${PV}.tar.gz"

SRC_URI[md5sum] = "c85c64612d032e18147b80f358d13b5c"
SRC_URI[sha256sum] = "83eadab98549e85cdda507be6d820b0a1d9956b268896f99b05fa90d079e701e"

S = "${WORKDIR}/srfi-34-${PV}"

inherit chicken_install

BBCLASSEXTEND = "cross crosssdk nativesdk"

repository: OSSystems/meta-chicken

repo_name: OSSystems/meta-chicken


text:
#======================================#
#           SUMMARY/LICENCE            #
#--------------------------------------#
LICENSE = "GPL-2.0+ & LGPL-2.1+"
LICENSE_libkmod = "LGPL-2.1+"
LIC_FILES_CHKSUM = "file://COPYING;md5=a6f89e2100d9b6cdffcea4f398e37343         \
                    file://libkmod/COPYING;md5=a6f89e2100d9b6cdffcea4f398e37343 \
                    "

#======================================#
#           REQUIRE/INHERIT            #
#--------------------------------------#
inherit autotools pkgconfig split-completion

#======================================#
#                SOURCE                #
#--------------------------------------#
SRC_URI = "${KERNELORG_MIRROR}/linux/utils/kernel/kmod/kmod-${PV}.tar.xz;name=source"

SRC_URI[source.md5sum] = "08297dfb6f2b3f625f928ca3278528af"
SRC_URI[source.sha256sum] = "610b8d1df172acc39a4fdf1eaa47a57b04873c82f32152e7a62e29b6ff9cb397"

#======================================#
#           DEPENDS/PROVIDES           #
#--------------------------------------#

#======================================#
#         BUILD CONFIGURATIONS         #
#--------------------------------------#
PACKAGECONFIG = " zlib xz "

PACKAGECONFIG[zlib]    = "--with-zlib, --without-zlib, zlib"
PACKAGECONFIG[xz]      = "--with-xz, --without-xz, xz"
PACKAGECONFIG[debug]   = "--enable-debug, --disable-debug"
PACKAGECONFIG[logging] = "--enable-logging, --disable-logging"

EXTRA_AUTORECONF_append = " --force --install --symlink "
EXTRA_OECONF_append     = " --enable-tools --disable-python --disable-manpages "

# The bash path maybe too long which could lead to build errors.
# Use this to limit the length.
CACHED_CONFIGUREVARS_append = " ac_cv_path_DOLT_BASH='/usr/bin/env bash' "

#======================================#
#                TASKS                 #
#--------------------------------------#
do_configure_prepend() {
    touch ${S}/libkmod/docs/gtk-doc.make
}

do_configure_append() {
    sed -i 's#}libtool#}${TARGET_SYS}-libtool#' ${B}/doltlibtool
}

do_install_append() {
    for tool in lsmod insmod rmmod depmod modinfo modprobe; do
        ln -sr ${D}${bindir}/kmod ${D}${bindir}/${tool}
    done
}

#======================================#
#            PACKAGES/FILES            #
#--------------------------------------#
PACKAGES_prepend = " libkmod "

FILES_libkmod = " ${libdir}/libkmod*${SOLIBS} ${libdir}/libkmod*${SOLIBS} "

#======================================#
#            INSTALL SCRIPT            #
#--------------------------------------#

#======================================#
#             ALTERNATIVES             #
#--------------------------------------#

#======================================#
#           USERADD/SYSTEMD            #
#--------------------------------------#

#======================================#
#                 TEST                 #
#--------------------------------------#


text:
// Copyright © 2018 Jack Zampolin <jack@blockstack.com>
//
// 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 addrindex

import (
	"encoding/json"
	"fmt"

	"github.com/btcsuite/btcd/rpcclient"
)

// AddrServer is the struct where all methods are defined
type AddrServer struct {
	Host         string
	User         string
	Pass         string
	DisableTLS   bool
	Port         int
	Client       *rpcclient.Client
	Transactions int

	versionData versionData
}

func (as *AddrServer) version() []byte {
	out, _ := json.Marshal(as.versionData)
	return out
}

type versionData struct {
	Version string `json:"version"`
	Commit  string `json:"commit"`
	Branch  string `json:"branch"`
}

// AddrServerConfig configures the AddrServer
type AddrServerConfig struct {
	Host         string `json:"host"`
	Usr          string `json:"usr"`
	Pass         string `json:"pass"`
	SSL          bool   `json:"ssl"`
	Port         int    `json:"port"`
	Transactions int    `json:"transactions"`
	Version      string
	Commit       string
	Branch       string
}

// NewAddrServer returns a new AddrServer instance
func NewAddrServer(cfg *AddrServerConfig) *AddrServer {
	out := &AddrServer{
		Host:         cfg.Host,
		User:         cfg.Usr,
		Pass:         cfg.Pass,
		DisableTLS:   !cfg.SSL,
		Port:         cfg.Port,
		Transactions: cfg.Transactions,
		versionData: versionData{
			Version: cfg.Version,
			Commit:  cfg.Commit,
			Branch:  cfg.Branch,
		},
	}
	client, err := rpcclient.New(out.connCfg(), nil)
	if err != nil {
		panic(err)
	}
	out.Client = client
	return out
}

// URL returns the backend server's URL
func (as *AddrServer) URL() string {
	if as.DisableTLS {
		return fmt.Sprintf("http://%s:%s@%v", as.User, as.Pass, as.Host)
	}
	return fmt.Sprintf("https://%s:%s@%v", as.User, as.Pass, as.Host)
}

func (as *AddrServer) connCfg() *rpcclient.ConnConfig {
	return &rpcclient.ConnConfig{
		Host:         as.Host,
		User:         as.User,
		Pass:         as.Pass,
		HTTPPostMode: true,
		DisableTLS:   as.DisableTLS,
	}
}

// fetchAllTransactions pages through the transactions for an address
// NOTE: This can take a long time!
func (as *AddrServer) fetchAllTransactions(addr string) (Transactions, error) {
	txns := []Transaction{}
	count := 0
	for {
		// Fetch page of transactions
		searchtxns, err := as.SearchRawTransactions(addr, (count * as.Transactions), as.Transactions)
		if err != nil {
			return nil, err
		}

		// Increment page count
		count++

		// If the page is full we need to append them and continue to next page
		if len(searchtxns.Result) == as.Transactions {
			for _, tx := range searchtxns.Result {
				txns = append(txns, tx)
			}
			continue
		}

		// If not we need to save the tansactions and return
		for _, tx := range searchtxns.Result {
			txns = append(txns, tx)
		}

		return txns, nil
	}
}

repository: johnthillaye/addrindex-server

repo_name: johnthillaye/addrindex-server


text:
package utils

import (
	"archive/zip"
	"io/ioutil"
	"os"
)

// CreateZipFileContent Zipファイルの中身を設定する
func CreateZipFileContent(writer *zip.Writer, zipPath string, targetFilePath string) error {
	// zip化対象のファイルを設定
	f, err := os.Open(targetFilePath)
	if err != nil {
		return err
	}
	defer f.Close()

	info, err := os.Stat(targetFilePath)
	if err != nil {
		return err
	}

	// zipファイル内のディレクトリ構造を設定
	header, _ := zip.FileInfoHeader(info)
	header.Name = zipPath
	if !info.IsDir() {
		header.Method = zip.Deflate
	}

	zf, err := writer.CreateHeader(header)
	if err != nil {
		return err
	}
	if info.IsDir() {
		return nil
	}

	body, err := ioutil.ReadAll(f)
	if err != nil {
		return err
	}
	if _, err := zf.Write(body); err != nil {
		return err
	}
	return nil
}

repository: silverlovesl/xy-go-common

repo_name: silverlovesl/xy-go-common


text:
package main

import "github.com/joseluisq/compactor"

func main() {
	compactor.CreateTarballWithChecksum(
		"./pkg/archive/",
		"fixtures",
		"./.tmp/pkg.tar.gz",
		"sha256",
		"./.tmp/pkg.CHECKSUM.tar.txt",
	)

	compactor.CreateZipballWithChecksum(
		"./pkg/archive/",
		"fixtures/file.txt",
		"./.tmp/pkg.zip",
		"sha256",
		"./.tmp/pkg.CHECKSUM.zip.txt",
	)
}

repository: joseluisq/compactor

repo_name: joseluisq/compactor


text:
package imdb_test

import (
	"reflect"
	"strings"
	"testing"

	"github.com/benbjohnson/cine/imdb"
)

// Ensure the header of a IMDB file can be retrieved.
func TestReader_Header(t *testing.T) {
	data := `` +
		`foo bar` + "\n" +
		`-------` + "\n" +
		`` + "\n" +
		`TITLE` + "\n" +
		`=====` + "\n" +
		`` + "\n" +
		`this is not the header` + "\n"

	// Read the first row of data.
	r := imdb.NewReader(strings.NewReader(data))
	header, err := r.Header()
	if err != nil {
		t.Fatal(err)
	} else if header != "foo bar\n-------\n\nTITLE\n" {
		t.Fatalf("unexpected header: %s", header)
	}
}

func TestReader_Read(t *testing.T) {
	// Mock data with weird header.
	data := `CRC: 0x475E5845  File: movies.list  Date: Fri Apr 24 00:00:00 2015` + "\n" +
		`-----------------------------------------------------------------------------` + "\n" +
		`` + "\n" +
		`MOVIES LIST` + "\n" +
		`===========` + "\n" +
		`` + "\n" +
		`"!Next?" (1994)						1994-1995` + "\n"

	// Read the first row of data.
	r := imdb.NewReader(strings.NewReader(data))
	row, err := r.Read()
	if err != nil {
		t.Fatal(err)
	} else if !reflect.DeepEqual(row, []string{`"!Next?" (1994)`, `1994-1995`}) {
		t.Fatalf("unexpected row: %#v", row)
	}
}

repository: benbjohnson/cine

repo_name: benbjohnson/cine