text:
package webhook

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"html"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"
	"time"

	"github.com/golang/glog"
	"istio.io/istio/pkg/log"
	//vault "github.com/hashicorp/vault/api"
	clientset "github.com/richardcase/vault-inject/pkg/client/clientset/versioned"
	mapscheme "github.com/richardcase/vault-inject/pkg/client/clientset/versioned/scheme"
	informers "github.com/richardcase/vault-inject/pkg/client/informers/externalversions"
	listers "github.com/richardcase/vault-inject/pkg/client/listers/vaultinject/v1alpha1"
	"github.com/richardcase/vault-inject/pkg/inject"
	//"github.com/richardcase/vault-inject/pkg/inject/publisher"
	//"github.com/richardcase/vault-inject/pkg/inject/template"
	admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
	"k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	//"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	//"k8s.io/apimachinery/pkg/types"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	//"k8s.io/apimachinery/pkg/util/strategicpatch"
	//"k8s.io/apimachinery/pkg/util/wait"
	kubeinformers "k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/scheme"
	typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
	//appslisters "k8s.io/client-go/listers/apps/v1beta2"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/record"
	//"k8s.io/kubernetes/pkg/apis/core/v1"
	adv1beta "k8s.io/api/admission/v1beta1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var (
	runtimeScheme = runtime.NewScheme()
	codecs        = serializer.NewCodecFactory(runtimeScheme)
	deserializer  = codecs.UniversalDeserializer()

	// TODO(https://github.com/kubernetes/kubernetes/issues/57982)
	defaulter = runtime.ObjectDefaulter(runtimeScheme)
)

const (
	agentName          = "vault-admission"
	watchDebounceDelay = 100 * time.Millisecond
)

func init() {
	_ = corev1.AddToScheme(runtimeScheme)
	_ = admissionregistrationv1beta1.AddToScheme(runtimeScheme)

	// The `v1` package from k8s.io/kubernetes/pkgp/apis/core/v1 has
	// the object defaulting functions which are not included in
	// k8s.io/api/corev1. The default functions are required by
	// runtime.ObjectDefaulter to workaround lack of server-side
	// defaulting with webhooks (see
	// https://github.com/kubernetes/kubernetes/issues/57982).
	_ = v1.AddToScheme(runtimeScheme)
}

// Webhook is the implemntation for the vault mutating webhook
type Webhook struct {
	mu sync.RWMutex

	kubeclientset kubernetes.Interface
	mapclientset  clientset.Interface

	mapsLister listers.VaultMapLister
	mapsSynced cache.InformerSynced

	namespace       string
	secrets         map[string]string
	config          *inject.Config
	initializerName string

	recorder record.EventRecorder

	healthCheckInterval time.Duration
	healthCheckFile     string

	server *http.Server
	//configFile string
	//watcher    *fsnotify.Watcher
	certFile string
	keyFile  string
	cert     *tls.Certificate
}

// NewWebhook returns a new vault initializer
func NewWebhook(
	p Parameters,
	kubeclientset kubernetes.Interface,
	mapclientset clientset.Interface,
	kubeInformerFactory kubeinformers.SharedInformerFactory,
	mapsInformerFactory informers.SharedInformerFactory,
	namespace string,
	configmapName string,
	secretName string,
	webhookName string,
	stopCh <-chan struct{}) (*Webhook, error) {

	config, err := inject.GetInitializerConfig(kubeclientset, namespace, configmapName)
	if err != nil {
		glog.Fatal(err)
	}

	secrets, err := inject.GetInitializerSecret(kubeclientset, namespace, secretName)
	if err != nil {
		glog.Fatal(err)
	}

	//TODO: with the current version (v1.8) this doesn't pick up unitialized deployments
	// see: https://github.com/kubernetes/kubernetes/pull/51247
	//deploymentInformer := kubeInformerFactory.Apps().V1beta2().Deployments()
	mapsInformer := mapsInformerFactory.Vaultinject().V1alpha1().VaultMaps()

	// TODO: Remove this when the above is true
	//restClient := kubeclientset.AppsV1beta1().RESTClient()

	mapscheme.AddToScheme(scheme.Scheme)
	glog.V(4).Info("Creating event broadcaster")
	eventBroadcaster := record.NewBroadcaster()
	eventBroadcaster.StartLogging(glog.Infof)
	eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeclientset.CoreV1().Events("")})
	recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: agentName})

	glog.V(2).Infof("Using certfile: %s", p.CertFile)
	glog.V(2).Infof("Using keyfile: %s", p.KeyFile)
	pair, err := tls.LoadX509KeyPair(p.CertFile, p.KeyFile)
	if err != nil {
		return nil, err
	}

	/*watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}
	// watch the parent directory of the target files so we can catch
	// symlink updates of k8s ConfigMaps volumes.
	for _, file := range []string{p.ConfigFile, p.MeshFile, p.CertFile, p.KeyFile} {
		watchDir, _ := filepath.Split(file)
		if err := watcher.Watch(watchDir); err != nil {
			return nil, fmt.Errorf("could not watch %v: %v", file, err)
		}
	}*/

	wh := &Webhook{
		kubeclientset:   kubeclientset,
		mapclientset:    mapclientset,
		namespace:       namespace,
		config:          config,
		secrets:         secrets,
		mapsLister:      mapsInformer.Lister(),
		mapsSynced:      mapsInformer.Informer().HasSynced,
		initializerName: webhookName,
		recorder:        recorder,

		server: &http.Server{
			Addr: fmt.Sprintf(":%v", p.Port),
		},
		//configFile:          p.ConfigFile,
		//watcher:             watcher,
		healthCheckInterval: p.HealthCheckInterval,
		healthCheckFile:     p.HealthCheckFile,
		certFile:            p.CertFile,
		keyFile:             p.KeyFile,
		cert:                &pair,
	}
	wh.server.TLSConfig = &tls.Config{GetCertificate: wh.getCert}
	wh.server.TLSConfig.InsecureSkipVerify = true
	h := http.NewServeMux()
	h.HandleFunc("/inject", wh.serveInject)
	h.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Pong, %q", html.EscapeString(r.URL.Path))
	})
	wh.server.Handler = h

	glog.Info("Setting up event handlers")
	mapsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			glog.Infof("New map %v", obj)
		},
	})

	return wh, nil
}

func (wh *Webhook) Run(stopCh <-chan struct{}) error {
	defer utilruntime.HandleCrash()

	glog.Info("Starting vault admission")

	// Wait for the caches to be synced before starting workers
	glog.Info("Waiting for informer caches to sync")
	//if ok := cache.WaitForCacheSync(stopCh, i.deploymentsSynced, i.mapsSynced); !ok {
	if ok := cache.WaitForCacheSync(stopCh, wh.mapsSynced); !ok {
		return fmt.Errorf("Failed to wait for caches to sync")
	}

	go func() {
		if err := wh.server.ListenAndServeTLS("", ""); err != nil {
			glog.Errorf("ListenAndServeTLS for admission webhook returned error: %v", err)
		}
	}()
	//defer wh.watcher.Close()
	defer wh.server.Close()

	var healthC <-chan time.Time
	if wh.healthCheckInterval != 0 && wh.healthCheckFile != "" {
		t := time.NewTicker(wh.healthCheckInterval)
		healthC = t.C
		defer t.Stop()
	}
	var timerC <-chan time.Time

	for {
		select {
		case <-timerC:
			/*config, err := inject.GetInitializerConfig(wh.kubeclientset, wh.namespace, wh.configmapName)
			if err != nil {
				glog.Errorf("update error: %v", err)
				break
			}
			pair, err := tls.LoadX509KeyPair(wh.certFile, wh.keyFile)
			if err != nil {
				glog.Errorf("reload cert error: %v", err)
				break
			}
			wh.mu.Lock()
			wh.cert = &pair
			wh.mu.Unlock()*/
		//case event := <-wh.watcher.Event:
		//	if event.IsModify() || event.IsCreate() {
		//		timerC = time.After(watchDebounceDelay)
		//	}
		//case err := <-wh.watcher.Error:
		//	glog.Errorf("Watcher error: %v", err)
		case <-healthC:
			content := []byte(`ok`)
			if err := ioutil.WriteFile(wh.healthCheckFile, content, 0644); err != nil {
				glog.Errorf("Health check update of %q failed: %v", wh.healthCheckFile, err)
			}
		case <-stopCh:
			break
		}
	}

	glog.Info("Shutting down admission webhook")
	return nil
}

func (wh *Webhook) getCert(*tls.ClientHelloInfo) (*tls.Certificate, error) {
	wh.mu.Lock()
	defer wh.mu.Unlock()
	return wh.cert, nil
}

/*
func (wh *Webhook) initializeDeployment(deployment *v1beta1.Deployment) error {

	//TODO: Move this else where
	vaultConfig := vault.DefaultConfig()
	if i.config.VaultAddress != "" {
		vaultConfig.Address = i.config.VaultAddress
	}
	vaultClient, err := vault.NewClient(vaultConfig)
	if err != nil {
		glog.Fatal(err.Error())
	}

	if deployment.ObjectMeta.GetInitializers() != nil {
		pendingInitializers := deployment.ObjectMeta.GetInitializers().Pending

		if i.initializerName == pendingInitializers[0].Name {
			glog.Infof("Initializing deployment: %s", deployment.Name)

			o, err := runtime.NewScheme().DeepCopy(deployment)
			if err != nil {
				return err
			}
			initializedDeployment := o.(*v1beta1.Deployment)

			// Remove self from the list of pending Initializers while preserving ordering.
			if len(pendingInitializers) == 1 {
				initializedDeployment.ObjectMeta.Initializers = nil
			} else {
				initializedDeployment.ObjectMeta.Initializers.Pending = append(pendingInitializers[:0], pendingInitializers[1:]...)
			}

			if i.config.IgnoreSystemNamespaces && deployment.Namespace == "kube-system" {
				glog.Infof("Ignoring deployments in kube-system namespace")
				_, err = i.kubeclientset.AppsV1beta1().Deployments(deployment.Namespace).Update(initializedDeployment)
				return err
			}

			if i.config.RequireAnnotation {
				a := deployment.ObjectMeta.GetAnnotations()
				_, ok := a[i.config.AnnotatioName]
				if !ok {
					glog.V(2).Infof("Required '%s' annotation missing; skipping vault injection", i.config.AnnotatioName)
					_, err = i.kubeclientset.AppsV1beta1().Deployments(deployment.Namespace).Update(initializedDeployment)
					return err
				}
			}

			maps, err := i.mapsLister.VaultMaps(initializedDeployment.Namespace).List(labels.NewSelector())
			if err != nil {
				return err
			}
			if len(maps) == 0 {
				glog.V(2).Infof("No VaultMap for namespace %s; skipping vault injection", initializedDeployment.Namespace)
				_, err = i.kubeclientset.AppsV1beta1().Deployments(deployment.Namespace).Update(initializedDeployment)
				return err
			}
			vaultmap := maps[0]

			vaultPath, err := template.ResolveTemplate(initializedDeployment, vaultmap.Spec.VaultPathPattern)
			if err != nil {
				return err
			}
			glog.V(2).Infof("Querying vault with path: %s", vaultPath)
			request := vaultClient.NewRequest("GET", vaultPath)
			if i.config.VaultAuthMode == "Token" {
				request.ClientToken = i.secrets["vaultToken"]
			}
			resp, err := vaultClient.RawRequest(request)
			if err != nil {
				glog.Errorf("Error querying vault for secrets for %s: %v", vaultPath, err.Error())
				return err
			}

			defer func() {
				if resp != nil && resp.Body != nil {
					_ = resp.Body.Close()
				}
			}()

			if resp != nil && resp.StatusCode == 404 {
				glog.Infof("No secrets in vault for path %s", vaultPath)
				_, err = i.kubeclientset.AppsV1beta1().Deployments(deployment.Namespace).Update(initializedDeployment)
				return err
			}
			secret, err := vault.ParseSecret(resp.Body)
			if err != nil {
				return err
			}
			secrets := make(map[string]string)
			for key, value := range secret.Data {
				i.secrets[key] = value.(string)
			}
			publisher, err := publisher.CreatePublisher(vaultmap.Spec.SecretsPublisher)
			if err != nil {
				return err
			}
			err = publisher.PublishSecrets(vaultmap, i.kubeclientset.(*kubernetes.Clientset), initializedDeployment, secrets)
			if err != nil {
				return err
			}

			oldData, err := json.Marshal(deployment)
			if err != nil {
				return err
			}

			// Flag that this container has vault secrets
			if initializedDeployment.Spec.Template.Annotations == nil {
				annotations := make(map[string]string)
				initializedDeployment.Spec.Template.SetAnnotations(annotations)
			}
			initializedDeployment.Spec.Template.Annotations["vault-secrets-initialized"] = "true"

			newData, err := json.Marshal(initializedDeployment)
			if err != nil {
				return err
			}

			patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1beta1.Deployment{})
			if err != nil {
				return err
			}

			_, err = i.kubeclientset.AppsV1beta1().Deployments(deployment.Namespace).Patch(deployment.Name, types.StrategicMergePatchType, patchBytes)
			if err != nil {
				return err
			}
			glog.Infof("Patched Deployment: %s\n", deployment.Name)
		}
	}
	return nil
}
*/

