text:
package router

import (
	"errors"
	"testing"
	"time"

	"github.com/cosminrentea/gobbler/protocol"
	"github.com/cosminrentea/gobbler/server/kvstore"
	"github.com/cosminrentea/gobbler/server/store"
	"github.com/cosminrentea/gobbler/server/store/dummystore"
	"github.com/cosminrentea/gobbler/testutil"

	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"
)

var aTestByteMessage = []byte("Hello World!")

type msChecker struct {
	*MockMessageStore
	*MockChecker
}

func newMSChecker() *msChecker {
	return &msChecker{
		NewMockMessageStore(testutil.MockCtrl),
		NewMockChecker(testutil.MockCtrl),
	}
}

type kvsChecker struct {
	*MockKVStore
	*MockChecker
}

func newKVSChecker() *kvsChecker {
	return &kvsChecker{
		NewMockKVStore(testutil.MockCtrl),
		NewMockChecker(testutil.MockCtrl),
	}
}

func TestRouter_AddAndRemoveRoutes(t *testing.T) {
	a := assert.New(t)

	// Given a Router
	router, _, _ := aStartedRouter()

	// when i add two routes in the same path
	routeBlah1, _ := router.Subscribe(NewRoute(
		RouteConfig{
			RouteParams: RouteParams{"application_id": "appid01", "user_id": "user01"},
			Path:        protocol.Path("/blah"),
			ChannelSize: chanSize,
		},
	))
	routeBlah2, _ := router.Subscribe(NewRoute(
		RouteConfig{
			RouteParams: RouteParams{"application_id": "appid02", "user_id": "user01"},
			Path:        protocol.Path("/blah"),
			ChannelSize: chanSize,
		},
	))

	// and one route in another path
	routeFoo, _ := router.Subscribe(NewRoute(
		RouteConfig{
			RouteParams: RouteParams{"application_id": "appid01", "user_id": "user01"},
			Path:        protocol.Path("/foo"),
			ChannelSize: chanSize,
		},
	))

	// then

	// the routes are stored
	a.Equal(2, len(router.routes[protocol.Path("/blah")]))
	a.True(routeBlah1.Equal(router.routes[protocol.Path("/blah")][0]))
	a.True(routeBlah2.Equal(router.routes[protocol.Path("/blah")][1]))

	a.Equal(1, len(router.routes[protocol.Path("/foo")]))
	a.True(routeFoo.Equal(router.routes[protocol.Path("/foo")][0]))

	// when i remove routes
	router.Unsubscribe(routeBlah1)
	router.Unsubscribe(routeFoo)

	// then they are gone
	a.Equal(1, len(router.routes[protocol.Path("/blah")]))
	a.True(routeBlah2.Equal(router.routes[protocol.Path("/blah")][0]))

	a.Nil(router.routes[protocol.Path("/foo")])
}

func TestRouter_ReplacingOfRoutesMatchingAppID(t *testing.T) {
	a := assert.New(t)

	// Given a Router with a route
	router, _, _ := aStartedRouter()

	matcherFunc := func(route, other RouteConfig, keys ...string) bool {
		return route.Path == other.Path && route.Get("application_id") == other.Get("application_id")
	}
	router.Subscribe(NewRoute(
		RouteConfig{
			RouteParams: RouteParams{"application_id": "appid01", "user_id": "user01"},
			Path:        protocol.Path("/blah"),
			Matcher:     matcherFunc,
		},
	))

	// when: i add another route with the same Application Id and Same Path
	router.Subscribe(NewRoute(
		RouteConfig{
			RouteParams: RouteParams{"application_id": "appid01", "user_id": "newUserId"},
			Path:        protocol.Path("/blah"),
			Matcher:     matcherFunc,
		},
	))

	// then: the router only contains the new route
	a.Equal(1, len(router.routes))
	a.Equal(1, len(router.routes["/blah"]))
	a.Equal("newUserId", router.routes["/blah"][0].Get("user_id"))
}

func TestRouter_SimpleMessageSending(t *testing.T) {
	ctrl, finish := testutil.NewMockCtrl(t)
	defer finish()
	a := assert.New(t)

	// Given a Router with route
	router, r := aRouterRoute(chanSize)
	msMock := NewMockMessageStore(ctrl)
	router.messageStore = msMock

	id, ts := uint64(2), time.Now().Unix()
	msMock.EXPECT().
		StoreMessage(gomock.Any(), gomock.Any()).
		Do(func(m *protocol.Message, nodeID uint8) (int, error) {
			m.ID = id
			m.Time = ts
			m.NodeID = nodeID
			return len(m.Encode()), nil
		})

	// when i send a message to the route
	router.HandleMessage(&protocol.Message{Path: r.Path, Body: aTestByteMessage, HeaderJSON: `{"Correlation-Id": "7sdks723ksgqn"}`})

	// then I can receive it a short time later
	assertChannelContainsMessage(a, r.MessagesChannel(), aTestByteMessage)
}

func TestRouter_RoutingWithSubTopics(t *testing.T) {
	ctrl, finish := testutil.NewMockCtrl(t)
	defer finish()
	a := assert.New(t)

	// Given a Router with route
	router, _, _ := aStartedRouter()

	msMock := NewMockMessageStore(ctrl)
	router.messageStore = msMock
	// expect a message to `blah` partition first and `blahblub` second
	firstStore := msMock.EXPECT().
		StoreMessage(gomock.Any(), gomock.Any()).
		Do(func(m *protocol.Message, nodeID uint8) (int, error) {
			a.Equal("/blah/blub", string(m.Path))
			return 0, nil
		})

	msMock.EXPECT().
		StoreMessage(gomock.Any(), gomock.Any()).After(firstStore).
		Do(func(m *protocol.Message, nodeID uint8) (int, error) {
			a.Equal("/blahblub", string(m.Path))
			return 0, nil
		})

	r, _ := router.Subscribe(NewRoute(
		RouteConfig{
			RouteParams: RouteParams{"application_id": "appid01", "user_id": "user01"},
			Path:        protocol.Path("/blah"),
			ChannelSize: chanSize,
		},
	))

	// when i send a message to a subroute
	router.HandleMessage(&protocol.Message{Path: "/blah/blub", Body: aTestByteMessage, HeaderJSON: `{"Correlation-Id": "7sdks723ksgqn"}`})

	// then I can receive the message
	assertChannelContainsMessage(a, r.MessagesChannel(), aTestByteMessage)

	// but, when i send a message to a resource, which is just a substring
	router.HandleMessage(&protocol.Message{Path: "/blahblub", Body: aTestByteMessage, HeaderJSON: `{"Correlation-Id": "7sdks723ksgqn"}`})

	// then the message gets not delivered
	a.Equal(0, len(r.MessagesChannel()))
}

func TestMatchesTopic(t *testing.T) {
	for _, test := range []struct {
		messagePath protocol.Path
		routePath   protocol.Path
		matches     bool
	}{
		{"/foo", "/foo", true},
		{"/foo/xyz", "/foo", true},
		{"/foo", "/bar", false},
		{"/fooxyz", "/foo", false},
		{"/foo", "/bar/xyz", false},
	} {
		if !test.matches == matchesTopic(test.messagePath, test.routePath) {
			t.Errorf("error: expected %v, but: matchesTopic(%q, %q) = %v",
				test.matches, test.messagePath, test.routePath, matchesTopic(test.messagePath, test.routePath))
		}
	}
}

func TestRoute_IsRemovedIfChannelIsFull(t *testing.T) {
	ctrl, finish := testutil.NewMockCtrl(t)
	defer finish()
	a := assert.New(t)

	// Given a Router with route
	router, r := aRouterRoute(chanSize)
	r.Timeout = 5 * time.Millisecond

	msMock := NewMockMessageStore(ctrl)
	router.messageStore = msMock

	msMock.EXPECT().
		StoreMessage(gomock.Any(), gomock.Any()).
		Do(func(m *protocol.Message, nodeID uint8) (int, error) {
			a.Equal(r.Path, m.Path)
			return 0, nil
		}).MaxTimes(chanSize + 1)

	// where the channel is full of messages
	for i := 0; i < chanSize; i++ {
		router.HandleMessage(&protocol.Message{Path: r.Path, Body: aTestByteMessage, HeaderJSON: `{"Correlation-Id": "id"}`})
	}

	// when I send one more message
	done := make(chan bool)
	go func() {
		router.HandleMessage(&protocol.Message{Path: r.Path, Body: aTestByteMessage, HeaderJSON: `{"Correlation-Id": "id"}`})
		done <- true
	}()

	// then: it returns immediately
	select {
	case <-done:
	case <-time.After(time.Millisecond * 10):
		a.Fail("Not returning!")
	}

	time.Sleep(time.Millisecond)

	// fetch messages from the channel
	for i := 0; i < chanSize; i++ {
		select {
		case _, open := <-r.MessagesChannel():
			a.True(open)
		case <-time.After(time.Millisecond * 10):
			a.Fail("error not enough messages in channel")
		}
	}

	// and the channel is closed
	select {
	case _, open := <-r.MessagesChannel():
		a.False(open)
	default:
		logger.Debug("len(r.C): %v", len(r.MessagesChannel()))
		a.Fail("channel was not closed")
	}
}

// Router should handle the buffered messages also after the closing of the route
func TestRouter_CleanShutdown(t *testing.T) {
	ctrl, finish := testutil.NewMockCtrl(t)
	defer finish()

	a := assert.New(t)

	var ID uint64

	msMock := NewMockMessageStore(ctrl)
	msMock.EXPECT().Store("blah", gomock.Any(), gomock.Any()).
		Return(nil).
		Do(func(partition string, callback func(msgID uint64) []byte) error {
			ID++
			callback(ID)
			return nil
		}).
		AnyTimes()

	router, _, _ := aStartedRouter()
	router.messageStore = msMock

	route, err := router.Subscribe(NewRoute(
		RouteConfig{
			RouteParams: RouteParams{"application_id": "appid01", "user_id": "user01"},
			Path:        protocol.Path("/blah"),
			ChannelSize: 3,
		},
	))
	a.Nil(err)

	doneC := make(chan bool)

	// read the messages until done is closed
	go func() {
		for {
			_, ok := <-route.MessagesChannel()
			select {
			case <-doneC:
				return
			default:
				a.True(ok)
			}
		}
	}()

	// Send messages in the router until error
	go func() {
		for {
			errHandle := router.HandleMessage(&protocol.Message{
				Path: protocol.Path("/blah"),
				Body: aTestByteMessage,
			})

			if errHandle != nil {
				mse, ok := errHandle.(*ModuleStoppingError)
				a.True(ok)
				a.Equal("Router", mse.Name)
				return
			}

			// if doneC channel has been closed and no error then we must fail the test
			select {
			case _, ok := <-doneC:
				if !ok {
					a.Fail("Expected error from router handle message")
				}
			default:
			}
		}
	}()

	close(doneC)
	err = router.Stop()
	a.Nil(err)

	// wait for above goroutine to finish
	<-time.After(100 * time.Millisecond)
}

