text:
@TechReport{OSGi,
  author = 	 {OSGiAlliance},
  title = 	 {OSGi Service Platform Specification},
  year = 	 {2012},
  note = 	 {\url{http://www.osgi.org/Download/File?url=/download/r5/osgi.core-5.0.0.pdf}}
}

@TechReport{Queue,
  author = 	 {Peter Kriens},
  title = 	 {How OSGi Changed My Life},
  year = 	 {2008},
  note = 	 {\url{http://queue.acm.org/detail.cfm?id=1348594}}
}

@BOOK{RalfEbert,
   year = {2004},
   author	=	{Ralf Ebert},
   title	=	{Eclipse RCP - Entwicklung von Desktop-Anwendungen mit der Eclipse Rich Client},
   note 	= 	{\url{http://www.ralfebert.de/archive/eclipse_rcp/EclipseRCP.pdf}}
}

@book{BertholdDaum,
author = {Berthold Daum},
title = {Rich-Client-Entwicklung mit Eclipse 3.3. - Anwendungen, Plugins und Rich Clients},
year = {2007}
publisher = {Dpunkt.Verlag GmbH, 2004}
}

@book{SWT,
author = {Steve Northover, Mike Wilson},
title = {SWT: The Standard Widget Toolkit, Volume 1},
year = {2004},
publisher = {Addison-Wesley Professional}
}

@book{rcp_unternehmenseinsatz,
author = {Stefan Reichert},
title = {Eclipse RCP im Unternehmenseinsatz: Verteilte Anwendungen entwerfen, entwickeln, testen und betreiben},
year = {2009},
publisher = {dpunkt Verlag; Auflage: 1}
}

@book{maven_popp,
author = {Günther Popp},
title = {Konfigurationsmanagement mit Subversion, Maven und Redmine: Grundlagen für Softwarearchitekten und Entwickler},
year = {2013},
publisher = {dpunkt.verlag GmbH; Auflage: 4}
}

@periodical{eclipse_magazin,
title = {Eclipse Magazin 3.10},
date = {03.2010},
OPTurl = {ftp://ftp.herasaf.org/EclipseMagazin/ECM%203.10_Forster_Sylejmani_Eggenschwiler_Maven.pdf},
year = {2010}
}

repository: maxemmert/PraxisArbeit

repo_name: maxemmert/PraxisArbeit


text:
package registry

import (
	"fmt"
	"sync"
	"testing"
	"time"

	"github.com/Bilibili/discovery/errors"
	"github.com/Bilibili/discovery/model"

	. "github.com/smartystreets/goconvey/convey"
)

var reg = &model.ArgRegister{AppID: "main.arch.test", Hostname: "reg", Color: "red", Zone: "sh0001", Env: "pre", Status: 1}
var regH1 = &model.ArgRegister{AppID: "main.arch.test", Hostname: "regH1", Color: "red", Zone: "sh0001", Env: "pre", Status: 1}

var reg2 = &model.ArgRegister{AppID: "main.arch.test2", Hostname: "reg2", Color: "red", Zone: "sh0001", Env: "pre", Status: 1}

var arg = &model.ArgRenew{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Hostname: "reg"}
var cancel = &model.ArgCancel{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Hostname: "reg"}
var cancel2 = &model.ArgCancel{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Hostname: "regH1"}

func TestReigster(t *testing.T) {
	i := model.NewInstance(reg)
	register(t, i)
}

func TestDiscovery(t *testing.T) {
	i1 := model.NewInstance(reg)
	i2 := model.NewInstance(regH1)
	r := register(t, i1, i2)
	Convey("test discovery", t, func() {
		pollArg := &model.ArgPolls{Zone: "sh0001", Env: "pre", AppID: []string{"main.arch.test"}, Hostname: "test"}
		fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 3}
		info, err := r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status)
		So(err, ShouldBeNil)
		So(len(info.Instances["sh0001"]), ShouldEqual, 2)
		ch, _, err := r.Polls(pollArg)
		So(err, ShouldBeNil)
		apps := <-ch
		So(len(apps["main.arch.test"].Instances["sh0001"]), ShouldEqual, 2)
		pollArg.LatestTimestamp[0] = apps["main.arch.test"].LatestTimestamp
		fmt.Println(apps["main.arch.test"])
		r.Cancel(cancel)
		ch, _, err = r.Polls(pollArg)
		So(err, ShouldBeNil)
		apps = <-ch
		So(len(apps["main.arch.test"].Instances), ShouldEqual, 1)
		pollArg.LatestTimestamp[0] = apps["main.arch.test"].LatestTimestamp
		r.Cancel(cancel2)
	})
}

func TestRenew(t *testing.T) {
	src := model.NewInstance(reg)
	r := register(t, src)
	Convey("test renew", t, func() {
		i, ok := r.Renew(arg)
		So(ok, ShouldBeTrue)
		So(i, ShouldResemble, src)
	})
}

func BenchmarkRenew(b *testing.B) {
	var (
		i  *model.Instance
		ok bool
	)
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			r, src := benchRegister(b)
			if i, ok = r.Renew(arg); !ok {
				b.Errorf("Renew(%v)", src.AppID)
			}
			benchCompareInstance(b, src, i)
		}
	})
}

func TestCancel(t *testing.T) {
	src := model.NewInstance(reg)
	r := register(t, src)
	Convey("test cancel", t, func() {
		i, ok := r.Cancel(cancel)
		So(ok, ShouldBeTrue)
		So(i, ShouldResemble, src)
		fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 3}
		_, err := r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status)
		So(err, ShouldResemble, errors.NothingFound)
	})
}

func BenchmarkCancel(b *testing.B) {
	var (
		i   *model.Instance
		ok  bool
		err error
	)
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			r, src := benchRegister(b)
			if i, ok = r.Cancel(cancel); !ok {
				b.Errorf("Cancel(%v) error", src.AppID)
			}
			benchCompareInstance(b, src, i)
			fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 3}
			if _, err = r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status); err != errors.NothingFound {
				b.Errorf("Fetch(%v) error(%v)", src.AppID, err)
			}
		}
	})
}

func TestFetchAll(t *testing.T) {
	i := model.NewInstance(reg)
	r := register(t, i)
	Convey("test fetch all", t, func() {
		am := r.FetchAll()
		So(len(am), ShouldResemble, 1)
	})
}

func BenchmarkFetchAll(b *testing.B) {
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			r, _ := benchRegister(b)
			if am := r.FetchAll(); len(am) != 1 {
				b.Errorf("FetchAll() error")
			}
		}
	})
}

func TestFetch(t *testing.T) {
	i := model.NewInstance(reg)
	r := register(t, i)
	Convey("test fetch", t, func() {
		fetchArg2 := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 1}
		c, err := r.Fetch(fetchArg2.Zone, fetchArg2.Env, fetchArg2.AppID, 0, fetchArg2.Status)
		So(err, ShouldBeNil)
		So(len(c.Instances), ShouldResemble, 1)
	})
}

func BenchmarkFetch(b *testing.B) {
	var (
		err error
		c   *model.InstanceInfo
	)
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			r, _ := benchRegister(b)
			fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 1}
			if c, err = r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status); err != nil {
				b.Errorf("Fetch(%v) error(%v)", arg.AppID, err)
			}
			fetchArg2 := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 2}
			if c, err = r.Fetch(fetchArg2.Zone, fetchArg2.Env, fetchArg2.AppID, 0, fetchArg2.Status); err != nil {
				b.Errorf("Fetch(%v) error(%v)", arg.AppID, err)
			}
			_ = c
		}
	})
}