// TODO(https://github.com/kubernetes/kubernetes/issues/57982)
// remove this workaround once server-side defaulting is fixed.
func applyDefaultsWorkaround(initContainers, containers []corev1.Container, volumes []corev1.Volume) {
	// runtime.ObjectDefaulter only accepts top-level resources. Construct
	// a dummy pod with fields we needed defaulted.
	defaulter.Default(&corev1.Pod{
		Spec: corev1.PodSpec{
			InitContainers: initContainers,
			Containers:     containers,
			Volumes:        volumes,
		},
	})
}

// It would be great to use https://github.com/mattbaird/jsonpatch to
// generate RFC6902 JSON patches. Unfortunately, it doesn't produce
// correct patches for object removal. Fortunately, our patching needs
// are fairly simple so generating them manually isn't horrible (yet).
type rfc6902PatchOperation struct {
	Op    string      `json:"op"`
	Path  string      `json:"path"`
	Value interface{} `json:"value,omitempty"`
}

func toAdmissionResponse(err error) *adv1beta.AdmissionResponse {
	return &adv1beta.AdmissionResponse{Result: &metav1.Status{Message: err.Error()}}
}

func (wh *Webhook) inject(ar *adv1beta.AdmissionReview) *adv1beta.AdmissionResponse {
	req := ar.Request
	var pod corev1.Pod
	if err := json.Unmarshal(req.Object.Raw, &pod); err != nil {
		log.Errorf("Could not unmarshal raw object: %v", err)
		return toAdmissionResponse(err)
	}

	log.Infof("AdmissionReview for Kind=%v Namespace=%v Name=%v (%v) UID=%v Rfc6902PatchOperation=%v UserInfo=%v",
		req.Kind, req.Namespace, req.Name, pod.Name, req.UID, req.Operation, req.UserInfo)
	log.Debugf("Object: %v", string(req.Object.Raw))
	log.Debugf("OldObject: %v", string(req.OldObject.Raw))

	/*if !injectRequired(ignoredNamespaces, wh.sidecarConfig.Policy, &pod.Spec, &pod.ObjectMeta) {
		log.Infof("Skipping %s/%s due to policy check", pod.Namespace, pod.Name)
		return &adv1beta.AdmissionResponse{
			Allowed: true,
		}
	}*/

	/*spec, status, err := injectionData(wh.sidecarConfig.Template, wh.sidecarTemplateVersion, &pod.Spec, &pod.ObjectMeta, wh.meshConfig.DefaultConfig, wh.meshConfig) // nolint: lll
	if err != nil {
		return toAdmissionResponse(err)
	}

	applyDefaultsWorkaround(spec.InitContainers, spec.Containers, spec.Volumes)
	annotations := map[string]string{istioSidecarAnnotationStatusKey: status}

	*/
	//patchBytes, err := createPatch(&pod, injectionStatus(&pod), annotations, spec)
	patchBytes, err := createPatch(&pod, nil)
	if err != nil {
		return toAdmissionResponse(err)
	}

	log.Infof("AdmissionResponse: patch=%v\n", string(patchBytes))

	reviewResponse := adv1beta.AdmissionResponse{
		Allowed: true,
		Patch:   patchBytes,
		PatchType: func() *adv1beta.PatchType {
			pt := adv1beta.PatchTypeJSONPatch
			return &pt
		}(),
	}
	return &reviewResponse
}

func (wh *Webhook) serveInject(w http.ResponseWriter, r *http.Request) {
	var body []byte
	if r.Body != nil {
		if data, err := ioutil.ReadAll(r.Body); err == nil {
			body = data
		}
	}
	if len(body) == 0 {
		log.Errorf("no body found")
		http.Error(w, "no body found", http.StatusBadRequest)
		return
	}

	// verify the content type is accurate
	contentType := r.Header.Get("Content-Type")
	if contentType != "application/json" {
		log.Errorf("contentType=%s, expect application/json", contentType)
		http.Error(w, "invalid Content-Type, want `application/json`", http.StatusUnsupportedMediaType)
		return
	}

	var reviewResponse *adv1beta.AdmissionResponse
	ar := adv1beta.AdmissionReview{}
	if _, _, err := deserializer.Decode(body, nil, &ar); err != nil {
		log.Errorf("Could not decode body: %v", err)
		reviewResponse = toAdmissionResponse(err)
	} else {
		reviewResponse = wh.inject(&ar)
	}

	response := adv1beta.AdmissionReview{}
	if reviewResponse != nil {
		response.Response = reviewResponse
		if ar.Request != nil {
			response.Response.UID = ar.Request.UID
		}
	}

	resp, err := json.Marshal(response)
	if err != nil {
		log.Errorf("Could not encode response: %v", err)
		http.Error(w, fmt.Sprintf("could encode response: %v", err), http.StatusInternalServerError)
	}
	if _, err := w.Write(resp); err != nil {
		log.Errorf("Could not write response: %v", err)
		http.Error(w, fmt.Sprintf("could write response: %v", err), http.StatusInternalServerError)
	}
}

// escape JSON Pointer value per https://tools.ietf.org/html/rfc6901
func escapeJSONPointerValue(in string) string {
	step := strings.Replace(in, "~", "~0", -1)
	return strings.Replace(step, "/", "~1", -1)
}

func updateAnnotation(target map[string]string, added map[string]string) (patch []rfc6902PatchOperation) {
	for key, value := range added {
		if target == nil {
			target = map[string]string{}
			patch = append(patch, rfc6902PatchOperation{
				Op:   "add",
				Path: "/metadata/annotations",
				Value: map[string]string{
					key: value,
				},
			})
		} else {
			op := "add"
			if target[key] != "" {
				op = "replace"
			}
			patch = append(patch, rfc6902PatchOperation{
				Op:    op,
				Path:  "/metadata/annotations/" + escapeJSONPointerValue(key),
				Value: value,
			})
		}
	}
	return patch
}

//func createPatch(pod *corev1.Pod, prevStatus *SidecarInjectionStatus, annotations map[string]string, sic *SidecarInjectionSpec) ([]byte, error) {
func createPatch(pod *corev1.Pod, annotations map[string]string) ([]byte, error) {
	var patch []rfc6902PatchOperation

	// Remove any containers previously injected by kube-inject using
	// container and volume name as unique key for removal.
	//patch = append(patch, removeContainers(pod.Spec.InitContainers, prevStatus.InitContainers, "/spec/initContainers")...)
	//patch = append(patch, removeContainers(pod.Spec.Containers, prevStatus.Containers, "/spec/containers")...)
	//patch = append(patch, removeVolumes(pod.Spec.Volumes, prevStatus.Volumes, "/spec/volumes")...)

	//patch = append(patch, addContainer(pod.Spec.InitContainers, sic.InitContainers, "/spec/initContainers")...)
	//patch = append(patch, addContainer(pod.Spec.Containers, sic.Containers, "/spec/containers")...)
	//patch = append(patch, addVolume(pod.Spec.Volumes, sic.Volumes, "/spec/volumes")...)

	patch = append(patch, updateAnnotation(pod.Annotations, annotations)...)

	return json.Marshal(patch)
}

repository: richardcase/vault-inject

repo_name: richardcase/vault-inject


text:
//Copyright (C) Mr.Pungle

package web_test

import (
	"net/http"
	"testing"
)

type fakeResp struct {
	Data string
}

func (rf *fakeResp) Write(bytes []byte) (int, error) {
	rf.Data += string(bytes)
	return len(bytes), nil
}

func (rf *fakeResp) WriteHeader(code int) {
	//TODO:..
}

func (rf *fakeResp) Header() http.Header {
	return nil
}

func fakeHandler1(resp http.ResponseWriter, req *http.Request) {
	resp.Write([]byte("1"))
}

func fakeHandler2(resp http.ResponseWriter, req *http.Request) {
	resp.Write([]byte("2"))
}

func fakeHandler3(resp http.ResponseWriter, req *http.Request) {
	resp.Write([]byte("3"))
}

func fakeHandler4(resp http.ResponseWriter, req *http.Request) {
	resp.Write([]byte("4"))
}

func TestMappingResolver(t *testing.T) {
	resolver := NewMappingResolver()
	if resolver == nil {
		t.Error("Create MappingResolver Error")
	}
	uri := "abcdefa"
	resolver.AddHandler(uri, fakeHandler1)
	resolver.AddHandler(uri+"2", fakeHandler2)
	resolver.AddHandler(uri+"3", fakeHandler3)
	resolver.AddHandler(uri+"4", fakeHandler4)

	hand, err := resolver.Resolve(uri + "5")
	if hand != nil {
		t.Error("Resolve error: Found the error handler.")
	}
	if err != nil {
		t.Error("Resolve occurred error: ", err.Error())
	}

	hand, err = resolver.Resolve(uri + "3")
	if hand == nil {
		t.Error("Resolve error: Can not found the real handler.")
	}
	if err != nil {
		t.Error("Resolve occurred error: ", err.Error())
	}

	resp := &fakeResp{}
	hand(resp, nil)
	if resp.Data != "3" {
		t.Error("Resolve error: Found the error handler.", resp.Data)
	}
}

func TestPrefixResolver(t *testing.T) {
	resolver := NewPrefixResolver()
	if resolver == nil {
		t.Error("Create PrefixResolver Error")
	}
}

func TestRegexpResolver(t *testing.T) {
	resolver := NewRegexpResolver()
	if resolver == nil {
		t.Error("Create RegexpResolver Error")
	}
}

license: MIT

repository: pungle/dawn

license_type: permissive

repo_name: pungle/dawn

branch_name: refs/heads/master

extension: go