func TestRouter_Check(t *testing.T) {
	ctrl, finish := testutil.NewMockCtrl(t)
	defer finish()
	a := assert.New(t)

	msMock := NewMockMessageStore(ctrl)
	kvsMock := NewMockKVStore(ctrl)
	msCheckerMock := newMSChecker()
	kvsCheckerMock := newKVSChecker()

	// Given a Multiplexer with route
	router, _, _ := aStartedRouter()

	// Test 0: Router is healthy by default
	a.Nil(router.Check())

	// Test 1b: Given messageStore is nil, then router's Check returns error
	router.messageStore = nil
	router.kvStore = kvsMock
	a.NotNil(router.Check())

	// Test 1c: Given kvStore is nil, then router's Check return error
	router.messageStore = msMock
	router.kvStore = nil
	a.NotNil(router.Check())

	// Test 2: Given mocked store dependencies, both healthy
	router.messageStore = msCheckerMock
	router.kvStore = kvsCheckerMock

	msCheckerMock.MockChecker.EXPECT().Check().Return(nil)
	kvsCheckerMock.MockChecker.EXPECT().Check().Return(nil)

	// Then the aggregated router health check will return "no error" / nil
	a.Nil(router.Check())

	// Test 3: Given a mocked messageStore which returns error on Check(),
	// Then router's aggregated Check() should return error
	msCheckerMock.MockChecker.EXPECT().Check().Return(errors.New("Storage is almost full"))
	a.NotNil(router.Check())

	// Test 4: Given a mocked kvStore which returns an error on Check()
	// and a healthy messageStore,
	// Then router's aggregated Check should return error
	msCheckerMock.MockChecker.EXPECT().Check().Return(nil)
	kvsCheckerMock.MockChecker.EXPECT().Check().Return(errors.New("DB closed"))
	a.NotNil(router.Check())
}

func TestPanicOnInternalDependencies(t *testing.T) {
	defer testutil.ExpectPanic(t)
	router := New(nil, nil, nil).(*router)
	router.panicIfInternalDependenciesAreNil()
}

func aStartedRouter() (*router, store.MessageStore, kvstore.KVStore) {
	kvs := kvstore.NewMemoryKVStore()
	ms := dummystore.New(kvs)
	router := New(ms, kvs, nil).(*router)
	router.Start()
	return router, ms, kvs
}

func aRouterRoute(_ int) (*router, *Route) {
	router, _, _ := aStartedRouter()
	route, _ := router.Subscribe(NewRoute(
		RouteConfig{
			RouteParams: RouteParams{"application_id": "appid01", "user_id": "user01"},
			Path:        protocol.Path("/blah"),
			ChannelSize: chanSize,
		},
	))
	return router, route
}

func assertChannelContainsMessage(a *assert.Assertions, c <-chan *protocol.Message, msg []byte) {
	select {
	case m := <-c:
		a.Equal(string(msg), string(m.Body))
	case <-time.After(time.Millisecond * 5):
		a.Fail("No message received")
	}
}

repository: cosminrentea/gobbler

repo_name: cosminrentea/gobbler


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

PR = "r0"

inherit debian-package

LICENSE = "PHP-3.0 & BSD-3-Clause"
LIC_FILES_CHKSUM = " \
    file://Auth-1.6.4/Auth.php;beginline=9;endline=13;md5=6863d257d87ab97c7e821ca3fe49a316 \
    file://Auth-1.6.4/Auth/Frontend/md5.js;endline=8;md5=915fa4679c019c47741472ce7ce6afd1 \
"

# source format is 3.0 (quilt) but there is no debian patch
DEBIAN_QUILT_PATCHES = ""

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

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

license: MIT

repository: nghiaht-tsdv/meta-debian

license_type: permissive

repo_name: nghiaht-tsdv/meta-debian

branch_name: refs/heads/jethro

gha_language: BitBake

extension: bb


text:
package cron

import (
	"time"
)

type dayPart struct {
	part
}

func (r *dayPart) toRun(t *time.Time) bool {
	value := t.Day()

	if r == nil {
		return true
	}
	if r.value != nil {
		if *r.value > 0 {
			return *r.value == value
		}
		return dateWithLastDayOfMonth(*t).Day() == value
	}

	return r.toRunWithoutValue(value)
}

func (r *dayPart) parse(str string) (*dayPart, error) {
	if p, err := parsePart(str, 0, 31); err != nil {
		return nil, err
	} else if p != nil {
		return &dayPart{part: *p}, nil
	}

	return nil, nil
}

repository: snmazko/cron-simple

repo_name: snmazko/cron-simple

branch_name: refs/heads/main

extension: go


text:
#include "tikz_visitor.hpp"

#include <algorithm>
#include <boost/algorithm/string.hpp>  // for search and replace
#include <string>

#include "label.hpp"

using namespace std;

void TikzVisitor::startUp() {
    ss << "\\documentclass[tikz]{standalone}" << endl;
    ss << "%\\documentclass[tikz,convert=pdf2svg]{standalone} % generate a SVG "
          "file automatically"
       << endl;
    ss << endl;
    ss << "\\usetikzlibrary{positioning}" << endl;
    ss << endl;
    ss << endl;

    // Generate colors based on what is used for Boxology's GUI
    for (const auto& kv : LABEL_COLORS) {
        auto color = kv.second;
        transform(color.begin(), color.end(), color.begin(), ::toupper);

        auto[id, id_capitalized] = make_id(LABEL_NAMES.at(kv.first));
        ss << "\\definecolor{" << id << "}{HTML}{" << color.substr(1) << "}" << endl;
    }

    ss << "\n\\begin{document}" << endl;
    ss << endl;

    ss << "\\begin{tikzpicture}[" << endl;
    ss << "             font=\\sffamily," << endl;
    ss << "             >=latex," << endl;
    ss << "             every edge/.style={draw, very thick}," << endl;
    ss << "             node/.style={draw, rounded corners, align=center, "
          "inner sep=5pt, fill=black!20},"
       << endl;
    ss << "             label/.style={midway, align=center, "
          "fill=white, text width=20mm}]"
       << endl;
    ss << endl;
}

void TikzVisitor::tearDown() {
    ss << endl;
    ss << "\\end{tikzpicture}" << endl;
    ss << "\\end{document}" << endl;

    _content = ss.str();
}

void TikzVisitor::beginNodes() { ss << "        %%% NODES" << endl; }

void TikzVisitor::onNode(shared_ptr<const Node> node) {

    auto[label_id, label_id_capitalized] = make_id(LABEL_NAMES.at(node->label()));
    auto[id, id_capitalized] = make_id(node->name());

    ss << "        \\node "
          "at ("
       << tikz_unit(node->x()) << "," << tikz_unit(-node->y())
       << ") "
          "[node, "
          "anchor=north west, "
          "text width="
       << tikz_unit(node->width())
       << ", "
          "minimum width="
       << tikz_unit(node->width())
       << ", "
          "minimum height="
       << tikz_unit(node->height())
       << ", "
          "fill="
       << label_id
       << "!50]"
       << " (" << id << ") {" << sanitize_tex(node->name())
       << "};";
    ss << endl;

    // for (const auto port : node->ports()) {
    //    port->name;
    //    (port->direction == Port::Direction::IN ? "in" : "out");
    //}
}

void TikzVisitor::beginConnections() {
    ss << endl;
    ss << "        %%% CONNECTIONS" << endl;
}

void TikzVisitor::onConnection(shared_ptr<const Connection> connection) {
    // connection->name;

    auto from = connection->from.node.lock();
    auto to = connection->to.node.lock();

    auto[from_id, from_id_capitalized] = make_id(from->name());
    auto[to_id, to_id_capitalized] = make_id(to->name());

    if (connection->name == "anonymous") {
        ss << "        \\path (" << from_id
           << ") "
              "edge [->, out=0, in=180] "
              "("
           << to_id << ");" << endl;
    } else {
        ss << "        \\path (" << from_id
           << ") "
              "edge [->, out=0, in=180] node[label] {"
           << sanitize_tex(connection->name)
           << "}"
              "("
           << to_id << ");" << endl;
    }
}

string TikzVisitor::tikz_unit(const double dim) {
    stringstream ss;
    ss << (int)(dim * pix2mm) << "mm";
    return ss.str();
}

string TikzVisitor::sanitize_tex(const std::string& text) {
    string result(text);

    // special-case the backslash
    boost::replace_all(result, "\\", "\\textbackslash");

    map<string, string> tex_substitutions{
        {"{", "\\{"}, {"}", "\\}"},
        {"$", "\\$"}, {"&", "\\&"},
        {"#", "\\#"}, {"^", "\\textasciicircum{}"},
        {"_", "\\_"}, {"~", "\\textasciitilde{}"},
        {"%", "\\%"}};

    for (const auto& kv : tex_substitutions) {
        boost::replace_all(result, kv.first, kv.second);
    }

    // finish the backslash special-case
    boost::replace_all(result, "textbackslash", "textbackslash{}");

    return result;
}

repository: severin-lemaignan/boxology

repo_name: severin-lemaignan/boxology

branch_name: refs/heads/master

extension: cpp


text:
// Copyright 2021 The Terraformer 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 aws

import (
	"context"
	"github.com/aws/aws-sdk-go-v2/service/opsworks"
	"github.com/aws/aws-sdk-go-v2/service/opsworks/types"
	"log"

	"github.com/GoogleCloudPlatform/terraformer/terraformutils"
)

type OpsworksGenerator struct {
	AWSService
}

func (g *OpsworksGenerator) InitResources() error {
	config, e := g.generateConfig()
	if e != nil {
		return e
	}
	svc := opsworks.NewFromConfig(config)

	e = g.fetchStacks(svc)
	if e != nil {
		return e
	}

	e = g.fetchUserProfile(svc)
	if e != nil {
		return e
	}

	return nil
}