func TestPoll(t *testing.T) {
	i := model.NewInstance(reg)
	r := register(t, i)
	Convey("test poll", t, func() {
		pollArg := &model.ArgPolls{Zone: "sh0001", Env: "pre", AppID: []string{"main.arch.test"}, Hostname: "csq"}
		ch, _, err := r.Polls(pollArg)
		So(err, ShouldBeNil)
		c := <-ch
		So(len(c[pollArg.AppID[0]].Instances), ShouldEqual, 1)
	})
}

func TestPolls(t *testing.T) {
	i1 := model.NewInstance(reg)
	i2 := model.NewInstance(reg2)
	r := register(t, i1, i2)
	Convey("test polls", t, func() {
		pollArg := &model.ArgPolls{Zone: "sh0001", Env: "pre", LatestTimestamp: []int64{0, 0}, AppID: []string{"main.arch.test", "main.arch.test2"}, Hostname: "csq"}
		ch, new, err := r.Polls(pollArg)
		So(err, ShouldBeNil)
		So(new, ShouldBeTrue)
		c := <-ch
		So(len(c), ShouldResemble, 2)
	})
}

func TestPollsChan(t *testing.T) {
	i1 := model.NewInstance(reg)
	i2 := model.NewInstance(reg2)
	r := register(t, i1, i2)

	Convey("test polls parallel", t, func(c C) {
		var (
			wg       sync.WaitGroup
			ch1, ch2 chan map[string]*model.InstanceInfo
			new      bool
			err      error
		)
		pollArg := &model.ArgPolls{Zone: "sh0001", Env: "pre", LatestTimestamp: []int64{time.Now().UnixNano(), time.Now().UnixNano()}, AppID: []string{"main.arch.test", "main.arch.test2"}, Hostname: "csq"}
		ch1, new, err = r.Polls(pollArg)
		c.So(err, ShouldEqual, errors.NotModified)
		c.So(new, ShouldBeFalse)
		c.So(ch1, ShouldNotBeNil)
		ch2, new, err = r.Polls(pollArg)
		c.So(err, ShouldEqual, errors.NotModified)
		c.So(new, ShouldBeFalse)
		c.So(ch2, ShouldNotBeNil)
		// wait group
		wg.Add(2)
		go func() {
			res := <-ch1
			c.So(len(res), ShouldResemble, 1)
			wg.Done()
		}()
		go func() {
			res := <-ch2
			c.So(len(res), ShouldResemble, 1)
			wg.Done()
		}()
		// re register when 1s later, make sure latest_timestamp changed
		time.Sleep(time.Second)
		h1 := model.NewInstance(regH1)
		r.Register(h1, 0)
		// wait
		wg.Wait()
	})
}

func BenchmarkPoll(b *testing.B) {
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			var (
				err error
				ch  chan map[string]*model.InstanceInfo
				c   map[string]*model.InstanceInfo
			)
			r, _ := benchRegister(b)
			pollArg := &model.ArgPolls{Zone: "sh0001", Env: "pre", AppID: []string{"main.arch.test"}, Hostname: "csq"}
			if ch, _, err = r.Polls(pollArg); err != nil {
				b.Errorf("Poll(%v) error(%v)", arg.AppID, err)
			}
			if c = <-ch; len(c[pollArg.AppID[0]].Instances) != 1 {
				b.Errorf("Poll(%v) lenth error", arg.AppID)
			}
		}
	})
}

func TestBroadcast(t *testing.T) {
	i := model.NewInstance(reg)
	r := register(t, i)
	Convey("test poll push connection", t, func() {
		go func() {
			Convey("must poll ahead of time", t, func() {
				time.Sleep(time.Microsecond * 5)
				var arg2 = &model.ArgRegister{AppID: "main.arch.test", Hostname: "go", Color: "red", Zone: "sh0001", Env: "pre", Status: 1}
				m2 := model.NewInstance(arg2)
				err2 := r.Register(m2, 0)
				So(err2, ShouldBeNil)
			})
		}()
		pollArg := &model.ArgPolls{Zone: "sh0001", Env: "pre", AppID: []string{"main.arch.test"}, LatestTimestamp: []int64{time.Now().UnixNano()}}
		ch, _, err := r.Polls(pollArg)
		So(err, ShouldResemble, errors.NotModified)
		c := <-ch
		So(len(c[pollArg.AppID[0]].Instances["sh0001"]), ShouldResemble, 2)
		So(c[pollArg.AppID[0]].Instances, ShouldNotBeNil)
		So(len(c[pollArg.AppID[0]].Instances["sh0001"]), ShouldResemble, 2)
	})
}

func BenchmarkBroadcast(b *testing.B) {
	for i := 0; i < b.N; i++ {
		var (
			err  error
			err2 error
			ch   chan map[string]*model.InstanceInfo
			c    map[string]*model.InstanceInfo
		)
		r, _ := benchRegister(b)
		go func() {
			time.Sleep(time.Millisecond * 1)
			var arg2 = &model.ArgRegister{AppID: "main.arch.test", Hostname: "go", Color: "red", Zone: "sh0001", Env: "pre", Status: 1}
			m2 := model.NewInstance(arg2)
			if err2 = r.Register(m2, 0); err2 != nil {
				b.Errorf("Reigster(%v) error(%v)", m2.AppID, err2)
			}
		}()
		pollArg := &model.ArgPolls{Zone: "sh0001", Env: "pre", AppID: []string{"main.arch.test"}, LatestTimestamp: []int64{time.Now().UnixNano()}}
		if ch, _, err = r.Polls(pollArg); err != nil && err != errors.NotModified {
			b.Errorf("Poll(%v) error(%v)", pollArg.AppID, err)
		}
		c = <-ch
		if len(c[pollArg.AppID[0]].Instances) != 2 {
			b.Errorf("Poll(%v) length error", pollArg.AppID)
		}
		if c[pollArg.AppID[0]].Instances == nil {
			b.Errorf("Poll(%v) zone instances nil error", pollArg.AppID)
		}
		if len(c[pollArg.AppID[0]].Instances["sh0001"]) != 2 {
			b.Errorf("Poll(%v) zone instances length error", pollArg.AppID)
		}
	}
}

func TestSet(t *testing.T) {
	i := model.NewInstance(reg)
	r := register(t, i)
	changes := &model.ArgSet{Zone: "sh0001", Env: "pre", AppID: "main.arch.test"}
	changes.Hostname = []string{"reg"}
	changes.Status = []uint32{1}
	Convey("test setstatus to 1", t, func() {
		ok := r.Set(changes)
		So(ok, ShouldBeTrue)
		fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 3}
		c, err := r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status)
		So(err, ShouldBeNil)
		So(c.Instances["sh0001"][0].Status, ShouldResemble, uint32(1))
	})
	changes = &model.ArgSet{Zone: "sh0001", Env: "pre", AppID: "main.arch.test"}
	changes.Hostname = []string{"reg"}
	changes.Color = []string{"blue"}
	Convey("test set color to blue", t, func() {
		ok := r.Set(changes)
		So(ok, ShouldBeTrue)
		fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 3}
		c, err := r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status)
		So(err, ShouldBeNil)
		So(c.Instances["sh0001"][0].Color, ShouldResemble, "blue")
	})
	changes = &model.ArgSet{Zone: "sh0001", Env: "pre", AppID: "main.arch.test"}
	changes.Hostname = []string{"reg"}
	changes.Metadata = []string{`{"weight":"11"}`}
	Convey("test set metadata weight to 11", t, func() {
		ok := r.Set(changes)
		So(ok, ShouldBeTrue)
		fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 3}
		c, err := r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status)
		So(err, ShouldBeNil)
		So(c.Instances["sh0001"][0].Metadata["weight"], ShouldResemble, "11")
	})
	i1 := model.NewInstance(regH1)
	r.Register(i1, 0)
	changes = &model.ArgSet{Zone: "sh0001", Env: "pre", AppID: "main.arch.test"}
	changes.Hostname = []string{"reg", "regH1"}
	changes.Metadata = []string{`{"weight":"12"}`, `{"weight":"13"}`}
	changes.Color = []string{"yellow", "yellow"}
	Convey("test set multi instance's color to blue and metadata weight to 12", t, func() {
		ok := r.Set(changes)
		So(ok, ShouldBeTrue)
		fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 3}
		c, err := r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status)
		So(err, ShouldBeNil)
		for _, ins := range c.Instances["sh0001"] {
			if ins.Hostname == "reg" {
				So(ins.Metadata["weight"], ShouldResemble, "12")
				So(ins.Color, ShouldResemble, "yellow")
			} else if ins.Hostname == "regH1" {
				So(ins.Metadata["weight"], ShouldResemble, "13")
				So(ins.Color, ShouldResemble, "yellow")
			}
		}
	})
}