text:
/*
Copyright 2014 The Camlistore Authors.

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

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

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

package integration

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"camlistore.org/pkg/test"
)

func TestFileSharing(t *testing.T) {
	share(t, "share_test.go")
}

func TestDirSharing(t *testing.T) {
	share(t, filepath.FromSlash("../integration"))
}

func share(t *testing.T, file string) {
	w := test.GetWorld(t)
	out := test.MustRunCmd(t, w.Cmd("camput", "file", file))
	fileRef := strings.Split(out, "\n")[0]

	out = test.MustRunCmd(t, w.Cmd("camput", "share", "-transitive", fileRef))
	shareRef := strings.Split(out, "\n")[0]

	testDir, err := ioutil.TempDir("", "camli-share-test-")
	if err != nil {
		t.Fatalf("ioutil.TempDir(): %v", err)
	}
	defer os.RemoveAll(testDir)

	// test that we can get it through the share
	test.MustRunCmd(t, w.Cmd("camget", "-o", testDir, "-shared", fmt.Sprintf("%v/share/%v", w.ServerBaseURL(), shareRef)))
	filePath := filepath.Join(testDir, filepath.Base(file))
	fi, err := os.Stat(filePath)
	if err != nil {
		t.Fatalf("camget -shared failed to get %v: %v", file, err)
	}
	if fi.IsDir() {
		// test that we also get the dir contents
		d, err := os.Open(filePath)
		if err != nil {
			t.Fatal(err)
		}
		defer d.Close()
		names, err := d.Readdirnames(-1)
		if err != nil {
			t.Fatal(err)
		}
		if len(names) == 0 {
			t.Fatalf("camget did not fetch contents of directory %v", file)
		}
	}

	// test that we're not allowed to get it directly
	fileURL := fmt.Sprintf("%v/share/%v", w.ServerBaseURL(), fileRef)
	_, err = test.RunCmd(w.Cmd("camget", "-shared", fileURL))
	if err == nil {
		t.Fatal("Was expecting error for 'camget -shared " + fileURL + "'")
	}
	if !strings.Contains(err.Error(), "client: got status code 401") {
		t.Fatalf("'camget -shared %v': got error %v, was expecting 401", fileURL, err)
	}
}

repository: DavidBenko/gateway

repo_name: DavidBenko/gateway

branch_name: refs/heads/develop

gha_language: Go


text:
@inproceedings{Kanamaru2019-yj,
 author = {Kanamaru, S and Oku, D and Tawada, M and Tanaka, S and Hayashi,
M and Yamaoka, M and Yanagisawa, M and Togawa, N},
 booktitle = {2019 IEEE International Conference on Consumer Electronics
(ICCE)},
 doi = {10.1109/ICCE.2019.8661947},
 issn = {2158-4001},
 month = {January},
 pages = {1--6},
 publisher = {ieeexplore.ieee.org},
 title = {Efficient Ising Model Mapping to Solving Slot Placement Problem},
 year = {2019}
}

extension: bib


text:
// Copyright © 2017 Mike Sample <mike@mikesample.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// bigkmzCmd represents the bigkmz command
var bigkmzCmd = &cobra.Command{
	Use:   "bigkmz",
	Short: "Create a KMZ with single jpg tile of the provided jpg. Suitable for Google Earth etc, not Garmins",
	Long: `Given a name-geo-anchored JPG this creates a KMZ file containing that single JPG.
Use this for overlay maps you want to view in high resolution on Google Earth etc.

Unlike the kmz subcommand, the image is not sliced into titles to meet
device limitations. It is intended for higher resolution producing
KMZs for use on Google Earth and other apps that can handle large
images.

Input is the same name-geo-anchored JPG file as can be used with the
kmz subcommand.  For example using the same JPG file you can create a
KMZ for your Garmin with kmz subcom, and another KMZ with the bigkmz
subcommand for your PC.  E.g. in the Search and Rescue context, team
members can have the map on their GPSs in the field and a SAR manager
can use the bigkmz on Google Earth at the command post.

`,
	Run: func(cmd *cobra.Command, args []string) {
		if err := processBig(viper.GetViper(), args); err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			fmt.Fprintf(os.Stderr, "see 'cutkmz bigkmz -h' for help\n")
			os.Exit(1)
		}
	},
}

func init() {
	RootCmd.AddCommand(bigkmzCmd)

	bigkmzCmd.Flags().IntP("max_pixels", "m", 0, "max pixel area, w x h (aka 'mega-pixels'). 0 means no limit, use image as is.")
	viper.BindPFlag("max_pixels", bigkmzCmd.Flags().Lookup("max_pixels"))

	bigkmzCmd.Flags().IntP("drawing_order", "d", 51, "Garmins make values > 50 visible. Tune if have overlapping overlays.")
	viper.BindPFlag("drawing_order", bigkmzCmd.Flags().Lookup("drawing_order"))

	bigkmzCmd.Flags().BoolP("keep_tmp", "k", false, "Don't delete intermediate files from $TMPDIR.")
	viper.BindPFlag("keep_tmp", bigkmzCmd.Flags().Lookup("keep_tmp"))

	bigkmzCmd.Flags().AddGoFlagSet(flag.CommandLine)
	flag.CommandLine.VisitAll(func(f *flag.Flag) {
		viper.BindPFlag(f.Name, bigkmzCmd.Flags().Lookup(f.Name))
	})
	flag.CommandLine.Parse(nil) // shut up 'not parsed' complaints
}

// processBig processes the name-geo-anchored files args into KMZs
// with a single (large) JPG.
//
// The max_pixels (width x height) can be used to reduce quality to
// desired pixel araea.  0, the default, means unlimited/leave the
// image as is.
func processBig(v *viper.Viper, args []string) error {
	maxPixels := v.GetInt("max_pixels")
	keepTmp := v.GetBool("keep_tmp")
	drawingOrder := v.GetInt("drawing_order")

	fmt.Printf("keep_tmp: %v, maxPixels: %v, drawing_order %v\n", keepTmp, maxPixels, drawingOrder)

	if len(args) == 0 {
		return fmt.Errorf("Image file required: must provide one or more imaage file path")
	}

	for _, image := range args {
		if _, err := os.Stat(image); os.IsNotExist(err) {
			return err
		}
		absImage, err := filepath.Abs(image)
		if err != nil {
			return fmt.Errorf("Issue with an image file path: %v", err)
		}
		base, box, err := getBox(absImage)
		if err != nil {
			return fmt.Errorf("Error with image file name: %v", err)
		}
		origMap, err := newMapTileFromFile(absImage, box[north], box[south], box[east], box[west])
		if err != nil {
			return fmt.Errorf("Error extracting image dimensions: %v", err)
		}
		tmpDir, err := ioutil.TempDir("", "cutkmz-")
		if err != nil {
			return fmt.Errorf("Error creating a temporary directory: %v", err)
		}
		tilesDir := filepath.Join(tmpDir, base, "tiles")
		err = os.MkdirAll(tilesDir, 0755)
		if err != nil {
			return fmt.Errorf("Error making tiles dir in tmp dir: %v", err)
		}

		fixedJpg := filepath.Join(tilesDir, base+"_tile_000.jpg") // one tile
		if maxPixels > 0 && maxPixels < (origMap.height*origMap.width) {
			resizeFixToJpg(fixedJpg, absImage, maxPixels)
		} else {
			// just copy the file, no de-interlace or stripping
			var in, out *os.File
			if out, err = os.Create(fixedJpg); err != nil {
				return err
			}
			if in, err = os.Open(absImage); err != nil {
				return err
			}
			if _, err = io.Copy(out, in); err != nil {
				return err
			}
		}

		fixedMap, err := newMapTileFromFile(fixedJpg, box[north], box[south], box[east], box[west])
		if err != nil {
			return err
		}

		var kdocWtr *os.File

		if kdocWtr, err = os.Create(filepath.Join(tmpDir, base, "doc.kml")); err != nil {
			return err
		}
		if err = startKML(kdocWtr, base); err != nil {
			return err
		}

		var relTPath string // file ref inside KML must be relative to kmz root
		if relTPath, err = filepath.Rel(filepath.Join(tmpDir, base), fixedMap.fpath); err != nil {
			return err
		}
		if err = kmlAddOverlay(kdocWtr, base, fixedMap.box, drawingOrder, relTPath); err != nil {
			return err
		}
		endKML(kdocWtr)
		kdocWtr.Close()
		var zf *os.File
		if zf, err = os.Create(base + "-big.kmz"); err != nil {
			return err
		}
		zipd(filepath.Join(tmpDir, base), zf)
		zf.Close()

		if !keepTmp {
			err = os.RemoveAll(tmpDir)
			if err != nil {
				return fmt.Errorf("Error removing tmp dir & contents: %v", err)
			}
		}
	}
	return nil
}

repository: msample/cutkmz

repo_name: msample/cutkmz


text:
package statsmt

import (
	"sync/atomic"
	"time"
)

type Counter32 struct {
	val uint32
}

func NewCounter32(name string) *Counter32 {
	return Register.GetOrAdd(name, &Counter32{}).(*Counter32)
}

func (c *Counter32) SetUint32(val uint32) {
	atomic.StoreUint32(&c.val, val)
}

func (c *Counter32) Inc() {
	atomic.AddUint32(&c.val, 1)
}

func (c *Counter32) Add(val int) {
	c.AddUint32(uint32(val))
}

func (c *Counter32) AddUint32(val uint32) {
	atomic.AddUint32(&c.val, val)
}

func (c *Counter32) Peek() uint32 {
	return atomic.LoadUint32(&c.val)
}

func (c *Counter32) ReportGraphite(prefix, buf []byte, now time.Time) []byte {
	val := atomic.LoadUint32(&c.val)
	buf = WriteUint32(buf, prefix, []byte("counter32"), val, now)
	return buf
}

repository: grafana/carbon-relay-ng

repo_name: grafana/carbon-relay-ng

gha_license_id: NOASSERTION


text:
@misc{Abecassis2011,
  title        = {OpenCV - Rotation (Deskewing)},
  author       = {Abecassis, Felix},
  year         = 2011,
  url          = {http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/},
  urldate      = {2018-10-27},
}

repository: colour-science/colour-checker-detection

repo_name: colour-science/colour-checker-detection

gha_language: Jupyter Notebook


text:
SUMMARY = "Provides functions, widgets, and gschemas for GNOME applications which want to use archives to transfer directories over the internet"
HOMEPAGE = "https://wiki.gnome.org/TingweiLan/GSoC2013Final"

LICENSE = "LGPLv2.1"
LIC_FILES_CHKSUM = "file://COPYING;md5=4fbd65380cdd255951079008b364516c"

SRC_URI[archive.md5sum] = "39b13fb2fc7752fa3b80616244dc4ef8"
SRC_URI[archive.sha256sum] = "5de9db0db028cd6cab7c2fec46ba90965474ecf9cd68cfd681a6488cf1fb240a"

DEPENDS = "glib-2.0 gtk+3 glib-2.0-native gnome-common autoconf-archive libarchive"

do_compile_prepend() {
       export GIR_EXTRA_LIBS_PATH="${B}/gnome-autoar/.libs"
}

inherit gnomebase gobject-introspection vala

EXTRA_OECONF = ""

repository: dma/citadel

repo_name: dma/citadel

extension: bb


text:
package main

import (
	"fmt"
	"io"
	"log"
	"os"

	"github.com/fujiwara/go-zabbix-get/zabbix"
)

var Output io.Writer

func main() {
	var err error
	if len(os.Args) >= 2 {
		Output, err = os.Create(os.Args[1])
		if err != nil {
			panic(err)
		}
		log.Printf("output to %s", os.Args[1])
	} else {
		Output = os.Stdout
	}
	err = zabbix.RunTrapper("127.0.0.1:10051", handler)
	if err != nil {
		panic(err)
	}
}

func handler(req zabbix.TrapperRequest) (res zabbix.TrapperResponse, err error) {
	for _, d := range req.Data {
		line := fmt.Sprintf(
			"host:%s\tkey:%s\tvalue:%s\n",
			d.Host,
			d.Key,
			d.Value,
		)
		Output.Write([]byte(line))
	}
	res.Proceeded = len(req.Data)
	return
}

repository: fujiwara/fluent-plugin-zabbix

repo_name: fujiwara/fluent-plugin-zabbix

gha_language: Ruby


text:
package main

import (
	"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3"
	"fmt"
	"os"

	"github.com/olekukonko/tablewriter"
	"github.com/orange-cloudfoundry/cf-security-entitlement/plugin/messages"
)

type ListCommand struct {
	Api string `short:"a" long:"api" description:"api to cf security"`
}

var listCommand ListCommand

func (c *ListCommand) Execute(_ []string) error {
	client := genClient(c.Api)
	username, err := cliConnection.Username()
	if err != nil {
		return err
	}
	messages.Printf("Getting security groups as %s...\n", messages.C.Cyan(username))
	secGroups, err := client.GetSecGroups([]ccv3.Query{}, 0)
	for i := range secGroups.Resources {
		_ = client.AddSecGroupRelationShips(&secGroups.Resources[i])
	}
	if err != nil {
		return err
	}
	messages.Println(messages.C.Green("OK\n"))

	if len(secGroups.Resources) == 0 {
		return nil
	}
	data := make([][]string, 0)
	for iSec, secGroup := range secGroups.Resources {
		subData := make([]string, 0)
		subData = append(subData, fmt.Sprintf("#%d", iSec))
		subData = append(subData, secGroup.Name)
		if len(secGroup.Relationships.Running_Spaces.Data) == 0 || len(secGroup.Relationships.Staging_Spaces.Data) == 0 {
			subData = append(subData, "", "", "")
			data = append(data, subData)
			continue
		}
		// à revoir
		for iSpace, space := range secGroup.Relationships.Running_Spaces.Data {
			if iSpace > 0 {
				subData = make([]string, 0)
				subData = append(subData, "", "")
			}
			subData = append(subData, space.OrgName, space.SpaceName)
			data = append(data, append(subData, "running"))
			if iSpace == 0 {
				subData[0] = ""
				subData[1] = ""
			}
			data = append(data, append(subData, "staging"))
		}
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"#", "name", "organization", "space", "lifecycle"})
	table.AppendBulk(data)
	table.SetRowSeparator("")
	table.SetAutoFormatHeaders(false)
	table.SetCenterSeparator("")
	table.SetColumnSeparator("")
	table.SetBorder(false)
	table.SetHeaderLine(false)
	table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
	table.SetRowLine(false)
	table.Render()
	return nil
}

func init() {
	desc := `List all security groups available for an org manager`
	_, err := parser.AddCommand(
		"manager-security-groups",
		desc,
		desc,
		&listCommand)
	if err != nil {
		panic(err)
	}
}


text:
@book{unitednations1948,
  author = {United Nations},
  title = {Universal {Declaration} of {Human} {Rights}},
  date = {1948-12}
}

repository: maehr/academic-pandoc-template

repo_name: maehr/academic-pandoc-template

branch_name: refs/heads/main

gha_license_id: MIT

gha_language: HTML


text:
@article{Bergstedt-2020-Influence,
    title = "Influence of surface water on coarse resolution C-band backscatter: Implications for freeze/thaw retrieval from scatterometer data",
    author = "Bergstedt, Helena  and
      Bartsch, Annett  and
      Duguay, Claude R.  and
      Jones, Benjamin M.",
    journal = "Remote Sensing of Environment, Volume 247",
    volume = "247",
    year = "2020",
    publisher = "Elsevier BV",
    url = "https://aclanthology.org/G20-50001",
    doi = "10.1016/j.rse.2020.111911",
    pages = "111911",
    abstract = "Abstract The freeze/thaw state of permafrost landscapes is an essential variable for monitoring ecological, hydrological and climate processes. Ground surface state can be obtained from satellite data through time series analysis of C-band backscatter from scatterometer and Synthetic Aperture Radar (SAR) observations. Scatterometer data has been used in a variety of studies concerning freeze/thaw retrieval of the land surface. Coarse spatial resolution scatterometer data has great potential for application in this field due to its high temporal resolution (approx. daily observations). In this study, we investigate the influence of sub-grid cell (12.5~km) surface water (ice free and ice covered) on freeze/thaw retrieval based on ASCAT data using a threshold algorithm. We found discrepancies related to the surface water fraction in the detected timing of thawing and freezing of up to 2~days earlier thawing for spring and 3.5~days earlier freezing for autumn for open water fractions of 40{\%} resulting in an overestimation of the frozen season. Results of this study led to the creation of a method for correction of water fraction impact on freeze/thaw data. Additionally, this study demonstrates the applicability of a new approach to freeze/thaw retrieval which has not so far been tested for SAR, specifically Sentinel-1.",
}

repository: gwf-uwaterloo/gwf-publications

repo_name: gwf-uwaterloo/gwf-publications

gha_language: Python


text:
@article{FGG, title={A Quantum Approximate Optimization Algorithm}, url={http://arxiv.org/abs/1411.4028}, abstractNote={We introduce a quantum algorithm that produces approximate solutions for combinatorial optimization problems. The algorithm depends on a positive integer p and the quality of the approximation improves as p is increased. The quantum circuit that implements the algorithm consists of unitary gates whose locality is at most the locality of the objective function whose optimum is sought. The depth of the circuit grows linearly with p times (at worst) the number of constraints. If p is fixed, that is, independent of the input size, the algorithm makes use of efficient classical preprocessing. If p grows with the input size a different strategy is proposed. We study the algorithm as applied to MaxCut on regular graphs and analyze its performance on 2-regular and 3-regular graphs for fixed p. For p = 1, on 3-regular graphs the quantum algorithm always finds a cut that is at least 0.6924 times the size of the optimal cut.}, note={arXiv:1411.4028 [quant-ph]}, number={arXiv:1411.4028}, publisher={arXiv}, author={Farhi, Edward and Goldstone, Jeffrey and Gutmann, Sam}, year={2014}, month={Nov}, language={en} }

@misc{FGG2,
  doi = {10.48550/ARXIV.1412.6062},

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

  author = {Farhi, Edward and Goldstone, Jeffrey and Gutmann, Sam},

  keywords = {Quantum Physics (quant-ph), FOS: Physical sciences, FOS: Physical sciences},

  title = {A Quantum Approximate Optimization Algorithm Applied to a Bounded Occurrence Constraint Problem},

  publisher = {arXiv},

  year = {2014},

  copyright = {arXiv.org perpetual, non-exclusive license}
}

@article{spin-glass,
  doi = {10.1287/opre.36.3.493},
  url = {https://doi.org/10.1287/opre.36.3.493},
  year = {1988},
  month = jun,
  publisher = {Institute for Operations Research and the Management Sciences ({INFORMS})},
  volume = {36},
  number = {3},
  pages = {493--513},
  author = {Francisco Barahona and Martin Gr\"{o}tschel and Michael J\"{u}nger and Gerhard Reinelt},
  title = {An Application of Combinatorial Optimization to Statistical Physics and Circuit Layout Design},
  journal = {Operations Research}
}

@article{qaoa-mixers,
  doi = {10.48550/ARXIV.2203.06095},
  url = {https://arxiv.org/abs/2203.06095},
  author = {Fuchs,  Franz G. and Lye,  Kjetil Olsen and Nilsen,  Halvor Møll and Stasik,  Alexander J. and Sartor,  Giorgio},
  keywords = {Quantum Physics (quant-ph),  FOS: Physical sciences,  FOS: Physical sciences},
  title = {Constrained mixers for the quantum approximate optimization algorithm},
  publisher = {arXiv},
  year = {2022},
  copyright = {Creative Commons Attribution 4.0 International}
}

@misc{ryananderson2018quantum,
      title={Quantum Algorithms, Architecture, and Error Correction},
      author={Ciarán Ryan-Anderson},
      year={2018},
      eprint={1812.04735},
      archivePrefix={arXiv},
      primaryClass={quant-ph}
}

@inproceedings{10.5555/545381.545449,
author = {Halperin, Eran and Livnat, Dror and Zwick, Uri},
title = {MAX CUT in Cubic Graphs},
year = {2002},
isbn = {089871513X},
publisher = {Society for Industrial and Applied Mathematics},
address = {USA},
abstract = {We present an improved semidefinite programming based approximation algorithm for
the MAX CUT problem in graphs of maximum degree at most 3. The approximation ratio
of the new algorithm is at least 0.9326. This improves, and also somewhat simplifies,
a result of Feige, Karpinski and Langberg. We also observe that results of Hopkins
and Staton and of Bondy and Locke yield a simple combinatorial 4/5-approximation algorithm
for the problem. Slightly improved results would appear in the full version of the
paper.},
booktitle = {Proceedings of the Thirteenth Annual ACM-SIAM Symposium on Discrete Algorithms},
pages = {506–513},
numpages = {8},
location = {San Francisco, California},
series = {SODA '02}
}

@INPROCEEDINGS{shor,
  author={Shor, P.W.},
  booktitle={Proceedings 35th Annual Symposium on Foundations of Computer Science},
  title={Algorithms for quantum computation: discrete logarithms and factoring},
  year={1994},
  volume={},
  number={},
  pages={124-134},
  doi={10.1109/SFCS.1994.365700}
}

@inproceedings{10.1145/237814.237866,
author = {Grover, Lov K.},
title = {A Fast Quantum Mechanical Algorithm for Database Search},
year = {1996},
isbn = {0897917855},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
url = {https://doi.org/10.1145/237814.237866},
doi = {10.1145/237814.237866},
booktitle = {Proceedings of the Twenty-Eighth Annual ACM Symposium on Theory of Computing},
pages = {212–219},
numpages = {8},
location = {Philadelphia, Pennsylvania, USA},
series = {STOC '96}
}

@misc{hastings2019classical,
      title={Classical and Quantum Bounded Depth Approximation Algorithms},
      author={M. B. Hastings},
      year={2019},
      eprint={1905.07047},
      archivePrefix={arXiv},
      primaryClass={quant-ph}
}

@article{boson,
  doi = {10.4086/toc.2013.v009a004},
  url = {https://doi.org/10.4086/toc.2013.v009a004},
  year = {2013},
  publisher = {Theory of Computing Exchange},
  volume = {9},
  number = {1},
  pages = {143--252},
  author = {Scott Aaronson and Alex Arkhipov},
  title = {},
  journal = {Theory of Computing}
}

@article{boolean-fns-as-hams,
author = {Hadfield, Stuart},
title = {On the Representation of Boolean and Real Functions as Hamiltonians for Quantum Computing},
year = {2021},
issue_date = {December 2021},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
volume = {2},
number = {4},
issn = {2643-6809},
url = {https://doi.org/10.1145/3478519},
doi = {10.1145/3478519},
journal = {ACM Transactions on Quantum Computing},
month = {dec},
articleno = {18},
numpages = {21},
keywords = {Quantum optimization, diagonal Hamiltonians, Boolean and pseudo-Boolean functions, Fourier analysis on the Boolean cube}
}

@article{JPY,
title = {How easy is local search?},
journal = {Journal of Computer and System Sciences},
volume = {37},
number = {1},
pages = {79-100},
year = {1988},
issn = {0022-0000},
doi = {https://doi.org/10.1016/0022-0000(88)90046-3},
url = {https://www.sciencedirect.com/science/article/pii/0022000088900463},
author = {David S. Johnson and Christos H. Papadimitriou and Mihalis Yannakakis},
abstract = {We investigate the complexity of finding locally optimal solutions to NP-hard combinatorial optimization problems. Local optimality arises in the context of local search algorithms, which try to find improved solutions by considering perturbations of the current solution (“neighbors” of that solution). If no neighboring solution is better than the current solution, it is locally optimal. Finding locally optimal solutions is presumably easier than finding optimal solutions. Nevertheless, many popular local search algorithms are based on neighborhood structures for which locally optimal solutions are not known to be computable in polynomial time, either by using the local search algorithms themselves or by taking some indirect route. We define a natural class PLS consisting essentially of those local search problems for which local optimality can be verified in polynomial time, and show that there are complete problems for this class. In particular, finding a partition of a graph that is locally optimal with respect to the well-known Kernighan-Lin algorithm for graph partitioning is PLS-complete, and hence can be accomplished in polynomial time only if local optima can be found in polynomial time for all local search problems in PLS.}
}

@inproceedings{lass2-QMC,
  doi = {10.4230/LIPICS.ICALP.2021.102},

  url = {https://drops.dagstuhl.de/opus/volltexte/2021/14171/},

  author = {Parekh, Ojas and Thompson, Kevin},

  keywords = {Quantum Max Cut, Quantum Approximation Algorithms, Lasserre Hierarchy, Local Hamiltonian, Heisenberg model, Theory of computation → Approximation algorithms analysis, Theory of computation → Semidefinite programming, Theory of computation → Quantum complexity theory},

  language = {en},

  title = {Application of the Level-2 Quantum Lasserre Hierarchy in Quantum Approximation Algorithms},

  publisher = {Schloss Dagstuhl - Leibniz-Zentrum für Informatik},

  year = {2021},

  copyright = {Creative Commons Attribution 4.0 International license}
}

@article{barak_etal,
  author    = {Boaz Barak and
               Ankur Moitra and
               Ryan O'Donnell and
               Prasad Raghavendra and
               Oded Regev and
               David Steurer and
               Luca Trevisan and
               Aravindan Vijayaraghavan and
               David Witmer and
               John Wright},
  title     = {Beating the random assignment on constraint satisfaction problems of bounded degree},
  journal   = {CoRR},
  volume    = {abs/1505.03424},
  year      = {2015},
  url       = {http://arxiv.org/abs/1505.03424},
  eprinttype = {arXiv},
  eprint    = {1505.03424},
  timestamp = {Thu, 11 Jul 2019 13:18:08 +0200},
  biburl    = {https://dblp.org/rec/journals/corr/BarakMORRSTVWW15.bib},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}

@article{GP19,
  doi = {10.4230/LIPICS.APPROX-RANDOM.2019.31},

  url = {http://drops.dagstuhl.de/opus/volltexte/2019/11246/},

  author = {Gharibian, Sevag and Parekh, Ojas},

  keywords = {Computer Science, 000 Computer science, knowledge, general works},

  language = {en},

  title = {Almost Optimal Classical Approximation Algorithms for a Quantum Generalization of Max-Cut},

  publisher = {Schloss Dagstuhl - Leibniz-Zentrum fuer Informatik GmbH, Wadern/Saarbruecken, Germany},

  year = {2019},

  copyright = {Creative Commons Attribution 3.0 Unported license (CC-BY 3.0)}
}

@inproceedings{AGM,
  doi = {10.4230/LIPICS.TQC.2020.7},

  url = {https://drops.dagstuhl.de/opus/volltexte/2020/12066/},

  author = {Anshu, Anurag and Gosset, David and Morenz, Karen},

  keywords = {Approximation algorithms, Quantum many-body systems},

  language = {en},

  title = {Beyond Product State Approximations for a Quantum Analogue of Max Cut},

  publisher = {Schloss Dagstuhl - Leibniz-Zentrum für Informatik},

  year = {2020},

  copyright = {Creative Commons Attribution 3.0 Unported license}
}

@misc{IBMQ,
  author       = {IBM Quantum},
  url = {https://quantum-computing.ibm.com/},
  year         = {2021}
}

@misc{hhl-ex,
  doi = {10.48550/ARXIV.2108.09004},

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

  author = {Morrell, Hector Jose and Wong, Hiu Yung},

  keywords = {Quantum Physics (quant-ph), Physics Education (physics.ed-ph), FOS: Physical sciences, FOS: Physical sciences},

  title = {Step-by-Step HHL Algorithm Walkthrough to Enhance the Understanding of Critical Quantum Computing Concepts},

  publisher = {arXiv},

  year = {2021},

  copyright = {arXiv.org perpetual, non-exclusive license}
}

@article{Shearer1992,
  doi = {10.1002/rsa.3240030211},
  url = {https://doi.org/10.1002/rsa.3240030211},
  year = {1992},
  publisher = {Wiley},
  volume = {3},
  number = {2},
  pages = {223--226},
  author = {James B. Shearer},
  title = {A note on bipartite subgraphs of triangle-free graphs},
  journal = {Random Structures and Algorithms}
}

@article{pricing,
	doi = {10.22331/q-2020-07-06-291},

	url = {https://doi.org/10.22331%2Fq-2020-07-06-291},

	year = 2020,
	month = {jul},

	publisher = {Verein zur Forderung des Open Access Publizierens in den Quantenwissenschaften},

	volume = {4},

	pages = {291},

	author = {Nikitas Stamatopoulos and Daniel J. Egger and Yue Sun and Christa Zoufal and Raban Iten and Ning Shen and Stefan Woerner},

	title = {Option Pricing using Quantum Computers},

	journal = {Quantum}
}

@article{Preskill_2018,
	doi = {10.22331/q-2018-08-06-79},

	url = {https://doi.org/10.22331%2Fq-2018-08-06-79},

	year = 2018,
	month = {aug},

	publisher = {Verein zur Forderung des Open Access Publizierens in den Quantenwissenschaften},

	volume = {2},

	pages = {79},

	author = {John Preskill},

	title = {Quantum Computing in the {NISQ} era and beyond},

	journal = {Quantum}
}

@MISC{cirq,
  title     = {Cirq},
  author    = {Developers, Cirq},
  abstract  = {Cirq is a Python library for writing, manipulating, and
               optimizing quantum circuits and running them against quantum
               computers and simulators.},
  publisher = {Zenodo},
  year      =  {2021}
}

@article{goewim,
author = {Goemans, Michel X. and Williamson, David P.},
title = {Improved Approximation Algorithms for Maximum Cut and Satisfiability Problems Using Semidefinite Programming},
year = {1995},
issue_date = {Nov. 1995},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
volume = {42},
number = {6},
issn = {0004-5411},
url = {https://doi.org/10.1145/227683.227684},
doi = {10.1145/227683.227684},
journal = {J. ACM},
month = {nov},
pages = {1115–1145},
numpages = {31},
keywords = {Approximation algorithms, convex optimization, randomized algorithms, satisfiability}
}

% The entry below contains non-ASCII chars that could not be converted
% to a LaTeX equivalent.

@article{khot,
author = { Khot, Subhash and  Kindler, Guy and  Mossel, Elchanan and  O’Donnell, Ryan},
title = {Optimal Inapproximability Results for MAX‐CUT and Other 2‐Variable CSPs?},
journal = {SIAM Journal on Computing},
volume = {37},
number = {1},
pages = {319-357},
year = {2007},
doi = {10.1137/S0097539705447372},

URL = {
        https://doi.org/10.1137/S0097539705447372

},
eprint = {
        https://doi.org/10.1137/S0097539705447372

}
}

@ARTICLE{hastad,
  title     = "Some optimal inapproximability results",
  author    = "H{\aa}stad, Johan",
  journal   = "J. ACM",
  publisher = "Association for Computing Machinery (ACM)",
  volume    =  48,
  number    =  4,
  pages     = "798--859",
  month     =  jul,
  year      =  2001,
  language  = "en"
}

@article{hastad2000,
  doi = {10.1016/s0020-0190(00)00032-6},
  url = {https://doi.org/10.1016/s0020-0190(00)00032-6},
  year = {2000},
  month = apr,
  publisher = {Elsevier {BV}},
  volume = {74},
  number = {1-2},
  pages = {1--6},
  author = {Johan H{\aa}stad},
  title = {On bounded occurrence constraint satisfaction},
  journal = {Information Processing Letters}
}

@INCOLLECTION{karp,
  title     = "Reducibility among Combinatorial Problems",
  booktitle = "Complexity of Computer Computations",
  author    = "Karp, Richard M",
  publisher = "Springer US",
  pages     = "85--103",
  year      =  1972,
  address   = "Boston, MA"
}

@article{hhl,
	doi = {10.1103/physrevlett.103.150502},

	url = {https://doi.org/10.1103%2Fphysrevlett.103.150502},

	year = 2009,
	month = {oct},

	publisher = {American Physical Society ({APS})},

	volume = {103},

	number = {15},

	author = {Aram W. Harrow and Avinatan Hassidim and Seth Lloyd},

	title = {Quantum Algorithm for Linear Systems of Equations},

	journal = {Physical Review Letters}
}

@article{threshold,
  author    = {Juho Hirvonen and
               Joel Rybicki and
               Stefan Schmid and
               Jukka Suomela},
  title     = {Large Cuts with Local Algorithms on Triangle-Free Graphs},
  journal   = {CoRR},
  volume    = {abs/1402.2543},
  year      = {2014},
  url       = {http://arxiv.org/abs/1402.2543},
  eprinttype = {arXiv},
  eprint    = {1402.2543},
  timestamp = {Mon, 13 Aug 2018 16:49:05 +0200},
  biburl    = {https://dblp.org/rec/journals/corr/HirvonenRSS14.bib},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}

@article{google,
  doi = {10.1038/s41586-019-1666-5},
  url = {https://doi.org/10.1038/s41586-019-1666-5},
  year = {2019},
  month = oct,
  publisher = {Springer Science and Business Media {LLC}},
  volume = {574},
  number = {7779},
  pages = {505--510},
  author = {Frank Arute and Kunal Arya and Ryan Babbush and Dave Bacon and Joseph C. Bardin and Rami Barends and Rupak Biswas and Sergio Boixo and Fernando G. S. L. Brandao and David A. Buell and Brian Burkett and Yu Chen and Zijun Chen and Ben Chiaro and Roberto Collins and William Courtney and Andrew Dunsworth and Edward Farhi and Brooks Foxen and Austin Fowler and Craig Gidney and Marissa Giustina and Rob Graff and Keith Guerin and Steve Habegger and Matthew P. Harrigan and Michael J. Hartmann and Alan Ho and Markus Hoffmann and Trent Huang and Travis S. Humble and Sergei V. Isakov and Evan Jeffrey and Zhang Jiang and Dvir Kafri and Kostyantyn Kechedzhi and Julian Kelly and Paul V. Klimov and Sergey Knysh and Alexander Korotkov and Fedor Kostritsa and David Landhuis and Mike Lindmark and Erik Lucero and Dmitry Lyakh and Salvatore Mandr{\`{a}} and Jarrod R. McClean and Matthew McEwen and Anthony Megrant and Xiao Mi and Kristel Michielsen and Masoud Mohseni and Josh Mutus and Ofer Naaman and Matthew Neeley and Charles Neill and Murphy Yuezhen Niu and Eric Ostby and Andre Petukhov and John C. Platt and Chris Quintana and Eleanor G. Rieffel and Pedram Roushan and Nicholas C. Rubin and Daniel Sank and Kevin J. Satzinger and Vadim Smelyanskiy and Kevin J. Sung and Matthew D. Trevithick and Amit Vainsencher and Benjamin Villalonga and Theodore White and Z. Jamie Yao and Ping Yeh and Adam Zalcman and Hartmut Neven and John M. Martinis},
  title = {Quantum supremacy using a programmable superconducting processor},
  journal = {Nature}
}

 @article{king,
 title={An Improved Approximation Algorithm for Quantum Max-Cut},
 url={http://arxiv.org/abs/2209.02589},
 abstractNote={We give an approximation algorithm for Quantum Max-Cut which works by rounding an SDP relaxation to an entangled quantum state. The SDP is used to choose the parameters of a variational quantum circuit. The entangled state is then represented as the quantum circuit applied to a product state. It achieves an approximation ratio of 0.582, signiﬁcantly improving on the algorithms of Anshu, Gosset, Morenz, 0.531 [1], and Parekh, Thompson, 0.533 [2]. In addition, we also study the EPR Hamiltonian, which we argue is a natural intermediate problem which isolates some key quantum features of local Hamiltonian problems. For the EPR Hamiltonian, we give an approximation algorithm with approximation ratio √1 .}, note={arXiv:2209.02589 [quant-ph]}, number={arXiv:2209.02589}, publisher={arXiv}, author={King, Robbie}, year={2022}, month={Sep}, language={en}
 }

 @misc{UGC,
      title={Unique Games hardness of Quantum Max-Cut, and a conjectured vector-valued Borell's inequality},
      author={Yeongwoo Hwang and Joe Neeman and Ojas Parekh and Kevin Thompson and John Wright},
      year={2022},
      eprint={2111.01254},
      archivePrefix={arXiv},
      primaryClass={quant-ph}
}

 @article{PT22, title={An Optimal Product-State Approximation for 2-Local Quantum Hamiltonians with Positive Terms}, url={http://arxiv.org/abs/2206.08342}, DOI={10.48550/arXiv.2206.08342}, abstractNote={We resolve the approximability of the maximum energy of the Quantum Max Cut (QMC) problem using product states. A classical 0.498-approximation, using a basic semidefinite programming relaxation, is known for QMC, paralleling the celebrated 0.878-approximation for classical Max Cut. For Max Cut, improving the 0.878-approximation is Unique-Games-hard (UG-hard), and one might expect that improving the 0.498-approximation is UG-hard for QMC. In contrast, we give a classical 1/2-approximation for QMC that is unconditionally optimal, since simple examples exhibit a gap of 1/2 between the energies of an optimal product state and general quantum state. Our result relies on a new nonlinear monogamy of entanglement inequality on a triangle that is derived from the second level of the quantum Lasserre hierarchy. This inequality also applies to the quantum Heisenberg model, and our results generalize to instances of Max 2-Local Hamiltonian where each term is positive and has no 1-local parts. Finally, we give further evidence that product states are essential for approximations of 2-Local Hamiltonian.}, note={arXiv:2206.08342 [quant-ph]}, number={arXiv:2206.08342}, publisher={arXiv}, author={Parekh, Ojas and Thompson, Kevin}, year={2022}, month={Jun} }

@misc{LMC,
  author = {Carlson, Charlie and Jorquera, Zack and Kolla, Alexandra and Kordonowy, Steven},

  title = {Comparing a classical and quantum one round algorithm on LocalMaxCut},

  publisher = {arXiv},

  year = {2023},

  copyright = {arXiv.org perpetual, non-exclusive license}
}


text:
package stream

// Middleware for the HTTP Server.
type Middleware func(next Handler) Handler

// MiddlewareFunc returns middlewareFunc as Middleware.
func MiddlewareFunc(middlewareFunc func(next HandlerFunc) HandlerFunc) Middleware {
	return func(next Handler) Handler { return middlewareFunc(next.HandleStream) }
}

// WithMiddleware adds middleware.
func WithMiddleware(middleware ...Middleware) Option {
	return option(func(opts *options) {
		opts.middleware = append(opts.middleware, middleware...)
	})
}

// AddMiddleware adds middleware.
func (s *Server) AddMiddleware(middleware ...Middleware) {
	s.middleware = append(s.middleware, middleware...)
	s.chain = chain(s.handler, s.middleware...)
}

func chain(next Handler, m ...Middleware) Handler {
	if len(m) < 1 {
		return next
	}
	h := next
	for i := len(m) - 1; i >= 0; i-- {
		h = m[i](h)
	}
	return h
}

repository: htdvisser/exp

repo_name: htdvisser/exp


text:
package siafile

import (
	"bytes"
	"io/ioutil"
	"testing"

	"github.com/HyperspaceApp/fastrand"
)

// TestRSEncode tests the rsCode type.
func TestRSEncode(t *testing.T) {
	badParams := []struct {
		data, parity int
	}{
		{-1, -1},
		{-1, 0},
		{0, -1},
		{0, 0},
		{0, 1},
		{1, 0},
	}
	for _, ps := range badParams {
		if _, err := NewRSCode(ps.data, ps.parity); err == nil {
			t.Error("expected bad parameter error, got nil")
		}
	}

	rsc, err := NewRSCode(10, 3)
	if err != nil {
		t.Fatal(err)
	}

	data := fastrand.Bytes(777)

	pieces, err := rsc.Encode(data)
	if err != nil {
		t.Fatal(err)
	}
	_, err = rsc.Encode(nil)
	if err == nil {
		t.Fatal("expected nil data error, got nil")
	}

	buf := new(bytes.Buffer)
	err = rsc.Recover(pieces, 777, buf)
	if err != nil {
		t.Fatal(err)
	}
	err = rsc.Recover(nil, 777, buf)
	if err == nil {
		t.Fatal("expected nil pieces error, got nil")
	}

	if !bytes.Equal(data, buf.Bytes()) {
		t.Fatal("recovered data does not match original")
	}
}

func BenchmarkRSEncode(b *testing.B) {
	rsc, err := NewRSCode(80, 20)
	if err != nil {
		b.Fatal(err)
	}
	data := fastrand.Bytes(1 << 20)

	b.SetBytes(1 << 20)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		rsc.Encode(data)
	}
}

func BenchmarkRSRecover(b *testing.B) {
	rsc, err := NewRSCode(50, 200)
	if err != nil {
		b.Fatal(err)
	}
	data := fastrand.Bytes(1 << 20)
	pieces, err := rsc.Encode(data)
	if err != nil {
		b.Fatal(err)
	}

	b.SetBytes(1 << 20)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		for j := 0; j < len(pieces)/2; j += 2 {
			pieces[j] = nil
		}
		rsc.Recover(pieces, 1<<20, ioutil.Discard)
	}
}

repository: HyperspaceApp/Hyperspace

repo_name: HyperspaceApp/Hyperspace


text:
require u-boot.inc

# No patches for other machines yet
COMPATIBLE_MACHINE = "(igep0020)"

DEFAULT_PREFERENCE_igep0020 = "1"

SRC_URI = "git://git.igep.es/pub/scm/u-boot-arm.git;protocol=git \
          "

# v2010.06-2 tag -> ccba4652f9d2bd32e76770661d5b5762631f2261
SRCREV = "ccba4652f9d2bd32e76770661d5b5762631f2261"
PR = "r1"

LIC_FILES_CHKSUM = "file://COPYING;md5=4c6cde5df68eff615d36789dc18edd3b"

S = "${WORKDIR}/git"

repository: ianmartin/meta-igep

repo_name: ianmartin/meta-igep


text:
@article{marta16generalBF,
 author = {M. Gomez-Barrero and C. Rathgeb and G. Li and R. Raghavendra and J. Galbally. and C. Busch},
 journal = {Information Fusion},
 month = {07},
 owner = {marta},
 pages = {37-50},
 timestamp = {2015.11.05},
 title = {Multi-Biometric Template Protection Based on Bloom Filters},
 volume = {42},
 year = {2018}
}

repository: mgbarrero/academic-kickstart

repo_name: mgbarrero/academic-kickstart


text:
package dbutil

import (
	. "github.com/dave/jennifer/jen"
	"reflect"
)

// createUpdateFunc
func createUpdateFunc(entity reflect.Type) Code {

	query := generateUpdateQuery(entity)

	queryLit := Lit(query)

	fields := createUpdateField(entity)

	functionName := "Update"

	param1 := Id("entity").Qual(entity.PkgPath(), entity.Name())
	params := []Code{param1}

	returnType1 := Error()
	returnType := []Code{returnType1}

	return createRepoFunction(entity, functionName, params, returnType).Block(
		List(Id("_"), Err()).Op(":=").Id("r").Dot("ReadWrite").Dot("Exec").Call(queryLit, fields),
		Return().Err(),
	)

}

func createUpdateField(entity reflect.Type) Code {
	fields := []Code{}
	for i := 1; i < entity.NumField(); i++ {
		idField := Id("entity").Dot(entity.Field(i).Name)
		fields = append(fields, idField)
	}

	idField := Id("entity").Dot(entity.Field(0).Name)
	fields = append(fields, idField)

	return List(fields...)
}


text:
SUMMARY = "Backport of functools.lru_cache from Python 3.3"
HOMEPAGE = "https://github.com/jaraco/backports.functools_lru_cache"
SECTION = "devel/python"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://setup.py;beginline=42;endline=42;md5=98fc3658e5970d26f6b2109808c766be"

PYPI_PACKAGE = "backports.functools_lru_cache"

SRC_URI[md5sum] = "b26a223250bd24ea2e0ad6ce47b19084"
SRC_URI[sha256sum] = "444a21bcec4ae177da554321f81a78dc879eaa8f6ea9920cb904830585d31e95"

DEPENDS = "python-setuptools-scm-native"

inherit setuptools pypi

repository: nedap/meta-openembedded

repo_name: nedap/meta-openembedded

gha_language: BitBake


text:
var searchData=
[
  ['unflatten',['unflatten',['../classnlohmann_1_1basic__json.html#a74fa3ab2003f2f6f2b69deaafed9126d',1,'nlohmann::basic_json']]],
  ['updatecontainer',['updateContainer',['../classDockerClientpp_1_1DockerClient.html#a402bac91e8a77c25f6c2159860844b71',1,'DockerClientpp::DockerClient']]]
];

repository: fedemengo/DockerClientpp

repo_name: fedemengo/DockerClientpp

extension: js


text:
@article{baumgartnerwiederverwendung,
 author = {Baumgartner, Peter and Kalz, Marco},
 title = {Wiederverwendung von Lernobjekten aus didaktischer Sicht1 Zusammenfassung}
}

repository: mkalz/mkalz-academic

repo_name: mkalz/mkalz-academic


text:
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"sort"
	"strconv"
)

func verifyNumber(stack []int, num int) bool {
	for i := 0; i < len(stack); i++ {
		for j := 1; j < len(stack); j++ {
			if stack[i] == stack[j] {
				continue
			}
			if stack[i]+stack[j] == num {
				return true
			}
		}
	}
	return false
}

func sum(buf []int) int {
	res := 0
	for _, num := range buf {
		res += num
	}
	return res
}

func main() {
	f, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	var stack []int
	var badNumber int
	var sequence []int

	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		line := scanner.Text()
		num, err := strconv.Atoi(line)
		if err != nil {
			log.Fatal(err)
		}
		sequence = append(sequence, num)
	}
	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}

	for _, num := range sequence {
		if len(stack) < 25 {
			stack = append(stack, num)
			continue
		}
		if !verifyNumber(stack, num) {
			badNumber = num
			break
		}
		stack = append(stack[1:], num)
	}
	fmt.Println(badNumber)

	var buf []int
	for _, num := range sequence {
		buf = append(buf, num)
		if sum(buf) == badNumber {
			sort.Ints(buf)
			fmt.Println(buf[0] + buf[len(buf)-1])
			break
		} else if (sum(buf)) < badNumber {
			continue
		} else { // sum(buf) > badNumber
			for sum(buf) > badNumber {
				buf = buf[1:]
			}
			if sum(buf) == badNumber {
				sort.Ints(buf)
				fmt.Println(buf[0] + buf[len(buf)-1])
				break
			}
		}
	}
}


text:
@incollection{bestavros86,
 author               = {Azer Bestavros and Ahmed Belal},
 booktitle            = {Bulletin of the Faculty of Engineering},
 publisher            = {Alexandria University},
 title                = {{M}aster{M}ind - A Game of Diagnosis Strategies},
 year                 = {1986},
 }

@booklet{heeffer07,
 author               = {Albrecht Heeffer and Harold Heeffer},
 journal              = {Unknown Journal},
 title                = {Near-Optimal Strategies for the Game of {L}ogik},
 url                  = {http://logica.ugent.be/albrecht/thesis/Logik.pdf},
 year                 = {2007},
 }

@article{knuth76,
 author               = {Donald E. Knuth},
 journal              = {Journal of Recreational Mathematics},
 number               = {1},
 pages                = {1--6},
 title                = {The Computer As {M}aster {M}ind},
 volume               = {9},
 year                 = {1976},
 }

@article{kooi05,
 author               = {Barteld Kooi},
 journal              = {Journal of the International Computer Games Association},
 number               = {1},
 pages                = {13--20},
 title                = {Yet Another {M}astermind Strategy},
 url                  = {http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.103.3614&rep=rep1&type=pdf},
 volume               = {28},
 year                 = {2005},
 }

@article{koyama93,
 author               = {Kenji Koyama and Tony W. Lai},
 journal              = {Journal of Recreational Mathematics},
 pages                = {251--256},
 title                = {An Optimal {M}astermind Strategy},
 year                 = {1993},
 }

@article{neuwirth81,
 author               = {Wien E. Neuwirth},
 journal              = {Journal of Operational Research},
 pages                = {B257--B278},
 title                = {Some Strategies for {M}astermind},
 volume               = {26},
 year                 = {1982},
 }

@article{runarsson09,
 author               = {Thomas Philip Runarsson and Juan J. Merelo-Guervos},
 journal              = {Unknown Journal},
 title                = {Adapting Heuristic {M}astermind Strategies to Evolutionary Algorithms},
 year                 = {2009},
 }

@booklet{stuckman06,
 author               = {Jeff Stuckman and Guo-Qiang Zhang},
 title                = {{M}astermind is {NP}-Complete},
 url                  = {arXiv:cs/0512049v1},
 year                 = {2006},
 }

@booklet{francis10,
 author               = {John Francis},
 title                = {Strategies for playing {B}ulls and {C}ows},
 url                  = {http://www.jfwaf.com/Bulls%20and%20Cows.pdf},
 year                 = {2010},
 }

@booklet{slovesnov11,
 author               = {Alexey Slovesnov},
 title                = {Search of optimal algorithms for {B}ulls and {C}ows game},
 url                  = {http://bulls-cows.sourceforge.net/bullscows.pdf},
 year                 = {2011},
 }

@booklet{pepperdine10,
 author               = {Andy Pepperdine},
 title                = {The game of {MOO}},
 url                  = {http://www.pepsplace.org.uk/Trivia/Moo/Moo.pdf},
 year                 = {2010},
 }

@article{aleph71,
 author               = {$\aleph_0$},
 title                = {Computer Recreations},
 journal              = {Software -– Practice \& Experience},
 volume               = {1},
 pages                = {201--204},
 number               = {2},
 year                 = {1971},
 }

@article{ritchie01,
 author               = {Dennis Ritchie},
 title                = {Ken, {U}nix, and Games},
 journal              = {Journal of the International Computer Games Association},
 volume               = {24},
 pages                = {67--70},
 number               = {2},
 year                 = {2001},
 url                  = {http://cm.bell-labs.com/who/dmr/ken-games.html},
 }

repository: fancidev/mastermind

repo_name: fancidev/mastermind


text:
// Copyright © 2019 The Knative Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package apiserver

import (
	"github.com/spf13/cobra"

	"knative.dev/client/pkg/kn/commands"
)

func NewApiServerCommand(p *commands.KnParams) *cobra.Command {
	apiServerImporterCmd := &cobra.Command{
		Use:   "apiserver",
		Short: "Kubernetes API Server Event Source command group",
	}
	apiServerImporterCmd.AddCommand(NewApiServerCreateCommand(p))
	apiServerImporterCmd.AddCommand(NewApiServerDeleteCommand(p))
	return apiServerImporterCmd
}


text:
package internal

import (
	"errors"
	"flag"
	log "github.com/mhchlib/logger"
	"github.com/mhchlib/mconfig/core/mconfig"
	"github.com/mhchlib/mregister/register"
	"net/http"
	"strconv"
	"strings"
)

// MconfigFlag ...
type MconfigFlag struct {
	Namspace    *string
	RegistryStr *string
	StoreStr    *string
	ExposeStr   *string
	EnableDebug *bool
}

var (
	// DefaultExposePort ...
	DefaultExposePort = 8080
	// DefaultExposeIp ...
	DefaultExposeIp = ""
)

// NewMconfigFlag ...
func NewMconfigFlag() *MconfigFlag {
	return &MconfigFlag{}
}

// ParseFlag ...
func ParseFlag(mconfig *mconfig.MConfigConfig) {
	mconfigFlag := initFlagConfig()
	flag.Parse()
	err := parseFlagData(mconfigFlag, mconfig)
	if err != nil {
		log.Fatal(err)
	}
}

func parseFlagData(mconfigFlag *MconfigFlag, mconfig *mconfig.MConfigConfig) error {
	//namespace
	mconfig.Namspace = *mconfigFlag.Namspace
	//registry
	if *mconfigFlag.RegistryStr != "" {
		mconfig.RegistryAddress = *mconfigFlag.RegistryStr
	}
	//store
	if *mconfigFlag.StoreStr != "" {
		mconfig.StoreAddress = *mconfigFlag.StoreStr
	}
	//expose
	mconfig.ServerIp = DefaultExposeIp
	mconfig.ServerPort = DefaultExposePort
	if *mconfigFlag.ExposeStr != "" {
		ip, port, err := parseExposeFlag(*mconfigFlag.ExposeStr)
		if err != nil {
			return err
		}
		mconfig.ServerIp = ip
		mconfig.ServerPort = port
		if mconfig.ServerIp == "" {
			ip, err := register.GetClientIp()
			if err != nil {
				log.Fatal("get client ip error")
			}
			mconfig.ServerIp = ip
		}
	}
	//debug
	if *mconfigFlag.EnableDebug {
		//debug
		//-------------
		go func() {
			log.Info(http.ListenAndServe("localhost:6060", nil))
		}()
		log.Info("you can now open http://localhost:6060/debug/charts/ in your browser for debug, support ppprof")
		//------------------
	}
	return nil
}

func parseExposeFlag(exposeStr string) (string, int, error) {
	splits := strings.Split(exposeStr, ":")
	if len(splits) != 2 {
		return "", 0, errors.New(exposeStr + " is invalid Expose Address")
	}
	ip := splits[0]
	port, err := strconv.Atoi(splits[1])
	if err != nil {
		return "", 0, errors.New(exposeStr + " is invalid Expose Address")
	}
	return ip, port, nil
}

func initFlagConfig() *MconfigFlag {
	mconfigFlag := NewMconfigFlag()
	mconfigFlag.Namspace = flag.String("namespace", "com.github.mhchlib", "input your namespace")
	mconfigFlag.RegistryStr = flag.String("registry", "", "input registry address like etcd://127.0.0.1:2389")
	mconfigFlag.StoreStr = flag.String("store", "file://mconfigData/", "input store address like file://mconfigData/")
	mconfigFlag.ExposeStr = flag.String("expose", ":8080", "input server ip, default local ip")
	mconfigFlag.EnableDebug = flag.Bool("debug", false, "enable debug mode")
	return mconfigFlag
}

repository: nathan-jiao/mconfig

repo_name: nathan-jiao/mconfig


text:
package str

import (
	"strings"
)

func ParseLines(lines string) []string {
	lines = strings.Replace(lines, "\n\r", "\n", -1)
	lines = strings.Replace(lines, "\r", "\n", -1)

	rawArr := strings.Fields(lines)
	rawLen := len(rawArr)

	newArr := make([]string, 0, rawLen)
	set := make(map[string]struct{}, rawLen)

	for i := 0; i < rawLen; i++ {
		if _, found := set[rawArr[i]]; found {
			continue
		}

		set[rawArr[i]] = struct{}{}
		newArr = append(newArr, rawArr[i])
	}

	return newArr
}

func ParseComma(str string) []string {
	str = strings.Replace(str, "，", ",", -1)

	rawArr := strings.Split(str, ",")
	rawLen := len(rawArr)

	newArr := make([]string, 0, rawLen)
	set := make(map[string]struct{}, rawLen)

	for i := 0; i < rawLen; i++ {
		if _, found := set[rawArr[i]]; found {
			continue
		}

		set[rawArr[i]] = struct{}{}
		newArr = append(newArr, rawArr[i])
	}

	return newArr
}

func ParseCommaTrim(str string) []string {
	str = strings.Replace(str, "，", ",", -1)

	rawArr := strings.Split(str, ",")
	rawLen := len(rawArr)

	newArr := make([]string, 0, rawLen)
	set := make(map[string]struct{}, rawLen)

	for i := 0; i < rawLen; i++ {
		t := strings.TrimSpace(rawArr[i])
		if t == "" {
			continue
		}

		if _, found := set[t]; found {
			continue
		}

		set[rawArr[i]] = struct{}{}
		newArr = append(newArr, rawArr[i])
	}

	return newArr
}

func MtoL(m map[string]struct{}) []string {
	cnt := len(m)
	lst := make([]string, 0, cnt)
	for v := range m {
		lst = append(lst, v)
	}
	return lst
}

repository: toolkits/pkg

repo_name: toolkits/pkg


text:
# Additional target for code linting with clang-tidy.

set(SRCS_DIR ${CMAKE_SOURCE_DIR}/src/)
set(INCS_DIR ${CMAKE_SOURCE_DIR}/include/)
set(TEMPLATES_DIR ${CMAKE_SOURCE_DIR}/templates/)

file(GLOB_RECURSE SRCS ${SRCS_DIR}/*.cpp)
file(GLOB_RECURSE INCS ${INCS_DIR}/*.h)
file(GLOB_RECURSE TEMPLATES ${TEMPLATES_DIR}/*.tcc)

find_program(CLANG-TIDY clang-tidy)

if (CLANG-TIDY)
    add_custom_target(lint)

    set(CLANG_TIDY_CHECKS "*,-clang-analyzer-alpha.*,-llvm-header-guard,-fuchsia-*")
    set(CLANG_TIDY_CXX_STD c++14)

    foreach (SRC ${SRCS})
        add_custom_command(TARGET lint COMMAND ${CLANG-TIDY} -checks=${CLANG_TIDY_CHECKS} ${SRC} -- -std=${CLANG_TIDY_CXX_STD} -I${INCS_DIR} -I${TEMPLATES_DIR} -x c++)
    endforeach (SRC ${SRCS})

    foreach (INC ${INCS})
        add_custom_command(TARGET lint COMMAND ${CLANG-TIDY} -checks=${CLANG_TIDY_CHECKS} ${INC} -- -std=${CLANG_TIDY_CXX_STD} -I${INCS_DIR} -I${TEMPLATES_DIR} -x c++)
    endforeach (INC ${INCS})

    foreach (TEMPLATE ${TEMPLATES})
        add_custom_command(TARGET lint COMMAND ${CLANG-TIDY} -checks=${CLANG_TIDY_CHECKS} ${TEMPLATE} -- -std=${CLANG_TIDY_CXX_STD} -I${TEMPLATES_DIR} -I${TEMPLATES_DIR} -x c++)
    endforeach (TEMPLATE ${TEMPLATES})
endif (CLANG-TIDY)

repository: hnrck/seaplanes

repo_name: hnrck/seaplanes

extension: cmake


text:
package hue

type Sensor struct {
	State struct {
		Daylight    bool   `json:"daylight,omitempty"`
		Buttonevent int    `json:"buttonevent,omitempty"`
		Lastupdated string `json:"lastupdated"`
	} `json:"state"`
	Swupdate struct {
		State       string `json:"state"`
		Lastinstall string `json:"lastinstall"`
	} `json:"swupdate,omitempty"`
	Config struct {
		On            	bool 			`json:"on"`
		Configured    	bool 			`json:"configured,omitempty"`
		Sunriseoffset 	int  			`json:"sunriseoffset,omitempty"`
		Sunsetoffset  	int  			`json:"sunsetoffset,omitempty"`
		Battery   		int           	`json:"battery,omitempty"`
		Reachable 		bool          	`json:"reachable,omitempty"`
		Pending   		[]interface{} 	`json:"pending,omitempty"`
	} `json:"config"`
	Name             string `json:"name"`
	Type             string `json:"type"`
	Modelid          string `json:"modelid"`
	Manufacturername string `json:"manufacturername"`
	Productname      string `json:"productname,omitempty"`
	Diversityid      string `json:"diversityid,omitempty"`
	Swversion        string `json:"swversion"`
	Uniqueid         string `json:"uniqueid,omitempty"`
	Capabilities     struct {
		Certified bool `json:"certified"`
		Primary   bool `json:"primary"`
		Inputs    []struct {
			Repeatintervals []int `json:"repeatintervals"`
			Events          []struct {
				Buttonevent int    `json:"buttonevent"`
				Eventtype   string `json:"eventtype"`
			} `json:"events"`
		} `json:"inputs"`
	} `json:"capabilities,omitempty"`
}

repository: ermos/hue

repo_name: ermos/hue


text:
package http

import (
	"encoding/json"
	"net/http"

	"github.com/asaskevich/govalidator"
	"github.com/blacksails/mailspree"
)

func (s server) mailHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Parse incoming request
		var m mailspree.Message
		if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
			respondBadRequest(w)
			return
		}

		// Validate request
		if valid, err := govalidator.ValidateStruct(m); !valid {
			respondValidationErrors(w, err)
			return
		}

		// Send the email
		if err := s.mailingProvider.SendEmail(m); err != nil {
			// If it fails tell the client
			respond(w, http.StatusServiceUnavailable, newJSONError(err.Error()))
			return
		}
		respondOK(w, nil)
	})
}

repository: blacksails/mailspree

repo_name: blacksails/mailspree


text:
# Copyright (C) 2013 Freescale Semiconductor

DESCRIPTION = "bootloader for udoo"
require recipes-bsp/u-boot/u-boot.inc

PROVIDES += "u-boot"

PV = "v2013.10"

LICENSE = "GPLv2+"
LIC_FILES_CHKSUM = "file://Licenses/README;md5=6bc50ecab884fce80cd3ef3da8852b08"

# revision of 3.10.9-1.0.0 alpha branch
SRC_URI = "git://github.com/UDOOboard/U-Boot_Unico-2013.git \
           file://udoo-env.patch"
SRCREV = "b48999bc21243676a80f94ff1d2cd78418aca013"
S = "${WORKDIR}/git"

PACKAGE_ARCH = "${MACHINE_ARCH}"
COMPATIBLE_MACHINE = "(udoo)"

# FIXME: Allow linking of 'tools' binaries with native libraries
#        used for generating the boot logo and other tools used
#        during the build process.
EXTRA_OEMAKE += 'HOSTCC="${BUILD_CC} ${BUILD_CPPFLAGS}" \
                 HOSTLDFLAGS="-L${STAGING_BASE_LIBDIR_NATIVE} -L${STAGING_LIBDIR_NATIVE}" \
                 HOSTSTRIP=true'

repository: rehsack/meta-stef

repo_name: rehsack/meta-stef


text:
@online{01,
  title  = {Hall of Light - Zombi},
  author = {{HOL TEAM}},
  year   = {1998},
  url    = {http://hol.abime.net/1628},
  note   = {Accessed: 2020-11-10}
}
@book{02,
  title  = {Sinclair User},
  author = {{U.S. Gold Ltd}},
  year   = {1990},
  page   = {22},
  number = {98},
  url    = {https://worldofspectrum.org/archive/magazines/sinclair-user/98#22},
  note   = {Accessed: 2020-11-10}
}
@online{03,
  title  = {The Making Of Rayman},
  author = {{Retro Gamer Team}},
  year   = {2014},
  url    = {https://www.retrogamer.net/retro_games90/the-making-of-rayman/},
  note   = {Accessed: 2020-11-10}
}
@online{04,
  title  = {Ubi Uncensored: The History Of Ubisoft By The People Who Wrote It},
  author = {Bertz, Matt},
  year   = {2011},
  url    = {https://www.gameinformer.com/b/features/archive/2011/12/06/ubi-uncensored.aspx},
  note   = {Accessed: 2020-11-10}
}
@online{05,
  title  = {Ubisoft: All Our Games Will Do This UPlay Thing},
  author = {Good, Owen},
  year   = {2009},
  url    = {https://www.kotaku.com.au/2009/11/ubisoft-all-our-games-will-do-this-uplay-thing/},
  note   = {Accessed: 2020-11-10}
}
@online{06,
  title  = {Ubisoft Launches 'Uplay' Achievement and Reward System with Assassin's Creed 2},
  author = {Faylor, Chris},
  year   = {2009},
  url    = {https://www.shacknews.com/article/61288/ubisoft-launches-uplay-achievement-and},
  note   = {Accessed: 2020-11-10}
}
@online{07,
  title  = {Constant net connection no longer required for Ubisoft games},
  author = {Senior, Tom},
  year   = {2010},
  url    = {https://www.pcgamer.com/constant-net-connection-no-longer-required-for-ubisoft-games/},
  note   = {Accessed: 2020-11-10}
}
@online{08,
  title  = {E3 2019: Uplay+ Is Ubisoft Subscription, With New Releases Like Ghost Recon Breakpoint And Watch Dogs Legion},
  author = {Watts, Steve},
  year   = {2019},
  url    = {https://www.gamespot.com/articles/e3-2019-uplay-is-ubisoft-subscription-with-new-rel/1100-6467606/},
  note   = {Accessed: 2020-11-10}
}
@online{10,
  title  = {Exclusive: Assassin's Creed Q\&A - The Scimitar Engine},
  author = {{Feature Staff}},
  year   = {2007},
  url    = {http://www.gamingexcellence.com/features/exclusive-assassins-creed-q-and-a-the-scimitar-engine},
  note   = {Accessed: 2020-11-10}
}
@book{11,
  publisher = {[Châtillon] Pix'n Love},
  number    = {2},
  pages     = {193},
  title     = {Biographie d'un créateur de jeux vidéo français},
  author    = {Daniel Ichbiah and Sébastien Mirc and Michel Ancel},
  year      = {2010},
  note      = {Accessed: 2020-11-10},
  isbn      = {978-2-918272-16-8},
  note      = {Collection: Les Grands noms du jeu vidéo}
}
@online{12,
  title  = {.... Ubi stands for ubiquity, which means to be everywhere at the same time. Had it right?},
  author = {{Ubisoft Montreal}},
  year   = {2013},
  url    = {https://twitter.com/UbisoftMTL/status/303541957727248384?s=20},
  note   = {Accessed: 2020-11-10}
}
@online{13,
  title  = {Ubisoft : une famille en état de siège},
  author = {Poussielgue, Grégoire},
  year   = {2005},
  url    = {https://www.lesechos.fr/2005/03/ubisoft-une-famille-en-etat-de-siege-1064949},
  note   = {Accessed: 2020-11-10}
}
@online{14,
  title  = {Amstrad CPC 464},
  author = {{Retro Gamer Team}},
  year   = {2014},
  url    = {https://www.retrogamer.net/profiles/hardware/amstrad-cpc-464/},
  note   = {Accessed: 2020-11-10}
}
@online{15,
  title  = {Tom Clancy video games - History of the franchise},
  author = {Jones, Sam},
  year   = {2017},
  url    = {https://www.fanatical.com/en/blog/the-history-of-tom-clancy-video-games},
  note   = {Accessed: 2020-11-10}
}
@online{16,
  title  = {The 15-year evolution of Steam},
  author = {Wilde, Tyler and Sayer, Matt},
  year   = {2018},
  url    = {https://www.pcgamer.com/steam-versions/},
  note   = {Accessed: 2020-11-10}
}
@online{17,
  title  = {Ubisoft Explains Why It Doesn't Release Games On Steam},
  author = {Makuch, Eddie},
  year   = {2019},
  url    = {https://www.gamespot.com/articles/ubisoft-explains-why-it-doesnt-release-games-on-st/1100-6469502/},
  note   = {Accessed: 2020-11-10}
}
@online{18,
  title  = {Assassin's Creed 2 Deluxe Edition on Steam},
  author = {{Valve}},
  year   = {2010},
  url    = {https://store.steampowered.com/app/33230/Assassins_Creed_2_Deluxe_Edition/},
  note   = {Accessed: 2020-11-10}
}
@online{19,
  title  = {Ubisoft Connect Is a Next-Gen Uplay With Cross-Progression and Digital Rewards},
  author = {Kim, Matt},
  year   = {2020},
  url    = {https://www.ign.com/articles/ubisoft-connect-is-a-next-gen-uplay-with-cross-progression-and-digital-rewards},
  note   = {Accessed: 2020-11-10}
}
@online{20,
  title  = {UPlay+ is becoming Ubisoft+, but still isn't worth the money},
  author = {Stanton, Rich},
  year   = {2020},
  url    = {https://www.pcgamer.com/uplay-is-becoming-ubisoft-but-still-isnt-worth-the-money/},
  note   = {Accessed: 2020-11-10}
}
@online{21,
  title  = {A History Of Tom Clancy Games: From Rainbow Six To The Division},
  author = {Tucker, Jake},
  year   = {2016},
  url    = {https://www.rockpapershotgun.com/2016/03/09/tom-clancy-games-history/2/},
  note   = {Accessed: 2020-11-10}
}
@online{22,
  title  = {Full Steam ahead: The History of Valve},
  author = {Dunn, Jeff},
  year   = {2013},
  url    = {https://www.gamesradar.com/history-of-valve/},
  note   = {Accessed: 2020-11-10}
}
@online{23,
  title  = {Valve's Gabe Newell Says Piracy Is a Service Problem},
  author = {Tito, Greg},
  year   = {2011},
  url    = {https://v1.escapistmagazine.com/news/view/114391-Valves-Gabe-Newell-Says-Piracy-Is-a-Service-Problem},
  note   = {Accessed: 2020-11-10}
}

@online{24,
  title  = {Revenue generated by game sales on Steam from 2014 to 2017},
  author = {Gough, Christina},
  year   = {2020},
  url    = {https://www.statista.com/statistics/547025/steam-game-sales-revenue/},
  note   = {Accessed: 2020-12-11}
}

@online{25,
  title  = {Ubisoft's \#MeToo Reckoning, Two Months Later},
  author = {Gach, Ethan and Parrish, Ash},
  year   = {2020},
  url    = {https://kotaku.com/ubisofts-metoo-reckoning-two-months-later-1844717203},
  note   = {Accessed: 2020-12-11}
}

@online{26,
  title  = {Ubisoft CEO releases video statement addressing toxic company culture and offensive Elite Squad content},
  author = {Moyse, Chris},
  year   = {2020},
  url    = {https://www.destructoid.com/stories/ubisoft-ceo-releases-video-statement-addressing-toxic-company-culture-and-offensive-elite-squad-content-603167.phtml},
  note   = {Accessed: 2020-12-11}
}
@online{27,
  title  = {A Message From Our CEO Yves Guillemot | Ubisoft [NA]},
  author = {{Ubisoft North America}},
  year   = {2020},
  url    = {https://www.youtube.com/watch?v=NbPQoO9O0R4&feature=emb_title},
  note   = {Accessed: 2020-12-11}
}
@online{28,
  title  = {World's 15 Largest Video Game Publishers by revenue (2017)},
  author = {{GEOSHEN}},
  year   = {2018},
  url    = {https://geoshen.com/posts/15-largest-video-game-publishers-by-revenue},
  note   = {Accessed: 2020-12-11}
}
@online{29,
title={Ubisoft: Weakest Link In A Strong Industry},
author={{The GARP Investor}},
year={2020},
url={https://seekingalpha.com/article/4384220-ubisoft-weakest-link-in-strong-industry},
note={Accessed: 2020-11-10}
}

@book{game01,
  title     = {Far Cry},
  year      = {2004},
  author    = {{Crytek}},
  publisher = {{Ubisoft}}
}
@book{game02,
  title     = {Assassin’s Creed},
  year      = {2007},
  author    = {{Ubisoft Montreal}},
  publisher = {{Ubisoft}}
}
@book{game03,
  title     = {Far Cry 2},
  year      = {2008},
  author    = {{Ubisoft Montreal}},
  publisher = {{Ubisoft}}
}
@book{game04,
  title     = {Assassin’s Creed II},
  year      = {2009},
  author    = {{Ubisoft Montreal}},
  publisher = {{Ubisoft}}
}
@book{game09,
  title     = {Rayman Origins},
  year      = {2011},
  author    = {{Ubisoft Montreal}},
  publisher = {{Ubisoft}}
}

@book{game05,
  title     = {Assassin’s Creed III},
  year      = {2012},
  author    = {{Ubisoft Montreal}},
  publisher = {{Ubisoft}}
}
@book{game06,
  title     = {Watch_Dogs},
  year      = {2014},
  author    = {{Ubisoft Montreal}},
  publisher = {{Ubisoft}}
}
@book{game07,
  title     = {Assassin’s Creed Unity},
  year      = {2014},
  author    = {{Ubisoft Montreal}},
  publisher = {{Ubisoft}}
}
@book{game08,
  title     = {The Division},
  year      = {2016},
  author    = {{Massive Entertainment}},
  publisher = {{Ubisoft}}
}


text:
@InProceedings{Berthet13,
  pdf = {http://jmlr.org/proceedings/papers/v30/Berthet13.pdf},
  title = {Complexity Theoretic Lower Bounds for Sparse Principal Component Detection},
  author = {Quentin Berthet and Philippe Rigollet},
  pages = {1046-1066},
  abstract = {In the context of sparse principal component detection, we bring evidence towards the existence of a statistical price to pay for computational efficiency. We measure the performance of a test by the smallest signal strength that it can detect and we propose a computationally efficient method based on semidefinite programming. We also prove that the statistical performance of this test cannot be strictly improved by any computationally efficient method. Our results can be viewed as complexity theoretic lower bounds conditionally on the assumptions that some instances of the planted clique problem cannot be solved in randomized polynomial time. },
}

repository: mreid/papersite

repo_name: mreid/papersite

gha_language: TeX


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

SPDX-License-Identifier: Apache-2.0
*/

