text:
package geocoder

import (
	"bytes"
	"context"
	"errors"
	"io/ioutil"
	"net/http"
	"reflect"
	"sync"
	"testing"
	"time"
)

type fakeHttpRequester struct {
	responseBodyJSON string
	err              error
}

func (c *fakeHttpRequester) Get(targetURL string) (*http.Response, error) {
	r := ioutil.NopCloser(bytes.NewReader([]byte(c.responseBodyJSON)))
	return &http.Response{Body: r}, c.err
}

type fakeRequestObserver struct{}

func (c *fakeRequestObserver) ObserveHTTPRequest(label string, duration time.Duration) {}

func Test_SignRequest(t *testing.T) {
	tests := []struct {
		name              string
		BusinessKey       *BusinessKey
		URL               string
		Language          string
		client            *fakeHttpRequester
		expectedSignature string
		expectedError     error
	}{
		{
			"Test Signing",
			&BusinessKey{ClientID: "my_test_client", SigningKey: "bXlfdGVzdF9rZXk=", Channel: "grg-local"},
			"/maps/api/geocode/xml?latlng=49.17584440,7.30196070&sensor=false&client=my_test_client&channel=grg-local",
			"en",
			&fakeHttpRequester{},
			"fGNFKf3Yt6Syb9dRF42E7vm1FwM=",
			nil,
		},
		{
			"Test Signing 1",
			&BusinessKey{ClientID: "my_test_client", SigningKey: "bXlfdGVzdF9rZXk=", Channel: "grg-local"},
			"/maps/api/geocode/json?channel=grg-local&client=my_test_client&language=en&latlng=45.32000000%2C12.67000000&sensor=false",
			"en",
			&fakeHttpRequester{},
			"bdwh-bmlibC2w2N_A2tgt7pSuAE=",
			nil,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Log(tt.name)

			geocoder, _ := NewGeocoder(tt.BusinessKey, tt.URL, tt.Language, tt.client, 10, time.Second, &fakeRequestObserver{})
			res, err := geocoder.getSignature(tt.URL)

			if res != tt.expectedSignature {
				t.Errorf("test for %v Failed - results not match\nGot:\n%v\nExpected:\n%v", tt.name, res, tt.expectedSignature)
			}

			if err != nil && tt.expectedError != nil && tt.expectedError.Error() != err.Error() {
				t.Errorf("test for %v Failed - results not match\nGot:\n%v\nExpected:\n%v", tt.name, err, tt.expectedError)
			}
		})
	}
}

func Test_ReverseGeocode(t *testing.T) {
	tests := []struct {
		name                   string
		BusinessKey            *BusinessKey
		URL                    string
		Language               string
		client                 *fakeHttpRequester
		overQueryLimitDuration time.Duration
		expectedResponse       *GoogleResponse
		expectedError          error
	}{
		{
			"Should return error on parsing failure",
			&BusinessKey{ClientID: "my_test_client", SigningKey: "bXlfdGVzdF9rZXk=", Channel: "grg-local"},
			"https://maps.googleapis.com/maps/api/geocode/json",
			"en",
			&fakeHttpRequester{responseBodyJSON: "", err: errors.New("failed")},
			time.Nanosecond,
			nil,
			errors.New("failed"),
		},
		{
			"Should return OVER_QUERY_LIMIT",
			&BusinessKey{ClientID: "my_test_client", SigningKey: "bXlfdGVzdF9rZXk=", Channel: "grg-local"},
			"https://maps.googleapis.com/maps/api/geocode/json",
			"en",
			&fakeHttpRequester{responseBodyJSON: `{"status":"OVER_QUERY_LIMIT"}`},
			time.Millisecond * 100,
			&GoogleResponse{Status: GRS_OVER_QUERY_LIMIT},
			nil,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Log(tt.name)

			geocoder, _ := NewGeocoder(tt.BusinessKey, tt.URL, tt.Language, tt.client, 5, tt.overQueryLimitDuration, nil)
			var wg sync.WaitGroup

			for i := 0; i < 5; i++ {
				wg.Add(1)
				go func() {
					defer wg.Done()
					now := time.Now()
					res, err := geocoder.ReverseGeocode(context.TODO(), 49.17584440, 7.30196070)

					if tt.overQueryLimitDuration > time.Nanosecond && -time.Until(now) <= tt.overQueryLimitDuration {
						t.Errorf("test for %v Failed - test took less time than expected\nGot:\n%v\nExpected:\n%v", tt.name, -time.Until(now), tt.overQueryLimitDuration)
					}
					if !reflect.DeepEqual(res, tt.expectedResponse) {
						t.Errorf("test for %v Failed - results not match\nGot:\n%v\nExpected:\n%v", tt.name, res, tt.expectedResponse)
					}

					if err != nil && tt.expectedError != nil && tt.expectedError.Error() != err.Error() {
						t.Errorf("test for %v Failed - results not match\nGot:\n%v\nExpected:\n%v", tt.name, err, tt.expectedError)
					}
				}()
			}
			wg.Wait()
		})
	}
}

func Test_buildURL(t *testing.T) {
	tests := []struct {
		name          string
		BusinessKey   *BusinessKey
		URL           string
		Language      string
		client        *fakeHttpRequester
		lat           float64
		lng           float64
		expectedURL   string
		expectedError error
	}{
		{
			"Should build url",
			&BusinessKey{ClientID: "my_test_client", SigningKey: "bXlfdGVzdF9rZXk=", Channel: "grg-local"},
			"https://maps.googleapis.com/maps/api/geocode/json",
			"en",
			&fakeHttpRequester{},
			45.32,
			12.67,
			"https://maps.googleapis.com/maps/api/geocode/json?channel=grg-local&client=my_test_client&language=en&latlng=45.32000000%2C12.67000000&sensor=false&signature=bdwh-bmlibC2w2N_A2tgt7pSuAE%3D",
			nil,
		},
		{
			"Should build escaped url",
			&BusinessKey{ClientID: "my&test&client", SigningKey: "bXlfdGVzdF9rZXk=", Channel: "grg-local!@#$%^&*() "},
			"https://maps.googleapis.com/maps/api/geocode/json",
			"en",
			&fakeHttpRequester{},
			45.32,
			12.67,
			"https://maps.googleapis.com/maps/api/geocode/json?channel=grg-local%21%40%23%24%25%5E%26%2A%28%29+&client=my%26test%26client&language=en&latlng=45.32000000%2C12.67000000&sensor=false&signature=Ui0NkXF9aJEZHtjQ-H1-V333LUk%3D",
			nil,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Log(tt.name)

			geocoder, _ := NewGeocoder(tt.BusinessKey, tt.URL, tt.Language, tt.client, 10, time.Second, &fakeRequestObserver{})
			res, err := geocoder.buildURL(tt.lat, tt.lng)

			if res.String() != tt.expectedURL {
				t.Errorf("test for %v Failed - results not match\nGot:\n%v\nExpected:\n%v", tt.name, res.String(), tt.expectedURL)
			}

			if err != nil && tt.expectedError != nil && tt.expectedError.Error() != err.Error() {
				t.Errorf("test for %v Failed - results not match\nGot:\n%v\nExpected:\n%v", tt.name, err, tt.expectedError)
			}
		})
	}
}

repository: alvillain/geocoder

repo_name: alvillain/geocoder


text:
@INPROCEEDINGS{6951528,
  author={S. {Barra} and A. {Casanova} and M. {De Marsico} and D. {Riccio}},
  booktitle={2014 IEEE Workshop on Biometric Measurements and Systems for Security and Medical Applications (BIOMS) Proceedings},
  title={Babies: Biometric authentication of newborn identities by means of ear signatures},
  year={2014},
  volume={},
  number={},
  pages={1-7},
  abstract={Many research studies demonstrated that recognition based on ear biometrics offers an accuracy which is comparable to face trait, especially in controlled settings. Our proposal is to exploit it to avoid the problem of newborn swap, which is possible and actually happens, most of all in crowded maternity wards of big hospitals. We tested the viability of this solution using a dataset of ear images of newborns, and the obtained results testify that it is possible to decrease the probability of an error using this technique.},
  keywords={biometrics (access control);ear;image processing;probability;BABIES;biometric authentication;newborn identities;ear signatures;ear biometrics;newborn swap;ear images;probability;Ear;Pediatrics;Shape;DNA;Fingerprint recognition;Training;Image recognition;newborn swap;ear biometrics},
  doi={10.1109/BIOMS.2014.6951528},
  ISSN={},
  month={Oct},}

license: MIT

license_type: permissive

branch_name: refs/heads/master

extension: bib


text:
@InProceedings{Simon15a,
  author = {Simon, Hans U.},
  title = {An Almost Optimal PAC Algorithm},
  pages = {1552-1563},
  abstract = {The best currently known general lower and upper bounds on the number
of labeled examples needed for learning a concept class in the PAC
framework (the realizable case) do not perfectly match: they leave a gap
of order $\log(1/\epsilon)$ (resp.~a gap which is logarithmic in another
one of the relevant parameters). It is an unresolved question whether
there exists an ``optimal PAC algorithm'' which establishes a general
upper bound with precisely the same order of magnitude as the general
lower bound. According to a result of Auer and Ortner, there is no way
for showing that arbitrary consistent algorithms are optimal because
they can provably differ from optimality by factor $\log(1/\epsilon)$.
In contrast to this result, we show that every consistent algorithm $L$
(even a provably suboptimal one) induces a family $(L_K)_{K\ge1}$ of
PAC algorithms (with $2K-1$ calls of $L$ as a subroutine) which come
very close to optimality: the number of labeled examples needed by $L_K$
exceeds the general lower bound only by factor $\ell_K(1/\epsillon)$
where $\ell_K$ denotes (a truncated version of) the $K$-times
iterated logarithm. Moreover, $L_K$ is applicable to any concept
class $C$ of finite VC-dimension and it can be implemented efficiently
whenever the consistency problem for $C$ is feasible. We show furthermore
that, for every consistent algorithm $L$, $L_2$ is an optimal PAC
algorithm for precisely the same concept classes which were used
by Auer and Ortner for showing the existence of suboptimal consistent
algorithms.  This can be seen as an indication that $L_K$ may have an
even better performance than it is suggested by our worstcase analysis.},
}

repository: mreid/papersite

repo_name: mreid/papersite

gha_license_id: MIT

gha_language: TeX


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"time"

	eosws "github.com/dfuse-io/eosws-go"
)

func main() {
	flag.Parse()

	COUNT := 1

	for i := 0; i < COUNT; i++ {
		j := i
		go func() {
			// client, err := eosws.New("ws://localhost:8001/v1/stream", os.Getenv("EOSWS_API_KEY"), "https://origin.example.com")
			client, err := eosws.New("wss://mainnet.eos.dfuse.io/v1/stream", os.Getenv("EOSWS_API_KEY"), "https://origin.example.com")
			//client, err := eosws.New("wss://kylin.eos.dfuse.io/v1/stream", os.Getenv("EOSWS_API_KEY"), "https://origin.example.com")
			errorCheck("connecting to endpoint", err)

			ga := &eosws.GetActionTraces{}
			ga.ReqID = "foo GetActions"
			ga.StartBlock = -10
			ga.Listen = true
			ga.WithProgress = 5
			ga.Data.Accounts = "eosio.token"
			ga.Data.ActionNames = "transfer"
			ga.Data.WithInlineTraces = true

			fmt.Println("Sending `get_actions` message")
			err = client.Send(ga)
			errorCheck("sending get_actions", err)

			for {
				msg, err := client.Read()
				if err != nil {
					fmt.Println("DIED", j, err)
					return
				}

				switch m := msg.(type) {
				case *eosws.ActionTrace:
					cnt, _ := json.Marshal(m)
					fmt.Println(string(cnt))
				case *eosws.Progress:
					fmt.Println("Progress", j, m.Data.BlockNum)
				default:
					fmt.Println("Unsupported message", m)
				}
			}
		}()
	}

	time.Sleep(500 * time.Second)
}

func errorCheck(prefix string, err error) {
	if err != nil {
		fmt.Printf("ERROR: %s: %s\n", prefix, err)
		os.Exit(1)
	}
}

repository: mwawrusch/eosws-go

repo_name: mwawrusch/eosws-go

gha_language: Go

extension: go


text:
function(lep_output_status msg)
  message(STATUS "${msg}")
endfunction()

