text:
DESCRIPTION = "GNU Common C++"
HOMEPAGE = "http://freshmeat.net/projects/commoncpp2"
LICENSE = "GPL"
PR="r2"
PARALLEL_MAKE = ""

SRC_URI = "ftp://ftp.gnu.org/gnu/commoncpp/commoncpp2-${PV}.tar.gz \
	file://configure.ac.patch"

inherit autotools pkgconfig autotools binconfig

SRC_URI[md5sum] = "e1041356c3129e4d3d3d6a44f281d905"
SRC_URI[sha256sum] = "cc0a7b96fd103154de70e8abfa5c5e3a6c8b9f5ca88f78aada4885c92ae089ba"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
package main

import (
	"github.com/bruth/assert"
	"labix.org/v2/mgo/bson"
	"testing"
)

var jsonString = `
{
    "timestamp": "2013-08-13T05:43:03.32344",
    "action": "update",
    "script": {
        "uri": "https://github.com/cbmi/project/blob/master/parse-users.py",
        "version": "a32f87cb"
    },
    "source": {
        "type": "delimited",
        "delimiter": ",",
        "uri": "148.29.12.100/path/to/users.csv",
        "name": "users.csv",
        "line": 5,
        "column": 4
    },
    "target": {
        "type": "relational",
        "uri": "148.29.12.101:5236",
        "database": "socialapp",
        "table": "users",
        "row": { "id": 38 },
        "column": "email"
    }
}
`

func TestInsertDoc(t *testing.T) {
	cfg := NewConfigWithArgs()
	defer cfg.Mongo.session.Close()

	var d, r bson.M

	// Drop the test database by default
	db := DB(cfg)
	db.DropDatabase()

	col := C(cfg)

	// Unmarshal JSON string into document
	unmarshalJSON([]byte(jsonString), &d)

	// Insert then fetch one
	col.Insert(&d)
	col.Find(nil).One(&r)

	// Ensure the _id key has been created
	v, ok := r["_id"]
	assert.True(t, ok)

	// This looks odd due to the type assertion. This converts it into
	// the interface{} value of "source" to a bson.M (another map) so "uri"
	// can be accessed
	v, _ = r["source"].(bson.M)["uri"]
	assert.Equal(t, v, "148.29.12.100/path/to/users.csv")
}

repository: chop-dbhi/etlogd

license_type: permissive

repo_name: chop-dbhi/etlogd

branch_name: refs/heads/master

extension: go


text:
package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/Krognol/go-wolfram"
	"github.com/bwmarrin/discordgo"
	"github.com/nstratos/go-myanimelist/mal"
	"github.com/spf13/viper"
	"github.com/turnage/graw/reddit"
)

var (
	wolf   wolfram.Client
	redd   reddit.Bot
	malCli *mal.Client
)

func main() {
	var err error

	viper.SetConfigName("bot")
	viper.SetConfigType("toml")
	viper.AddConfigPath(".")
	if err = viper.ReadInConfig(); err != nil {
		fmt.Println("[Config] Error reading config: ", err)
		return
	}

	fmt.Println("[Reddit] Init...")
	app := reddit.App{
		ID:       viper.GetString("reddit.id"),
		Secret:   viper.GetString("reddit.secret"),
		Username: viper.GetString("reddit.username"), // Why graw needs this, I don't know
		Password: viper.GetString("reddit.password"), // redd does just fine without...
	}
	botConfig := reddit.BotConfig{
		Agent: viper.GetString("reddit.agent"),
		App:   app,
		Rate:  1 * time.Second,
	}
	redd, err = reddit.NewBot(botConfig)
	if err != nil {
		fmt.Println("[Reddit] Failed to get session: ", err)
		return
	}

	fmt.Println("[Wolfram|Alpha] Init...") // Wolfram|Alpha's API appears to be stateless
	wolf = wolfram.Client{AppID: viper.GetString("wolfram.key")}

	fmt.Println("[MAL] Init...")
	malCli = mal.NewClient(nil)
	malCli.SetCredentials(viper.GetString("mal.username"), viper.GetString("mal.password"))

	fmt.Println("[Discord] Init...") // Init discord last, because reasons.
	discord, err := discordgo.New("Bot " + viper.GetString("discord.key"))
	if err != nil {
		fmt.Println("[Discord] Error getting session: ", err)
		return
	}
	discord.AddHandler(messageCreate)
	if err := discord.Open(); err != nil {
		fmt.Println("[Discord] Error opening session: ", err)
		return
	}

	fmt.Println("[Main] Ready.")
	fmt.Println("[Main] Press Ctrl-C to exit.")
	sc := make(chan os.Signal, 1)
	signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
	<-sc // This waits for somthing to come in on the "sc" channel.
	fmt.Println("[Main] Ctrl-C Recieved. Exiting!")
	discord.Close()
}

license: MIT


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

package main

import (
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/apigee/registry/rpc"
	"github.com/golang/protobuf/proto"
	statuspb "google.golang.org/genproto/googleapis/rpc/status"
	"google.golang.org/grpc/status"
)

func check(err error) {
	if err != nil {
		log.Printf("ERROR %+v", err)
		os.Exit(-1)
	}
}

// Do performs a gRPC Web request.
func Do(server, service, method string, req, res proto.Message) error {
	reqBytes, err := proto.Marshal(req)
	if err != nil {
		return err
	}
	buf := new(bytes.Buffer)
	buf.WriteByte(0x0) // compressed-flag, message is uncompresseed
	err = binary.Write(buf, binary.BigEndian, int32(len(reqBytes)))
	if err != nil {
		return err
	}
	buf.Write(reqBytes)
	url := server + "/" + service + "/" + method
	request, err := http.NewRequest("POST", url, buf)
	if err != nil {
		return err
	}
	token := os.Getenv("APG_REGISTRY_TOKEN")
	request.Header.Set("authorization", "Bearer "+token)
	request.Header.Set("content-type", "application/grpc-web+proto")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return err
	}
	if response.StatusCode != 200 {
		return fmt.Errorf("non-ok response %d", response.StatusCode)
	}
	ss := response.Header["Grpc-Status"]
	if len(ss) > 0 {
		return fmt.Errorf("call completed with gRPC status %s", ss[0])
	}
	var compression int8
	err = binary.Read(response.Body, binary.BigEndian, &compression)
	if err != nil {
		return err
	}
	if compression != 0 {
		return errors.New("unsupported compressed response")
	}
	var payloadLength int32
	err = binary.Read(response.Body, binary.BigEndian, &payloadLength)
	if err != nil {
		return err
	}
	payloadBody := make([]byte, payloadLength)
	c, err := response.Body.Read(payloadBody)
	if err != nil {
		return err
	}
	if c != int(payloadLength) {
		return fmt.Errorf("error reading payload, expected %d bytes, got %d", payloadLength, c)
	}
	if response.StatusCode != http.StatusOK {
		stpb := &statuspb.Status{}
		err := proto.Unmarshal(payloadBody, stpb)
		if err != nil {
			return err
		}
		st := status.FromProto(stpb)
		log.Printf("status %+v", st.Err())
	}
	err = proto.Unmarshal(payloadBody, res)
	if err != nil {
		return err
	}
	return err
}

func main() {
	server := os.Getenv("APG_REGISTRY_AUDIENCES")
	if server == "" {
		check(fmt.Errorf("APG_REGISTRY_AUDIENCES is unset"))
	}
	// Make a sample API call with gRPC Web.
	req := &rpc.ListProjectsRequest{
		PageSize: 4,
	}
	res := &rpc.ListProjectsResponse{}
	err := Do(server, "google.cloud.apigee.registry.v1.Registry", "ListProjects", req, res)
	check(err)
	log.Printf("response: %+v", res)
}

repository: Jamaalbwells/registry

repo_name: Jamaalbwells/registry

branch_name: refs/heads/main

gha_language: JavaScript


text:
DESCRIPTION = "Dreambox compatibility links"
SECTION = "base"
PRIORITY = "required"
MAINTAINER = "Felix Domke <tmbinc@elitedvb.net>"
PV = "1.0"
PR = "r0"

FILES = "/lib/libgcc_s_nof.so.1 /usr/lib/libcrypto.so.0.9.7 /usr/lib/libssl.so.0.9.7"
PACKAGE_ARCH = "all"

do_install() {
	install -d ${D}/lib
	ln -sf libgcc_s.so.1 ${D}/lib/libgcc_s_nof.so.1
	install -d ${D}/usr/lib
	ln -sf libcrypto.so.0.9.8 ${D}/usr/lib/libcrypto.so.0.9.7
	ln -sf libssl.so.0.9.8 ${D}/usr/lib/libssl.so.0.9.7
	ln -sf libpython2.6.so.1.0 ${D}/usr/lib/libpython2.5.so.1.0
}

gha_language: C

extension: bb