package client

import (
	"time"

	"github.com/mcc-github/blockchain/protos/common"
	"github.com/mcc-github/blockchain/protos/token"
	tk "github.com/mcc-github/blockchain/token"
)

type Prover interface {

	RequestIssue(tokensToIssue []*token.Token, signingIdentity tk.SigningIdentity) ([]byte, error)

	RequestTransfer(tokenIDs []*token.TokenId, shares []*token.RecipientShare, signingIdentity tk.SigningIdentity) ([]byte, error)

	RequestRedeem(tokenIDs []*token.TokenId, quantity string, signingIdentity tk.SigningIdentity) ([]byte, error)

	ListTokens(signingIdentity tk.SigningIdentity) ([]*token.UnspentToken, error)
}

type FabricTxSubmitter interface {

	Submit(txEnvelope *common.Envelope, waitTimeout time.Duration) (*common.Status, bool, error)

	CreateTxEnvelope(tokenTx []byte) (*common.Envelope, string, error)
}

type Client struct {
	Config          *ClientConfig
	SigningIdentity tk.SigningIdentity
	Prover          Prover
	TxSubmitter     FabricTxSubmitter
}

func NewClient(config ClientConfig, signingIdentity tk.SigningIdentity) (*Client, error) {
	err := ValidateClientConfig(config)
	if err != nil {
		return nil, err
	}

	prover, err := NewProverPeer(&config)
	if err != nil {
		return nil, err
	}

	txSubmitter, err := NewTxSubmitter(&config, signingIdentity)
	if err != nil {
		return nil, err
	}

	return &Client{
		Config:          &config,
		SigningIdentity: signingIdentity,
		Prover:          prover,
		TxSubmitter:     txSubmitter,
	}, nil
}

