text:
% This should the last document processed by sphinx (to resolve all citations). hence
% the z_ prefix to the filename

@INPROCEEDINGS{XTang_ICCD_2015,
author={X. Tang and P. Gaillardon and G. De Micheli},
booktitle={2015 33rd IEEE International Conference on Computer Design (ICCD)},
title={FPGA-SPICE: A simulation-based power estimation framework for FPGAs},
year={2015},
volume={},
number={},
pages={696-703},
keywords={circuit simulation;field programmable gate arrays;logic design;power consumption;SPICE;table lookup;flip-flops;global routing architecture;circuit elements;grid-level testbenches;full-chip-level testbenches;component-level testbenches;architectural description language;LUTs;FPGAs routing multiplexers;look up tables;power consumption;analytical power models;probabilistic activity estimation;field programmable gate array;simulation-based power estimation framework;FPGA-SPICE;Field programmable gate arrays;Routing;Integrated circuit modeling;Estimation;SPICE;Table lookup},
doi={10.1109/ICCD.2015.7357183},
ISSN={},
month={Oct},}

@ARTICLE{XTang_JETCAS_2018,
author={X. Tang and E. Giacomin and G. De Micheli and P. Gaillardon},
journal={IEEE Journal on Emerging and Selected Topics in Circuits and Systems},
title={Post-P amp;R Performance and Power Analysis for RRAM-Based FPGAs},
year={2018},
volume={8},
number={3},
pages={639-650},
keywords={Field programmable gate arrays;Random access memory;Analytical models;Delays;Resistance;Routing;Programmable logic arrays;resistive ram;simulation;system modeling;integrated circuit reliability},
doi={10.1109/JETCAS.2018.2847600},
ISSN={2156-3357},
month={Sept},}

@book{VBetz_Book_1999,
 editor = {Betz, Vaughn and Rose, Jonathan and Marquardt, Alexander},
 title = {Architecture and CAD for Deep-Submicron FPGAs},
 year = {1999},
 isbn = {0792384601},
 publisher = {Kluwer Academic Publishers},
 address = {Norwell, MA, USA},
}

@article{XTang_TCAS1_2016,
	title={{A Study on the Programming Structures for RRAM-based FPGA Architectures}},
	author={Tang, Xifan and Kim, Gain and Gaillardon, Pierre-Emmanuel and De Micheli, Giovanni},
	journal={IEEE Transactions on Circuits and Systems I: Regular Papers},
	volume={63},
	number={4},
	pages={503--516},
	year={2016},
	publisher={IEEE}
}

@ARTICLE{XTang_TCAS1_2017,
	author={X. Tang and E. Giacomin and G. De Micheli and P. E. Gaillardon},
	journal={IEEE Transactions on Circuits and Systems I: Regular Papers},
	title={{Circuit Designs of High-Performance and Low-Power RRAM-Based Multiplexers Based on 4T(ransistor)1R(RAM) Programming Structure}},
	year={2017},
	volume={64},
	number={5},
	pages={1173-1186},
	keywords={Delays;Logic gates;Multiplexing;Programming;Resistance;Routing;Transistors;Circuit design;high-performance;low-power;multiplexer;resistive memory},
	doi={10.1109/TCSI.2016.2638542},
	ISSN={1549-8328},
	month={May},}