func (g *OpsworksGenerator) fetchApps(stackID *string, svc *opsworks.Client) error {
	apps, err := svc.DescribeApps(context.TODO(), &opsworks.DescribeAppsInput{
		StackId: stackID,
	})
	if err != nil {
		return err
	}
	for _, app := range apps.Apps {
		g.Resources = append(g.Resources, terraformutils.NewSimpleResource(
			StringValue(app.AppId),
			StringValue(app.AppId),
			"aws_opsworks_application",
			"aws",
			[]string{"tags."},
		))
	}
	return nil
}

func (g *OpsworksGenerator) fetchLayers(stackID *string, svc *opsworks.Client) error {
	apps, err := svc.DescribeLayers(context.TODO(), &opsworks.DescribeLayersInput{
		StackId: stackID,
	})
	if err != nil {
		return err
	}
	for _, layer := range apps.Layers {
		switch layer.Type {
		case types.LayerTypeCustom:
			g.Resources = append(g.Resources, terraformutils.NewSimpleResource(
				StringValue(layer.LayerId),
				StringValue(layer.LayerId),
				"aws_opsworks_custom_layer",
				"aws",
				[]string{"tags."},
			))
		case types.LayerTypePhpApp:
			g.Resources = append(g.Resources, terraformutils.NewSimpleResource(
				StringValue(layer.LayerId),
				StringValue(layer.LayerId),
				"aws_opsworks_php_app_layer",
				"aws",
				[]string{"tags."},
			))
		case types.LayerTypeJavaApp:
			g.Resources = append(g.Resources, terraformutils.NewSimpleResource(
				StringValue(layer.LayerId),
				StringValue(layer.LayerId),
				"aws_opsworks_java_app_layer",
				"aws",
				[]string{"tags."},
			))
		case types.LayerTypeWeb:
			g.Resources = append(g.Resources, terraformutils.NewSimpleResource(
				StringValue(layer.LayerId),
				StringValue(layer.LayerId),
				"aws_opsworks_static_web_layer",
				"aws",
				[]string{"tags."},
			))
		}
	}
	return nil
}

func (g *OpsworksGenerator) fetchInstances(stackID *string, svc *opsworks.Client) error {
	apps, err := svc.DescribeInstances(context.TODO(), &opsworks.DescribeInstancesInput{
		StackId: stackID,
	})
	if err != nil {
		return err
	}
	for _, instances := range apps.Instances {
		g.Resources = append(g.Resources, terraformutils.NewSimpleResource(
			StringValue(instances.InstanceId),
			StringValue(instances.InstanceId),
			"aws_opsworks_instance",
			"aws",
			[]string{"tags."},
		))
	}
	return nil
}
func (g *OpsworksGenerator) fetchRdsInstances(stackID *string, svc *opsworks.Client) error {
	apps, err := svc.DescribeRdsDbInstances(context.TODO(), &opsworks.DescribeRdsDbInstancesInput{
		StackId: stackID,
	})
	if err != nil {
		return err
	}
	for _, rdsDbInstance := range apps.RdsDbInstances {
		g.Resources = append(g.Resources, terraformutils.NewResource(
			StringValue(rdsDbInstance.RdsDbInstanceArn),
			StringValue(rdsDbInstance.RdsDbInstanceArn),
			"aws_opsworks_instance",
			"aws",
			map[string]string{
				"rds_db_instance_arn": StringValue(rdsDbInstance.RdsDbInstanceArn),
				"stack_id":            StringValue(stackID),
			},
			[]string{"tags."},
			map[string]interface{}{},
		))
	}
	return nil
}

func (g *OpsworksGenerator) fetchStacks(svc *opsworks.Client) error {
	apps, err := svc.DescribeStacks(context.TODO(), &opsworks.DescribeStacksInput{})
	if err != nil {
		return err
	}
	for _, stack := range apps.Stacks {
		g.Resources = append(g.Resources, terraformutils.NewSimpleResource(
			StringValue(stack.StackId),
			StringValue(stack.StackId),
			"aws_opsworks_stack",
			"aws",
			[]string{"tags."},
		))

		e := g.fetchApps(stack.StackId, svc)
		if e != nil {
			log.Println(err)
		}

		e = g.fetchInstances(stack.StackId, svc)
		if e != nil {
			log.Println(err)
		}

		e = g.fetchRdsInstances(stack.StackId, svc)
		if e != nil {
			log.Println(err)
		}

		e = g.fetchLayers(stack.StackId, svc)
		if e != nil {
			log.Println(err)
		}
	}
	return nil
}

func (g *OpsworksGenerator) fetchUserProfile(svc *opsworks.Client) error {
	apps, err := svc.DescribeUserProfiles(context.TODO(), &opsworks.DescribeUserProfilesInput{})
	if err != nil {
		return err
	}
	for _, userProfile := range apps.UserProfiles {
		g.Resources = append(g.Resources, terraformutils.NewSimpleResource(
			StringValue(userProfile.IamUserArn),
			StringValue(userProfile.IamUserArn),
			"aws_opsworks_user_profile",
			"aws",
			[]string{"tags."},
		))
	}
	return nil
}

repository: IAC-InfrastructureAsCode/terraformer

repo_name: IAC-InfrastructureAsCode/terraformer

gha_language: Go


text:
DESCRIPTION = "OPKG feed for kedder PPA"
HOMEPAGE = "https://github.com/kedder/openvario-ppa"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

inherit allarch

SRC_URI = " \
    file://kedder-feeds.conf \
"

do_configure() {
    :
}

do_compile() {
    :
}

do_install() {
    install -d ${D}/etc/opkg
    install -m 0644 ${WORKDIR}/kedder-feeds.conf ${D}/etc/opkg
}

FILES:${PN} = "/etc/opkg/kedder-feeds.conf"

repository: kedder/openvario-ppa

repo_name: kedder/openvario-ppa


text:
//
//	Created by MarcasRealAccount on 8. Oct. 2020
//

#include "Engine/Configuration/ConfigurationFile.h"
#include "Engine/Configuration/ConfigurationManager.h"

#include <stdint.h>
#include <filesystem>

namespace gp1 {

	namespace configuration {

		ConfigurationFile::ConfigurationFile(std::string id, std::string filePath)
			: m_id(id), m_filePath(filePath) {}

		ConfigurationFile::~ConfigurationFile() {
			SaveConfiguration();
			ConfigurationManager::RemoveConfigurationFileImpl(this);
		}

		void ConfigurationFile::ReadConfiguration() {
			FILE* file = fopen(this->m_filePath.c_str(), "r");
			if (file) {
				fseek(file, 0, SEEK_END);
				uint32_t length = (uint32_t)ftell(file);
				char* buf = new char[length];
				fseek(file, 0, SEEK_SET);
				fread(buf, sizeof(char), length, file);

				std::string currentLine = "";
				for (uint32_t i = 0; i < length; i++) {
					char c = buf[i];
					if (c == '\n') {
						size_t separatorIndex = currentLine.find_first_of('=');
						std::string configId = currentLine.substr(0, separatorIndex);
						std::string configValue = currentLine.substr(separatorIndex + 1);
						SetConfig(configId, configValue);
						currentLine = "";
					} else {
						currentLine += c;
					}
				}

				delete[] buf;
				fclose(file);
			}
		}

		void ConfigurationFile::SaveConfiguration() {
			std::filesystem::path filepath{ this->m_filePath };
			std::filesystem::create_directories(filepath.parent_path());

			FILE* file = fopen(this->m_filePath.c_str(), "w");
			if (file) {
				for (auto config : this->m_configs) {
					fwrite(config.first.c_str(), sizeof(char), config.first.size(), file);
					fwrite("=", sizeof(char), 1, file);
					fwrite(config.second.c_str(), sizeof(char), config.second.size(), file);
					fwrite("\n", sizeof(char), 1, file);
				}
				fclose(file);
			}
		}

		void ConfigurationFile::SetConfig(std::string configId, std::string configValue) {
			this->m_configs.insert_or_assign(configId, configValue);
		}

		void ConfigurationFile::RemoveConfig(std::string configId) {
			auto itr = this->m_configs.find(configId);
			if (itr != this->m_configs.end())
				this->m_configs.erase(itr);
		}

		const std::string* ConfigurationFile::GetConfig(std::string configId) {
			auto itr = this->m_configs.find(configId);
			if (itr != this->m_configs.end())
				return &itr->second;
			return nullptr;
		}

		const std::string& ConfigurationFile::GetId() const {
			return this->m_id;
		}

	} // namespace configuration

} // namespace gp1