func BenchmarkSet(b *testing.B) {
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			var (
				c   *model.InstanceInfo
				err error
				ok  bool
			)
			r, _ := benchRegister(b)
			changes := &model.ArgSet{Zone: "sh0001", Env: "pre", AppID: "main.arch.test"}
			changes.Hostname = []string{"reg"}
			changes.Status = []uint32{1}
			if ok = r.Set(changes); !ok {
				b.Errorf("SetStatus(%v) error", arg.AppID)
			}
			fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 3}
			if c, err = r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status); err != nil {
				b.Errorf("Fetch(%v) error(%v)", fetchArg.AppID, err)
				b.FailNow()
			}
			if c.Instances["sh0001"][0].Status != 1 {
				b.Errorf("SetStatus(%v) change error", fetchArg.AppID)
			}
		}
	})
}

func TestResetExp(t *testing.T) {
	i := model.NewInstance(reg)
	r := register(t, i)
	Convey("test ResetExp", t, func() {
		r.resetExp()
		So(r.gd.expPerMin, ShouldResemble, int64(2))
	})
}

func benchCompareInstance(b *testing.B, src *model.Instance, i *model.Instance) {
	if src.AppID != i.AppID || src.Color != i.Color || src.Env != i.Env || src.Hostname != i.Hostname {
		b.Errorf("instance compare error")
	}
}

func register(t *testing.T, is ...*model.Instance) (r *Registry) {
	Convey("test register", t, func() {
		r = NewRegistry()
		var num int
		for _, i := range is {
			err := r.Register(i, 0)
			So(err, ShouldBeNil)
			if i.AppID == "main.arch.test" {
				num++
			}
		}
		fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 3}
		instancesInfo, err := r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status)
		So(err, ShouldBeNil)
		So(len(instancesInfo.Instances["sh0001"]), ShouldResemble, num)
	})
	return r
}

func benchRegister(b *testing.B) (r *Registry, i *model.Instance) {
	r = NewRegistry()
	i = model.NewInstance(reg)
	if err := r.Register(i, 0); err != nil {
		b.Errorf("Reigster(%v) error(%v)", i.AppID, err)
	}
	return r, i
}

func TestEvict(t *testing.T) {
	Convey("test evict for protect", t, func() {
		r := NewRegistry()
		m := model.NewInstance(reg)
		// promise the renewtime of instance is expire
		m.RenewTimestamp -= 100
		err := r.Register(m, 0)
		So(err, ShouldBeNil)
		// move up the statistics of heartbeat for evict
		r.gd.facLastMin = r.gd.facInMin
		r.evict()
		fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 3}
		c, err := r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status)
		So(err, ShouldBeNil)
		// protect
		So(len(c.Instances), ShouldResemble, 1)
	})
}

func TestEvict2(t *testing.T) {
	Convey("test evict for cancel", t, func() {
		r := NewRegistry()
		m := model.NewInstance(reg)
		err := r.Register(m, 0)
		So(err, ShouldBeNil)
		_, ok := r.Renew(arg)
		So(ok, ShouldBeTrue)
		// promise the renewtime of instance is expire
		m.RenewTimestamp -= int64(time.Second * 100)
		r.Register(m, 0)
		// move up the statistics of heartbeat for evict
		r.gd.facLastMin = r.gd.facInMin
		r.evict()
		fetchArg := &model.ArgFetch{Zone: "sh0001", Env: "pre", AppID: "main.arch.test", Status: 1}
		_, err = r.Fetch(fetchArg.Zone, fetchArg.Env, fetchArg.AppID, 0, fetchArg.Status)
		So(err, ShouldResemble, errors.NothingFound)
	})
}

license: MIT

license_type: permissive

branch_name: refs/heads/master

gha_license_id: MIT

extension: go


text:
DESCRIPTION="update-scripts"

LICENSE = "Apache-2.0"
LICENSE_MD5SUM = "4336ad26bb93846e47581adc44c4514d"
SOURCE_REPOSITORY = "git://git@github.com/ARMmbed/mbed-cloud-client.git"
SOURCE_BRANCH = "master"
SRCREV = "62de4b89d2350379278893f2f7a3ac937b4ae5f6"
SCRIPT_DIR = "${WORKDIR}/git/update-client-hub/modules/pal-linux/scripts"

# Default Update scripts are for Raspberrypi3. Please override these for HW specific srcipts if required.
UPDATE_CMDLINE          ?= "${SCRIPT_DIR}/arm_update_cmdline.sh"
UPDATE_ACTIVATE         ?= "${SCRIPT_DIR}/yocto_rpi/arm_update_activate.sh"
UPDATE_ACTIVATE_DETAILS ?= "${SCRIPT_DIR}/yocto_rpi/arm_update_active_details.sh"

LIC_FILES_CHKSUM = "file://${WORKDIR}/git/LICENSE;md5=${LICENSE_MD5SUM}"

# Patches for quilt goes to files directory
#FILESEXTRAPATHS_prepend := "${THISDIR}/files:"

SRC_URI = "${SOURCE_REPOSITORY};branch=${SOURCE_BRANCH};protocol=ssh"

# Deploy for getting update-client-hub to working area
do_configure() {
    cd "${WORKDIR}/git"
    ${binlocaldir}/mbed deploy --protocol ssh
}

# Install update-scripts
do_install() {
    install -d "${D}/opt/arm"
    install -m 755 "${UPDATE_CMDLINE}"          "${D}/opt/arm"
    install -m 755 "${UPDATE_ACTIVATE}"         "${D}/opt/arm"
    install -m 755 "${UPDATE_ACTIVATE_DETAILS}" "${D}/opt/arm"
}

FILES_${PN} += "/opt \
                /opt/arm"

repository: geoffrey-vl/meta-mbed-cloud-client

repo_name: geoffrey-vl/meta-mbed-cloud-client

extension: bb


text:
package paypal

import (
	"fmt"
	"net/url"
)

type DisputeStatus string

const (
	DisputeStatusOpen                     DisputeStatus = "OPEN"
	DisputeStatusWaitingForBuyerResponse  DisputeStatus = "WAITING_FOR_BUYER_RESPONSE"
	DisputeStatusWaitingForSellerResponse DisputeStatus = "WAITING_FOR_SELLER_RESPONSE"
	DisputeStatusUnderReview              DisputeStatus = "UNDER_REVIEW"
	DisputeStatusResolved                 DisputeStatus = "RESOLVED"
	DisputeStatusOther                    DisputeStatus = "OTHER"
)

type Dispute struct {
	DisputeId             string                 `json:"dispute_id,omitempty"`
	CreateTime            string                 `json:"create_time,omitempty"`
	UpdateTime            string                 `json:"update_time,omitempty"`
	DisputedTransactions  []*DisputedTransaction `json:"disputed_transactions,omitempty"`
	Reason                string                 `json:"reason,omitempty"`
	Status                DisputeStatus          `json:"status,omitempty"`
	DisputeAmount         *Currency              `json:"dispute_amount,omitempty"`
	DisputeOutcome        *DisputeOutcome        `json:"dispute_outcome,omitempty"`
	Messages              []*Message             `json:"messages,omitempty"`
	SellerResponseDueDate string                 `json:"seller_response_due_date,omitempty"`
	Links                 []*Link                `json:"links,omitempty"`
}