func (c *Client) Issue(tokensToIssue []*token.Token, waitTimeout time.Duration) (*common.Envelope, string, *common.Status, bool, error) {
	serializedTokenTx, err := c.Prover.RequestIssue(tokensToIssue, c.SigningIdentity)
	if err != nil {
		return nil, "", nil, false, err
	}

	txEnvelope, txid, err := c.TxSubmitter.CreateTxEnvelope(serializedTokenTx)
	if err != nil {
		return nil, "", nil, false, err
	}

	ordererStatus, committed, err := c.TxSubmitter.Submit(txEnvelope, waitTimeout)
	return txEnvelope, txid, ordererStatus, committed, err
}

func (c *Client) Transfer(tokenIDs []*token.TokenId, shares []*token.RecipientShare, waitTimeout time.Duration) (*common.Envelope, string, *common.Status, bool, error) {
	serializedTokenTx, err := c.Prover.RequestTransfer(tokenIDs, shares, c.SigningIdentity)
	if err != nil {
		return nil, "", nil, false, err
	}

	txEnvelope, txid, err := c.TxSubmitter.CreateTxEnvelope(serializedTokenTx)
	if err != nil {
		return nil, "", nil, false, err
	}

	ordererStatus, committed, err := c.TxSubmitter.Submit(txEnvelope, waitTimeout)
	return txEnvelope, txid, ordererStatus, committed, err
}