text:
@article{klein2020-async-hpo,
  title={{M}odel-based {A}synchronous {H}yperparameter and {N}eural {A}rchitecture {S}earch},
  author={Klein, Aaron and Tiao, Louis and Lienart, Thibaut and Archambeau, C\'{e}dric and Seeger, Matthias},
  journal={arXiv preprint arXiv:2003.10865},
  year={2020},
  month={March}
}

extension: bib


text:
SUMMARY = "Components for common profile testing and interactive use"
LICENSE = "MIT"

inherit packagegroup

RDEPENDS_${PN} = " \
    connman-client \
"

repository: intel/intel-iot-refkit

repo_name: intel/intel-iot-refkit

gha_license_id: MIT

gha_language: Python


text:
// MIT License
//
// Copyright (c) 2019 Thibault NORMAND
//
// 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 db

import (
	"math"
)

const (
	// DefaultPerPage defines the default value for pagination
	DefaultPerPage uint = 20
)

// Pagination is a pagination calcul handler for database request.
type Pagination struct {
	Page    uint
	PerPage uint
	total   uint
}

// SetTotal is used to defines the total count of paginated values.
func (p *Pagination) SetTotal(total uint) {
	p.total = total
}

// NumPages returns the total number of pages
func (p *Pagination) NumPages() uint {
	return maxuint(1, uint(math.Ceil(float64(p.total)/float64(p.PerPage))))
}

// Total returns the total number of items
func (p *Pagination) Total() uint {
	return p.total
}

// Offset returns the offset of first element
func (p *Pagination) Offset() uint {
	offset := (p.Page - 1) * p.PerPage
	// a couple reasonable boundaries
	offset = minuint(offset, p.total)
	offset = maxuint(offset, 0)
	return offset
}

// PrevPage returns the page number for the page before this
// bottoms out at the first page
func (p *Pagination) PrevPage() uint {
	return maxuint(p.Page-1, 1)
}

// HasPrev returns the status if current page has a previous one
func (p *Pagination) HasPrev() bool {
	return p.Page > 1
}

// NextPage returns the page number for the next page. won't go past the end
func (p *Pagination) NextPage() uint {
	return minuint(p.Page+1, p.NumPages())
}

// HasNext returns the status if current page has a next one
func (p *Pagination) HasNext() bool {
	return p.Page+1 <= p.NumPages()
}

// HasOtherPages returns the status of having previous or next pages
func (p *Pagination) HasOtherPages() bool {
	return p.HasPrev() || p.HasNext()
}

// CurrentPageCount returns the element count of the current page
func (p *Pagination) CurrentPageCount() uint {
	return minuint((p.total - p.Offset()), p.PerPage)
}

// NewPaginator returns a pagination holder
func NewPaginator(page, perPage uint) *Pagination {
	// Sanitize inputs
	if page <= 0 {
		page = 1
	}
	if perPage <= 0 {
		perPage = DefaultPerPage
	}

	// Return paginator instance
	return &Pagination{
		Page:    page,
		PerPage: perPage,
		total:   0,
	}
}

// -----------------------------------------------------------------------------

func minuint(a, b uint) uint {
	return uint(math.Min(float64(a), float64(b)))
}

func maxuint(a, b uint) uint {
	return uint(math.Max(float64(a), float64(b)))
}


text:
require gnuplot.inc

PR = "r5"

SRC_URI = "ftp://ftp.gnuplot.info/pub/gnuplot/gnuplot-${PV}.tar.gz \
	   file://subdirs.patch;patch=1 \
	   file://debian-separate-x11-package.patch;patch=1 \
	   http://www.mneuroth.de/privat/zaurus/qtplot-0.2.tar.gz \
	   file://matrix.patch;patch=1 \
   	   file://term.patch;patch=1 \
	   file://gnuplot.desktop \
	   file://gnuplot.png"


text:
#include "mainwindow.h"
#include "ui_mainwindow.h"

void msg(QString msg){
    QMessageBox msgBox;
    msgBox.setText(msg);
    msgBox.exec();
}

MainWindow::MainWindow() :
    QMainWindow(),
    ui(new Ui::MainWindow)
{
    this->controller = new Controller();

    QObject::connect(controller, SIGNAL(processAddNodeList(OBBNode*)),
                              this, SLOT(addNodeList(OBBNode*)));

    QObject::connect(controller, SIGNAL(processRemoveNodeList(OBBNode*)),
                              this, SLOT(removeNodeList(OBBNode*)));

    //QObject::connect(&subjectDialog, SIGNAL(processPassinfo(SubInfo)),
      //                        this, SLOT(passSubinfo(SubInfo)));

    ui->setupUi(this);

    this->receiverLiveStream = NULL;
    this->eventsLiveStream = NULL;
    this->numberOfBStream = 0;
    this->numberOfVStream = 0;
    this->lastIndexLiveStream = -1;

    QStandardItemModel *model = new QStandardItemModel(0, MAX_COLUMNS_TABLE_EVENTS, this);
    uint j = 0;
    for(j = 0; j < MAX_COLUMNS_TABLE_EVENTS; j++){
        model->setHorizontalHeaderItem(j, new QStandardItem(columns_name[j]));
    }

    ui->tableEvents->setModel(model);

    this->controller->startService();

    qRegisterMetaType<BehaviorEventPacket>("BehaviorEventPacket");
    qRegisterMetaType<QList<QString> >("QList<QString>");

    sqldb = new SQLiteDatabaseManager(); //default
    if(!sqldb->exists())
        sqldb->create();

    OpenBBoxManagerDAO dao(sqldb);

    idmanager = dao.insert(new OpenBBoxManagerObject(QDateTime::currentDateTime().toTime_t()));

    if(idmanager < 0){
        msg("OpenBBox Manager: Error inserting new Manager`s instance.\n " + sqldb->lastError().text() + "\n\n Closing aplication");
        exit(EXIT_FAILURE);
    }

    ui->actionSQLite->setChecked(true);
    lastQAction = ui->actionSQLite;

}

void MainWindow::addNewEvent(QString key, BehaviorEventPacket packet){
//#define COLUMNS_NAME {QString("id"), QString("sec"), QString("type"), QString("pin"), QString("context")}
       if(mapEventsStream.contains(key)) {
           if(mapEventsStream.value(key)->rowCount() >= MAX_ROWS_TABLE_EVENTS) {
                mapEventsStream.value(key)->takeRow(0);
           }
               QList<QStandardItem *> *info = new QList<QStandardItem *>();
               info->push_back(new QStandardItem(QString::number(packet.pktBehaviorContext.id)));
               info->push_back(new QStandardItem(QString::number(packet.pktBehaviorContext.time)));
               info->push_back(new QStandardItem(QString::number(packet.pktBehaviorContext.typePin)));
               info->push_back(new QStandardItem(QString::number(packet.pktBehaviorContext.typeEvent)));
               info->push_back(new QStandardItem(QString::number(packet.pktBehaviorContext.pin)));
               info->push_back(new QStandardItem(QString::fromLatin1(packet.pktBehaviorContext.pinsContext)));
               if(info->size() == MAX_COLUMNS_TABLE_EVENTS){
               mapEventsStream.value(key)->appendRow(*info);
               ui->tableEvents->scrollToBottom();
           }else{
               qCritical("Error: Size of column events dont match");
           }
       }

}

void MainWindow::addPacketDB(QString key, uint idtask, BehaviorEventPacket packet, uint port, long time){

    BehaviorEventPacketDAO bepdao(sqldb);
    bepdao.insert(new BehaviorEventPacketObject(idtask, port, time,
                                                packet.pktBehaviorContext.id,
                                                packet.pktBehaviorContext.time,
                                                packet.pktBehaviorContext.time_usec,
                                                packet.pktBehaviorContext.pin,
                                                packet.pktBehaviorContext.typeEvent,
                                                packet.pktBehaviorContext.typePin,
                                                QString::fromLatin1(packet.pktBehaviorContext.pinsContext)));

    if(packet.pktBehaviorContext.pin == 0 && packet.pktBehaviorContext.typeEvent == 1){
        setTaskEnd(key);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::addNodeList(OBBNode * node)
{
    char labelStr[sizeof("Stream xxxxxxx")];
    char tooltipStr[sizeof("Label: xxxxxxxxxxxxxxxxxxxxx IP: xxxxxxxxxxxxxxx MAC: xx:xx:xx:xx:xx:xx No. Cam: xx")];
    struct sockaddr_in addr_remote;
    addr_remote.sin_addr.s_addr = (in_addr_t)node->getIPAdress();
    QString ip = inet_ntoa(addr_remote.sin_addr);

    sprintf(labelStr,"Stream %d", numberOfBStream);
    QString key(labelStr);
    sprintf(tooltipStr,"Label: %s IP: %s MAC: %s No. Cam: %d", node->getLabel(), qPrintable(ip), node->getMacAddress(), node->getNumberOfVideoStream());
    QString tooltip(tooltipStr);

    QListWidgetItem * item = new QListWidgetItem(key);
    item->setToolTip(tooltip);
    item->setIcon(QIcon(RESOURCE_IMAGE_STOP));
    ui->listUIServers->addItem(item);
    node->getBehaviorStream()->setKeySteam(labelStr);
    mapNode.insert(labelStr, node);

    //Creating map of behavior events
    QStandardItemModel *model = new QStandardItemModel(0, MAX_COLUMNS_TABLE_EVENTS, this); //2 Rows and 3 Columns
    int i = 0;

    for(i = 0; i < MAX_COLUMNS_TABLE_EVENTS; i++){
        model->setHorizontalHeaderItem(i, new QStandardItem(columns_name[i]));
    }

    mapEventsStream.insert(labelStr, model);
    PinconfigDialog * pinconfig = new PinconfigDialog();
    pinconfig->setKeystream(labelStr);
    mapPinpanel.insert(labelStr, pinconfig);

    QObject::connect(pinconfig, SIGNAL(processStopNodeTestSender(QString)), this, SLOT(stopNodeTestSender(QString)));

    for(i = 0; i < node->getNumberOfVideoStream(); i++){
        sprintf(labelStr,"Stream %d Camera %d", numberOfBStream, i);
        numberOfVStream++;
        mapReceiver.insert(labelStr, node->getVideoStream(i));
        node->getVideoStream(i)->setKeyStream(labelStr);
    }

    numberOfBStream++;

    QObject::connect(node->getBehaviorStream(), SIGNAL(processAddNewEvent(QString,BehaviorEventPacket)),
                     this, SLOT(addNewEvent(QString,BehaviorEventPacket)));

    QObject::connect(node->getBehaviorStream(), SIGNAL(processAddPacketDB(QString, uint, BehaviorEventPacket, uint, long)),
                              this, SLOT(addPacketDB(QString, uint, BehaviorEventPacket, uint, long)));

    OpenBBoxNodeDAO dao(sqldb);
    int id = dao.insert(new OpenBBoxNodeObject(idmanager,
                                               QDateTime::currentDateTime().toTime_t(),
                                               0,
                                               node->getLabel(),
                                               node->getMacAddress(),
                                               ip,
                                               node->getPortController(),
                                               node->getNumberOfVideoStream()));
    if(id != -1) {
        node->setIDDatabase(id);
    }else{
        msg("OpenBBox Manager: Error inserting new OpenBBoxNode`s instance.\n " + sqldb->lastError().text() + "\n\n Closing aplication");
    }
}

void MainWindow::removeNodeList(OBBNode * node)
{
    int i = 0;
    int j = 0;
    //remove node (basic)
    mapNode.remove(node->getBehaviorStream()->getKeyStream());
    //remove the behavior event table of the node
    mapEventsStream.remove(node->getBehaviorStream()->getKeyStream());
    //remove the pinpanel of the node
    mapPinpanel.remove(node->getBehaviorStream()->getKeyStream());
    //remove the node showed in the UI
    for(j = 0; j < ui->listUIServers->count(); j++){
        QListWidgetItem* item = ui->listUIServers->item(j);
        if(item->text().compare(node->getBehaviorStream()->getKeyStream()) == 0){
            QListWidgetItem* itemToRemove = ui->listUIServers->takeItem(j);
            delete itemToRemove;
            break;
        }
    }
    //remove the video streamed showed in the UI
    if(node->getNumberOfVideoStream()>0){
        for(int i = 0; i < ui->listCameras->count(); i++){
            if(ui->listCameras->item(i)->text().contains(node->getBehaviorStream()->getKeyStream())){
                QListWidgetItem* itemToRemove = ui->listCameras->takeItem(i);
                delete itemToRemove;
            }
        }
    }

    for(i = 0; i < node->getNumberOfVideoStream(); i++){
        mapReceiver.remove(node->getVideoStream(i)->getKeyStream());
        if(receiverLiveStream ==  node->getVideoStream(i)){
            QObject::disconnect(receiverLiveStream, SIGNAL(processDisplayFrames(uchar*, uint, uint, uint, uint)),
                                  this, SLOT(updatePlayerUIBuffer(uchar*, uint, uint, uint, uint)));
            receiverLiveStream->setLiveStream(false);
            receiverLiveStream = NULL;
            lastIndexLiveStream = -1;
            ui->label->clear();
        }
        node->getVideoStream(i)->stopServer();
    }
    node->getBehaviorStream()->stopServer();
   //delete node;
}

void MainWindow::updatePlayerUI(QImage img, QString info)
{
    (void)info;
    if (!img.isNull())
    {
        // Convert the QImage to a QPixmap for display
        QPixmap p;
        image2Pixmap(img,p);
        ui->label->setPixmap(p);
    }
}
//TODO [DecodeYUV] Improve method
QImage decodeYUV_impl(uint8_t * rawStreamingFrame, int width, int height, int size)
{
    //int sz = width * height;
    QImage img(width, height, QImage::Format_RGB888);
      img.fill(QColor(Qt::white).rgb());

    QImage rgbImage;

    /*  for (int x = 0; x < 10; ++x) {
        for (int y = 0; y < 10; ++y) {
          img.setPixel(x, y, qRgb(0, 0, 0));
        }
      }
    int i, j;
    int Y, Cr = 0, Cb = 0;
    for (j = 0; j < height; j++) {
        int pixPtr = j * width;
        int jDiv2 = j >> 1;
                    for (i = 0; i < width; i++) {
                        Y = fg[pixPtr];
                        if (Y < 0)
                            Y += 255;
                        if ((i & 0x1) != 1) {
                            int cOff = sz + jDiv2 * width + (i >> 1) * 2;
                            Cb = fg[cOff];
                            if (Cb < 0)
                                Cb += 127;
                            else
                                Cb -= 128;
                            Cr = fg[cOff + 1];
                            if (Cr < 0)
                                Cr += 127;
                            else
                                Cr -= 128;
                        }
                        int R = Y + Cr + (Cr >> 2) + (Cr >> 3) + (Cr >> 5);
                        if (R < 0)
                            R = 0;
                        else if (R > 255)
                            R = 255;
                        int G = Y - (Cb >> 2) + (Cb >> 4) + (Cb >> 5) - (Cr >> 1)
                                + (Cr >> 3) + (Cr >> 4) + (Cr >> 5);
                        if (G < 0)
                            G = 0;
                        else if (G > 255)
                            G = 255;
                        int B = Y + Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6);
                        if (B < 0)
                            B = 0;
                        else if (B > 255)
                            B = 255;
                        //rgb[pixPtr++] = (0xff000000 + (B << 16) + (G << 8) + R);
                        img.setPixel(i, j, qRgb(R, G, B));
                    }
    }*/

          // Print data size
          //qDebug() << "Print the data size from read file: " << size << " bytes...";
          // Get the raw data in the bytearray

          const char * binaryData = (char*)rawStreamingFrame;

          // Define the H and W of our output image ( we know it's 640 x 480 )
          // Create a QByteArray to store the RGB Data

          int redContainer[height*width];
          int greenContainer[height*width];
          int blueContainer[height*width];

          // To reconstruct pixels in pairs, 4 bytes of data are required. The bytes are arranged as u, y1, v, y2. The total number of bytes in the image stream is 2 x width x height.

          //qDebug() << "Looping through... " << size-4;

          // Loop through 4 bytes at a time

          int cnt = -1;

          for ( int i = 0 ; i <= size-4 ; i += 4 ) {

             // Extract yuv components

             int u  = (int)binaryData[i];
             int y1 = (int)binaryData[i+1];
             int v  = (int)binaryData[i+2];
             int y2 = (int)binaryData[i+3];

             // Define the RGB

             int r1 = 0 , g1 = 0 , b1 = 0;
             int r2 = 0 , g2 = 0 , b2 = 0;

             // u and v are +-0.5
             u -= 128;
             v -= 128;
             // Conversion

             r1 = y1 + 1.403*v;
             g1 = y1 - 0.344*u - 0.714*v;
             b1 = y1 + 1.770*u;
             r2 = y2 + 1.403*v;
             g2 = y2 - 0.344*u - 0.714*v;
             b2 = y2 + 1.770*u;

             // Increment by one so we can insert

             cnt+=1;

             // Append to the array holding our RGB Values

             redContainer[cnt] = r1;
             greenContainer[cnt] = g1;
             blueContainer[cnt] = b1;

             // Increment again since we have 2 pixels per uv value
             cnt+=1;
             // Store the second pixel

             redContainer[cnt] = r2;
             greenContainer[cnt] = g2;
             blueContainer[cnt] = b2;

          }

          // Define a QImage for our RGB Data
          rgbImage = QImage(width, height, QImage::Format_RGB888);
          // Print constructing RGB image
          //qDebug() << "Now constructing RGB Image... ";
          // Now construct our RGB image

          int pixelCounter = -1;
          for ( int i = 0; i < height; ++i ) {
              for ( int j = 0; j < width; ++j ) {
                  pixelCounter+=1;
                  rgbImage.setPixel( j, i, qRgb( redContainer[pixelCounter] ,  greenContainer[pixelCounter] , blueContainer[pixelCounter] ) );
              }
          }

          // Print pixel counter
          //qDebug() << "Counted number of pixels: " << pixelCounter;

    return rgbImage;
}

const u_int8_t huffman_table[] = {
            0xFF,0xC4,0x01,0xA2,0x00,0x00,0x01,0x05,0x01,0x01,0x01,0x01,
            0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,
            0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x01,0x00,0x03,
            0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,
            0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,
            0x0A,0x0B,0x10,0x00,0x02,0x01,0x03,0x03,0x02,0x04,0x03,0x05,
            0x05,0x04,0x04,0x00,0x00,0x01,0x7D,0x01,0x02,0x03,0x00,0x04,
            0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,
            0x71,0x14,0x32,0x81,0x91,0xA1,0x08,0x23,0x42,0xB1,0xC1,0x15,
            0x52,0xD1,0xF0,0x24,0x33,0x62,0x72,0x82,0x09,0x0A,0x16,0x17,
            0x18,0x19,0x1A,0x25,0x26,0x27,0x28,0x29,0x2A,0x34,0x35,0x36,
            0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,
            0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,
            0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,
            0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,
            0x96,0x97,0x98,0x99,0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,
            0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xC2,
            0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,
            0xD6,0xD7,0xD8,0xD9,0xDA,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,
            0xE8,0xE9,0xEA,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,
            0xFA,0x11,0x00,0x02,0x01,0x02,0x04,0x04,0x03,0x04,0x07,0x05,
            0x04,0x04,0x00,0x01,0x02,0x77,0x00,0x01,0x02,0x03,0x11,0x04,
            0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,
            0x32,0x81,0x08,0x14,0x42,0x91,0xA1,0xB1,0xC1,0x09,0x23,0x33,
            0x52,0xF0,0x15,0x62,0x72,0xD1,0x0A,0x16,0x24,0x34,0xE1,0x25,
            0xF1,0x17,0x18,0x19,0x1A,0x26,0x27,0x28,0x29,0x2A,0x35,0x36,
            0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,
            0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,
            0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,
            0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,
            0x95,0x96,0x97,0x98,0x99,0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,
            0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,
            0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,
            0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,
            0xE8,0xE9,0xEA,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA};

QByteArray fixJpegImage(QByteArray * array){
    QByteArray ret;

    if((0xFF & array->at(0)) != 0xFF && (0xFF & array->at(1)) != 0xD8)
        return NULL;

    ret.append(array->mid(0,2));
    array->remove(0,2);

    bool has_dht = false;
    QByteArray aux;
    while(!has_dht){
        aux = array->mid(0,4);
        array->remove(0,4);
        if ((0xFF & aux.at(0)) != 0xff)
            return NULL;

        if((0xFF & aux.at(1)) == 0xc4)
            has_dht = true;
        else if ((0xFF & aux.at(1)) == 0xda)
            break;

        //Skip to the next marker.
        int size = (((0xFF &aux.at(2))) << 8) + (0xFF & aux.at(3));
        ret.append(aux);
        ret.append(array->mid(0, size-2));
                array->remove(0, size-2);
    }

    if(!has_dht){
        ret.append((char*)huffman_table, sizeof(huffman_table)/sizeof(u_int8_t));
        ret.append(aux);
    }

    ret.append(*array);

    return ret;
}

void MainWindow::updatePlayerUIBuffer(uchar* buffer, uint size, uint type, uint width, uint height)
{
    QPixmap pix;
    QImage img;
    QByteArray aux;
    switch(type){
        case FORMAT_YUV:
                img = decodeYUV_impl(buffer, width, height, size);
                if(!img.isNull())
                {
                  // Convert the QImage to a QPixmap for display
                  image2Pixmap(img, pix);
                  ui->label->setPixmap(pix);
                }
        break;
        case FORMAT_MJPEG:
                aux.append((char*)buffer, size);
                pix.loadFromData(fixJpegImage(&aux), "JPEG");
                if (!pix.isNull())
                {
                    // Convert the QImage to a QPixmap for display
                    ui->label->setPixmap(pix);
                }else{
                    qCritical("Null image. Fail to converte Jpeg to Qimage");
                }
        break;
        case FORMAT_H264:
        default:
            qCritical("Error: Format not supported to display");
        break;
    }

    free(buffer);
}

void MainWindow::image2Pixmap(QImage &img, QPixmap &pixmap)
{
        // Convert the QImage to a QPixmap for display
        pixmap = QPixmap(img.size());
        QPainter painter;
        painter.begin(&pixmap);
        painter.drawImage(0,0,img);
        painter.end();
}

void MainWindow::on_listCameras_doubleClicked(const QModelIndex &index)
{
    if(ui->listCameras->selectedItems().count() == 1) {
        const QString key = ui->listCameras->currentItem()->text();
        if (!key.isEmpty()) {
            if(receiverLiveStream != NULL) {
               if(lastIndexLiveStream > -1) {
                   ui->listCameras->item(lastIndexLiveStream)->setTextColor(QColor("Black"));
               }
               QObject::disconnect(receiverLiveStream, SIGNAL(processDisplayFrames(uchar*, uint, uint, uint, uint)),
                                      this, SLOT(updatePlayerUIBuffer(uchar*, uint, uint, uint, uint)));
               receiverLiveStream->setLiveStream(false);
               receiverLiveStream = NULL;
               ui->label->clear();
            }else{
               receiverLiveStream = mapReceiver.value(key);
               QObject::connect(receiverLiveStream, SIGNAL(processDisplayFrames(uchar*, uint, uint, uint, uint)),
                                this, SLOT(updatePlayerUIBuffer(uchar*, uint, uint, uint, uint)));
               receiverLiveStream->setLiveStream(true);
               lastIndexLiveStream = index.row();
               ui->listCameras->item(lastIndexLiveStream)->setTextColor(QColor("Blue"));
            }
        }else{
            msg("Unable to find in list");
        }
    }else{
            msg("OpenBBox Node not selected");
    }
}

void MainWindow::on_listUIServers_doubleClicked(const QModelIndex &index)
{
    if(ui->listUIServers->selectedItems().count() == 1) {
        const QString key = ui->listUIServers->currentItem()->text();
        if (!key.isEmpty()) {

            for(int j = 0; j < MAX_COLUMNS_TABLE_EVENTS; j++){
                mapEventsStream.value(key)->setHorizontalHeaderItem(j, new QStandardItem(columns_name[j]));
            }
            ui->tableEvents->setModel(mapEventsStream.value(key));

            for(int i = 0; i < ui->listUIServers->count(); i++){
                ui->listUIServers->item(i)->setTextColor(QColor("Black"));
            }
            ui->listUIServers->item(index.row())->setTextColor(QColor("Blue"));

        }else{
            msg("Unable to find in list");
        }
    }else{
        msg("OpenBBox Node not selected");
    }
}

void MainWindow::on_listUIServers_clicked(const QModelIndex &index)
{
     updateRecordingButtonByList(ui->listUIServers->item(index.row())->text());

     QString nnode = ui->listUIServers->item(index.row())->text();
     OBBNode * node = mapNode.value(nnode);
     if(node->getSubject().status || node->getCurrentTask()!=0){
         ui->nodestatus->setText(QString("Subject:  \n   %1\n\nTask: \n   %2").arg(node->getSubject().name).arg(QString(node->getBehaviorTask()->file).remove(0,1)));
     }else{
         ui->nodestatus->setText(QString("Subject:  \n   NONE\n\nTask:  \n   NONE"));
     }
     if(lastBStream != nnode){
         //remove last node's camera list
         for(int i = 0; i < ui->listCameras->count(); i++){
            QListWidgetItem* itemToRemove = ui->listCameras->takeItem(i);
            delete itemToRemove;
         }
         lastBStream = nnode;
         //add camera list of this node
         if(node->getNumberOfVideoStream()>0){
             char tooltipStr[sizeof("Port: xxxxx Cam: xx")];
             for(int i = 0; i < node->getNumberOfVideoStream(); i++){
                 QString labelStr = node->getVideoStream(i)->getKeyStream();
                 sprintf(tooltipStr,"Port: %d Cam: %d", node->getVideoStream(i)->getPort(), i+1);
                 QString tooltip(tooltipStr);
                 QListWidgetItem * item = new QListWidgetItem(labelStr);
                 item->setToolTip(tooltip);
                 if(node->getBehaviorStream()->getstop()){
                    item->setIcon(QIcon(RESOURCE_IMAGE_CAMERA));
                 }else{
                    item->setIcon(QIcon(RESOURCE_IMAGE_CAMERARECORD));
                 }
                 if(node->getVideoStream(i)->isLiveStream()){
                     item->setTextColor(QColor("Blue"));
                 }
                 ui->listCameras->addItem(item);
             }
         }

     }
}

void MainWindow::on_listUIServers_itemSelectionChanged()
{
    if(ui->listUIServers->selectedItems().count() == 0) {
        ui->nodestatus->setText("No Node Selected");
    }else if(ui->listUIServers->selectedItems().count() > 1) {
        ui->nodestatus->setText("Multiple Nodes Selected");
    }else if(ui->listUIServers->selectedItems().count() == 1) {
        QList<QListWidgetItem* > list = ui->listUIServers->selectedItems();
        ui->nodestatus->setText(QString("Subject:  \n   %1\n\nTask:  \n   %2")
                                .arg(mapNode.value(list.at(0)->text())->getSubject().name)
                                .arg(QString(mapNode.value(list.at(0)->text())->getBehaviorTask()->file).remove(0,1)));

    }
}

void MainWindow::updateRecordingButtonByList(QString key){
    if(!mapNode.value(key)->getBehaviorStream()->getstop()){
        ui->startStopButton->setIcon(QIcon(RESOURCE_IMAGE_STOP));
        ui->startStopButton->setIconSize(QSize(30,30));
    }else{
        ui->startStopButton->setIcon(QIcon(RESOURCE_IMAGE_START));
        ui->startStopButton->setIconSize(QSize(30,30));
    }
}

void MainWindow::setTaskEnd(QString key){

    OBBNode * node = mapNode.value(key);
    //fill end time to database
    BehaviorTaskDAO dao(sqldb);
    QList<BehaviorTaskObject *> listBTO = dao.get(node->getBehaviorTaskID());
    listBTO.at(0)->setTimeEnd(QDateTime::currentDateTime().toTime_t());
    listBTO.at(0)->setID(node->getBehaviorTaskID());
    dao.update(listBTO.at(0));

    //stop behavior receiver

    updateRecordingButtonByList(key);

    //stop recording if there are any cameras in node
    for(int j = 0; j < node->getNumberOfVideoStream(); j++){
        node->getVideoStream(j)->stopRecording();
    }

    //remove its camera list if they are showed on UI
    for(int j = 0; j < ui->listCameras->count(); j++){
        if(!ui->listCameras->item(j)->text().contains(node->getBehaviorStream()->getKeyStream())){
            break;
        }
        ui->listCameras->item(j)->setIcon(QIcon(RESOURCE_IMAGE_CAMERA));
    }

    if(ui->listUIServers->findItems(key, 0).size() == 1){
        ui->listUIServers->findItems(key, 0).at(0)->setIcon(QIcon(RESOURCE_IMAGE_STOP));
    }

    //reset node's task & subject, so refill is required
    node->setCurrentTask(0);
    SubInfo sub = node->getSubject();
    sub.status = false;
    node->setSubject(sub);

}

void MainWindow::on_startStopButton_clicked()
{
    if(ui->listUIServers->selectedItems().count() > 0) {
        QList<QListWidgetItem* > list = ui->listUIServers->selectedItems();
        int i = 0;
        for(i = 0; i < list.size(); i++){
           QString key = list.at(i)->text();
           OBBNode * node = mapNode.value(key);
           if (!key.isEmpty()) {
                if(!node->getBehaviorStream()->getstop()){
                    if (controller->stopOBBNodeTask(node, STOPTYPE_BUTTON)){
                        setTaskEnd(key);
                    }
                }else{
                    BehaviorTaskDAO dao(sqldb);
                    node->setBehaviorTaskID(dao.insert(new BehaviorTaskObject(node->getIDDatabase(),
                                                                              node->getSubject().id,
                                                                              node->getCurrentTask(),
                                                                              QDateTime::currentDateTime().toTime_t(),
                                                                              0, "")));
                    switch (controller->startOBBNodeTask(node, false)) {
                    case 0:
                    {

                        qDebug("behaviortask id: %d", node->getBehaviorTaskID());
                        list.at(i)->setIcon(QIcon(RESOURCE_IMAGE_START));
                        updateRecordingButtonByList(key);
                        for(int j = 0; j < ui->listCameras->count(); j++){
                            ui->listCameras->item(j)->setIcon(QIcon(RESOURCE_IMAGE_CAMERARECORD));
                        }
                        mapEventsStream.value(key)->removeRows(0, mapEventsStream.value(key)->rowCount());
                    }
                        break;
                    case 1:
                        msg("Missing Task!!");
                        break;
                    case 2:
                        msg("Missing Subject Info!!");
                        break;
                    default:
                        break;
                    }
                }
           }
        }
    }else{
         msg("OpenBBox Node not selected");
    }
}

void MainWindow::on_loadBtn_clicked()
{
   if(ui->listUIServers->selectedItems().count() > 0) {
       //subjectDialog.
       subjectDialog.exec();
       QString fileName = subjectDialog.getTaskDir();
       qDebug(qPrintable(fileName));
       SubInfo sub = subjectDialog.getSubject();
       if(sub.status){
           int idsub = -1;
           SubjectDAO subDAO(sqldb);

           if(!subDAO.subjectExists(sub.name)) {
               idsub = subDAO.insert(new SubjectObject(sub.name,"","","",QDateTime::currentDateTime().toTime_t(),0,0,0));
               if( idsub > -1) {
                    msg("Added new subject to database");
               }
           } else {
               idsub = subDAO.get("tag", sub.name).at(0)->getID();
               msg("Subject already exists in database");
           }
           QList<QListWidgetItem* > list = ui->listUIServers->selectedItems();

           //assign subject info. to all selected nodes
           for(int i = 0; i < list.size(); i++){
               QString keystream = list.at(i)->text();
               sub.id = idsub;
               mapNode.value(keystream)->setSubject(sub);
           }

           if(list.size() == 1){
               ui->nodestatus->setText(QString("Subject:  \n   %1\n\nTask:  \n   ")
                                       .arg(sub.name));
           }

           if(fileName != ""){
               QFile file(fileName);
               if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                   qDebug() << "Can't open file";
                   return;
               }
               QByteArray all = file.readAll();
               QByteArray hash = QCryptographicHash::hash(all,QCryptographicHash::Md5);
               int idtaskfile = -1;
               TaskFileDAO tf(sqldb);
               OBBNode * node;
               if(!tf.fileExists(hash)) {
                   idtaskfile = tf.insert(new TaskFileObject(file.fileName().section("/",file.fileName().count("/"),file.fileName().count("/")),
                                                             QDateTime::currentDateTime().toTime_t(),
                                                             "test",
                                                             file.fileName().section(".", 1, 1),
                                                             all, hash.toHex()));
                   if( idtaskfile > -1) {
                        msg("Added new task file to database");
                   }
               } else {
                   idtaskfile = tf.get("hash", hash.toHex()).at(0)->getID();
                   msg("Task file already exists in database");
               }

               QList<QListWidgetItem* > list = ui->listUIServers->selectedItems();
               for(int i = 0; i < list.size(); i++){
                   node = this->mapNode.value(list.at(i)->text());
                   node->setCurrentTask(idtaskfile);
                   QByteArray fileStream = tf.get(idtaskfile).at(0)->getFile();
                   QTextStream in(&fileStream,QIODevice::ReadOnly);
                   int j = 0;
                   int k = 0;
                   int l;
                   const char *c_str;

                   while ( !in.atEnd())
                   {
                     QString line = in.readLine();
                     l = line.size();
                     QByteArray qba = line.toLatin1();
                     c_str = qba.data();
                     strcpy(node->getBehaviorTask()->file+j, c_str);
                     j = j+l+1;
                     k++;

                     line = line.replace(" ", "");
                     line = line.replace("\t", "");
                     line = line.replace("", "");
                     line = line.replace("\r", "");
                     line = line.toUpper(); // remove spaces, tabs and put to upper

                     if(line.size() > 0){ // be sure
                         if(line.at(0) != '\\') { //remove easy comments
                           line = line.section('\\', 0, 0);
                           if(line.at(0) == (CONST_DELIMITER)){
                               if(line.section('=', 1, 1).toInt() != 0){
                                   line = line.replace(CONST_DELIMITER, "");
                                   if(line.contains("RESP")){
                                       mapPinpanel.value(list.at(i)->text())->addInputpins(line.section('=', 0, 0), line.section('=', 1, 1).toInt());
                                   }else{
                                       mapPinpanel.value(list.at(i)->text())->addOutputpins(line.section('=', 0, 0), line.section('=', 1, 1).toInt());
                                   }
                               }
                           }
                         }
                     }
                   }
                   qDebug("Task size: %d",j);
                   node->getBehaviorTask()->lines = k;

               }
               if(list.size() == 1){
                   ui->nodestatus->setText(QString("Subject:  \n   %1\n\nTask:  \n   %2").
                                           arg(node->getSubject().name).
                                           arg(QString(this->mapNode.value(list.at(0)->text())->getBehaviorTask()->file).remove(0,1)));
               }
           }else
              msg("MPC file not selected");
       }else
           msg("Subject not filled");

   }else{
        msg("OpenBBox Node not selected");
   }
}

void MainWindow::passSubinfo(SubInfo sub){

    if(ui->listUIServers->selectedItems().count() > 0) {
        int idsub = -1;
        SubjectDAO subDAO(sqldb);

        if(!subDAO.subjectExists(sub.name)) {
            idsub = subDAO.insert(new SubjectObject(sub.name,"","","",QDateTime::currentDateTime().toTime_t(),0,0,0));
            if( idsub > -1) {
                 msg("Added new subject to database");
            }
        } else {
            idsub = subDAO.get("tag", sub.name).at(0)->getID();
            msg("Subject already exists in database");
        }
        QList<QListWidgetItem* > list = ui->listUIServers->selectedItems();

        //assign subject info. to all selected nodes
        for(int i = 0; i < list.size(); i++){
            QString keystream = list.at(i)->text();
            sub.id = idsub;
            mapNode.value(keystream)->setSubject(sub);
        }

        if(list.size() == 1){
            ui->nodestatus->setText(QString("Subject:  \n   %1\n\nTask:  \n   ")
                                    .arg(sub.name));
        }

    }else{
        msg("No node selected");
    }

}

void MainWindow::on_actionSQLite_triggered()
{
    sqldb = new SQLiteDatabaseManager(); //default
    lastQAction->setChecked(false);
    lastQAction = ui->actionSQLite;
    lastQAction->setChecked(true);

    if(!sqldb->exists())
        sqldb->create();

    OpenBBoxManagerDAO dao(sqldb);

    idmanager = dao.insert(new OpenBBoxManagerObject(QDateTime::currentDateTime().toTime_t()));

    if(idmanager < 0){
        msg("OpenBBox Manager: Error inserting new Manager`s instance.\n " + sqldb->lastError().text() + "\n\nClosing application....");
        exit(EXIT_FAILURE);
    }
}

void MainWindow::on_actionMySQL_triggered()
{
    sqldb = new MySQLDatabaseManager(); //default
    lastQAction->setChecked(false);
    lastQAction = ui->actionMySQL;
    lastQAction->setChecked(true);

    if(!sqldb->exists())
        sqldb->create();

    OpenBBoxManagerDAO dao(sqldb);

    idmanager = dao.insert(new OpenBBoxManagerObject(QDateTime::currentDateTime().toTime_t()));

    if(idmanager < 0){
        msg("OpenBBox Manager: Error inserting new Manager`s instance.\n " + sqldb->lastError().text() + "\n\nClosing application....");
        exit(EXIT_FAILURE);
    }
}

void MainWindow::on_actionControl_triggered()
{
    controlWindow.show();
}

void MainWindow::on_testButton_clicked()
{
    if(ui->listUIServers->selectedItems().count() == 1) {
        QList<QListWidgetItem* > list = ui->listUIServers->selectedItems();
        OBBNode * node;
        if(!list.at(0)->text().isEmpty()){
            node = this->mapNode.value(list.at(0)->text());
            if(node->getCurrentTask()!=0){
                mapPinpanel.value(node->getBehaviorStream()->getKeyStream())->setPanel(node->getSenderTaskStream(), node->getBehaviorStream());
                mapPinpanel.value(list.at(0)->text())->show();
                controller->startOBBNodeTask(node, true);
            }else
               msg("MPC file not selected");
        }
    }else{
         msg("OpenBBox Node not selected");
    }
}

void MainWindow::stopNodeTestSender(QString keystream){
    if(mapNode.contains(keystream)){
        controller->stopOBBNodeTask(mapNode.value(keystream), STOPTYPE_BUTTON);
    }else{
         msg("OpenBBox not available");
    }
}

repository: kemerelab/OpenBBox

repo_name: kemerelab/OpenBBox


text:
# This package builds tools to manipulate Reiser4 file systems,
# the libaal package must be built and installed as well to
# run these tools.
PR = "r1"
DESCRIPTION = "User-level tools for Reiser4 filesystems"
HOMEPAGE = "http://www.namesys.com"
SECTION = "base"
LICENSE = "GPLv2"

SRC_URI = "ftp://ftp.namesys.com/pub/${PN}/old-versions/${P}.tar.gz \
		file://oid40.c.patch \
		file://key_short.c.patch \
		file://key_large.c.patch \
		file://align.patch"

LIBAAL = "libaal"

DEPENDS = "${LIBAAL}"

# This disables anything which uses libminimal - that library
# is used for boot loader stuff and so is not required unless
# the system will boot from a Reiser4 file system, the same
# setting must exist for the LIBAAL build
DISABLE_LIBMINIMAL ?= "--disable-libminimal"
EXTRA_OECONF = "${DISABLE_LIBMINIMAL}"

LEAD_SONAME = "libreiser4"

inherit autotools

SRC_URI[md5sum] = "b2cbc8eb9429b50e0e99ba4eeda4801e"
SRC_URI[sha256sum] = "4990e24f9a49588cc2d7c3646fb9b5c3946213db26e1df129d218265a88ada2e"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
package main

import (
	"net/http"
	"fmt"
)

type muk int

func (m muk) ServeHTTP(w http.ResponseWriter, r *http.Request){
	fmt.Fprintln(w,"in the function")
}

func main(){
	var m muk
http.ListenAndServe(":8080",m) //m is of type handler as muk is implementing the method of the same signature as by the handler interface
//or any value of muk type is implicitly implementing handler interface
}


text:
#-------------------------------------------------------------------------------
# Copyright Butterfly Energy Systems 2022.
# Distributed under the Boost Software License, Version 1.0.
# https://www.boost.org/LICENSE_1_0.txt
#-------------------------------------------------------------------------------

# Inspired by https://github.com/alexreinking/SharedStaticStarter

cmake_minimum_required(VERSION 3.12)

include(CMakeFindDependencyMacro)

set(valid_components
    core
    core-headers
    coro-usage)
set(CPPWAMP_MINIMUM_BOOST_VERSION 1.77.0)
set(CPPWAMP_MINIMUM_MSGPACK_VERSION 1.0.0)

set(${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)

set(input_component_list "${${CMAKE_FIND_PACKAGE_NAME}_FIND_COMPONENTS}")
foreach(component ${input_component_list})
    if(NOT component IN_LIST valid_components)
        set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
            "'${component}' is not a supported CppWAMP component.")
        return()
    endif()
endforeach()

set(core_deps       core core-headers)
set(coro-usage_deps core-headers coro-usage)

list(APPEND component_list core-headers)
foreach(component ${input_component_list})
    list(APPEND component_list "${${component}_deps}")
endforeach ()
list(REMOVE_DUPLICATES component_list)

set(required "${${CMAKE_FIND_PACKAGE_NAME}_FIND_REQUIRED}")
set(quietly "${${CMAKE_FIND_PACKAGE_NAME}_FIND_QUIETLY}")

if(coro-usage IN_LIST component_list)
    if("${${CMAKE_FIND_PACKAGE_NAME}_FIND_REQUIRED_coro-usage}")
        find_dependency(Boost ${CPPWAMP_MINIMUM_BOOST_VERSION}
                        COMPONENTS coroutine context thread system)
    else()
        if(required)
            find_dependency(Boost ${CPPWAMP_MINIMUM_BOOST_VERSION}
                            COMPONENTS system
                            OPTIONAL_COMPONENTS coroutine context thread)
        elseif(quietly)
            find_package(Boost ${CPPWAMP_MINIMUM_BOOST_VERSION}
                         QUIET
                         COMPONENTS system
                         OPTIONAL_COMPONENTS coroutine context thread)
        else()
            find_package(Boost ${CPPWAMP_MINIMUM_BOOST_VERSION}
                         COMPONENTS system
                         OPTIONAL_COMPONENTS coroutine context thread)
        endif()
    endif()
else()
    find_dependency(Boost ${CPPWAMP_MINIMUM_BOOST_VERSION}
                    COMPONENTS system)
endif()

if(quietly)
    find_package(jsoncons QUIET)
else()
    find_package(jsoncons)
endif()

set(linkage static)
if(DEFINED CPPWAMP_OPT_SHARED_LIBS)
    if(CPPWAMP_OPT_SHARED_LIBS)
        set(linkage shared)
    endif()
elseif(BUILD_SHARED_LIBS)
    set(linkage shared)
endif()

macro(load_target name)
    if("${name}" IN_LIST component_list)
        set(target_file
            "${CMAKE_CURRENT_LIST_DIR}/cppwamp-${name}-target.cmake")
        if(NOT EXISTS ${target_file}
           AND "${${CMAKE_FIND_PACKAGE_NAME}_FIND_REQUIRED_${name}}")
            set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
                "CppWAMP ${name} target was not found.")
            return()
        endif()
        if(EXISTS ${target_file})
            include(${target_file})
        endif()
    endif()
endmacro()

macro(load_compiled_target name)
    if("${name}" IN_LIST component_list)
        set(target_file
            "${CMAKE_CURRENT_LIST_DIR}/cppwamp-${linkage}-${name}-target.cmake")
        if(NOT EXISTS ${target_file}
           AND "${${CMAKE_FIND_PACKAGE_NAME}_FIND_REQUIRED_${name}}")
            set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
                "CppWAMP ${name} target was not found.")
            return()
        endif()
        if(EXISTS ${target_file})
            include(${target_file})
        endif()
    endif()