# Status report function.
# Automatically align right column and selects text based on condition.
# Usage:
#   status(<text>)
#   status(<heading> <value1> [<value2> ...])
#   status(<heading> <condition> THEN <text for TRUE> ELSE <text for FALSE> )
function(status text)
  set(status_cond)
  set(status_then)
  set(status_else)

  set(status_current_name "cond")
  foreach(arg ${ARGN})
    if(arg STREQUAL "THEN")
      set(status_current_name "then")
    elseif(arg STREQUAL "ELSE")
      set(status_current_name "else")
    else()
      list(APPEND status_${status_current_name} ${arg})
    endif()
  endforeach()

  if(DEFINED status_cond)
    set(status_placeholder_length 32)
    string(RANDOM LENGTH ${status_placeholder_length} ALPHABET " " status_placeholder)
    string(LENGTH "${text}" status_text_length)
    if(status_text_length LESS status_placeholder_length)
      string(SUBSTRING "${text}${status_placeholder}" 0 ${status_placeholder_length} status_text)
    elseif(DEFINED status_then OR DEFINED status_else)
      lep_output_status("${text}")
      set(status_text "${status_placeholder}")
    else()
      set(status_text "${text}")
    endif()

    if(DEFINED status_then OR DEFINED status_else)
      if(${status_cond})
        string(REPLACE ";" " " status_then "${status_then}")
        string(REGEX REPLACE "^[ \t]+" "" status_then "${status_then}")
        lep_output_status("${status_text} ${status_then}")
      else()
        string(REPLACE ";" " " status_else "${status_else}")
        string(REGEX REPLACE "^[ \t]+" "" status_else "${status_else}")
        lep_output_status("${status_text} ${status_else}")
      endif()
    else()
      string(REPLACE ";" " " status_cond "${status_cond}")
      string(REGEX REPLACE "^[ \t]+" "" status_cond "${status_cond}")
      lep_output_status("${status_text} ${status_cond}")
    endif()
  else()
    lep_output_status("${text}")
  endif()
endfunction()

include(CMakeParseArguments)

# Debugging function
function(lep_cmake_dump_vars)
  set(VARS "")
  get_cmake_property(_variableNames VARIABLES)
  cmake_parse_arguments(DUMP "" "TOFILE" "" ${ARGN})
  set(regex "${DUMP_UNPARSED_ARGUMENTS}")
  string(TOLOWER "${regex}" regex_lower)
  foreach(_variableName ${_variableNames})
    string(TOLOWER "${_variableName}" _variableName_lower)
    if(_variableName MATCHES "${regex}" OR _variableName_lower MATCHES "${regex_lower}")
      set(VARS "${VARS}${_variableName}=${${_variableName}}\n")
    endif()
  endforeach()
  if(DUMP_TOFILE)
    file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/${DUMP_TOFILE} "${VARS}")
  else()
    message(AUTHOR_WARNING "${VARS}")
  endif()
endfunction()

repository: PubFork/tesseract-android-lib

repo_name: PubFork/tesseract-android-lib

extension: cmake


text:
if (64bit_build)
  set(tbb_archdir intel64)
else ()
  set(tbb_archdir ia32)
endif ()

set(tbb_libdir lib/${tbb_archdir}/gcc4.7)
set(tbb_libsuffix "${CMAKE_SHARED_LIBRARY_SUFFIX}*")
include(tbb.common)

repository: OpenChemistry/tomviz-superbuild

repo_name: OpenChemistry/tomviz-superbuild

gha_language: Shell


text:
package mongo

import (
	"context"
	"log"
	"sync"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"github.com/sk000f/metrix/pkg/collector"
)

var mongoOnce sync.Once
var clientInstance *mongo.Client
var clientInstanceError error

// DB represents a MongoDB client
type DB struct {
	ConnStr string
}

// SaveProjects saves Projects into the MongoDB database
func (m *DB) SaveProjects(p []*collector.Project) {
	for _, proj := range p {
		mP := Project{
			ProjectID:         proj.ID,
			Name:              proj.Name,
			Path:              proj.Path,
			PathWithNamespace: proj.PathWithNamespace,
			Namespace:         proj.Namespace,
			WebURL:            proj.WebURL,
		}

		m.UpdateProject(mP)
	}
}

// SaveDeployment saves a Deployment into the MongoDB database
func (m *DB) SaveDeployment(d *collector.Deployment) {
	mD := Deployment{
		DeploymentID:     d.ID,
		Status:           d.Status,
		EnvironmentName:  d.EnvironmentName,
		ProjectID:        d.ProjectID,
		ProjectName:      d.ProjectName,
		ProjectPath:      d.ProjectPath,
		ProjectNamespace: d.ProjectNamespace,
		PipelineID:       d.PipelineID,
		FinishedAt:       d.FinishedAt,
		Duration:         d.Duration,
	}
	m.UpdateDeployment(mD)
}

// Project represents metrix view of a project object
type Project struct {
	ID                primitive.ObjectID `bson:"_id"`
	ProjectID         int                `bson:"project_id"`
	Name              string             `bson:"name"`
	Path              string             `bson:"path"`
	PathWithNamespace string             `bson:"path_with_namespace"`
	Namespace         string             `bson:"namespace"`
	WebURL            string             `bson:"web_url"`
	GroupName         string             `bson:"group_name"`
}

// Deployment represents metrix view of a deployment object
type Deployment struct {
	ID               primitive.ObjectID `bson:"_id"`
	DeploymentID     int                `bson:"deployment_id"`
	Status           string             `bson:"status"`
	EnvironmentName  string             `bson:"envrionment_name"`
	ProjectID        int                `bson:"project_id"`
	ProjectName      string             `bson:"project_name"`
	ProjectPath      string             `bson:"project_path"`
	ProjectNamespace string             `bson:"project_namespace"`
	PipelineID       int                `bson:"pipeline_id"`
	FinishedAt       *time.Time         `bson:"finished_at"`
	Duration         float64            `bson:"duration"`
}

// UpdateProject adds or updates the specified project in the MongoDB database
func (m *DB) UpdateProject(p Project) {

	c, err := m.GetMongoClient()
	if err != nil {
		log.Fatal(err)
	}

	collection := c.Database("metrix").Collection("projects")

	filter := bson.M{"project_id": p.ProjectID}
	updateOpts := options.Update().SetUpsert(true)

	update := bson.M{
		"$set": bson.M{
			"project_id":          p.ProjectID,
			"name":                p.Name,
			"path":                p.Path,
			"path_with_namespace": p.PathWithNamespace,
			"namespace":           p.Namespace,
			"web_url":             p.WebURL,
		},
	}
	_, err = collection.UpdateOne(context.TODO(), filter, update, updateOpts)
	if err != nil {
		log.Fatalf("Error updating Project: %v", err.Error())
	}
}

// UpdateDeployment adds or updates the specified deployment in the MongoDB database
func (m *DB) UpdateDeployment(d Deployment) {

	c, err := m.GetMongoClient()
	if err != nil {
		log.Fatal(err)
	}

	collection := c.Database("metrix").Collection("deployments")

	filter := bson.M{"deployment_id": d.DeploymentID}
	updateOpts := options.Update().SetUpsert(true)

	update := bson.M{
		"$set": bson.M{
			"deployment_id":     d.DeploymentID,
			"status":            d.Status,
			"environment_name":  d.EnvironmentName,
			"project_id":        d.ProjectID,
			"project_name":      d.ProjectName,
			"project_path":      d.ProjectPath,
			"project_namespace": d.ProjectNamespace,
			"pipeline_id":       d.PipelineID,
			"finished_at":       d.FinishedAt,
			"duration":          d.Duration,
		},
	}
	_, err = collection.UpdateOne(context.TODO(), filter, update, updateOpts)
	if err != nil {
		log.Fatalf("Error updating Deployment: %v", err.Error())
	}
}

// GetMongoClient creates or returns existing MongoDB client
func (m *DB) GetMongoClient() (*mongo.Client, error) {

	mongoOnce.Do(func() {

		clientOptions := options.Client().ApplyURI(m.ConnStr)

		client, err := mongo.Connect(context.TODO(), clientOptions)
		if err != nil {
			log.Fatal(err)
			clientInstanceError = err
		}

		clientInstance = client
	})

	return clientInstance, clientInstanceError
}

branch_name: refs/heads/main