func (c *Client) Redeem(tokenIDs []*token.TokenId, quantity string, waitTimeout time.Duration) (*common.Envelope, string, *common.Status, bool, error) {
	serializedTokenTx, err := c.Prover.RequestRedeem(tokenIDs, quantity, c.SigningIdentity)
	if err != nil {
		return nil, "", nil, false, err
	}

	txEnvelope, txid, err := c.TxSubmitter.CreateTxEnvelope(serializedTokenTx)
	if err != nil {
		return nil, "", nil, false, err
	}

	ordererStatus, committed, err := c.TxSubmitter.Submit(txEnvelope, waitTimeout)
	return txEnvelope, txid, ordererStatus, committed, err
}

func (c *Client) ListTokens() ([]*token.UnspentToken, error) {
	return c.Prover.ListTokens(c.SigningIdentity)
}

repository: ubi-iot/blockchain

repo_name: ubi-iot/blockchain


text:
%%% Skróty

%%% czasopisma:

@String{j-LECT-NOTES-COMP-SCI   = "Lecture Notes in Computer Science"}

%%% wydawcy:

@String{pub-PH                  = "Pren{\-}tice-Hall"}
@String{pub-PH:adr              = "Englewood Cliffs, NJ 07632, USA"}

%%% Bibliografia:

@Article{Abboud,
author = "Abboud, Nadine and Grötschel, Martin and Koch, Thorsten",
year = "2008",
month = "06",
pages = "453-468",
title = "Mathematical methods for physical layout of printed circuit boards: An overview",
volume = "30",
journal = "OR Spectrum",
doi = "10.1007/s00291-007-0080-9"
}

@book{Khandpur,
  title={Printed Circuit Boards: Design, Fabrication, Assembly and Testing},
  author={Khandpur, R.S.},
  isbn={9780070588141},
  lccn={2006272449},
  url={https://books.google.com.bd/books?id=VY8iBAAAQBAJ},
  year={2005},
  publisher={Tata McGraw-Hill}
}

@book{Williams,
  title={Build Your Own Printed Circuit Board},
  author={Williams, A.},
  isbn={9780071427838},
  lccn={2003278564},
  url={https://books.google.pl/books?id=SoA4koYHRxsC},
  year={2004},
  publisher={McGraw-Hill Education}
}

@book{schroeder,
  title={Printed Circuit Board Design Using AutoCAD},
  author={Schroeder, C.},
  isbn={9780750698344},
  lccn={97022001},
  series={EDN series for design engineers},
  url={https://books.google.pl/books?id=t0fPJOGYaasC},
  year={1998},
  publisher={Newnes}
}

@Article{Charras,
author = "Charras, Jean-Pierre",
year = "2019",
month = "04",
title = "XNC Format: Gerber Takes Data Into the Future",
journal = "Design007",
url = "http://www.magazines007.com/pdf/Design007-Apr2019.pdf",
volume = "4",
pages = "24-28",
publisher = "Barry Matties"
}

@book{voldman,
  title={ESD: Analog Circuits and Design},
  author={Voldman, S.H.},
  isbn={9781118701683},
  lccn={2014021528},
  series={ESD series},
  url={https://books.google.pl/books?id=61QzBAAAQBAJ},
  year={2014},
  publisher={Wiley},
  chapter = {Appendix: Standards},
  pages = {250-259}
}

@book{prasad,
  title={Surface Mount Technology: Principles and Practice},
  author={Prasad, R.},
  isbn={9781461540847},
  url={https://books.google.pl/books?id=cVHtBwAAQBAJ},
  year={2013},
  publisher={Springer US}
}

@manual{vrml,
url = {https://www.w3.org/People/Raggett/vrml/vrml.html},
title = {Extending WWW to support Platform Independent Virtual Reality},
author = {David Raggett},
organization = {Hewlett Packard Laboratories},
year = {1994}
}

@book{mvp,
  title={Professional ASP.NET Design Patterns},
  author={Millett, S.},
  isbn={9780470952894},
  series={EBL-Schweitzer},
  url={https://books.google.pl/books?id=-oun5phKEhgC},
  year={2010},
  publisher={Wiley},
  page = {354-357}
}