endmacro()

load_target(core-headers)
load_target(coro-usage)
load_compiled_target(core)

set(${CMAKE_FIND_PACKAGE_NAME}_FOUND TRUE)

repository: ecorm/cppwamp

repo_name: ecorm/cppwamp

extension: cmake


text:
@article{Raman2018Computational,
 abstract = {In this chapter, we describe Fast-SL, an in silico approach to predict synthetic lethals in genome-scale metabolic models. Synthetic lethals are sets of genes or reactions where only the simultaneous removal of all genes or reactions in the set abolishes growth of an organism. In silico approaches to predict synthetic lethals are based on Flux Balance Analysis (FBA), a popular constraint-based analysis method based on linear programming. FBA has been shown to accurately predict the viability of various genome-scale metabolic models. Fast-SL builds on the framework of FBA and enables the prediction of synthetic lethal reactions or genes in different organisms, under various environmental conditions. Predicting synthetic lethals in metabolic network models allows us to generate hypotheses on possible novel genetic interactions and potential candidates for combinatorial therapy, in case of pathogenic organisms. We here summarize the Fast-SL approach for analyzing metabolic networks and detail the procedure to predict synthetic lethals in any given metabolic model. We illustrate the approach by predicting synthetic lethals in Escherichia coli. The Fast-SL implementation for MATLAB is available from https://github.com/RamanLab/FastSL/ .},
 added-at = {2018-12-02T16:09:07.000+0100},
 author = {Raman, Karthik and Pratapa, Aditya and Mohite, Omkar and Balachandran, Shankar},
 biburl = {https://www.bibsonomy.org/bibtex/250d15a815f673cc94b94361201051258/karthikraman},
 citeulike-article-id = {14558183},
 citeulike-linkout-0 = {http://view.ncbi.nlm.nih.gov/pubmed/29222760},
 citeulike-linkout-1 = {http://www.hubmed.org/display.cgi?uids=29222760},
 interhash = {6c803ebaa9bd716bd0c5671aa199c5a9},
 intrahash = {50d15a815f673cc94b94361201051258},
 issn = {1940-6029},
 journal = {Methods in molecular biology (Clifton, N.J.)},
 keywords = {flux-analysis myown synthetic-lethality},
 pages = {315--336},
 pmid = {29222760},
 posted-at = {2018-03-29 08:38:26},
 priority = {2},
 timestamp = {2019-04-17T12:56:37.000+0200},
 title = {Computational Prediction of Synthetic Lethals in Genome-Scale Metabolic Models Using Fast-SL.},
 url = {http://view.ncbi.nlm.nih.gov/pubmed/29222760},
 volume = {1716},
 year = {2018}
}

repository: karthikraman/ramanlab-home

repo_name: karthikraman/ramanlab-home


text:
#include "src/application.hpp"

#include "src/widget.hpp"

Application* Application::g_instance_ = nullptr;

Application* Application::GetInstance() {
  if (g_instance_ == nullptr) {
    g_instance_ = new Application();
  }
  return g_instance_;
}

void Application::Init(HINSTANCE instance, int cmd_show) {
  instance_ = instance;
  cmd_show_ = cmd_show;
  BasicWidget::Init(instance);
}

int Application::GetCmdShow() const { return cmd_show_; }

HINSTANCE Application::GetHInstance() const { return instance_; }

void Application::Run() {
  MSG msg = {};
  while (GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
}

int WINAPI wWinMain(HINSTANCE hInstance,
                    [[maybe_unused]] HINSTANCE hPrevInstance,
                    [[maybe_unused]] LPWSTR lpCmdLine, int nShowCmd) {
  Application* app = Application::GetInstance();
  app->Init(hInstance, nShowCmd);
  return main();
}

license: Unlicense

repository: degmuk/winapi-lib

repo_name: degmuk/winapi-lib


text:
package mapper

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"sync"
	"time"

	"github.com/pourer/pikamgr/coordinate"
	"github.com/pourer/pikamgr/topom/dao"
	"github.com/pourer/pikamgr/utils/log"
)

type topomMapper struct {
	product string
	client  Client
	mutex   *sync.Mutex
	topom   *dao.Topom
}

func NewTopomMapper(product, adminAddr string, client Client) (*topomMapper, error) {
	t := &topomMapper{
		product: product,
		client:  client,
		mutex:   new(sync.Mutex),
		topom:   &dao.Topom{},
	}
	if err := t.init(adminAddr); err != nil {
		return nil, err
	}

	return t, nil
}

func (m *topomMapper) init(adminAddr string) error {
	t := &dao.Topom{
		StartTime:   time.Now().String(),
		AdminAddr:   adminAddr,
		ProductName: m.product,
		Pid:         os.Getpid(),
	}

	t.Pwd, _ = os.Getwd()
	if b, err := exec.Command("uname", "-a").Output(); err != nil {
		log.Errorln("topomMapper::init run command uname failed. err:", err)
	} else {
		t.Sys = strings.TrimSpace(string(b))
	}

	m.mutex.Lock()
	m.topom = t
	m.mutex.Unlock()

	log.Infoln("topomMapper::init new topom:", string(t.Encode()))
	return nil
}

func (m *topomMapper) Create() error {
	data := m.topom.Encode()
	log.Infof("topomMapper::Create \n%s\n", string(data))

	if err := m.client.Create(coordinate.TopomPath(m.product), data); err != nil {
		log.Errorln("topomMapper::Create create fail. err:", err)
		return fmt.Errorf("topomMapper::Create create fail. err-[%s]", err.Error())
	}

	log.Infof("topomMapper::Create Suc. \n%s\n", string(data))
	return nil
}

func (m *topomMapper) Delete() error {
	data := m.topom.Encode()
	log.Infof("topomMapper::Delete \n%s\n", string(data))

	if err := m.client.Delete(coordinate.TopomPath(m.product)); err != nil {
		log.Errorln("topomMapper::Delete delete fail. err:", err)
		return fmt.Errorf("topomMapper::Delete delete fail. err-[%s]", err.Error())
	}

	log.Infof("topomMapper::Delete Suc. \n%s\n", string(data))
	return nil
}

func (m *topomMapper) Info() (*dao.Topom, error) {
	m.mutex.Lock()
	t := m.topom
	m.mutex.Unlock()
	return t, nil
}

repository: pourer/pikamgr

repo_name: pourer/pikamgr


text:
package edac

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func TestMemoryInfoHasErrors(t *testing.T) {
	tests := []struct {
		name     string
		mi       MemoryInfo
		expected bool
	}{
		{
			name: "no-errors",
		},
		{
			name:     "correctable",
			mi:       MemoryInfo{Correctable: 1},
			expected: true,
		},
		{
			name:     "correctable-noinfo",
			mi:       MemoryInfo{CorrectableNoInfo: 1},
			expected: true,
		},
		{
			name:     "uncorrectable",
			mi:       MemoryInfo{Uncorrectable: 1},
			expected: true,
		},
		{
			name:     "uncorrectable-noinfo",
			mi:       MemoryInfo{UncorrectableNoInfo: 1},
			expected: true,
		},
		{
			name: "all",
			mi: MemoryInfo{
				Correctable:         1,
				CorrectableNoInfo:   1,
				Uncorrectable:       1,
				UncorrectableNoInfo: 1,
			},
			expected: true,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			tc.mi.Name = "mc0"
			require.Equal(t, tc.expected, tc.mi.HasErrors())
			require.Contains(t, tc.mi.String(), tc.mi.Name)
		})
	}
}

func TestDimmRankHasErrors(t *testing.T) {
	tests := []struct {
		name     string
		dr       DimmRank
		expected bool
	}{
		{
			name: "no-errors",
		},
		{
			name:     "correctable",
			dr:       DimmRank{Correctable: 1},
			expected: true,
		},
		{
			name:     "uncorrectable",
			dr:       DimmRank{Uncorrectable: 1},
			expected: true,
		},
		{
			name: "all",
			dr: DimmRank{
				Correctable:   1,
				Uncorrectable: 1,
			},
			expected: true,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			tc.dr.Name = "dimm0"
			require.Equal(t, tc.expected, tc.dr.HasErrors())
			require.Contains(t, tc.dr.String(), tc.dr.Name)
		})
	}
}

repository: Unity-Technologies/go-edac

repo_name: Unity-Technologies/go-edac


text:
DESCRIPTION = "Sugar datastore"
LICENSE = "GPLv2"

PR = "r1"

DEPENDS = "sugar-toolkit python-xappy "
RDEPENDS_${PN} = "sugar-toolkit sugar-base python-xappy python-cjson xapian-bindings-python"

SRC_URI = "http://download.sugarlabs.org/sources/sucrose/glucose/sugar-datastore/${PN}-${PV}.tar.bz2"

inherit autotools

FILES_${PN} += "${datadir}/dbus-1"

SRC_URI[md5sum] = "e57580e9fd44ecc2cb7a947dd8854817"
SRC_URI[sha256sum] = "6049dddd3863110b95ec7c7b53c15f6ef8c7b627e3a04f0e9053978685a699db"


text:
package handler

import "testing"

func TestMove(t *testing.T) {

	d := &Data{}
	d.Vars = make(map[string]interface{})
	d.Vars["VAR2"] = "test data"
	d.Vars["VAR1"] = "value1"
	str := "MOVE UPSHIFT(VAR2) TO VAR1"

	d.Move(str)

	if d.Vars["VAR1"] != "TEST DATA" {
		t.Errorf("Expected %v got %v", "TEST DATA", d.Vars["VAR1"])
	}

	//test move with date2str function

	// dateStr := "MOVE DATE2STR(\"08/07/2019\", \"yy-mm-dd\") TO VAR1"

	// d.Move(dateStr)

	// expected := "2019-Aug-07"
	// if d.Vars["VAR1"] != expected {
	// 	t.Errorf("Expected %v, got %v", expected, d.Vars["VAR1"])
	// }

}

repository: the-kompany/gobol

repo_name: the-kompany/gobol