type DisputedTransaction struct {
	BuyerTransactionId       string                     `json:"buyer_transaction_id,omitempty"`
	SellerTransactionId      string                     `json:"seller_transaction_id,omitempty"`
	CreateTime               string                     `json:"create_time,omitempty"`
	TransactionStatus        string                     `json:"transaction_status,omitempty"`
	GrossAmount              *Currency                  `json:"gross_amount,omitempty"`
	InvoiceNumber            string                     `json:"invoice_number,omitempty"`
	Custom                   string                     `json:"custom,omitempty"`
	Buyer                    *Buyer                     `json:"buyer,omitempty"`
	Seller                   *Seller                    `json:"seller,omitempty"`
	Items                    []*DisputedTransactionItem `json:"items,omitempty"`
	SellerProtectionEligible bool                       `json:"seller_protection_eligible,omitempty"`
}

type DisputeOutcome struct {
	OutcomeCode    string    `json:"outcome_code,omitempty"`
	AmountRefunded *Currency `json:"amount_refunded,omitempty"`
}

type Message struct {
	PostedBy   string `json:"posted_by,omitempty"`
	TimePosted string `json:"time_posted,omitempty"`
	Content    string `json:"content,omitempty"`
}

type Buyer struct {
	Email string `json:"email,omitempty"`
	Name  string `json:"name,omitempty"`
}

type Seller struct {
	Email      string `json:"email,omitempty"`
	Name       string `json:"name,omitempty"`
	MerchantId string `json:"merchant_id,omitempty"`
}

type DisputedTransactionItem struct {
	ItemId               string    `json:"item_id,omitempty"`
	PartnerTransactionId string    `json:"partner_transaction_id,omitempty"`
	Reason               string    `json:"reason,omitempty"`
	DisputeAmount        *Currency `json:"dispute_amount,omitempty"`
	Notes                string    `json:"notes,omitempty"`
}

type DisputeListParam struct {
	StartTime             string
	DisputedTransactionId string
	PageSize              int
	NextPageToken         string
	DisputeState          string
}

func (this *DisputeListParam) QueryString() string {
	var p = url.Values{}
	if len(this.StartTime) > 0 {
		p.Set("start_time", this.StartTime)
	}
	if len(this.DisputedTransactionId) > 0 {
		p.Set("disputed_transaction_id", this.DisputedTransactionId)
	}
	if this.PageSize > 0 {
		p.Set("page_size", fmt.Sprintf("%d", this.PageSize))
	}
	if len(this.NextPageToken) > 0 {
		p.Set("next_page_token", this.NextPageToken)
	}
	if len(this.DisputeState) > 0 {
		p.Set("dispute_state", this.DisputeState)
	}
	return "?" + p.Encode()
}

type DisputeList struct {
	Items []*Dispute `json:"items,omitempty"`
	Links []*Link    `json:"links,omitempty"`
}

repository: smartwalle/paypal

repo_name: smartwalle/paypal


text:
package whois

import (
	"io/ioutil"
	"reflect"
	"testing"
)

// Uncomment and run to write a domain to a file
// func TestWriteFile(t *testing.T) {
// 	domain := "decafproductions.com"
// 	query, err := WhoisQuery(domain)

// 	if err != nil {
// 		panic(err)
// 	}

// 	ioutil.WriteFile("test/" + domain, []byte(query), 0755)
// }

type ParsedAnswer struct {
	// times
	LastUpdatedAt string
	CreatedAt string
	ExpiresAt string

	// contact points
	Registrar string
	ContactEmails []string
}

func TestWhoisParserUS(t *testing.T) {
	answer := ParsedAnswer{
		LastUpdatedAt: "2015-11-20 07:42:26 +0000 GMT",
		CreatedAt: "2008-12-21 20:11:01 +0000 GMT",
		ExpiresAt: "2016-12-20 23:59:59 +0000 GMT",
		Registrar: "Adam Shannon",
		ContactEmails: []string{"ashannon1000@gmail.com"},
	}
	VerifyParsedResposne("ashannon.us", answer, t)
}

func TestWhoisParserCOM(t *testing.T) {
	answer := ParsedAnswer{
		LastUpdatedAt: "2015-11-13 00:00:00 +0000 UTC",
		CreatedAt: "2012-12-13 00:00:00 +0000 UTC",
		ExpiresAt: "2016-12-13 00:00:00 +0000 UTC",
		Registrar: "ENOM, INC.",
	}
	VerifyParsedResposne("decafproductions.com", answer, t)
}

func TestWhoisParserXOrg(t *testing.T) {
	answer := ParsedAnswer{
		LastUpdatedAt: "2007-01-12 21:42:24 +0000 UTC",
		CreatedAt: "1997-01-18 05:00:00 +0000 UTC",
		ExpiresAt: "2016-01-19 05:00:00 +0000 UTC",
		Registrar: "X.ORG Foundation, LLC",
		ContactEmails: []string{"leon@shiman.com"},
	}
	VerifyParsedResposne("x.org", answer, t)
}

func TestWhoisParserNO(t *testing.T) {
	answer := ParsedAnswer{
		CreatedAt: "2014-09-04 00:00:00 +0000 UTC",
		ExpiresAt: "0001-01-01 00:00:00 +0000 UTC",
		LastUpdatedAt: "2015-09-04 00:00:00 +0000 UTC",
	}
	VerifyParsedResposne("ban.no", answer, t)
}

func VerifyParsedResposne(domain string, answer ParsedAnswer, t *testing.T) {
	resp, err := ioutil.ReadFile("testdata/" + domain)

	if err != nil {
		t.Errorf("error getting whois query response = %s", err)
	}

	parsed, err := ParseWhoisResponse(string(resp))

	if err != nil {
		t.Errorf("error parsing whois response = %s", err)
	}

	last_updated_str := parsed.LastUpdatedAt.String()
	if last_updated_str != answer.LastUpdatedAt {
		t.Errorf("last updated times don't match (actual = %s)", last_updated_str)
	}

	created_at_str := parsed.CreatedAt.String()
	if created_at_str != answer.CreatedAt {
		t.Errorf("created at times don't match (actual = %s)", created_at_str)
	}

	expires_at_str := parsed.ExpiresAt.String()
	if expires_at_str != answer.ExpiresAt {
		t.Errorf("expires at times don't match (actual = %s)", expires_at_str)
	}

	registrar_str := parsed.Registrar
	if registrar_str != answer.Registrar {
		t.Errorf("registrar doesn't match (actual = %s)", registrar_str)
	}

	contact_emails := parsed.ContactEmails
	if !reflect.DeepEqual(contact_emails, answer.ContactEmails) {
		t.Errorf("contact emails don't match (actual = %s)", contact_emails)
	}

	// fmt.Printf("Registrar = %s\n", parsed.Registrar)
	// fmt.Printf("ContactEmails = %s\n", parsed.ContactEmails)
	// fmt.Printf("ContactPhoneNumbers = %s\n", parsed.ContactPhoneNumbers)
	// fmt.Printf("NameServers = %s\n", parsed.NameServers)
	// fmt.Printf("DNSSECEnabled = %t\n", parsed.DNSSECEnabled)
}

repository: cwebd/go-whois

repo_name: cwebd/go-whois


text:
package burningdice

import (
	"math/big"
)