@inproceedings{JLuu_FPGA_2011,
	author = {Luu, Jason and Anderson, Jason Helge and Rose, Jonathan Scott},
	title = {{Architecture Description and Packing for Logic Blocks with Hierarchy, Modes and Complex Interconnect}},
	booktitle = {Proceedings of the 19th ACM/SIGDA International Symposium on Field Programmable Gate Arrays},
	series = {FPGA '11},
	year = {2011},
	isbn = {978-1-4503-0554-9},
	location = {Monterey, CA, USA},
	pages = {227--236},
	numpages = {10},
	url = {http://doi.acm.org/10.1145/1950413.1950457},
	doi = {10.1145/1950413.1950457},
	acmid = {1950457},
	publisher = {ACM},
	address = {New York, NY, USA},
	keywords = {architecture description language, clustering, complex block, configurable memory, configurable multiplier, fpga, hard logic cluster, logic block, logic cluster, packing, soft logic cluster, splitting},
}

@INPROCEEDINGS{JGoeders_FPT_2012,
	author={J. B. Goeders and S. J. E. Wilton},
	booktitle={2012 International Conference on Field-Programmable Technology},
	title={{VersaPower: Power Estimation for Diverse FPGA Architectures}},
	year={2012},
	pages={229-234},
	keywords={CMOS integrated circuits;SPICE;computer architecture;field programmable gate arrays;logic CAD;CMOS technology;HDL;SPICE;VPR;VersaPower;Versatile Place and Route 6.0;academic FPGA CAD tool;complex logic block;diverse FPGA architecture;field programmable gate array;fracturable look-up table;power consumption;power estimation;size 130 nm;size 22 nm;size 45 nm;Capacitance;Field programmable gate arrays;Multiplexing;Solid modeling;Table lookup;Transistors;Wires},
	doi={10.1109/FPT.2012.6412139},
	month={Dec},}

@inproceedings{JRose_FPGA_2012,
   author = {Rose, Jonathan and Luu, Jason and Yu, Chi Wai and Densmore, Opal and Goeders, Jeffrey and Somerville, Andrew and Kent, Kenneth B. and Jamieson, Peter and Anderson, Jason},
   title = {{The VTR Project: Architecture and CAD for FPGAs from Verilog to Routing}},
   booktitle = {Proceedings of the ACM/SIGDA International Symposium on Field Programmable Gate Arrays},
   series = {FPGA '12},
   year = {2012},
   isbn = {978-1-4503-1155-7},
   location = {Monterey, California, USA},
   pages = {77--86},
   numpages = {10},
   url = {http://doi.acm.org/10.1145/2145694.2145708},
   doi = {10.1145/2145694.2145708},
   acmid = {2145708},
   publisher = {ACM},
   address = {New York, NY, USA},
   keywords = {CAD, FPGA, architecture},
}

repository: mithro/OpenFPGA

repo_name: mithro/OpenFPGA


text:
# A function to create a zserio C++ runtime static library.
#
# Usage: zserio_add_runtime_library
#   RUNTIME_LIBRARY_DIR runtime_library_dir
function(zserio_add_runtime_library)
    # parse cmdline args
    foreach (ARG ${ARGV})
        if ((ARG STREQUAL RUNTIME_LIBRARY_DIR))
            if (DEFINED VALUE_${ARG})
                message(FATAL_ERROR "Option ${ARG} used multiple times!")
            endif ()
            set(ARG_NAME ${ARG})
        else ()
            if (DEFINED VALUE_${ARG_NAME})
                message(FATAL_ERROR "Argument ${ARG_NAME} requires exactly one value!")
            endif ()
            set(VALUE_${ARG_NAME} ${ARG})
        endif ()
    endforeach ()

    foreach (ARG RUNTIME_LIBRARY_DIR)
        if (NOT DEFINED VALUE_${ARG})
            message(FATAL_ERROR "No value defined for required argument ${ARG}!")
        endif ()
    endforeach ()

    add_subdirectory(${VALUE_RUNTIME_LIBRARY_DIR} ZserioCppRuntime)
endfunction()

# A function to create a static library out of Zserio-generated sources.
#
# Usage: zserio_add_library
#   target_name
#   SOURCE_DIR src_dir
#   MAIN_SOURCE src_file
#   SOURCES all source files (optional, relative to SOURCE_DIR)
#   OUT_DIR out_dir
#   OUT_FILES out_files...
#   ZSERIO_CORE_DIR zserio_core_dir
#   ZSERIO_CPP_DIR zserio_cpp_dir
#   ZSERIO_OPTIONS ... (optional)
#   EXPECTED_WARNINGS num_warnings (optional, default 0)
#   IGNORE_ERRORS ON|OFF (optional, default OFF)
#   ZSERIO_LOG_FILENAME (optional)
#   APPEND_TO_ZSERIO_LOG_FILE ON|OFF (optional, default OFF)
#
# Only the files mentioned in OUT_FILES will be added to the static library target.
# OUT_FILES can be EMPTY if no output should be generated.
# Glob is not used because using GLOB for sources is frowned upon in CMake world.
# (CMake doesn't pick up changes in the glob, e.g. added files.)
#
# The actual Zserio generation target is added to the top-level target "gen".
function(zserio_add_library TARGET_NAME)
    # parse cmdline args
    foreach (ARG ${ARGN})
        if ((ARG STREQUAL SOURCE_DIR) OR
            (ARG STREQUAL MAIN_SOURCE) OR
            (ARG STREQUAL SOURCES) OR
            (ARG STREQUAL OUT_DIR) OR
            (ARG STREQUAL OUT_FILES) OR
            (ARG STREQUAL ZSERIO_CORE_DIR) OR
            (ARG STREQUAL ZSERIO_CPP_DIR) OR
            (ARG STREQUAL ZSERIO_OPTIONS) OR
            (ARG STREQUAL EXPECTED_WARNINGS) OR
            (ARG STREQUAL IGNORE_ERRORS) OR
            (ARG STREQUAL ZSERIO_LOG_FILENAME) OR
            (ARG STREQUAL APPEND_TO_ZSERIO_LOG_FILE))
            if (DEFINED VALUE_${ARG})
                message(FATAL_ERROR "Option ${ARG} used multiple times!")
            endif ()
            set(ARG_NAME ${ARG})
        else ()
            list(APPEND VALUE_${ARG_NAME} ${ARG})
        endif ()
    endforeach ()

    foreach (ARG SOURCE_DIR MAIN_SOURCE OUT_DIR OUT_FILES ZSERIO_CORE_DIR ZSERIO_CPP_DIR)
        if (NOT DEFINED VALUE_${ARG})
            message(FATAL_ERROR "No value defined for required argument ${ARG}!")
        endif ()
    endforeach ()

    foreach (ARG SOURCE_DIR MAIN_SOURCE OUT_DIR ZSERIO_CORE_DIR ZSERIO_CPP_DIR)
        list(LENGTH VALUE_${ARG} LEN)
        if (NOT(LEN EQUAL 1))
            message(FATAL_ERROR "Argument ${ARG} requires exactly one value!")
        endif ()
    endforeach ()

    # defaults
    if (NOT DEFINED VALUE_EXPECTED_WARNINGS)
        set(VALUE_EXPECTED_WARNINGS 0)
    endif ()
    if (NOT DEFINED VALUE_IGNORE_ERRORS)
        set(VALUE_IGNORE_ERRORS OFF)
    endif ()
    if (NOT DEFINED VALUE_APPEND_TO_ZSERIO_LOG_FILE)
        set(VALUE_APPEND_TO_ZSERIO_LOG_FILE OFF)
    endif ()

    # create ALL_SOURCES list with full paths
    foreach (SOURCE ${VALUE_SOURCES})
        list(APPEND ALL_SOURCES ${VALUE_SOURCE_DIR}/${SOURCE})
    endforeach ()
    list(APPEND ALL_SOURCES ${VALUE_SOURCE_DIR}/${VALUE_MAIN_SOURCE})

    # Java is required, so search for it already here at file-scope
    if (NOT DEFINED JAVA_BIN OR JAVA_BIN STREQUAL "JAVA_BIN-NOTFOUND")
        find_program(JAVA_BIN java PATHS $ENV{JAVA_HOME}/bin ENV PATH NO_DEFAULT_PATH)
        if (JAVA_BIN STREQUAL "JAVA_BIN-NOTFOUND")
            message(FATAL_ERROR "Java not found, define JAVA_BIN in CMake or JAVA_HOME in environment!")
        endif ()
    endif ()

    # check if library is header only
    if ("${VALUE_OUT_FILES}" STREQUAL "EMPTY")
        set(VALUE_OUT_FILES "")
    endif ()
    string(FIND "${VALUE_OUT_FILES}" ".cpp" SOURCE_FILE_POSITION)

    # set ${VALUE_OUT_FILES} as GENERATED
    set_source_files_properties(${VALUE_OUT_FILES} PROPERTIES GENERATED TRUE)

    # set zserio extra options given by environment
    set(ZSERIO_EXTRA_OPTIONS "$ENV{ZSERIO_EXTRA_ARGS}")
    separate_arguments(ZSERIO_EXTRA_OPTIONS)

    # hack to always re-run Zserio compiler (Zserio itself can skip sources generations if it's not needed)
    # - uses ${TARGET_NAME}_ALWAYS_GENERATE output which will be never generated and thus it will always re-run
    add_custom_command(OUTPUT ${TARGET_NAME}_ALWAYS_GENERATE
        COMMAND ${CMAKE_COMMAND} -DJAVA_BIN=${JAVA_BIN}
            -DCORE_DIR=${VALUE_ZSERIO_CORE_DIR} -DCPP_DIR=${VALUE_ZSERIO_CPP_DIR} -DOUT_DIR=${VALUE_OUT_DIR}
            -DSOURCE_DIR=${VALUE_SOURCE_DIR} -DMAIN_SOURCE=${VALUE_MAIN_SOURCE}
            -DOPTIONS="${VALUE_ZSERIO_OPTIONS}" -DEXTRA_OPTIONS="${ZSERIO_EXTRA_OPTIONS}"
            -DEXPECTED_WARNINGS=${VALUE_EXPECTED_WARNINGS}
            -DIGNORE_ERRORS=${VALUE_IGNORE_ERRORS}
            -DLOG_FILENAME="${VALUE_ZSERIO_LOG_FILENAME}"
            -DAPPEND_TO_LOG_FILE=${VALUE_APPEND_TO_ZSERIO_LOG_FILE}
            -P ${CMAKE_MODULE_PATH}/zserio_tool.cmake
        COMMENT "Generating sources with Zserio from ${VALUE_MAIN_SOURCE}")

    # add a custom target for the generation step
    add_custom_target(${TARGET_NAME}_generate
        DEPENDS ${TARGET_NAME}_ALWAYS_GENERATE)

    # add to custom "gen" target
    if (NOT TARGET gen)
        add_custom_target(gen COMMENT "Trigger compilation of all included zserio files.")
    endif ()
    add_dependencies(gen ${TARGET_NAME}_generate)

    # delete whole directory even if Zserio generated a file that's not listed in ZSERIO_GENERATED_SOURCES
    set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${VALUE_OUT_DIR})

    # add a static library
    if (SOURCE_FILE_POSITION EQUAL -1)
        add_library(${TARGET_NAME} INTERFACE)
        add_dependencies(${TARGET_NAME} ${TARGET_NAME}_generate)
        target_include_directories(${TARGET_NAME} INTERFACE ${VALUE_OUT_DIR})
        target_link_libraries(${TARGET_NAME} INTERFACE ZserioCppRuntime)
    else ()
        add_library(${TARGET_NAME} STATIC ${VALUE_OUT_FILES})
        add_dependencies(${TARGET_NAME} ${TARGET_NAME}_generate)
        target_include_directories(${TARGET_NAME} PUBLIC ${VALUE_OUT_DIR})
        target_link_libraries(${TARGET_NAME} PUBLIC ZserioCppRuntime)
        if (SOURCE_FILE_POSITION EQUAL -1)
            # make sure that cmake knows language when no sources are available
            set_target_properties(${TARGET_NAME} PROPERTIES LINKER_LANGUAGE CXX)
        endif ()
        set_target_properties(${TARGET_NAME} PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED YES
                CXX_EXTENSIONS NO)
    endif ()
endfunction()

repository: ndsev/zserio

license_type: permissive

repo_name: ndsev/zserio

branch_name: refs/heads/master

gha_language: Java

extension: cmake


text:
require linux-ti-staging_4.19.bb

# Look in the generic major.minor directory for files
# This will have priority over generic non-rt path
FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}-4.19:"

license: MIT

repository: bjornwilliam/meta-ti

repo_name: bjornwilliam/meta-ti

gha_license_id: MIT

extension: bb


text:
# base recipe: meta/recipes-support/libgcrypt/libgcrypt_1.8.4.bb
# base branch: warrior

SUMMARY = "General purpose cryptographic library based on the code from GnuPG"
HOMEPAGE = "http://directory.fsf.org/project/libgcrypt/"

# helper program gcryptrnd and getrandom are under GPL, rest LGPL
LICENSE = "GPLv2+ & LGPLv2.1+ & GPLv3+"
LICENSE_${PN} = "LGPLv2.1+"
LICENSE_${PN}-dev = "GPLv2+ & LGPLv2.1+"
LICENSE_dumpsexp-dev = "GPLv3+"

LIC_FILES_CHKSUM = " \
    file://COPYING;md5=94d55d512a9ba36caa9b7df079bae19f \
    file://COPYING.LIB;md5=bbb461211a33b134d42ed5ee802b37ff \
    file://LICENSES;md5=840e3bcb754e5046ffeda7619034cbd8 \
    file://src/dumpsexp.c;endline=16;md5=3134b0d35419b6af066b890fde4b6e05 \
"

inherit debian-package
require recipes-debian/sources/libgcrypt20.inc

FILESPATH_append = ":${COREBASE}/meta/recipes-support/libgcrypt/files"
SRC_URI += " \
    file://0001-Add-and-use-pkg-config-for-libgcrypt-instead-of-conf.patch \
    file://0002-libgcrypt-fix-building-error-with-O2-in-sysroot-path.patch \
    file://0004-tests-Makefile.am-fix-undefined-reference-to-pthread.patch \
"

DEPENDS = "libgpg-error"

inherit autotools texinfo binconfig-disabled pkgconfig

BINCONFIG = "${bindir}/libgcrypt-config"

EXTRA_OECONF = "--disable-asm"
EXTRA_OEMAKE_class-target = "LIBTOOLFLAGS='--tag=CC'"

PACKAGECONFIG ??= "capabilities"
PACKAGECONFIG[capabilities] = "--with-capabilities,--without-capabilities,libcap"

do_configure_prepend() {
	rm -f ${S}/m4/gpg-error.m4
}

# libgcrypt.pc is added locally and thus installed here
do_install_append() {
	install -d ${D}/${libdir}/pkgconfig
	install -m 0644 ${B}/src/libgcrypt.pc ${D}/${libdir}/pkgconfig/
}

PACKAGES =+ "dumpsexp-dev"

FILES_${PN}-dev += "${bindir}/hmac256"
FILES_dumpsexp-dev += "${bindir}/dumpsexp"

BBCLASSEXTEND = "native nativesdk"

repository: meta-debian/meta-debian

repo_name: meta-debian/meta-debian

branch_name: refs/heads/warrior

gha_language: BitBake


text:
DESCRIPTION = "Utility for signing and verifying files for UEFI Secure Boot"
LICENSE = "GPLv3 & LGPL-2.1 & LGPL-3.0 & MIT"

# sbsigntool statically links to libccan.a which is built with modules
# passed to "create-ccan-tree" (and their dependencies). Therefore,
# we also keep track of all the ccan module licenses.
LIC_FILES_CHKSUM = "file://LICENSE.GPLv3;md5=9eef91148a9b14ec7f9df333daebc746 \
                    file://COPYING;md5=a7710ac18adec371b84a9594ed04fd20 \
                    file://lib/ccan.git/ccan/endian/LICENSE;md5=2d5025d4aa3495befef8f17206a5b0a1 \
                    file://lib/ccan.git/ccan/htable/LICENSE;md5=2d5025d4aa3495befef8f17206a5b0a1 \
                    file://lib/ccan.git/ccan/list/LICENSE;md5=2d5025d4aa3495befef8f17206a5b0a1 \
                    file://lib/ccan.git/ccan/read_write_all/LICENSE;md5=2d5025d4aa3495befef8f17206a5b0a1 \
                    file://lib/ccan.git/ccan/talloc/LICENSE;md5=2d5025d4aa3495befef8f17206a5b0a1 \
                    file://lib/ccan.git/ccan/typesafe_cb/LICENSE;md5=2d5025d4aa3495befef8f17206a5b0a1 \
                    file://lib/ccan.git/ccan/failtest/LICENSE;md5=6a6a8e020838b23406c81b19c1d46df6 \
                    file://lib/ccan.git/ccan/tlist/LICENSE;md5=6a6a8e020838b23406c81b19c1d46df6 \
                    file://lib/ccan.git/ccan/time/LICENSE;md5=838c366f69b72c5df05c96dff79b35f2 \
"

# The original upstream is git://kernel.ubuntu.com/jk/sbsigntool but it has
# not been maintained and many patches have been backported in this repo.
SRC_URI = "git://git.kernel.org/pub/scm/linux/kernel/git/jejb/sbsigntools.git;protocol=https;name=sbsigntools \
           git://github.com/rustyrussell/ccan.git;protocol=https;destsuffix=git/lib/ccan.git;name=ccan \
          "

SRCREV_sbsigntools  ?= "efbb550858e7bd3f43e64228d22aea440ef6a14d"
SRCREV_ccan         ?= "b1f28e17227f2320d07fe052a8a48942fe17caa5"
SRCREV_FORMAT       =  "sbsigntools_ccan"

DEPENDS = "binutils-native gnu-efi-native help2man-native openssl-native util-linux-native"

PV = "0.8-git${SRCPV}"

S = "${WORKDIR}/git"

inherit native autotools pkgconfig

do_configure_prepend() {
	cd ${S}

	if [ ! -e lib/ccan ]; then

		# Use empty SCOREDIR because 'make scores' is not run.
		# The default setting depends on (non-whitelisted) host tools.
		sed -i -e 's#^\(SCOREDIR=\).*#\1#' lib/ccan.git/Makefile

		lib/ccan.git/tools/create-ccan-tree \
		--build-type=automake lib/ccan \
		talloc read_write_all build_assert array_size endian
	fi

	# Create generatable docs from git
	(
	 echo "Authors of sbsigntool:"
	 echo
	 git log --format='%an' | sort -u | sed 's,^,\t,'
	) > AUTHORS

	# Generate simple ChangeLog
	git log --date=short --format='%ad %t %an <%ae>%n%n  * %s%n' > ChangeLog

	cd ${B}
}

def efi_arch(d):
    import re
    harch = d.getVar("HOST_ARCH")
    if re.match("i[3456789]86", harch):
        return "ia32"
    return harch

EXTRA_OEMAKE = "\
    INCLUDES+='-I${S}/lib/ccan.git/ \
              -I${STAGING_INCDIR_NATIVE}/efi \
              -I${STAGING_INCDIR_NATIVE} \
              -I${STAGING_INCDIR_NATIVE}/efi/${@efi_arch(d)}' \
    "

repository: intel/intel-iot-refkit

repo_name: intel/intel-iot-refkit

gha_language: Python


text:
SUMMARY = "Library to assist determining when holidays occur"
LICENSE = "LGPLv2.1"
LIC_FILES_CHKSUM = " \
	file://COPYING.LIB;md5=2d5025d4aa3495befef8f17206a5b0a1 \
"

inherit kde-kf5

SRC_URI[md5sum] = "ba7bac91aeeddb03631dd12b6d44f9e2"
SRC_URI[sha256sum] = "b7e9cdc3aed84ce898071390804d32e03415f43de3f06615d8818fa931898479"

PV = "${KF5_VERSION}"

DEPENDS += " \
    qtdeclarative \
"

FILES_${PN} += "${OE_QMAKE_PATH_QML}/org/kde/${BPN}"


text:
@article{article,
author = {Serrano-Macías, María and Alvarez-Galvez, Javier},
year = {2017},
month = {09},
pages = {127-150},
title = {Education and tourism in Spain: Identification of tourist profiles through the application of decision trees},
journal = {Empiria}
}

extension: bib


text:
package main

import (
	gStructs "github.com/AlessandroPomponio/go-gibberish/structs"
	"github.com/gorilla/mux"
	healthcheck "github.com/shitpostingio/analysis-commons/health-check"
	"log"
	"net/http"
)

const (
	kbPathKey      = "GB_KNOWLEDGE_PATH"
	bindAddressKey = "GB_BIND_ADDRESS"
)

var (
	knowledgeBasePath = "knowledge.json"
	bindAddress       = "localhost:10002"
	knowledgeBase     *gStructs.GibberishData
	r                 *mux.Router
)

func main() {

	r.HandleFunc("/gibberish", handleGibberish).Methods("POST")
	r.HandleFunc("/healthy", healthcheck.ConfirmServiceHealth).Methods("GET")
	log.Println("Gibberish server powered on!")
	log.Fatal(http.ListenAndServe(bindAddress, r))

}

repository: shitpostingio/gibberish-microservice

repo_name: shitpostingio/gibberish-microservice

branch_name: refs/heads/main

extension: go


text:
SUMMARY = "Whitelisted OpenBMC IPMI OEM commands"
DESCRIPTION = "Whitelisted OpenBMC IPMI OEM commands for OpenPOWER based systems"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://${COREBASE}/meta/files/common-licenses/Apache-2.0;md5=89aea4e17d99a7cacdbeed46a0096b10"

inherit native
inherit phosphor-ipmi-host-whitelist

repository: ampere-openbmc/openbmc

repo_name: ampere-openbmc/openbmc

gha_license_id: NOASSERTION


text:
@misc{AngularWebpage,
  title = {{AngularJS Homepage}},
  howpublished = {\url{https://angularjs.org/}},
  note = {Accessed: 2016-03-16}
}
@misc{d3Webpage,
  title = {{D3.js Homepage}},
  howpublished = {\url{https://d3js.org/}},
  note = {Accessed: 2016-03-16}
}
@misc{CrichtonInstitute,
  title = {{Crichton Institute Homepage}},
  howpublished = {\url{http://crichtonobservatory.org.uk/}},
  note = {Accessed: 2016-03-18}
}
@misc{LondonDashboard,
  title = {{London Dashboard}},
  howpublished = {\url{http://data.london.gov.uk/}},
  note = {Accessed: 2016-03-18}
}
@misc{DublinDashboard,
  title = {{Dublin Dashboard}},
  howpublished = {\url{http://www.dublindashboard.ie/pages/index/}},
  note = {Accessed: 2016-03-18}
}
@misc{NOMISScot,
  title = {{NOMIS Scotland}},
  howpublished = {\url{https://www.nomisweb.co.uk/reports/lmp/gor/2013265931/report.aspx}},
  note = {Accessed: 2016-03-28}
}
@misc{StatisticsScotBeta,
  title = {{Statistics.Gov.Scot Beta Site}},
  howpublished = {\url{http://statistics.gov.scot/}},
  note = {Accessed: 2016-03-28}
}
@misc{AngularGridster,
  title = {{Angular Gridster}},
  howpublished = {\url{https://github.com/ManifestWebDesign/angular-gridster}},
  note = {Accessed: 2016-03-30}
}
@misc{Django,
  title = {{Django Homepage}},
  howpublished = {\url{https://www.djangoproject.com/}},
  note = {Accessed: 2016-03-30}
}
@misc{CrichtonInsituteFounded,
  title = {{Cabinet Secretary Launches Crichton Institute}},
  howpublished = {\url{http://www.gla.ac.uk/news/archiveofnews/2013/march/headline_269859_en.html}},
  note = {Accessed: 2016-03-31}
}
@misc{CrichtonInstituteAboutUs,
  title = {{Crichton Institute About Us}},
  howpublished = {\url{http://crichtoninstitute.co.uk/index.php/about-us}},
  note = {Accessed: 2016-03-31}
}
@misc{CrichtonInsituteCoreAims,
  title = {{Crichton Institute Core Aims}},
  howpublished = {\url{http://crichtoninstitute.co.uk/index.php/core-aims}},
  note = {Accessed: 2016-03-31}
}
@misc{ScotGovOpenDataResourcePack,
  title = {{Scottish Government Open Data Resource Pack}},
  howpublished = {\url{http://www.gov.scot/Publications/2015/08/4093/12#cs2}},
  note = {Accessed: 2016-03-31}
}
@misc{EvaMilroyLinkedIn,
  title = {{Eva Milroy (Development Officer of Crichton Institute)}},
  howpublished = {\url{https://www.linkedin.com/in/evamilroy}},
  note = {Accessed: 2016-03-31}
}
@misc{TonyFitzpatrickLinkedIn,
  title = {{Tony Fitzpatrick (Director of Crichton Institute Regional Observatory and Associate Senior Research Fellow at University of Glasgow)}},
  howpublished = {\url{https://www.linkedin.com/in/tony-fitzpatrick-18328238}},
  note = {Accessed: 2016-03-31}
}
@misc{CrichtonInstituteRegionalObservatory,
  title = {{Crichton Institute Regional Observatory}},
  howpublished = {\url{http://crichtonobservatory.org.uk/}},
  note = {Accessed: 2016-03-31}
}
@misc{PopulationHealthReport,
  title = {{Population and its Health in Dumfries and Galloway}},
  howpublished = {\url{http://crichtonobservatory.org.uk/index.php/resident-population/details/9/339/resident-population-population-and-its-health-in-dumfries-and-galloway}},
  note = {Accessed: 2016-03-31}
}
@misc{ANewApproachToWebApplications,
  title = {{Ajax: A New Approach to Web Applications}},
  howpublished = {\url{http://adaptivepath.org/ideas/ajax-new-approach-web-applications/}},
  year = {2005},
  note = {Accessed: 2016-04-02}
}
@misc{W3CAjaxProposal,
  title = {{The XMLHttpRequest Object}},
  howpublished = {\url{https://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/}},
  year = {2006},
  note = {Accessed: 2016-04-02}
}
@misc{Bootstrap,
  title = {{Bootstrap Homepage}},
  howpublished = {\url{https://getbootstrap.com/}},
  note = {Accessed: 2016-04-02}
}
@misc{Gridster,
  title = {{Gridster Homepage}},
  howpublished = {\url{http://gridster.net/}},
  note = {Accessed: 2016-04-02}
}
@misc{NGSortable,
  title = {{Ng-Sortable Homepage}},
  howpublished = {\url{https://github.com/a5hik/ng-sortable}},
  note = {Accessed: 2016-04-05}
}
@misc{DjangoORM,
  title = {{Information on Django Object Relational Mapping}},
  howpublished = {\url{https://docs.djangoproject.com/en/1.9/topics/db/}},
  note = {Accessed: 2016-04-05}
}
@misc{W3SPARQL,
  title = {{SPARQL Query Language for RDF - W3 Recommendation}},
  howpublished = {\url{https://www.w3.org/TR/rdf-sparql-query/}},
  note = {Accessed: 2016-04-06}
}
@misc{AgileMethods,
  title = {{Get Ready For Agile Methods, With Care}},
  howpublished = {\url{http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=976920&tag=1}},
  note = {Accessed: 2016-04-07}
}
@misc{ExtremeProgramming,
  title = {{Extreme Programming: A Gentle Introduction}},
  howpublished = {\url{http://www.extremeprogramming.org/}},
  note = {Accessed: 2016-04-07}
}
@book{ContinuousIntegration,
  title = {{Continuous Integration: Improving Software Quality and Reducing Risk}},
  author = {Paul M. Duvall and Steve Matyas and Andrew Glover},
  year = {2007},
  publisher = {Pearson Education}
}
@inbook{Planning,
  author = {Kent Beck and Martin Fowler},
  title = {{Planning Extreme Programming}},
  year = {2001},
  publisher = {Addison-Wesley Professional},
  chapter = {5}
}
@misc{Customers,
  title = {{Customer Relationships and Extreme Programming}},
  howpublished = {\url{http://dl.acm.org/citation.cfm?id=1083113 }},
  note = {Accessed: 2016-04-08}
}
@inbook{UserStories,
  author = {Ron Jeffries and Ann Anderson and Chet Hendrickson},
  title = {{Extreme Programming Installed}},
  year = {2001},
  publisher = {Addison-Wesley Professional},
  chapter = {4}
}
@misc{SVN,
  title = {{Subversion Homepage}},
  howpublished = {\url{https://subversion.apache.org/}},
  note = {Accessed: 2016-04-08}
}
@misc{Trac,
  title = {{Trac Homepage}},
  howpublished = {\url{https://trac.edgewall.org/}},
  note = {Accessed: 2016-04-08}
}
@misc{Jenkins,
  title = {{Jenkins Homepage}},
  howpublished = {\url{https://jenkins.io/}},
  note = {Accessed: 2016-04-08}
}
@misc{Git,
  title = {{Git Is Giving Subversion A Run For Its Money: What Took So Long?}},
  howpublished = {\url{http://readwrite.com/2014/01/21/git-subversion-developers/}},
  note = {Accessed: 2016-04-08}
}
@misc{Cobertura,
  title = {{Cobertura Homepage}},
  howpublished = {\url{http://cobertura.github.io/cobertura/}},
  note = {Accessed: 2016-04-08}
}
@misc{Retrospectives,
  title = {{Agile Retrospective Resource Wiki}},
  howpublished = {\url{http://retrospectivewiki.org/index.php?title=Agile_Retrospective_Resource_Wiki}},
  note = {Accessed: 2016-04-08}
}


text:
@article{bedtools,
  title    = "{BEDTools}: a flexible suite of utilities for comparing genomic
              features",
  author   = "Quinlan, Aaron R and Hall, Ira M",
  abstract = "MOTIVATION: Testing for correlations between different sets of
              genomic features is a fundamental task in genomics research.
              However, searching for overlaps between features with existing
              web-based methods is complicated by the massive datasets that are
              routinely produced with current sequencing technologies. Fast and
              flexible tools are therefore required to ask complex questions of
              these data in an efficient manner. RESULTS: This article
              introduces a new software suite for the comparison, manipulation
              and annotation of genomic features in Browser Extensible Data
              (BED) and General Feature Format (GFF) format. BEDTools also
              supports the comparison of sequence alignments in BAM format to
              both BED and GFF features. The tools are extremely efficient and
              allow the user to compare large datasets (e.g. next-generation
              sequencing data) with both public and custom genome annotation
              tracks. BEDTools can be combined with one another as well as with
              standard UNIX commands, thus facilitating routine genomics tasks
              as well as pipelines that can quickly answer intricate questions
              of large genomic datasets. AVAILABILITY AND IMPLEMENTATION:
              BEDTools was written in C++. Source code and a comprehensive user
              manual are freely available at http://code.google.com/p/bedtools
              CONTACT: aaronquinlan@gmail.com; imh4y@virginia.edu SUPPLEMENTARY
              INFORMATION: Supplementary data are available at Bioinformatics
              online.",
  journal  = "Bioinformatics",
  volume   =  26,
  number   =  6,
  pages    = "841--842",
  month    =  mar,
  year     =  2010,
  language = "en",
  doi      = {10.1093/bioinformatics/btq033}
}

@article {mosdepth,
  Title = {Mosdepth: quick coverage calculation for genomes and exomes},
  Author = {Pedersen, Brent S and Quinlan, Aaron R},
  DOI = {10.1093/bioinformatics/btx699},
  Number = {5},
  Volume = {34},
  Month = {March},
  Year = {2018},
  Journal = {Bioinformatics (Oxford, England)},
  ISSN = {1367-4803},
  Pages = {867—868},
  URL = {http://europepmc.org/articles/PMC6030888},
}

@article {coverage,
  Title = {Sequencing depth and coverage: key considerations in genomic analyses},
  Author = {Sims, David and Sudbery, Ian and Ilott, Nicholas E and Heger, Andreas and Ponting, Chris P},
  DOI = {10.1038/nrg3642},
  Number = {2},
  Volume = {15},
  Month = {February},
  Year = {2014},
  Journal = {Nature reviews. Genetics},
  ISSN = {1471-0056},
  Pages = {121—132},
  URL = {https://doi.org/10.1038/nrg3642},
}

@article {samformat,
  Title = {The Sequence Alignment/Map format and SAMtools},
  Author = {Li, Heng and Handsaker, Bob and Wysoker, Alec and Fennell, Tim and Ruan, Jue and Homer, Nils and Marth, Gabor and Abecasis, Goncalo and Durbin, Richard and {1000 Genome Project Data Processing Subgroup}},
  DOI = {10.1093/bioinformatics/btp352},
  Number = {16},
  Volume = {25},
  Month = {August},
  Year = {2009},
  Journal = {Bioinformatics (Oxford, England)},
  ISSN = {1367-4803},
  Pages = {2078—2079},
  URL = {http://europepmc.org/articles/PMC2723002},
}
@article {bamtools,
	Title = {BamTools: a C++ API and toolkit for analyzing and managing BAM files},
	Author = {Barnett, Derek W and Garrison, Erik K and Quinlan, Aaron R and Strömberg, Michael P and Marth, Gabor T},
	DOI = {10.1093/bioinformatics/btr174},
	Number = {12},
	Volume = {27},
	Month = {June},
	Year = {2011},
	Journal = {Bioinformatics (Oxford, England)},
	ISSN = {1367-4803},
	Pages = {1691—1692},
	URL = {http://europepmc.org/articles/PMC3106182},
}

@article {poloni,
	Title = {A targeted next-generation gene panel reveals a novel heterozygous nonsense variant in the TP63 gene in patients with arrhythmogenic cardiomyopathy},
	Author = {Poloni, Giulia and Calore, Martina and Rigato, Ilaria and Marras, Elena and Minervini, Giovanni and Mazzotti, Elisa and Lorenzon, Alessandra and Li Mura, Ilena Egle Astrid and Telatin, Andrea and Zara, Ivano and Simionati, Barbara and Perazzolo Marra, Martina and Ponti, Jessica and Occhi, Gianluca and Vitiello, Libero and Daliento, Luciano and Thiene, Gaetano and Basso, Cristina and Corrado, Domenico and Tosatto, Silvio and Bauce, Barbara and Rampazzo, Alessandra and De Bortoli, Marzia},
	DOI = {10.1016/j.hrthm.2018.11.015},
	Number = {5},
	Volume = {16},
	Month = {May},
	Year = {2019},
	Journal = {Heart rhythm},
	ISSN = {1547-5271},
	Pages = {773—780},
	URL = {https://doi.org/10.1016/j.hrthm.2018.11.015},
}
@misc{phylosophy,
   author = "{Wikipedia contributors}",
   title = "Unix philosophy --- {W}ikipedia{,} The Free Encyclopedia",
   year = "2019",
   url = "https://en.wikipedia.org/w/index.php?title=Unix_philosophy&oldid=919880773",
   note = "[Online; accessed 20 December 2019 ]"
}

@misc{opt,
  author = {Weißl, Johannes},
  title = {cpp-optparse},
  year = {2017},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/weisslj/cpp-optparse}},
  commit = {2ec0b7aca9a692ff93017ed44ca9d13a8e7d4d00}
}

@dataset{dataset,
  author       = {Birolo, Giovanni and
                  Telatin, Andrea},
  title        = {{covtobed test files - 2 BAM files produced by
                   target enrichment experiments}},
  month        = feb,
  year         = 2020,
  publisher    = {Zenodo},
  doi          = {10.5281/zenodo.3643386},
  url          = {https://doi.org/10.5281/zenodo.3643386}
}

repository: telatin/covtobed

repo_name: telatin/covtobed


text:
@phdthesis{stocker2013climate,
 author = {Stocker, Benjamin},
 title = {Climate Forcings and Feedbacks from the Terrestrial Biosphere: From Greenhouse-gas Emissions to Anthropogenic Land Use Change},
 year = {2013}
}


text:
/*     Copyright 2019 Diligent Graphics LLC
 *
 *  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
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.
 *
 *  In no event and under no legal theory, whether in tort (including negligence),
 *  contract, or otherwise, unless required by applicable law (such as deliberate
 *  and grossly negligent acts) or agreed to in writing, shall any Contributor be
 *  liable for any damages, including any direct, indirect, special, incidental,
 *  or consequential damages of any character arising as a result of this License or
 *  out of the use or inability to use the software (including but not limited to damages
 *  for loss of goodwill, work stoppage, computer failure or malfunction, or any and
 *  all other commercial damages or losses), even if such Contributor has been advised
 *  of the possibility of such damages.
 */

/// \file
/// Routines that initialize D3D12-based engine implementation

#include "pch.h"
#include <array>
#include "EngineFactoryD3D12.h"
#include "RenderDeviceD3D12Impl.h"
#include "DeviceContextD3D12Impl.h"
#include "SwapChainD3D12Impl.h"
#include "D3D12TypeConversions.h"
#include "EngineFactoryD3DBase.h"
#include "StringTools.h"
#include "EngineMemory.h"
#include "CommandQueueD3D12Impl.h"
#include <Windows.h>
#include <dxgi1_4.h>

namespace Diligent
{

/// Engine factory for D3D12 implementation
class EngineFactoryD3D12Impl : public EngineFactoryD3DBase<IEngineFactoryD3D12, DeviceType::D3D12>
{
public:
    static EngineFactoryD3D12Impl* GetInstance()
    {
        static EngineFactoryD3D12Impl TheFactory;
        return &TheFactory;
    }

    using TBase = EngineFactoryD3DBase<IEngineFactoryD3D12, DeviceType::D3D12>;

    EngineFactoryD3D12Impl() :
        TBase{IID_EngineFactoryD3D12}
    {}

    void CreateDeviceAndContextsD3D12(const EngineD3D12CreateInfo& EngineCI,
                                      IRenderDevice**              ppDevice,
                                      IDeviceContext**             ppContexts) override final;

    void AttachToD3D12Device(void*                        pd3d12NativeDevice,
                             size_t                       CommandQueueCount,
                             ICommandQueueD3D12**         ppCommandQueues,
                             const EngineD3D12CreateInfo& EngineCI,
                             IRenderDevice**              ppDevice,
                             IDeviceContext**             ppContexts) override final;

    void CreateSwapChainD3D12(IRenderDevice*            pDevice,
                              IDeviceContext*           pImmediateContext,
                              const SwapChainDesc&      SwapChainDesc,
                              const FullScreenModeDesc& FSDesc,
                              void*                     pNativeWndHandle,
                              ISwapChain**              ppSwapChain) override final;
};

static void GetHardwareAdapter(IDXGIFactory2* pFactory, IDXGIAdapter1** ppAdapter, D3D_FEATURE_LEVEL FeatureLevel)
{
    CComPtr<IDXGIAdapter1> adapter;
    *ppAdapter = nullptr;

    for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != pFactory->EnumAdapters1(adapterIndex, &adapter); ++adapterIndex, adapter.Release())
    {
        DXGI_ADAPTER_DESC1 desc;
        adapter->GetDesc1(&desc);

        if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
        {
            // Skip software devices
            continue;
        }

        // Check to see if the adapter supports Direct3D 12, but don't create the
        // actual device yet.
        if (SUCCEEDED(D3D12CreateDevice(adapter, FeatureLevel, _uuidof(ID3D12Device), nullptr)))
        {
            break;
        }
    }

    *ppAdapter = adapter.Detach();
}

void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12(const EngineD3D12CreateInfo& EngineCI,
                                                          IRenderDevice**              ppDevice,
                                                          IDeviceContext**             ppContexts)
{
    if (EngineCI.DebugMessageCallback != nullptr)
        SetDebugMessageCallback(EngineCI.DebugMessageCallback);

    if (EngineCI.APIVersion != DILIGENT_API_VERSION)
        LOG_ERROR_AND_THROW("Diligent Engine runtime (", EngineCI.APIVersion, ") is not compatible with the client API version (", DILIGENT_API_VERSION, ")");

    VERIFY(ppDevice && ppContexts, "Null pointer provided");
    if (!ppDevice || !ppContexts)
        return;

    for (Uint32 Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; Type < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; ++Type)
    {
        auto   CPUHeapAllocSize = EngineCI.CPUDescriptorHeapAllocationSize[Type];
        Uint32 MaxSize          = 1 << 20;
        if (CPUHeapAllocSize > 1 << 20)
        {
            LOG_ERROR("CPU Heap allocation size is too large (", CPUHeapAllocSize, "). Max allowed size is ", MaxSize);
            return;
        }

        if ((CPUHeapAllocSize % 16) != 0)
        {
            LOG_ERROR("CPU Heap allocation size (", CPUHeapAllocSize, ") is expected to be multiple of 16");
            return;
        }
    }

    *ppDevice = nullptr;
    memset(ppContexts, 0, sizeof(*ppContexts) * (1 + EngineCI.NumDeferredContexts));

    RefCntAutoPtr<CommandQueueD3D12Impl> pCmdQueueD3D12;
    CComPtr<ID3D12Device>                d3d12Device;
    try
    {
        // Enable the D3D12 debug layer.
        if (EngineCI.EnableDebugLayer)
        {
            CComPtr<ID3D12Debug> debugController;
            if (SUCCEEDED(D3D12GetDebugInterface(__uuidof(debugController), reinterpret_cast<void**>(static_cast<ID3D12Debug**>(&debugController)))))
            {
                debugController->EnableDebugLayer();
                //static_cast<ID3D12Debug1*>(debugController.p)->SetEnableSynchronizedCommandQueueValidation(FALSE);
                if (EngineCI.EnableGPUBasedValidation)
                {
                    CComPtr<ID3D12Debug1> debugController1;
                    debugController->QueryInterface(IID_PPV_ARGS(&debugController1));
                    if (debugController1)
                    {
                        debugController1->SetEnableGPUBasedValidation(true);
                    }
                }
            }
        }

        CComPtr<IDXGIFactory4> factory;

        HRESULT hr = CreateDXGIFactory1(__uuidof(factory), reinterpret_cast<void**>(static_cast<IDXGIFactory4**>(&factory)));
        CHECK_D3D_RESULT_THROW(hr, "Failed to create DXGI factory");

        // Direct3D12 does not allow feature levels below 11.0 (D3D12CreateDevice fails to create a device).
        const auto MinimumFeatureLevel = EngineCI.MinimumFeatureLevel >= DIRECT3D_FEATURE_LEVEL_11_0 ? EngineCI.MinimumFeatureLevel : DIRECT3D_FEATURE_LEVEL_11_0;

        CComPtr<IDXGIAdapter1> hardwareAdapter;
        if (EngineCI.AdapterId == EngineD3D12CreateInfo::DefaultAdapterId)
        {
            GetHardwareAdapter(factory, &hardwareAdapter, GetD3DFeatureLevel(MinimumFeatureLevel));
            if (hardwareAdapter == nullptr)
                LOG_ERROR_AND_THROW("No suitable hardware adapter found");
        }
        else
        {
            auto Adapters = FindCompatibleAdapters(MinimumFeatureLevel);
            if (EngineCI.AdapterId < Adapters.size())
                hardwareAdapter = Adapters[EngineCI.AdapterId];
            else
            {
                LOG_ERROR_AND_THROW(EngineCI.AdapterId, " is not a valid hardware adapter id. Total number of compatible adapters available on this system: ", Adapters.size());
            }
        }

        {
            DXGI_ADAPTER_DESC1 desc;
            hardwareAdapter->GetDesc1(&desc);
            LOG_INFO_MESSAGE("D3D12-capabale hardware found: ", NarrowString(desc.Description), " (", desc.DedicatedVideoMemory >> 20, " MB)");
        }

        constexpr auto MaxFeatureLevel = DIRECT3D_FEATURE_LEVEL_12_1;
        for (auto FeatureLevel = MaxFeatureLevel; FeatureLevel >= MinimumFeatureLevel; FeatureLevel = static_cast<DIRECT3D_FEATURE_LEVEL>(Uint8{FeatureLevel} - 1))
        {
            auto d3dFeatureLevel = GetD3DFeatureLevel(FeatureLevel);

            hr = D3D12CreateDevice(hardwareAdapter, d3dFeatureLevel, __uuidof(d3d12Device), reinterpret_cast<void**>(static_cast<ID3D12Device**>(&d3d12Device)));
            if (SUCCEEDED(hr))
            {
                VERIFY_EXPR(d3d12Device);
                break;
            }
        }
        if (FAILED(hr))
        {
            LOG_WARNING_MESSAGE("Failed to create hardware device. Attempting to create WARP device");

            CComPtr<IDXGIAdapter> warpAdapter;
            hr = factory->EnumWarpAdapter(__uuidof(warpAdapter), reinterpret_cast<void**>(static_cast<IDXGIAdapter**>(&warpAdapter)));
            CHECK_D3D_RESULT_THROW(hr, "Failed to enum warp adapter");

            for (auto FeatureLevel = MaxFeatureLevel; FeatureLevel >= MinimumFeatureLevel; FeatureLevel = static_cast<DIRECT3D_FEATURE_LEVEL>(Uint8{FeatureLevel} - 1))
            {
                auto d3dFeatureLevel = GetD3DFeatureLevel(FeatureLevel);

                hr = D3D12CreateDevice(warpAdapter, d3dFeatureLevel, __uuidof(d3d12Device), reinterpret_cast<void**>(static_cast<ID3D12Device**>(&d3d12Device)));
                if (SUCCEEDED(hr))
                {
                    VERIFY_EXPR(d3d12Device);
                    break;
                }
            }
            CHECK_D3D_RESULT_THROW(hr, "Failed to crate warp device");
        }

        if (EngineCI.EnableDebugLayer)
        {
            CComPtr<ID3D12InfoQueue> pInfoQueue;
            hr = d3d12Device->QueryInterface(__uuidof(pInfoQueue), reinterpret_cast<void**>(static_cast<ID3D12InfoQueue**>(&pInfoQueue)));
            if (SUCCEEDED(hr))
            {
                // Suppress whole categories of messages
                //D3D12_MESSAGE_CATEGORY Categories[] = {};

                // Suppress messages based on their severity level
                D3D12_MESSAGE_SEVERITY Severities[] =
                    {
                        D3D12_MESSAGE_SEVERITY_INFO //
                    };

                // Suppress individual messages by their ID
                //D3D12_MESSAGE_ID DenyIds[] = {};

                D3D12_INFO_QUEUE_FILTER NewFilter = {};
                //NewFilter.DenyList.NumCategories = _countof(Categories);
                //NewFilter.DenyList.pCategoryList = Categories;
                NewFilter.DenyList.NumSeverities = _countof(Severities);
                NewFilter.DenyList.pSeverityList = Severities;
                //NewFilter.DenyList.NumIDs = _countof(DenyIds);
                //NewFilter.DenyList.pIDList = DenyIds;

                hr = pInfoQueue->PushStorageFilter(&NewFilter);
                VERIFY(SUCCEEDED(hr), "Failed to push storage filter");

                if (EngineCI.BreakOnCorruption)
                {
                    hr = pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true);
                    VERIFY(SUCCEEDED(hr), "Failed to set break on corruption");
                }

                if (EngineCI.BreakOnError)
                {
                    hr = pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true);
                    VERIFY(SUCCEEDED(hr), "Failed to set break on error");
                }
            }
        }

#ifndef RELEASE
        // Prevent the GPU from overclocking or underclocking to get consistent timings
        //d3d12Device->SetStablePowerState(TRUE);
#endif

        // Describe and create the command queue.
        D3D12_COMMAND_QUEUE_DESC queueDesc = {};

        queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
        queueDesc.Type  = D3D12_COMMAND_LIST_TYPE_DIRECT;

        CComPtr<ID3D12CommandQueue> pd3d12CmdQueue;
        hr = d3d12Device->CreateCommandQueue(&queueDesc, __uuidof(pd3d12CmdQueue), reinterpret_cast<void**>(static_cast<ID3D12CommandQueue**>(&pd3d12CmdQueue)));
        CHECK_D3D_RESULT_THROW(hr, "Failed to create command queue");
        hr = pd3d12CmdQueue->SetName(L"Main Command Queue");
        VERIFY_EXPR(SUCCEEDED(hr));

        CComPtr<ID3D12Fence> pd3d12Fence;
        hr = d3d12Device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(pd3d12Fence), reinterpret_cast<void**>(static_cast<ID3D12Fence**>(&pd3d12Fence)));
        CHECK_D3D_RESULT_THROW(hr, "Failed to create main command queue fence");
        d3d12Device->SetName(L"Main Command Queue fence");

        auto& RawMemAllocator = GetRawAllocator();
        pCmdQueueD3D12        = NEW_RC_OBJ(RawMemAllocator, "CommandQueueD3D12 instance", CommandQueueD3D12Impl)(pd3d12CmdQueue, pd3d12Fence);
    }
    catch (const std::runtime_error&)
    {
        LOG_ERROR("Failed to initialize D3D12 resources");
        return;
    }

    std::array<ICommandQueueD3D12*, 1> CmdQueues = {pCmdQueueD3D12};
    AttachToD3D12Device(d3d12Device, CmdQueues.size(), CmdQueues.data(), EngineCI, ppDevice, ppContexts);
}

void EngineFactoryD3D12Impl::AttachToD3D12Device(void*                        pd3d12NativeDevice,
                                                 size_t                       CommandQueueCount,
                                                 ICommandQueueD3D12**         ppCommandQueues,
                                                 const EngineD3D12CreateInfo& EngineCI,
                                                 IRenderDevice**              ppDevice,
                                                 IDeviceContext**             ppContexts)
{
    if (EngineCI.DebugMessageCallback != nullptr)
        SetDebugMessageCallback(EngineCI.DebugMessageCallback);

    if (EngineCI.APIVersion != DILIGENT_API_VERSION)
        LOG_ERROR_AND_THROW("Diligent Engine runtime (", EngineCI.APIVersion, ") is not compatible with the client API version (", DILIGENT_API_VERSION, ")");

    VERIFY(pd3d12NativeDevice && ppCommandQueues && ppDevice && ppContexts, "Null pointer provided");
    if (!pd3d12NativeDevice || !ppCommandQueues || !ppDevice || !ppContexts)
        return;

    *ppDevice = nullptr;
    memset(ppContexts, 0, sizeof(*ppContexts) * (1 + EngineCI.NumDeferredContexts));

    try
    {
        SetRawAllocator(EngineCI.pRawMemAllocator);
        auto& RawMemAllocator = GetRawAllocator();
        auto  d3d12Device     = reinterpret_cast<ID3D12Device*>(pd3d12NativeDevice);

        RenderDeviceD3D12Impl* pRenderDeviceD3D12(NEW_RC_OBJ(RawMemAllocator, "RenderDeviceD3D12Impl instance", RenderDeviceD3D12Impl)(RawMemAllocator, this, EngineCI, d3d12Device, CommandQueueCount, ppCommandQueues));
        pRenderDeviceD3D12->QueryInterface(IID_RenderDevice, reinterpret_cast<IObject**>(ppDevice));

        RefCntAutoPtr<DeviceContextD3D12Impl> pImmediateCtxD3D12(NEW_RC_OBJ(RawMemAllocator, "DeviceContextD3D12Impl instance", DeviceContextD3D12Impl)(pRenderDeviceD3D12, false, EngineCI, 0, 0));
        // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D12 will
        // keep a weak reference to the context
        pImmediateCtxD3D12->QueryInterface(IID_DeviceContext, reinterpret_cast<IObject**>(ppContexts));
        pRenderDeviceD3D12->SetImmediateContext(pImmediateCtxD3D12);

        for (Uint32 DeferredCtx = 0; DeferredCtx < EngineCI.NumDeferredContexts; ++DeferredCtx)
        {
            RefCntAutoPtr<DeviceContextD3D12Impl> pDeferredCtxD3D12(NEW_RC_OBJ(RawMemAllocator, "DeviceContextD3D12Impl instance", DeviceContextD3D12Impl)(pRenderDeviceD3D12, true, EngineCI, 1 + DeferredCtx, 0));
            // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D12 will
            // keep a weak reference to the context
            pDeferredCtxD3D12->QueryInterface(IID_DeviceContext, reinterpret_cast<IObject**>(ppContexts + 1 + DeferredCtx));
            pRenderDeviceD3D12->SetDeferredContext(DeferredCtx, pDeferredCtxD3D12);
        }
    }
    catch (const std::runtime_error&)
    {
        if (*ppDevice)
        {
            (*ppDevice)->Release();
            *ppDevice = nullptr;
        }
        for (Uint32 ctx = 0; ctx < 1 + EngineCI.NumDeferredContexts; ++ctx)
        {
            if (ppContexts[ctx] != nullptr)
            {
                ppContexts[ctx]->Release();
                ppContexts[ctx] = nullptr;
            }
        }

        LOG_ERROR("Failed to create device and contexts");
    }
}

void EngineFactoryD3D12Impl::CreateSwapChainD3D12(IRenderDevice*            pDevice,
                                                  IDeviceContext*           pImmediateContext,
                                                  const SwapChainDesc&      SCDesc,
                                                  const FullScreenModeDesc& FSDesc,
                                                  void*                     pNativeWndHandle,
                                                  ISwapChain**              ppSwapChain)
{
    VERIFY(ppSwapChain, "Null pointer provided");
    if (!ppSwapChain)
        return;

    *ppSwapChain = nullptr;

    try
    {
        auto* pDeviceD3D12        = ValidatedCast<RenderDeviceD3D12Impl>(pDevice);
        auto* pDeviceContextD3D12 = ValidatedCast<DeviceContextD3D12Impl>(pImmediateContext);
        auto& RawMemAllocator     = GetRawAllocator();

        auto* pSwapChainD3D12 = NEW_RC_OBJ(RawMemAllocator, "SwapChainD3D12Impl instance", SwapChainD3D12Impl)(SCDesc, FSDesc, pDeviceD3D12, pDeviceContextD3D12, pNativeWndHandle);
        pSwapChainD3D12->QueryInterface(IID_SwapChain, reinterpret_cast<IObject**>(ppSwapChain));
    }
    catch (const std::runtime_error&)
    {
        if (*ppSwapChain)
        {
            (*ppSwapChain)->Release();
            *ppSwapChain = nullptr;
        }

        LOG_ERROR("Failed to create the swap chain");
    }
}

#ifdef DOXYGEN
/// Loads Direct3D12-based engine implementation and exports factory functions
/// \param [out] GetFactoryFunc - Pointer to the function that returns factory for D3D12 engine implementation.
///                               See EngineFactoryD3D12Impl.
/// \remarks Depending on the configuration and platform, the function loads different dll:
/// Platform\\Configuration   |           Debug               |        Release
/// --------------------------|-------------------------------|----------------------------
///         x86               | GraphicsEngineD3D12_32d.dll   |    GraphicsEngineD3D12_32r.dll
///         x64               | GraphicsEngineD3D12_64d.dll   |    GraphicsEngineD3D12_64r.dll
///
void LoadGraphicsEngineD3D12(GetEngineFactoryD3D12Type& GetFactoryFunc)
{
// This function is only required because DoxyGen refuses to generate documentation for a static function when SHOW_FILES==NO
#    error This function must never be compiled;
}
#endif

IEngineFactoryD3D12* GetEngineFactoryD3D12()
{
    return EngineFactoryD3D12Impl::GetInstance();
}

} // namespace Diligent

repository: IngoChou/DiligentCore

repo_name: IngoChou/DiligentCore

extension: cpp


text:
package cmd

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
)

const zenhubGraphQLV1Endpoint = "https://api.zenhub.io/v1/graphql"

// ZenHubClient implements a partial ZenHub API.
type ZenHubClient struct {
	token string
}

// NewZenHubClient creates ZenHubClient.
func NewZenHubClient(token string) *ZenHubClient {
	return &ZenHubClient{
		token: token,
	}
}

func (zh *ZenHubClient) request(ctx context.Context, query string, vars map[string]interface{}) ([]byte, error) {
	greq := graphQLRequest{Query: query, Variables: vars}
	data, err := json.Marshal(greq)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest(http.MethodPost, zenhubGraphQLV1Endpoint, bytes.NewReader(data))
	if err != nil {
		return nil, err
	}
	req = req.WithContext(ctx)
	req.Header.Set("X-Authentication-Token", zh.token)
	req.Header.Add("Content-Type", "application/json")

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("status code should be 200, but got %d", resp.StatusCode)
	}

	var gresp graphQLResponse
	err = json.NewDecoder(resp.Body).Decode(&gresp)
	if err != nil {
		return nil, err
	}

	if len(gresp.Errors) > 0 {
		return nil, errors.New(gresp.Errors[0].Message)
	}
	return []byte(gresp.Data), nil
}

// NOTE:
// Queries are copied from the value showen on the Network tab on Chrome
// Developer tool when manually connecting a PR with an issue.

// Connect connect a pull request with an issue.
func (zh *ZenHubClient) Connect(ctx context.Context, issueID, pullRequestID string) error {
	query := "mutation CreateIssuePrConnection($input: CreateIssuePrConnectionInput!) {\n  createIssuePrConnection(input: $input) {\n    issue {\n      id\n      __typename\n    }\n    __typename\n  }\n}\n"
	vars := map[string]interface{}{
		"input": map[string]interface{}{
			"issueId":       issueID,
			"pullRequestId": pullRequestID,
		},
	}

	_, err := zh.request(ctx, query, vars)
	if err != nil {
		return err
	}
	return nil
}

// GetIssueID gets a zenhub internal ID for either PR or issue.
func (zh *ZenHubClient) GetIssueID(ctx context.Context, repositoryGhID, issueGhNumber int) (string, error) {
	query := fmt.Sprintf(
		"query IssueByInfo {\n  issueByInfo(repositoryGhId: %d, issueNumber: %d) {\n    id\n    __typename\n  }\n}\n",
		repositoryGhID,
		issueGhNumber,
	)
	vars := map[string]interface{}{}

	data, err := zh.request(ctx, query, vars)
	if err != nil {
		return "", err
	}

	var resp struct {
		IssueByInfo struct {
			ID string `json:"id"`
		} `json:"issueByInfo"`
	}
	err = json.Unmarshal(data, &resp)
	if err != nil {
		return "", err
	}

	return resp.IssueByInfo.ID, nil
}

repository: cybozu-go/neco

repo_name: cybozu-go/neco

gha_language: Go


text:
#include "<%= $cur_module.name %>.h"

<% $cur_module.parents.each do |parent| %>
namespace <%= parent.downcase %> {<%
end %>

IMPLEMENT_LOGCLASS(C<%= $cur_module.name %>Base, "<%= $cur_module.name %>JNI");

//<%= $cur_module.name %>FactorySingleton staff
const char* const C<%= $cur_module.name %>Base::FACTORY_SINGLETON_CLASS = "<%= JavaGen::make_package_name($cur_module) %>.<%= $cur_module.name %>FactorySingleton";
jclass C<%= $cur_module.name %>Base::s_clsFactorySingleton = 0;
jmethodID C<%= $cur_module.name %>Base::s_midFactorySetInstance;
jmethodID C<%= $cur_module.name %>Base::s_midFactoryGetInstance;

//<%= $cur_module.name %>Factory staff
const char* const C<%= $cur_module.name %>Base::IFACTORY_CLASS = "<%= JavaGen::make_package_name($cur_module) %>.I<%= $cur_module.name %>Factory";
jclass C<%= $cur_module.name %>Base::s_clsIFactory = 0;
jmethodID C<%= $cur_module.name %>Base::s_midGetApiSingleton;
jmethodID C<%= $cur_module.name %>Base::s_midGetApiObject;

//<%= $cur_module.name %>SingletonBase staff
const char* const C<%= $cur_module.name %>Base::SINGLETON_BASE_CLASS = "<%= JavaGen::make_package_name($cur_module) %>.<%= $cur_module.name %>SingletonBase";
jclass C<%= $cur_module.name %>Base::s_clsSingletonBase = 0;

//<%= $cur_module.name %>Base staff
const char* const C<%= $cur_module.name %>Base::OBJECT_BASE_CLASS = "<%= JavaGen::make_package_name($cur_module) %>.<%= $cur_module.name %>Base";
jclass C<%= $cur_module.name %>Base::s_clsObjectBase = 0;

<% if $cur_module.is_template_default_instance %>
//IRhoApiDefaultId staff
const char* const C<%= $cur_module.name %>Base::IDEFAULTID_CLASS = "com.rhomobile.rhodes.api.IRhoApiDefaultId";
jclass C<%= $cur_module.name %>Base::s_clsIDefaultId = 0;
jmethodID C<%= $cur_module.name %>Base::s_midGetDefaultID;
jmethodID C<%= $cur_module.name %>Base::s_midSetDefaultID;
<% end %>

//Method tasks
<% $cur_module.methods.each do |method| %>
const char* const C<%= $cur_module.name %>Base::<%= method.native_name.upcase %>_TASK_CLASS = <%
if method.access == ModuleMethod::ACCESS_STATIC %>
        "<%= JavaGen::make_package_name($cur_module) %>.<%= $cur_module.name %>SingletonBase$<%= method.native_name %>Task";
<% else %>
        "<%= JavaGen::make_package_name($cur_module) %>.<%= $cur_module.name %>Base$<%= method.native_name %>Task";
<% end %>
jclass C<%= $cur_module.name %>Base::s_cls<%= method.native_name %>Task = 0;
jmethodID C<%= $cur_module.name %>Base::s_mid<%= method.native_name %>Task;
<% end %>

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

JNIEnv* C<%= $cur_module.name %>Base::jniInit()
{
    JNIEnv *env = jnienv();
    if(!env)
    {
        LOG(FATAL) + "JNI init failed: JNIEnv is null";
        return 0;
    }
    return jniInit(env);
}
//----------------------------------------------------------------------------------------------------------------------

JNIEnv* C<%= $cur_module.name %>Base::jniInit(JNIEnv* env)
{
    static bool initialized = false;
    env = MethodExecutorJni::jniInit(env);
    if (!env) {
        LOG(FATAL) + "JNI init failed";
        return 0;
    }

    if(!initialized)
    {
        //init <%= $cur_module.name %>FactorySingleton JNI
        s_clsFactorySingleton = loadClass(env, FACTORY_SINGLETON_CLASS);
        if (!s_clsFactorySingleton) return 0;

        s_midFactorySetInstance = env->GetStaticMethodID(s_clsFactorySingleton, "setInstance", "(L<%= JavaGen::make_package_path($cur_module) %>/I<%= $cur_module.name %>Factory;)V");
        if(!s_midFactorySetInstance)
        {
            LOG(FATAL) + "Failed to get method 'setInstance' for java class " + FACTORY_SINGLETON_CLASS;
            return NULL;
        }
        s_midFactoryGetInstance = env->GetStaticMethodID(s_clsFactorySingleton, "getInstance", "()L<%= JavaGen::make_package_path($cur_module) %>/I<%= $cur_module.name %>Factory;");
        if(!s_midFactoryGetInstance)
        {
            LOG(FATAL) + "Failed to get method 'getInstance' for java class " + FACTORY_SINGLETON_CLASS;
            return NULL;
        }

        //init I<%= $cur_module.name %>Factory JNI
        s_clsIFactory = loadClass(env, IFACTORY_CLASS);
        if (!s_clsIFactory) return 0;
        s_midGetApiSingleton = env->GetMethodID(s_clsIFactory, "getApiSingleton", "()L<%= JavaGen::make_package_path($cur_module) %>/I<%= $cur_module.name %>Singleton;");
        if(!s_midGetApiSingleton)
        {
            LOG(FATAL) + "Failed to get method 'getApiSingleton' for java class " + IFACTORY_CLASS;
            return NULL;
        }
        s_midGetApiObject = env->GetMethodID(s_clsIFactory, "getApiObject", "(Ljava/lang/String;)L<%= JavaGen::make_package_path($cur_module) %>/I<%= $cur_module.name %>;");
        if(!s_midGetApiObject)
        {
            LOG(FATAL) + "Failed to get method 'getApiObject' for java class " + IFACTORY_CLASS;
            return NULL;
        }

        s_clsSingletonBase = loadClass(env, SINGLETON_BASE_CLASS);
        if (!s_clsSingletonBase) return 0;
        s_clsObjectBase = loadClass(env, OBJECT_BASE_CLASS);
        if (!s_clsObjectBase) return 0;

<% $cur_module.methods.each do |method|
    java_class = "I#{$cur_module.name}"
    java_class += 'Singleton' if method.access == ModuleMethod::ACCESS_STATIC
    params_signature = "(L#{JavaGen::make_package_path($cur_module)}/#{java_class};"
    method.params.each do |param|
        params_signature += JavaGen::make_native_type_signature(param.type)
    end
    params_signature += "Lcom/rhomobile/rhodes/api/IMethodResult;)V"
%>
        s_cls<%= method.native_name %>Task = loadClass(env, <%= method.native_name.upcase %>_TASK_CLASS);
        if (!s_cls<%= method.native_name %>Task) return 0;
        s_mid<%= method.native_name %>Task = env->GetMethodID(s_cls<%= method.native_name %>Task, "<init>",
                        "<%= params_signature %>");
        if(!s_mid<%= method.native_name %>Task)
        {
            LOG(FATAL) + "Failed to get constructor for java class " + <%= method.native_name.upcase %>_TASK_CLASS;
            return NULL;
        }
<% end %>
<% if $cur_module.is_template_default_instance %>
        s_clsIDefaultId = loadClass(env, IDEFAULTID_CLASS);
        if (!s_clsIDefaultId) return 0;
        s_midGetDefaultID = env->GetMethodID(s_clsIDefaultId, "getDefaultID", "()Ljava/lang/String;");
        if(!s_midGetDefaultID)
        {
            LOG(FATAL) + "Failed to get method 'getDefaultID' for java class " + IDEFAULTID_CLASS;
            return NULL;
        }
        s_midSetDefaultID = env->GetMethodID(s_clsIDefaultId, "setDefaultID", "(Ljava/lang/String;)V");
        if(!s_midSetDefaultID)
        {
            LOG(FATAL) + "Failed to get method 'setDefaultID' for java class " + IDEFAULTID_CLASS;
            return NULL;
        }
<% end %>

        initialized = true;
        LOG(TRACE) + "C<%= $cur_module.name %> JNI init succeeded";
    }
    return env;
}
//----------------------------------------------------------------------------------------------------------------------

void C<%= $cur_module.name %>Base::setJavaFactory(JNIEnv* env, jobject jFactory)
{
    LOG(TRACE) + "setJavaFactory";

    env = jniInit(env);
    if (!env) {
        LOG(FATAL) + "JNI initialization failed";
        return;
    }

    env->CallStaticVoidMethod(s_clsFactorySingleton, s_midFactorySetInstance, jFactory);

    LOG(TRACE) + "setJavaFactory succeeded";
}
//----------------------------------------------------------------------------------------------------------------------
<% if $cur_module.is_template_default_instance %>
rho::String C<%= $cur_module.name %>Base::getDefaultID()
{
    LOG(TRACE) + "getDefaultID";

    JNIEnv *env = jniInit();
    if (!env) {
        LOG(FATAL) + "JNI initialization failed";
        return rho::String();
    }

    jhobject jhSingleton = getSingleton(env);
    jhstring res = static_cast<jstring>(env->CallObjectMethod(jhSingleton.get(), s_midGetDefaultID));
    return rho_cast<rho::String>(env, res);
}
//----------------------------------------------------------------------------------------------------------------------

void C<%= $cur_module.name %>Base::setDefaultID(const rho::String& id)
{
    LOG(TRACE) + "setDefaultID: " + id;

    JNIEnv *env = jniInit();
    if (!env) {
        LOG(FATAL) + "JNI initialization failed";
        return;
    }

    jhobject instance = getSingleton(env);
    jhstring jhId = rho_cast<jstring>(env, id);
    env->CallVoidMethod(instance.get(), s_midSetDefaultID, jhId.get());
}
//----------------------------------------------------------------------------------------------------------------------
<% end %>
jobject C<%= $cur_module.name %>Base::getFactory(JNIEnv* env)
{
    jobject res = env->CallStaticObjectMethod(s_clsFactorySingleton, s_midFactoryGetInstance);
    return res;
}
//----------------------------------------------------------------------------------------------------------------------

jobject C<%= $cur_module.name %>Base::getSingleton(JNIEnv* env)
{
    jhobject jhFactory = getFactory(env);
    jobject res = env->CallObjectMethod(jhFactory.get(), s_midGetApiSingleton);
    return res;
}
//----------------------------------------------------------------------------------------------------------------------

jobject C<%= $cur_module.name %>Base::getObject(JNIEnv* env)
{
    jhstring jhId = rho_cast<jstring>(env, m_id);
    jhobject jhFactory = getFactory(env);
    jobject res = env->CallObjectMethod(jhFactory.get(), s_midGetApiObject, jhId.get());
    return res;
}
//----------------------------------------------------------------------------------------------------------------------

<% $cur_module.parents.each do |parent| %>
}<%
end %>

repository: rhomobile/rhodes

repo_name: rhomobile/rhodes

gha_language: C


text:
package main

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

type createUserRequest struct {
	Name      string    `json:"name"`
	Email     string    `json:"email"`
	Attribute attribute `json:"attribute"`
}

type attribute struct {
	Birthday string `json:"birthday,omitempty"`
	Gender   string `json:"gender,omitempty"`
}

type createUserResponse struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

type userHandler struct {
}

type userProtoHandler struct {
}

func (h *userHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	if v := r.URL.Query().Get("token"); v != "12345" {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	var request createUserRequest
	decoder := json.NewDecoder(r.Body)
	if err := decoder.Decode(&request); err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// Some process...

	response := createUserResponse{
		ID:   11241988,
		Name: request.Name,
	}

	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json")

	encoder := json.NewEncoder(w)
	encoder.SetIndent("", " ")
	encoder.Encode(&response)
}

func (h *userProtoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	response := &UserProtoResponse{
		Id:     169743,
		Name:   "Immortan Joe",
		Active: true,
		Setting: &UserProtoResponse_Setting{
			Email: "immortan@madmax.com",
		},
	}
	buf, err := response.Marshal()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/protobuf")
	w.Write(buf)
}

repository: mercari/go-httpdoc

repo_name: mercari/go-httpdoc


text:
%% This BibTeX bibliography file in UTF-8 format was created using Papers.
%% http://mekentosj.com/papers/

@article{Shakura:1973p4854,
author = {N. I Shakura and R. A Sunyaev},
journal = {A{\&}A},
title = {Black holes in binary systems. Observational appearance.},
abstract = {Abstract image available at: http://adsabs.harvard.edu/abs/1973A{\&}A....24..337S},
pages = {337},
volume = {24},
year = {1973},
month = {Dec},
URL = {http://adsabs.harvard.edu/cgi-bin/nph-data_query?bibcode=1973A%2526A....24..337S&link_type=GIF},
}

gha_language: TeX


text:
// Copyright (c) 2014 - Max Ekman <max@looplab.se>
//
// 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 gcp

import (
	"context"
	"errors"
	"fmt"
	"log"
	"sync"
	"time"

	"cloud.google.com/go/pubsub"
	"google.golang.org/api/iterator"
	"gopkg.in/mgo.v2/bson"

	eh "github.com/looplab/eventhorizon"
)

// ErrCouldNotMarshalEvent is when an event could not be marshaled into BSON.
var ErrCouldNotMarshalEvent = errors.New("could not marshal event")

// ErrCouldNotUnmarshalEvent is when an event could not be unmarshaled into a concrete type.
var ErrCouldNotUnmarshalEvent = errors.New("could not unmarshal event")

// EventBus is an event bus that notifies registered EventHandlers of
// published events. It will use the SimpleEventHandlingStrategy by default.
type EventBus struct {
	handlers  map[eh.EventType]map[eh.EventHandler]bool
	observers map[eh.EventObserver]bool

	// handlerMu guards all maps at once for concurrent writes. No need for
	// separate mutexes per map for this as AddHandler/AddObserven is often
	// called at program init and not at run time.
	handlerMu sync.RWMutex

	// handlingStrategy is the strategy to use when handling event, for example
	// to handle the asynchronously.
	handlingStrategy eh.EventHandlingStrategy

	client *pubsub.Client
	topic  *pubsub.Topic
	ready  chan bool // NOTE: Used for testing only
	exit   chan bool
}

// NewEventBus creates a EventBus.
func NewEventBus(projectID, appID string) (*EventBus, error) {
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, err
	}

	// Get or create the topic.
	name := appID + "_events"
	topic := client.Topic(name)
	if ok, err := topic.Exists(ctx); err != nil {
		return nil, err
	} else if !ok {
		if topic, err = client.CreateTopic(ctx, name); err != nil {
			return nil, err
		}
	}

	b := &EventBus{
		handlers:  make(map[eh.EventType]map[eh.EventHandler]bool),
		observers: make(map[eh.EventObserver]bool),
		client:    client,
		topic:     topic,
		ready:     make(chan bool, 1), // Buffered to not block receive loop.
		exit:      make(chan bool),
	}

	go b.recv()

	return b, nil
}

// SetHandlingStrategy implements the SetHandlingStrategy method of the
// eventhorizon.EventBus interface.
func (b *EventBus) SetHandlingStrategy(strategy eh.EventHandlingStrategy) {
	b.handlingStrategy = strategy
}

// PublishEvent implements the PublishEvent method of the eventhorizon.EventBus interface.
func (b *EventBus) PublishEvent(ctx context.Context, event eh.Event) {
	b.handlerMu.RLock()
	defer b.handlerMu.RUnlock()

	// Handle the event if there is a handler registered.
	if handlers, ok := b.handlers[event.EventType()]; ok {
		for h := range handlers {
			if b.handlingStrategy == eh.AsyncEventHandlingStrategy {
				go h.HandleEvent(ctx, event)
			} else {
				h.HandleEvent(ctx, event)
			}
		}
	}

	// Notify all observers about the event.
	if err := b.notify(ctx, event); err != nil {
		log.Println("error: event bus publish:", err)
	}

}

// AddHandler implements the AddHandler method of the eventhorizon.EventBus interface.
func (b *EventBus) AddHandler(handler eh.EventHandler, eventType eh.EventType) {
	b.handlerMu.Lock()
	defer b.handlerMu.Unlock()

	// Create list for new event types.
	if _, ok := b.handlers[eventType]; !ok {
		b.handlers[eventType] = make(map[eh.EventHandler]bool)
	}

	// Add the handler for the event type.
	b.handlers[eventType][handler] = true
}

func (b *EventBus) handle(event eh.Event) {
}

// AddObserver implements the AddObserver method of the eventhorizon.EventBus interface.
func (b *EventBus) AddObserver(observer eh.EventObserver) {
	b.handlerMu.Lock()
	defer b.handlerMu.Unlock()

	b.observers[observer] = true
}

// Close exits the receive goroutine by unsubscribing to all channels.
func (b *EventBus) Close() error {
	select {
	case b.exit <- true:
	default:
		log.Println("eventbus: already closed")
	}
	<-b.exit

	return b.topic.Delete(context.Background())
}

func (b *EventBus) notify(ctx context.Context, event eh.Event) error {
	gcpEvent := gcpEvent{
		AggregateID:   event.AggregateID(),
		AggregateType: event.AggregateType(),
		EventType:     event.EventType(),
		Version:       event.Version(),
		Timestamp:     event.Timestamp(),
		Context:       eh.MarshalContext(ctx),
	}

	// Marshal event data if there is any.
	if event.Data() != nil {
		rawData, err := bson.Marshal(event.Data())
		if err != nil {
			return ErrCouldNotMarshalEvent
		}
		gcpEvent.RawData = bson.Raw{Kind: 3, Data: rawData}
	}

	// Marshal the event (using BSON for now).
	var data []byte
	var err error
	if data, err = bson.Marshal(gcpEvent); err != nil {
		return ErrCouldNotMarshalEvent
	}

	msgIDs, err := b.topic.Publish(context.Background(), &pubsub.Message{
		Data: data,
	})
	if err != nil {
		return err
	}

	// TODO: Use the message ID to avoid handling duplicate messages.
	_ = msgIDs

	return nil
}

func (b *EventBus) recv() {
	ctx := context.Background()

	// Create the subscription, it should not exist as we use a new UUID as name.
	id := "subscriber_" + eh.NewUUID().String()
	sub, err := b.client.CreateSubscription(ctx, id, b.topic, 10*time.Second, nil)
	if err != nil {
		// TODO: Handle error.
		log.Println("could not create subscription:", err)
		return
	}

	log.Println("eventbus: start receiving")
	go func() {
		<-b.exit
		if err := sub.Delete(ctx); err != nil {
			log.Println("eventbus: could not delete subscription:", err)
		}
		log.Println("eventbus: stop receiving")
		close(b.exit)
	}()

	// Don't block if no one is receiving and buffer is full.
	select {
	case b.ready <- true:
	default:
	}

	it, err := sub.Pull(ctx)
	if err != nil {
		// TODO: Handle error.
		log.Println("could not pull messages:", err)
	}
	defer it.Stop()

	for {
		msg, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
			log.Println("could not get next message:", err)
			break
		}

		b.handleMessage(msg)
	}
}

func (b *EventBus) handleMessage(msg *pubsub.Message) {
	// TODO: Only ack true when event is handled correctly.
	defer msg.Done(true)

	// Manually decode the raw BSON event.
	data := bson.Raw{
		Kind: 3,
		Data: msg.Data,
	}
	var gcpEvent gcpEvent
	if err := data.Unmarshal(&gcpEvent); err != nil {
		log.Println("error: event bus receive:", ErrCouldNotUnmarshalEvent)
		return
	}

	// Create an event of the correct type.
	if data, err := eh.CreateEventData(gcpEvent.EventType); err == nil {
		// Manually decode the raw BSON event.
		if err := gcpEvent.RawData.Unmarshal(data); err != nil {
			log.Println("error: event bus receive:", ErrCouldNotUnmarshalEvent)
			return
		}

		// Set concrete event and zero out the decoded event.
		gcpEvent.data = data
		gcpEvent.RawData = bson.Raw{}
	}

	event := event{gcpEvent: gcpEvent}
	ctx := eh.UnmarshalContext(gcpEvent.Context)

	b.handlerMu.RLock()
	defer b.handlerMu.RUnlock()

	// Notify all observers about the event.
	for o := range b.observers {
		if b.handlingStrategy == eh.AsyncEventHandlingStrategy {
			go o.Notify(ctx, event)
		} else {
			o.Notify(ctx, event)
		}
	}
}

// gcpEvent is the internal event used with the gcp event bus.
type gcpEvent struct {
	EventType     eh.EventType           `bson:"event_type"`
	RawData       bson.Raw               `bson:"data,omitempty"`
	data          eh.EventData           `bson:"-"`
	Timestamp     time.Time              `bson:"timestamp"`
	AggregateType eh.AggregateType       `bson:"aggregate_type"`
	AggregateID   eh.UUID                `bson:"_id"`
	Version       int                    `bson:"version"`
	Context       map[string]interface{} `bson:"context"`
}

// event is the private implementation of the eventhorizon.Event interface
// for a MongoDB event store.
type event struct {
	gcpEvent
}

// EventType implements the EventType method of the eventhorizon.Event interface.
func (e event) EventType() eh.EventType {
	return e.gcpEvent.EventType
}

// Data implements the Data method of the eventhorizon.Event interface.
func (e event) Data() eh.EventData {
	return e.gcpEvent.data
}

// Timestamp implements the Timestamp method of the eventhorizon.Event interface.
func (e event) Timestamp() time.Time {
	return e.gcpEvent.Timestamp
}

// AggregateType implements the AggregateType method of the eventhorizon.Event interface.
func (e event) AggregateType() eh.AggregateType {
	return e.gcpEvent.AggregateType
}

// AggrgateID implements the AggrgateID method of the eventhorizon.Event interface.
func (e event) AggregateID() eh.UUID {
	return e.gcpEvent.AggregateID
}

// Version implements the Version method of the eventhorizon.Event interface.
func (e event) Version() int {
	return e.gcpEvent.Version
}

// String implements the String method of the eventhorizon.Event interface.
func (e event) String() string {
	return fmt.Sprintf("%s@%d", e.gcpEvent.EventType, e.gcpEvent.Version)
}

repository: cddaiwei/eventhorizon

repo_name: cddaiwei/eventhorizon


text:
package main

import (
	"fmt"
	"sort"
)

func main() {
	fmt.Println("0" > "0")

	arr := []string{"1", "2", "12", "21"}
	sort.Slice(arr, func(i, j int) bool {
		if len(arr[i]) == len(arr[j]) {
			return arr[i] > arr[j]
		}
		return len(arr[i]) > len(arr[j])
	})
	fmt.Println(arr)
	fmt.Println(arr[2])
}

func kthLargestNumber(nums []string, k int) string {
	sort.Slice(nums, func(i, j int) bool {
		if len(nums[i]) == len(nums[j]) {
			return nums[i] > nums[j]
		}
		return len(nums[i]) > len(nums[j])
	})
	return nums[k-1]
}

repository: PseudoCowboy/streak-algorithm

repo_name: PseudoCowboy/streak-algorithm


text:
//
// Copyright (C) 2021 IOTech Ltd
//
// SPDX-License-Identifier: Apache-2.0

package dtos

import (
	"testing"

	"github.com/edgexfoundry/go-mod-core-contracts/v2/models"

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

func TestFromProvisionWatcherModelToUpdateDTO(t *testing.T) {
	model := models.ProvisionWatcher{}
	dto := FromProvisionWatcherModelToUpdateDTO(model)
	assert.Equal(t, model.Id, *dto.Id)
	assert.Equal(t, model.Name, *dto.Name)
	assert.Equal(t, model.Labels, dto.Labels)
	assert.Nil(t, model.Identifiers, dto.Identifiers)
	assert.Nil(t, model.BlockingIdentifiers, dto.BlockingIdentifiers)

	assert.Equal(t, model.DeviceNameTemplate, *dto.DeviceNameTemplate)
	assert.Equal(t, model.ProfileName, *dto.ProfileName)
	assert.Equal(t, model.ServiceName, *dto.ServiceName)
	assert.EqualValues(t, model.AdminState, *dto.AdminState)
	assert.EqualValues(t, model.ProtocolName, *dto.ProtocolName)
	assert.EqualValues(t, model.DeviceDescription, *dto.DeviceDescription)

	assert.Equal(t, model.ProfileNameTemplate, *dto.ProfileNameTemplate)
	assert.Equal(t, model.ProfileLabels, dto.ProfileLabels)
	assert.Equal(t, model.ProfileDescription, *dto.ProfileDescription)
}

repository: IOTechSystems/go-mod-core-contracts

repo_name: IOTechSystems/go-mod-core-contracts


text:
@article{li2021wireless,
 author = {Li, Danyang and Xu, Jingao and Yang, Zheng and Wu, Chenshu and Li, Jianbo and Lane, Nicholas D},
 journal = {ACM Transactions on Sensor Networks (TOSN)},
 number = {1},
 pages = {1--23},
 publisher = {ACM New York, NY},
 title = {Wireless Localization with Spatial-Temporal Robust Fingerprints},
 volume = {18},
 year = {2021}
}


text:
package accesstoken

import (
	"crypto/rsa"
	"time"

	jwt "github.com/dgrijalva/jwt-go"
	"github.com/go-gorp/gorp"

	"github.com/ovh/cds/engine/api/cache"
	"github.com/ovh/cds/sdk"
	"github.com/ovh/cds/sdk/log"
)

var (
	localIssuer string
	signingKey  *rsa.PrivateKey
	verifyKey   *rsa.PublicKey
)

// Init the package by passing the signing key
func Init(issuer string, k []byte) error {
	localIssuer = issuer
	var err error
	signingKey, err = jwt.ParseRSAPrivateKeyFromPEM(k)
	if err != nil {
		return sdk.WithStack(err)
	}
	verifyKey = &signingKey.PublicKey
	return nil
}

// OriginUI aims to discriminate JWT token associated with XSRF token or not
const OriginUI = "UI"

// New returns a new access token for a user
func New(u sdk.User, groups []sdk.Group, origin, desc string, expiration time.Time) (sdk.AccessToken, string, error) {
	var token sdk.AccessToken
	token.ID = sdk.UUID()
	token.Created = time.Now()
	token.ExpireAt = expiration
	token.Description = desc
	token.Origin = origin
	token.Status = sdk.AccessTokenStatusEnabled
	token.Groups = groups

	var tmpUser = u
	tmpUser.Auth = sdk.Auth{}
	tmpUser.Favorites = nil
	tmpUser.Groups = nil
	tmpUser.Permissions = sdk.UserPermissions{}
	token.User = tmpUser
	token.UserID = u.ID

	jwttoken, err := Regen(&token)
	if err != nil {
		return token, jwttoken, sdk.WithStack(err)
	}

	return token, jwttoken, nil
}

// Regen regenerate the signed token value
func Regen(token *sdk.AccessToken) (string, error) {
	claims := sdk.AccessTokenJWTClaims{
		ID:     token.ID,
		Groups: sdk.GroupsToIDs(token.Groups),
		StandardClaims: jwt.StandardClaims{
			Issuer:    localIssuer,
			Subject:   token.User.Username,
			Id:        token.ID,
			IssuedAt:  time.Now().Unix(),
			ExpiresAt: token.ExpireAt.Unix(),
		},
	}

	jwtToken := jwt.NewWithClaims(jwt.SigningMethodRS512, claims)
	ss, err := jwtToken.SignedString(signingKey)
	if err != nil {
		return "", sdk.WithStack(err)
	}

	return ss, nil
}

// IsValid checks a jwt token against all access_token
func IsValid(db gorp.SqlExecutor, jwtToken string) (sdk.AccessToken, bool, error) {
	var accessToken sdk.AccessToken

	token, err := VerifyToken(jwtToken)
	if err != nil {
		return accessToken, false, sdk.WrapError(err, "invalid token")
	}

	claims := token.Claims.(*sdk.AccessTokenJWTClaims)
	id := claims.StandardClaims.Id

	// Load the access token from the id read in the claim
	accessToken, err = FindByID(db, id)
	if err != nil {
		return accessToken, false, sdk.WrapError(sdk.ErrUnauthorized, "unable find access token %s: %v", id, err)
	}

	// Check groups from the claims againts the groups in the database
	ids := sdk.GroupsToIDs(accessToken.Groups)
	for _, groupID := range claims.Groups {
		if !sdk.IsInInt64Array(groupID, ids) {
			log.Debug("accesstoken.IsValid> token %s is invalid (group mismatch): %v", id, err)
			return accessToken, false, nil
		}
	}

	return accessToken, token != nil, nil
}

var _XSRFTokenDuration = 60 * 60 * 24 * 7 // 1 Week

// StoreXSRFToken generate and store a CSRF token for a given access_token
func StoreXSRFToken(store cache.Store, accessToken sdk.AccessToken) string {
	log.Debug("accesstoken.StoreXSRFToken")
	var xsrfToken = sdk.UUID()
	var k = cache.Key("token", "xsrf", accessToken.ID)
	store.SetWithTTL(k, &xsrfToken, _XSRFTokenDuration)
	return xsrfToken
}

// CheckXSRFToken checks a value "xsrfToken" against the access token CSRF generated by the API
func CheckXSRFToken(store cache.Store, accessToken sdk.AccessToken, xsrfToken string) bool {
	log.Debug("accesstoken.CheckXSRFToken")
	var expectedXSRFfToken string
	var k = cache.Key("token", "xsrf", accessToken.ID)
	if store.Get(k, &expectedXSRFfToken) {
		return expectedXSRFfToken == xsrfToken
	}
	return false
}

// VerifyToken checks token technical validity
func VerifyToken(jwtToken string) (*jwt.Token, error) {
	token, err := jwt.ParseWithClaims(jwtToken, &sdk.AccessTokenJWTClaims{},
		func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, sdk.NewErrorFrom(sdk.ErrUnauthorized, "Unexpected signing method: %v", token.Header["alg"])
			}
			return verifyKey, nil
		})

	if err != nil {
		return nil, sdk.WithStack(err)
	}

	if claims, ok := token.Claims.(*sdk.AccessTokenJWTClaims); ok && token.Valid {
		log.Debug("Token isValid %v %v", claims.Issuer, claims.StandardClaims.ExpiresAt)
	} else {
		return nil, sdk.ErrUnauthorized
	}

	return token, nil
}

repository: Laymer/cds

repo_name: Laymer/cds


text:
// Copyright 2011 Arne Vansteenkiste (barnex@gmail.com).  All rights reserved.
// Use of this source code is governed by a freeBSD
// license that can be found in the LICENSE.txt file.

package runtime

// This file implements CUDA streams

//#include <cuda_runtime.h>
import "C"
import "unsafe"

import ()

type Stream uintptr

// The default stream
const STREAM0 Stream = 0

// Creates an asynchronous stream
func StreamCreate() Stream {
	var stream C.cudaStream_t
	err := Error(C.cudaStreamCreate(&stream))
	if err != Success {
		panic(err)
	}
	return Stream(unsafe.Pointer(stream))
}

// Destroys an asynchronous stream
func StreamDestroy(stream Stream) {
	err := Error(C.cudaStreamDestroy(C.cudaStream_t(unsafe.Pointer(stream))))
	if err != Success {
		panic(err)
	}
}

// Destroys an asynchronous stream
func (s *Stream) Destroy() {
	StreamDestroy(*s)
	*s = 0
}

// Returns Success if all operations have completed, ErrorNotReady otherwise
func StreamQuery(stream Stream) Error {
	return Error(C.cudaStreamQuery(C.cudaStream_t(unsafe.Pointer(stream))))
}

// Returns Success if all operations have completed, ErrorNotReady otherwise
func (s Stream) Query() Error {
	return StreamQuery(s)
}

// Blocks until the stream has completed.
func StreamSynchronize(stream Stream) {
	err := Error(C.cudaStreamSynchronize(C.cudaStream_t(unsafe.Pointer(stream))))
	if err != Success {
		panic(err)
	}
}

// Blocks until the stream has completed.
func (s Stream) Synchronize() {
	err := Error(C.cudaStreamSynchronize(C.cudaStream_t(unsafe.Pointer(s))))
	if err != Success {
		panic(err)
	}
}


text:
WRAP_CLASS("itk::TriangleMeshToSimplexMeshFilter")

  WRAP_INCLUDE_TYPE("itkDefaultStaticMeshTraits.h")
  WRAP_INCLUDE_TYPE("itkDefaultDynamicMeshTraits.h")

  SET(MANAGED_TYPE_TEMPLATE ${MANAGED_ITK_SOURCE_COMMON_PATH}/itkManagedMeshToMeshFilter_TYPE.cxx.in)
  SET(MANAGED_WRAPPER_TEMPLATE ${MANAGED_ITK_SOURCE_COMMON_PATH}/itkManagedMeshToMeshFilter_WRAPPER.cxx.in)

  FOREACH(d "3")
    FOREACH(m ${WRAP_ITK_MESH_PIXELS})
      WRAP_TEMPLATE("${ITKM_M${m}${d}S}${ITKM_SM${m}${d}S}"  "${ITKT_M${m}${d}S},${ITKT_SM${m}${d}S}")
      WRAP_TEMPLATE("${ITKM_M${m}${d}D}${ITKM_SM${m}${d}D}"  "${ITKT_M${m}${d}D},${ITKT_SM${m}${d}D}")
    ENDFOREACH(m)
  ENDFOREACH(d)

END_WRAP_CLASS()

repository: amirsalah/manageditk

repo_name: amirsalah/manageditk


text:
SUMMARY = "Node Manager Proxy"
DESCRIPTION = "The Node Manager Proxy provides a simple interface for communicating \
with Management Engine via IPMB"

SRC_URI = "git://git@github.com/Intel-BMC/node-manager.git;protocol=ssh"
SRCREV = "9aca80fa2a405938de99aae777e6cfcf08525563"
PV = "0.1+git${SRCPV}"

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

SYSTEMD_SERVICE:${PN} = "node-manager-proxy.service"

DEPENDS = "sdbusplus \
           phosphor-logging \
           boost"

S = "${WORKDIR}/git"
inherit cmake systemd

repository: Intel-BMC/openbmc

repo_name: Intel-BMC/openbmc


text:
package misc

import (
	"testing"

	"github.com/heedy/pipescript"
)

func TestDistance(t *testing.T) {
	Register()
	pipescript.TestCase{
		Pipescript: "distance(40.424454, -86.911356)",
		Input: []pipescript.Datapoint{
			{Timestamp: 1, Data: map[string]interface{}{"latitude": 40.424095, "longitude": -86.907388}},
			{Timestamp: 2, Data: map[string]interface{}{"latitude": 40.425353, "longitude": -86.913997}},
		},
		Output: []pipescript.Datapoint{
			{Timestamp: 1, Data: float64(338.24967084131407)},
			{Timestamp: 2, Data: float64(244.88709902527467)},
		},
	}.Run(t)
}

repository: heedy/pipescript

repo_name: heedy/pipescript


text:
#include <henson/chai/puppet.hpp>

#include <henson/command-line.hpp>
#include <henson/puppet.hpp>
#ifdef HENSON_PYTHON
#include <henson/python-puppet.hpp>
#endif
namespace h = henson;

#include <string>
#include <memory>
#include <spdlog/spdlog.h>
namespace spd = spdlog;
extern std::string active_puppet;
extern std::shared_ptr<spd::logger> logger;

void chai_puppet(chaiscript::ChaiScript& chai, henson::NameMap& namemap, std::string script_prefix)
{
    // BaseCoroutine
    chai.add(chaiscript::user_type<h::BaseCoroutine>(), "BaseCoroutine");
    chai.add(chaiscript::fun(&h::BaseCoroutine::running),      "running");
    chai.add(chaiscript::fun(&h::BaseCoroutine::signal_stop),  "signal_stop");
    chai.add(chaiscript::fun(&h::BaseCoroutine::total_time),   "total_time");
    chai.add(chaiscript::fun(&h::BaseCoroutine::name),         "name");

    // Puppet
    chai.add(chaiscript::base_class<h::BaseCoroutine, h::Puppet>());
    chai.add(chaiscript::user_type<h::Puppet>(),        "Puppet");
    chai.add(chaiscript::fun([](h::Puppet& puppet)
    {
        active_puppet = puppet.name();
        logger->debug("Proceeding with {}", puppet.name());
        puppet.proceed();
        return puppet.running();
    }), "proceed");

    chai.add(chaiscript::fun([&namemap,script_prefix](std::string cmd_line_str, henson::ProcMap* pm)
    {
        auto cmd_line = h::CommandLine(cmd_line_str);
        return std::make_shared<h::Puppet>(cmd_line.executable(script_prefix),
                                           cmd_line.argv.size(),
                                           &cmd_line.argv[0],
                                           pm,
                                           &namemap);
    }), "load");

#ifdef HENSON_PYTHON
    // PythonPuppet
    chai.add(chaiscript::base_class<h::BaseCoroutine, h::PythonPuppet>());
    chai.add(chaiscript::user_type<h::PythonPuppet>(),  "PythonPuppet");
    chai.add(chaiscript::fun([](h::PythonPuppet& puppet)
    {
        active_puppet = puppet.name();
        logger->debug("Proceeding with {}", puppet.name());
        puppet.proceed();
        return puppet.running();
    }), "proceed");
    chai.add(chaiscript::fun([&namemap,script_prefix](std::string python_cmd_line_str, henson::ProcMap* pm)
    {
        auto cmd_line = h::CommandLine(python_cmd_line_str);
        return std::make_shared<h::PythonPuppet>(cmd_line.executable(script_prefix), cmd_line.argv, pm, &namemap);
    }), "python");
#endif
}

repository: mrzv/henson

repo_name: mrzv/henson


text:
SUMMARY = "libpldm_intel"
DESCRIPTION = "Provides encode/decode APIs for PLDM specifications"

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

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

PV = "1.0+git${SRCPV}"

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

inherit cmake

DEPENDS += " \
    gtest \
    "

branch_name: refs/heads/intel


text:
package api

import (
	"errors"
	"net/http"
	"net/url"
	"socialapi/models"
	"socialapi/request"
	"socialapi/workers/common/handler"
	"socialapi/workers/common/mux"
	"socialapi/workers/common/response"
	"socialapi/workers/helper"
	"socialapi/workers/presence"
	"time"

	"github.com/koding/bongo"
)

// AddHandlers added the internal handlers to the given Muxer
func AddHandlers(m *mux.Mux) {
	httpRateLimiter := helper.NewDefaultRateLimiter()

	m.AddHandler(
		handler.Request{
			Handler:   Ping,
			Name:      "presence-ping",
			Type:      handler.GetRequest,
			Endpoint:  presence.EndpointPresencePing,
			Ratelimit: httpRateLimiter,
		},
	)
	m.AddHandler(
		handler.Request{
			Handler:   ListMembers,
			Name:      "presence-listmembers",
			Type:      handler.GetRequest,
			Endpoint:  presence.EndpointPresenceListMembers,
			Ratelimit: httpRateLimiter,
		},
	)
	m.AddHandler(
		handler.Request{
			Handler:   HandlePrivatePing,
			Name:      "presence-ping-private",
			Type:      handler.PostRequest,
			Endpoint:  presence.EndpointPresencePingPrivate,
			Ratelimit: httpRateLimiter,
		},
	)
}

// ListMembers lists the members of group
func ListMembers(u *url.URL, h http.Header, _ interface{}, context *models.Context) (int, http.Header, interface{}, error) {
	if err := context.IsGroupAdmin(); err != nil {
		return response.NewBadRequest(err)
	}

	query := request.GetQuery(u)
	query = context.OverrideQuery(query)
	p := &models.PresenceDaily{}
	return response.HandleResultAndError(p.FetchActiveAccounts(query))
}

// Ping handles the pings coming from client side
func Ping(u *url.URL, h http.Header, _ interface{}, context *models.Context) (int, http.Header, interface{}, error) {
	// only logged in users can send a ping
	if !context.IsLoggedIn() {
		return response.NewBadRequest(models.ErrNotLoggedIn)
	}

	req := &presence.Ping{
		GroupName: context.GroupName,
		AccountID: context.Client.Account.Id, // if client is logged in, those values are all set
	}

	return handlePing(u, h, req)
}

// HandlePrivatePing handles the pings coming from internal services
func HandlePrivatePing(u *url.URL, h http.Header, req *presence.PrivatePing) (int, http.Header, interface{}, error) {
	if req == nil {
		return response.NewBadRequest(errors.New("req should be set"))
	}

	if req.Username == "" {
		return response.NewBadRequest(errors.New("username should be set"))
	}

	acc, err := models.Cache.Account.ByNick(req.Username)
	if err != nil {
		return response.NewBadRequest(err)
	}

	ping := &presence.Ping{
		GroupName: req.GroupName,
		AccountID: acc.Id, // if client is logged in, those values are all set
	}

	return handlePing(u, h, ping)
}

// handlePing handles the pings coming from anywhere
func handlePing(u *url.URL, h http.Header, req *presence.Ping) (int, http.Header, interface{}, error) {
	if req == nil {
		return response.NewBadRequest(errors.New("req should be set"))
	}
	if req.GroupName == "" {
		return response.NewBadRequest(errors.New("groupName should be set"))
	}

	if req.AccountID == 0 {
		return response.NewBadRequest(errors.New("accountId should be set"))
	}

	req.CreatedAt = time.Now().UTC()

	// send the ping request to the related worker
	if err := bongo.B.PublishEvent(presence.EventName, req); err != nil {
		return response.NewBadRequest(err)
	}

	return response.NewDefaultOK()
}

repository: dizag/koding

repo_name: dizag/koding


text:
package megacode

import "fmt"

// Encode encodes a MegaCode identifier to a bitstream of simple 0s and 1s.
// ID must be < 2**24, and the high bit must be set.
func Encode(ID uint32) ([]byte, error) {
	return nil, fmt.Errorf("not implemented yet")
}


text:
require recipes-multimedia/gstreamer/gst-plugins.inc

LICENSE = "GPLv2+ & LGPLv2.1+"
LIC_FILES_CHKSUM = "file://COPYING;md5=a6f89e2100d9b6cdffcea4f398e37343 \
                    file://common/coverage/coverage-report.pl;beginline=2;endline=17;md5=622921ffad8cb18ab906c56052788a3f"

DEPENDS += "gst-plugins-base libid3tag libmad mpeg2dec liba52 lame libcdio opencore-amr"

EXTRA_OECONF += "--enable-orc"

PR = "r3"
GIT_PV = ""

SRCREV = "9afc696e5fa9fb980e02df5637f022796763216f"

inherit autotools pkgconfig gettext git-project

SRC_URI = "git://anongit.freedesktop.org/gstreamer/${PN}"

SRC_URI += " \
	file://orc.m4-fix-location-of-orcc-when-cross-compiling.patch \
"

do_common_update() {
	cd ${S}
	# Make sure we have common
	if test ! -f common/gst-autogen.sh;
	then
	  echo "+ Setting up common submodule"
	  git submodule init
	fi
	git submodule update

	# source helper functions
	if test ! -f common/gst-autogen.sh;
	then
	  echo There is something wrong with your source tree.
	  echo You are missing common/gst-autogen.sh
	  exit 1
	fi
	. common/gst-autogen.sh
	# install pre-commit hook for doing clean commits
	if test ! \( -x .git/hooks/pre-commit -a -L .git/hooks/pre-commit \);
	then
	    rm -f .git/hooks/pre-commit
	    ln -s ../../common/hooks/pre-commit.hook .git/hooks/pre-commit
	fi

	# GNU gettext automake support doesn't get along with git.
	# https://bugzilla.gnome.org/show_bug.cgi?id=661128
	autopoint || touch config.rpath
	touch -t 200001010000 po/gst-plugins-base-0.10.pot
}
addtask common_update after do_unpack before do_patch

do_configure_prepend() {
	# This m4 file contains nastiness which conflicts with libtool 2.2.2
	rm ${S}/m4/lib-link.m4 || true
}

require mips-only.inc

repository: kiyala/op

repo_name: kiyala/op


text:
require live555.inc

PR = "${INC_PR}.0"

SRC_URI[md5sum] = "8e5ebefdf7d12ca9cfd7175ff3d7eef2"
SRC_URI[sha256sum] = "695cf22d43516f082e26ee9eb8373a0ae3b4ed472f1e224b51d881219f694f2e"

repository: mrchapp/arago-oe-dev

repo_name: mrchapp/arago-oe-dev


text:
find_path(AVFORMAT_INCLUDE_DIR
  NAMES libavformat/avformat.h)

find_library(AVFORMAT_LIBRARY
  NAMES avformat)

set(AVFORMAT_LIBRARIES ${AVFORMAT_LIBRARY})
set(AVFORMAT_INCLUDE_DIRS ${AVFORMAT_INCLUDE_DIR})

include(FindPackageHandleStandardArgs)

find_package_handle_standard_args(AVFORMAT DEFAULT_MSG AVFORMAT_LIBRARY AVFORMAT_INCLUDE_DIR)


text:
LICENSE = "GPL"
SECTION = "libs"
PR = "r1"

DEPENDS= "libxml2 glib-2.0 zlib gtk-doc libbonobo gnome-vfs"
RDEPENDS = "gconf gnome-vfs"

PACKAGES =+ "${PN}-gnome ${PN}-gnome-dev "

FILES_${PN}-gnome = "${libdir}/libgsf-gnome-1.so.*"
FILES_${PN}-gnome-dev = "${libdir}/libgsf-gnome-1.* ${includedir}/libgsf-1/gsf-gnome"

inherit autotools pkgconfig gnome

do_stage() {
autotools_stage_all
}