text:
@article{Dou_2018_feb,
 author = {Liru Dou and KaiKai He and Takumi Higaki and Xiangfeng Wang and Tonglin Mao},
 doi = {10.1104/pp.17.01124},
 journal = {Plant Physiol.},
 month = {feb},
 number = {3},
 pages = {2071--2081},
 publisher = {Oxford University Press (OUP)},
 title = {Ethylene Signaling Modulates Cortical Microtubule Reassembly in Response to Salt Stress},
 url = {https://doi.org/10.1104%2Fpp.17.01124},
 volume = {176},
 year = {2018}
}

repository: wanglab-cau/CrazyHsu

repo_name: wanglab-cau/CrazyHsu

extension: bib


text:
//
//  protocol_structures.h
//  atlas
//
//  Created by Janis on 26.05.15.
//  Copyright (c) 2015 Janis. All rights reserved.
//

#ifndef __atlas__protocol_structures__
#define __atlas__protocol_structures__

namespace protocol
{

#pragma pack(1)

typedef struct
{
    uint64_t    txId;
    uint32_t    seqNr;
    uint64_t    rxId[4];
    double      distance[4];
} msgDistance_t;

}

#endif /* defined(__atlas__protocol_structures__) */

extension: h


text:
SUMMARY = "bitbake-layers recipe"
DESCRIPTION = "Recipe created by bitbake-layers"
LICENSE = "CLOSED"

SRC_URI = "file://emotion-1.0.tar.xz"
S = "${WORKDIR}"

do_install() {
install -d ${D}${bindir}
install -m 0755 emotions.py ${D}${bindir}
install -m 0755 haarcascade_frontalface_default.xml ${D}${bindir}
install -m 0755 model.h5 ${D}${bindir}
}

python do_display_banner() {
    bb.plain("**********************************");
    bb.plain("*  Program created by:           *");
    bb.plain("*  Angelo Isaac Bonilla          *");
    bb.plain("*  Frander Díaz Ureña            *");
    bb.plain("*  Pablo Chaves Alfaro           *");
    bb.plain("*  Steven Rojas Cubero           *");
    bb.plain("**********************************");
}

addtask display_banner before do_build


text:
@inproceedings{pinto2020audiovisual,
  title={Audiovisual Classification of Group Emotion Valence Using Activity Recognition Networks},
  author={Pinto, Jo{\~a}o Ribeiro and Gon{\c{c}}alves, Tiago and Pinto, Carolina and Sanhudo, Lu{\'\i}s and Fonseca, Joaquim and Gon{\c{c}}alves, Filipe and Carvalho, Pedro and Cardoso, Jaime S},
  booktitle={2020 IEEE 4th International Conference on Image Processing, Applications and Systems (IPAS)},
  pages={114--119},
  year={2020},
  organization={IEEE}
}

gha_license_id: MIT

gha_language: Jupyter Notebook


text:
require mbed-edge.inc

COMPATIBLE_MACHINE = "raspberrypi3"

PROVIDES += " virtual/mbed-edge virtual/mbed-edge-dbg "
RPROVIDES_${PN} += " virtual/mbed-edge virtual/mbed-edge-dbg "

FILESEXTRAPATHS_prepend := "${THISDIR}/files/mbed-rpi3:"
SRC_URI += "file://target.cmake \
            file://sotp_fs_rpi3_yocto.h"

do_install_append() {
    install -m 755 "${SCRIPT_DIR}/arm_update_cmdline.sh"                  "${D}/opt/arm"
    install -m 755 "${SCRIPT_DIR}/yocto_rpi/arm_update_activate.sh"       "${D}/opt/arm"
    install -m 755 "${SCRIPT_DIR}/yocto_rpi/arm_update_active_details.sh" "${D}/opt/arm"
}

repository: esajaa/meta-mbed-edge

repo_name: esajaa/meta-mbed-edge


text:
//
// Created by Andri Yadi on 14/04/20.
//
#include <Arduino.h>
#if defined(RISCV)

#include <rtc.h>
#include <time.h>

#include "../../wifi/DxWiFi.h"
#include "../TimeUtils.h"

#if !USE_WIFI_BUILTIN_SNTP
#include <NTP.h>
static NTP *ntp_ = NULL;
static WiFiEspUDP *wifiUdp_ = NULL;
#endif // End of !USE_WIFI_BUILTIN_SNTP

bool requestTime(int timezone) {
#if !USE_WIFI_BUILTIN_SNTP
    if (ntp_ == NULL)
    {
        wifiUdp_ = new WiFiEspUDP();
        ntp_ = new NTP(*wifiUdp_);
        ntp_->updateInterval(2000);

        // ntp_->ruleDST("CEST", Last, Sun, Mar, 2, 120);

        ntp_->begin(false);
        return false;
    }
    else {
        return ntp_->update();
    }

#else

    long epoch; char ansStr[40];
    if (DxWiFi.getTime(epoch, ansStr, timezone)) {
        DEBUGLOG("Got time %ld -> %s\r\n", epoch, ansStr);

        processTime(epoch);
        return true;
    }
    else {
        DEBUGLOG("ERROR: Failed getting SNTP time\r\n");

        //TODO: Should continue?
        return false;
    }
#endif

    return false;
}

void processTime(long epoch) {
#if !USE_WIFI_BUILTIN_SNTP
    if (ntp_ == NULL)
    {
        return;
    }

    DEBUGLOG("Current time: %s - %s\r\n", ntp_->formattedTime("%d. %B %Y"), ntp_->formattedTime("%A %T"));

    rtc_timer_set(ntp_->year(), ntp_->month(), ntp_->day(), ntp_->hours(), ntp_->month(), ntp_->seconds());

    auto *dateTime = rtc_timer_get_tm();
    time_t timeSinceEpoch = mktime(dateTime);
    unsigned long expiresSecond = timeSinceEpoch + 7200;
    DEBUGLOG("Epoch: %lu - %lu\n\n", timeSinceEpoch, expiresSecond);

    // Delete NTP
    delete ntp_;
    ntp_ = NULL;

    // delete wifiUdp_;
    wifiUdp_ = NULL;

#else
    struct tm epoch_tm;
    time_t epoch_time = (time_t)epoch;
    memcpy(&epoch_tm, localtime(&epoch_time), sizeof (struct tm));

    rtc_timer_set_tm(&epoch_tm);

    // For testing
    auto *dateTime = rtc_timer_get_tm();
    time_t timeSinceEpoch = mktime(dateTime);
    unsigned long expiresSecond = timeSinceEpoch + 7200;
    DEBUGLOG("Epoch: %lu -> %lu\n\n", timeSinceEpoch, expiresSecond);
#endif
}

long getEpoch() {
    auto *dateTime = rtc_timer_get_tm();
    time_t timeSinceEpoch = mktime(dateTime);
    DEBUGLOG("Epoch: %lu\n\n", timeSinceEpoch);

    return timeSinceEpoch;
}

#endif // End of defined(RISCV)

repository: andriyadi/AzureIoTLiteClient

repo_name: andriyadi/AzureIoTLiteClient

extension: cpp


text:
DESCRIPTION = "SamyGO Extensions ${PN}"
LICENSE = "GPL"
SECTION = "Gallery/Games"
MAINTAINER = "Ser Lev Arris <arris@ZsoltTech.Com>"
HOMEPAGE = "http://samygo.sourceforge.net"

PR = "r03"

RECOMMENDS = ""
RRECOMMENDS = ""
DEPENDS = ""
RDEPENDS = ""

# from r01
# SRCDATE = "20100201"
# r02
# SRCDATE = "20100308"
# r03 (fix for subdir search, nested hack)
SRCDATE = "20100327"

SRC_URI = "svn://samygo.svn.sourceforge.net/svnroot/samygo/SamyGO-Extensions;module=${PN};proto=https"

PACKAGES = "${PN}-dbg ${PN} ${PN}-bin ${PN}-dev ${PN}-doc ${PN}-locale"

# Enable this to generate package per MACHINE
# PACKAGE_ARCH = ${MACHINE_ARCH}
PACKAGE_ARCH = noarch

S = ${WORKDIR}/${PN}/trunk

do_install () {
	mkdir -p ${D}/etc
	install -m 0755 rcSGO ${D}/
	install -m 0755 rc.sysinit ${D}/etc/
        mkdir -p ${D}/usr/share/doc/${PN}
        cp -a doc/* ${D}/usr/share/doc/${PN}/ || true
}

FILES_${PN} = "/rcSGO /etc/rc.sysinit"
FILES_${PN}-doc = "/usr/share/doc/${PN}"

repository: metalsky/SamyGO

repo_name: metalsky/SamyGO


text:
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2018 Datadog, Inc.

package dataset

import (
	"testing"

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

func TestRanks(t *testing.T) {
	d := NewDataset()
	d.Add(1)
	d.Add(3)
	d.Add(3)
	d.Add(3)
	d.Add(5)

	assert.Equal(t, int64(0), d.MinRank(0))
	assert.Equal(t, int64(0), d.MaxRank(0))
	assert.Equal(t, int64(0), d.MinRank(1))
	assert.Equal(t, int64(1), d.MaxRank(1))
	assert.Equal(t, int64(1), d.MinRank(2))
	assert.Equal(t, int64(1), d.MaxRank(2))
	assert.Equal(t, int64(1), d.MinRank(3))
	assert.Equal(t, int64(4), d.MaxRank(3))
	assert.Equal(t, int64(4), d.MinRank(4))
	assert.Equal(t, int64(4), d.MaxRank(4))
	assert.Equal(t, int64(4), d.MinRank(5))
	assert.Equal(t, int64(5), d.MaxRank(5))
	assert.Equal(t, int64(5), d.MinRank(6))
	assert.Equal(t, int64(5), d.MaxRank(6))
}

repository: wg/sketches-go

repo_name: wg/sketches-go

gha_license_id: NOASSERTION


text:
# if (NOT APPLE)
#     set(msgpack_DIR $ENV{HOME}/.local/lib/cmake/msgpack)
#     include_directories($ENV{HOME}/.local/include)
#     link_directories($ENV{HOME}/.local/lib)
# else()
#     # include_directories($ENV{HOME}/github/gecko/src)
#     # include_directories($ENV{HOME}/github/gecko/zmq)
#     # link_directories($ENV{HOME}/github/gecko/build)
#     include_directories(/usr/local/include)
#     link_directories(/usr/local/lib)
# endif()
#
# # Get msgpack -----------------------------------------------------
# if(APPLE)
#   pkg_check_modules(MessagePack REQUIRED msgpack)
#   if(MessagePack_FOUND)
#       include_directories(${MessagePack_INCLUDE_DIR})
#       message(STATUS ">> MsgPack Found: ${MessagePack_VERSION}")
#       message(STATUS ">> MsgPack: ${MessagePack_LIBRARIES}  ${MessagePack_INCLUDE_DIR}")
#       list(APPEND ALL_LIBS ${ALL_LIBS} ${MessagePack_LIBRARIES})
#
#       # this is a template library, so no cpp
#       # include_directories(msgpack)
#       include_directories(.)
#
#   else()
#       message(WARNING "\n<<--- Could not find MsgPack --->>\n")
#   endif()
# elseif(UNIX)
#     find_package(msgpack REQUIRED)
#     if(msgpack_FOUND)
#         include_directories(${msgpack_INCLUDE_DIR})
#         message(STATUS ">> MsgPack Found: ${msgpack_VERSION}")
#         message(STATUS ">> MsgPack: ${msgpack_LIBS}  ${msgpack_INCLUDE_DIR}")
#         list(APPEND ALL_LIBS ${msgpack_LIBRARIES})
#
#         # this is a template library, so no cpp
#         # include_directories(msgpack)
#         include_directories(${CMAKE_CURRENT_LIST_DIR}/../.)
#
#     else()
#         message(WARNING "\n<<--- Could not find MsgPack --->>\n")
#     endif()
# endif()
#
# message(STATUS ">> Compiling MsgPack")
# # message(STATUS "oo> ${PATH}")
# include_directories(${CMAKE_CURRENT_LIST_DIR}/../extlibs/gecko-msgpack)
# # add_subdirectory(${PATH}/extlibs/gecko-msgpack)

repository: gecko-robotics/gecko

repo_name: gecko-robotics/gecko

gha_language: HTML

extension: cmake


text:
#pragma once

#include <unordered_map>
#include <string>

template <typename T, unsigned int R, unsigned int C>
class Sparse_t
{
public:
	std::unordered_map<unsigned int, T> data[R];

private:
	Sparse_t& add(const Sparse_t& m)
	{
		for (int i = 0; i < R; i++) {
			for (const auto e : m.data[i]) {
				auto& ref = data[i];
				if (const auto it = ref.find(e.first); it != ref.end())
					it->second += e.second;
				else
					ref.insert(e);
			}
		}

		return *this;
	}

	Sparse_t& sub(const Sparse_t& m)
	{
		for (int i = 0; i < R; i++) {
			for (const auto e : m.data[i]) {
				auto& ref = data[i];
				if (const auto it = ref.find(e.first); it != ref.end())
					it->second -= e.second;
				else
					ref[e.first] = -e.second;
			}
		}

		return *this;
	}

	Sparse_t& mul(const Sparse_t& m)
	{
		Sparse_t res;

		for (int i = 0; i < R; i++)
		{
			for (int j = 0; j < C; j++)
			{
				T sum = 0;
				for (auto& e : data[i]) {
					const auto& ref = m.data[e.first];
					if (const auto it = ref.find(j); it != ref.end())
						sum += e.second * it->second;
				}

				res.data[i][j] = sum;
			}
		}

		*this = res;

		return *this;
	}

	Sparse_t& mul(const T& s)
	{
		for (int i = 0; i < R; i++)
			for (auto& e : data[i])
				e.second *= s;

		return *this;
	}

	Sparse_t& div(const T& s)
	{
		for (int i = 0; i < R; i++)
			for (auto& e : data[i])
				e.second /= s;

		return *this;
	}

public:
	Sparse_t() {}

	Sparse_t(T* arr)
	{
		for (int i = 0; i < R; i++)
			for (int j = 0; j < C; j++)
				if (const T t = arr[i * C + j]; t)
					data[i][j] = t;
	}

	Sparse_t(const Sparse_t& m)
	{
		for (int i = 0; i < R; i++)
			data[i] = m.data[i];
	}

	friend Sparse_t operator+(Sparse_t lhs, const Sparse_t& rhs)
	{
		return lhs.add(rhs);
	}

	friend Sparse_t operator-(Sparse_t lhs, const Sparse_t& rhs)
	{
		return lhs.sub(rhs);
	}

	friend Sparse_t operator*(Sparse_t lhs, const Sparse_t& rhs)
	{
		return lhs.mul(rhs);
	}

	friend Sparse_t operator*(Sparse_t m, const T& s)
	{
		return m.mul(s);
	}

	friend Sparse_t operator*(const T& s, Sparse_t m)
	{
		return m.mul(s);
	}

	friend Sparse_t operator/(Sparse_t m, const T& s)
	{
		return m.div(s);
	}

	Sparse_t& operator+=(const Sparse_t& m)
	{
		return add(m);
	}

	Sparse_t& operator-=(const Sparse_t& m)
	{
		return sub(m);
	}

	Sparse_t& operator*=(const Sparse_t& m)
	{
		return mul(m);
	}

	Sparse_t& operator*=(const T& s)
	{
		return mul(s);
	}

	Sparse_t& operator/=(const T& s)
	{
		return div(s);
	}

	bool operator==(const Sparse_t& m) const
	{
		for (int i = 0; i < R; i++)
		{
			const auto& ref1 = data[i];
			const auto& ref2 = m.data[i];

			if (ref1.size() != ref2.size())
				return false;

			for (const auto& e : ref1)
			{
				if (const auto it = ref2.find(e.first); it != ref2.end()) {
					if (e.second != it->second) { return false; }
				} else
					return false;
			}
		}

		return true;
	}

	bool operator!=(const Sparse_t& m) const
	{
		for (int i = 0; i < R; i++)
		{
			const auto& ref1 = data[i];
			const auto& ref2 = m.data[i];

			if (ref1.size() != ref2.size())
				return true;

			for (const auto& e : ref1)
			{
				if (const auto it = ref2.find(e.first); it != ref2.end()) {
					if (e.second != it->second) { return true; }
				}
				else
					return true;
			}
		}

		return false;
	}

	T sparsity() const
	{
		unsigned int non_zero_elems = 0;
		for (int i = 0; i < R; i++)
			non_zero_elems += data[i].size();

		return static_cast<T>(1) - static_cast<T>(non_zero_elems) / (R * C);
	}

	std::string toString() const
	{
		std::string res = "Sparse_t<";
		res += std::string(typeid(T).name()) + ", " + std::to_string(R) + ", " + std::to_string(C) + ">{";

		for (int i = 0; i < R; i++) {
			const auto it = data[i].find(0);
			res += "\n\t[" + ((it != data[i].end()) ? std::to_string(it->second) : std::to_string(static_cast<T>(0)));

			for (int j = 1; j < C; j++) {
				const auto it = data[i].find(j);
				res += ", " + ((it != data[i].end()) ? std::to_string(it->second) : std::to_string(static_cast<T>(0)));
			}

			res += "]";
		}
		res += "\n}";

		return res;
	}

	friend std::ostream& operator<<(std::ostream& os, const Sparse_t<T, R, C>& m)
	{
		os << m.toString();
		return os;
	}
};

repository: david-bermejo/gopt

repo_name: david-bermejo/gopt

extension: hpp


text:
@inproceedings{2001AIPC..556..240K,
 abstract = {Gamma-ray burst astronomy has undergone a revolution in the last three
years, spurred by the discovery of fading long-wavelength
counterparts. We now know that at least the long duration GRBs
lie at cosmological distances with estimated electromagnetic
energy release of 10$^51$-10$^53$ erg, making these the
brightest explosions in the Universe. In this article we review
the current observational state, beginning with the statistics
of X-ray, optical, and radio afterglow detections. We then
discuss the insights these observations have given to the
progenitor population, the energetics of the GRB events, and the
physics of the afterglow emission. We focus particular attention
on the evidence linking GRBs to the explosion of massive stars.
Throughout, we identify remaining puzzles and uncertainties, and
emphasize promising observational tools for addressing them. The
imminent launch of HETE-2 and the increasingly sophisticated and
coordinated ground-based and space-based observations have
primed this field for fantastic growth. This overview is a
combined write-up of talks given at this conference and in
NASA's Goddard Space Flight Center. . <P />},
 adsnote = {Provided by the SAO/NASA Astrophysics Data System},
 adsurl = {https://ui.adsabs.harvard.edu/abs/2001AIPC..556..240K},
 author = {Kulkarni, S.~R. and Berger, E. and Bloom, J.~S. and Chaffee, F. and
Diercks, A. and Djorgovski, S.~G. and Frail, D.~A. and
Galama, T.~J. and Goodrich, R.~W. and Harrison, F.~A. and
Sari, R. and Yost, S.~A.},
 booktitle = {Explosive Phenomena in Astrophysical Compact Objects},
 doi = {10.1063/1.1368281},
 editor = {Chang, Heon-Young and Lee, Chang-Hwan and Rho, Mannque and
Yi, Insu},
 keywords = {98.70.Rz, 95.30.Gv, gamma-ray sources, gamma-ray bursts, Radiation mechanisms, polarization},
 month = {Mar},
 pages = {240-260},
 series = {American Institute of Physics Conference Series},
 title = {The afterglows of gamma-ray bursts},
 volume = {556},
 year = {2001}
}

repository: profjsb/my-content

repo_name: profjsb/my-content

gha_language: TeX


text:
PR = "r0"

inherit debian-package

LICENSE = "NCSA"
LIC_FILES_CHKSUM = " \
	file://COPYING;md5=61cbac6719ae682ce6cd45b5c11e21af \
	file://COPYRIGHT;md5=61cbac6719ae682ce6cd45b5c11e21af \
"

inherit autotools

# Avoid strip
EXTRA_OEMAKE += "INSTALL_PROGRAM='${INSTALL}'"

do_install_append (){
	# Debian don't need binary from libtar
	rm -rf ${D}${bindir}
}

repository: nghiaht-tsdv/meta-debian

repo_name: nghiaht-tsdv/meta-debian

branch_name: refs/heads/jethro

gha_language: BitBake


text:
package gtks

// ENUM_NAME = GTK_ARROW_UP, 0
// ENUM_NAME = GTK_ARROW_DOWN, 1
// ENUM_NAME = GTK_ARROW_LEFT, 2
// ENUM_NAME = GTK_ARROW_RIGHT, 3
// ENUM_NAME = GTK_ARROW_NONE, 4
type ArrowType int

const (
	ARROW_UP ArrowType = iota
	ARROW_DOWN
	ARROW_LEFT
	ARROW_RIGHT
	ARROW_NONE
)

repository: portalgun-io/gtk-sugar

repo_name: portalgun-io/gtk-sugar


text:
message("compile:gcc v8.2 arm-linux-gnueabihf-gcc/g++ -std=c++17 -g")
set(CMAKE_SYSTEM_NAME Linux)

#设置编译器路径
# set(COMPILER_PATH /usr/local/toolchain/gcc-arm-8.2-2018.08-x86_64-arm-linux-gnueabihf/bin)
# set(PRE_FIX arm-linux-gnueabihf-)
# set(CMAKE_FIND_ROOT_PATH ${COMPILER_PATH})
# set(CMAKE_C_COMPILER ${COMPILER_PATH}/${PRE_FIX}gcc)
# set(CMAKE_CXX_COMPILER ${COMPILER_PATH}/${PRE_FIX}g++)
# set(CMAKE_STRIP ${COMPILER_PATH}/${PRE_FIX}strip)

#specify the cross compiler
set(CMAKE_C_COMPILER   /home/yu/workspace/toolchain/gcc-arm-8.2-2018.08-x86_64-arm-linux-gnueabihf/bin/arm-linux-gnueabihf-gcc)
set(CMAKE_CXX_COMPILER /home/yu/workspace/toolchain/gcc-arm-8.2-2018.08-x86_64-arm-linux-gnueabihf/bin/arm-linux-gnueabihf-g++)
set(CMAKE_STRIP /home/yu/workspace/toolchain/gcc-arm-8.2-2018.08-x86_64-arm-linux-gnueabihf/bin/arm-linux-gnueabihf-strip)

# where is the target environment
set(CMAKE_FIND_ROOT_PATH  /home/yu/workspace/toolchain/gcc-arm-8.2-2018.08-x86_64-arm-linux-gnueabihf/bin)

# search for programs in the build host directories (not necessary)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
# for libraries and headers in the target directories (not necessary)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

# set C and CPP compile flag
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -o2 -std=c++17 -fPIC -Wno-psabi")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -o2 -fPIC")

# set install dir
set(CMAKE_INSTALL_PREFIX ${PROJECT_SOURCE_DIR}/build/install)

repository: ComakeOnline/mindproject

repo_name: ComakeOnline/mindproject


text:
#ifndef VIENNACL_LINALG_DETAIL_BISECT_BISECT_LARGE_HPP_
#define VIENNACL_LINALG_DETAIL_BISECT_BISECT_LARGE_HPP_

/* =========================================================================
   Copyright (c) 2010-2015, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.
   Portions of this software are copyright by UChicago Argonne, LLC.

                            -----------------
                  ViennaCL - The Vienna Computing Library
                            -----------------

   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at

   (A list of authors and contributors can be found in the manual)

   License:         MIT (X11), see file LICENSE in the base directory
============================================================================= */

/** @file viennacl/linalg/detail//bisect/bisect_large.hpp
    @brief Computation of eigenvalues of a large symmetric, tridiagonal matrix

    Implementation based on the sample provided with the CUDA 6.0 SDK, for which
    the creation of derivative works is allowed by including the following statement:
    "This software contains source code provided by NVIDIA Corporation."
*/

// includes, system
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <stdio.h>

// includes, project
#include "viennacl/linalg/detail/bisect/config.hpp"
#include "viennacl/linalg/detail/bisect/structs.hpp"
#include "viennacl/linalg/detail/bisect/bisect_kernel_calls.hpp"

namespace viennacl
{
namespace linalg
{
namespace detail
{

////////////////////////////////////////////////////////////////////////////////
//! Run the kernels to compute the eigenvalues for large matrices
//! @param  input   handles to input data
//! @param  result  handles to result data
//! @param  mat_size  matrix size
//! @param  precision  desired precision of eigenvalues
//! @param  lg  lower limit of Gerschgorin interval
//! @param  ug  upper limit of Gerschgorin interval
////////////////////////////////////////////////////////////////////////////////
template<typename NumericT>
void
computeEigenvaluesLargeMatrix(InputData<NumericT> &input, ResultDataLarge<NumericT> &result,
                              const unsigned int mat_size,
                              const NumericT lg, const NumericT ug,  const NumericT precision)
{

  // First kernel call: decide on which intervals bisect_Large_OneIntervals/
  // bisect_Large_MultIntervals is executed
  viennacl::linalg::detail::bisectLarge(input, result, mat_size, lg, ug, precision);

  // compute eigenvalues for intervals that contained only one eigenvalue
  // after the first processing step
  viennacl::linalg::detail::bisectLarge_OneIntervals(input, result, mat_size, precision);

  // process intervals that contained more than one eigenvalue after
  // the first processing step
  viennacl::linalg::detail::bisectLarge_MultIntervals(input, result, mat_size, precision);

}

////////////////////////////////////////////////////////////////////////////////
//! Process the result, that is obtain result from device and do simple sanity
//! checking
//! @param  result  handles to result data
//! @param  mat_size  matrix size
////////////////////////////////////////////////////////////////////////////////
template<typename NumericT>
bool
processResultDataLargeMatrix(ResultDataLarge<NumericT> &result,
                             const unsigned int mat_size)
{
    bool bCompareResult = true;
    // copy data from intervals that contained more than one eigenvalue after
    // the first processing step
    std::vector<NumericT> lambda_mult(mat_size);
    viennacl::copy(result.g_lambda_mult, lambda_mult);

    std::vector<unsigned int> pos_mult(mat_size);
    viennacl::copy(result.g_pos_mult, pos_mult);

    std::vector<unsigned int> blocks_mult_sum(mat_size);
    viennacl::copy(result.g_blocks_mult_sum, blocks_mult_sum);

    unsigned int num_one_intervals = result.g_num_one;
    unsigned int sum_blocks_mult = mat_size - num_one_intervals;

    // copy data for intervals that contained one eigenvalue after the first
    // processing step
    std::vector<NumericT> left_one(mat_size);
    std::vector<NumericT> right_one(mat_size);
    std::vector<unsigned int> pos_one(mat_size);

    viennacl::copy(result.g_left_one, left_one);
    viennacl::copy(result.g_right_one, right_one);
    viennacl::copy(result.g_pos_one, pos_one);

    // singleton intervals generated in the second step
    for (unsigned int i = 0; i < sum_blocks_mult; ++i)
    {
      if (pos_mult[i] != 0)
        result.std_eigenvalues[pos_mult[i] - 1] = lambda_mult[i];

      else
      {
        throw memory_exception("Invalid array index! Are there more than 256 equal eigenvalues?");
      }
    }

    // singleton intervals generated in the first step
    unsigned int index = 0;

    for (unsigned int i = 0; i < num_one_intervals; ++i, ++index)
    {
        result.std_eigenvalues[pos_one[i] - 1] = left_one[i];
    }
    return bCompareResult;
}
} // namespace detail
}  // namespace linalg
}  // namespace viennacl
#endif //VIENNACL_LINALG_DETAIL_BISECT_LARGE_HPP_

repository: HSAFoundation/viennacl-dev

repo_name: HSAFoundation/viennacl-dev


text:
#ifndef _ARDUINO_ILI9806_H_
#define _ARDUINO_ILI9806_H_

#include <Arduino.h>
#include <Print.h>
#include "../Arduino_GFX.h"
#include "../Arduino_TFT.h"

#define ILI9806_TFTWIDTH 480  ///< ILI9806 max TFT width
#define ILI9806_TFTHEIGHT 854 ///< ILI9806 max TFT height

#define ILI9806_RST_DELAY 120    ///< delay ms wait for reset finish
#define ILI9806_SLPIN_DELAY 120  ///< delay ms wait for sleep in finish
#define ILI9806_SLPOUT_DELAY 120 ///< delay ms wait for sleep out finish

#define ILI9806_NOP 0x00     ///< No-op register
#define ILI9806_SWRESET 0x01 ///< Software reset register
#define ILI9806_RDDID 0x04   ///< Read display identification information
#define ILI9806_RDDST 0x09   ///< Read Display Status

#define ILI9806_SLPIN 0x10  ///< Enter Sleep Mode
#define ILI9806_SLPOUT 0x11 ///< Sleep Out
#define ILI9806_PTLON 0x12  ///< Partial Mode ON
#define ILI9806_NORON 0x13  ///< Normal Display Mode ON

#define ILI9806_RDMODE 0x0A     ///< Read Display Power Mode
#define ILI9806_RDMADCTL 0x0B   ///< Read Display MADCTL
#define ILI9806_RDPIXFMT 0x0C   ///< Read Display Pixel Format
#define ILI9806_RDIMGFMT 0x0D   ///< Read Display Image Format
#define ILI9806_RDSELFDIAG 0x0F ///< Read Display Self-Diagnostic Result

#define ILI9806_INVOFF 0x20   ///< Display Inversion OFF
#define ILI9806_INVON 0x21    ///< Display Inversion ON
#define ILI9806_GAMMASET 0x26 ///< Gamma Set
#define ILI9806_DISPOFF 0x28  ///< Display OFF
#define ILI9806_DISPON 0x29   ///< Display ON

#define ILI9806_CASET 0x2A ///< Column Address Set
#define ILI9806_PASET 0x2B ///< Page Address Set
#define ILI9806_RAMWR 0x2C ///< Memory Write
#define ILI9806_RAMRD 0x2E ///< Memory Read

#define ILI9806_PTLAR 0x30    ///< Partial Area
#define ILI9806_VSCRDEF 0x33  ///< Vertical Scrolling Definition
#define ILI9806_MADCTL 0x36   ///< Memory Access Control
#define ILI9806_VSCRSADD 0x37 ///< Vertical Scrolling Start Address
#define ILI9806_PIXFMT 0x3A   ///< COLMOD: Pixel Format Set

#define ILI9806_FRMCTR1 0xB1 ///< Frame Rate Control (In Normal Mode/Full Colors)
#define ILI9806_FRMCTR2 0xB2 ///< Frame Rate Control (In Idle Mode/8 colors)
#define ILI9806_FRMCTR3 0xB3 ///< Frame Rate control (In Partial Mode/Full Colors)
#define ILI9806_INVCTR 0xB4  ///< Display Inversion Control
#define ILI9806_DFUNCTR 0xB6 ///< Display Function Control

#define ILI9806_PWCTR1 0xC0 ///< Power Control 1
#define ILI9806_PWCTR2 0xC1 ///< Power Control 2
#define ILI9806_PWCTR3 0xC2 ///< Power Control 3
#define ILI9806_PWCTR4 0xC3 ///< Power Control 4
#define ILI9806_PWCTR5 0xC4 ///< Power Control 5
#define ILI9806_VMCTR1 0xC5 ///< VCOM Control 1
#define ILI9806_VMCTR2 0xC7 ///< VCOM Control 2

#define ILI9806_RDID1 0xDA ///< Read ID 1
#define ILI9806_RDID2 0xDB ///< Read ID 2
#define ILI9806_RDID3 0xDC ///< Read ID 3
#define ILI9806_RDID4 0xDD ///< Read ID 4

#define ILI9806_GMCTRP1 0xE0 ///< Positive Gamma Correction
#define ILI9806_GMCTRN1 0xE1 ///< Negative Gamma Correction
#define ILI9806_PWCTR6 0xFC

#define ILI9806_MADCTL_MY 0x80  ///< Bottom to top
#define ILI9806_MADCTL_MX 0x40  ///< Right to left
#define ILI9806_MADCTL_MV 0x20  ///< Reverse Mode
#define ILI9806_MADCTL_ML 0x10  ///< LCD refresh Bottom to top
#define ILI9806_MADCTL_RGB 0x00 ///< Red-Green-Blue pixel order
#define ILI9806_MADCTL_BGR 0x08 ///< Blue-Green-Red pixel order
#define ILI9806_MADCTL_MH 0x04  ///< LCD refresh right to left

static const uint8_t ili9806_init_operations[] = {
    BEGIN_WRITE,
    WRITE_COMMAND_8, 0xFF, // EXTC Command Set enable register
    WRITE_BYTES, 3, 0xFF, 0x98, 0x06,

    WRITE_C8_D8, 0xBA, 0x60, // SPI Interface Setting

    WRITE_COMMAND_8, 0xBC, // GIP 1
    WRITE_BYTES, 21,
    0x01, 0x10, 0x00, 0x00, 0x01,
    0x01, 0x0B, 0x11, 0x32, 0x10,
    0x00, 0x00, 0x01, 0x01, 0x01,
    0x01, 0x50, 0x52, 0x01, 0x00,
    0x40,

    WRITE_COMMAND_8, 0xBD, // GIP 2
    WRITE_BYTES, 8,
    0x01, 0x23, 0x45, 0x67, 0x01,
    0x23, 0x45, 0x67,

    WRITE_COMMAND_8, 0xBE, // GIP 3
    WRITE_BYTES, 9,
    0x00, 0x21, 0xAB, 0x60, 0x22,
    0x22, 0x22, 0x22, 0x22,

    WRITE_C8_D8, 0xC7, 0x30, // VCOM Control

    WRITE_COMMAND_8, 0xED, // EN_volt_reg
    WRITE_BYTES, 3, 0x7F, 0x0F, 0x00,

    WRITE_COMMAND_8, 0xC0,            // Power Control 1
    WRITE_BYTES, 3, 0x03, 0x0B, 0x0C, // 0A VGH VGL

    WRITE_COMMAND_8, 0xFD, // External Power Selection Set
    WRITE_BYTES, 2, 0x0A, 0x00,

    WRITE_C8_D8, 0xFC, 0x08, // LVGL

    WRITE_COMMAND_8, 0xDF, // Engineering Setting
    WRITE_BYTES, 6,
    0x00, 0x00, 0x00, 0x00, 0x00,
    0x20,

    WRITE_C8_D8, 0xF3, 0x74, // DVDD Voltage Setting

    WRITE_COMMAND_8, 0xB4, // Display Inversion Control
    WRITE_BYTES, 3, 0x00, 0x00, 0x00,

    WRITE_COMMAND_8, 0xB5, // Blanking Porch Control
    WRITE_BYTES, 2, 0x08, 0x15,

    WRITE_C8_D8, 0xF7, 0x81, // 480x854

    WRITE_COMMAND_8, 0xB1, // Frame Rate Control
    WRITE_BYTES, 3, 0x00, 0x13, 0x13,

    WRITE_COMMAND_8, 0xF2, // Panel Timing Control
    WRITE_BYTES, 4, 0x80, 0x04, 0x40, 0x28,

    WRITE_COMMAND_8, 0xC1, // Power Control 2
    WRITE_BYTES, 3,
    0x17,
    0x71, // VGMP
    0x71, // VGMN

    WRITE_COMMAND_8, 0xE0, // P_Gamma
    WRITE_BYTES, 16,
    0x00, // P1
    0x13, // P2
    0x1A, // P3
    0x0C, // P4
    0x0E, // P5
    0x0B, // P6
    0x07, // P7
    0x05, // P8
    0x05, // P9
    0x0A, // P10
    0x0F, // P11
    0x0F, // P12
    0x0E, // P13
    0x1C, // P14
    0x16, // P15
    0x00, // P16

    WRITE_COMMAND_8, 0xE1, // N_Gamma
    WRITE_BYTES, 16,
    0x00, // P1
    0x13, // P2
    0x1A, // P3
    0x0C, // P4
    0x0E, // P5
    0x0B, // P6
    0x07, // P7
    0x05, // P8
    0x05, // P9
    0x0A, // P10
    0x0F, // P11
    0x0F, // P12
    0x0E, // P13
    0x1C, // P14
    0x16, // P15
    0x00, // P16

    WRITE_C8_D8, 0x3A, 0x55, // 55-16BIT,66-18BIT,77-24BIT

    WRITE_COMMAND_8, 0x11,
    END_WRITE,

    DELAY, ILI9806_SLPOUT_DELAY,

    BEGIN_WRITE,
    WRITE_COMMAND_8, 0x29,
    END_WRITE,

    DELAY, 25,

    BEGIN_WRITE,
    WRITE_COMMAND_8, 0x2C,
    END_WRITE};

class Arduino_ILI9806 : public Arduino_TFT
{
public:
  Arduino_ILI9806(Arduino_DataBus *bus, int8_t rst = GFX_NOT_DEFINED, uint8_t r = 0, bool ips = false);

  bool begin(int32_t speed = GFX_NOT_DEFINED) override;

  void setRotation(uint8_t r) override;

  void writeAddrWindow(int16_t x, int16_t y, uint16_t w, uint16_t h) override;

  void invertDisplay(bool) override;
  void displayOn() override;
  void displayOff() override;

protected:
  void tftInit() override;

private:
};

#endif


text:
@article{sander2015,
	title = {Compilation of {Henry}'s law constants (version 4.0) for water as solvent},
	volume = {15},
	issn = {1680-7324},
	url = {http://www.atmos-chem-phys.net/15/4399/2015/acp-15-4399-2015.html},
	doi = {10.5194/acp-15-4399-2015},
	number = {8},
	journal = {Atmospheric Chemistry and Physics},
	author = {Sander, R.},
	month = apr,
	year = {2015},
	pages = {4399--4981},
}

@article{akita1974,
	title = {Bubble {Size}, {Interfacial} {Area}, and {Liquid}-{Phase} {Mass} {Transfer} {Coefficient} in {Bubble} {Columns}},
	volume = {13},
	issn = {0196-4305},
	url = {http://dx.doi.org/10.1021/i260049a016},
	doi = {10.1021/i260049a016},
	number = {1},
	journal = {Industrial \& Engineering Chemistry Process Design and Development},
	author = {Akita, Kiyomi and Yoshida, Fumitake},
	month = jan,
	year = {1974},
	pages = {84--91},
}

@article{akita1981,
	title = {Diffusivities of gases in aqueous electrolyte solutions},
	volume = {20},
	issn = {0196-4313},
	url = {http://pubs.acs.org/doi/abs/10.1021/i100001a017},
	doi = {10.1021/i100001a017},
	number = {1},
	journal = {Industrial \& Engineering Chemistry Fundamentals},
	author = {Akita, Kiyomi},
	month = feb,
	year = {1981},
	pages = {89--94},
}

@inproceedings{millar2018,
	title = {Performance map of the hydraulic air compressor installed at {Dynamic} {Earth}, {Sudbury}},
	author = {Millar, Dean and Sivret, Justin and Pavese, Valeria and Hutchison, Alex and Young, Stephen and Noula-Millar, Caterina and Clifford, Tom},
	year = {2018},
	note = {event-place: Xi'an, China},
}

@inproceedings{millar2016,
	title = {The role of water solubility in applications of hydraulic air compressors in mining},
	booktitle = {Proceedings of 2016 {Energy} \& {Water} {Symposium}},
	author = {Millar, Dean L. and Hutchison, Alexander D. and Noula, Caterina and Pavese, Valeria and Rico, Javier and Young, Stephen},
	year = {2016},
	note = {event-place: Windsor, Ontario, Canada},
}


text:
% This file was created with JabRef 2.10b2.
% Encoding: ISO8859_1

@Article{Baba:2009,
  Title                    = {Satake diagrams and restricted root systems of semisimple pseudo-{R}iemannian symmetric spaces},
  Author                   = {Baba, Kurando},
  Journal                  = {Tokyo J. Math.},
  Year                     = {2009},
  Number                   = {1},
  Pages                    = {127--158},
  Volume                   = {32},

  Fjournal                 = {Tokyo Journal of Mathematics},
  ISSN                     = {0387-3870},
  Mrclass                  = {17B20 (17B22 53C35)},
  Mrnumber                 = {2541161},
  Mrreviewer               = {Oksana S. Yakimova},
  Owner                    = {user},
  Timestamp                = {2017.12.04},
  Url                      = {https://doi.org/10.3836/tjm/1249648414}
}

@Book{Bourbaki:2002,
  Title                    = {Lie groups and {L}ie algebras. {C}hapters 4--6},
  Author                   = {Bourbaki, Nicolas},
  Publisher                = {Springer-Verlag, Berlin},
  Year                     = {2002},
  Note                     = {Translated from the 1968 French original by Andrew Pressley},
  Series                   = {Elements of Mathematics (Berlin)},

  ISBN                     = {3-540-42650-7},
  Mrclass                  = {17-01 (00A05 20E42 20F55 22-01)},
  Mrnumber                 = {1890629},
  Owner                    = {user},
  Pages                    = {xii+300},
  Timestamp                = {2017.11.15},
  Url                      = {https://doi.org/10.1007/978-3-540-89394-3}
}

@Book{Carter:2005,
  Title                    = {Lie algebras of finite and affine type},
  Author                   = {Carter, R. W.},
  Publisher                = {Cambridge University Press, Cambridge},
  Year                     = {2005},
  Series                   = {Cambridge Studies in Advanced Mathematics},
  Volume                   = {96},

  ISBN                     = {978-0-521-85138-1; 0-521-85138-6},
  Mrclass                  = {17-02 (17B67)},
  Mrnumber                 = {2188930},
  Mrreviewer               = {Stephen Slebarski},
  Owner                    = {user},
  Pages                    = {xviii+632},
  Timestamp                = {2017.11.15},
  Url                      = {https://doi.org/10.1017/CBO9780511614910}
}

@Article{Chuah:2013,
  Title                    = {Cartan automorphisms and {V}ogan superdiagrams},
  Author                   = {Chuah, Meng-Kiat},
  Journal                  = {Math. Z.},
  Year                     = {2013},
  Number                   = {3-4},
  Pages                    = {793--800},
  Volume                   = {273},

  Fjournal                 = {Mathematische Zeitschrift},
  ISSN                     = {0025-5874},
  Mrclass                  = {17B20 (17B40)},
  Mrnumber                 = {3030677},
  Mrreviewer               = {Zi-Xin Hou},
  Owner                    = {user},
  Timestamp                = {2017.12.04},
  Url                      = {https://doi.org/10.1007/s00209-012-1030-z}
}

@Article{Dynkin:1952,
  Title                    = {Semisimple subalgebras of semisimple {L}ie algebras},
  Author                   = {Dynkin, E. B.},
  Journal                  = {Mat. Sbornik N.S.},
  Year                     = {1952},
  Note                     = {Reprinted in English translation in \cite{Dynkin:2000}.},
  Pages                    = {349--462 (3 plates)},
  Volume                   = {30(72)},

  Mrclass                  = {09.1X},
  Mrnumber                 = {0047629},
  Mrreviewer               = {I. Kaplansky},
  Owner                    = {user},
  Timestamp                = {2017.11.15}
}

@Book{Dynkin:2000,
  Title                    = {Selected papers of {E}. {B}. {D}ynkin with commentary},
  Author                   = {Dynkin, E. B.},
  Publisher                = {American Mathematical Society, Providence, RI; International Press, Cambridge, MA},
  Year                     = {2000},
  Note                     = {Edited by A. A. Yushkevich, G. M. Seitz and A. L. Onishchik},

  ISBN                     = {0-8218-1065-0},
  Mrclass                  = {01A75 (60Jxx)},
  Mrnumber                 = {1757976},
  Mrreviewer               = {William M. McGovern},
  Owner                    = {user},
  Pages                    = {xxviii+796},
  Timestamp                = {2017.11.15}
}

@Article{Frappat/Sciarrino/Sorba:1989,
  Title                    = {Structure of basic {L}ie superalgebras and of their affine extensions},
  Author                   = {Frappat, L. and Sciarrino, A. and Sorba, P.},
  Journal                  = {Comm. Math. Phys.},
  Year                     = {1989},
  Number                   = {3},
  Pages                    = {457--500},
  Volume                   = {121},

  Fjournal                 = {Communications in Mathematical Physics},
  ISSN                     = {0010-3616},
  Mrclass                  = {17B70 (17A70 17B40)},
  Mrnumber                 = {990776},
  Mrreviewer               = {A. Pianzola},
  Owner                    = {user},
  Timestamp                = {2017.12.18},
  Url                      = {http://0-projecteuclid.org.library.ucc.ie/euclid.cmp/1104178142}
}

@Book{Grove/Benson:1985,
  Title                    = {Finite reflection groups},
  Author                   = {Grove, L. C. and Benson, C. T.},
  Publisher                = {Springer-Verlag, New York},
  Year                     = {1985},
  Edition                  = {Second},
  Series                   = {Graduate Texts in Mathematics},
  Volume                   = {99},

  ISBN                     = {0-387-96082-1},
  Mrclass                  = {20-01 (20B25 20H15)},
  Mrnumber                 = {777684},
  Owner                    = {user},
  Pages                    = {x+133},
  Timestamp                = {2017.11.15},
  Url                      = {https://doi.org/10.1007/978-1-4757-1869-0}
}

@Book{Helgason:2001,
  Title                    = {Differential geometry, {L}ie groups, and symmetric spaces},
  Author                   = {Helgason, Sigurdur},
  Publisher                = {American Mathematical Society, Providence, RI},
  Year                     = {2001},
  Note                     = {Corrected reprint of the 1978 original},
  Series                   = {Graduate Studies in Mathematics},
  Volume                   = {34},

  ISBN                     = {0-8218-2848-7},
  Mrclass                  = {53C35 (22E10 22E46 22E60)},
  Mrnumber                 = {1834454},
  Owner                    = {user},
  Pages                    = {xxvi+641},
  Timestamp                = {2017.11.15},
  Url                      = {https://doi.org/10.1090/gsm/034}
}

@Book{Humphreys:1990,
  Title                    = {Reflection groups and {C}oxeter groups},
  Author                   = {Humphreys, James E.},
  Publisher                = {Cambridge University Press, Cambridge},
  Year                     = {1990},
  Series                   = {Cambridge Studies in Advanced Mathematics},
  Volume                   = {29},

  ISBN                     = {0-521-37510-X},
  Mrclass                  = {20-02 (20F32 20F55 20G15 20H15)},
  Mrnumber                 = {1066460},
  Mrreviewer               = {Louis Solomon},
  Owner                    = {user},
  Pages                    = {xii+204},
  Timestamp                = {2017.11.15},
  Url                      = {https://doi.org/10.1017/CBO9780511623646}
}

@Book{Kac:1990,
  Title                    = {Infinite-dimensional {L}ie algebras},
  Author                   = {Kac, Victor G.},
  Publisher                = {Cambridge University Press, Cambridge},
  Year                     = {1990},
  Edition                  = {Third},

  ISBN                     = {0-521-37215-1; 0-521-46693-8},
  Mrclass                  = {17B65 (17B67 17B68 58F07)},
  Mrnumber                 = {1104219},
  Owner                    = {user},
  Pages                    = {xxii+400},
  Timestamp                = {2017.11.15},
  Url                      = {https://doi.org/10.1017/CBO9780511626234}
}

@Article{Khastgir/Sasaki:1996,
  Title                    = {Non-canonical folding of {D}ynkin diagrams and reduction of affine {T}oda theories},
  Author                   = {Khastgir, S. Pratik and Sasaki, Ryu},
  Journal                  = {Progr. Theoret. Phys.},
  Year                     = {1996},
  Number                   = {3},
  Pages                    = {503--518},
  Volume                   = {95},

  Fjournal                 = {Progress of Theoretical Physics},
  ISSN                     = {0033-068X},
  Mrclass                  = {81T10 (17B81 58F07 81R10)},
  Mrnumber                 = {1388245},
  Mrreviewer               = {Mehmet Koca},
  Owner                    = {user},
  Timestamp                = {2017.12.18},
  Url                      = {https://doi.org/10.1143/PTP.95.503}
}

@Book{OnishchikVinberg:1990,
  Title                    = {Lie groups and algebraic groups},
  Author                   = {Onishchik, A. L. and Vinberg, {\`E}. B.},
  Publisher                = {Springer-Verlag},
  Year                     = {1990},

  Address                  = {Berlin},
  Note                     = {Translated from the Russian and with a preface by D. A. Leites},
  Series                   = {Springer Series in Soviet Mathematics},

  ISBN                     = {3-540-50614-4},
  Mrclass                  = {22-01 (17B20 20G20 22E10 22E15)},
  Mrnumber                 = {91g:22001},
  Mrreviewer               = {James E. Humphreys},
  Owner                    = {user},
  Pages                    = {xx+328},
  Timestamp                = {2017.11.15}
}

@Book{Onishchik/Vinberg:1990,
  Title                    = {Lie groups and algebraic groups},
  Author                   = {Onishchik, A. L. and Vinberg, \`E. B.},
  Publisher                = {Springer-Verlag, Berlin},
  Year                     = {1990},
  Note                     = {Translated from the Russian and with a preface by D. A. Leites},
  Series                   = {Springer Series in Soviet Mathematics},

  ISBN                     = {3-540-50614-4},
  Mrclass                  = {22-01 (17B20 20G20 22E10 22E15)},
  Mrnumber                 = {1064110},
  Mrreviewer               = {James E. Humphreys},
  Owner                    = {user},
  Pages                    = {xx+328},
  Timestamp                = {2017.11.15},
  Url                      = {https://doi.org/10.1007/978-3-642-74334-4}
}

@Article{Ransingh:2013,
  Title                    = {Vogan diagrams of untwisted affine {K}ac-{M}oody superalgebras},
  Author                   = {Ransingh, Biswajit},
  Journal                  = {Asian-Eur. J. Math.},
  Year                     = {2013},
  Number                   = {4},
  Pages                    = {1350062, 10},
  Volume                   = {6},

  Fjournal                 = {Asian-European Journal of Mathematics},
  ISSN                     = {1793-5571},
  Mrclass                  = {17B67 (17B05 17B22 17B40)},
  Mrnumber                 = {3149279},
  Mrreviewer               = {Xiangqian Guo},
  Owner                    = {user},
  Timestamp                = {2018.01.11}
}

@Article{Ransingh:unpub,
  Title                    = {{Vogan diagrams of affine twisted Lie superalgebras}},
  Author                   = {Ransingh, B.},
  Journal                  = {ArXiv e-prints},
  Year                     = {2013},

  Month                    = mar,

  Adsnote                  = {Provided by the SAO/NASA Astrophysics Data System},
  Adsurl                   = {http://adsabs.harvard.edu/abs/2013arXiv1303.0092R},
  Archiveprefix            = {arXiv},
  Eprint                   = {1303.0092},
  Keywords                 = {Mathematical Physics, Mathematics - Representation Theory},
  Owner                    = {user},
  Primaryclass             = {math-ph},
  Timestamp                = {2018.01.11}
}

@Article{Regelskis/Vlaar:2016,
  Title                    = {{Reflection matrices, coideal subalgebras and generalized Satake diagrams of affine type}},
  Author                   = {{Regelskis}, V. and {Vlaar}, B.},
  Journal                  = {ArXiv e-prints},
  Year                     = {2016},

  Month                    = feb,

  Adsnote                  = {Provided by the SAO/NASA Astrophysics Data System},
  Adsurl                   = {http://adsabs.harvard.edu/abs/2016arXiv160208471R},
  Archiveprefix            = {arXiv},
  Eprint                   = {1602.08471},
  Keywords                 = {Mathematical Physics, Mathematics - Quantum Algebra, Mathematics - Representation Theory, Nonlinear Sciences - Exactly Solvable and Integrable Systems},
  Owner                    = {user},
  Primaryclass             = {math-ph},
  Timestamp                = {2017.12.04}
}

@Book{Satake:1980,
  Title                    = {Algebraic structures of symmetric domains},
  Author                   = {Satake, Ichir\^o},
  Publisher                = {Iwanami Shoten, Tokyo; Princeton University Press, Princeton, N.J.},
  Year                     = {1980},
  Series                   = {Kan\^o Memorial Lectures},
  Volume                   = {4},

  Mrclass                  = {32-02 (17C35 32Mxx 53C35)},
  Mrnumber                 = {591460},
  Mrreviewer               = {S. Murakami},
  Owner                    = {user},
  Pages                    = {xvi+321},
  Timestamp                = {2017.11.15}
}

@InCollection{Zuber:1998,
  Title                    = {Generalized {D}ynkin diagrams and root systems and their folding},
  Author                   = {Zuber, Jean-Bernard},
  Booktitle                = {Topological field theory, primitive forms and related topics ({K}yoto, 1996)},
  Publisher                = {Birkh\"auser Boston, Boston, MA},
  Year                     = {1998},
  Pages                    = {453--493},
  Series                   = {Progr. Math.},
  Volume                   = {160},

  Mrclass                  = {17B20 (05C25 20F55)},
  Mrnumber                 = {1653035},
  Mrreviewer               = {Saeid Azam},
  Owner                    = {user},
  Timestamp                = {2017.12.18}
}

@Book{Vinberg:1994,
  Title                    = {Lie groups and {L}ie algebras, {III}},
  Editor                   = {Vinberg, \`E. B.},
  Publisher                = {Springer-Verlag, Berlin},
  Year                     = {1994},
  Note                     = {Structure of Lie groups and Lie algebras, A translation of {{\i}t Current problems in mathematics. Fundamental directions. Vol. 41} (Russian), Akad. Nauk SSSR, Vsesoyuz. Inst. Nauchn. i Tekhn. Inform., Moscow, 1990 [ MR1056485 (91b:22001)], Translation by V. Minachin [V. V. Minakhin], Translation edited by A. L. Onishchik and \`E. B. Vinberg},
  Series                   = {Encyclopaedia of Mathematical Sciences},
  Volume                   = {41},

  ISBN                     = {3-540-54683-9},
  Mrclass                  = {22-06 (17-06 22Exx)},
  Mrnumber                 = {1349140},
  Owner                    = {user},
  Pages                    = {iv+248},
  Timestamp                = {2017.11.15},
  Url                      = {https://doi.org/10.1007/978-3-662-03066-0}
}


text:
package java_test

import (
	"io/ioutil"
	"testing"

	"github.com/effxhq/effx-cli/metadata/java"
	"github.com/stretchr/testify/require"
)

func TestHandlePomFile(t *testing.T) {
	content, _ := ioutil.ReadFile("./pom.xml")
	res := java.HandlePomFile(string(content))

	require.Equal(t, res, "1.9")
}

repository: effxhq/effx-cli

repo_name: effxhq/effx-cli

gha_language: Go


text:
package spacelift

import (
	"context"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"

	"github.com/spacelift-io/terraform-provider-spacelift/spacelift/internal"
	"github.com/spacelift-io/terraform-provider-spacelift/spacelift/internal/structs"
)

func dataVCSAgentPools() *schema.Resource {
	return &schema.Resource{
		Description: "" +
			"`spacelift_vcs_agent_pools` represents the VCS agent pools assigned " +
			"to the Spacelift account.",

		ReadContext: dataVCSAgentPoolsRead,

		Schema: map[string]*schema.Schema{
			"vcs_agent_pools": {
				Type:     schema.TypeList,
				Computed: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"vcs_agent_pool_id": {
							Type:        schema.TypeString,
							Description: "ID of the VCS agent pool to retrieve",
							Required:    true,
						},
						"description": {
							Type:        schema.TypeString,
							Description: "Free-form VCS agent pool description for users",
							Computed:    true,
						},
						"name": {
							Type:        schema.TypeString,
							Description: "Name of the VCS agent pool",
							Computed:    true,
						},
					},
				},
			},
		},
	}
}

func dataVCSAgentPoolsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
	var query struct {
		VCSAgentPools []*structs.VCSAgentPool `graphql:"vcsAgentPools()"`
	}
	variables := map[string]interface{}{}

	if err := meta.(*internal.Client).Query(ctx, "VCSAgentPoolsRead", &query, variables); err != nil {
		return diag.Errorf("could not query for VCS Agent pools: %v", err)
	}

	d.SetId("spacelift-vcs-agent-pools")

	vcsAgentPools := query.VCSAgentPools
	if vcsAgentPools == nil {
		d.Set("vcs_agent_pools", nil)
		return nil
	}

	aps := flattenDataVCSAgentPoolsList(vcsAgentPools)
	if err := d.Set("vcs_agent_pools", aps); err != nil {
		d.SetId("")
		return diag.Errorf("could not set VCS agent pools: %v", err)
	}

	return nil
}

func flattenDataVCSAgentPoolsList(vcsAgentPools []*structs.VCSAgentPool) []map[string]interface{} {
	out := make([]map[string]interface{}, len(vcsAgentPools))

	for index, ap := range vcsAgentPools {
		var description *string

		if ap.Description != nil {
			description = ap.Description
		} else {
			description = nil
		}

		out[index] = map[string]interface{}{
			"vcs_agent_pool_id": ap.ID,
			"name":              ap.Name,
			"description":       description,
		}
	}

	return out
}


text:
// Copyright (C) 2017-Present CloudFoundry.org Foundation, Inc. All rights reserved.
//
// This program and the accompanying materials are made available under
// the terms of the 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 lifecycle

import (
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"time"

	specs "github.com/opencontainers/runtime-spec/specs-go"

	"code.cloudfoundry.org/clock"
	"code.cloudfoundry.org/lager/v3"

	"bpm/config"
	"bpm/models"
	"bpm/runc/client"
	"bpm/usertools"
)

const (
	ContainerSigQuitGracePeriod = 2 * time.Second
	ContainerStatePollInterval  = 1 * time.Second

	ContainerStateRunning = "running"
	ContainerStatePaused  = "paused"
	ContainerStateStopped = "stopped"
)

var (
	timeoutError    = errors.New("failed to stop job within timeout")
	isNotExistError = errors.New("process is not running or could not be found")
)

func IsNotExist(err error) bool {
	return err == isNotExistError
}

//go:generate go run -mod=vendor github.com/golang/mock/mockgen -copyright_file ./mock_lifecycle/header.txt -destination ./mock_lifecycle/mocks.go bpm/runc/lifecycle UserFinder,CommandRunner,RuncAdapter,RuncClient

type UserFinder interface {
	Lookup(username string) (specs.User, error)
}

type CommandRunner interface {
	Run(*exec.Cmd) error
}

type RuncAdapter interface {
	CreateJobPrerequisites(bpmCfg *config.BPMConfig, procCfg *config.ProcessConfig, user specs.User) (*os.File, *os.File, error)
	BuildSpec(logger lager.Logger, bpmCfg *config.BPMConfig, procCfg *config.ProcessConfig, user specs.User) (specs.Spec, error)
}

type RuncClient interface {
	CreateBundle(bundlePath string, jobSpec specs.Spec, user specs.User) error
	RunContainer(pidFilePath, bundlePath, containerID string, detach bool, stdout, stderr io.Writer) (int, error)
	Exec(containerID, command string, stdin io.Reader, stdout, stderr io.Writer) error
	ContainerState(containerID string) (*specs.State, error)
	ListContainers() ([]client.ContainerState, error)
	SignalContainer(containerID string, signal client.Signal) error
	DeleteContainer(containerID string) error
	DestroyBundle(bundlePath string) error
}

type RuncLifecycle struct {
	clock         clock.Clock
	commandRunner CommandRunner
	runcAdapter   RuncAdapter
	runcClient    RuncClient
	userFinder    UserFinder
	deleteFile    func(string) error
}

func NewRuncLifecycle(
	runcClient RuncClient,
	runcAdapter RuncAdapter,
	userFinder UserFinder,
	commandRunner CommandRunner,
	clock clock.Clock,
	deleteFile func(string) error,
) *RuncLifecycle {
	return &RuncLifecycle{
		clock:         clock,
		runcClient:    runcClient,
		runcAdapter:   runcAdapter,
		userFinder:    userFinder,
		commandRunner: commandRunner,
		deleteFile:    deleteFile,
	}
}

func (j *RuncLifecycle) StartProcess(logger lager.Logger, bpmCfg *config.BPMConfig, procCfg *config.ProcessConfig) error {
	logger = logger.Session("start-process")
	logger.Info("starting")
	defer logger.Info("complete")

	stdout, stderr, err := j.setupProcess(logger, bpmCfg, procCfg)
	if err != nil {
		return err
	}
	defer stdout.Close()
	defer stderr.Close()

	logger.Info("running-container")
	_, err = j.runcClient.RunContainer(
		bpmCfg.PidFile().External(),
		bpmCfg.BundlePath(),
		bpmCfg.ContainerID(),
		true,
		stdout,
		stderr,
	)

	return err
}

func (j *RuncLifecycle) RunProcess(logger lager.Logger, bpmCfg *config.BPMConfig, procCfg *config.ProcessConfig) (int, error) {
	logger = logger.Session("run-process")
	logger.Info("starting")
	defer logger.Info("complete")

	stdout, stderr, err := j.setupProcess(logger, bpmCfg, procCfg)
	if err != nil {
		return 0, err
	}
	defer stdout.Close()
	defer stderr.Close()

	logger.Info("running-container")
	return j.runcClient.RunContainer(
		bpmCfg.PidFile().External(),
		bpmCfg.BundlePath(),
		bpmCfg.ContainerID(),
		false,
		io.MultiWriter(stdout, os.Stdout),
		io.MultiWriter(stderr, os.Stderr),
	)
}

func (j *RuncLifecycle) setupProcess(logger lager.Logger, bpmCfg *config.BPMConfig, procCfg *config.ProcessConfig) (io.WriteCloser, io.WriteCloser, error) {
	user, err := j.userFinder.Lookup(usertools.VcapUser)
	if err != nil {
		return nil, nil, err
	}

	logger.Info("creating-job-prerequisites")
	stdout, stderr, err := j.runcAdapter.CreateJobPrerequisites(bpmCfg, procCfg, user)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to create system files: %s", err.Error())
	}

	logger.Info("building-spec")
	spec, err := j.runcAdapter.BuildSpec(logger, bpmCfg, procCfg, user)
	if err != nil {
		return nil, nil, err
	}

	logger.Info("creating-bundle")
	err = j.runcClient.CreateBundle(bpmCfg.BundlePath(), spec, user)
	if err != nil {
		return nil, nil, fmt.Errorf("bundle build failure: %s", err.Error())
	}

	if procCfg.Hooks != nil {
		preStartCmd := exec.Command(procCfg.Hooks.PreStart)
		preStartCmd.Env = spec.Process.Env
		preStartCmd.Stdout = stdout
		preStartCmd.Stderr = stderr

		err := j.commandRunner.Run(preStartCmd)
		if err != nil {
			return nil, nil, fmt.Errorf("prestart hook failed: %s", err.Error())
		}
	}

	return stdout, stderr, nil
}

func (j *RuncLifecycle) StatProcess(cfg *config.BPMConfig) (*models.Process, error) {
	container, err := j.runcClient.ContainerState(cfg.ContainerID())
	if err != nil {
		return nil, err
	}

	if container == nil {
		return nil, isNotExistError
	}

	return newProcessFromContainerState(
		container.ID,
		container.Status,
		container.Pid,
	), nil
}

func (j *RuncLifecycle) OpenShell(cfg *config.BPMConfig, stdin io.Reader, stdout, stderr io.Writer) error {
	return j.runcClient.Exec(cfg.ContainerID(), "/bin/bash", stdin, stdout, stderr)
}

func (j *RuncLifecycle) ListProcesses() ([]*models.Process, error) {
	containers, err := j.runcClient.ListContainers()
	if err != nil {
		return nil, err
	}

	var processes []*models.Process
	for _, c := range containers {
		processes = append(processes, newProcessFromContainerState(
			c.ID,
			containerStateFromString(c.Status),
			c.InitProcessPid,
		))
	}

	return processes, nil
}

func (j *RuncLifecycle) StopProcess(logger lager.Logger, cfg *config.BPMConfig, procCfg *config.ProcessConfig, exitTimeout time.Duration) error {
	err := j.runcClient.SignalContainer(cfg.ContainerID(), procCfg.ParseShutdownSignal())
	if err != nil {
		return err
	}

	state, err := j.runcClient.ContainerState(cfg.ContainerID())
	if err != nil {
		logger.Error("failed-to-fetch-state", err)
	} else {
		if state.Status == ContainerStateStopped {
			return nil
		}
	}

	timeout := j.clock.NewTimer(exitTimeout)
	stateTicker := j.clock.NewTicker(ContainerStatePollInterval)
	defer stateTicker.Stop()

	for {
		select {
		case <-stateTicker.C():
			state, err = j.runcClient.ContainerState(cfg.ContainerID())
			if err != nil {
				logger.Error("failed-to-fetch-state", err)
			} else {
				if state.Status == ContainerStateStopped {
					return nil
				}
			}
		case <-timeout.C():
			err := j.runcClient.SignalContainer(cfg.ContainerID(), client.Quit)
			if err != nil {
				logger.Error("failed-to-sigquit", err)
			}

			j.clock.Sleep(ContainerSigQuitGracePeriod)
			return timeoutError
		}
	}
}

func (j *RuncLifecycle) RemoveProcess(logger lager.Logger, cfg *config.BPMConfig) error {
	logger.Info("forcefully-deleting-container")
	if err := j.runcClient.DeleteContainer(cfg.ContainerID()); err != nil {
		return err
	}

	logger.Info("destroying-bundle")
	if err := j.runcClient.DestroyBundle(cfg.BundlePath()); err != nil {
		return err
	}

	logger.Info("deleting-pidfile")
	return j.deleteFile(cfg.PidFile().External())
}

func newProcessFromContainerState(id string, status specs.ContainerState, pid int) *models.Process {
	return &models.Process{
		Name:   id,
		Pid:    pid,
		Status: containerStateToString(status),
	}
}

type commandRunner struct{}

func NewCommandRunner() CommandRunner          { return &commandRunner{} }
func (*commandRunner) Run(cmd *exec.Cmd) error { return cmd.Run() }

func containerStateToString(cs specs.ContainerState) string {
	switch cs {
	case specs.StateCreating:
		return models.ProcessStateCreating
	case specs.StateCreated:
		return models.ProcessStateCreated
	case specs.StateRunning:
		return models.ProcessStateRunning
	case specs.StateStopped:
		return models.ProcessStateFailed
	default:
		return models.ProcessStateFailed
	}
}

func containerStateFromString(status string) specs.ContainerState {
	switch status {
	case models.ProcessStateCreating:
		return specs.StateCreating
	case models.ProcessStateCreated:
		return specs.StateCreated
	case models.ProcessStateRunning:
		return specs.StateRunning
	case models.ProcessStateFailed:
		return specs.StateStopped
	default:
		return models.ProcessStateFailed
	}
}

repository: cloudfoundry/bpm-release

repo_name: cloudfoundry/bpm-release


text:
// Package main provides ...
package main

import (
    "fmt"
    "time"
)

func worker(id int, jobs <-chan int, results chan<- int) {
    for j:= range jobs {
        fmt.Println("worker ", id, "processing job ", j)
        time.Sleep(time.Second)
        results <- j*2
    }
}

func main() {
    jobs := make(chan int, 100)
    results := make(chan int, 100)

    for w:=1; w<=3; w++{
        go worker(w, jobs, results)
    }

    for j:=1; j<=9; j++ {
        jobs <- j
    }
    close(jobs)

    for a:=1; a<=9; a++ {
        <-results
    }
}

repository: Zuckonit/letitgo

repo_name: Zuckonit/letitgo


text:
/******************************************************************************

Copyright (c) 2009-2012, Intel Corporation
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.

3. Neither the name of the Intel Corporation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

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.

******************************************************************************/

#include <winsock2.h>
#include <Windows.h>
#include <winnt.h>
#include "ieee1588.hpp"
#include "avbts_clock.hpp"
#include "avbts_osnet.hpp"
#include "avbts_oslock.hpp"
#include "windows_hal.hpp"
#include "avbts_message.hpp"
#include "gptp_cfg.hpp"
#include <tchar.h>
#include <iphlpapi.h>

#include <ether_port.hpp>
#include <wireless_port.hpp>
#include <intel_wireless.hpp>

/* Generic PCH delays */
#define PHY_DELAY_GB_TX_PCH 7750  //1G delay
#define PHY_DELAY_GB_RX_PCH 7750  //1G delay
#define PHY_DELAY_MB_TX_PCH 27500 //100M delay
#define PHY_DELAY_MB_RX_PCH 27500 //100M delay

/* I210 delays */
#define PHY_DELAY_GB_TX_I210 184  //1G delay
#define PHY_DELAY_GB_RX_I210 382  //1G delay
#define PHY_DELAY_MB_TX_I210 1044 //100M delay
#define PHY_DELAY_MB_RX_I210 2133 //100M delay

#define MACSTR_LENGTH 17

uint32_t findLinkSpeed(LinkLayerAddress *local_addr);

static bool exit_flag;

void print_usage( char *arg0 ) {
	fprintf( stderr,
		"%s "
		"[-R <priority 1>] <network interface>\n"
		"where <network interface> is a MAC address entered as xx-xx-xx-xx-xx-xx\n",
		arg0 );
}

BOOL WINAPI ctrl_handler( DWORD ctrl_type ) {
	bool ret;
	if( ctrl_type == CTRL_C_EVENT ) {
		exit_flag = true;
		ret = true;
	} else {
		ret = false;
	}
	return ret;
}

int parseMacAddr( _TCHAR *macstr, uint8_t *octet_string ) {
	int i;
	_TCHAR *cur = macstr;

	if( strnlen_s( macstr, MACSTR_LENGTH ) != 17 ) return -1;

	for( i = 0; i < ETHER_ADDR_OCTETS; ++i ) {
		octet_string[i] = strtol( cur, &cur, 16 ) & 0xFF;
		++cur;
	}

	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	PortInit_t portInit;

	phy_delay_map_t ether_phy_delay;
	ether_phy_delay[LINKSPEED_1G].set_delay
	(PHY_DELAY_GB_TX_PCH, PHY_DELAY_GB_RX_PCH);
	ether_phy_delay[LINKSPEED_100MB].set_delay
	(PHY_DELAY_MB_TX_PCH, PHY_DELAY_MB_RX_PCH);

	portInit.clock = NULL;
	portInit.index = 1;
	portInit.timestamper = NULL;
	portInit.net_label = NULL;
	portInit.automotive_profile = false;
	portInit.isGM = false;
	portInit.testMode = false;
	portInit.initialLogSyncInterval = LOG2_INTERVAL_INVALID;
	portInit.initialLogPdelayReqInterval = LOG2_INTERVAL_INVALID;
	portInit.operLogPdelayReqInterval = LOG2_INTERVAL_INVALID;
	portInit.operLogSyncInterval = LOG2_INTERVAL_INVALID;
	portInit.condition_factory = NULL;
	portInit.thread_factory = NULL;
	portInit.timer_factory = NULL;
	portInit.lock_factory = NULL;
	portInit.neighborPropDelayThreshold =
		CommonPort::NEIGHBOR_PROP_DELAY_THRESH;

	bool syntonize = false;
	bool wireless = false;
	uint8_t priority1 = 248;
	int i;
	int phy_delays[4] =	{ -1, -1, -1, -1 };
	uint8_t addr_ostr[ETHER_ADDR_OCTETS];

	// Register default network interface
	WindowsPCAPNetworkInterfaceFactory *default_factory = new WindowsPCAPNetworkInterfaceFactory();
	OSNetworkInterfaceFactory::registerFactory( factory_name_t( "default" ), default_factory );

	// Create thread, lock, timer, timerq factories
	portInit.thread_factory = new WindowsThreadFactory();
	portInit.lock_factory = new WindowsLockFactory();
	portInit.timer_factory = new WindowsTimerFactory();
	portInit.condition_factory = new WindowsConditionFactory();
	WindowsNamedPipeIPC *ipc = new WindowsNamedPipeIPC();
	WindowsTimerQueueFactory *timerq_factory = new WindowsTimerQueueFactory();
	CommonPort *port;
	WindowsWirelessAdapter *wl_adapter = NULL;

	if( !ipc->init() ) {
		delete ipc;
		ipc = NULL;
	}

	// If there are no arguments, output usage
	if (1 == argc) {
		print_usage(argv[0]);
		return -1;
	}

	/* Process optional arguments */
	for( i = 1; i < argc; ++i ) {
		if (ispunct(argv[i][0]))
		{
			if (toupper(argv[i][1]) == 'H') {
				print_usage(argv[0]);
				return -1;
			}
			if (toupper(argv[i][1]) == 'W')
			{
				wireless = true;
			}
			else if (toupper(argv[i][1]) == 'R') {
				if (i + 1 >= argc) {
					printf("Priority 1 value must be specified on "
						"command line, using default value\n");
				}
				else {
					unsigned long tmp = strtoul(argv[i + 1], NULL, 0); ++i;
					if (tmp > 255) {
						printf("Invalid priority 1 value, using "
							"default value\n");
					}
					else {
						priority1 = (uint8_t)tmp;
					}
				}
			}
		} else
		{
			break;
		}
	}

	// Parse local HW MAC address
	if (i < argc)
	{
		parseMacAddr(argv[i++], addr_ostr);
		portInit.net_label = new LinkLayerAddress(addr_ostr);
	} else
	{
		printf("Local hardware MAC address required");
		return -1;
	}

	if( wireless )
	{
		if (i < argc)
		{
			parseMacAddr(argv[i++], addr_ostr);
			portInit.virtual_label = new LinkLayerAddress(addr_ostr);
		} else
		{
			printf("Wireless operation requires local virtual MAC address");
			return -1;
		}
	}

	if (!wireless)
	{
		// Create HWTimestamper object
		portInit.timestamper = new WindowsEtherTimestamper();
	} else
	{
		portInit.timestamper = new WindowsWirelessTimestamper();
		(static_cast<WindowsWirelessTimestamper *> (portInit.timestamper))->setAdapter(new IntelWirelessAdapter());
	}

	// Create Clock object
	portInit.clock = new IEEE1588Clock(false, false, priority1, timerq_factory, ipc, portInit.lock_factory);  // Do not force slave

	if (!wireless)
	{
		// Create Port Object linked to clock and low level
		portInit.phy_delay = &ether_phy_delay;
		EtherPort *eport = new EtherPort(&portInit);
		eport->setLinkSpeed( findLinkSpeed( static_cast <LinkLayerAddress *> ( portInit.net_label )));
		port = eport;
		if (!eport->init_port()) {
			printf("Failed to initialize port\n");
			return -1;
		}
		port->processEvent(POWERUP);
	} else
	{
		if (i < argc)
		{
			parseMacAddr(argv[i++], addr_ostr);
			LinkLayerAddress peer_addr(addr_ostr);
			port = new WirelessPort(&portInit, peer_addr);
			(static_cast <WirelessTimestamper *> (portInit.timestamper))->setPort( static_cast<WirelessPort *> ( port ));
			if (!port->init_port()) {
				printf("Failed to initialize port\n");
				return -1;
			}
			port->processEvent(POWERUP);
		} else
		{
			printf("Wireless operation requires remote MAC address");
			return -1;
		}
	}

	// Wait for Ctrl-C
	if( !SetConsoleCtrlHandler( ctrl_handler, true )) {
		printf( "Unable to register Ctrl-C handler\n" );
		return -1;
	}

	while( !exit_flag ) Sleep( 1200 );

	delete( ipc );

	return 0;
}

#define WIN_LINKSPEED_MULT (1000/*1 Kbit*/)

uint32_t findLinkSpeed( LinkLayerAddress *local_addr )
{
	ULONG ret_sz;
	char *buffer;
	PIP_ADAPTER_ADDRESSES pAddr;
	ULONG err;
	uint32_t ret;

	buffer = (char *) malloc((size_t)15000);
	ret_sz = 15000;
	pAddr = (PIP_ADAPTER_ADDRESSES)buffer;
	err = GetAdaptersAddresses( AF_UNSPEC, 0, NULL, pAddr, &ret_sz );
	for (; pAddr != NULL; pAddr = pAddr->Next)
	{
		//fprintf(stderr, "** here : %p\n", pAddr);
		if (pAddr->PhysicalAddressLength == ETHER_ADDR_OCTETS &&
			*local_addr == LinkLayerAddress(pAddr->PhysicalAddress))
		{
			break;
		}
	}

	if (pAddr == NULL)
		return INVALID_LINKSPEED;

	switch ( pAddr->ReceiveLinkSpeed / WIN_LINKSPEED_MULT )
	{
	default:
		GPTP_LOG_ERROR("Can't find link speed, %llu", pAddr->ReceiveLinkSpeed);
		ret = INVALID_LINKSPEED;
		break;
	case LINKSPEED_1G:
		ret = LINKSPEED_1G;
		break;
	case LINKSPEED_100MB:
		ret = LINKSPEED_100MB;
		break;
	}

	delete buffer;
	return ret;
}

repository: lukasz-wiecaszek/gptp

repo_name: lukasz-wiecaszek/gptp


text:
package grpc

import (
	"context"
	"time"

	"github.com/rs/xid"
	"github.com/rs/zerolog"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

// TraceField provides the field names for logging the trace
type TraceField struct {
	// RequestFieldName is the name of the trace id field in the request e.g. x-b3-traceid
	RequestFieldName string
	// LoggingFieldName is the name of the trace field to send to the logger e.g. logging.googleapis.com/trace
	LoggingFieldName string
}

// RequestID extracts the request id from context, if there is
// no request id a fresh ID is generated
func RequestID(ctx context.Context, fieldName string) string {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return xid.New().String()
	}
	if v, ok := md[fieldName]; ok && len(v) > 0 {
		return v[0]
	}
	return xid.New().String()
}

// TraceID extracts the trace ID from the context, if there is
// no trace id an empty string is returned
func TraceID(ctx context.Context, fieldName string) string {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return ""
	}
	if v, ok := md[fieldName]; ok && len(v) > 0 {
		return v[0]
	}
	return ""
}

// LogUnaryInterceptor returns grpc middleware to log unary method calls
func LogUnaryInterceptor(l zerolog.Logger, fieldName string, tf TraceField) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		var start = time.Now().UTC()
		log := l.With().Fields(map[string]interface{}{
			fieldName:           RequestID(ctx, fieldName),
			tf.LoggingFieldName: TraceID(ctx, tf.RequestFieldName),
			"grpc.method":       info.FullMethod,
		}).Logger()
		ctx = log.WithContext(ctx)
		defer log.Debug().
			TimeDiff("grpc.duration", time.Now().UTC(), start).
			Msg("handled gRPC unary request")
		return handler(ctx, req)
	}
}

// WrappedServerStream is a thin wrapper around grpc.ServerStream
// that allows modifying context
type WrappedServerStream struct {
	grpc.ServerStream

	WrappedContext context.Context
}

// Context returns the wrapper's WrappedContext,
// overwriting the nested grpc.ServerStream.Context()
func (w *WrappedServerStream) Context() context.Context {
	return w.WrappedContext
}

// LogStreamInterceptor returns grpc middleware to log stream method calls
func LogStreamInterceptor(l zerolog.Logger, fieldName string, tf TraceField) grpc.StreamServerInterceptor {
	return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
		var start = time.Now().UTC()
		log := l.With().Fields(map[string]interface{}{
			fieldName:           RequestID(ss.Context(), fieldName),
			tf.LoggingFieldName: TraceID(ss.Context(), tf.RequestFieldName),
			"grpc.method":       info.FullMethod,
		}).Logger()
		ctx := log.WithContext(ss.Context())
		ws := &WrappedServerStream{
			ss,
			ctx,
		}
		defer log.Debug().
			TimeDiff("grpc.duration", time.Now().UTC(), start).
			Msg("handled gRPC stream request")
		return handler(srv, ws)
	}
}

repository: thisissoon/gokit

repo_name: thisissoon/gokit


text:
SECTION = "kernel"
SUMMARY = "Linux kernel for TI devices"
LICENSE = "GPL-2.0-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=6bc538ed5bd9a7fc9398086aedcd7e46"

KERNEL_CLASSES += "${@bb.utils.contains('TFA_PLATFORM', 'k3', 'kernel-fitimage-ti-u-boot', '', d)}"

inherit kernel

DEFCONFIG_BUILDER = "${S}/ti_config_fragments/defconfig_builder.sh"
require recipes-kernel/linux/setup-defconfig.inc
require recipes-kernel/linux/kernel-rdepends.inc
require recipes-kernel/linux/ti-kernel.inc
include ${@ 'recipes-kernel/linux/ti-kernel-devicetree-prefix.inc' if d.getVar('KERNEL_DEVICETREE_PREFIX') else ''}

DEPENDS += "gmp-native libmpc-native"

# Look in the generic major.minor directory for files
FILESEXTRAPATHS:prepend := "${THISDIR}/${PN}-5.10:"

KERNEL_EXTRA_ARGS += "LOADADDR=${UBOOT_ENTRYPOINT} \
		      ${EXTRA_DTC_ARGS}"

S = "${WORKDIR}/git"

BRANCH = "ti-linux-5.10.y"

SRCREV = "991c5ce91e43cb620f534dc9fe7b0ad21f4f4388"
PV = "5.10.168+git${SRCPV}"

# Append to the MACHINE_KERNEL_PR so that a new SRCREV will cause a rebuild
MACHINE_KERNEL_PR:append = "b"
PR = "${MACHINE_KERNEL_PR}"

KERNEL_GIT_URI = "git://git.ti.com/git/ti-linux-kernel/ti-linux-kernel.git"
KERNEL_GIT_PROTOCOL = "https"
SRC_URI += "${KERNEL_GIT_URI};protocol=${KERNEL_GIT_PROTOCOL};branch=${BRANCH} \
            file://init_disassemble_info-signature-changes-causes-compile-failures.patch \
            file://0001-ata-ahci-fix-enum-constants-for-gcc-13.patch \
            file://defconfig"

FILES:${KERNEL_PACKAGE_NAME}-devicetree += "/${KERNEL_IMAGEDEST}/*.itb"

# Special configuration for remoteproc/rpmsg IPC modules
module_conf_rpmsg_client_sample = "blacklist rpmsg_client_sample"
module_conf_ti_k3_r5_remoteproc = "softdep ti_k3_r5_remoteproc pre: virtio_rpmsg_bus"
module_conf_ti_k3_dsp_remoteproc = "softdep ti_k3_dsp_remoteproc pre: virtio_rpmsg_bus"
KERNEL_MODULE_PROBECONF += "rpmsg_client_sample ti_k3_r5_remoteproc ti_k3_dsp_remoteproc"
KERNEL_MODULE_AUTOLOAD:append:j721e = " rpmsg_kdrv_switch"

repository: YoeDistro/meta-ti

repo_name: YoeDistro/meta-ti


text:
@article{2002JEI....11..414C,
 adsnote = {Provided by the SAO/NASA Astrophysics Data System},
 adsurl = {https://ui.adsabs.harvard.edu/abs/2002JEI....11..414C},
 author = {Cox, I. and Miller, M. and Bloom, J. and Honsinger, Chris},
 doi = {10.1117/1.1494075},
 journal = {Journal of Electronic Imaging},
 month = {Jan},
 number = {3},
 pages = {414},
 title = {Digital Watermarking},
 volume = {11},
 year = {2002}
}


text:
package crypto

import (
	"errors"
)

const (
	CODE_FORMAT_JSON     = "json"
	CODE_FORMAT_PROTOBUF = "protobuf"
)

type Coder interface {
	Decode(ciphertext []byte, target interface{}) error
	Encode(content interface{}) ([]byte, error)
}

var (
	coderRegister = map[string]Coder{}
)

func GenerateCoder(format string) (Coder, error) {
	if coder, ok := coderRegister[format]; ok {
		return coder, nil
	}
	return nil, errors.New("coder is not exist")
}

func IsCoderExist(format string) bool {
	for key, _ := range coderRegister {
		if key == format {
			return true
		}
	}

	return false
}

repository: liuwill/tcp-client-runner

repo_name: liuwill/tcp-client-runner


text:
/*
   Copyright 2018-2019 Banco Bilbao Vizcaya Argentaria, S.A.

   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 spec

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"testing"
	"time"
)

type TestF func(t *testing.T)

type LetF func(t *testing.T, desc string, fns ...TestF)
type ReportF func() string

func New() (LetF, ReportF) {
	report := make([]string, 1)
	return func(t *testing.T, desc string, fns ...TestF) {
			t.Helper()
			var ri int
			idx := strings.Count(t.Name(), "/")
			for _, fn := range fns {
				status := t.Run(strconv.Itoa(idx), func(t *testing.T) {
					report = append(report, t.Name()+": "+desc)
					ri = len(report) - 1
					fmt.Println(desc)
					fn(t)
				})
				switch {
				case status == true:
					report[ri] += " -> ok!"
				case status == false:
					report[ri] += " -> failed!"
				}
			}
		}, func() string {
			return strings.Join(report, "\n")
		}
}

func Equal(t testing.TB, exp, got interface{}, msg ...string) {
	t.Helper()
	if !reflect.DeepEqual(exp, got) {
		t.Fatalf("Not equals: %s -> expecting '%v' got '%v'\n", msg, exp, got)
	}
}

func True(t testing.TB, cond bool, msg ...string) {
	t.Helper()
	if cond != true {
		t.Fatalf("Condition is not true: %s -> %v", msg, cond)
	}
}

func False(t testing.TB, cond bool, msg ...string) {
	t.Helper()
	if cond != false {
		t.Fatalf("Condition is not false: %s -> %v", msg, cond)
	}
}

func NoError(t testing.TB, err error, msg ...string) {
	t.Helper()
	if err != nil {
		t.Fatalf("Error is not nil: %s -> %v", msg, err)
	}
}

func Error(t testing.TB, err error, msg ...string) {
	t.Helper()
	if err == nil {
		t.Fatalf("Error is not nil: %s -> %v", msg, err)
	}
}

func isNil(object interface{}) bool {

	if object == nil {
		return true
	}

	value := reflect.ValueOf(object)

	if value.IsNil() {
		return true
	}

	return false
}

func NotNil(t testing.TB, object interface{}, msg ...string) {
	t.Helper()
	if isNil(object) {
		t.Fatalf("Object is nil: %v --> %v", msg, object)
	}
}

func Retry(t testing.TB, tries int, delay time.Duration, fn func() error) {
	t.Helper()
	var i int
	var err error
	for i = 0; i < tries; i++ {
		err = fn()
		if err == nil {
			return
		}
		time.Sleep(delay)
	}
	if err != nil {
		t.Fatalf("Error in condition:: try %v --> err %v", i, err)
	}
	if err == nil {
		t.Fatalf("Retry timed out in try %v (delay %v)", tries, delay)
	}
}

func RetryOnFalse(t testing.TB, tries int, delay time.Duration, fn func() bool, format string, vars ...interface{}) {
	t.Helper()
	Retry(t, tries, delay, func() error {
		if fn() {
			return nil
		}
		return fmt.Errorf(format, vars...)
	})
}

repository: aalda/qed

repo_name: aalda/qed


text:
// Embed entry point

// Import all the third party stuff
import { createMemoryHistory as createHistory } from 'history'
import * as R from 'ramda'
import * as React from 'react'
import * as redux from 'react-redux'
import { Route, Router, Switch, useLocation, useParams } from 'react-router-dom'
import * as M from '@material-ui/core'

// initialize config from window.QUILT_CATALOG_CONFIG
import cfg from 'constants/config'

// init Sentry before importing other modules
// to allow importing it directly in other modules and capturing errors
import * as Sentry from 'utils/Sentry'

Sentry.init(cfg)

// side-effect: inject global css
import 'sanitize.css'

// Import the rest of our modules
import * as Layout from 'components/Layout'
import Placeholder from 'components/Placeholder'
import * as Auth from 'containers/Auth'
import { ThrowNotFound, createNotFound } from 'containers/NotFoundPage'
import * as Notifications from 'containers/Notifications'
import * as routes from 'constants/embed-routes'
import * as style from 'constants/style'
import * as APIConnector from 'utils/APIConnector'
import * as AWS from 'utils/AWS'
import * as BucketCache from 'utils/BucketCache'
import { createBoundary } from 'utils/ErrorBoundary'
import * as GraphQL from 'utils/GraphQL'
import * as NamedRoutes from 'utils/NamedRoutes'
import * as Cache from 'utils/ResourceCache'
import * as Store from 'utils/Store'
import defer from 'utils/defer'
import { ErrorDisplay } from 'utils/error'
import * as RT from 'utils/reactTools'
import * as s3paths from 'utils/s3paths'
import useConstant from 'utils/useConstant'
import useMemoEq from 'utils/useMemoEq'
import usePrevious from 'utils/usePrevious'

// TODO: consider reimplementing these locally or moving to some shared location
import { displayError } from 'containers/Bucket/errors'

import WithGlobalStyles from '../global-styles'

import AppBar from './AppBar'
import * as EmbedConfig from './EmbedConfig'
import * as Overrides from './Overrides'
import * as ipc from './ipc'

const SuspensePlaceholder = () => <Placeholder color="text.secondary" />

const Dir = RT.mkLazy(() => import('./Dir'), SuspensePlaceholder)
const File = RT.mkLazy(() => import('./File'), SuspensePlaceholder)
const Search = RT.mkLazy(() => import('./Search'), SuspensePlaceholder)

const FinalBoundary = createBoundary(() => (error) => (
  <h1
    style={{
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      height: 400,
      maxHeight: '90vh',
      fontFamily: 'sans-serif',
      margin: 0,
    }}
  >
    {error.headline || 'Something went wrong'}
  </h1>
))

function StyledError({ children }) {
  return (
    <M.Box
      display="flex"
      alignItems="center"
      justifyContent="center"
      height={400}
      maxHeight="90vh"
      textAlign="center"
    >
      <M.Typography variant="h3">{children}</M.Typography>
    </M.Box>
  )
}

const ErrorBoundary = createBoundary(() => (error) => (
  <StyledError>{error.headline || 'Something went wrong'}</StyledError>
))

const CatchNotFound = createNotFound(() => <StyledError>Page not found</StyledError>)

function Root() {
  const l = useLocation()
  const { paths } = NamedRoutes.use()
  return (
    <CatchNotFound id={`${l.pathname}${l.search}${l.hash}`}>
      <Switch>
        <Route path={paths.bucketRoot}>
          <Bucket />
        </Route>
        <Route>
          <ThrowNotFound />
        </Route>
      </Switch>
    </CatchNotFound>
  )
}

function Bucket() {
  const { bucket } = useParams()
  const { paths } = NamedRoutes.use()

  return (
    <BucketLayout bucket={bucket}>
      <Switch>
        <Route path={paths.bucketFile} exact strict>
          <File />
        </Route>
        <Route path={paths.bucketDir} exact>
          <Dir />
        </Route>
        <Route path={paths.bucketSearch} exact>
          <Search />
        </Route>
        <Route>
          <ThrowNotFound />
        </Route>
      </Switch>
    </BucketLayout>
  )
}

function BucketLayout({ bucket, children }) {
  const data = BucketCache.useBucketExistence(bucket)
  return (
    <>
      <AppBar bucket={bucket} />
      <M.Container maxWidth="lg">
        {data.case({
          Ok: () => children,
          Err: displayError(),
          _: () => <Placeholder color="text.secondary" />,
        })}
      </M.Container>
      <M.Box flexGrow={1} />
    </>
  )
}

function useInit() {
  const messageParent = ipc.useMessageParent()
  const [state, setState] = React.useState(null)

  ipc.useMessageHandler(
    React.useCallback(
      ({ type, ...init }) => {
        if (type !== 'init') return
        try {
          if (!init.bucket && !init.route)
            throw new Error('missing either .bucket or .route')
          if (init.scope) {
            if (typeof init.scope !== 'string') throw new Error('.scope must be a string')
            // eslint-disable-next-line no-param-reassign
            init.scope = s3paths.ensureSlash(init.scope)
          }
          Overrides.validate(init.overrides)
          setState(init)
        } catch (e) {
          const message = `Configuration error: ${e.message}`
          // eslint-disable-next-line no-console
          console.error(message)
          // eslint-disable-next-line no-console
          console.log('init object:', init)
          messageParent({ type: 'error', message, init })
          setState(e)
        }
      },
      [setState, messageParent],
    ),
  )

  React.useEffect(() => {
    messageParent({ type: 'ready' })
  }, [messageParent])

  return state
}

function Init() {
  const [key, setKey] = React.useState(0)
  const init = useInit()
  usePrevious(init, (prev) => {
    if (init !== prev) {
      setKey((k) => k + 1)
    }
  })
  if (!init) return <Placeholder color="text.secondary" />
  if (init instanceof Error) {
    return <StyledError>Configuration error</StyledError>
  }
  return (
    <ErrorBoundary key={key}>
      <App {...{ key, init }} />
    </ErrorBoundary>
  )
}

function usePostInit(init) {
  const dispatch = redux.useDispatch()
  const messageParent = ipc.useMessageParent()
  const [state, setState] = React.useState(null)

  React.useEffect(() => {
    const result = defer()
    dispatch(Auth.actions.signIn(init.credentials, result.resolver))
    result.promise
      .then(() => {
        setState(true)
        messageParent({ type: 'init', init })
      })
      .catch((e) => {
        // eslint-disable-next-line no-console
        console.warn('Authentication failure:')
        // eslint-disable-next-line no-console
        console.error(e)
        setState(new ErrorDisplay('Authentication Failure'))
        messageParent({
          type: 'error',
          message: `Authentication failure: ${e.message}`,
          credentials: init.credentials,
        })
      })
  }, [init, dispatch, messageParent])

  return state
}

function PostInit({ init, children }) {
  const state = usePostInit(init)
  if (!state) return <Placeholder color="text.secondary" />
  if (state instanceof Error) throw state
  return children
}

function WithCustomTheme({ theme, children }) {
  const customTheme = useMemoEq(theme, style.createCustomAppTheme)
  return (
    <M.MuiThemeProvider theme={customTheme}>
      <WithGlobalStyles>{children}</WithGlobalStyles>
    </M.MuiThemeProvider>
  )
}

function CustomThemeProvider({ theme, children }) {
  if (!theme || R.isEmpty(theme)) return children
  return <WithCustomTheme theme={theme}>{children}</WithCustomTheme>
}

const appendLink = (el) => {
  const x = window.document.getElementsByTagName('link')[0]
  x.parentNode.insertBefore(el, x)
}

const removeLink = (el) => {
  el.parentNode.removeChild(el)
}

function useCssFiles(files = []) {
  React.useEffect(() => {
    const els = files.map((href) => {
      const el = window.document.createElement('link')
      el.rel = 'stylesheet'
      el.href = href
      appendLink(el)
      return el
    })

    return () => {
      els.forEach(removeLink)
    }
  }, [files])
}

function useSyncHistory(history) {
  const messageParent = ipc.useMessageParent()

  ipc.useMessageHandler(
    React.useCallback(
      ({ type, ...data }) => {
        if (type !== 'navigate') return
        try {
          if (!data.route) throw new Error('missing .route')
          if (typeof data.route !== 'string') throw new Error('.route must be a string')
          history.push(data.route)
        } catch (e) {
          const message = `Navigate: error: ${e.message}`
          // eslint-disable-next-line no-console
          console.error(message)
          // eslint-disable-next-line no-console
          console.log('params:', data)
          messageParent({ type: 'error', message, data })
        }
      },
      [history, messageParent],
    ),
  )

  React.useEffect(
    () =>
      history.listen((l, action) => {
        messageParent({
          type: 'navigate',
          route: `${l.pathname}${l.search}${l.hash}`,
          action,
        })
      }),
    [history, messageParent],
  )
}

function App({ init }) {
  const { urls } = NamedRoutes.use()
  const history = useConstant(() =>
    createHistory({
      initialEntries: [init.route || urls.bucketDir(init.bucket, init.path)],
    }),
  )

  useSyncHistory(history)

  const storage = useConstant(() => ({
    load: () => ({}),
    set: () => {},
    remove: () => {},
  }))

  useCssFiles(init.css)

  return RT.nest(
    [Overrides.Provider, { value: init.overrides }],
    [EmbedConfig.Provider, { config: init }],
    [CustomThemeProvider, { theme: init.theme }],
    Store.Provider,
    Cache.Provider,
    [Router, { history }],
    [React.Suspense, { fallback: <Placeholder color="text.secondary" /> }],
    GraphQL.Provider,
    Notifications.Provider,
    [APIConnector.Provider, { fetch, middleware: [Auth.apiMiddleware] }],
    [Auth.Provider, { storage }],
    AWS.Credentials.Provider,
    AWS.Config.Provider,
    AWS.S3.Provider,
    Notifications.WithNotifications,
    BucketCache.Provider,
    [PostInit, { init }],
    Root,
  )
}

export default function Embed() {
  return RT.nest(
    FinalBoundary,
    [M.MuiThemeProvider, { theme: style.appTheme }],
    WithGlobalStyles,
    Layout.Root,
    ErrorBoundary,
    [NamedRoutes.Provider, { routes }],
    Init,
  )
}

repository: quiltdata/quilt

repo_name: quiltdata/quilt

extension: js


text:
package goloader

import (
	"encoding/binary"
	"unsafe"
)

//go:linkname add runtime.add
func add(p unsafe.Pointer, x uintptr) unsafe.Pointer

//go:linkname adduintptr runtime.add
func adduintptr(p uintptr, x int) unsafe.Pointer

func putUint24(b []byte, v uint32) {
	_ = b[2] // early bounds check to guarantee safety of writes below
	b[0] = byte(v)
	b[1] = byte(v >> 8)
	b[2] = byte(v >> 16)
}

func alignof(i int, align int) int {
	if i%align != 0 {
		i = i + (align - i%align)
	}
	return i
}

func bytearrayAlign(b *[]byte, align int) {
	length := len(*b)
	if length%align != 0 {
		*b = append(*b, make([]byte, align-length%align)...)
	}
}

func putAddress(b []byte, addr uint64) {
	if PtrSize == Uint32Size {
		binary.LittleEndian.PutUint32(b, uint32(addr))
	} else {
		binary.LittleEndian.PutUint64(b, uint64(addr))
	}
}

// sign extend a 24-bit integer
func signext24(x int64) int32 {
	return (int32(x) << 8) >> 8
}

func copy2Slice(dst []byte, src uintptr, size int) {
	var s = sliceHeader{
		Data: src,
		Len:  size,
		Cap:  size,
	}
	copy(dst, *(*[]byte)(unsafe.Pointer(&s)))
}

//go:nosplit
//go:noinline
//see runtime.internal.atomic.Loadp
func loadp(ptr unsafe.Pointer) unsafe.Pointer {
	return *(*unsafe.Pointer)(ptr)
}

repository: weblfe/goloader

repo_name: weblfe/goloader


text:
@techreport{gupta1983,
	address = {Office of Nuclear Waste Isolation},
	title = {Sensitivity/{Uncertainty} {Analysis} of a {Borehole} {Scenario} {Comparing} {Latin} {Hypercube} {Sampling} and {Deterministic} {Sensitivity} {Approaches}},
	number = {BMI/ONWI-516},
	institution = {Battelle Memorial Institute},
	author = {Gupta, S.K. and Harper, W.V.},
	year = {1983},
}


text:
require tzcode-native.inc
SRC_URI = "\
  http://bent.latency.net/bent/darcs/zoneinfo-${PV}/src/tzcode${PV}.tar.gz \
  http://bent.latency.net/bent/darcs/zoneinfo-${PV}/src/tzdata${PV}.tar.gz \
"

PR = "${INC_PR}.0"

repository: demsey/openembedded

repo_name: demsey/openembedded