func ChanceOfSuccessesOrGreaterWithOpenSixes(targetSuccesses, numDice uint) *big.Rat {
	chance := ChanceOfSuccessesOrGreater(targetSuccesses, numDice)

	var initialSuccesses uint
	for initialSuccesses = 1; initialSuccesses < targetSuccesses; initialSuccesses++ {
		chanceOfThisManySuccesses := chanceOfSuccesses(initialSuccesses, numDice)

		var sixes uint
		for sixes = 1; sixes <= initialSuccesses; sixes++ {
			chanceOfThisManySixes := chanceOfSixesGivenSuccesses(sixes, initialSuccesses)
			chanceOfOpening := ChanceOfSuccessesOrGreaterWithOpenSixes(targetSuccesses - initialSuccesses, sixes)
			chanceOfOpening = chanceOfOpening.Mul(chanceOfOpening, chanceOfThisManySixes)
			chanceOfOpening = chanceOfOpening.Mul(chanceOfOpening, chanceOfThisManySuccesses)
			chance = chance.Add(chance, chanceOfOpening)
		}
	}
	return chance
}

func ChanceOfSuccessesOrGreater(targetSuccesses, numDice uint) *big.Rat {
	chance := big.NewRat(0,1)
	for enoughSuccesses := targetSuccesses; enoughSuccesses <= numDice; enoughSuccesses++ {
		chance = chance.Add(chance, chanceOfSuccesses(enoughSuccesses, numDice))
	}
	return chance
}

type exponentiable interface {
	toThe(n uint) *big.Rat
}

func chanceOfN(targetNumRolls, numDiceTotal uint, chanceForRoll, chanceAgainstRoll exponentiable) *big.Rat {
	if targetNumRolls > numDiceTotal {
		return big.NewRat(0,1)
	}

	successCombinations := combinations(targetNumRolls, numDiceTotal)

	chance := big.NewRat(1,1).SetInt(successCombinations)
	chance = chance.Mul(chance, chanceForRoll.toThe(targetNumRolls))
	return chance.Mul(chance, chanceAgainstRoll.toThe(numDiceTotal - targetNumRolls))
}

func chanceOfSuccesses(targetSuccesses, numDice uint) *big.Rat {
	return chanceOfN(targetSuccesses, numDice, oneHalf, oneHalf)
}

func chanceOfSixesGivenSuccesses(targetSixes, numSuccesses uint) *big.Rat {
	return chanceOfN(targetSixes, numSuccesses, oneThird, twoThirds)
}

repository: TheDorkKnight/burningdice

repo_name: TheDorkKnight/burningdice


text:
package agent

import (
	"fmt"
	"sync"

	"github.com/chrislusf/gleam/pb"
)

var (
	statsChanMap        = make(map[string]chan *pb.ExecutionStat)
	statsChanMapRWMutex sync.Mutex
)

func getStatsChan(flowHashCode uint32, stepId int32, taskId int32) chan *pb.ExecutionStat {
	key := fmt.Sprintf("%d-%d-%d", flowHashCode, stepId, taskId)
	statsChanMapRWMutex.Lock()
	defer statsChanMapRWMutex.Unlock()
	return statsChanMap[key]
}

func deleteStatsChanByInstructionSet(instructionSet *pb.InstructionSet) {
	deleteStatsChan(instructionSet.FlowHashCode,
		instructionSet.Instructions[0].GetStepId(),
		instructionSet.Instructions[0].GetTaskId())
}

func deleteStatsChan(flowHashCode uint32, stepId int32, taskId int32) {
	key := fmt.Sprintf("%d-%d-%d", flowHashCode, stepId, taskId)
	statsChanMapRWMutex.Lock()
	defer statsChanMapRWMutex.Unlock()
	delete(statsChanMap, key)
}

func createStatsChanByInstructionSet(instructionSet *pb.InstructionSet) chan *pb.ExecutionStat {
	statsChan := make(chan *pb.ExecutionStat)
	key := fmt.Sprintf("%d-%d-%d",
		instructionSet.FlowHashCode,
		instructionSet.Instructions[0].GetStepId(),
		instructionSet.Instructions[0].GetTaskId())
	statsChanMapRWMutex.Lock()
	defer statsChanMapRWMutex.Unlock()
	statsChanMap[key] = statsChan
	return statsChan
}

repository: naveenholla/gleam

repo_name: naveenholla/gleam

gha_language: Go


text:
SUMMARY = "ISC Kea DHCP Server"
DESCRIPTION = "Kea is the next generation of DHCP software developed by ISC. It supports both DHCPv4 and DHCPv6 protocols along with their extensions, e.g. prefix delegation and dynamic updates to DNS."
HOMEPAGE = "http://kea.isc.org"
SECTION = "connectivity"
LICENSE = "MPL-2.0 & Apache-2.0"
LIC_FILES_CHKSUM = "file://COPYING;md5=68d95543d2096459290a4e6b9ceccffa"

DEPENDS += "kea-native"

SRC_URI = "\
    http://ftp.isc.org/isc/kea/${PV}/${BP}.tar.gz \
    file://0001-remove-AC_TRY_RUN.patch \
    file://kea-dhcp4.service \
    file://kea-dhcp6.service \
    file://kea-dhcp-ddns.service \
"
SRC_URI[md5sum] = "4f8d1251fd41ef2e822a4eb3f0797d46"
SRC_URI[sha256sum] = "0bba8b045672884a928ff4b2a8575ac5ba420eb6ba47a9338f1932bc38dcf866"

inherit autotools systemd

SYSTEMD_SERVICE_${PN} = "kea-dhcp4.service kea-dhcp6.service kea-dhcp-ddns.service"
SYSTEMD_AUTO_ENABLE = "disable"

DEBUG_OPTIMIZATION_remove_mips = " -Og"
DEBUG_OPTIMIZATION_append_mips = " -O"
BUILD_OPTIMIZATION_remove_mips = " -Og"
BUILD_OPTIMIZATION_append_mips = " -O"

DEBUG_OPTIMIZATION_remove_mipsel = " -Og"
DEBUG_OPTIMIZATION_append_mipsel = " -O"
BUILD_OPTIMIZATION_remove_mipsel = " -Og"
BUILD_OPTIMIZATION_append_mipsel = " -O"

do_configure_prepend_class-target() {
    mkdir -p ${B}/src/lib/log/compiler/
    ln -sf ${STAGING_BINDIR_NATIVE}/kea-msg-compiler ${B}/src/lib/log/compiler/kea-msg-compiler
    # replace abs_top_builddir to avoid introducing the build path
    # don't expand the abs_top_builddir on the target as the abs_top_builddir is meanlingless on the target
    find ${S} -type f -name *.sh.in | xargs sed -i  "s:@abs_top_builddir@:@abs_top_builddir_placeholder@:g"
    sed -i "s:@abs_top_srcdir@:@abs_top_srcdir_placeholder@:g" ${S}/src/bin/admin/kea-admin.in
}

do_install_append_class-target() {
    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${WORKDIR}/kea-dhcp*service ${D}${systemd_system_unitdir}
    sed -i -e 's,@SBINDIR@,${sbindir},g' -e 's,@BASE_BINDIR@,${base_bindir},g' \
           -e 's,@LOCALSTATEDIR@,${localstatedir},g' -e 's,@SYSCONFDIR@,${sysconfdir},g' \
           ${D}${systemd_system_unitdir}/kea-dhcp*service
}

do_install_append() {
    rm -rf "${D}${localstatedir}"
}

PACKAGECONFIG ??= "openssl log4cplus boost"

PACKAGECONFIG[openssl] = "--with-openssl=${STAGING_DIR_TARGET}${prefix},,openssl,openssl"
PACKAGECONFIG[log4cplus] = "--with-log4cplus=${STAGING_DIR_TARGET}${prefix},,log4cplus,log4cplus"
PACKAGECONFIG[boost] = "--with-boost-libs=-lboost_system,,boost,boost"

FILES_${PN}-staticdev += "${libdir}/kea/hooks/*.a ${libdir}/hooks/*.a"
FILES_${PN} += "${libdir}/hooks/*.so"