text:
/*
Copyright IBM Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package blocksprovider

import (
	"math"
	"sync/atomic"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/mcc-github/blockchain-protos-go/common"
	gossip_proto "github.com/mcc-github/blockchain-protos-go/gossip"
	"github.com/mcc-github/blockchain-protos-go/orderer"
	"github.com/mcc-github/blockchain/common/flogging"
	"github.com/mcc-github/blockchain/gossip/api"
	gossipcommon "github.com/mcc-github/blockchain/gossip/common"
	"github.com/mcc-github/blockchain/gossip/discovery"
	"github.com/mcc-github/blockchain/gossip/util"
)

type LedgerInfo interface {

	LedgerHeight() (uint64, error)
}

type GossipServiceAdapter interface {

	PeersOfChannel(gossipcommon.ChannelID) []discovery.NetworkMember

	AddPayload(chainID string, payload *gossip_proto.Payload) error

	Gossip(msg *gossip_proto.GossipMessage)
}

type BlocksProvider interface {

	DeliverBlocks()

	UpdateOrderingEndpoints(endpoints []string)

	Stop()
}

type BlocksDeliverer interface {

	Recv() (*orderer.DeliverResponse, error)

	Send(*common.Envelope) error
}

type streamClient interface {
	BlocksDeliverer

	UpdateEndpoints(endpoints []string)

	GetEndpoints() []string

	Close()

	Disconnect()
}

type blocksProviderImpl struct {
	chainID string

	client streamClient

	gossip GossipServiceAdapter

	mcs api.MessageCryptoService

	done int32

	wrongStatusThreshold int
}

const wrongStatusThreshold = 10

var maxRetryDelay = time.Second * 10
var logger = flogging.MustGetLogger("blocksProvider")

func NewBlocksProvider(chainID string, client streamClient, gossip GossipServiceAdapter, mcs api.MessageCryptoService) BlocksProvider {
	return &blocksProviderImpl{
		chainID:              chainID,
		client:               client,
		gossip:               gossip,
		mcs:                  mcs,
		wrongStatusThreshold: wrongStatusThreshold,
	}
}

func (b *blocksProviderImpl) DeliverBlocks() {
	errorStatusCounter := 0
	statusCounter := 0
	defer b.client.Close()
	for !b.isDone() {
		msg, err := b.client.Recv()
		if err != nil {
			logger.Warningf("[%s] Receive error: %s", b.chainID, err.Error())
			return
		}
		switch t := msg.Type.(type) {
		case *orderer.DeliverResponse_Status:
			if t.Status == common.Status_SUCCESS {
				logger.Warningf("[%s] ERROR! Received success for a seek that should never complete", b.chainID)
				return
			}
			if t.Status == common.Status_BAD_REQUEST || t.Status == common.Status_FORBIDDEN {
				logger.Errorf("[%s] Got error %v", b.chainID, t)
				errorStatusCounter++
				if errorStatusCounter > b.wrongStatusThreshold {
					logger.Criticalf("[%s] Wrong statuses threshold passed, stopping block provider", b.chainID)
					return
				}
			} else {
				errorStatusCounter = 0
				logger.Warningf("[%s] Got error %v", b.chainID, t)
			}
			maxDelay := float64(maxRetryDelay)
			currDelay := float64(time.Duration(math.Pow(2, float64(statusCounter))) * 100 * time.Millisecond)
			time.Sleep(time.Duration(math.Min(maxDelay, currDelay)))
			if currDelay < maxDelay {
				statusCounter++
			}
			b.client.Disconnect()
			continue
		case *orderer.DeliverResponse_Block:
			errorStatusCounter = 0
			statusCounter = 0
			blockNum := t.Block.Header.Number

			if err := b.mcs.VerifyBlock(gossipcommon.ChannelID(b.chainID), blockNum, t.Block); err != nil {
				logger.Errorf("[%s] Error verifying block with sequnce number %d, due to %s", b.chainID, blockNum, err)
				continue
			}

			marshaledBlock, err := proto.Marshal(t.Block)
			if err != nil {
				logger.Errorf("[%s] Error serializing block with sequence number %d, due to %s", b.chainID, blockNum, err)
				continue
			}

			numberOfPeers := len(b.gossip.PeersOfChannel(gossipcommon.ChannelID(b.chainID)))

			payload := createPayload(blockNum, marshaledBlock)

			gossipMsg := createGossipMsg(b.chainID, payload)

			logger.Debugf("[%s] Adding payload to local buffer, blockNum = [%d]", b.chainID, blockNum)

			if err := b.gossip.AddPayload(b.chainID, payload); err != nil {
				logger.Warningf("Block [%d] received from ordering service wasn't added to payload buffer: %v", blockNum, err)
			}

			logger.Debugf("[%s] Gossiping block [%d], peers number [%d]", b.chainID, blockNum, numberOfPeers)
			if !b.isDone() {
				b.gossip.Gossip(gossipMsg)
			}
		default:
			logger.Warningf("[%s] Received unknown: %v", b.chainID, t)
			return
		}
	}
}

func (b *blocksProviderImpl) Stop() {
	atomic.StoreInt32(&b.done, 1)
	b.client.Close()
}

func (b *blocksProviderImpl) UpdateOrderingEndpoints(endpoints []string) {
	if !b.areEndpointsUpdated(endpoints) {

		return
	}

	logger.Debug("Updating endpoint, to %s", endpoints)
	b.client.UpdateEndpoints(endpoints)
	logger.Debug("Disconnecting so endpoints update will take effect")

	b.client.Disconnect()
}

func (b *blocksProviderImpl) areEndpointsUpdated(endpoints []string) bool {
	if len(endpoints) != len(b.client.GetEndpoints()) {
		return true
	}

	for _, endpoint := range endpoints {
		if !util.Contains(endpoint, b.client.GetEndpoints()) {

			return true
		}
	}

	return false
}

func (b *blocksProviderImpl) isDone() bool {
	return atomic.LoadInt32(&b.done) == 1
}

func createGossipMsg(chainID string, payload *gossip_proto.Payload) *gossip_proto.GossipMessage {
	gossipMsg := &gossip_proto.GossipMessage{
		Nonce:   0,
		Tag:     gossip_proto.GossipMessage_CHAN_AND_ORG,
		Channel: []byte(chainID),
		Content: &gossip_proto.GossipMessage_DataMsg{
			DataMsg: &gossip_proto.DataMessage{
				Payload: payload,
			},
		},
	}
	return gossipMsg
}

func createPayload(seqNum uint64, marshaledBlock []byte) *gossip_proto.Payload {
	return &gossip_proto.Payload{
		Data:   marshaledBlock,
		SeqNum: seqNum,
	}
}

repository: ubi-iot/blockchain

repo_name: ubi-iot/blockchain


text:
SUMMARY = "pure-python library for parsing ELF and DWARF"
HOMEPAGE = "https://github.com/eliben/pyelftools"
SECTION = "devel/python"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://LICENSE;md5=5ce2a2b07fca326bc7c146d10105ccfc"

LICENSE = "unlicense"
NO_GENERIC_LICENSE[unlicense] = "LICENCE"
LICENSE_${PN} = "unlicense"

PV = "0.25"

SRC_URI[md5sum] = "c5629b9a5d19c82107a946cce52eeec2"
SRC_URI[sha256sum] = "89c6da6f56280c37a5ff33468591ba9a124e17d71fe42de971818cbff46c1b24"

inherit pypi
inherit setuptools3

BBCLASSEXTEND = "native nativesdk"

repository: Linaro/meta-ledge

repo_name: Linaro/meta-ledge

branch_name: refs/heads/hardknott

extension: bb


text:
@inproceedings{recht2019imagenet,
  title={Do ImageNet Classifiers Generalize to ImageNet?},
  author={Recht, Benjamin and Roelofs, Rebecca and Schmidt, Ludwig and Shankar, Vaishaal},
  booktitle={International Conference on Machine Learning},
  pages={5389--5400},
  year={2019}
}

repository: tensorflow/datasets

repo_name: tensorflow/datasets

gha_language: Python


text:
package commands

import (
	"fmt"

	"github.com/hashicorp/gaudit/config"
	"github.com/hashicorp/gaudit/state"
)

func Results(options config.Options) {

	// get latest audit
	audit, err := state.Load(options.Storage)
	if err != nil {
		fmt.Println("ERROR: " + err.Error())
	}

	// output
	for _, r := range audit.Index {
		repo := audit.Repos[r]
		fmt.Println(repo.FullName)
		for _, rule := range audit.Results[r].Rules {
			if rule.Status == "error" || options.Args["verbose"] == "true" {
				fmt.Println("  [" + rule.Status + "] " + rule.Name)
			}
		}
	}

}

repository: Urs-Bruelhart/gaudit

repo_name: Urs-Bruelhart/gaudit


text:
package server

import (
	"io"
	"log"
	"net/http"
	"time"

	"github.com/gorilla/mux"
	"github.com/image-server/image-server/core"
	mantajob "github.com/image-server/image-server/job/manta"
	"github.com/image-server/image-server/logger"
	"github.com/image-server/image-server/uploader/manta/client"
	"github.com/unrolled/render"
)

func CreateBatchHandler(w http.ResponseWriter, req *http.Request, sc *core.ServerConfiguration) {
	defer logger.RequestLatency("create_batch", time.Now())

	vars := mux.Vars(req)
	namespace := vars["namespace"]

	r := render.New(render.Options{
		IndentJSON: true,
	})

	job, err := mantajob.CreateJob(sc.Outputs, sc.RemoteBasePath, namespace, req.Body)
	if err != nil {
		errorHandlerJSON(err, w, http.StatusInternalServerError)
		return
	}

	json := map[string]string{
		"job_id": job.JobID,
	}

	r.JSON(w, http.StatusOK, json)

	go job.AddInputs()
}

func BatchHandler(w http.ResponseWriter, req *http.Request, sc *core.ServerConfiguration) {
	defer logger.RequestLatency("batch", time.Now())

	vars := mux.Vars(req)
	uuid := vars["uuid"]

	mantaClient := client.DefaultClient()
	job, err := mantaClient.GetJob(uuid)

	if err != nil {
		log.Println(err)
		errorHandler(err, w, req, 500)
		return
	}

	if job.State == "done" {
		result, err := getJobOutput(uuid, mantaClient)
		if err != nil {
			log.Println(err)
			errorHandler(err, w, req, 500)
			return
		}

		w.WriteHeader(200)
		io.Copy(w, result)
	} else {
		// If not complete, return job details and 202
		r := render.New(render.Options{
			IndentJSON: true,
		})

		r.JSON(w, 202, job)
	}
}

func getJobOutput(uuid string, mantaClient *client.Client) (io.Reader, error) {
	output, err := mantaClient.GetJobOutput(uuid)
	if err != nil {
		return nil, err
	}

	result, err := mantaClient.GetObject(output)
	if err != nil {
		return nil, err
	}

	return result, nil
}

repository: image-server/image-server

repo_name: image-server/image-server


text:
DESCRIPTION = "Set various aspects of Philips (and compatible) WebCams."
SECTION = "console"
PRIORITY = "optional"
HOMEPAGE = "http://www.vanheusden.com/setpwc/"
LICENSE = "GPL"
PR = "r0"

SRC_URI = "http://www.vanheusden.com/setpwc/setpwc-${PV}.tgz"

TARGET_CC_ARCH += " ${LDFLAGS}"

inherit autotools

INHIBIT_AUTO_STAGE = "1"

do_install() {
	install -d ${D}${bindir}
	install -m 0755 ${S}/setpwc ${D}${bindir}/setpwc
}

SRC_URI[md5sum] = "1bc721cdfcbac24027e2afc93685d29f"
SRC_URI[sha256sum] = "855dcf73bda36e6445119f0b1b0a63464ba237d82794f115912464f8aebc5ed1"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
SUMMARY = "Phosphor OpenBMC - Applications"
PR = "r1"

inherit packagegroup
inherit obmc-phosphor-utils
inherit obmc-phosphor-license

VIRTUAL-RUNTIME_obmc-phosphor-fan-ctl ?= "virtual/obmc-phosphor-fan-ctl"
VIRTUAL-RUNTIME_obmc-phosphor-sensor-ctl ?= "virtual/obmc-phosphor-sensor-ctl"
VIRTUAL-RUNTIME_obmc-phosphor-chassis-ctl ?= "virtual/obmc-phosphor-chassis-ctl"
VIRTUAL-RUNTIME_obmc-phosphor-flash-ctl ?= "virtual/obmc-phosphor-flash-ctl"

PROVIDES = "${PACKAGES}"
PACKAGES = " \
        packagegroup-obmc-phosphor-apps-extras \
        packagegroup-obmc-phosphor-apps-extrasdev \
        ${@mf_enabled("obmc-phosphor-fan-mgmt", "packagegroup-obmc-phosphor-apps-fan-mgmt", d)} \
        ${@mf_enabled("obmc-phosphor-chassis-mgmt", "packagegroup-obmc-phosphor-apps-chassis-mgmt", d)} \
        ${@mf_enabled("obmc-phosphor-sensor-mgmt", "packagegroup-obmc-phosphor-apps-sensor-mgmt", d)} \
        ${@mf_enabled("obmc-phosphor-flash-mgmt", "packagegroup-obmc-phosphor-apps-flash-mgmt", d)} \
        ${@df_enabled("obmc-phosphor-event-mgmt", "packagegroup-obmc-phosphor-apps-event-mgmt", d)} \
        ${@df_enabled("obmc-phosphor-policy-mgmt", "packagegroup-obmc-phosphor-apps-policy-mgmt", d)} \
        ${@df_enabled("obmc-phosphor-user-mgmt", "packagegroup-obmc-phosphor-apps-user-mgmt", d)} \
        ${@df_enabled("obmc-phosphor-system-mgmt", "packagegroup-obmc-phosphor-apps-system-mgmt", d)} \
        "

SUMMARY_packagegroup-obmc-phosphor-apps-extras = "Extra features"
RDEPENDS_packagegroup-obmc-phosphor-apps-extras = " \
	obmc-rest \
        host-ipmid \
        "

SUMMARY_packagegroup-obmc-phosphor-apps-extrasdev = "Development features"
RDEPENDS_packagegroup-obmc-phosphor-apps-extrasdev = " \
        rest-dbus \
        "

SUMMARY_packagegroup-obmc-phosphor-apps-fan-mgmt = "Fan management support"
RDEPENDS_packagegroup-obmc-phosphor-apps-fan-mgmt = \
        "${@cf_enabled("obmc-phosphor-fan-mgmt", " \
                virtual/obmc-phosphor-fan-mgmt \
                ${VIRTUAL-RUNTIME_obmc-phosphor-fan-ctl} \
        ", d)}"

SUMMARY_packagegroup-obmc-phosphor-apps-chassis-mgmt = "Chassis management support"
RDEPENDS_packagegroup-obmc-phosphor-apps-chassis-mgmt = "\
        ${@cf_enabled("obmc-phosphor-chassis-mgmt", " \
                virtual/obmc-phosphor-chassis-mgmt \
                ${VIRTUAL-RUNTIME_obmc-phosphor-chassis-ctl} \
        ", d)}"

SUMMARY_packagegroup-obmc-phosphor-apps-sensor-mgmt = "Sensor management support"
RDEPENDS_packagegroup-obmc-phosphor-apps-sensor-mgmt = "\
        ${@cf_enabled("obmc-phosphor-sensor-mgmt", " \
                virtual/obmc-phosphor-sensor-mgmt \
                ${VIRTUAL-RUNTIME_obmc-phosphor-sensor-ctl} \
        ", d)}"

SUMMARY_packagegroup-obmc-phosphor-apps-flash-mgmt = "Flash management support"
RDEPENDS_packagegroup-obmc-phosphor-apps-flash-mgmt = "\
        ${@cf_enabled("obmc-phosphor-flash-mgmt", " \
                virtual/obmc-phosphor-flash-mgmt \
                ${VIRTUAL-RUNTIME_obmc-phosphor-flash-ctl} \
        ", d)}"

SUMMARY_packagegroup-obmc-phosphor-apps-event-mgmt = "Event management support"
RDEPENDS_packagegroup-obmc-phosphor-apps-event-mgmt = " \
        ${@df_enabled("obmc-phosphor-event-mgmt", " \
                virtual/obmc-phosphor-event-mgmt \
        ", d)}"

SUMMARY_packagegroup-obmc-phosphor-apps-policy-mgmt = "Policy management support"
RDEPENDS_packagegroup-obmc-phosphor-apps-policy-mgmt = " \
        ${@df_enabled("obmc-phosphor-policy-mgmt", " \
                virtual/obmc-phosphor-policy-mgmt \
        ", d)}"

SUMMARY_packagegroup-obmc-phosphor-apps-user-mgmt = "User management support"
RDEPENDS_packagegroup-obmc-phosphor-apps-user-mgmt = " \
        ${@df_enabled("obmc-phosphor-user-mgmt", " \
                virtual/obmc-phosphor-user-mgmt \
        ", d)}"

SUMMARY_packagegroup-obmc-phosphor-apps-system-mgmt = "System management support"
RDEPENDS_packagegroup-obmc-phosphor-apps-system-mgmt = " \
        ${@df_enabled("obmc-phosphor-system-mgmt", " \
                virtual/obmc-phosphor-system-mgmt \
        ", d)}"


text:
/*
 * NiFi Rest Api
 *
 * The Rest Api provides programmatic access to command and control a NiFi instance in real time. Start and                                              stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description,                                             definitions of the expected input and output, potential response codes, and the authorizations required                                             to invoke each service.
 *
 * API version: 1.13.2
 * Contact: dev@nifi.apache.org
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package nifi

import (
	"bytes"
	_context "context"
	_ioutil "io/ioutil"
	_nethttp "net/http"
	_neturl "net/url"
	"strings"
)

// Linger please
var (
	_ _context.Context
)

// ProvenanceEventsApiService ProvenanceEventsApi service
type ProvenanceEventsApiService service

type ProvenanceEventsApiApiGetInputContentRequest struct {
	ctx           _context.Context
	ApiService    *ProvenanceEventsApiService
	id            string
	clusterNodeId *string
}

func (r ProvenanceEventsApiApiGetInputContentRequest) ClusterNodeId(clusterNodeId string) ProvenanceEventsApiApiGetInputContentRequest {
	r.clusterNodeId = &clusterNodeId
	return r
}

func (r ProvenanceEventsApiApiGetInputContentRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) {
	return r.ApiService.GetInputContentExecute(r)
}

/*
 * GetInputContent Gets the input content for a provenance event
 * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
 * @param id The provenance event id.
 * @return ProvenanceEventsApiApiGetInputContentRequest
 */
func (a *ProvenanceEventsApiService) GetInputContent(ctx _context.Context, id string) ProvenanceEventsApiApiGetInputContentRequest {
	return ProvenanceEventsApiApiGetInputContentRequest{
		ApiService: a,
		ctx:        ctx,
		id:         id,
	}
}

/*
 * Execute executes the request
 * @return map[string]interface{}
 */
func (a *ProvenanceEventsApiService) GetInputContentExecute(r ProvenanceEventsApiApiGetInputContentRequest) (map[string]interface{}, *_nethttp.Response, error) {
	var (
		localVarHTTPMethod   = _nethttp.MethodGet
		localVarPostBody     interface{}
		localVarFormFileName string
		localVarFileName     string
		localVarFileBytes    []byte
		localVarReturnValue  map[string]interface{}
	)

	localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProvenanceEventsApiService.GetInputContent")
	if err != nil {
		return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
	}

	localVarPath := localBasePath + "/provenance-events/{id}/content/input"
	localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", _neturl.PathEscape(parameterToString(r.id, "")), -1)

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := _neturl.Values{}
	localVarFormParams := _neturl.Values{}

	if r.clusterNodeId != nil {
		localVarQueryParams.Add("clusterNodeId", parameterToString(*r.clusterNodeId, ""))
	}
	// to determine the Content-Type header
	localVarHTTPContentTypes := []string{}

	// set Content-Type header
	localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
	if localVarHTTPContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHTTPContentType
	}

	// to determine the Accept header
	localVarHTTPHeaderAccepts := []string{"*/*"}

	// set Accept header
	localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
	if localVarHTTPHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
	}
	req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
	if err != nil {
		return localVarReturnValue, nil, err
	}

	localVarHTTPResponse, err := a.client.callAPI(req)
	if err != nil || localVarHTTPResponse == nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
	localVarHTTPResponse.Body.Close()
	localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))
	if err != nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	if localVarHTTPResponse.StatusCode >= 300 {
		newErr := GenericOpenAPIError{
			body:  localVarBody,
			error: localVarHTTPResponse.Status,
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
	if err != nil {
		newErr := GenericOpenAPIError{
			body:  localVarBody,
			error: err.Error(),
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	return localVarReturnValue, localVarHTTPResponse, nil
}

type ProvenanceEventsApiApiGetOutputContentRequest struct {
	ctx           _context.Context
	ApiService    *ProvenanceEventsApiService
	id            string
	clusterNodeId *string
}

func (r ProvenanceEventsApiApiGetOutputContentRequest) ClusterNodeId(clusterNodeId string) ProvenanceEventsApiApiGetOutputContentRequest {
	r.clusterNodeId = &clusterNodeId
	return r
}

func (r ProvenanceEventsApiApiGetOutputContentRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) {
	return r.ApiService.GetOutputContentExecute(r)
}

/*
 * GetOutputContent Gets the output content for a provenance event
 * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
 * @param id The provenance event id.
 * @return ProvenanceEventsApiApiGetOutputContentRequest
 */
func (a *ProvenanceEventsApiService) GetOutputContent(ctx _context.Context, id string) ProvenanceEventsApiApiGetOutputContentRequest {
	return ProvenanceEventsApiApiGetOutputContentRequest{
		ApiService: a,
		ctx:        ctx,
		id:         id,
	}
}

/*
 * Execute executes the request
 * @return map[string]interface{}
 */
func (a *ProvenanceEventsApiService) GetOutputContentExecute(r ProvenanceEventsApiApiGetOutputContentRequest) (map[string]interface{}, *_nethttp.Response, error) {
	var (
		localVarHTTPMethod   = _nethttp.MethodGet
		localVarPostBody     interface{}
		localVarFormFileName string
		localVarFileName     string
		localVarFileBytes    []byte
		localVarReturnValue  map[string]interface{}
	)

	localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProvenanceEventsApiService.GetOutputContent")
	if err != nil {
		return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
	}

	localVarPath := localBasePath + "/provenance-events/{id}/content/output"
	localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", _neturl.PathEscape(parameterToString(r.id, "")), -1)

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := _neturl.Values{}
	localVarFormParams := _neturl.Values{}

	if r.clusterNodeId != nil {
		localVarQueryParams.Add("clusterNodeId", parameterToString(*r.clusterNodeId, ""))
	}
	// to determine the Content-Type header
	localVarHTTPContentTypes := []string{}

	// set Content-Type header
	localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
	if localVarHTTPContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHTTPContentType
	}

	// to determine the Accept header
	localVarHTTPHeaderAccepts := []string{"*/*"}

	// set Accept header
	localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
	if localVarHTTPHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
	}
	req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
	if err != nil {
		return localVarReturnValue, nil, err
	}

	localVarHTTPResponse, err := a.client.callAPI(req)
	if err != nil || localVarHTTPResponse == nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
	localVarHTTPResponse.Body.Close()
	localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))
	if err != nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	if localVarHTTPResponse.StatusCode >= 300 {
		newErr := GenericOpenAPIError{
			body:  localVarBody,
			error: localVarHTTPResponse.Status,
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
	if err != nil {
		newErr := GenericOpenAPIError{
			body:  localVarBody,
			error: err.Error(),
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	return localVarReturnValue, localVarHTTPResponse, nil
}

type ProvenanceEventsApiApiGetProvenanceEventRequest struct {
	ctx           _context.Context
	ApiService    *ProvenanceEventsApiService
	id            string
	clusterNodeId *string
}

func (r ProvenanceEventsApiApiGetProvenanceEventRequest) ClusterNodeId(clusterNodeId string) ProvenanceEventsApiApiGetProvenanceEventRequest {
	r.clusterNodeId = &clusterNodeId
	return r
}

func (r ProvenanceEventsApiApiGetProvenanceEventRequest) Execute() (ProvenanceEventEntity, *_nethttp.Response, error) {
	return r.ApiService.GetProvenanceEventExecute(r)
}

/*
 * GetProvenanceEvent Gets a provenance event
 * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
 * @param id The provenance event id.
 * @return ProvenanceEventsApiApiGetProvenanceEventRequest
 */
func (a *ProvenanceEventsApiService) GetProvenanceEvent(ctx _context.Context, id string) ProvenanceEventsApiApiGetProvenanceEventRequest {
	return ProvenanceEventsApiApiGetProvenanceEventRequest{
		ApiService: a,
		ctx:        ctx,
		id:         id,
	}
}

/*
 * Execute executes the request
 * @return ProvenanceEventEntity
 */
func (a *ProvenanceEventsApiService) GetProvenanceEventExecute(r ProvenanceEventsApiApiGetProvenanceEventRequest) (ProvenanceEventEntity, *_nethttp.Response, error) {
	var (
		localVarHTTPMethod   = _nethttp.MethodGet
		localVarPostBody     interface{}
		localVarFormFileName string
		localVarFileName     string
		localVarFileBytes    []byte
		localVarReturnValue  ProvenanceEventEntity
	)

	localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProvenanceEventsApiService.GetProvenanceEvent")
	if err != nil {
		return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
	}

	localVarPath := localBasePath + "/provenance-events/{id}"
	localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", _neturl.PathEscape(parameterToString(r.id, "")), -1)

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := _neturl.Values{}
	localVarFormParams := _neturl.Values{}

	if r.clusterNodeId != nil {
		localVarQueryParams.Add("clusterNodeId", parameterToString(*r.clusterNodeId, ""))
	}
	// to determine the Content-Type header
	localVarHTTPContentTypes := []string{}

	// set Content-Type header
	localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
	if localVarHTTPContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHTTPContentType
	}

	// to determine the Accept header
	localVarHTTPHeaderAccepts := []string{"application/json"}

	// set Accept header
	localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
	if localVarHTTPHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
	}
	req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
	if err != nil {
		return localVarReturnValue, nil, err
	}

	localVarHTTPResponse, err := a.client.callAPI(req)
	if err != nil || localVarHTTPResponse == nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
	localVarHTTPResponse.Body.Close()
	localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))
	if err != nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	if localVarHTTPResponse.StatusCode >= 300 {
		newErr := GenericOpenAPIError{
			body:  localVarBody,
			error: localVarHTTPResponse.Status,
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
	if err != nil {
		newErr := GenericOpenAPIError{
			body:  localVarBody,
			error: err.Error(),
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	return localVarReturnValue, localVarHTTPResponse, nil
}

type ProvenanceEventsApiApiSubmitReplayRequest struct {
	ctx        _context.Context
	ApiService *ProvenanceEventsApiService
	body       *SubmitReplayRequestEntity
}

func (r ProvenanceEventsApiApiSubmitReplayRequest) Body(body SubmitReplayRequestEntity) ProvenanceEventsApiApiSubmitReplayRequest {
	r.body = &body
	return r
}

func (r ProvenanceEventsApiApiSubmitReplayRequest) Execute() (ProvenanceEventEntity, *_nethttp.Response, error) {
	return r.ApiService.SubmitReplayExecute(r)
}

/*
 * SubmitReplay Replays content from a provenance event
 * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
 * @return ProvenanceEventsApiApiSubmitReplayRequest
 */
func (a *ProvenanceEventsApiService) SubmitReplay(ctx _context.Context) ProvenanceEventsApiApiSubmitReplayRequest {
	return ProvenanceEventsApiApiSubmitReplayRequest{
		ApiService: a,
		ctx:        ctx,
	}
}

/*
 * Execute executes the request
 * @return ProvenanceEventEntity
 */
func (a *ProvenanceEventsApiService) SubmitReplayExecute(r ProvenanceEventsApiApiSubmitReplayRequest) (ProvenanceEventEntity, *_nethttp.Response, error) {
	var (
		localVarHTTPMethod   = _nethttp.MethodPost
		localVarPostBody     interface{}
		localVarFormFileName string
		localVarFileName     string
		localVarFileBytes    []byte
		localVarReturnValue  ProvenanceEventEntity
	)

	localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProvenanceEventsApiService.SubmitReplay")
	if err != nil {
		return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}
	}

	localVarPath := localBasePath + "/provenance-events/replays"

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := _neturl.Values{}
	localVarFormParams := _neturl.Values{}
	if r.body == nil {
		return localVarReturnValue, nil, reportError("body is required and must be specified")
	}

	// to determine the Content-Type header
	localVarHTTPContentTypes := []string{"application/json"}

	// set Content-Type header
	localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
	if localVarHTTPContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHTTPContentType
	}

	// to determine the Accept header
	localVarHTTPHeaderAccepts := []string{"application/json"}

	// set Accept header
	localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
	if localVarHTTPHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
	}
	// body params
	localVarPostBody = r.body
	req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
	if err != nil {
		return localVarReturnValue, nil, err
	}

	localVarHTTPResponse, err := a.client.callAPI(req)
	if err != nil || localVarHTTPResponse == nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
	localVarHTTPResponse.Body.Close()
	localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))
	if err != nil {
		return localVarReturnValue, localVarHTTPResponse, err
	}

	if localVarHTTPResponse.StatusCode >= 300 {
		newErr := GenericOpenAPIError{
			body:  localVarBody,
			error: localVarHTTPResponse.Status,
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
	if err != nil {
		newErr := GenericOpenAPIError{
			body:  localVarBody,
			error: err.Error(),
		}
		return localVarReturnValue, localVarHTTPResponse, newErr
	}

	return localVarReturnValue, localVarHTTPResponse, nil
}

repository: simingweng/nifi-go-client

repo_name: simingweng/nifi-go-client


text:
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// 	protoc-gen-go v1.26.0-devel
// 	protoc        v3.15.2
// source: pb/v1/worker.proto

package messageman

import (
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	emptypb "google.golang.org/protobuf/types/known/emptypb"
	reflect "reflect"
	sync "sync"
)

const (
	// Verify that this generated code is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
	// Verify that runtime/protoimpl is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)

type ReceiveRequest struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Name    string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
	Message []byte `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
}

func (x *ReceiveRequest) Reset() {
	*x = ReceiveRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_pb_v1_worker_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *ReceiveRequest) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*ReceiveRequest) ProtoMessage() {}

func (x *ReceiveRequest) ProtoReflect() protoreflect.Message {
	mi := &file_pb_v1_worker_proto_msgTypes[0]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use ReceiveRequest.ProtoReflect.Descriptor instead.
func (*ReceiveRequest) Descriptor() ([]byte, []int) {
	return file_pb_v1_worker_proto_rawDescGZIP(), []int{0}
}

func (x *ReceiveRequest) GetName() string {
	if x != nil {
		return x.Name
	}
	return ""
}

func (x *ReceiveRequest) GetMessage() []byte {
	if x != nil {
		return x.Message
	}
	return nil
}

var File_pb_v1_worker_proto protoreflect.FileDescriptor

var file_pb_v1_worker_proto_rawDesc = []byte{
	0x0a, 0x12, 0x70, 0x62, 0x2f, 0x76, 0x31, 0x2f, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x2e, 0x70,
	0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x6d, 0x61, 0x6e,
	0x2e, 0x76, 0x31, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74,
	0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
	0x22, 0x3e, 0x0a, 0x0e, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65,
	0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
	0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67,
	0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
	0x32, 0x51, 0x0a, 0x0d, 0x57, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63,
	0x65, 0x12, 0x40, 0x0a, 0x07, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x12, 0x1d, 0x2e, 0x6d,
	0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x6d, 0x61, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63,
	0x65, 0x69, 0x76, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f,
	0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d,
	0x70, 0x74, 0x79, 0x42, 0x44, 0x5a, 0x32, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f,
	0x6d, 0x2f, 0x74, 0x75, 0x72, 0x67, 0x61, 0x79, 0x6f, 0x7a, 0x67, 0x75, 0x72, 0x2f, 0x6d, 0x65,
	0x73, 0x73, 0x61, 0x67, 0x65, 0x6d, 0x61, 0x6e, 0x2f, 0x70, 0x62, 0x2f, 0x76, 0x31, 0x3b, 0x6d,
	0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x6d, 0x61, 0x6e, 0xaa, 0x02, 0x0d, 0x4d, 0x65, 0x73, 0x73,
	0x61, 0x67, 0x65, 0x6d, 0x61, 0x6e, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
	0x33,
}

var (
	file_pb_v1_worker_proto_rawDescOnce sync.Once
	file_pb_v1_worker_proto_rawDescData = file_pb_v1_worker_proto_rawDesc
)

func file_pb_v1_worker_proto_rawDescGZIP() []byte {
	file_pb_v1_worker_proto_rawDescOnce.Do(func() {
		file_pb_v1_worker_proto_rawDescData = protoimpl.X.CompressGZIP(file_pb_v1_worker_proto_rawDescData)
	})
	return file_pb_v1_worker_proto_rawDescData
}

var file_pb_v1_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_pb_v1_worker_proto_goTypes = []interface{}{
	(*ReceiveRequest)(nil), // 0: messageman.v1.ReceiveRequest
	(*emptypb.Empty)(nil),  // 1: google.protobuf.Empty
}
var file_pb_v1_worker_proto_depIdxs = []int32{
	0, // 0: messageman.v1.WorkerService.Receive:input_type -> messageman.v1.ReceiveRequest
	1, // 1: messageman.v1.WorkerService.Receive:output_type -> google.protobuf.Empty
	1, // [1:2] is the sub-list for method output_type
	0, // [0:1] is the sub-list for method input_type
	0, // [0:0] is the sub-list for extension type_name
	0, // [0:0] is the sub-list for extension extendee
	0, // [0:0] is the sub-list for field type_name
}

func init() { file_pb_v1_worker_proto_init() }
func file_pb_v1_worker_proto_init() {
	if File_pb_v1_worker_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_pb_v1_worker_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*ReceiveRequest); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: file_pb_v1_worker_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   1,
			NumExtensions: 0,
			NumServices:   1,
		},
		GoTypes:           file_pb_v1_worker_proto_goTypes,
		DependencyIndexes: file_pb_v1_worker_proto_depIdxs,
		MessageInfos:      file_pb_v1_worker_proto_msgTypes,
	}.Build()
	File_pb_v1_worker_proto = out.File
	file_pb_v1_worker_proto_rawDesc = nil
	file_pb_v1_worker_proto_goTypes = nil
	file_pb_v1_worker_proto_depIdxs = nil
}

repository: turgayozgur/messageman

repo_name: turgayozgur/messageman


text:
@ARTICLE{Wu2016,
  author = {Wenchao Wu and Jiayi Xu and Haipeng Zeng and Yixian Zheng and Huamin Qu and Bing Ni and Mingxuan Yuan and Lionel M. Ni},
  title = {{TelCoVis}: Visual exploration of co-occurrence in urban human mobility based on telco data},
  journal = {IEEE Transactions on Visualization and Computer Graphics},
  year = {2016},
  volume = {22},
  pages = {935--944},
  number = {1},
  abstract = {Understanding co-occurrence in urban human mobility (i.e. people from two regions visit an urban place during the same time span) is of great value in a variety of applications, such as urban planning, business intelligence, social behavior analysis, as well as containing contagious diseases. In recent years, the widespread use of mobile phones brings an unprecedented opportunity to capture large-scale and fine-grained data to study co-occurrence in human mobility. However, due to the lack of systematic and efficient methods, it is challenging for analysts to carry out in-depth analyses and extract valuable information. In this paper, we present TelCoVis, an interactive visual analytics system, which helps analysts leverage their domain knowledge to gain insight into the co-occurrence in urban human mobility based on telco data. Our system integrates visualization techniques with new designs and combines them in a novel way to enhance analysts' perception for a comprehensive exploration. In addition, we propose to study the correlations in co-occurrence (i.e. people from multiple regions visit different places during the same time span) by means of biclustering techniques that allow analysts to better explore coordinated relationships among different regions and identify interesting patterns. The case studies based on a real-world dataset and interviews with domain experts have demonstrated the effectiveness of our system in gaining insights into co-occurrence and facilitating various analytical tasks.},
  doi = {10.1109/TVCG.2015.2467194}
}

repository: vis-au/treevisnet

repo_name: vis-au/treevisnet


text:
package pixel

import "image/color"

// RGBA represents an alpha-premultiplied RGBA color with components within range [0, 1].
//
// The difference between color.RGBA is that the value range is [0, 1] and the values are floats.
type RGBA struct {
	R, G, B, A float64
}

// RGB returns a fully opaque RGBA color with the given RGB values.
//
// A common way to construct a transparent color is to create one with RGB constructor, then
// multiply it by a color obtained from the Alpha constructor.
func RGB(r, g, b float64) RGBA {
	return RGBA{r, g, b, 1}
}

// Alpha returns a white RGBA color with the given alpha component.
func Alpha(a float64) RGBA {
	return RGBA{a, a, a, a}
}

// Add adds color d to color c component-wise and returns the result (the components are not
// clamped).
func (c RGBA) Add(d RGBA) RGBA {
	return RGBA{
		R: c.R + d.R,
		G: c.G + d.G,
		B: c.B + d.B,
		A: c.A + d.A,
	}
}

// Sub subtracts color d from color c component-wise and returns the result (the components
// are not clamped).
func (c RGBA) Sub(d RGBA) RGBA {
	return RGBA{
		R: c.R - d.R,
		G: c.G - d.G,
		B: c.B - d.B,
		A: c.A - d.A,
	}
}

// Mul multiplies color c by color d component-wise (the components are not clamped).
func (c RGBA) Mul(d RGBA) RGBA {
	return RGBA{
		R: c.R * d.R,
		G: c.G * d.G,
		B: c.B * d.B,
		A: c.A * d.A,
	}
}

// Scaled multiplies each component of color c by scale and returns the result (the components
// are not clamped).
func (c RGBA) Scaled(scale float64) RGBA {
	return RGBA{
		R: c.R * scale,
		G: c.G * scale,
		B: c.B * scale,
		A: c.A * scale,
	}
}

// RGBA returns alpha-premultiplied red, green, blue and alpha components of the RGBA color.
func (c RGBA) RGBA() (r, g, b, a uint32) {
	r = uint32(0xffff * c.R)
	g = uint32(0xffff * c.G)
	b = uint32(0xffff * c.B)
	a = uint32(0xffff * c.A)
	return
}

// ToRGBA converts a color to RGBA format. Using this function is preferred to using RGBAModel, for
// performance (using RGBAModel introduces additional unnecessary allocations).
func ToRGBA(c color.Color) RGBA {
	if c, ok := c.(RGBA); ok {
		return c
	}
	r, g, b, a := c.RGBA()
	return RGBA{
		float64(r) / 0xffff,
		float64(g) / 0xffff,
		float64(b) / 0xffff,
		float64(a) / 0xffff,
	}
}

// RGBAModel converts colors to RGBA format.
var RGBAModel = color.ModelFunc(rgbaModel)

func rgbaModel(c color.Color) color.Color {
	return ToRGBA(c)
}

repository: faiface/pixel

repo_name: faiface/pixel


text:
@INPROCEEDINGS{Dmitrieva2009,
  author = {Julia Dmitrieva and Fons J. Verbeek},
  title = {Node-Link and Containment Methods in Ontology Visualization},
  abstract = {OWL Ontology language can be very expressive. This could provide difficulty in ontology understanding process. We belief, that an ontology visualization equipped with intuitive interactions can simplify this process, and help the user during ontology exploration and development. We introduce an approach representing an ontology with two different tree visualization techniques: the node-link technique, and the containment technique. These two representations show the structure of an ontology differently. The former, represents an ontology as a graph structure. This graph structure, based on the ontology hierarchy and properties, can be explored in different geometries: Euclidean, hyperbolic and spherical. The second representation shows only the hierarchical structure. The design of the containment approach is implemented in a non-standard way. In place of traditional two-dimensional space-filling techniques, we elaborate on the sphere-packing approach and make our hierarchy visualization three-dimensional. We augment this technique with the semantic zoom functionality, where the level of detail is a function of a distance from the viewer.},
  url = {http://ceur-ws.org/Vol-529/owled2009_submission_9.pdf},
  year = {2009},
  booktitle = {OWLED'09: Proceedings of the International Workshop on OWL: Experiences and Directions},
  editor = {Rinke Hoekstra and Peter F. Patel-Schneider},
  publisher = {CEUR Workshop Proceedings},
}


text:
# micro-image
#
# Image configuration for the OE Micro Linux Distribuion (micro, micro-uclibc)
#
# This image basically consists of: libc, busybox, udev, sysv init, and a few
# init scripts for running up the system.
#
# It is truely tiny and should build with most architectures/machines.
#
# The image is tested to build and run succesfully with the following machines:
#
#	* at91sam9263ek (jffs2 image size ~ 1 MB, uclibc)
#	* x86
#
# Maintainer: Martin Lund <mgl@doredevelopment.dk>
#

# Install basic files only
IMAGE_INSTALL = "base-files base-passwd"
IMAGE_LINGUAS = ""

# Use busybox as login manager
IMAGE_LOGIN_MANAGER = "busybox"

# Include minimum init and init scripts
IMAGE_DEV_MANAGER = "udev"
IMAGE_INIT_MANAGER = "sysvinit sysvinit-pidof"
IMAGE_INITSCRIPTS = ""

inherit image


text:
SUMMARY = "Lightweight terminal"
DESCRIPTION = "Desktop-independent VTE-based terminal emulator with support for multiple tabs"
HOMEPAGE = "http://lxde.sourceforge.net/"
BUGTRACKER = ""

LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=59530bdf33659b29e73d4adb9f9f6552"

SECTION = "x11/utils"
DEPENDS = "glib-2.0 vte"

SRC_URI = "${SOURCEFORGE_MIRROR}/lxde/lxterminal-${PV}.tar.gz"

SRC_URI[md5sum] = "fd9140b45c0f28d021253c4aeb8c4aea"
SRC_URI[sha256sum] = "f495166b308a96e8c30c8892b33ab163f3865253a9bbd4bdac462f974fda7253"

PR = "r1"

inherit autotools pkgconfig

repository: DougBarry/meta-openpandora-vendor

repo_name: DougBarry/meta-openpandora-vendor


text:
package broker

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

	"gopkg.in/check.v1"

	"github.com/eleme/lindb/rpc"
	brokerpb "github.com/eleme/lindb/rpc/pkg/broker"
)

const (
	requestTimeout = 2 * time.Second
	address        = ":9001"
)

type testSuite struct {
	server rpc.Server
}

func Test(t *testing.T) {
	check.TestingT(t)
}

var _ = check.Suite(&testSuite{
	server: NewBrokerServer(address),
})

func (ts *testSuite) SetUpSuite(c *check.C) {
	ts.server.Init()
	ts.server.Listen()
	ts.server.Register()
	go func() {
		ts.server.Serve()
	}()
}

func (ts *testSuite) TearDownSuite(c *check.C) {
}

func (ts *testSuite) TestRequest(c *check.C) {
	cli := NewBrokerClient(address, requestTimeout)

	wg := sync.WaitGroup{}

	for i := 0; i < 3; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			points := buildPoints()
			err := cli.WritePoints(points)
			c.Assert(err, check.IsNil)
		}()
	}

	wg.Wait()
	cli.Close()
}

func (ts *testSuite) TestStreamRequest(c *check.C) {
	cli := NewBrokerClient(address, requestTimeout)

	wg := sync.WaitGroup{}

	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			points := buildPoints()

			err := cli.WritePointsStream(points)
			c.Assert(err, check.IsNil)

			err = cli.WritePointsStream(points)
			c.Assert(err, check.IsNil)

			err = cli.WritePointsStream(points)
			c.Assert(err, check.IsNil)

		}()
	}

	wg.Wait()
	cli.Close()
}

func buildPoints() (points []*brokerpb.Point) {
	for i := range []int{1, 2, 3} {
		name := fmt.Sprintf("name-%d", i)
		tags := map[string]string{"t1": "v1"}
		f1 := buildField("f1", brokerpb.AggType_GAUGE, 1)
		f2 := buildField("f2", brokerpb.AggType_SUM, 2)
		fields := []*brokerpb.Field{f1, f2}
		points = append(points, buildPoint(name, int64(i), tags, fields))
	}
	return points
}

func buildPoint(name string, ts int64, tags map[string]string, fields []*brokerpb.Field) *brokerpb.Point {
	return &brokerpb.Point{
		Name:      name,
		Timestamp: ts,
		Tags:      tags,
		Fields:    fields,
	}
}

func buildField(name string, aggType brokerpb.AggType, value float64) *brokerpb.Field {
	return &brokerpb.Field{
		Name:    name,
		AggType: aggType,
		Value:   value,
	}
}

branch_name: refs/heads/develop


text:
package rgm

import (
	"fmt"
	"github.com/libgit2/git2go"
	"log"
	"strings"
)

type RemoteConfig struct {
	Name string
	URL  string
}

// For an existing Git repo and an RPM (e.g. cowsay) Setup the remotes.
//
// This is a best effort procedure.  Not all remotes will be available
// (fedora might not have package x).  As long as at least one remote
// works it is a success.
func SetupRpmRemotes(repo *git.Repository, rcs []RemoteConfig) error {

	var one_worked bool = false

	for _, rc := range rcs {

		// try to set up the remote, continue if it doesn't work
		err := setupRpmRemote(repo, &rc)
		if err != nil {
			log.Println(err)
		} else {
			one_worked = true
		}
	}

	if one_worked {
		return nil
	} else {
		return fmt.Errorf("unable to setup any remotes")
	}
}

func setupRpmRemote(repo *git.Repository, cfg *RemoteConfig) error {
	_, err := repo.Remotes.Create(cfg.Name, cfg.URL)
	if err != nil {
		return fmt.Errorf("git add remote for '%v' failed: %v", cfg.Name, err)
	}

	return nil
}

func FetchAll(repo *git.Repository) error {
	var one_worked bool = false

	remotes, err := repo.Remotes.List()
	if err != nil {
		return fmt.Errorf("unable to list remotes: %v", err)
	}

	for _, remote := range remotes {
		r, err := repo.Remotes.Lookup(remote) // get Remote obj
		if err != nil {
			log.Printf("unable to find remote '%v': %v", remote, err)
			continue
		}

		err = r.Fetch(nil, nil, "")
		if err != nil {
			log.Printf("git fetch remote '%v' failed: %v", remote, err)
		} else {
			one_worked = true
		}
	}

	if one_worked {
		return nil
	} else {
		return fmt.Errorf("unable to fetch any remotes")
	}
}

// For a repo with remote branches the expected local branch name
// is the same but with "remotes/" removed.
//  remotes/fedora/f31 -> fedora/31
// This gets the set of local branches (e.g. fedora/f31) that "should"
// exist based on the remotes that were found.
func getExpectedLocalBranches(repo *git.Repository) ([]string, error) {

	var branches []string
	iter, err := repo.NewBranchIterator(git.BranchRemote)
	if err != nil {
		return nil, err
	}
	defer iter.Free()
	for {
		ref, branch_type, err := iter.Next()
		if err != nil {
			break
		}
		if branch_type != git.BranchRemote {
			continue
		}
		branch, _ := ref.Branch().Name() // fedora/f31
		// exclude special branch refs like HEAD
		if branch == "origin/HEAD" {
			continue
		}
		branches = append(branches, branch)
	}

	return branches, nil
}

func setupRpmBranch(repo *git.Repository, branch string) error {

	var err error

	// first, lookup the remote branch and create a local one if needed

	local_branch, err := repo.LookupBranch(branch, git.BranchLocal)
	if local_branch == nil || err != nil {
		remote_branch, err := repo.LookupBranch(branch, git.BranchRemote)
		if err != nil {
			return fmt.Errorf("unable to find remote '%s': %v", branch, err)
		}
		defer remote_branch.Free()

		commit, err := repo.LookupCommit(remote_branch.Target())
		if err != nil {
			return fmt.Errorf("lookup commit failed: %v", err)
		}
		defer commit.Free()

		local_branch, err = repo.CreateBranch(branch, commit, false)
		if err != nil {
			return fmt.Errorf("create branch '%s' failed: %v", branch, err)
		}
	}
	if local_branch == nil {
		return fmt.Errorf("Failed to create local branch '%v'.", branch)
	}
	defer local_branch.Free()

	// second, --set-upstream tracking branch

	// checkout -b would do what we want, but git2go doesn't
	// have an exact equivalent.
	//
	//   git checkout -b fedora/f31 fedora/f31
	//
	// It is easiest to just set the .git/config values.
	//
	// git config "branch.fedora/f31.remote" fedora
	// git config "branch.fedora/f31.merge" "refs/heads/f31"

	branch_parts := strings.Split(branch, "/")
	remote := branch_parts[0]                           // fedora
	short_branch := strings.Join(branch_parts[1:], "/") // f31

	cfg, err := repo.Config()
	if err != nil {
		return fmt.Errorf("Failed to get Config: %v", err)
	}
	err = cfg.SetString(fmt.Sprintf("branch.%s.remote", branch), remote)
	if err != nil {
		return fmt.Errorf("Failed to set config remote: %v", err)
	}
	err = cfg.SetString(fmt.Sprintf("branch.%s.merge", branch), fmt.Sprintf("refs/heads/%s", short_branch))
	if err != nil {
		return fmt.Errorf("Failed to set config merge: %v", err)
	}

	return nil
}

// Setup a local branch corresponding to each remote branch.
//
//  git branch -a
//  ...
//  fedora/31 -> remotes/fedora/f31
//
// This makes sure all the local branches exist and are up to date.
func SetupRpmBranches(repo *git.Repository) error {

	branches, err := getExpectedLocalBranches(repo)
	if err != nil {
		return fmt.Errorf("unable to get branches: %v", err)
	}

	for _, branch := range branches {
		err = setupRpmBranch(repo, branch)
		if err != nil {
			return err
		}
	}

	return nil
}

// Walk all the local branches and perform a git pull.
func PullAll(repo *git.Repository) error {

	err := FetchAll(repo)
	if err != nil {
		return fmt.Errorf("Unable to fetch for pull: %v", err)
	}

	branches, err := getExpectedLocalBranches(repo)
	if err != nil {
		return err
	}

	for _, branch := range branches {

		err = repo.SetHead("refs/heads/" + branch)
		if err != nil {
			return fmt.Errorf("unable to set head to '%s': %v", branch, err)
		}

		err = repo.CheckoutHead(&git.CheckoutOpts{
			Strategy: git.CheckoutForce,
		})
		if err != nil {
			return fmt.Errorf("unable to checkout head: %v", err)
		}

		local_branch, err := repo.LookupBranch(branch, git.BranchLocal)
		if err != nil {
			return fmt.Errorf("unable to lookup branch '%s': %v", branch, err)
		}
		defer local_branch.Free()

		remote_branch, err := repo.LookupBranch(branch, git.BranchRemote)
		if err != nil {
			return fmt.Errorf("unable to lookup remote branch '%s': %v", branch, err)
		}
		defer remote_branch.Free()

		commit, err := repo.AnnotatedCommitFromRef(remote_branch.Reference)
		if err != nil {
			return fmt.Errorf("unable to lookup commit for branch '%v': %v", branch, err)
		}
		defer commit.Free()

		commits := make([]*git.AnnotatedCommit, 1)
		commits[0] = commit

		analysis, _, err := repo.MergeAnalysis(commits)
		if err != nil {
			return fmt.Errorf("unable to run merge analysis: %v", err)
		}

		if (analysis & git.MergeAnalysisUpToDate) != 0 {
			// OK
		} else if (analysis & git.MergeAnalysisFastForward) != 0 {
			local_branch_ref := local_branch.Reference
			_, err := local_branch_ref.SetTarget(remote_branch.Reference.Target(), "pull: Fast-forward")
			if err != nil {
				return fmt.Errorf("Fast-forward merge of '%s' failed: %v", branch, err)
			}

			err = repo.CheckoutHead(&git.CheckoutOpts{
				Strategy: git.CheckoutForce,
			})
			if err != nil {
				return fmt.Errorf("unable to checkout head: %v", err)
			}
		} else if (analysis & git.MergeAnalysisNormal) != 0 {
			return fmt.Errorf("A merge is required for '%s'", branch)
		} else {
			return fmt.Errorf("Unhandled MergeAnalysis? '%v'", analysis)
		}
	}

	return nil
}

// Does all the steps to mirror an RPM: clone, setup branches,
// fetch, pull, etc.  Will get the existing repo, in whatever
// state it may be in, in to an updated state.
func RpmMirror(config string, rpm string, path string) error {
	cfg_tmpl, err := LoadConfig(config)
	if err != nil {
		return err
	}

	cfg, err := ExecConfigTemplate(cfg_tmpl, rpm)
	if err != nil {
		return err
	}

	repo, err := git.Clone(cfg.Origin.URL, path, &git.CloneOptions{Bare: false})
	if err != nil {
		return err
	}

	err = SetupRpmRemotes(repo, cfg.Remotes)
	if err != nil {
		return err
	}

	err = FetchAll(repo)
	if err != nil {
		return err
	}

	err = SetupRpmBranches(repo)
	if err != nil {
		return err
	}

	err = PullAll(repo)
	if err != nil {
		return err
	}

	return nil
}

repository: jmahler/rgm

repo_name: jmahler/rgm


text:
SRC_URI = "${GNU_MIRROR}/autoconf/autoconf-${PV}.tar.bz2 \
	   file://program_prefix.patch;patch=1"
LICENSE = "GPL"
DESCRIPTION = "A package of M4 macros to produce scripts to \
automatically configure sourcecode."

PR = "r1"
SECTION = "devel"
inherit autotools


text:
require linux.inc

PR = "r1"

# Mark archs/machines that this kernel supports
DEFAULT_PREFERENCE = "-1"
DEFAULT_PREFERENCE_qemuarm = "1"
DEFAULT_PREFERENCE_qemuppc = "1"
DEFAULT_PREFERENCE_qemush4 = "1"
DEFAULT_PREFERENCE_qemumips = "1"
DEFAULT_PREFERENCE_qemux86 = "1"

SRC_URI = "${KERNELORG_MIRROR}/pub/linux/kernel/v2.6/${P}.tar.bz2;name=kernel \
           file://ARM-Add-support-for-LZMA-compressed-kernel-images.patch;status=pending \
	   file://use-noclone-attribute-for-naked.patch;status=pending \
           file://defconfig"

SRC_URI[kernel.md5sum] = "10eebcb0178fb4540e2165bfd7efc7ad"
SRC_URI[kernel.sha256sum] = "fa395fec7de633df1cb85b6248b8f35af98380ed128a8bc465fb48bc4d252633"


text:
@article{10.2307/2332286,
    ISSN = {00063444},
    URL = {http://www.jstor.org/stable/2332286},
    author = {William R. Thompson},
    journal = {Biometrika},
    number = {3/4},
    pages = {285--294},
    publisher = {[Oxford University Press, Biometrika Trust]},
    title = {On the Likelihood that One Unknown Probability Exceeds Another in View of the Evidence of Two Samples},
    volume = {25},
    year = {1933}
}

@incollection{NIPS2011_4321,
    title = {An Empirical Evaluation of Thompson Sampling},
    author = {Olivier Chapelle and Li, Lihong},
    booktitle = {Advances in Neural Information Processing Systems 24},
    editor = {J. Shawe-Taylor and R. S. Zemel and P. L. Bartlett and F. Pereira and K. Q. Weinberger},
    pages = {2249--2257},
    year = {2011},
    publisher = {Curran Associates, Inc.},
    url = {http://papers.nips.cc/paper/4321-an-empirical-evaluation-of-thompson-sampling.pdf}
}

@article{LAI19854,
    title = "Asymptotically efficient adaptive allocation rules",
    journal = "Advances in Applied Mathematics",
    volume = "6",
    number = "1",
    pages = "4 - 22",
    year = "1985",
    issn = "0196-8858",
    doi = "https://doi.org/10.1016/0196-8858(85)90002-8",
    url = "http://www.sciencedirect.com/science/article/pii/0196885885900028",
    author = "T.L Lai and Herbert Robbins"
}

@article{DBLP:journals/ftml/BubeckC12,
    author    = {S{\'{e}}bastien Bubeck and
               Nicol{\`{o}} Cesa{-}Bianchi},
    title     = {Regret Analysis of Stochastic and Nonstochastic Multi-armed Bandit
               Problems},
    journal   = {Foundations and Trends in Machine Learning},
    volume    = {5},
    number    = {1},
    pages     = {1--122},
    year      = {2012},
    url       = {https://doi.org/10.1561/2200000024},
    doi       = {10.1561/2200000024},
    timestamp = {Sat, 20 May 2017 01:00:00 +0200},
    biburl    = {https://dblp.org/rec/bib/journals/ftml/BubeckC12},
    bibsource = {dblp computer science bibliography, https://dblp.org}
}

@inproceedings{46647,
    title	= {Deep Bayesian Bandits Showdown},
    author	= {Carlos Riquelme and George Tucker and Jasper Roland Snoek},
    year	= {2018},
    URL	= {https://openreview.net/pdf?id=SyYe6k-CW}
}

@inproceedings{DBLP:conf/nips/CombesMP17,
    author    = {Richard Combes and
               Stefan Magureanu and
               Alexandre Prouti{\`{e}}re},
    title     = {Minimal Exploration in Structured Stochastic Bandits},
    booktitle = {Advances in Neural Information Processing Systems 30: Annual Conference
               on Neural Information Processing Systems 2017, 4-9 December 2017,
               Long Beach, CA, {USA}},
    pages     = {1761--1769},
    year      = {2017},
    crossref  = {DBLP:conf/nips/2017},
    url       = {http://papers.nips.cc/paper/6773-minimal-exploration-in-structured-stochastic-bandits},
    timestamp = {Mon, 27 Nov 2017 12:38:48 +0100},
    biburl    = {https://dblp.org/rec/bib/conf/nips/CombesMP17},
    bibsource = {dblp computer science bibliography, https://dblp.org}
}

@incollection{NIPS2014_5378,
    title = {Stochastic Multi-Armed-Bandit Problem with Non-stationary Rewards},
    author = {Besbes, Omar and Gur, Yonatan and Zeevi, Assaf},
    booktitle = {Advances in Neural Information Processing Systems 27},
    editor = {Z. Ghahramani and M. Welling and C. Cortes and N. D. Lawrence and K. Q. Weinberger},
    pages = {199--207},
    year = {2014},
    publisher = {Curran Associates, Inc.},
    url = {http://papers.nips.cc/paper/5378-stochastic-multi-armed-bandit-problem-with-non-stationary-rewards.pdf}
}

@inproceedings{Wu:2018:LCB:3209978.3210051,
    author = {Wu, Qingyun and Iyer, Naveen and Wang, Hongning},
    title = {Learning Contextual Bandits in a Non-stationary Environment},
    booktitle = {The 41st International ACM SIGIR Conference on Research \&\#38; Development in Information Retrieval},
    series = {SIGIR '18},
    year = {2018},
    isbn = {978-1-4503-5657-2},
    location = {Ann Arbor, MI, USA},
    pages = {495--504},
    numpages = {10},
    url = {http://doi.acm.org/10.1145/3209978.3210051},
    doi = {10.1145/3209978.3210051},
    acmid = {3210051},
    publisher = {ACM},
    address = {New York, NY, USA},
    keywords = {non-stationary bandit, recommender systems, regret analysis},
}

@book{Sutton1998,
    added-at = {2018-09-18T19:21:39.000+0200},
    author = {Sutton, Richard S. and Barto, Andrew G.},
    biburl = {https://www.bibsonomy.org/bibtex/2f46601cf8b13d39d1378af0d79438b12/analyst},
    edition = {Second},
    interhash = {ac6b144aaec1819919a2fba9f705c852},
    intrahash = {f46601cf8b13d39d1378af0d79438b12},
    keywords = {2018 book reference reinforcement-learning},
    publisher = {The MIT Press},
    timestamp = {2018-09-18T19:22:02.000+0200},
    title = {Reinforcement Learning: An Introduction},
    url = {http://incompleteideas.net/book/the-book-2nd.html},
    year = {2018 }
}

@article{DBLP:journals/pieee/ShahriariSWAF16,
    author    = {Bobak Shahriari and
               Kevin Swersky and
               Ziyu Wang and
               Ryan P. Adams and
               Nando de Freitas},
    title     = {Taking the Human Out of the Loop: {A} Review of Bayesian Optimization},
    journal   = {Proceedings of the {IEEE}},
    volume    = {104},
    number    = {1},
    pages     = {148--175},
    year      = {2016},
    url       = {https://doi.org/10.1109/JPROC.2015.2494218},
    doi       = {10.1109/JPROC.2015.2494218},
    timestamp = {Wed, 04 Jul 2018 01:00:00 +0200},
    biburl    = {https://dblp.org/rec/bib/journals/pieee/ShahriariSWAF16},
    bibsource = {dblp computer science bibliography, https://dblp.org}
}

@article{DBLP:journals/corr/abs-1712-01815,
    author    = {David Silver and
               Thomas Hubert and
               Julian Schrittwieser and
               Ioannis Antonoglou and
               Matthew Lai and
               Arthur Guez and
               Marc Lanctot and
               Laurent Sifre and
               Dharshan Kumaran and
               Thore Graepel and
               Timothy P. Lillicrap and
               Karen Simonyan and
               Demis Hassabis},
    title     = {Mastering Chess and Shogi by Self-Play with a General Reinforcement
               Learning Algorithm},
    journal   = {CoRR},
    volume    = {abs/1712.01815},
    year      = {2017},
    url       = {http://arxiv.org/abs/1712.01815},
    archivePrefix = {arXiv},
    eprint    = {1712.01815},
    timestamp = {Mon, 13 Aug 2018 01:00:00 +0200},
    biburl    = {https://dblp.org/rec/bib/journals/corr/abs-1712-01815},
    bibsource = {dblp computer science bibliography, https://dblp.org}
}

@Book{Bellman:1957,
    author =       "Bellman, Richard",
    title =        "Dynamic Programming",
    publisher =    "Princeton University Press",
    year =         "1957",
    address =   "Princeton, NJ, USA",
    edition =   "1",
    bib2html_rescat = "General RL",
}

@PhdThesis{Watkins:1989,
    author =       "Watkins, Christopher John Cornish Hellaby",
    title =        "Learning from Delayed Rewards",
    school =       "King's College",
    year =         "1989",
    address =   "Cambridge, UK",
    month =     "May",
    url = "http://www.cs.rhul.ac.uk/~chrisw/new_thesis.pdf",
    bib2html_rescat = "Parameter",
}

@article{Tesauro:1995:TDL:203330.203343,
    author = {Tesauro, Gerald},
    title = {Temporal Difference Learning and TD-Gammon},
    journal = {Commun. ACM},
    issue_date = {March 1995},
    volume = {38},
    number = {3},
    month = mar,
    year = {1995},
    issn = {0001-0782},
    pages = {58--68},
    numpages = {11},
    url = {http://doi.acm.org/10.1145/203330.203343},
    doi = {10.1145/203330.203343},
    acmid = {203343},
    publisher = {ACM},
    address = {New York, NY, USA},
}

@inproceedings{DBLP:conf/aaai/DabneyRBM18,
    author    = {Will Dabney and
               Mark Rowland and
               Marc G. Bellemare and
               R{\'{e}}mi Munos},
    title     = {Distributional Reinforcement Learning With Quantile Regression},
    booktitle = {Proceedings of the Thirty-Second {AAAI} Conference on Artificial Intelligence,
               (AAAI-18), the 30th innovative Applications of Artificial Intelligence
               (IAAI-18), and the 8th {AAAI} Symposium on Educational Advances in
               Artificial Intelligence (EAAI-18), New Orleans, Louisiana, USA, February
               2-7, 2018},
    pages     = {2892--2901},
    year      = {2018},
    crossref  = {DBLP:conf/aaai/2018},
    url       = {https://www.aaai.org/ocs/index.php/AAAI/AAAI18/paper/view/17184},
    timestamp = {Tue, 23 Oct 2018 06:42:15 +0200},
    biburl    = {https://dblp.org/rec/bib/conf/aaai/DabneyRBM18},
    bibsource = {dblp computer science bibliography, https://dblp.org}
}

@inproceedings{DBLP:conf/aaai/DabneyRBM18,
    author    = {Will Dabney and
               Mark Rowland and
               Marc G. Bellemare and
               R{\'{e}}mi Munos},
    title     = {Distributional Reinforcement Learning With Quantile Regression},
    booktitle = {Proceedings of the Thirty-Second {AAAI} Conference on Artificial Intelligence,
               (AAAI-18), the 30th innovative Applications of Artificial Intelligence
               (IAAI-18), and the 8th {AAAI} Symposium on Educational Advances in
               Artificial Intelligence (EAAI-18), New Orleans, Louisiana, USA, February
               2-7, 2018},
    pages     = {2892--2901},
    year      = {2018},
    crossref  = {DBLP:conf/aaai/2018},
    url       = {https://www.aaai.org/ocs/index.php/AAAI/AAAI18/paper/view/17184},
    timestamp = {Tue, 23 Oct 2018 06:42:15 +0200},
    biburl    = {https://dblp.org/rec/bib/conf/aaai/DabneyRBM18},
    bibsource = {dblp computer science bibliography, https://dblp.org}
}

@article{DBLP:journals/corr/MnihKSGAWR13,
    author    = {Volodymyr Mnih and
               Koray Kavukcuoglu and
               David Silver and
               Alex Graves and
               Ioannis Antonoglou and
               Daan Wierstra and
               Martin A. Riedmiller},
    title     = {Playing Atari with Deep Reinforcement Learning},
    journal   = {CoRR},
    volume    = {abs/1312.5602},
    year      = {2013},
    url       = {http://arxiv.org/abs/1312.5602},
    archivePrefix = {arXiv},
    eprint    = {1312.5602},
    timestamp = {Mon, 13 Aug 2018 01:00:00 +0200},
    biburl    = {https://dblp.org/rec/bib/journals/corr/MnihKSGAWR13},
    bibsource = {dblp computer science bibliography, https://dblp.org}
}

@article{journals/corr/LillicrapHPHETS15,
    added-at = {2018-08-13T00:00:00.000+0200},
    author = {Lillicrap, Timothy P. and Hunt, Jonathan J. and Pritzel, Alexander and Heess, Nicolas and Erez, Tom and Tassa, Yuval and Silver, David and Wierstra, Daan},
    biburl = {https://www.bibsonomy.org/bibtex/23fd60842eb3f0ca78c9ac78886bdccb1/dblp},
    ee = {http://arxiv.org/abs/1509.02971},
    interhash = {ca27256847b6d007ec304a3792387470},
    intrahash = {3fd60842eb3f0ca78c9ac78886bdccb1},
    journal = {CoRR},
    keywords = {dblp},
    timestamp = {2018-08-14T11:49:15.000+0200},
    title = {Continuous control with deep reinforcement learning.},
    url = {http://dblp.uni-trier.de/db/journals/corr/corr1509.html#LillicrapHPHETS15},
    volume = {abs/1509.02971},
    year = 2015
}

@InProceedings{pmlr-v48-mniha16,
    title = 	 {Asynchronous Methods for Deep Reinforcement Learning},
    author = 	 {Volodymyr Mnih and Adria Puigdomenech Badia and Mehdi Mirza and Alex Graves and Timothy Lillicrap and Tim Harley and David Silver and Koray Kavukcuoglu},
    booktitle = 	 {Proceedings of The 33rd International Conference on Machine Learning},
    pages = 	 {1928--1937},
    year = 	 {2016},
    editor = 	 {Maria Florina Balcan and Kilian Q. Weinberger},
    volume = 	 {48},
    series = 	 {Proceedings of Machine Learning Research},
    address = 	 {New York, New York, USA},
    month = 	 {20--22 Jun},
    publisher = 	 {PMLR},
    pdf = 	 {http://proceedings.mlr.press/v48/mniha16.pdf},
    url = 	 {http://proceedings.mlr.press/v48/mniha16.html},
}

@ARTICLE{Browne2012,
    AUTHOR   = {Browne, Cb and Powley, Edward},
    DOI      = {10.1109/TCIAIG.2012.2186810},
    FILE     = {http://bib.unthinkingdepths.fr/seb/pdf/Browne, Powley_2012_A survey of monte carlo tree search methods.pdf},
    ISSN     = {1943-068X},
    JOURNAL  = {Intelligence and AI},
    NUMBER   = {1},
    PAGES    = {1--49},
    TITLE    = {{A survey of monte carlo tree search methods}},
    URL      = {http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=6145622},
    VOLUME   = {4},
    YEAR     = {2012},
}

repository: mauriciogtec/blog

repo_name: mauriciogtec/blog


text:
// Copyright (c) 2018 CyberAgent, Inc. All rights reserved.
// https://github.com/openfresh/gosrt

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package srt

import (
	"errors"
	"fmt"
	"io"
	"net"
	"runtime"
	"testing"
	"time"
)

func TestConnClose(t *testing.T) {
	for _, network := range []string{"srt"} {
		if !testableNetwork(network) {
			t.Logf("skipping %s test", network)
			continue
		}

		ln, err := newLocalListener(network)
		if err != nil {
			t.Fatal(err)
		}
		defer ln.Close()

		c, err := Dial(ln.Addr().Network(), ln.Addr().String())
		if err != nil {
			t.Fatal(err)
		}
		defer c.Close()

		if err := c.Close(); err != nil {
			if perr := parseCloseError(err, false); perr != nil {
				t.Error(perr)
			}
			t.Fatal(err)
		}
		var b [1]byte
		n, err := c.Read(b[:])
		if n != 0 || err == nil {
			t.Fatalf("got (%d, %v); want (0, error)", n, err)
		}
	}
}

func TestListenerClose(t *testing.T) {
	for _, network := range []string{"srt"} {
		if !testableNetwork(network) {
			t.Logf("skipping %s test", network)
			continue
		}

		ln, err := newLocalListener(network)
		if err != nil {
			t.Fatal(err)
		}

		dst := ln.Addr().String()
		if err := ln.Close(); err != nil {
			if perr := parseCloseError(err, false); perr != nil {
				t.Error(perr)
			}
			t.Fatal(err)
		}
		c, err := ln.Accept()
		if err == nil {
			c.Close()
			t.Fatal("should fail")
		}

		if network == "srt" {
			time.Sleep(time.Millisecond)

			cc, err := Dial("srt", dst)
			if err == nil {
				t.Error("Dial to closed SRT listener succeeded.")
				cc.Close()
			}
		}
	}
}

// nacl was previous failing to reuse an address.
func TestListenCloseListen(t *testing.T) {
	const maxTries = 10
	for tries := 0; tries < maxTries; tries++ {
		ln, err := newLocalListener("srt")
		if err != nil {
			t.Fatal(err)
		}
		addr := ln.Addr().String()
		if err := ln.Close(); err != nil {
			if perr := parseCloseError(err, false); perr != nil {
				t.Error(perr)
			}
			t.Fatal(err)
		}
		ln, err = Listen("srt", addr)
		if err == nil {
			// Success. nacl couldn't do this before.
			ln.Close()
			return
		}
		t.Errorf("failed on try %d/%d: %v", tries+1, maxTries, err)
	}
	t.Fatalf("failed to listen/close/listen on same address after %d tries", maxTries)
}

func TestZeroByteRead(t *testing.T) {
	for _, network := range []string{"srt"} {
		if !testableNetwork(network) {
			t.Logf("skipping %s test", network)
			continue
		}

		ln, err := newLocalListener(network)
		if err != nil {
			t.Fatal(err)
		}
		connc := make(chan net.Conn, 1)
		go func() {
			defer ln.Close()
			c, err := ln.Accept()
			if err != nil {
				t.Error(err)
			}
			connc <- c // might be nil
		}()
		c, err := Dial(network, ln.Addr().String())
		if err != nil {
			t.Fatal(err)
		}
		defer c.Close()
		sc := <-connc
		if sc == nil {
			continue
		}
		defer sc.Close()

		if runtime.GOOS == "windows" {
			// A zero byte read on Windows caused a wait for readability first.
			// Rather than change that behavior, satisfy it in this test.
			// See Issue 15735.
			go io.WriteString(sc, "a")
		}

		n, err := c.Read(nil)
		if n != 0 || err != nil {
			t.Errorf("%s: zero byte client read = %v, %v; want 0, nil", network, n, err)
		}

		if runtime.GOOS == "windows" {
			// Same as comment above.
			go io.WriteString(c, "a")
		}
		n, err = sc.Read(nil)
		if n != 0 || err != nil {
			t.Errorf("%s: zero byte server read = %v, %v; want 0, nil", network, n, err)
		}
	}
}

// withSRTConnPair sets up a SRT connection between two peers, then
// runs peer1 and peer2 concurrently. withSRTConnPair returns when
// both have completed.
func withSRTConnPair(t *testing.T, peer1, peer2 func(c *SRTConn) error) {
	ln, err := newLocalListener("srt")
	if err != nil {
		t.Fatal(err)
	}
	defer ln.Close()
	errc := make(chan error, 2)
	go func() {
		c1, err := ln.Accept()
		if err != nil {
			errc <- err
			return
		}
		defer c1.Close()
		errc <- peer1(c1.(*SRTConn))
	}()
	go func() {
		c2, err := Dial("srt", ln.Addr().String())
		if err != nil {
			errc <- err
			return
		}
		defer c2.Close()
		errc <- peer2(c2.(*SRTConn))
	}()
	for i := 0; i < 2; i++ {
		if err := <-errc; err != nil {
			t.Fatal(err)
		}
	}
}

// Tests that a blocked Read is interrupted by a concurrent SetReadDeadline
// modifying that Conn's read deadline to the past.
// See golang.org/cl/30164 which documented this. The net/http package
// depends on this.
func TestReadTimeoutUnblocksRead(t *testing.T) {
	serverDone := make(chan struct{})
	server := func(cs *SRTConn) error {
		defer close(serverDone)
		errc := make(chan error, 1)
		go func() {
			defer close(errc)
			go func() {
				// TODO: find a better way to wait
				// until we're blocked in the cs.Read
				// call below. Sleep is lame.
				time.Sleep(100 * time.Millisecond)

				// Interrupt the upcoming Read, unblocking it:
				cs.SetReadDeadline(time.Unix(123, 0)) // time in the past
			}()
			var buf [1]byte
			n, err := cs.Read(buf[:1])
			if n != 0 || err == nil {
				errc <- fmt.Errorf("Read = %v, %v; want 0, non-nil", n, err)
			}
		}()
		select {
		case err := <-errc:
			return err
		case <-time.After(5 * time.Second):
			buf := make([]byte, 2<<20)
			buf = buf[:runtime.Stack(buf, true)]
			println("Stacks at timeout:\n", string(buf))
			return errors.New("timeout waiting for Read to finish")
		}

	}
	// Do nothing in the client. Never write. Just wait for the
	// server's half to be done.
	client := func(*SRTConn) error {
		<-serverDone
		return nil
	}
	withSRTConnPair(t, client, server)
}


text:
SUMMARY = "A collection of powerful tools for manipulating EPROM load files."
SECTION = "devel"
LICENSE = "GPLv3+ & LGPLv3+"
LIC_FILES_CHKSUM = "file://LICENSE;md5=8dfcbf2f0a144b97f0931b6394debea7"

SRC_URI = " \
    http://srecord.sourceforge.net/srecord-${PV}.tar.gz \
    file://add-option-to-remove-docs.patch \
"

SRC_URI[md5sum] = "4de4a7497472d7972645c2af91313769"
SRC_URI[sha256sum] = "49a4418733c508c03ad79a29e95acec9a2fbc4c7306131d2a8f5ef32012e67e2"

UPSTREAM_CHECK_URI = "http://sourceforge.net/projects/srecord/files/releases"

DEPENDS = "libtool-native boost groff-native"

inherit autotools-brokensep

EXTRA_OECONF = "--without-gcrypt LIBTOOL=${STAGING_BINDIR_CROSS}/${HOST_SYS}-libtool"

# Set variable WITHOUT_DOC=0 to enable documentation generation
EXTRA_OEMAKE = "WITHOUT_DOC=1"

BBCLASSEXTEND = "native"

repository: ni/meta-openembedded

repo_name: ni/meta-openembedded

branch_name: refs/heads/nilrt/master/hardknott

gha_language: BitBake


text:
package main

import (
	"context"
	"encoding/base64"
	"flag"
	"fmt"
	"os"
	"sync"

	"github.com/joho/godotenv"

	"github.com/google/go-github/v32/github"
	"github.com/p1ass/sodium"
	"golang.org/x/oauth2"
)

func main() {
	var (
		owner = flag.String("owner", "", "Repository Owner")
		repo  = flag.String("repo", "", "Repository Name")
	)
	flag.Parse()
	if owner == nil || *owner == "" {
		fmt.Println("should be passed repository owner by -owner=")
		os.Exit(1)
		return
	}
	if repo == nil || *repo == "" {
		fmt.Println("should be passed repository name by -repo=")
		os.Exit(1)
		return
	}
	fmt.Println(fmt.Sprintf("Repository: %s/%s", *owner, *repo))

	secrets, err := godotenv.Read()
	if err != nil {
		fmt.Println(".env file not found: ", err.Error())
		os.Exit(1)
		return
	}

	cli := newClient()
	pubKey, err := getPublicKey(cli, *owner, *repo)
	if err != nil {
		fmt.Println("failed to get public key:", err.Error())
		os.Exit(1)
		return
	}

	wg := sync.WaitGroup{}

	for name, secret := range secrets {
		name := name
		secret := secret
		wg.Add(1)
		go func() {
			if err := updateSecret(cli, pubKey, *owner, *repo, name, secret); err != nil {
				fmt.Println("failed to update secret:", err.Error())
				os.Exit(1)
				return
			}
			wg.Done()
		}()
	}
	wg.Wait()
}

// ref https://qiita.com/kazz187/items/aa9885bb968722ac9b1d
func updateSecret(cli *github.Client, pubKey *github.PublicKey, owner, repo, name, secret string) error {
	pkBase64 := pubKey.GetKey()
	pk := make([]byte, 32)
	_, err := base64.StdEncoding.Decode(pk, []byte(pkBase64))
	if err != nil {
		fmt.Println("base64 decode error:", pkBase64, err.Error())
		return err
	}

	// sodium で暗号化を施す
	encSec := sodium.Bytes(secret).SealedBox(sodium.BoxPublicKey{Bytes: pk})
	encSecBase64 := base64.StdEncoding.EncodeToString(encSec)

	// Secret を更新
	es := &github.EncryptedSecret{
		Name:           name,
		KeyID:          *pubKey.KeyID,
		EncryptedValue: encSecBase64,
	}
	_, err = cli.Actions.CreateOrUpdateRepoSecret(context.Background(), owner, repo, es)
	if err != nil {
		fmt.Println("failed to update secret", err.Error())
		return err
	}
	return nil
}

func newClient() *github.Client {
	sts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")},
	)
	oc := oauth2.NewClient(context.Background(), sts)
	cli := github.NewClient(oc)
	return cli
}

func getPublicKey(cli *github.Client, owner string, repo string) (*github.PublicKey, error) {
	pubKey, _, err := cli.Actions.GetRepoPublicKey(context.Background(), owner, repo)
	if err != nil {
		return nil, err
	}
	return pubKey, nil
}


text:
@article{MR2299764,
 author = {Martín, Francisco and Nadirashvili, Nikolai},
 doi = {10.1007/s00205-006-0023-7},
 fjournal = {Archive for Rational Mechanics and Analysis},
 issn = {0003-9527},
 journal = {Arch. Ration. Mech. Anal.},
 mrclass = {53A10},
 mrnumber = {2299764},
 mrreviewer = {Fei-Tsen Liang},
 number = {2},
 pages = {285--301},
 title = {A Jordan curve spanned by a complete minimal surface},
 url = {https://doi.org/10.1007/s00205-006-0023-7},
 volume = {184},
 year = {2007}
}

repository: torralbofco/geometric-analysis-fork

repo_name: torralbofco/geometric-analysis-fork


text:
@inproceedings{koli2019,
 author = {Nelson, Greg L and Xie, Benjamin and Hu, Andrew and Ko,
Amy J},
 booktitle = {Koli Calling},
 location = {Koli, Finland},
 month = {11},
 title = {Towards a validated formative assessment for
language-specific program tracing skills},
 year = {2019}
}

repository: bxie/bxie-academic

repo_name: bxie/bxie-academic