BBCLASSEXTEND += "native"

PARALLEL_MAKEINST = ""


text:
@article{MR1484619,
 author = {Ros, Antonio and Urbano, Francisco},
 doi = {10.2969/jmsj/05010203},
 fjournal = {Journal of the Mathematical Society of Japan},
 issn = {0025-5645},
 journal = {J. Math. Soc. Japan},
 mrclass = {53C42 (53C40)},
 mrnumber = {1484619},
 mrreviewer = {Ildefonso Castro},
 number = {1},
 pages = {203--226},
 title = {Lagrangian submanifolds of $\bf C^n$ with conformal
Maslov form and the Whitney sphere},
 url = {https://doi.org/10.2969/jmsj/05010203},
 volume = {50},
 year = {1998}
}

repository: torralbofco/geometric-analysis-fork

repo_name: torralbofco/geometric-analysis-fork

extension: bib


text:
%% LaTeX2e file `clickable_citation.bib'
%% generated by the `filecontents' environment
%% from source `clickable_citation' on 2017/06/08.
%%
@misc{A01,
  author = {Author, A.},
  year = {2001},
  title = {Alpha},
  url = {http://tex.stackexchange.com/questions/4420/best-way-to-start-using-latex-tex},
}

repository: bhishanpdl/Programming

repo_name: bhishanpdl/Programming


text:
package items

import (
	"fmt"
	"github.com/xosmig/roguelike/core/character"
)

const amuletHPBonus = 3

type HealthAmulet struct{}

func NewHealthAmulet() character.Item {
	return HealthAmulet{}
}

func (amulet HealthAmulet) Wear(character character.Character) error {
	character.SetMaxHP(character.GetMaxHP() + amuletHPBonus)
	character.SetHP(character.GetHP() + amuletHPBonus)
	return nil
}

func (amulet HealthAmulet) TakeOff(character character.Character) error {
	if character.GetHP() <= amuletHPBonus {
		return fmt.Errorf("this amulet keeps you alive")
	}

	character.SetHP(character.GetHP() - amuletHPBonus)
	character.SetMaxHP(character.GetMaxHP() - amuletHPBonus)
	return nil
}

func (amulet HealthAmulet) IconName() string {
	return "health_amulet"
}

license: Unlicense

repository: xosmig/roguelike

repo_name: xosmig/roguelike

gha_license_id: Unlicense


text:
package executor

import (
	"github.com/screwdriver-cd/sd-cmd/util"
)

var habPath = "/hab/bin/hab"

// Habitat is the Habitat Executor struct
type Habitat struct {
	Args []string
	Spec *util.Habitat
}

// NewHabitat returns the Habitat struct
func NewHabitat(spec *util.CommandSpec, args []string) (habitat *Habitat, err error) {
	habitat = &Habitat{
		Args: args,
		Spec: &util.Habitat{
			Mode:    spec.Habitat.Mode,
			Package: spec.Habitat.Package,
			Command: spec.Habitat.Command,
		},
	}
	return habitat, nil
}

// install executes "hab install" with a package name
func (h *Habitat) install() (err error) {
	pkgInstallArgs := []string{"pkg", "install", h.Spec.Package}

	return execCommand(habPath, pkgInstallArgs)
}

// exec executes "hab exec" with a package name, command and args from a CLI
func (h *Habitat) exec() (err error) {
	execArgs := append([]string{"pkg", "exec", h.Spec.Package, h.Spec.Command}, h.Args...)

	return execCommand(habPath, execArgs)
}

// Run executes "hab install" and "hab exec"
func (h *Habitat) Run() (err error) {
	lgr.Debug.Println("start installing habitat command.")

	err = h.install()
	if err != nil {
		lgr.Debug.Println(err)
		return
	}

	lgr.Debug.Println("start executing habitat command.")
	err = h.exec()
	if err != nil {
		lgr.Debug.Println(err)
	} else {
		lgr.Debug.Println("execute habitat command succeeded.")
	}
	return
}


text:
DESCRIPTION = "esmi oob tool"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://${COREBASE}/meta/files/common-licenses/Apache-2.0;md5=89aea4e17d99a7cacdbeed46a0096b10"

SRC_URI = "git://github.com/amd/esmi_oob_library.git;branch=master;protocol=https \
        file://0001-fixed-header-incude.patch \
    "

SRCREV = "00cc0fb0265af1d240a0aff5ed96f90a73ff8c51"

S = "${WORKDIR}/git"

inherit cmake

repository: Nuvoton-Israel/openbmc

repo_name: Nuvoton-Israel/openbmc

branch_name: refs/heads/npcm-master

gha_license_id: NOASSERTION

gha_language: Python


text:
DESCRIPTION = "WiFi AP mode toggle in Edison"
SECTION = "base"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

FILESEXTRAPATHS:prepend := "${THISDIR}/files/:"

SRC_URI = "file://ap-mode-toggle"
SRC_URI:append = " file://ap-mode-toggle.service"

S = "${WORKDIR}"
PR = "r6"

SYSTEMD_SERVICE:${PN} = "ap-mode-toggle.service"

inherit systemd

FILES_${PN} = "${systemd_unitdir}/system/*"
FILES_${PN} += "${bindir}/*"

do_install:append() {
	install -d ${D}${bindir}
	install -m 0755 ${S}/ap-mode-toggle ${D}${bindir}

	install -d ${D}/${systemd_unitdir}/system
	install -m 644 ${S}/ap-mode-toggle.service ${D}/${systemd_unitdir}/system
}

repository: edison-fw/meta-intel-edison

repo_name: edison-fw/meta-intel-edison

gha_language: Shell


text:
package golang

import (
	"context"
	"errors"
	"testing"

	"github.com/EricHripko/pack.yaml/pkg/packer2llb"
	"github.com/EricHripko/pack.yaml/pkg/packer2llb/config"

	cib_mock "github.com/EricHripko/buildkit-fdk/pkg/cib/mock"
	"github.com/golang/mock/gomock"
	"github.com/moby/buildkit/client/llb"
	"github.com/moby/buildkit/frontend/dockerfile/dockerfile2llb"
	"github.com/moby/buildkit/frontend/gateway/client"
	specs "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
	fsutil "github.com/tonistiigi/fsutil/types"
)

type golangTestSuite struct {
	suite.Suite
	ctrl   *gomock.Controller
	ctx    context.Context
	build  *cib_mock.MockService
	src    *cib_mock.MockReference
	plugin *Plugin
}

func (suite *golangTestSuite) SetupTest() {
	suite.ctrl = gomock.NewController(suite.T())
	suite.ctx = context.Background()
	suite.build = cib_mock.NewMockService(suite.ctrl)
	suite.src = cib_mock.NewMockReference(suite.ctrl)
	suite.plugin = NewPlugin()
}

func (suite *golangTestSuite) TearDownTest() {
	suite.ctrl.Finish()
}

func (suite *golangTestSuite) TestInvalidConfig() {
	// Arrange
	cfg := config.New()
	cfg.Other["go"] = map[string]interface{}{
		"tags": "tag1",
	}

	// Act
	err := suite.plugin.Detect(suite.ctx, suite.src, cfg)

	// Assert
	require.NotNil(suite.T(), err)
}

func (suite *golangTestSuite) TestDetectNotFound() {
	// Arrange
	req := client.ReadDirRequest{Path: "."}
	files := []*fsutil.Stat{
		{Path: "README.md"},
	}
	suite.src.EXPECT().
		ReadDir(suite.ctx, req).
		Return(files, nil)

	// Act
	err := suite.plugin.Detect(suite.ctx, suite.src, config.New())

	// Assert
	require.Nil(suite.T(), err)
}

func (suite *golangTestSuite) TestDetectFoundGoSource() {
	// Arrange
	req := client.ReadDirRequest{Path: "."}
	files := []*fsutil.Stat{
		{Path: "hello.go"},
	}
	suite.src.EXPECT().
		ReadDir(suite.ctx, req).
		Return(files, nil)
	suite.src.EXPECT().
		ReadFile(suite.ctx, gomock.Any()).
		Return(nil, errors.New("not found")).
		Times(2)

	// Act
	err := suite.plugin.Detect(suite.ctx, suite.src, config.New())

	// Assert
	require.Same(suite.T(), ErrUnknownDep, err)
}

func (suite *golangTestSuite) TestDetectGoModNotFound() {
	// Arrange
	req := client.ReadDirRequest{Path: "."}
	files := []*fsutil.Stat{
		{Path: "hello.go"},
	}
	suite.src.EXPECT().
		ReadDir(suite.ctx, req).
		Return(files, nil)
	suite.src.EXPECT().
		ReadFile(suite.ctx, gomock.Any()).
		Return(nil, errors.New("not found"))
	cfg := config.New()
	cfg.Other["go"] = map[string]interface{}{
		"dependencyMode": "modules",
	}

	// Act
	err := suite.plugin.Detect(suite.ctx, suite.src, cfg)

	// Assert
	require.NotNil(suite.T(), err)
	require.Contains(suite.T(), err.Error(), "fail to read go.mod")
}

func (suite *golangTestSuite) TestDetectGoModFails() {
	// Arrange
	req := client.ReadDirRequest{Path: "."}
	files := []*fsutil.Stat{
		{Path: "hello.go"},
	}
	suite.src.EXPECT().
		ReadDir(suite.ctx, req).
		Return(files, nil)
	goMod := []byte("\"")
	suite.src.EXPECT().
		ReadFile(suite.ctx, gomock.Any()).
		Return(goMod, nil).
		Times(3)

	// Act
	err := suite.plugin.Detect(suite.ctx, suite.src, config.New())

	// Assert
	require.NotNil(suite.T(), err)
}

func (suite *golangTestSuite) TestDetectGoModIncomplete() {
	// Arrange
	req := client.ReadDirRequest{Path: "."}
	files := []*fsutil.Stat{
		{Path: "hello.go"},
	}
	suite.src.EXPECT().
		ReadDir(suite.ctx, req).
		Return(files, nil)
	goMod := []byte("")
	suite.src.EXPECT().
		ReadFile(suite.ctx, gomock.Any()).
		Return(goMod, nil).
		Times(3)

	// Act
	err := suite.plugin.Detect(suite.ctx, suite.src, config.New())

	// Assert
	require.Same(suite.T(), ErrModIncomplete, err)
}

func (suite *golangTestSuite) TestDetectGoModSucceeds() {
	// Arrange
	req := client.ReadDirRequest{Path: "."}
	files := []*fsutil.Stat{
		{Path: "hello.go"},
	}
	suite.src.EXPECT().
		ReadDir(suite.ctx, req).
		Return(files, nil)
	goMod := []byte(`
module github.com/notareal/project

go 1.15
`)
	suite.src.EXPECT().
		ReadFile(suite.ctx, gomock.Any()).
		Return(goMod, nil).
		Times(3)
	tags := []string{"tag1", "tag2"}
	cfg := config.New()
	cfg.Other["go"] = map[string]interface{}{
		"tags": tags,
	}

	// Act
	err := suite.plugin.Detect(suite.ctx, suite.src, cfg)

	// Assert
	require.Same(suite.T(), packer2llb.ErrActivate, err)
	require.Equal(suite.T(), tags, suite.plugin.pluginConfig.Tags)
}

func (suite *golangTestSuite) TestBuildFailsFrom1() {
	// Arrange
	suite.plugin.pluginConfig.Version = "1.14"

	platform := &specs.Platform{OS: "linux", Architecture: "amd64"}
	expected := errors.New("something went wrong")
	suite.build.EXPECT().
		From("golang:1.14", platform, gomock.Any()).
		Return(llb.Scratch(), nil, expected)

	// Act
	_, _, actual := suite.plugin.Build(suite.ctx, platform, suite.build)

	// Assert
	require.Same(suite.T(), expected, actual)
}

func (suite *golangTestSuite) TestBuildFailsSrc() {
	// Arrange
	suite.plugin.pluginConfig.Version = "1.14"

	platform := &specs.Platform{OS: "linux", Architecture: "amd64"}
	suite.build.EXPECT().
		From("golang:1.14", platform, gomock.Any()).
		Return(llb.Scratch(), nil, nil)

	expected := errors.New("something went wrong")
	suite.build.EXPECT().
		SrcState().
		Return(llb.Scratch(), expected)

	// Act
	_, _, actual := suite.plugin.Build(suite.ctx, platform, suite.build)

	// Assert
	require.Same(suite.T(), expected, actual)
}

func (suite *golangTestSuite) TestBuildFailsFrom2() {
	// Arrange
	suite.plugin.pluginConfig.Version = "1.14"

	platform := &specs.Platform{OS: "linux", Architecture: "amd64"}
	suite.build.EXPECT().
		From("golang:1.14", platform, gomock.Any()).
		Return(llb.Scratch(), nil, nil)
	suite.build.EXPECT().
		SrcState().
		Return(llb.Scratch(), nil)

	expected := errors.New("something went wrong")
	suite.build.EXPECT().
		From("gcr.io/distroless/base:debug", platform, gomock.Any()).
		Return(llb.Scratch(), nil, expected)

	// Act
	_, _, actual := suite.plugin.Build(suite.ctx, platform, suite.build)

	// Assert
	require.Same(suite.T(), expected, actual)
}

func (suite *golangTestSuite) TestBuildSucceeds() {
	// Arrange
	suite.plugin.config.Debug = false
	suite.plugin.pluginConfig.DependencyMode = DMGoMod
	suite.plugin.pluginConfig.Version = "1.14"
	suite.plugin.pluginConfig.Tags = []string{"tag1", "tag2"}

	platform := &specs.Platform{OS: "linux", Architecture: "amd64"}
	suite.build.EXPECT().
		From("golang:1.14", platform, gomock.Any()).
		Return(llb.Scratch(), nil, nil)
	suite.build.EXPECT().
		SrcState().
		Return(llb.Scratch(), nil)
	expected := &dockerfile2llb.Image{}
	suite.build.EXPECT().
		From("gcr.io/distroless/base", platform, gomock.Any()).
		Return(llb.Scratch(), expected, nil)

	// Act
	state, actual, err := suite.plugin.Build(suite.ctx, platform, suite.build)

	// Assert
	require.Nil(suite.T(), err)
	require.NotNil(suite.T(), state)
	require.Same(suite.T(), expected, actual)
}

func TestGolangPlugin(t *testing.T) {
	suite.Run(t, new(golangTestSuite))
}

branch_name: refs/heads/main


text:
package logr_test

import (
	"bytes"
	"context"
	"strings"
	"testing"
	"time"

	"github.com/mattermost/logr/v2"
	"github.com/mattermost/logr/v2/formatters"
	"github.com/mattermost/logr/v2/test"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestFlush(t *testing.T) {
	buf := &bytes.Buffer{}
	formatter := &formatters.Plain{DisableTimestamp: true, Delim: " | "}
	filter := &logr.StdFilter{Lvl: logr.Info, Stacktrace: logr.Error}
	target := test.NewSlowTarget(buf, 2)
	lgr, _ := logr.New()
	err := lgr.AddTarget(target, "flushTest", filter, formatter, 3000)
	require.NoError(t, err)

	cfg := test.DoSomeLoggingCfg{
		Lgr:        lgr,
		Goroutines: 20,
		Loops:      100,
		Lvl:        logr.Error,
	}
	test.DoSomeLogging(cfg)
	logger := lgr.NewLogger()
	logger.Info("Last entry @!!@")

	start := time.Now()

	// blocks until flush is finished.
	err = lgr.Flush()
	require.NoError(t, err)

	dur := time.Since(start)
	t.Logf("Flush duration: %v", dur)

	output := buf.String()
	if !strings.Contains(output, "@!!@") {
		t.Errorf("missing last log record")
	}

	// make sure logging can continue after flush.
	test.DoSomeLogging(cfg)
	logger.Info("Last entry %^^%")

	// blocks until flush is finished.
	err = lgr.Flush()
	require.NoError(t, err)

	output = buf.String()
	if !strings.Contains(output, "%^^%") {
		t.Errorf("missing last log record")
	}
}

func TestFlushAfterShutdown(t *testing.T) {
	buf := &bytes.Buffer{}
	formatter := &formatters.Plain{DisableTimestamp: true, Delim: " | "}
	filter := &logr.StdFilter{Lvl: logr.Info, Stacktrace: logr.Error}
	target := test.NewSlowTarget(buf, 2)
	lgr, _ := logr.New()
	err := lgr.AddTarget(target, "flushTest", filter, formatter, 3000)
	require.NoError(t, err)

	cfg := test.DoSomeLoggingCfg{
		Lgr:        lgr,
		Goroutines: 20,
		Loops:      100,
		Lvl:        logr.Error,
	}
	test.DoSomeLogging(cfg)

	err = lgr.Shutdown()
	require.NoError(t, err)

	// Should error since shutdown already called. Shouldn't crash.
	err = lgr.Flush()
	require.Error(t, err)
}

func TestLogAfterShutdown(t *testing.T) {
	buf := &bytes.Buffer{}
	formatter := &formatters.Plain{DisableTimestamp: true, Delim: " | "}
	filter := &logr.StdFilter{Lvl: logr.Info, Stacktrace: logr.Error}
	target := test.NewSlowTarget(buf, 2)
	lgr, _ := logr.New()
	err := lgr.AddTarget(target, "shutdownTest", filter, formatter, 3000)
	require.NoError(t, err)

	cfg := test.DoSomeLoggingCfg{
		Lgr:        lgr,
		Goroutines: 20,
		Loops:      100,
		Lvl:        logr.Error,
	}
	test.DoSomeLogging(cfg)

	err = lgr.Shutdown()
	require.NoError(t, err)

	// Should NOP since shutdown already called. Shouldn't crash.
	logger := lgr.NewLogger().With(logr.String("test", "yes"))
	logger.Info("This shouldn't get logged")

	// Second shutdown should error, but not crash.
	err = lgr.Shutdown()
	require.Error(t, err)

	output := buf.String()
	if strings.Contains(output, "This shouldn't get logged") {
		t.Errorf("log record should not appear after shutdown")
	}
}

func TestRemoveTarget(t *testing.T) {
	formatter := &formatters.Plain{DisableTimestamp: true, Delim: " | "}
	filter := &logr.StdFilter{Lvl: logr.Info, Stacktrace: logr.Error}
	lgr, _ := logr.New()

	buf1 := &bytes.Buffer{}
	target1 := test.NewSlowTarget(buf1, 2)
	err := lgr.AddTarget(target1, "t1", filter, formatter, 3000)
	require.NoError(t, err)

	buf2 := &bytes.Buffer{}
	target2 := test.NewSlowTarget(buf2, 2)
	err = lgr.AddTarget(target2, "t2", filter, formatter, 3000)
	require.NoError(t, err)

	cfg := test.DoSomeLoggingCfg{
		Lgr:        lgr,
		Goroutines: 20,
		Loops:      100,
		Lvl:        logr.Error,
	}
	test.DoSomeLogging(cfg)

	err = lgr.RemoveTargets(context.Background(), func(ti logr.TargetInfo) bool {
		return ti.Name == "t2"
	})
	assert.NoError(t, err)

	tarr := lgr.TargetInfos()
	assert.Len(t, tarr, 1)
	assert.Equal(t, tarr[0].Name, "t1")

	err = lgr.Shutdown()
	if err != nil {
		t.Error(err)
	}
}


text:
// Copyright 2017 Xiaomi, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// 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 main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"syscall"

	"github.com/lxlee1102/falcon-data-reentry/funcs"
	"github.com/lxlee1102/falcon-data-reentry/g"
)

func SetMaxFilefds(n uint64) (err error) {
	var rLimit syscall.Rlimit
	err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
	if err != nil {
		log.Println("Error Getting Rlimit ", err)
		return
	}
	rLimit.Max = n
	rLimit.Cur = n
	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
	if err != nil {
		log.Println("Error Setting Rlimit ", err)
		return
	}

	log.Println("Setrlimit:", n)
	return
}

func main() {

	g.BinaryName = BinaryName
	g.Version = Version
	g.GitCommit = GitCommit

	cfg := flag.String("c", "cfg.json", "configuration file")
	version := flag.Bool("v", false, "show version")

	flag.Parse()

	if *version {
		fmt.Printf("v%s-%s", Version, GitCommit)
		os.Exit(0)
	}

	g.ParseConfig(*cfg)

	if g.Config().Debug {
		g.InitLog("debug")
	} else {
		g.InitLog("info")
	}

	err := SetMaxFilefds(g.Config().MaxFiles)
	if err != nil {
		return
	}

	go funcs.WorkRun()

	select {}

}


text:
package main

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"github.com/Girbons/comics-downloader/cmd/app"
)

var (
	release   string // sha1 revision used to build the program
	buildTime string // when the executable was built
)

func main() {
	url := flag.String("url", "", "Comic URL or Comic URLS by separating each site with a comma without the use of spaces")
	format := flag.String("format", "pdf", "Comic format output, supported formats are pdf,epub,cbr,cbz")
	country := flag.String("country", "", "Set the country to retrieve a manga, Used by MangaRock")
	versionFlag := flag.Bool("version", false, "Display the release")
	all := flag.Bool("all", false, "Download all issues of the Comic or Comics")
	last := flag.Bool("last", false, "Download the last Comic issue")
	flag.Parse()

	if *versionFlag {
		fmt.Printf("Built on %s from release %s\n", buildTime, release)
		os.Exit(0)
	}

	// is this the best way?
	if *url == "" {
		for _, v := range flag.Args() {
			if !strings.HasPrefix(v, "-") || !strings.HasPrefix(v, "--") {
				if strings.HasPrefix(v, "http") || strings.HasPrefix(v, "https") {
					*url = *url + fmt.Sprintf("%s,", v)
				}
			}
		}
	}

	app.Run(*url, *format, *country, *all, *last, false)
}

repository: CorentinB/comics-downloader

repo_name: CorentinB/comics-downloader


text:
@inproceedings{su2016learning,
  title={Learning to switch between sensorimotor primitives using multimodal haptic signals},
  author={Su, Zhe and Kroemer, Oliver and Loeb, Gerald E and Sukhatme, Gaurav S and Schaal, Stefan},
  booktitle={International Conference on Simulation of Adaptive Behavior},
  pages={170--182},
  year={2016},
  organization={Springer}
}


text:
include(${CMAKE_TOOLCHAIN_FILE})
include(cpp_unit_test_helpers)
_cpp_setup_test_env("cache_sanitize_version")

_cpp_add_test(
TITLE "User provided version"
CONTENTS
    "include(cache/cache_sanitize_version)"
    "_cpp_cache_sanitize_version(output 1.0)"
    "_cpp_assert_equal(\${output} \"1.0\")"
)

_cpp_add_test(
TITLE "No version"
CONTENTS
    "include(cache/cache_sanitize_version)"
    "_cpp_cache_sanitize_version(output \"\")"
    "_cpp_assert_equal(\${output} \"latest\")"
)

repository: keipertk/CMakePackagingProject

repo_name: keipertk/CMakePackagingProject

extension: cmake