doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
bfdff3ce-0fab-42ec-be5d-f44b1ef9372a
{ "language": "BitBake" }
```bitbake ``` Use this to compile full image and produce extra-packages
```bitbake # Creates the "feed", packages not required for the image # but that should be built for the feed so that other # components may use them and install on demand. require blackpole-image.bb DEPENDS += "${OPTIONAL_PACKAGES}" ```
cb158fd2-fb89-45e9-b031-e32b83386a59
{ "language": "BitBake" }
```bitbake ``` Add debug image with no modules for kernel dev work
```bitbake DESCRIPTION = "A console kernel development image, no modules" LICENSE = "MIT" IMAGE_FEATURES += "package-management" IMAGE_LINGUAS = "en-us" inherit core-image CORE_OS = " \ busybox-hwclock \ task-core-ssh-openssh openssh-keygen \ term-prompt \ tzdata \ " DEV_SDK_INSTALL = " \ binutils \ binutils-symlinks \ coreutils \ cpp \ cpp-symlinks \ diffutils \ file \ gcc \ gcc-symlinks \ g++ \ g++-symlinks \ gettext \ git \ ldd \ libstdc++ \ libstdc++-dev \ libtool \ make \ pkgconfig \ " EXTRA_TOOLS_INSTALL = " \ bzip2 \ ethtool \ findutils \ i2c-tools \ iftop \ iperf \ htop \ less \ procps \ sysfsutils \ tcpdump \ unzip \ wget \ zip \ " IMAGE_INSTALL += " \ ${CORE_OS} \ ${DEV_SDK_INSTALL} \ ${EXTRA_TOOLS_INSTALL} \ " set_local_timezone() { ln -sf /usr/share/zoneinfo/EST5EDT ${IMAGE_ROOTFS}/etc/localtime } disable_bootlogd() { echo BOOTLOGD_ENABLE=no > ${IMAGE_ROOTFS}/etc/default/bootlogd } ROOTFS_POSTPROCESS_COMMAND += " \ set_local_timezone ; \ disable_bootlogd ; \ " export IMAGE_BASENAME = "duovero-debug-image" ```
f33adcbe-8547-49e8-8a6d-880bde3f74ef
{ "language": "BitBake" }
```bitbake ``` Update libao to latest version
```bitbake LICENSE = "GPL" DESCRIPTION = "A cross platform audio library" HOMEPAGE = "http://www.xiph.org/ao/" SECTION = "libs" PRIORITY = "optional" PR = "r0" SRC_URI = "http://www.xiph.org/ao/src/libao-${PV}.tar.gz" inherit autotools pkgconfig EXTRA_OECONF = "--disable-esd --disable-esdtest \ --disable-alsa --disable-alsa09 \ --disable-arts --disable-nas" do_stage() { install -d ${STAGING_INCDIR}/ao install -m 0644 ${S}/include/ao/ao.h ${S}/include/ao/os_types.h \ ${S}/include/ao/plugin.h ${STAGING_INCDIR}/ao/ oe_libinstall -so -C src libao ${STAGING_LIBDIR} install -d ${STAGING_DATADIR}/aclocal install -m 0644 ao.m4 ${STAGING_DATADIR}/aclocal/ } FILES_${PN} += "${libdir}/ao/plugins-2/*.so" ```
90b4f6fa-2a9f-471b-a919-b3945978ad19
{ "language": "BitBake" }
```bitbake ``` Add recipe for xapian-core package
```bitbake SUMMARY = "This package contains the core Xapian runtime library" DESCRIPTION = "\ The Xapian search engine library is a highly adaptable toolkit which allows \ developers to easily add advanced indexing and search facilities to their own \ applications. It implements the probabilistic model of information retrieval, \ and provides facilities for performing ranked free-text searches, relevance \ eedback, phrase searching, boolean searching, stemming, and simultaneous \ pdate and searching. It is highly scalable, and is capable of working with \ collections containing hundreds of millions of documents. \ " HOMEPAGE = "http://xapian.org/" PR = "r0" inherit debian-package LICENSE = "GPLv2+" LIC_FILES_CHKSUM = "\ file://COPYING;md5=4325afd396febcb659c36b49533135d4" inherit autotools #install follow Debian jessie do_install_append() { install -d ${D}${libdir}/xapian-examples/examples mv ${D}${bindir}/simple* ${D}${libdir}/xapian-examples/examples/ } PACKAGES =+ "libxapian22 xapian-examples" DEBIANNAME_${PN} = "xapian-tools" DEBIANNAME_${PN}-dev = "libxapian-dev" DEBIANNAME_${PN}-doc = "xapian-doc" DEBIANNAME_${PN}-dbg = "libxapian22-dbg" FILES_libxapian22 = "${libdir}/libxapian.so.*" FILES_xapian-examples = "${libdir}/xapian-examples/examples/simple*" FILES_${PN}-dev += "${libdir}/cmake/xapian/* ${bindir}/xapian-config" FILES_${PN}-dbg += "${libdir}/xapian-examples/examples/.debug/*" #follow debian/control RDEPENDS_libxapian-dev += "libxapian22 libc6-dev" RDEPENDS_xapian-tools += "libxapian22" ```
54c3e293-c56e-47c3-9255-c3d9289c8c8b
{ "language": "BitBake" }
```bitbake MAINTAINER = "Koen Kooi <Koen@dominion.kabel.utwente.nl>" HOMEPAGE = "http://tapioca-voip.sourceforge.net/wiki/index.php/Tapioca" LICENSE = "LGPL" DEPENDS = "gtk+ glib-2.0 dbus gconf tapioca-xmpp tapioca farsight gst-plugins-farsight" inherit autotools pkgconfig SRC_URI = "${SOURCEFORGE_MIRROR}/tapioca-voip/${P}.tar.gz" FILES_${PN} += "${datadir}/dbus*" ``` Add missing RDEPENDS to tapioca-xmpp.
```bitbake MAINTAINER = "Koen Kooi <Koen@dominion.kabel.utwente.nl>" HOMEPAGE = "http://tapioca-voip.sourceforge.net/wiki/index.php/Tapioca" LICENSE = "LGPL" DEPENDS = "gtk+ glib-2.0 dbus gconf tapioca-xmpp tapioca farsight gst-plugins-farsight" RDEPENDS = "tapioca-xmpp" PR = "r1" inherit autotools pkgconfig SRC_URI = "${SOURCEFORGE_MIRROR}/tapioca-voip/${P}.tar.gz" FILES_${PN} += "${datadir}/dbus*" ```
eaa4b644-db08-41c5-bd70-64a8fcd7be9e
{ "language": "BitBake" }
```bitbake ``` Add recipe for insserv package
```bitbake # # base recipe: http://cgit.openembedded.org/cgit.cgi/openembedded-core/tree/meta/\ # recipes-devtools/insserv/insserv_1.14.0.bb?h=fido # base branch: fido # base commit: f0873b83d693af4a103999160d67fcf25c7eedc1 # SUMMARY = "Boot sequence organizer using LSB init.d dependencies" DESCRIPTION = "This utility reorders the init.d boot scripts based on \ dependencies agiven in scripts'LSB comment headers, or in override files \ included in this package or added in /etc/insserv." # There is no known home page for insserv LICENSE = "GPLv2" LIC_FILES_CHKSUM = "file://COPYING;md5=751419260aa954499f7abaabaa882bbe" PR = "r0" inherit debian-package #Add option -D-GNU_SOURCE: The O_NOATIME variable in insserv.c \ #is depends on __USE_GNU and __USE_GNU depends on _GNU_SOURCE CFLAGS += " -D_GNU_SOURCE" do_install () { oe_runmake 'DESTDIR=${D}' install install -m0644 ${S}/insserv.conf ${D}${sysconfdir}/insserv.conf #Create /etc/bash_completion.d folder install -d ${D}${sysconfdir}/bash_completion.d chmod 0755 ${D}${sysconfdir}/bash_completion.d #Install /etc/bash_completion.d/insserv install -m 0644 ${S}/debian/insserv.bash-completion \ ${D}${sysconfdir}/bash_completion.d/insserv } ```
1cdecde8-c9a4-44c9-a71e-d85b2d1a0d26
{ "language": "BitBake" }
```bitbake ``` Add recipe for libyaml package
```bitbake SUMMARY = "Fast YAML 1.1 parser and emitter library" DESCRIPTION = "LibYAML is a C library for parsing and emitting data in YAML 1.1, a \ human-readable data serialization format." HOMEPAGE = "http://pyyaml.org/wiki/LibYAML" PR = "r0" inherit debian-package LICENSE = "MIT" LIC_FILES_CHKSUM = "file://LICENSE;md5=6015f088759b10e0bc2bf64898d4ae17" inherit autotools DEBIAN_NOAUTONAME_${PN}-dev = "1" ```
9c59103e-ebf4-4937-99d3-86850cf3932b
{ "language": "BitBake" }
```bitbake ``` Add recipe for dsh package
```bitbake SUMMARY = "dancer's shell, or distributed shell" DESCRIPTION = "\ Executes specified command on a group of computers using remote shell \ methods such as rsh or ssh. \ dsh can parallelise job submission using several algorithms, such as using \ fan-out method or opening as much connections as possible, or using a window \ of connections at one time.It also supports 'interactive mode' for interactive\ maintenance of remote hosts." PR = "r0" inherit debian-package LICENSE = "GPLv2+" LIC_FILES_CHKSUM = "file://COPYING;md5=94d55d512a9ba36caa9b7df079bae19f" inherit autotools-brokensep gettext pkgconfig DEBIAN_PATCH_TYPE = "nopatch" DEPENDS += "libdshconfig" EXTRA_OECONF += "--sysconfdir=/etc/dsh --mandir=/usr/share/man" #install follow Debian jessie do_install_append() { install -d ${D}${libdir}/update-cluster install -d ${D}${sysconfdir}/${PN}/group install -d ${D}${datadir}/locale/ja/LC_MESSAGES/ install -m 0644 ${S}/debian/machines.list ${D}${sysconfdir}/${PN}/ ln -s ../machines.list ${D}${sysconfdir}/${PN}/group/all install -m 0755 ${S}/debian/dsh.updatelist ${D}${libdir}/update-cluster/ install -m 0644 ${S}/po/ja.gmo ${D}${datadir}/locale/ja/LC_MESSAGES/dsh.mo } FILES_${PN} += "${libdir}/* ${datadir}/locale/*" ```
29767c4a-23bc-4bd9-8ddc-04eb0f41bb05
{ "language": "BitBake" }
```bitbake DESCRIPTION = "Evince is simply a document viewer" LICENSE = "GPL" DEPENDS = "tiff espgs poppler gtk+ libgnomeui libgnomeprint libgnomeprintui" RDEPENDS = "espgs gconf" RRECOMMENDS = "gnome-vfs-plugin-file" PR = "r0" inherit gnome pkgconfig SRC_URI = "http://ftp.gnome.org/pub/GNOME/sources/evince/0.5/${PN}-${PV}.tar.bz2 \ file://more-no-doc.patch;patch=1" EXTRA_OECONF = "--disable-tiff" ``` Add SECTION. Make DESCRIPTION more useful.
```bitbake DESCRIPTION = "Evince is a document viewer for document formats like pdf, ps, djvu." LICENSE = "GPL" SECTION = "x11/office" DEPENDS = "tiff espgs poppler gtk+ libgnomeui libgnomeprint libgnomeprintui" RDEPENDS = "espgs gconf" RRECOMMENDS = "gnome-vfs-plugin-file" PR = "r1" inherit gnome pkgconfig SRC_URI = "http://ftp.gnome.org/pub/GNOME/sources/evince/0.5/${PN}-${PV}.tar.bz2 \ file://more-no-doc.patch;patch=1" EXTRA_OECONF = "--disable-tiff" ```
8100867e-ee1f-4342-8220-04cbd1cf7b5f
{ "language": "BitBake" }
```bitbake ``` Add python library pamela which supports PAM
```bitbake DESCRIPTION = "Pamela: yet another Python wrapper for PAM" LICENSE = "MIT" LIC_FILES_CHKSUM = "file://PKG-INFO;md5=bfb663f37eb99232bc8ccfa4ea8f1202" SRC_URI[md5sum] = "de6516118d51eb5fc97017f3b6d5c68b" SRC_URI[sha256sum] = "1e198446a6cdd87704aa0def7621d62e7c20b0e6068e2788b9a866a8355e5d6b" PYPI_PACKAGE = "pamela" inherit pypi setuptools RDEPENDS_${PN} = "libpam" inherit distro_features_check REQUIRED_DISTRO_FEATURES = "pam" ```
ba1c4b5a-c7a1-4c05-af9c-000bff9a3229
{ "language": "BitBake" }
```bitbake ``` Add recipe for compiling clk_wiz driver
```bitbake inherit features_check REQUIRED_DISTRO_FEATURES = "clk-wiz" inherit esw python3native DEPENDS += "xilstandalone" ESW_COMPONENT_SRC = "/XilinxProcessorIPLib/drivers/clk_wiz/src/" ESW_COMPONENT_NAME = "libclk_wiz.a" addtask do_generate_driver_data before do_configure after do_prepare_recipe_sysroot do_prepare_recipe_sysroot[rdeptask] = "do_unpack" ```
f21ee2a6-cb39-4e26-b06a-e6698cd9b83e
{ "language": "BitBake" }
```bitbake ``` Add recipe for psmisc package
```bitbake # # base recipe: /meta/recipes-extended/psmisc/psmisc_22.21.bb # base branch: master # base commit: e335d9519c883165e70cda5c1fde348391686e31 # SUMMARY = "Utilities for managing processes on your system" DESCRIPTION = "The psmisc package contains utilities for managing processes \ on your system: pstree, killall and fuser. The pstree command displays a \ tree structure of all of the running processes on your system. The killall \ command sends a specified signal (SIGTERM if nothing is specified) to \ processes identified by name. The fuser command identifies the PIDs \ of processes that are using specified files or filesystems." HOMEPAGE = "http://psmisc.sf.net/" PR = "r0" inherit debian-package LICENSE = "GPLv2+" LIC_FILES_CHKSUM = "file://COPYING;md5=0636e73ff0215e8d672dc4c32c317bb3" inherit autotools gettext #Move /usr/bin/fuser file to /bin/ folder do_install_append () { install -d ${D}${base_bindir} mv ${D}${bindir}/fuser ${D}${base_bindir}/fuser } FILES_${PN} += "${base_bindir}/fuser" ```
f613eac3-81d9-4da8-9378-72115f0fcac3
{ "language": "BitBake" }
```bitbake ``` Add recipe for tftp-hpa package
```bitbake # # base recipe: http://cgit.openembedded.org/cgit.cgi/meta-openembedded/tree/\ # meta-networking/recipes-daemons/tftp-hpa/tftp-hpa_5.2.bb? # base branch: master # base commit: 98842e4e9f53f5f8614dd583dde9f5e898aadbb2 # SUMMARY = "Client for the Trivial File Transfer Protocol" DESCRIPTION = \ "The Trivial File Transfer Protocol (TFTP) is normally used only for \ booting diskless workstations. The tftp package provides the user \ interface for TFTP, which allows users to transfer files to and from a \ remote machine. This program and TFTP provide very little security, \ and should not be enabled unless it is expressly needed." HOMEPAGE = "http://git.kernel.org/cgit/network/tftp/tftp-hpa.git" PR = "r0" inherit debian-package LICENSE = "BSD-4-Clause" LIC_FILES_CHKSUM = "\ file://MCONFIG.in;beginline=1;endline=9;md5=c28ba5adb43041fae4629db05c83cbdd \ file://tftp/tftp.c;beginline=1;endline=32;md5=988c1cba99d70858a26cd877209857f4" DEBIAN_PATCH_TYPE = "nopatch" #Add tftpd-hpa package PACKAGES =+ "tftpd-hpa" do_install_append() { #Create new folders install -d ${D}${sysconfdir} install -d ${D}${sysconfdir}/init.d install -d ${D}${sysconfdir}/init install -d ${D}${bindir} install -d ${D}${sbindir} install -m 0755 ${S}/tftp/tftp \ ${D}${bindir} install -m 0755 ${S}/tftpd/tftpd \ ${D}${sbindir}/in.tftpd install -m 0644 ${S}/debian/tftpd-hpa.upstart \ ${D}${sysconfdir}/init/tftpd-hpa.conf install -m 0755 ${S}/debian/tftpd-hpa.init \ ${D}${sysconfdir}/init.d/tftpd-hpa } FILES_tftpd-hpa = "${sbindir}/in.tftpd \ ${sysconfdir}/* \ " ```
dabe1990-a6aa-466a-b9bd-87e2737f9737
{ "language": "BitBake" }
```bitbake ``` Add recipe for passwdqc package
```bitbake DESCRIPTION = "password strength checking and policy enforcement toolset" PR="r0" inherit debian-package autotools-brokensep LICENSE = "BSD & PD" LIC_FILES_CHKSUM = "file://LICENSE;md5=1b4af6f3d4ee079a38107366e93b334d" DEPENDS += "libpam" do_compile_prepend_class-target() { sed -i -e "s/^CC = gcc/CC = ${TARGET_SYS}-gcc/" ${S}/Makefile } # Add more package follow deian PACKAGES =+ "libpam-${PN} libpasswdqc0" # Install files follow debian FILES_libpasswdqc0 += "${base_libdir}/*.so.*" FILES_libpam-${PN} += "${base_libdir}/security/*" FILES_${PN}-dbg += "${base_libdir}/security/.debug" # Rename package name follow debian PKG_${PN}-dev = "lib${PN}-dev" ```
be923b3a-9431-4ab2-ab46-d7aa33fa2815
{ "language": "BitBake" }
```bitbake ``` Upgrade to latest version with HEVC content.
```bitbake DESCRIPTION = "AMSDK multimedia support files" HOMEPAGE = "https://gforge.ti.com/gf/project/am_multimedia/" LICENSE = "CC-BY-NC-ND-3.0 & CC-BY-3.0" SECTION = "multimedia" LIC_FILES_CHKSUM = "file://Multimedia_Data_Files_Manifest.doc;md5=9254447a504d2179d83a6bc9e2c28142" PR = "r0" COMPATIBLE_MACHINE = "(omap3|ti33x|ti43x|omap-a15)" PACKAGE_ARCH = "${MACHINE_ARCH}" VIDEO_FILES = "video_480p " VIDEO_FILES_append_am37x-evm = "video_vga_r" VIDEO_FILES_append_beagleboard = "video_vga" VIDEO_FILES_append_am3517-evm = "video_wqvga" VIDEO_FILES_append_ti33x = "video_wvga \ video_wqvga" VIDEO_FILES_append_dra7xx = "video_wvga \ video_1080p \ video_720p \ video_yuv" SRC_URI = "https://gforge.ti.com/gf/download/frsrelease/1251/7520/amsdk-av-files_${PV}.tar.gz;name=avfilestarball" S = "${WORKDIR}/amsdk-av-files" do_compile() { : } do_install() { install -d ${D}${datadir}/ti \ ${D}${datadir}/ti/audio \ ${D}${datadir}/ti/video install -m 0644 ${S}/audio/* ${D}${datadir}/ti/audio/ for file in ${VIDEO_FILES}; do install -m 0644 ${S}/${file}/* ${D}${datadir}/ti/video/ done } FILES_${PN} += "${datadir}/ti/*" SRC_URI[avfilestarball.md5sum] = "c4c849cf6c16e4898869264bbd05fd5d" SRC_URI[avfilestarball.sha256sum] = "287cc95a68befa594b8b9a8514c57240620d535b2b99c6d3e1f91bc278ef37ef" ```
34476325-a440-4432-98b9-50c6595feb46
{ "language": "BitBake" }
```bitbake ``` Add a bitbake recipe to build logutils
```bitbake SUMMARY = "Go package that augments the standard library "log" package" HOMEPAGE = "https://github.com/hashicorp/logutils" LICENSE = "MPL-2.0" LIC_FILES_CHKSUM = "file://LICENSE;md5=b278a92d2c1509760384428817710378" PKG_NAME = "github.com/hashicorp/logutils" SRC_URI = "git://${PKG_NAME}.git" SRCREV = "0dc08b1671f34c4250ce212759ebd880f743d883" S = "${WORKDIR}/git" do_install() { install -d ${D}${prefix}/local/go/src/${PKG_NAME} cp -a ${S}/* ${D}${prefix}/local/go/src/${PKG_NAME}/ } SYSROOT_PREPROCESS_FUNCS += "logutils_sysroot_preprocess" logutils_sysroot_preprocess () { install -d ${SYSROOT_DESTDIR}${prefix}/local/go/src/${PKG_NAME} cp -a ${D}${prefix}/local/go/src/${PKG_NAME} ${SYSROOT_DESTDIR}${prefix}/local/go/src/$(dirname ${PKG_NAME}) } FILES_${PN} += "${prefix}/local/go/src/${PKG_NAME}/*" ```
dde8ecf2-c03e-4842-94fc-2de9962507a3
{ "language": "BitBake" }
```bitbake ``` Add recipe for python-setuptools package.
```bitbake # base recipe: meta/recipes-devtools/python/python-setuptools_40.8.0.bb # base branch: warrior DESCRITPION = "Python Distutils Enhancements" SUMMARY = "Extensions to the python-distutils for large or complex distributions." require recipes-devtools/python/python-setuptools.inc inherit debian-package require recipes-debian/sources/python-setuptools.inc LICENSE = "Apache-2.0 " LIC_FILES_CHKSUM = "file://LICENSE;md5=9a33897f1bca1160d7aad3835152e158" FILESPATH_append = ":${COREBASE}/meta/recipes-devtools/python/files" PROVIDES = "python-distribute" inherit setuptools RREPLACES_${PN} = "python-distribute" RPROVIDES_${PN} = "python-distribute" RCONFLICTS_${PN} = "python-distribute" ```
55f50a41-a624-4462-a29c-3967e2259fa4
{ "language": "BitBake" }
```bitbake ``` Add new release if gpe-mixer.
```bitbake LICENSE = "GPL" PR = "r0" inherit gpe pkgconfig DESCRIPTION = "GPE audio mixer" DEPENDS = "gtk+ libgpewidget" SECTION = "gpe" PRIORITY = "optional" ```
e0f1a7df-2300-4356-8086-2c8f6d96a35a
{ "language": "BitBake" }
```bitbake ``` Add new recipe for opentyrian-hg
```bitbake DESCRIPTION = "OpenTyrian is a port of the DOS shoot-em-up Tyrian." HOMEPAGE = "https://code.google.com/p/opentyrian/" SECTION = "games" LICENSE = "GPLv2" DEPENDS = "virtual/libsdl libsdl-net" REV = "3f3819c0b2" PV = "2.1+hg${REV}" PR = "r0" SRC_URI = "hg://opentyrian.googlecode.com/hg;module=opentyrian;rev=${REV} \ http://camanis.net/tyrian/tyrian21.zip;name=data" S = "${WORKDIR}/opentyrian" FILES_${PN} += " ${datadir}/applications ${datadir}/pixmaps ${datadir}/opentyrian" FILES_${PN}-doc = "${mandir}/man6" do_compile() { oe_runmake release } do_install() { install -d ${D}${bindir} install -d ${D}${mandir}/man6 install -d ${D}${datadir}/pixmaps install -d ${D}${datadir}/applications install -d ${D}${datadir}/opentyrian/data install -m 0755 opentyrian ${D}${bindir} install -m 0644 linux/man/opentyrian.6 ${D}${mandir}/man6 install -m 0644 -T linux/icons/tyrian-48.png ${D}${datadir}/pixmaps/opentyrian.png install -m 0644 linux/opentyrian.desktop ${D}${datadir}/applications install -m 0644 ${WORKDIR}/tyrian21/* ${D}${datadir}/opentyrian/data } SRC_URI[data.md5sum] = "2a3b206a6de25ed4b771af073f8ca904" SRC_URI[data.sha256sum] = "7790d09a2a3addcd33c66ef063d5900eb81cc9c342f4807eb8356364dd1d9277" ```
11b5f5e6-2b15-43b6-9bb8-ab4b5a48f8cb
{ "language": "BitBake" }
```bitbake ``` Add recipe for Azure IoT device python SDK
```bitbake SUMMARY = "Microsoft Azure IoT Device Library" AUTHOR = "Microsoft Corporation" HOMEPAGE = "https://github.com/Azure/azure-iot-sdk-python/tree/master/azure-iot-device" LICENSE = "MIT" LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302" inherit pypi setuptools3 RDEPENDS_${PN} += "\ ${PYTHON_PN}-janus \ ${PYTHON_PN}-paho-mqtt \ ${PYTHON_PN}-pysocks \ ${PYTHON_PN}-requests \ ${PYTHON_PN}-requests-unixsocket \ ${PYTHON_PN}-six \ ${PYTHON_PN}-transitions \ ${PYTHON_PN}-urllib3 \ " RDEPENDS_${PN} += "\ ${PYTHON_PN}-asyncio \ ${PYTHON_PN}-crypt \ ${PYTHON_PN}-datetime \ ${PYTHON_PN}-io \ ${PYTHON_PN}-json \ ${PYTHON_PN}-logging \ ${PYTHON_PN}-multiprocessing \ ${PYTHON_PN}-netclient \ " PR = "r0" SRC_URI[sha256sum] = "6186c9be8c25917a29ac9f432b484d5c28e428ec83a919926c77b0472d36abc7" ```
5e538e06-9403-4bbb-b844-b0090de31600
{ "language": "BitBake" }
```bitbake ``` Add cryptography example C applications
```bitbake DESCRIPTION = "TI Cryptography Example Applications" HOMEPAGE = "http://arago-project.org/git/projects/?p=crypto-example-apps.git;a=summary" LICENSE = "BSD" LIC_FILES_CHKSUM = "file://AES/aes_256.c;beginline=9;endline=35;md5=8edbb4dee965d2f2eb5ca2822addcae5" SECTION = "console" PR = "r0" BRANCH ?= "master" SRCREV = "d3cc223206367a02097c7ad4e997cf2bef975277" SRC_URI = "git://arago-project.org/git/projects/crypto-example-apps.git;protocol=git;branch=${BRANCH}" S = "${WORKDIR}/git" do_compile() { # build the release version oe_runmake release } do_install() { oe_runmake DESTDIR=${D} install } ```
e249aae7-8f0c-465a-808b-2ec4e8a777df
{ "language": "BitBake" }
```bitbake ``` Add bitbake recipe to build consul
```bitbake DESCRIPTION = "A tool for discovering and configuring services in your infrastructure" HOMEPAGE = "https://www.consul.io/" LICENSE = "MPL-2.0" LIC_FILES_CHKSUM = "file://LICENSE;md5=b278a92d2c1509760384428817710378" DEPENDS += "golang-cross \ circbuf \ consul-migrate \ go-checkpoint \ go-msgpack \ go-syslog \ hcl \ logutils \ memberlist \ raft \ raft-boltdb \ scada-client \ serf \ yamux \ muxado \ dns \ cli \ mapstructure \ columnize \ go-radix \ golang-lru \ " PKG_NAME = "github.com/hashicorp/consul" SRC_URI = "git://${PKG_NAME}.git" SRCREV = "5aa90455ce78d4d41578bafc86305e6e6b28d7d2" S = "${WORKDIR}/git" CCACHE = "" #Stops go from installing and testing the package do_configure(){ } do_compile() { #Setting up GOPATH to find deps (including those already in consul) cd ${S} rm -rf .gopath mkdir -p .gopath/src/$(dirname ${PKG_NAME}) ln -sf ../../../.. .gopath/src/${PKG_NAME} export GOPATH=${S}:${STAGING_DIR_TARGET}/${prefix}/local/go:${S}/.gopath export GOARCH="${TARGET_ARCH}" # supported amd64, 386, arm if [ "${TARGET_ARCH}" = "x86_64" ]; then export GOARCH="amd64" fi go install github.com/hashicorp/consul } do_install() { install -d ${D}${prefix}/local/go/src/${PKG_NAME} install -d ${D}${prefix}/bin cp -a ${S}/* ${D}${prefix}/local/go/src/${PKG_NAME}/ cp -a ${S}/.gopath/bin/* ${D}${prefix}/bin/ } FILES_${PN} += "${prefix}/local/go/src/${PKG_NAME}/* ${prefix}/bin/*" ```
a857047a-a5fc-4909-bde3-f2ed1927352e
{ "language": "BitBake" }
```bitbake DESCRIPTION = "Action GUI for Installer" HOMEPAGE = "http://assassin.projects.openmoko.org/" LICENSE = "GPL" DEPENDS = "dbus (>= 1.1.1) glib-2.0 e-wm packagekit etk edbus eet" RDEPENDS = "etk-theme-ninja" PV = "0.2+svnr${SRCREV}" PR = "r6.03" SRC_URI = "svn://svn.projects.openmoko.org/svnroot/;module=assassin;proto=https" S = "${WORKDIR}/assassin" inherit autotools pkgconfig EXTRA_OECONF = "" FILES_${PN} += "${prefix}/share/*" ``` Revert "[assassin] Remove curl in DEPENDS of assassin"
```bitbake DESCRIPTION = "Action GUI for Installer" HOMEPAGE = "http://assassin.projects.openmoko.org/" LICENSE = "GPL" DEPENDS = "dbus (>= 1.1.1) glib-2.0 e-wm packagekit etk edbus eet curl" RDEPENDS = "etk-theme-ninja" PV = "0.2+svnr${SRCREV}" PR = "r6.02" SRC_URI = "svn://svn.projects.openmoko.org/svnroot/;module=assassin;proto=https" S = "${WORKDIR}/assassin" inherit autotools pkgconfig EXTRA_OECONF = "" FILES_${PN} += "${prefix}/share/*" ```
8d12563f-1007-4c14-8456-67b04842c2c4
{ "language": "BitBake" }
```bitbake DESCRIPTION = "Action GUI for Installer" HOMEPAGE = "http://assassin.projects.openmoko.org/" LICENSE = "GPL" DEPENDS = "dbus (>= 1.1.1) glib-2.0 e-wm packagekit etk edbus eet curl" RDEPENDS = "etk-theme-ninja" PV = "0.2+svnr${SRCREV}" PR = "r6.02" SRC_URI = "svn://svn.projects.openmoko.org/svnroot/;module=assassin;proto=https" S = "${WORKDIR}/assassin" inherit autotools pkgconfig EXTRA_OECONF = "" FILES_${PN} += "${prefix}/share/*" ``` Remove curl in DEPENDS of assassin
```bitbake DESCRIPTION = "Action GUI for Installer" HOMEPAGE = "http://assassin.projects.openmoko.org/" LICENSE = "GPL" DEPENDS = "dbus (>= 1.1.1) glib-2.0 e-wm packagekit etk edbus eet" RDEPENDS = "etk-theme-ninja" PV = "0.2+svnr${SRCREV}" PR = "r6.03" SRC_URI = "svn://svn.projects.openmoko.org/svnroot/;module=assassin;proto=https" S = "${WORKDIR}/assassin" inherit autotools pkgconfig EXTRA_OECONF = "" FILES_${PN} += "${prefix}/share/*" ```
db4eb881-c45f-4785-a959-b7d841d89e30
{ "language": "BitBake" }
```bitbake ``` Add recipe for libdshconfig package
```bitbake DESCRIPTION = "\ Runtime library for configuration file parser,required for running \ programs with dsh config file support. \ dsh uses this library to parse configuration files." PR = "r0" inherit debian-package LICENSE = "GPLv2+" LIC_FILES_CHKSUM = "file://COPYING;md5=94d55d512a9ba36caa9b7df079bae19f" inherit autotools-brokensep DEBIAN_PATCH_TYPE = "nopatch" #configure follow debian/rules EXTRA_OECONF = "--with-versioned-symbol" DEBIANNAME_${PN}-dev = "${PN}1-dev" ```
6a1ce8e0-eaa7-404a-81e3-63ac8558a374
{ "language": "BitBake" }
```bitbake ``` Add network manager addon for XBMC
```bitbake DESCRIPTION = "XBMC network manager addon" LICENSE = "GPLv2" LIC_FILES_CHKSUM = "file://LICENSE.txt;md5=7226e01ff2d738e2246d467214c409b9" DEPENDS += "xbmc" PR = "r0" SRC_URI = "http://mirrors.xbmc.org/addons/frodo/script.linux.nm/script.linux.nm-0.1.4.zip" SRC_URI[md5sum] = "918ffb412b571d3e0e00f1d8a7e9e4fb" S = "${WORKDIR}/script.linux.nm/" do_install() { install -d ${D}/home/root/.xbmc/addons/ cp -axr ${S} ${D}/home/root/.xbmc/addons/ } FILES_${PN} += "/home/root/.xbmc/addons/script.linux.nm" ```
7b56da22-3f46-4028-a360-0b4c1e7a30b4
{ "language": "BitBake" }
```bitbake ``` Add recipe for libdatetime-perl package
```bitbake SUMMARY = "module for manipulating dates, times and timestamps" DESCRIPTION = "\ DateTime is a Perl module which aims to provide a complete, correct, and easy \ to use date/time object implementation. It provides an easy way to manipulate \ dates and times, including date calculations (even addition and subtraction) \ and provides convenient methods for extracting or modifying portions of any \ date or time. \ . \ This module supports the Olson time zone database, meaning that historical \ time zone information, and more importantly, daylight saving time rules, can \ be handled transparently, simply by setting the correct time zone. This is \ done by using the DateTime::TimeZone module. \ " HOMEPAGE = "http://datetime.perl.org/" PR = "r0" inherit debian-package LICENSE = "Artistic-2.0" LIC_FILES_CHKSUM = "\ file://LICENSE;md5=1d2e1c522435425bc51123e3d4782081" inherit cpan_build RDEPENDS_${PN} += "\ libparams-validate-perl libdatetime-locale-perl \ libdatetime-timezone-perl libtry-tiny-perl" # source format is 3.0 (quilt) but there is no debian patch DEBIAN_QUILT_PATCHES = "" do_install_append() { perl_version=${PERLVERSION} short_perl_version=`echo ${perl_version%.*}` install -d ${D}${libdir}/perl5/$short_perl_version mv ${D}${libdir}/perl/vendor_perl/${PERLVERSION}/* \ ${D}${libdir}/perl5/$short_perl_version } FILES_${PN} += "${libdir}/*" FILES_${PN}-dbg += "${libdir}/perl5/*/auto/DateTime/.debug" ```
b3cd0de4-41c0-47f1-87d7-fa5b925f7645
{ "language": "BitBake" }
```bitbake ``` Add recipe for libjson-perl package
```bitbake SUMMARY = "module for manipulating JSON-formatted data" PR = "r0" inherit debian-package LICENSE = "GPL-1+" LIC_FILES_CHKSUM = "file://README;md5=309aa8b91686700797df6e79ceb678f0" inherit cpan FILES_${PN} += "${datadir}" BBCLASSEXTEND = "native nativesdk" ```
6fec3509-81fb-4f47-9766-1ff1813be489
{ "language": "BitBake" }
```bitbake ``` Add PSP version for ti816x devices.
```bitbake require u-boot-omap3.inc COMPATIBLE_MACHINE = "ti816x" BRANCH = "master" # Use literal tags in SRCREV, when available, instead of commit IDs SRCREV = "v2010.06_TI816XPSP_04.00.00.10" UVER = "2010.06" PSPREL = "04.00.00.10" PR = "r1" ```
3dec743b-37b6-4fc9-a3f5-94505d99f08a
{ "language": "BitBake" }
```bitbake ``` Add recipe for target, native and nativesdk use
```bitbake SUMMARY = "UpdateHub utilities for update package management and server" SECTION = "devel/python" LICENSE = "MIT" LIC_FILES_CHKSUM = "file://LICENSE;md5=d7d0c756730e640e1731676efa6782e9" SRC_URI = "git://github.com/UpdateHub/uhu.git;protocol=https" SRCREV = "fed71af14f79fdc8db8da90f63b8b3d59ea93174" PV = "1.0.0+${SRCPV}" S = "${WORKDIR}/git" inherit setuptools3 CLEANBROKEN = "1" do_install_append_class-native() { sed -i -e '1s|^#!.*|#!/usr/bin/env python3|' ${D}${bindir}/uhu create_wrapper ${D}${bindir}/uhu LC_ALL=C.UTF-8 LANG=C.UTF-8 LOCPATH=/usr/lib/locale } # FIXME: The native package is not adding the runtime dependencies for # the sysroot populate. The issue is reported on YOCTO: #10113 do_populate_sysroot[rdeptask] = "do_populate_sysroot" # FIXME: Runtime dependency of python3-prompt-toolkit which is not handled # for native case. The issue is also related to YOCTO: #10113 RDEPENDS_${PN} += " \ python3-wcwidth \ python3-six \ " RDEPENDS_${PN} += " \ updatehub-package-schema \ python3-click \ python3-progress \ python3-requests \ python3-rfc3987 \ python3-jsonschema \ python3-prompt-toolkit \ python3-humanize \ " BBCLASSEXTEND = "native nativesdk" ```
7061cac9-97b1-4651-b31c-8f415c343869
{ "language": "BitBake" }
```bitbake LICENSE = "BSD-X" SECTION = "x11/libs" PRIORITY = "optional" DEPENDS = "virtual/libx11 xcalibrateext libxext" DESCRIPTION = "XCalibrate client-side library" PV = "0.0+git4be232e30cd33a44a1ce6d3ec429ee6101540c62" SRC_URI = "git://anongit.freedesktop.org/git/xorg/lib/libXCalibrate;protocol=git;tag=4be232e30cd33a44a1ce6d3ec429ee6101540c62" S = "${WORKDIR}/git" inherit autotools pkgconfig do_stage() { autotools_stage_all } ``` Use increment-able PV format as other git version recipes do.
```bitbake LICENSE = "BSD-X" SECTION = "x11/libs" PRIORITY = "optional" DEPENDS = "virtual/libx11 xcalibrateext libxext" DESCRIPTION = "XCalibrate client-side library" PR = "r0" PV = "0.0+${PR}+gitr4be232e30cd33a44a1ce6d3ec429ee6101540c62" SRC_URI = "git://anongit.freedesktop.org/git/xorg/lib/libXCalibrate;protocol=git;tag=4be232e30cd33a44a1ce6d3ec429ee6101540c62" S = "${WORKDIR}/git" inherit autotools pkgconfig do_stage() { autotools_stage_all } ```
db33115d-b932-419a-8a7b-f30612e5d6ae
{ "language": "BitBake" }
```bitbake ``` Test application for OMAP DRM interface
```bitbake DESCRIPTION = "Test applications for OMAP DRM interface" LICENSE = "GPLv2" LIC_FILES_CHKSUM = "file://viddec3test.c;beginline=1;endline=16;md5=c391f44e40a29096285e3121923041df" DEPENDS += "libdrm libdce libav" inherit autotools pkgconfig PR = "r3" SRCREV = "64e4e389dd8be4947c107a057f34556a4280281a" SRC_URI = "git://git.ti.com/glsdk/omapdrmtest.git;protocol=git" S = "${WORKDIR}/git" INSANE_SKIP_omapdrmtest = "dev-deps" ```
6716b9bb-393a-4470-96f0-c857381f5035
{ "language": "BitBake" }
```bitbake ``` Add new release of gpe-filemanager.
```bitbake inherit gpe PR = "r0" LICENSE = "GPL" DESCRIPTION = "GPE file manager" DEPENDS = "libgpewidget gnome-vfs dbus" SECTION = "gpe" RDEPENDS = "gpe-icons" RRECOMMENDS = "gnome-vfs-plugin-file" FILES_${PN} += " ${datadir}/gpe" ```
99127a88-0f87-4efd-8fe0-a130c8f5cdd1
{ "language": "BlitzMax" }
```blitzmax Type mxLoggerObserverGUI Field m_output:Object Method Reset() If TGadget(m_output) SetGadgetText(TGadget(m_output), "") End If End Method Method SendMessage:Object(message:Object, context:Object) Local msg:String = String(message) If String(context) = "error" Notify(msg, True) Else If TGadget(m_output) Local gadget:TGadget = TGadget(m_output) SetGadgetText(gadget, GadgetText(gadget) + "~n" + String(message)) Else If m_output = Null Notify(msg) End If End Method End Type``` Refresh the GUI when mxLoggerObserverGUI updates text of a TGadget
```blitzmax Type mxLoggerObserverGUI Field m_output:Object Method Reset() If TGadget(m_output) SetGadgetText(TGadget(m_output), "") End If End Method Method SendMessage:Object(message:Object, context:Object) Local msg:String = String(message) If String(context) = "error" Notify(msg, True) Else If TGadget(m_output) Local gadget:TGadget = TGadget(m_output) SetGadgetText(gadget, GadgetText(gadget) + "~n" + String(message)) 'Refresh GUI Driver.Poll Else If m_output = Null Notify(msg) End If End Method End Type```
77dd6efd-ad25-4837-bd1b-881453b00bcc
{ "language": "Bluespec" }
```bluespec function String toHex(Bit#(s) num); function String f(Bit#(s) n); String dig[16] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; return (n == 0) ? "" : f(n / 16) + dig[n % 16]; endfunction return (num == 0) ? "0" : f(num); endfunction ``` Implement toHex supporting don't-care bits
```bluespec function Bit#(n) removeDontCares(Bit#(n) num); Bit#(n) res = 0; for(Integer i = 0; i < valueOf(n); i = i + 1) res[i] = (num[i] == 1'b1) ? 1'b1 : 1'b0; return res; endfunction function String toHex(Bit#(n) num) provisos ( Div#(n , 4, ndig), Mul#(ndig, 4, nadj), Add#(pad , n, nadj) ); String dig[16] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; Bit#(nadj) numadj = extend(removeDontCares(num)); String res = ""; for(Integer i = valueOf(nadj) - 1; i >= 0; i = i - 4) begin Bit#(4) dign = numadj[i:i-3]; res = res + dig[dign]; end return res; endfunction ```
6fd347f6-faed-4aa9-911a-47625652f891
{ "language": "Bluespec" }
```bluespec import Ethernet::*; (* always_ready, always_enabled *) interface DE5Pins; method Action osc_50(Bit#(1) b3d, Bit#(1) b4a, Bit#(1) b4d, Bit#(1) b7a, Bit#(1) b7d, Bit#(1) b8a, Bit#(1) b8d); method Action sfp(Bit#(1) refclk); method Action buttons(Bit#(4) v); // method Bit#(4) serial_tx_data; // method Action serial_rx(Bit#(4) data); interface SFPCtrl#(4) sfpctrl; // method Bit#(1) led0; // method Bit#(1) led1; // method Bit#(1) led2; method Bit#(1) led3; method Bit#(4) led_bracket; interface Clock deleteme_unused_clock; interface Clock deleteme_unused_clock2; interface Clock deleteme_unused_clock3; interface Reset deleteme_unused_reset; endinterface ``` Fix "Attempt to use this undetermined clock" Error
```bluespec import Ethernet::*; (* always_ready, always_enabled *) interface DE5Pins; method Action osc_50(Bit#(1) b3d, Bit#(1) b4a, Bit#(1) b4d, Bit#(1) b7a, Bit#(1) b7d, Bit#(1) b8a, Bit#(1) b8d); method Action sfp(Bit#(1) refclk); method Action buttons(Bit#(4) v); // method Bit#(4) serial_tx_data; // method Action serial_rx(Bit#(4) data); interface SFPCtrl#(4) sfpctrl; method Bit#(1) led0; // method Bit#(1) led1; // method Bit#(1) led2; method Bit#(1) led3; method Bit#(4) led_bracket; `ifndef BSIM interface Clock deleteme_unused_clock; interface Clock deleteme_unused_clock2; interface Clock deleteme_unused_clock3; interface Reset deleteme_unused_reset; `endif endinterface ```
51aad0a5-7bbe-4c9c-8eeb-e737b63e7ecd
{ "language": "Boo" }
```boo namespace BooJs.Compiler.Steps import Boo.Lang.Compiler.Ast import Boo.Lang.Compiler.Steps class ProcessGoto(AbstractTransformerCompilerStep): """ Process labels and goto statements The supported uses are very limited. It's only possible to jump to a label previously defined in the same function. No jumps to forward labels are allowed. Even if fully supporting goto statements with forward jumping is theoretically possible (similarly on how generators are transformed for example), it would be difficult to implement for the benefits it provides. TODO: Check implementation constraints. Referenced label can only be present in the same method and above the goto statement """ override def Run(): if len(Errors) > 0: return Visit CompileUnit def OnLabelStatement(node as LabelStatement): parent = node.ParentNode as Block index = parent.Statements.IndexOf(node) loop = [| while true: pass |] loop.Block.Statements = parent.Statements.PopRange(index+1) # We need to break out of the loop when we reach the end :) loop.Block.Statements.Add(BreakStatement()) parent.Statements.Add(loop) ``` Make sure Goto is only processed once
```boo namespace BooJs.Compiler.Steps import Boo.Lang.Compiler.Ast import Boo.Lang.Compiler.Steps class ProcessGoto(AbstractTransformerCompilerStep): """ Process labels and goto statements The supported uses are very limited. It's only possible to jump to a label previously defined in the same function. No jumps to forward labels are allowed. Even if fully supporting goto statements with forward jumping is theoretically possible (similarly on how generators are transformed for example), it would be difficult to implement for the benefits it provides. TODO: Check implementation constraints. Referenced label can only be present in the same method and above the goto statement """ override def Run(): if len(Errors) > 0: return Visit CompileUnit def OnLabelStatement(node as LabelStatement): # Make sure we only process the statement once if node.ContainsAnnotation(self): return node.Annotate(self) parent = node.ParentNode as Block index = parent.Statements.IndexOf(node) loop = [| while true: pass |] loop.Block.Statements = parent.Statements.PopRange(index+1) # We need to break out of the loop when we reach the end :) loop.Block.Statements.Add(BreakStatement()) parent.Statements.Add(loop) ```
f2acad57-c12a-407d-9ff5-9a8bed01d0df
{ "language": "Boo" }
```boo namespace BooJs.Compiler.Steps import Boo.Lang.Compiler.Ast import Boo.Lang.Compiler.Steps class NormalizeGeneratorExpression(AbstractTransformerCompilerStep): """ Converts generator expressions to a simpler format: ( i*2 for i in range(3) ) --- { __gen = []; for i in range(3): __gen.push(i*2); return __gen }() """ def LeaveGeneratorExpression(node as GeneratorExpression): # ( i*2 for i as int in range(3) ) => ( expression for declarations in iterator if filter ) # Build a loop statement with the details from the generator loop = ForStatement() loop.Declarations = node.Declarations loop.Iterator = node.Iterator if not node.Filter: loop.Block = [| block: _gen.push($(node.Expression)) |].Body else: loop.Block = [| block: _gen.push($(node.Expression)) if $(node.Filter.Condition) |].Body # Build the body of the anonymous function body = [| block: $loop return _gen |].Body # Replace the generator expression with the result of executing the anonymous function ReplaceCurrentNode([| {_gen as (object)| $(body) }([]) |]) ``` Use sequence instead of self execution functions
```boo namespace BooJs.Compiler.Steps import Boo.Lang.Compiler.Ast import Boo.Lang.Compiler.Steps class NormalizeGeneratorExpression(AbstractTransformerCompilerStep): """ Converts generator expressions to a simpler format: ( i*2 for i in range(3) ) --- { __gen = []; for i in range(3): __gen.push(i*2); return __gen }() """ # Keep track of last visited method _method as Method def OnMethod(node as Method): last = _method _method = node super(node) _method = last def OnListLiteralExpression(node as ListLiteralExpression): """ If generator is contained in a list literal, remove the list literal """ if len(node.Items) == 1 and node.Items.First.NodeType == NodeType.GeneratorExpression: result = Visit(node.Items.First) ReplaceCurrentNode result return super(node) def LeaveGeneratorExpression(node as GeneratorExpression): """ Convert generator expressions to a sequence: ( i*2 for i in range(3) ) => @(__gen = [], Boo.each(range(3), { i | __gen.push(i*2) }), __gen) """ # Make sure the __gen variable is declared _method.Locals.Add(Local(node.LexicalInfo, '__gen')) if node.Filter: lambda = [| { $(node.Filter.Condition) and __gen.push( $(node.Expression) ) } |] else: lambda = [| { __gen.push( $(node.Expression) ) } |] lambda.LexicalInfo = node.LexicalInfo for decl in node.Declarations: lambda.Parameters.Add(ParameterDeclaration(node.LexicalInfo, Name: decl.Name)) result = [| @(__gen = [], Boo.each($(node.Iterator), $lambda), __gen) |] ReplaceCurrentNode result ```
e47ba9a3-2633-4fde-969c-bb60dd8cb32a
{ "language": "Brainfuck" }
```brainfuck global w; global t; global k; LIKELIHOOD_FUNCTION_OUTPUT = 1; RANDOM_STARTING_PERTURBATIONS = 1; /* Include relevant functions */ #include "matrices.mdl"; //rate matrices #include "GY94_Header.ibf"; /* Read in the data */ DataSet raw_data = ReadDataFile("temp.fasta"); /* Filter the data to find and remove any stop codons*/ DataSetFilter filt_data = CreateFilter(raw_data,3,"", "","TAA,TAG,TGA"); /* Collect observed frequencies into vectors */ HarvestFrequencies(observedFreq_data,filt_data,3,1,1); /* Get the codon frequencies from the nucleotide frequency vectors */ codonFreq_data = BuildCodonFrequencies(observedFreq_data); /* Define the model and tree */ Model MyModel = (GY94, codonFreq_data, 1); UseModel (USE_NO_MODEL); UseModel(MyModel); Tree Tree01 = DATAFILE_TREE; /*COMPUTE LIKELIHOODS*/ LikelihoodFunction LikFn2 = (filt_data, Tree01); Optimize (paramValues2, LikFn2); fprintf (stdout, LikFn2); ``` Save the correct hyphy materials
```brainfuck global w; global t; global k; LIKELIHOOD_FUNCTION_OUTPUT = 1; RANDOM_STARTING_PERTURBATIONS = 1; /* Include relevant functions */ #include "matrices_fix_k.mdl"; //rate matrices #include "GY94_Header.ibf"; /* Read in the data */ DataSet raw_data = ReadDataFile("temp.fasta"); /* Filter the data to find and remove any stop codons*/ DataSetFilter filt_data = CreateFilter(raw_data,3,"", "","TAA,TAG,TGA"); /* Collect observed frequencies into vectors */ HarvestFrequencies(observedFreq_data,filt_data,3,1,1); /* Get the codon frequencies from the nucleotide frequency vectors */ codonFreq_data = BuildCodonFrequencies(observedFreq_data); /* Define the model and tree */ Model MyModel = (GY94, codonFreq_data, 1); UseModel (USE_NO_MODEL); UseModel(MyModel); Tree Tree01 = DATAFILE_TREE; /*COMPUTE LIKELIHOODS*/ LikelihoodFunction LikFn2 = (filt_data, Tree01); Optimize (paramValues2, LikFn2); fprintf (stdout, LikFn2); ```
7befc42a-9e23-420a-9a7d-2ec595a461e3
{ "language": "Brainfuck" }
```brainfuck ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ f >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ i >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ z >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ b >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ u >++++++++++ lf > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ set loop num > leave 0 for exit flag > +++ set cycle num >>>> +++++ set second cycle num <<<< << back to cycle [ >> cycle check [ - decrement cycle num >+>+<< sets zero flags bit to 1 [ >[-]>[-]<< sets temp bit to 0 in case it's still not 0 < go to exit this is why we need 2 zero ] >> check if zero flag is on [ <<<<<<<<<<.>.>..>>>>>>>> fizz <<+++>> restore cycle number [-]<[-] zero the flags ] < back to cycle num < back to exit flag ] >>>>> cycle check [ - decrement cycle num >+>+<< sets zero flags bit to 1 [ >[-]>[-]<< sets temp bit to 0 in case it's still not 0 < go to exit this is why we need 2 zero ] >> check if zero flag is on [ <<<<<<<<<<<.>.<<..>>>>>>>>>>>> buzz <<+++++>> restore cycle number [-]<[-] zero the flags ] < back to cycle num < back to exit flag ] <<<< <<.>> new line <- ] ``` Add filling char to bf
```brainfuck +++++++++++++++++++++++++++++++++++++++++++++ empty line sign >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ f >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ i >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ z >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ b >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ u >++++++++++ lf > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ set loop num > leave 0 for exit flag >>> +++ set cycle num >>>> +++++ set second cycle num <<<<<< << back to cycle [ >+>+ set else flag (when no cycle is zero) >> cycle check [ - decrement cycle num >+>+<< sets zero flags bit to 1 [ >[-]>[-]<< sets temp bit to 0 in case it's still not 0 < go to exit this is why we need 2 zero ] >> check if zero flag is on [ <<<<<<<<<<<<.>.>..>>>>>>>>>> fizz <<<<[-]<[-]>>>>> remove else flags <<+++>> restore cycle number [-]<[-] zero the flags ] < back to cycle num < back to exit flag ] >>>>> cycle check [ - decrement cycle num >+>+<< sets zero flags bit to 1 [ >[-]>[-]<< sets temp bit to 0 in case it's still not 0 < go to exit this is why we need 2 zero ] >> check if zero flag is on [ <<<<<<<<<<<<<.>.<<..>>>>>>>>>>>>>> buzz <<<<<<<<[-]<[-]>>>>>>>>> remove else flags <<+++++>> restore cycle number [-]<[-] zero the flags ] < back to cycle num < back to exit flag ] <<<<<<< back to loop > [ <<<<<<<<.>>>>>>>> new line [-] ] < <.> - decrement loop ] ```
1f6cd629-8213-4712-b5c4-f063827f18b4
{ "language": "Bro" }
```bro # Copyright (C) 2016, Missouri Cyber Team # All Rights Reserved # See the file "LICENSE" in the main distribution directory for details module ROCK; export { const sensor_id = "sensor001-001" &redef; } # Load integration with Snort on ROCK @load ./frameworks/files/unified2-integration # Load integration with FSF @load ./frameworks/files/extract2fsf # Load file extraction @load ./frameworks/files/extraction redef FileExtract::prefix = "/data/bro/logs/extract_files/"; redef FileExtract::default_limit = 1048576000; # Add GeoIP info to conn log @load ./misc/conn-add-geoip # Add worker information to conn log @load ./misc/conn-add-worker ``` Revert "Removes kafka from main config"
```bro # Copyright (C) 2016, Missouri Cyber Team # All Rights Reserved # See the file "LICENSE" in the main distribution directory for details module ROCK; export { const sensor_id = "sensor001-001" &redef; } # Load integration with Snort on ROCK @load ./frameworks/files/unified2-integration # Load integration with FSF @load ./frameworks/files/extract2fsf # Load file extraction @load ./frameworks/files/extraction redef FileExtract::prefix = "/data/bro/logs/extract_files/"; redef FileExtract::default_limit = 1048576000; # Configure Kafka output # Bro Kafka Output (plugin must be loaded!) @load Kafka/KafkaWriter/logs-to-kafka redef KafkaLogger::topic_name = "bro_raw"; redef KafkaLogger::sensor_name = ROCK::sensor_id; # Add GeoIP info to conn log @load ./misc/conn-add-geoip # Add worker information to conn log @load ./misc/conn-add-worker ```
f900779f-49a9-430c-babe-ab76f371d9a8
{ "language": "Bro" }
```bro ``` Add archive formats from upstream.
```bro @load ../__load__.bro module FileExtraction; const archive_types: set[string] = { "application/x-rar-compressed", "application/x-bzip2", "application/gzip", "application/x-lzma", "application/x-lzip", "application/x-xz", "application/x-lzop", "application/x-compress", "application/x-7z-compressed", "application/x-ace-compressed", "application/vnd.ms-cab-compressed", "application/x-gtar", "application/zip", }; hook FileExtraction::extract(f: fa_file, meta: fa_metadata) &priority=5 { if ( meta$mime_type in archive_types ) break; } ```
f55c1c2a-b984-4774-a236-f2ad3ebd0bd8
{ "language": "Bro" }
```bro ##! Packet source using Napatech module Napatech; export { ## The size of the software deduplication lru cache const dedupe_lru_size = 1024 &redef; ## Because applications can share streams, the Host Buffer Allowance ## allows an application to consume a portion of the host buffer ## before the application stops receiving traffic. ## For Bro, you most likely want to set this to 100 const host_buffer_allowance = 100 &redef; }``` Add default value for enable_software_deduplication
```bro ##! Packet source using Napatech module Napatech; export { ## Should the plugin try to deduplicate packets with the color1 ## value of the DYN4 packet descriptor? const enable_software_deduplication = T &redef; ## The size of the software deduplication lru cache const dedupe_lru_size = 1024 &redef; ## Because applications can share streams, the Host Buffer Allowance ## allows an application to consume a portion of the host buffer ## before the application stops receiving traffic. ## For Bro, you most likely want to set this to 100 const host_buffer_allowance = 100 &redef; }```
cedf71a3-241d-4826-888d-1109814e3b53
{ "language": "C#" }
```c# using StackExchange.Elastic; namespace StackExchange.Opserver { public class OpserverCore { // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so. public static void Init() { try { ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix; ElasticException.ExceptionOccurred += e => Current.LogException(e); } catch { } } } } ``` Comment out per-error logging, now only needed for logging
```c# using StackExchange.Elastic; namespace StackExchange.Opserver { public class OpserverCore { // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so. public static void Init() { try { ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix; // We're going to get errors - that's kinda the point of monitoring // No need to log every one here unless for crazy debugging //ElasticException.ExceptionOccurred += e => Current.LogException(e); } catch { } } } } ```
60fb5902-94f7-48fb-97cf-d161605d9316
{ "language": "C#" }
```c# /* Copyright 2014 David Bordoley Copyright 2014 Zumero, 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 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. */ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; namespace SQLitePCL.pretty { public static class ResultSet { public static IEnumerable<IColumnInfo> Columns(this IReadOnlyList<IResultSetValue> rs) { Contract.Requires(rs != null); return rs.Select(value => value.ColumnInfo); } } } ``` Change Columns static method to return IReadOnlyList.
```c# /* Copyright 2014 David Bordoley Copyright 2014 Zumero, 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 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. */ using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; namespace SQLitePCL.pretty { public static class ResultSet { public static IReadOnlyList<IColumnInfo> Columns(this IReadOnlyList<IResultSetValue> rs) { Contract.Requires(rs != null); return new ResultSetColumnsListImpl(rs); } internal sealed class ResultSetColumnsListImpl : IReadOnlyList<IColumnInfo> { private readonly IReadOnlyList<IResultSetValue> rs; internal ResultSetColumnsListImpl(IReadOnlyList<IResultSetValue> rs) { this.rs = rs; } public IColumnInfo this[int index] { get { return rs[index].ColumnInfo; } } public int Count { get { return rs.Count; } } public IEnumerator<IColumnInfo> GetEnumerator() { return rs.Select(val => val.ColumnInfo).GetEnumerator(); } IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } } } ```
2cd4bea6-9c9f-41e9-a05f-4ff79b682d66
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Contentful.Core.Models { /// <summary> /// Represents information about the actual binary file of an <see cref="Asset"/>. /// </summary> public class File { /// <summary> /// The original name of the file. /// </summary> public string FileName { get; set; } /// <summary> /// The content type of the data contained within this file. /// </summary> public string ContentType { get; set; } /// <summary> /// An absolute URL to this file. /// </summary> public string Url { get; set; } /// <summary> /// Detailed information about the file stored by Contentful. /// </summary> public FileDetails Details { get; set; } } } ``` Add upload property to file
```c# using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Contentful.Core.Models { /// <summary> /// Represents information about the actual binary file of an <see cref="Asset"/>. /// </summary> public class File { /// <summary> /// The original name of the file. /// </summary> public string FileName { get; set; } /// <summary> /// The content type of the data contained within this file. /// </summary> public string ContentType { get; set; } /// <summary> /// An absolute URL to this file. /// </summary> public string Url { get; set; } /// <summary> /// The url to upload this file from. /// </summary> [JsonProperty("upload")] public string UploadUrl { get; set; } /// <summary> /// Detailed information about the file stored by Contentful. /// </summary> public FileDetails Details { get; set; } } } ```
3c5d1994-962e-40c8-a595-94943823fe7d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using ArcGIS.ServiceModel; using ArcGIS.ServiceModel.Operation; namespace ArcGIS.Test { public class JsonDotNetSerializer : ISerializer { static ISerializer _serializer = null; public static void Init() { _serializer = new JsonDotNetSerializer(); SerializerFactory.Get = (() => _serializer ?? new JsonDotNetSerializer()); } readonly Newtonsoft.Json.JsonSerializerSettings _settings; public JsonDotNetSerializer() { _settings = new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore, ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }; } public Dictionary<String, String> AsDictionary<T>(T objectToConvert) where T : CommonParameters { var stringValue = Newtonsoft.Json.JsonConvert.SerializeObject(objectToConvert, _settings); var jobject = Newtonsoft.Json.Linq.JObject.Parse(stringValue); var dict = new Dictionary<String, String>(); foreach (var item in jobject) { dict.Add(item.Key, item.Value.ToString()); } return dict; } public T AsPortalResponse<T>(String dataToConvert) where T : IPortalResponse { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(dataToConvert, _settings); } } } ``` Use same namespace for serializers
```c# using System; using System.Collections.Generic; using ArcGIS.ServiceModel; using ArcGIS.ServiceModel.Operation; namespace ArcGIS.ServiceModel.Serializers { public class JsonDotNetSerializer : ISerializer { static ISerializer _serializer = null; public static void Init() { _serializer = new JsonDotNetSerializer(); SerializerFactory.Get = (() => _serializer ?? new JsonDotNetSerializer()); } readonly Newtonsoft.Json.JsonSerializerSettings _settings; public JsonDotNetSerializer() { _settings = new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore, ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }; } public Dictionary<String, String> AsDictionary<T>(T objectToConvert) where T : CommonParameters { var stringValue = Newtonsoft.Json.JsonConvert.SerializeObject(objectToConvert, _settings); var jobject = Newtonsoft.Json.Linq.JObject.Parse(stringValue); var dict = new Dictionary<String, String>(); foreach (var item in jobject) { dict.Add(item.Key, item.Value.ToString()); } return dict; } public T AsPortalResponse<T>(String dataToConvert) where T : IPortalResponse { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(dataToConvert, _settings); } } } ```
311f2cc1-aa37-4422-b8ea-c31fda8280d1
{ "language": "C#" }
```c# namespace XSerializer.Encryption { /// <summary> /// Provides a mechanism for an application to specify an instance of /// <see cref="IEncryptionMechanism"/> to be used by XSerializer when /// encrypting or decrypting data. /// </summary> public static class EncryptionMechanism { /// <summary> /// The default instance of <see cref="IEncryptionMechanism"/>. /// </summary> public static readonly IEncryptionMechanism _defaultEncryptionMechanism = new ClearTextEncryptionMechanism(); private static IEncryptionMechanism _current = _defaultEncryptionMechanism; /// <summary> /// Gets or sets the instance of <see cref="IEncryptionMechanism"/> /// to be used by XSerializer when encrypting or decrypting data. /// When setting this property, if <paramref name="value"/> is null, /// then <see cref="_defaultEncryptionMechanism"/> will be used instead. /// </summary> public static IEncryptionMechanism Current { internal get { return _current; } set { _current = value ?? _defaultEncryptionMechanism; } } } }``` Use correct casing on public static field.
```c# namespace XSerializer.Encryption { /// <summary> /// Provides a mechanism for an application to specify an instance of /// <see cref="IEncryptionMechanism"/> to be used by XSerializer when /// encrypting or decrypting data. /// </summary> public static class EncryptionMechanism { /// <summary> /// The default instance of <see cref="IEncryptionMechanism"/>. /// </summary> public static readonly IEncryptionMechanism DefaultEncryptionMechanism = new ClearTextEncryptionMechanism(); private static IEncryptionMechanism _current = DefaultEncryptionMechanism; /// <summary> /// Gets or sets the instance of <see cref="IEncryptionMechanism"/> /// to be used by XSerializer when encrypting or decrypting data. /// When setting this property, if <paramref name="value"/> is null, /// then <see cref="DefaultEncryptionMechanism"/> will be used instead. /// </summary> public static IEncryptionMechanism Current { internal get { return _current; } set { _current = value ?? DefaultEncryptionMechanism; } } } }```
59af934f-ec83-4060-a25c-4b5e9348d83c
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osuTK; namespace osu.Framework.Graphics.UserInterface { public class BasicDirectorySelectorBreadcrumbDisplay : DirectorySelectorBreadcrumbDisplay { protected override DirectorySelectorDirectory CreateRootDirectoryItem() => new ComputerPiece(); protected override DirectorySelectorDirectory CreateDirectoryItem(DirectoryInfo directory, string displayName = null) => new CurrentDisplayPiece(directory, displayName); public BasicDirectorySelectorBreadcrumbDisplay() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } protected class ComputerPiece : CurrentDisplayPiece { protected override IconUsage? Icon => null; public ComputerPiece() : base(null, "Computer") { } } protected class CurrentDisplayPiece : BasicDirectorySelectorDirectory { protected override IconUsage? Icon => Directory.Name.Contains(Path.DirectorySeparatorChar) ? base.Icon : null; public CurrentDisplayPiece(DirectoryInfo directory, string displayName = null) : base(directory, displayName) { } [BackgroundDependencyLoader] private void load() { Flow.Add(new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = FontAwesome.Solid.ChevronRight, Size = new Vector2(FONT_SIZE / 2) }); } } } } ``` Rename some more nested classes
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osuTK; namespace osu.Framework.Graphics.UserInterface { public class BasicDirectorySelectorBreadcrumbDisplay : DirectorySelectorBreadcrumbDisplay { protected override DirectorySelectorDirectory CreateRootDirectoryItem() => new BreadcrumbDisplayComputer(); protected override DirectorySelectorDirectory CreateDirectoryItem(DirectoryInfo directory, string displayName = null) => new BreadcrumbDisplayDirectory(directory, displayName); public BasicDirectorySelectorBreadcrumbDisplay() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } protected class BreadcrumbDisplayComputer : BreadcrumbDisplayDirectory { protected override IconUsage? Icon => null; public BreadcrumbDisplayComputer() : base(null, "Computer") { } } protected class BreadcrumbDisplayDirectory : BasicDirectorySelectorDirectory { protected override IconUsage? Icon => Directory.Name.Contains(Path.DirectorySeparatorChar) ? base.Icon : null; public BreadcrumbDisplayDirectory(DirectoryInfo directory, string displayName = null) : base(directory, displayName) { } [BackgroundDependencyLoader] private void load() { Flow.Add(new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = FontAwesome.Solid.ChevronRight, Size = new Vector2(FONT_SIZE / 2) }); } } } } ```
fe306f2b-ce0f-48a6-a6f6-03efbd3db57c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KGP.Curves { public class ThresholdLinearCurve : ICurve { private float threshold; public float Threshold { get { return this.threshold; } set { this.threshold = value; } } public ThresholdLinearCurve(float threshold) { this.threshold = threshold; } public float Apply(float value) { float absval = Math.Abs(value); if (absval <= threshold) { return 0.0f; } else { float diff = (absval - threshold) / (1.0f - threshold); return diff * Math.Sign(value); } } } } ``` Comment and fix on namespace
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KGP { /// <summary> /// Linear threshold curve, clamp while absolute value is within threshold /// </summary> public class ThresholdLinearCurve : ICurve { private float threshold; /// <summary> /// Current threshold /// </summary> public float Threshold { get { return this.threshold; } set { this.threshold = value; } } /// <summary> /// Constructor /// </summary> /// <param name="threshold">Initial threshold value</param> public ThresholdLinearCurve(float threshold) { this.threshold = threshold; } /// <summary> ///Apply threshold curve /// </summary> /// <param name="value">Intial value</param> /// <returns>Value with curve applied</returns> public float Apply(float value) { float absval = Math.Abs(value); if (absval <= threshold) { return 0.0f; } else { float diff = (absval - threshold) / (1.0f - threshold); return diff * Math.Sign(value); } } } } ```
9e0fa810-9645-47d0-8d7d-126844e2b3ab
{ "language": "C#" }
```c# namespace Server { using System; using System.IO; using System.Text; internal partial class Program { class Dup : Stream { string _name; private Dup() { } public Dup(string name) { _name = name; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length => throw new NotImplementedException(); public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { DateTime now = DateTime.Now; StringBuilder sb = new StringBuilder(); sb.AppendLine("Raw message from " + _name + " " + now.ToString()); var truncated_array = new byte[count]; for (int i = offset; i < offset + count; ++i) truncated_array[i - offset] = buffer[i]; string str = System.Text.Encoding.Default.GetString(truncated_array); sb.AppendLine("data = '" + str); LoggerNs.Logger.Log.WriteLine(sb.ToString()); } } } } ``` Add quotes and length of JSON packets being sent.
```c# namespace Server { using System; using System.IO; using System.Text; internal partial class Program { class Dup : Stream { string _name; private Dup() { } public Dup(string name) { _name = name; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length => throw new NotImplementedException(); public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { DateTime now = DateTime.Now; StringBuilder sb = new StringBuilder(); sb.AppendLine("Raw message from " + _name + " " + now.ToString()); var truncated_array = new byte[count]; for (int i = offset; i < offset + count; ++i) truncated_array[i - offset] = buffer[i]; string str = System.Text.Encoding.Default.GetString(truncated_array); sb.AppendLine("data (length " + str.Length + ")= '" + str + "'"); LoggerNs.Logger.Log.WriteLine(sb.ToString()); } } } } ```
dc056fcf-f33e-4fa3-8250-ae898b12c72d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { interface ICodeModelInstanceFactory { /// <summary> /// Requests the project system to create a <see cref="EnvDTE.FileCodeModel"/> through the project system. /// </summary> /// <remarks> /// This is sometimes necessary because it's possible to go from one <see cref="EnvDTE.FileCodeModel"/> to another, /// but the language service can't create that instance directly, as it doesn't know what the <see cref="EnvDTE.FileCodeModel.Parent"/> /// member should be. The expectation is the implementer of this will do what is necessary and call back into the code model implementation /// with a parent object.</remarks> EnvDTE.FileCodeModel TryCreateFileCodeModelThroughProjectSystem(string filePath); } } ``` Update documentation now that we can point to a concrete method
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { interface ICodeModelInstanceFactory { /// <summary> /// Requests the project system to create a <see cref="EnvDTE.FileCodeModel"/> through the project system. /// </summary> /// <remarks> /// This is sometimes necessary because it's possible to go from one <see cref="EnvDTE.FileCodeModel"/> to another, /// but the language service can't create that instance directly, as it doesn't know what the <see cref="EnvDTE.FileCodeModel.Parent"/> /// member should be. The expectation is the implementer of this will do what is necessary and call back into <see cref="IProjectCodeModel.GetOrCreateFileCodeModel(string, object)"/> /// handing it the appropriate parent.</remarks> EnvDTE.FileCodeModel TryCreateFileCodeModelThroughProjectSystem(string filePath); } } ```
adeca731-1092-427e-8d7a-32b3eb37db53
{ "language": "C#" }
```c# using System; using Shouldly; using Spk.Common.Helpers.Service; using Xunit; namespace Spk.Common.Tests.Helpers.Service { public class ServiceResultTests { [Theory] [InlineData("test")] [InlineData("")] [InlineData(null)] public void SetData_SuccessShouldBeTrue(string value) { // Arrange var sr = new ServiceResult<string>(); // Act sr.SetData(value); // Assert sr.Success.ShouldBeTrue(); } [Theory] [InlineData("error")] public void GetFirstError_ShouldReturnFirstError(string error) { // Arrange var sr = new ServiceResult<string>(); // Act sr.AddError(error); // Assert sr.GetFirstError().ShouldBe(error); } [Fact] public void AddError_ShouldArgumentNullException_WhenNullError() { // Act & assert Assert.Throws<ArgumentNullException>(() => { var sr = new ServiceResult<string>(); sr.AddError(null); }); } } } ``` Test case renamed to be more accurate
```c# using System; using Shouldly; using Spk.Common.Helpers.Service; using Xunit; namespace Spk.Common.Tests.Helpers.Service { public class ServiceResultTests { [Theory] [InlineData("test")] [InlineData("")] [InlineData(null)] public void Success_ShouldBeTrue_WhenDataIsSet(string value) { // Arrange var sr = new ServiceResult<string>(); // Act sr.SetData(value); // Assert sr.Success.ShouldBeTrue(); } [Theory] [InlineData("error")] public void GetFirstError_ShouldReturnFirstError(string error) { // Arrange var sr = new ServiceResult<string>(); // Act sr.AddError(error); sr.AddError("bleh"); // Assert sr.GetFirstError().ShouldBe(error); } [Fact] public void AddError_ShouldArgumentNullException_WhenNullError() { // Act & assert Assert.Throws<ArgumentNullException>(() => { var sr = new ServiceResult<string>(); sr.AddError(null); }); } } } ```
912d4696-fd3d-4654-a6dd-161a9b31d15a
{ "language": "C#" }
```c# using System.Collections.Concurrent; using System.IO; using NLog; using NLog.Config; using NLog.Targets; namespace Microsoft.Azure.Commands.DataLakeStore.Models { /// <summary> /// NLog is used by the ADLS dataplane sdk to log debug messages. We can create a custom target /// which basically queues the debug data to the ConcurrentQueue for debug messages. /// https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target /// </summary> [Target("AdlsLogger")] public sealed class AdlsLoggerTarget : TargetWithLayout { internal ConcurrentQueue<string> DebugMessageQueue; public AdlsLoggerTarget() { } protected override void Write(LogEventInfo logEvent) { string logMessage = Layout.Render(logEvent); DebugMessageQueue?.Enqueue(logMessage); } } } ``` Remove unused usings and make the target class internal
```c# using System.Collections.Concurrent; using NLog; using NLog.Targets; namespace Microsoft.Azure.Commands.DataLakeStore.Models { /// <summary> /// NLog is used by the ADLS dataplane sdk to log debug messages. We can create a custom target /// which basically queues the debug data to the ConcurrentQueue for debug messages. /// https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target /// </summary> [Target("AdlsLogger")] internal sealed class AdlsLoggerTarget : TargetWithLayout { internal ConcurrentQueue<string> DebugMessageQueue; protected override void Write(LogEventInfo logEvent) { string logMessage = Layout.Render(logEvent); DebugMessageQueue?.Enqueue(logMessage); } } } ```
8ec3e52b-968a-463b-887f-f4ebc3576318
{ "language": "C#" }
```c# using Simpler; using System; using Schedules.API.Models; using Schedules.API.Tasks.Reminders; namespace Schedules.API.Tasks.Sending { public class PostRemindersEmailSend : InOutTask<PostRemindersEmailSend.Input, PostRemindersEmailSend.Output> { public class Input { public Send Send { get; set; } } public class Output { public Send Send { get; set; } } public FetchDueReminders FetchDueReminders { get; set; } public SendEmails SendEmails { get; set; } public override void Execute () { FetchDueReminders.In.RemindOn = In.Send.RemindOn; FetchDueReminders.Execute(); SendEmails.In.DueReminders = FetchDueReminders.Out.DueReminders; SendEmails.Execute(); Out.Send = new Send { Sent = SendEmails.Out.Sent, Errors = SendEmails.Out.Errors }; } } } ``` Return the given RemindOn date
```c# using Simpler; using System; using Schedules.API.Models; using Schedules.API.Tasks.Reminders; namespace Schedules.API.Tasks.Sending { public class PostRemindersEmailSend : InOutTask<PostRemindersEmailSend.Input, PostRemindersEmailSend.Output> { public class Input { public Send Send { get; set; } } public class Output { public Send Send { get; set; } } public FetchDueReminders FetchDueReminders { get; set; } public SendEmails SendEmails { get; set; } public override void Execute () { FetchDueReminders.In.RemindOn = In.Send.RemindOn; FetchDueReminders.Execute(); SendEmails.In.DueReminders = FetchDueReminders.Out.DueReminders; SendEmails.Execute(); Out.Send = new Send { RemindOn = In.Send.RemindOn, Sent = SendEmails.Out.Sent, Errors = SendEmails.Out.Errors }; } } } ```
38cd315d-ec68-4791-862b-36386d9d4427
{ "language": "C#" }
```c# using System; using System.Diagnostics.Contracts; using System.Globalization; using System.Net.Mail; using System.Net.Mime; using RazorEngine.Text; namespace Essential.Templating.Razor.Email.Helpers { public static class ResourceTemplateHelperExtensions { public static IEncodedString Link(this ResourceTemplateHelper helper, string path, string contentId, string mediaType, TransferEncoding transferEncoding, CultureInfo culture = null) { Contract.Requires<ArgumentNullException>(helper != null); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(path)); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentId)); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(mediaType)); var resource = helper.Get(path, culture); if (resource == null) { var message = string.Format("Resource [{0}] was not found.", contentId); throw new TemplateHelperException(message); } var linkedResource = new LinkedResource(resource, mediaType) { TransferEncoding = transferEncoding }; helper.AddLinkedResource(linkedResource); var renderedResult = new RawString(string.Format("cid:{0}", contentId)); return renderedResult; } } } ``` Store ContentId against the LinkedResource
```c# using System; using System.Diagnostics.Contracts; using System.Globalization; using System.Net.Mail; using System.Net.Mime; using RazorEngine.Text; namespace Essential.Templating.Razor.Email.Helpers { public static class ResourceTemplateHelperExtensions { public static IEncodedString Link(this ResourceTemplateHelper helper, string path, string contentId, string mediaType, TransferEncoding transferEncoding, CultureInfo culture = null) { Contract.Requires<ArgumentNullException>(helper != null); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(path)); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentId)); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(mediaType)); var resource = helper.Get(path, culture); if (resource == null) { var message = string.Format("Resource [{0}] was not found.", contentId); throw new TemplateHelperException(message); } var linkedResource = new LinkedResource(resource, mediaType) { TransferEncoding = transferEncoding, ContentId = contentId }; helper.AddLinkedResource(linkedResource); var renderedResult = new RawString(string.Format("cid:{0}", contentId)); return renderedResult; } } } ```
b7819be1-5a04-4753-bcd5-9581e5ee666a
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using OpenTK.Graphics; namespace osu.Game.Rulesets.Osu.Edit.Masks.SliderMasks.Components { public class SliderBodyPiece : CompositeDrawable { private readonly Slider slider; private readonly SliderBody body; public SliderBodyPiece(Slider slider) { this.slider = slider; InternalChild = body = new SliderBody(slider) { AccentColour = Color4.Transparent, PathWidth = slider.Scale * 64 }; slider.PositionChanged += _ => updatePosition(); } [BackgroundDependencyLoader] private void load(OsuColour colours) { body.BorderColour = colours.Yellow; updatePosition(); } private void updatePosition() => Position = slider.StackedPosition; protected override void Update() { base.Update(); Size = body.Size; OriginPosition = body.PathOffset; // Need to cause one update body.UpdateProgress(0); } } } ``` Update with slider body changes
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using OpenTK.Graphics; namespace osu.Game.Rulesets.Osu.Edit.Masks.SliderMasks.Components { public class SliderBodyPiece : CompositeDrawable { private readonly Slider slider; private readonly SnakingSliderBody body; public SliderBodyPiece(Slider slider) { this.slider = slider; InternalChild = body = new SnakingSliderBody(slider) { AccentColour = Color4.Transparent, PathWidth = slider.Scale * 64 }; slider.PositionChanged += _ => updatePosition(); } [BackgroundDependencyLoader] private void load(OsuColour colours) { body.BorderColour = colours.Yellow; updatePosition(); } private void updatePosition() => Position = slider.StackedPosition; protected override void Update() { base.Update(); Size = body.Size; OriginPosition = body.PathOffset; // Need to cause one update body.UpdateProgress(0); } } } ```
66c6cf60-51f0-4d72-a27c-78b5a04d4bcd
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace AlertRoster.Web.Models { public class Group { [Key] public int Id { get; private set; } [Required, StringLength(25)] public String DisplayName { get; set; } [StringLength(25)] public String PhoneNumber { get; set; } public virtual ICollection<MemberGroup> Members { get; private set; } public virtual ICollection<Message> Messages { get; private set; } // TODO Who are admins? // TODO Reply-mode : Reply-All, Reply-to-Admin, Reject? private Group() { // Parameter-less ctor for EF } public Group(String displayName) { this.DisplayName = displayName; this.Members = new List<MemberGroup>(); this.Messages = new List<Message>(); } } }``` Add reply mode and a shortcut for getting admins
```c# using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace AlertRoster.Web.Models { public class Group { [Key] public int Id { get; private set; } [Required, StringLength(25)] public String DisplayName { get; set; } [StringLength(25)] public String PhoneNumber { get; set; } public virtual ICollection<MemberGroup> Members { get; private set; } public virtual IEnumerable<Member> Admins => Members.Where(_ => _.Role == MemberGroup.GroupRole.Administrator).Select(_ => _.Member); public virtual ICollection<Message> Messages { get; private set; } [Required] public ReplyMode Replies { get; set; } = ReplyMode.ReplyAll; private Group() { // Parameter-less ctor for EF } public Group(String displayName) { this.DisplayName = displayName; this.Members = new List<MemberGroup>(); this.Messages = new List<Message>(); } public enum ReplyMode : byte { ReplyAll = 0, ReplyToAdmins = 1, Reject = 2 } } }```
4470378e-b7b1-4401-8756-2583419c4a36
{ "language": "C#" }
```c# // MvxColorExtensions.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using Cirrious.CrossCore.UI; using MonoTouch.UIKit; namespace Cirrious.MvvmCross.Plugins.Color.Touch { public static class MvxColorExtensions { public static UIColor ToAndroidColor(this MvxColor color) { return MvxTouchColor.ToUIColor(color); } } }``` Fix for native extension method name (not Android!)
```c# // MvxColorExtensions.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using Cirrious.CrossCore.UI; using MonoTouch.UIKit; namespace Cirrious.MvvmCross.Plugins.Color.Touch { public static class MvxColorExtensions { public static UIColor ToNativeColor(this MvxColor color) { return MvxTouchColor.ToUIColor(color); } } }```
6fb2d588-39fa-4c01-9408-73d60463e5e3
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace PS.Mothership.Core.Common.Dto.Merchant { [DataContract] public class OpportunityDto { [DataMember] public Guid OpportunityGuid { get; set; } [DataMember] public string OpportunityLocatorId { get; set; } [DataMember] public Guid ProspectGuid { get; set; } [DataMember] public Guid CustomerGuid { get; set; } [DataMember] public Guid CurrentOfferGuid { get; set; } [DataMember] public Guid PartnerGuid { get; set; } [DataMember] public Guid CurrentStatusTrnGuid { get; set; } [DataMember] public OfferDto CurrentOffer { get; set; } } } ``` Update user info on opportunity.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace PS.Mothership.Core.Common.Dto.Merchant { [DataContract] public class OpportunityDto { [DataMember] public Guid OpportunityGuid { get; set; } [DataMember] public string OpportunityLocatorId { get; set; } [DataMember] public Guid ProspectGuid { get; set; } [DataMember] public Guid CustomerGuid { get; set; } [DataMember] public Guid CurrentOfferGuid { get; set; } [DataMember] public Guid PartnerGuid { get; set; } [DataMember] public Guid CurrentStatusTrnGuid { get; set; } [DataMember] public OfferDto CurrentOffer { get; set; } [DataMember] public Guid UpdateUserGuid { get; set; } [DataMember] public string UpdateUsername { get; set; } [DataMember] public DateTimeOffset UpdateDate { get; set; } } } ```
82334cba-51d0-4f10-afe7-14f96efe4e39
{ "language": "C#" }
```c# using MongoDB.Driver; using Persistence.MongoDB; using SO115App.Models.Classi.Marker; using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti; using SO115App.Models.Servizi.Infrastruttura.Marker; namespace SO115App.Persistence.MongoDB.Marker { public class DeleteChiamataInCorsoByIdUtente : IDeleteChiamataInCorsoByIdUtente { private readonly DbContext _dbContext; private readonly IGetUtenteById _getUtente; public DeleteChiamataInCorsoByIdUtente(DbContext dbContext, IGetUtenteById getUtente) { _dbContext = dbContext; _getUtente = getUtente; } public void Delete(string idUtente) { var utente = _getUtente.GetUtenteByCodice(idUtente); var nominativo = utente.Nome + " " + utente.Cognome; _dbContext.ChiamateInCorsoCollection.DeleteOne(Builders<ChiamateInCorso>.Filter.Eq(x => x.DescrizioneOperatore, nominativo)); } } } ``` Fix - Cancellazione Chiamate In Corso al logout
```c# using MongoDB.Driver; using Persistence.MongoDB; using SO115App.Models.Classi.Marker; using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti; using SO115App.Models.Servizi.Infrastruttura.Marker; namespace SO115App.Persistence.MongoDB.Marker { public class DeleteChiamataInCorsoByIdUtente : IDeleteChiamataInCorsoByIdUtente { private readonly DbContext _dbContext; private readonly IGetUtenteById _getUtente; public DeleteChiamataInCorsoByIdUtente(DbContext dbContext, IGetUtenteById getUtente) { _dbContext = dbContext; _getUtente = getUtente; } public void Delete(string idUtente) { var utente = _getUtente.GetUtenteByCodice(idUtente); var nominativo = utente.Nome + " " + utente.Cognome; _dbContext.ChiamateInCorsoCollection.DeleteMany(Builders<ChiamateInCorso>.Filter.Eq(x => x.DescrizioneOperatore, nominativo)); } } } ```
52e3c33f-fb14-4521-873f-d948f7854aa2
{ "language": "C#" }
```c# using System.Collections.Generic; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models.Editors; using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { /// <summary> /// Represents a media picker property editor. /// </summary> [DataEditor( Constants.PropertyEditors.Aliases.MediaPicker, EditorType.PropertyValue | EditorType.MacroParameter, "Media Picker", "mediapicker", ValueType = ValueTypes.Text, Group = Constants.PropertyEditors.Groups.Media, Icon = Constants.Icons.MediaImage)] public class MediaPickerPropertyEditor : DataEditor { /// <summary> /// Initializes a new instance of the <see cref="MediaPickerPropertyEditor"/> class. /// </summary> public MediaPickerPropertyEditor(ILogger logger) : base(logger) { } /// <inheritdoc /> protected override IConfigurationEditor CreateConfigurationEditor() => new MediaPickerConfigurationEditor(); protected override IDataValueEditor CreateValueEditor() => new MediaPickerPropertyValueEditor(Attribute); internal class MediaPickerPropertyValueEditor : DataValueEditor, IDataValueReference { public MediaPickerPropertyValueEditor(DataEditorAttribute attribute) : base(attribute) { } public IEnumerable<UmbracoEntityReference> GetReferences(object value) { var asString = value is string str ? str : value?.ToString(); if (string.IsNullOrEmpty(asString)) yield break; if (Udi.TryParse(asString, out var udi)) yield return new UmbracoEntityReference(udi); } } } } ``` Handle for multiple picked media relations
```c# using System.Collections.Generic; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models.Editors; using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { /// <summary> /// Represents a media picker property editor. /// </summary> [DataEditor( Constants.PropertyEditors.Aliases.MediaPicker, EditorType.PropertyValue | EditorType.MacroParameter, "Media Picker", "mediapicker", ValueType = ValueTypes.Text, Group = Constants.PropertyEditors.Groups.Media, Icon = Constants.Icons.MediaImage)] public class MediaPickerPropertyEditor : DataEditor { /// <summary> /// Initializes a new instance of the <see cref="MediaPickerPropertyEditor"/> class. /// </summary> public MediaPickerPropertyEditor(ILogger logger) : base(logger) { } /// <inheritdoc /> protected override IConfigurationEditor CreateConfigurationEditor() => new MediaPickerConfigurationEditor(); protected override IDataValueEditor CreateValueEditor() => new MediaPickerPropertyValueEditor(Attribute); internal class MediaPickerPropertyValueEditor : DataValueEditor, IDataValueReference { public MediaPickerPropertyValueEditor(DataEditorAttribute attribute) : base(attribute) { } public IEnumerable<UmbracoEntityReference> GetReferences(object value) { var asString = value is string str ? str : value?.ToString(); if (string.IsNullOrEmpty(asString)) yield break; foreach (var udiStr in asString.Split(',')) { if (Udi.TryParse(udiStr, out var udi)) yield return new UmbracoEntityReference(udi); } } } } } ```
c0d882a7-0a62-4ae3-a439-e61283c9cfc9
{ "language": "C#" }
```c# using System; namespace ChamberLib { public interface IShaderProgram { string Name { get; } void Apply(); void UnApply(); IShaderStage VertexShader { get; } IShaderStage FragmentShader { get; } void SetUniform(string name, bool value); void SetUniform(string name, byte value); void SetUniform(string name, sbyte value); void SetUniform(string name, short value); void SetUniform(string name, ushort value); void SetUniform(string name, int value); void SetUniform(string name, uint value); void SetUniform(string name, float value); void SetUniform(string name, double value); void SetUniform(string name, Vector2 value); void SetUniform(string name, Vector3 value); void SetUniform(string name, Vector4 value); void SetUniform(string name, Matrix value); } } ``` Add the bind attributes property and method to the interface.
```c# using System; using System.Collections.Generic; namespace ChamberLib { public interface IShaderProgram { string Name { get; } void Apply(); void UnApply(); IShaderStage VertexShader { get; } IShaderStage FragmentShader { get; } IEnumerable<string> BindAttributes { get; } void SetBindAttributes(IEnumerable<string> bindattrs); void SetUniform(string name, bool value); void SetUniform(string name, byte value); void SetUniform(string name, sbyte value); void SetUniform(string name, short value); void SetUniform(string name, ushort value); void SetUniform(string name, int value); void SetUniform(string name, uint value); void SetUniform(string name, float value); void SetUniform(string name, double value); void SetUniform(string name, Vector2 value); void SetUniform(string name, Vector3 value); void SetUniform(string name, Vector4 value); void SetUniform(string name, Matrix value); } } ```
2af25663-c267-47c6-9117-3a30eced28a1
{ "language": "C#" }
```c# @using Piranha.Extend; @using Piranha.Manager.Manager; @model Block @foreach(var name in Model.GetFieldNames()) { <div class="form-group"> <label>@name</label> @Html.Editor(name) </div> }``` Split Pascal cased property names into words
```c# @using Piranha.Extend; @using Piranha.Manager.Manager; @using System.Text.RegularExpressions; @model Block @foreach(var name in Model.GetFieldNames()) { var label = Regex.Replace(name, "(\\B[A-Z])", " $1"); <div class="form-group"> <label>@label</label> @Html.Editor(name) </div> }```
e2c6a4bb-03bc-4bf5-a87f-efadfee5f5e3
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using HandlebarsDotNet.Compiler.Lexer; using System.Linq.Expressions; namespace HandlebarsDotNet.Compiler { internal class ExpressionScopeConverter : TokenConverter { public static IEnumerable<object> Convert(IEnumerable<object> sequence) { return new ExpressionScopeConverter().ConvertTokens(sequence).ToList(); } private ExpressionScopeConverter() { } public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence) { var enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) { var item = enumerator.Current; if (item is StartExpressionToken) { var startExpression = item as StartExpressionToken; item = GetNext(enumerator); if ((item is Expression) == false) { throw new HandlebarsCompilerException( string.Format("Token '{0}' could not be converted to an expression", item)); } yield return HandlebarsExpression.Statement( (Expression)item, startExpression.IsEscaped); item = GetNext(enumerator); if ((item is EndExpressionToken) == false) { throw new HandlebarsCompilerException("Handlebars statement was not reduced to a single expression"); } if (((EndExpressionToken)item).IsEscaped != startExpression.IsEscaped) { throw new HandlebarsCompilerException("Starting and ending handleabars do not match"); } } else { yield return item; } } } private static object GetNext(IEnumerator<object> enumerator) { enumerator.MoveNext(); return enumerator.Current; } } } ``` Fix spelling mistake in error message
```c# using System; using System.Collections.Generic; using System.Linq; using HandlebarsDotNet.Compiler.Lexer; using System.Linq.Expressions; namespace HandlebarsDotNet.Compiler { internal class ExpressionScopeConverter : TokenConverter { public static IEnumerable<object> Convert(IEnumerable<object> sequence) { return new ExpressionScopeConverter().ConvertTokens(sequence).ToList(); } private ExpressionScopeConverter() { } public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence) { var enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) { var item = enumerator.Current; if (item is StartExpressionToken) { var startExpression = item as StartExpressionToken; item = GetNext(enumerator); if ((item is Expression) == false) { throw new HandlebarsCompilerException( string.Format("Token '{0}' could not be converted to an expression", item)); } yield return HandlebarsExpression.Statement( (Expression)item, startExpression.IsEscaped); item = GetNext(enumerator); if ((item is EndExpressionToken) == false) { throw new HandlebarsCompilerException("Handlebars statement was not reduced to a single expression"); } if (((EndExpressionToken)item).IsEscaped != startExpression.IsEscaped) { throw new HandlebarsCompilerException("Starting and ending handlebars do not match"); } } else { yield return item; } } } private static object GetNext(IEnumerator<object> enumerator) { enumerator.MoveNext(); return enumerator.Current; } } } ```
7394b0dc-dab5-4bc6-8e36-b1aa41594853
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using TestObjectBuilder; namespace TestObjectBuilderTests.Tests { public class TestObjectBuilderBuilderTests { [TestFixture] public class CreateNewObject { [Test] public void CreatesProductWithoutPropertiesAndAZeroArgConstructor() { // Arrange ITestObjBuilder<ProductWithoutProperties> builder = TestObjectBuilderBuilder<ProductWithoutProperties>.CreateNewObject(); // Act ProductWithoutProperties product = builder.Build(); // Assert Assert.NotNull(product); } } } } ``` Replace first TestObjectBuilderBuilder unit test with two tests to make the tests less brittle.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using TestObjectBuilder; namespace TestObjectBuilderTests.Tests { public class TestObjectBuilderBuilderTests { [TestFixture] public class CreateNewObject { [Test] public void ProductBuilderCreateBuildsObjectsOfTypeProduct() { // Arrange // Act ITestObjBuilder<ProductWithoutProperties> builder = TestObjectBuilderBuilder<ProductWithoutProperties>.CreateNewObject(); // Assert Assert.AreSame(typeof(ProductWithoutProperties), builder.GetType().GetMethod("Build").ReturnType); } [Test] public void ProductBuilderHasNoPropertiesWhenProductHasNoProperties() { // Arrange // Act ITestObjBuilder<ProductWithoutProperties> builder = TestObjectBuilderBuilder<ProductWithoutProperties>.CreateNewObject(); // Assert Assert.AreEqual(0, builder.GetType().GetProperties().Count()); } } } } ```
cbeeaa15-eb10-431d-b5b1-dfb6798ae862
{ "language": "C#" }
```c# using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGameUtils.Diagnostics; namespace PCGame.GameComponents { public class UIFPSCounter : DrawableGameComponent { private FPSCounter _fpsCounter = new FPSCounter(); private SpriteBatch _spriteBatch; private SpriteFont _font; private Vector2 _topLeftPoint; private Vector2 _avgFPSLocation; private readonly Color _fontColor = Color.Black; public UIFPSCounter(Game game, SpriteFont font, Vector2 topLeftPoint, SpriteBatch spriteBatch) : base(game) { _spriteBatch = spriteBatch; _font = font; _topLeftPoint = topLeftPoint; _avgFPSLocation = Vector2.Add(_topLeftPoint, new Vector2(0, 20)); } public override void Update(GameTime gameTime) { _fpsCounter.Update(gameTime); base.Update(gameTime); } public override void Draw(GameTime gameTime) { _spriteBatch.DrawString(_font, "Current FPS: " + _fpsCounter.CurrentFPS, _topLeftPoint, _fontColor); _spriteBatch.DrawString(_font, "Avg FPS: " + _fpsCounter.AverageFPS, _avgFPSLocation, _fontColor); base.Draw(gameTime); } } } ``` Fix incorrect namespace for UI component.
```c# using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGameUtils.Diagnostics; namespace MonoGameUtils.UI.GameComponents { public class UIFPSCounter : DrawableGameComponent { private FPSCounter _fpsCounter = new FPSCounter(); private SpriteBatch _spriteBatch; private SpriteFont _font; private Vector2 _topLeftPoint; private Vector2 _avgFPSLocation; private readonly Color _fontColor = Color.Black; public UIFPSCounter(Game game, SpriteFont font, Vector2 topLeftPoint, SpriteBatch spriteBatch) : base(game) { _spriteBatch = spriteBatch; _font = font; _topLeftPoint = topLeftPoint; _avgFPSLocation = Vector2.Add(_topLeftPoint, new Vector2(0, 20)); } public override void Update(GameTime gameTime) { _fpsCounter.Update(gameTime); base.Update(gameTime); } public override void Draw(GameTime gameTime) { _spriteBatch.DrawString(_font, "Current FPS: " + _fpsCounter.CurrentFPS, _topLeftPoint, _fontColor); _spriteBatch.DrawString(_font, "Avg FPS: " + _fpsCounter.AverageFPS, _avgFPSLocation, _fontColor); base.Draw(gameTime); } } } ```
bb92261c-66ce-45e5-ac03-4137ac35ac6c
{ "language": "C#" }
```c# using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Net.Sockets; using System.Threading.Tasks; namespace RebirthTracker.PacketHandlers { /// <summary> /// Request a game host try a hole punch /// </summary> [Opcode(26)] public class HolePunchPacketHandler : IPacketHandler { /// <summary> /// Constructor called through reflection in PacketHandlerFactory /// </summary> public HolePunchPacketHandler() { } /// <summary> /// Handle the packet /// </summary> public async Task Handle(UdpReceiveResult result) { var peer = result.RemoteEndPoint; await Logger.Log("Hole Punch").ConfigureAwait(false); ushort gameID = BitConverter.ToUInt16(result.Buffer, 1); await Logger.Log($"Got Game ID {gameID}"); Game game; using (var db = new GameContext()) { game = (await db.Games.Where(x => x.ID == gameID).ToListAsync().ConfigureAwait(false)).FirstOrDefault(); } Packet packet; if (game != null) { packet = new Packet(26, $"{peer.Address}/{peer.Port}"); await packet.Send(Globals.MainClient, game.Endpoint).ConfigureAwait(false); return; } packet = new Packet(27, gameID); await packet.Send(Globals.MainClient, peer).ConfigureAwait(false); } } } ``` Add additional hole punch logging
```c# using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Net.Sockets; using System.Threading.Tasks; namespace RebirthTracker.PacketHandlers { /// <summary> /// Request a game host try a hole punch /// </summary> [Opcode(26)] public class HolePunchPacketHandler : IPacketHandler { /// <summary> /// Constructor called through reflection in PacketHandlerFactory /// </summary> public HolePunchPacketHandler() { } /// <summary> /// Handle the packet /// </summary> public async Task Handle(UdpReceiveResult result) { var peer = result.RemoteEndPoint; await Logger.Log("Hole Punch").ConfigureAwait(false); ushort gameID = BitConverter.ToUInt16(result.Buffer, 1); await Logger.Log($"Got Game ID {gameID}").ConfigureAwait(false); Game game; using (var db = new GameContext()) { game = (await db.Games.Where(x => x.ID == gameID).ToListAsync().ConfigureAwait(false)).FirstOrDefault(); } Packet packet; if (game != null) { await Logger.Log("Sending hole punch packet").ConfigureAwait(false); packet = new Packet(26, $"{peer.Address}/{peer.Port}"); await packet.Send(Globals.MainClient, game.Endpoint).ConfigureAwait(false); return; } await Logger.Log("Couldn't fetch game").ConfigureAwait(false); packet = new Packet(27, gameID); await packet.Send(Globals.MainClient, peer).ConfigureAwait(false); } } } ```
c67d6181-861e-4d94-87f9-41a1738af751
{ "language": "C#" }
```c# namespace TraktApiSharp.Tests.Experimental.Requests.Calendars { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Calendars; using TraktApiSharp.Objects.Get.Calendars; [TestClass] public class TraktCalendarAllDVDMoviesRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsNotAbstract() { typeof(TraktCalendarAllDVDMoviesRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsSealed() { typeof(TraktCalendarAllDVDMoviesRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsSubclassOfATraktCalendarAllRequest() { typeof(TraktCalendarAllDVDMoviesRequest).IsSubclassOf(typeof(ATraktCalendarAllRequest<TraktCalendarMovie>)).Should().BeTrue(); } } } ``` Make sure that authorization of TraktCalendarAllDVDMoviesRequest is not required
```c# namespace TraktApiSharp.Tests.Experimental.Requests.Calendars { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Calendars; using TraktApiSharp.Objects.Get.Calendars; using TraktApiSharp.Requests; [TestClass] public class TraktCalendarAllDVDMoviesRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsNotAbstract() { typeof(TraktCalendarAllDVDMoviesRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsSealed() { typeof(TraktCalendarAllDVDMoviesRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsSubclassOfATraktCalendarAllRequest() { typeof(TraktCalendarAllDVDMoviesRequest).IsSubclassOf(typeof(ATraktCalendarAllRequest<TraktCalendarMovie>)).Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestHasAuthorizationNotRequired() { var request = new TraktCalendarAllDVDMoviesRequest(null); request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.NotRequired); } } } ```
e47bca97-6d95-4b8d-9626-dee5e0466507
{ "language": "C#" }
```c# @using ForumModels; @{ string usersFile = Server.MapPath("~/App_Data/users.json"); var userList = new UserList(usersFile); } <table class="table"> <thead> <tr class="lead"> <th></th> <th>Name</th> <th>MSDN Name</th> <th>StackOverflow ID</th> </tr> </thead> @{int count = 0; } @foreach (var user in userList.Users) { count++; <tr class="lead"> <td>@count</td> <td>@user.Name</td> <td><a href="https://social.msdn.microsoft.com/Profile/@user.MSDNName/activity">@user.MSDNName</a></td> <td><a href="http://stackoverflow.com/users/@user.StackOverflowID?tab=reputation">@user.StackOverflowID</a></td> </tr> } </table> ``` Add user photo to users list
```c# @using ForumModels; @{ string usersFile = Server.MapPath("~/App_Data/users.json"); var userList = new UserList(usersFile); } <table class="table"> <thead> <tr class="lead"> <th></th> <th></th> <th>Name</th> <th>MSDN Name</th> <th>StackOverflow ID</th> </tr> </thead> @{int count = 0; } @foreach (var user in userList.Users) { count++; <tr class="lead"> <td width="20px">@count</td> <td width="20px"><img src="https://i1.social.s-msft.com/profile/u/avatar.jpg?displayname=@user.MSDNName" /></td> <td>@user.Name</td> <td><a href="https://social.msdn.microsoft.com/Profile/@user.MSDNName/activity">@user.MSDNName</a></td> <td><a href="http://stackoverflow.com/users/@user.StackOverflowID?tab=reputation">@user.StackOverflowID</a></td> </tr> } </table> ```
c74e97ad-371f-438d-8d1f-74c6100cec65
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Components; namespace osu.Game.Screens.OnlinePlay.Playlists { public class PlaylistsReadyButton : ReadyButton { [Resolved(typeof(Room), nameof(Room.EndDate))] private Bindable<DateTimeOffset?> endDate { get; set; } [Resolved] private IBindable<WorkingBeatmap> gameBeatmap { get; set; } public PlaylistsReadyButton() { Text = "Start"; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Green; Triangles.ColourDark = colours.Green; Triangles.ColourLight = colours.GreenLight; } protected override void Update() { base.Update(); Enabled.Value = endDate.Value != null && DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(gameBeatmap.Value.Track.Length) < endDate.Value; } } } ``` Disable playlist start button when attempts have been exhausted
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Components; namespace osu.Game.Screens.OnlinePlay.Playlists { public class PlaylistsReadyButton : ReadyButton { [Resolved(typeof(Room), nameof(Room.EndDate))] private Bindable<DateTimeOffset?> endDate { get; set; } [Resolved] private IBindable<WorkingBeatmap> gameBeatmap { get; set; } public PlaylistsReadyButton() { Text = "Start"; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Green; Triangles.ColourDark = colours.Green; Triangles.ColourLight = colours.GreenLight; } private bool hasRemainingAttempts = true; protected override void LoadComplete() { base.LoadComplete(); userScore.BindValueChanged(aggregate => { if (maxAttempts.Value == null) return; int remaining = maxAttempts.Value.Value - aggregate.NewValue.PlaylistItemAttempts.Sum(a => a.Attempts); hasRemainingAttempts = remaining > 0; }); } protected override void Update() { base.Update(); Enabled.Value = hasRemainingAttempts && enoughTimeLeft; } private bool enoughTimeLeft => // This should probably consider the length of the currently selected item, rather than a constant 30 seconds. endDate.Value != null && DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(gameBeatmap.Value.Track.Length) < endDate.Value; } } ```
8ac1e926-baa7-43f2-846c-f3d0b57b4018
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System.Diagnostics; namespace osu.Framework.Extensions.ObjectExtensions { /// <summary> /// Extensions that apply to all objects. /// </summary> public static class ObjectExtensions { /// <summary> /// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>". /// </summary> /// <remarks> /// This should only be used when an assertion or other handling is not a reasonable alternative. /// </remarks> /// <param name="obj">The nullable object.</param> /// <typeparam name="T">The type of the object.</typeparam> /// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns> public static T AsNonNull<T>(this T? obj) where T : class { Debug.Assert(obj != null); return obj; } /// <summary> /// If the given object is null. /// </summary> public static bool IsNull<T>(this T obj) => ReferenceEquals(obj, null); /// <summary> /// <c>true</c> if the given object is not null, <c>false</c> otherwise. /// </summary> public static bool IsNotNull<T>(this T obj) => !ReferenceEquals(obj, null); } } ``` Annotate return value for consumers
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace osu.Framework.Extensions.ObjectExtensions { /// <summary> /// Extensions that apply to all objects. /// </summary> public static class ObjectExtensions { /// <summary> /// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>". /// </summary> /// <remarks> /// This should only be used when an assertion or other handling is not a reasonable alternative. /// </remarks> /// <param name="obj">The nullable object.</param> /// <typeparam name="T">The type of the object.</typeparam> /// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns> public static T AsNonNull<T>(this T? obj) where T : class { Debug.Assert(obj != null); return obj; } /// <summary> /// If the given object is null. /// </summary> public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null); /// <summary> /// <c>true</c> if the given object is not null, <c>false</c> otherwise. /// </summary> public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null); } } ```
9fbb37fb-aed6-497c-a6eb-2588c4fdfdf7
{ "language": "C#" }
```c# using System; using Baseline; namespace Marten.Testing { public class ConnectionSource : ConnectionFactory { public static readonly string ConnectionString = Environment.GetEnvironmentVariable("marten_testing_database"); static ConnectionSource() { if (ConnectionString.IsEmpty()) throw new Exception( "You need to set the connection string for your local Postgresql database in the environment variable 'marten-testing-database'"); } public ConnectionSource() : base(ConnectionString) { } } }``` Correct error message for missing test connection string
```c# using System; namespace Marten.Testing { public class ConnectionSource : ConnectionFactory { public static readonly string ConnectionString = Environment.GetEnvironmentVariable("marten_testing_database"); static ConnectionSource() { if (ConnectionString.IsEmpty()) throw new Exception( "You need to set the connection string for your local Postgresql database in the environment variable 'marten_testing_database'"); } public ConnectionSource() : base(ConnectionString) { } } }```
3925f09d-a70d-43af-9abe-977bf90c2b41
{ "language": "C#" }
```c# using Harmony; using LunaClient.Systems.Lock; using LunaCommon.Enums; using System.Collections.Generic; // ReSharper disable All namespace LunaClient.Harmony { /// <summary> /// This harmony patch is intended to override the "FindVesselsLandedAt" that sometimes is called to check if there are vessels in a launch site /// We just remove the other controlled vessels from that check and set them correctly /// </summary> [HarmonyPatch(typeof(ShipConstruction))] [HarmonyPatch("FindVesselsLandedAt")] [HarmonyPatch(new[] { typeof(FlightState), typeof(string) })] public class ShipConstruction_FindVesselsLandedAt { private static readonly List<ProtoVessel> ProtoVesselsToRemove = new List<ProtoVessel>(); [HarmonyPostfix] private static void PostfixFindVesselsLandedAt(List<ProtoVessel> __result) { if (MainSystem.NetworkState < ClientState.Connected) return; ProtoVesselsToRemove.Clear(); foreach (var pv in __result) { if (!LockSystem.LockQuery.ControlLockExists(pv.vesselID)) ProtoVesselsToRemove.Add(pv); } foreach (var pv in ProtoVesselsToRemove) { __result.Remove(pv); } } } } ``` Fix find vessels landed at
```c# using Harmony; using LunaClient.Systems.Lock; using LunaCommon.Enums; using System.Collections.Generic; // ReSharper disable All namespace LunaClient.Harmony { /// <summary> /// This harmony patch is intended to override the "FindVesselsLandedAt" that sometimes is called to check if there are vessels in a launch site /// We just remove the other controlled vessels from that check and set them correctly /// </summary> [HarmonyPatch(typeof(ShipConstruction))] [HarmonyPatch("FindVesselsLandedAt")] [HarmonyPatch(new[] { typeof(FlightState), typeof(string) })] public class ShipConstruction_FindVesselsLandedAt { private static readonly List<ProtoVessel> ProtoVesselsToRemove = new List<ProtoVessel>(); [HarmonyPostfix] private static void PostfixFindVesselsLandedAt(List<ProtoVessel> __result) { if (MainSystem.NetworkState < ClientState.Connected) return; ProtoVesselsToRemove.Clear(); foreach (var pv in __result) { if (LockSystem.LockQuery.ControlLockExists(pv.vesselID)) ProtoVesselsToRemove.Add(pv); } foreach (var pv in ProtoVesselsToRemove) { __result.Remove(pv); } } } } ```
bbd00a08-0516-417e-a5b0-039a7ca84a4d
{ "language": "C#" }
```c# // Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Runtime.CompilerServices; namespace Draw2D.Core { public abstract class ObservableObject : INotifyPropertyChanged { public bool IsDirty { get; set; } public event PropertyChangedEventHandler PropertyChanged; public void Notify([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public bool Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (!Equals(field, value)) { field = value; IsDirty = true; Notify(propertyName); return true; } return false; } } } ``` Mark IsDirty property as internal
```c# // Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Runtime.CompilerServices; namespace Draw2D.Core { public abstract class ObservableObject : INotifyPropertyChanged { internal bool IsDirty { get; set; } public event PropertyChangedEventHandler PropertyChanged; public void Notify([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public bool Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (!Equals(field, value)) { field = value; IsDirty = true; Notify(propertyName); return true; } return false; } } } ```
d70e1ca6-c437-4dd8-8309-8201b62d1608
{ "language": "C#" }
```c# using System.Data.Entity; namespace food_tracker { public class TrackerContext : DbContext { public TrackerContext() : base("name=NutritionTrackerContext") { Configuration.LazyLoadingEnabled = false; this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); } public DbSet<WholeDay> Days { get; set; } public DbSet<NutritionItem> Nutrition { get; set; } } } ``` Change back to use the default database name.
```c# using System.Data.Entity; namespace food_tracker { public class TrackerContext : DbContext { public TrackerContext() : base() { Configuration.LazyLoadingEnabled = false; this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); } public DbSet<WholeDay> Days { get; set; } public DbSet<NutritionItem> Nutrition { get; set; } } } ```
25b6c1f5-f676-4e88-80a6-982d3724d55b
{ "language": "C#" }
```c# namespace Bakery.Processes { using Specification.Builder; using System; using System.Text; using System.Threading.Tasks; using Xunit; public class SystemDiagnosticsProcessTests { [Fact] public async Task EchoWithCombinedOutput() { var processSpecification = ProcessSpecificationBuilder.Create() .WithProgram(@"echo") .WithArguments("a", "b", "c") .WithEnvironment() .WithCombinedOutput() .Build(); var processFactory = new ProcessFactory(); var process = processFactory.Start(processSpecification); var stringBuilder = new StringBuilder(); await process.WaitForExit(TimeSpan.FromSeconds(5)); while (true) { var output = await process.TryReadAsync(TimeSpan.FromSeconds(1)); if (output == null) break; stringBuilder.Append(output.Text); } var totalOutput = stringBuilder.ToString(); Assert.Equal("a b c", totalOutput); } } } ``` Update tests re: process builder, etc.
```c# namespace Bakery.Processes { using System; using System.Text; using System.Threading.Tasks; using Xunit; public class SystemDiagnosticsProcessTests { [Fact] public async Task EchoWithCombinedOutput() { var process = await new ProcessFactory().RunAsync(builder => { return builder .WithProgram("echo") .WithArguments("a", "b", "c") .WithEnvironment() .WithCombinedOutput() .Build(); }); var stringBuilder = new StringBuilder(); while (true) { var output = await process.TryReadAsync(TimeSpan.FromSeconds(1)); if (output == null) break; stringBuilder.Append(output.Text); } var totalOutput = stringBuilder.ToString(); Assert.Equal("a b c", totalOutput); } } } ```
1b81c7be-050a-45c5-b2c3-ca13f299c18f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Cake.Core.Diagnostics; namespace Cake.Arguments { /// <summary> /// Responsible for parsing <see cref="Verbosity"/>. /// </summary> internal sealed class VerbosityParser { private readonly Dictionary<string, Verbosity> _lookup; /// <summary> /// Initializes a new instance of the <see cref="VerbosityParser"/> class. /// </summary> public VerbosityParser() { _lookup = new Dictionary<string, Verbosity>(StringComparer.OrdinalIgnoreCase) { { "q", Verbosity.Quiet }, { "quiet", Verbosity.Quiet }, { "m", Verbosity.Minimal }, { "minimal", Verbosity.Minimal }, { "n", Verbosity.Normal }, { "normal", Verbosity.Normal }, { "v", Verbosity.Verbose }, { "verbose", Verbosity.Verbose }, { "d", Verbosity.Diagnostic }, { "diagnostic", Verbosity.Diagnostic } }; } /// <summary> /// Parses the provided string to a <see cref="Verbosity"/>. /// </summary> /// <param name="value">The string to parse.</param> /// <returns>The verbosity.</returns> public Verbosity Parse(string value) { Verbosity verbosity; if (_lookup.TryGetValue(value, out verbosity)) { return verbosity; } const string format = "The value '{0}' is not a valid verbosity."; var message = string.Format(format, value ?? string.Empty); throw new InvalidOperationException(message); } } }``` Add invariant IFormatterProvider to avoid issues based on user local
```c# using System; using System.Collections.Generic; using System.Globalization; using Cake.Core.Diagnostics; namespace Cake.Arguments { /// <summary> /// Responsible for parsing <see cref="Verbosity"/>. /// </summary> internal sealed class VerbosityParser { private readonly Dictionary<string, Verbosity> _lookup; /// <summary> /// Initializes a new instance of the <see cref="VerbosityParser"/> class. /// </summary> public VerbosityParser() { _lookup = new Dictionary<string, Verbosity>(StringComparer.OrdinalIgnoreCase) { { "q", Verbosity.Quiet }, { "quiet", Verbosity.Quiet }, { "m", Verbosity.Minimal }, { "minimal", Verbosity.Minimal }, { "n", Verbosity.Normal }, { "normal", Verbosity.Normal }, { "v", Verbosity.Verbose }, { "verbose", Verbosity.Verbose }, { "d", Verbosity.Diagnostic }, { "diagnostic", Verbosity.Diagnostic } }; } /// <summary> /// Parses the provided string to a <see cref="Verbosity"/>. /// </summary> /// <param name="value">The string to parse.</param> /// <returns>The verbosity.</returns> public Verbosity Parse(string value) { Verbosity verbosity; if (_lookup.TryGetValue(value, out verbosity)) { return verbosity; } const string format = "The value '{0}' is not a valid verbosity."; var message = string.Format(CultureInfo.InvariantCulture, format, value); throw new InvalidOperationException(message); } } }```
c56d0e1c-1e85-4e85-8a25-8634bc2aab55
{ "language": "C#" }
```c# namespace TraktApiSharp.Services { using Authentication; using System; /// <summary>Provides helper methods for serializing and deserializing Trakt objects.</summary> public static class TraktSerializationService { public static string Serialize(TraktAuthorization authorization) { if (authorization == null) throw new ArgumentNullException(nameof(authorization), "authorization must not be null"); return string.Empty; } public static TraktAuthorization Deserialize(string authorization) { return null; } } } ``` Add implementation for serializing TraktAuthorization.
```c# namespace TraktApiSharp.Services { using Authentication; using Extensions; using System; using Utils; /// <summary>Provides helper methods for serializing and deserializing Trakt objects.</summary> public static class TraktSerializationService { /// <summary>Serializes an <see cref="TraktAuthorization" /> instance to a Json string.</summary> /// <param name="authorization">The authorization information, which should be serialized.</param> /// <returns>A Json string, containing all properties of the given authorization.</returns> /// <exception cref="ArgumentNullException">Thrown, if the given authorization is null.</exception> public static string Serialize(TraktAuthorization authorization) { if (authorization == null) throw new ArgumentNullException(nameof(authorization), "authorization must not be null"); var anonymousAuthorization = new { AccessToken = authorization.AccessToken, RefreshToken = authorization.RefreshToken, ExpiresIn = authorization.ExpiresIn, Scope = authorization.AccessScope.ObjectName, TokenType = authorization.TokenType.ObjectName, CreatedAt = authorization.Created.ToTraktLongDateTimeString(), IgnoreExpiration = authorization.IgnoreExpiration }; return Json.Serialize(anonymousAuthorization); } public static TraktAuthorization Deserialize(string authorization) { return null; } } } ```
0785694a-c9b9-4508-8557-3b6c3f5d741f
{ "language": "C#" }
```c# using IIUWr.Fereol.Common; using IIUWr.Fereol.Interface; using IIUWr.ViewModels.Fereol; using LionCub.Patterns.DependencyInjection; using System; using HTMLParsing = IIUWr.Fereol.HTMLParsing; namespace IIUWr { public static class ConfigureIoC { public static void All() { #if DEBUG IoC.AsInstance(new Uri(@"http://192.168.1.150:8002/")); #else IoC.AsInstance(new Uri(@"https://zapisy.ii.uni.wroc.pl/")); #endif ViewModels(); Fereol.Common(); Fereol.HTMLParsing(); } public static void ViewModels() { IoC.AsSingleton<SemestersViewModel>(); IoC.PerRequest<SemesterViewModel>(); IoC.PerRequest<CourseViewModel>(); IoC.PerRequest<TutorialViewModel>(); } public static class Fereol { public static void Common() { IoC.AsSingleton<ICredentialsManager, CredentialsManager>(); IoC.AsSingleton<ISessionManager, CredentialsManager>(); } public static void HTMLParsing() { IoC.AsSingleton<IConnection, HTMLParsing.Connection>(); IoC.AsSingleton<HTMLParsing.Interface.IHTTPConnection, HTMLParsing.Connection>(); IoC.AsSingleton<ICoursesService, HTMLParsing.CoursesService>(); } } } } ``` Remove not needed IoC registrations
```c# using IIUWr.Fereol.Common; using IIUWr.Fereol.Interface; using IIUWr.ViewModels.Fereol; using LionCub.Patterns.DependencyInjection; using System; using HTMLParsing = IIUWr.Fereol.HTMLParsing; namespace IIUWr { public static class ConfigureIoC { public static void All() { #if DEBUG IoC.AsInstance(new Uri(@"http://192.168.1.150:8002/")); #else IoC.AsInstance(new Uri(@"https://zapisy.ii.uni.wroc.pl/")); #endif ViewModels(); Fereol.Common(); Fereol.HTMLParsing(); } public static void ViewModels() { IoC.AsSingleton<SemestersViewModel>(); } public static class Fereol { public static void Common() { IoC.AsSingleton<ICredentialsManager, CredentialsManager>(); IoC.AsSingleton<ISessionManager, CredentialsManager>(); } public static void HTMLParsing() { IoC.AsSingleton<IConnection, HTMLParsing.Connection>(); IoC.AsSingleton<HTMLParsing.Interface.IHTTPConnection, HTMLParsing.Connection>(); IoC.AsSingleton<ICoursesService, HTMLParsing.CoursesService>(); } } } } ```
f33ea74d-ac5e-495d-b14d-b67f2ebe9f6e
{ "language": "C#" }
```c# using NBi.Core.Structure; using NBi.Core.Structure.Olap; using NBi.Core.Structure.Relational; using NBi.Core.Structure.Tabular; using NUnit.Framework; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace NBi.Testing.Integration.Core.Structure { public class StructureDiscoveryFactoryProviderTest { private class FakeStructureDiscoveryFactoryProvider : StructureDiscoveryFactoryProvider { public new string InquireFurtherAnalysisService(string connectionString) { return base.InquireFurtherAnalysisService(connectionString); } } [Test] [Category("Olap")] public void InquireFurtherAnalysisService_Multidimensional_ReturnCorrectServerMode() { var connectionString = ConnectionStringReader.GetAdomd(); var provider = new FakeStructureDiscoveryFactoryProvider(); var serverMode = provider.InquireFurtherAnalysisService(connectionString); Assert.That(serverMode, Is.EqualTo("olap")); } [Test] [Category("Tabular")] public void InquireFurtherAnalysisService_Tabular_ReturnCorrectServerMode() { var connectionString = ConnectionStringReader.GetAdomdTabular(); var provider = new FakeStructureDiscoveryFactoryProvider(); var serverMode = provider.InquireFurtherAnalysisService(connectionString); Assert.That(serverMode, Is.EqualTo("tabular")); } } } ``` Fix category for a test about tabular structure
```c# using NBi.Core.Structure; using NBi.Core.Structure.Olap; using NBi.Core.Structure.Relational; using NBi.Core.Structure.Tabular; using NUnit.Framework; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace NBi.Testing.Integration.Core.Structure { public class StructureDiscoveryFactoryProviderTest { private class FakeStructureDiscoveryFactoryProvider : StructureDiscoveryFactoryProvider { public new string InquireFurtherAnalysisService(string connectionString) { return base.InquireFurtherAnalysisService(connectionString); } } [Test] [Category("Olap")] public void InquireFurtherAnalysisService_Multidimensional_ReturnCorrectServerMode() { var connectionString = ConnectionStringReader.GetAdomd(); var provider = new FakeStructureDiscoveryFactoryProvider(); var serverMode = provider.InquireFurtherAnalysisService(connectionString); Assert.That(serverMode, Is.EqualTo("olap")); } [Test] [Category("Olap")] public void InquireFurtherAnalysisService_Tabular_ReturnCorrectServerMode() { var connectionString = ConnectionStringReader.GetAdomdTabular(); var provider = new FakeStructureDiscoveryFactoryProvider(); var serverMode = provider.InquireFurtherAnalysisService(connectionString); Assert.That(serverMode, Is.EqualTo("tabular")); } } } ```
da00bd2a-c133-47f8-993d-754e2a96f776
{ "language": "C#" }
```c# using SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account; namespace SFA.DAS.EmployerApprenticeshipsService.Web.Models { public class UserAccountsViewModel { public Accounts Accounts; public int Invitations; public string SuccessMessage; } }``` Change user accounts view model to use the new viewmodel for displaying SuccessMessage
```c# using SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account; namespace SFA.DAS.EmployerApprenticeshipsService.Web.Models { public class UserAccountsViewModel { public Accounts Accounts; public int Invitations; public SuccessMessageViewModel SuccessMessage; } }```
9441fcc7-e89b-4e74-89fc-b59d40b7996e
{ "language": "C#" }
```c# /* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // 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. // /* ------------------------------------------------------------------------- */ using Cube.Mixin.Drawing; namespace Cube.Xui.Converters { /* --------------------------------------------------------------------- */ /// /// ImageConverter /// /// <summary> /// Provides functionality to convert from an Image object to /// a BitmapImage object. /// </summary> /// /* --------------------------------------------------------------------- */ public class ImageConverter : SimplexConverter { /* ----------------------------------------------------------------- */ /// /// ImageValueConverter /// /// <summary> /// Initializes a new instance of the ImageConverter class. /// </summary> /// /* ----------------------------------------------------------------- */ public ImageConverter() : base(e => { var src = e is System.Drawing.Image image ? image : e is System.Drawing.Icon icon ? icon.ToBitmap() : null; return src.ToBitmapImage(); }) { } } } ``` Fix to dispose when the specified object is Icon.
```c# /* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // 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. // /* ------------------------------------------------------------------------- */ using Cube.Mixin.Drawing; namespace Cube.Xui.Converters { /* --------------------------------------------------------------------- */ /// /// ImageConverter /// /// <summary> /// Provides functionality to convert from an Image object to /// a BitmapImage object. /// </summary> /// /* --------------------------------------------------------------------- */ public class ImageConverter : SimplexConverter { /* ----------------------------------------------------------------- */ /// /// ImageValueConverter /// /// <summary> /// Initializes a new instance of the ImageConverter class. /// </summary> /// /* ----------------------------------------------------------------- */ public ImageConverter() : base(e => { if (e is System.Drawing.Image i0) return i0.ToBitmapImage(false); if (e is System.Drawing.Icon i1) return i1.ToBitmap().ToBitmapImage(true); return null; }) { } } } ```
d67620fc-9164-43fd-a353-e16ebbe0e54d
{ "language": "C#" }
```c# using System; using System.ComponentModel.Composition.Hosting; using System.Reflection; using MuffinFramework.Muffin; using MuffinFramework.Platform; using MuffinFramework.Service; namespace MuffinFramework { public class MuffinClient : IDisposable { private readonly object _lockObj = new object(); public bool IsStarted { get; private set; } public AggregateCatalog Catalog { get; private set; } public PlatformLoader PlatformLoader { get; private set; } public ServiceLoader ServiceLoader { get; private set; } public MuffinLoader MuffinLoader { get; private set; } public MuffinClient() { Catalog = new AggregateCatalog(); Catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetCallingAssembly())); PlatformLoader = new PlatformLoader(); ServiceLoader = new ServiceLoader(); MuffinLoader = new MuffinLoader(); } public void Start() { lock (_lockObj) { if (IsStarted) throw new InvalidOperationException("MuffinClient has already been started."); IsStarted = true; } PlatformLoader.Enable(Catalog, new PlatformArgs(PlatformLoader)); ServiceLoader.Enable(Catalog, new ServiceArgs(PlatformLoader, ServiceLoader)); MuffinLoader.Enable(Catalog, new MuffinArgs(PlatformLoader, ServiceLoader, MuffinLoader)); } public virtual void Dispose() { Catalog.Dispose(); PlatformLoader.Dispose(); ServiceLoader.Dispose(); MuffinLoader.Dispose(); } } }``` Change the order Loaders are disposed
```c# using System; using System.ComponentModel.Composition.Hosting; using System.Reflection; using MuffinFramework.Muffin; using MuffinFramework.Platform; using MuffinFramework.Service; namespace MuffinFramework { public class MuffinClient : IDisposable { private readonly object _lockObj = new object(); public bool IsStarted { get; private set; } public AggregateCatalog Catalog { get; private set; } public PlatformLoader PlatformLoader { get; private set; } public ServiceLoader ServiceLoader { get; private set; } public MuffinLoader MuffinLoader { get; private set; } public MuffinClient() { Catalog = new AggregateCatalog(); Catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetCallingAssembly())); PlatformLoader = new PlatformLoader(); ServiceLoader = new ServiceLoader(); MuffinLoader = new MuffinLoader(); } public void Start() { lock (_lockObj) { if (IsStarted) throw new InvalidOperationException("MuffinClient has already been started."); IsStarted = true; } PlatformLoader.Enable(Catalog, new PlatformArgs(PlatformLoader)); ServiceLoader.Enable(Catalog, new ServiceArgs(PlatformLoader, ServiceLoader)); MuffinLoader.Enable(Catalog, new MuffinArgs(PlatformLoader, ServiceLoader, MuffinLoader)); } public virtual void Dispose() { MuffinLoader.Dispose(); ServiceLoader.Dispose(); PlatformLoader.Dispose(); Catalog.Dispose(); } } }```
15a87901-225b-47a6-9088-dd0fd9e198aa
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using OpenTK; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts { /// <summary> /// Represents a part of the summary timeline.. /// </summary> internal abstract class TimelinePart : CompositeDrawable { public Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>(); private readonly Container timeline; protected TimelinePart() { AddInternal(timeline = new Container { RelativeSizeAxes = Axes.Both }); Beatmap.ValueChanged += b => { timeline.RelativeChildSize = new Vector2((float)Math.Max(1, b.Track.Length), 1); LoadBeatmap(b); }; } protected void Add(Drawable visualisation) => timeline.Add(visualisation); protected virtual void LoadBeatmap(WorkingBeatmap beatmap) { timeline.Clear(); } } } ``` Fix timeline sizes being updated potentially before the track has a length
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using OpenTK; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts { /// <summary> /// Represents a part of the summary timeline.. /// </summary> internal abstract class TimelinePart : CompositeDrawable { public Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>(); private readonly Container timeline; protected TimelinePart() { AddInternal(timeline = new Container { RelativeSizeAxes = Axes.Both }); Beatmap.ValueChanged += b => { updateRelativeChildSize(); LoadBeatmap(b); }; } private void updateRelativeChildSize() { if (!Beatmap.Value.TrackLoaded) { timeline.RelativeChildSize = Vector2.One; return; } var track = Beatmap.Value.Track; if (!track.IsLoaded) { // the track may not be loaded completely (only has a length once it is). Schedule(updateRelativeChildSize); return; } timeline.RelativeChildSize = new Vector2((float)Math.Max(1, track.Length), 1); } protected void Add(Drawable visualisation) => timeline.Add(visualisation); protected virtual void LoadBeatmap(WorkingBeatmap beatmap) { timeline.Clear(); } } } ```
83d6a246-17db-4758-9811-1ea033290160
{ "language": "C#" }
```c# using System; using Xunit; namespace DnxFlash.Test { public class MessageTest { private Message sut; public class Constructor : MessageTest { [Fact] public void Should_set_message() { sut = new Message("test message"); Assert.Equal("test message", sut.Text); } [Theory, InlineData(null), InlineData("")] public void Should_throw_exception_if_message_is_not_valid(string message) { var exception = Assert.Throws<ArgumentNullException>(() => new Message(message)); Assert.Equal("message", exception.ParamName); } [Fact] public void Should_set_title() { sut = new Message( text: "test message", title: "test"); Assert.Equal("test", sut.Title); } [Fact] public void Should_set_type() { sut = new Message( text: "test message", type: "test"); Assert.Equal("test", sut.Type); } } } } ``` Fix failing test due to project rename
```c# using System; using Xunit; namespace DnxFlash.Test { public class MessageTest { private Message sut; public class Constructor : MessageTest { [Fact] public void Should_set_message() { sut = new Message("test message"); Assert.Equal("test message", sut.Text); } [Theory, InlineData(null), InlineData("")] public void Should_throw_exception_if_message_is_not_valid(string text) { var exception = Assert.Throws<ArgumentNullException>(() => new Message(text)); Assert.Equal("text", exception.ParamName); } [Fact] public void Should_set_title() { sut = new Message( text: "test message", title: "test"); Assert.Equal("test", sut.Title); } [Fact] public void Should_set_type() { sut = new Message( text: "test message", type: "test"); Assert.Equal("test", sut.Type); } } } } ```
de964fbf-6d83-46ba-bc2c-1d31b6a4e0ba
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Scoring { internal class ManiaScoreProcessor : ScoreProcessor { protected override double DefaultAccuracyPortion => 0.8; protected override double DefaultComboPortion => 0.2; public override HitWindows CreateHitWindows() => new ManiaHitWindows(); } } ``` Adjust mania scoring to be 95% based on accuracy
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Scoring { internal class ManiaScoreProcessor : ScoreProcessor { protected override double DefaultAccuracyPortion => 0.95; protected override double DefaultComboPortion => 0.05; public override HitWindows CreateHitWindows() => new ManiaHitWindows(); } } ```
7a376af6-2a1c-4f86-8d71-a0bcf3426b2e
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Scoring { internal class ManiaScoreProcessor : ScoreProcessor { public override HitWindows CreateHitWindows() => new ManiaHitWindows(); } } ``` Make mania 80% acc 20% combo
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Scoring { internal class ManiaScoreProcessor : ScoreProcessor { protected override double DefaultAccuracyPortion => 0.8; protected override double DefaultComboPortion => 0.2; public override HitWindows CreateHitWindows() => new ManiaHitWindows(); } } ```
2ccd0965-a49e-41bf-b67d-a89c1608559f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SassSharp.Ast { public class SassSyntaxTree { public SassSyntaxTree(IEnumerable<Node> children) { this.Children = children; } public IEnumerable<Node> Children { get; private set; } } } ``` Add a fluent create method ast
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SassSharp.Ast { public class SassSyntaxTree { public SassSyntaxTree(IEnumerable<Node> children) { this.Children = children; } public IEnumerable<Node> Children { get; private set; } public static SassSyntaxTree Create(params Node[] nodes) { return new SassSyntaxTree(nodes); } } } ```
abb492be-e255-427c-9d4b-ad3f57fcf264
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace NewAnalyzerTemplate { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class NewAnalyzerTemplateAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { } } } ``` Add description at top of new template
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. /*This tutorial is going to guide you to write a diagnostic analyzer that enforces the placement of one space between the if keyword of an if statement and the open parenthesis of the condition. For more information, please reference the ReadMe. Before you begin, got to Tools->Extensions and Updates->Online, and install: - .NET Compiler SDK - Roslyn Syntax Visualizer */ using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace NewAnalyzerTemplate { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class NewAnalyzerTemplateAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { } } } ```
1156d6fd-454f-4a74-93dd-4f0e5b78b5df
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. #if DNX [assembly: AssemblyTitle("NLog.Web.ASPNET5")] [assembly: AssemblyProduct("NLog.Web for ASP.NET5")] #else [assembly: AssemblyTitle("NLog.Web")] [assembly: AssemblyProduct("NLog.Web")] #endif [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © NLog 2015-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("74d5915b-bea9-404c-b4d0-b663164def37")] ``` Update assemblyinfo & strong name version to 4.0.0.0
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. #if DNX [assembly: AssemblyTitle("NLog.Web.ASPNET5")] [assembly: AssemblyProduct("NLog.Web for ASP.NET Core")] #else [assembly: AssemblyTitle("NLog.Web")] [assembly: AssemblyProduct("NLog.Web")] #endif [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © NLog 2015-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("4.0.0.0")] //fixed // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("74d5915b-bea9-404c-b4d0-b663164def37")] ```
b3904943-be00-432d-a32d-68acdd88a133
{ "language": "C#" }
```c# // Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Reactive.Linq; using Perspex.Markup.Data; using Xunit; namespace Perspex.Markup.UnitTests.Binding { public class ExpressionObserverTests_PerspexProperty { [Fact] public async void Should_Get_Simple_Property_Value() { var data = new Class1(); var target = new ExpressionObserver(data, "Foo"); var result = await target.Take(1); Assert.Equal("foo", result); } [Fact] public void Should_Track_Simple_Property_Value() { var data = new Class1(); var target = new ExpressionObserver(data, "Foo"); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); data.SetValue(Class1.FooProperty, "bar"); Assert.Equal(new[] { "foo", "bar" }, result); sub.Dispose(); } private class Class1 : PerspexObject { public static readonly PerspexProperty<string> FooProperty = PerspexProperty.Register<Class1, string>("Foo", defaultValue: "foo"); } } } ``` Fix test in Release mode.
```c# // Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Reactive.Linq; using Perspex.Markup.Data; using Xunit; namespace Perspex.Markup.UnitTests.Binding { public class ExpressionObserverTests_PerspexProperty { public ExpressionObserverTests_PerspexProperty() { var foo = Class1.FooProperty; } [Fact] public async void Should_Get_Simple_Property_Value() { var data = new Class1(); var target = new ExpressionObserver(data, "Foo"); var result = await target.Take(1); Assert.Equal("foo", result); } [Fact] public void Should_Track_Simple_Property_Value() { var data = new Class1(); var target = new ExpressionObserver(data, "Foo"); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); data.SetValue(Class1.FooProperty, "bar"); Assert.Equal(new[] { "foo", "bar" }, result); sub.Dispose(); } private class Class1 : PerspexObject { public static readonly PerspexProperty<string> FooProperty = PerspexProperty.Register<Class1, string>("Foo", defaultValue: "foo"); } } } ```
5fef6d7c-42bd-4629-949c-3496b4dc560e
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class YoumuSlashTimingEffectsController : MonoBehaviour { [SerializeField] private AudioSource musicSource; [SerializeField] private float pitchMult = 1f; [SerializeField] private float timeScaleMult = 1f; [SerializeField] private float volumeMult = 1f; bool failed = false; bool ended = false; float initialTimeScale; float initialVolume; void Start () { YoumuSlashPlayerController.onFail += onFail; YoumuSlashPlayerController.onGameplayEnd += onGameplayEnd; initialTimeScale = Time.timeScale; initialVolume = musicSource.volume; } void onGameplayEnd() { ended = true; } void onFail() { failed = true; } private void LateUpdate() { if (MicrogameController.instance.getVictoryDetermined()) Time.timeScale = initialVolume; else if (ended) Time.timeScale = timeScaleMult * initialTimeScale; if (failed) musicSource.pitch = Time.timeScale * pitchMult; musicSource.volume = volumeMult * initialVolume; } } ``` Fix wrong timescale being forced on win/loss
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class YoumuSlashTimingEffectsController : MonoBehaviour { [SerializeField] private AudioSource musicSource; [SerializeField] private float pitchMult = 1f; [SerializeField] private float timeScaleMult = 1f; [SerializeField] private float volumeMult = 1f; bool failed = false; bool ended = false; float initialTimeScale; float initialVolume; void Start () { YoumuSlashPlayerController.onFail += onFail; YoumuSlashPlayerController.onGameplayEnd += onGameplayEnd; initialTimeScale = Time.timeScale; initialVolume = musicSource.volume; } void onGameplayEnd() { ended = true; } void onFail() { failed = true; } private void LateUpdate() { if (MicrogameController.instance.getVictoryDetermined()) Time.timeScale = initialTimeScale; else if (ended) Time.timeScale = timeScaleMult * initialTimeScale; if (failed) musicSource.pitch = Time.timeScale * pitchMult; musicSource.volume = volumeMult * initialVolume; } } ```
2cb9ab1e-c0cc-4c47-a240-1cf20e520bbc
{ "language": "C#" }
```c# #load "LogHelper.csx" using System.Configuration; public static class AppSettingsHelper { public static string GetAppSetting(string SettingName, bool LogValue = true ) { string SettingValue = ""; try { SettingValue = ConfigurationManager.AppSettings[SettingName].ToString(); if ((!String.IsNullOrEmpty(SettingValue)) && LogValue) { LogHelper.Info($"Retreived AppSetting {SettingName} with a value of {SettingValue}"); } else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue) { LogHelper.Info($"Retreived AppSetting {SettingName} but logging value was turned off"); } else if(!String.IsNullOrEmpty(SettingValue)) { LogHelper.Info($"AppSetting {SettingName} was null of empty"); } } catch (ConfigurationErrorsException ex) { LogHelper.Error($"Unable to find AppSetting {SettingName} with exception of {ex.Message}"); } catch (System.Exception ex) { LogHelper.Error($"Looking for AppSetting {SettingName} caused an exception of {ex.Message}"); } return SettingValue; } }``` Change type in error from of to or
```c# #load "LogHelper.csx" using System.Configuration; public static class AppSettingsHelper { public static string GetAppSetting(string SettingName, bool LogValue = true ) { string SettingValue = ""; try { SettingValue = ConfigurationManager.AppSettings[SettingName].ToString(); if ((!String.IsNullOrEmpty(SettingValue)) && LogValue) { LogHelper.Info($"Retreived AppSetting {SettingName} with a value of {SettingValue}"); } else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue) { LogHelper.Info($"Retreived AppSetting {SettingName} but logging value was turned off"); } else if(!String.IsNullOrEmpty(SettingValue)) { LogHelper.Info($"AppSetting {SettingName} was null or empty"); } } catch (ConfigurationErrorsException ex) { LogHelper.Error($"Unable to find AppSetting {SettingName} with exception of {ex.Message}"); } catch (System.Exception ex) { LogHelper.Error($"Looking for AppSetting {SettingName} caused an exception of {ex.Message}"); } return SettingValue; } }```
0de8464b-3947-4bc0-b11b-8b81b226dede
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)] internal sealed class ExcludeFromCodeCoverageAttribute : Attribute { } } ``` Make ExcludeFromCodeCoverage conditional on DEBUG
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Diagnostics.CodeAnalysis { [Conditional("DEBUG")] // don't bloat release assemblies [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)] internal sealed class ExcludeFromCodeCoverageAttribute : Attribute { } } ```
641dbf98-4ad5-482e-9e54-3eb32bf3d6f3
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ServerHost")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jorgen Thelin")] [assembly: AssemblyProduct("ServerHost")] [assembly: AssemblyCopyright("Copyright © Jorgen Thelin 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e9fff8d5-f4c0-483d-aee6-5ff82afd434f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Update copyright data and assembly description.
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ServerHost")] [assembly: AssemblyDescription("ServerHost - A .NET Server Hosting utility library, including in-process server host testing.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jorgen Thelin")] [assembly: AssemblyProduct("ServerHost")] [assembly: AssemblyCopyright("Copyright © Jorgen Thelin 2015-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e9fff8d5-f4c0-483d-aee6-5ff82afd434f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ```
6b1c7cec-e219-4780-ad63-f681c13fb865
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; using BrightstarDB.EntityFramework; namespace BrightstarDB.PerformanceBenchmarks.Models { [Entity("http://xmlns.com/foaf/0.1/Person")] public interface IFoafPerson { string Id { get; } [PropertyType("http://xmlns.com/foaf/0.1/name")] string Name { get; set; } [PropertyType("http://xmlns.com/foaf/0.1/givenName")] string GivenName { get; set; } [PropertyType("http://xmlns.com/foaf/0.1/familyName")] string FamilyName { get; set; } [PropertyType("http://xmlns.com/foaf/0.1/age")] int Age { get; set; } [PropertyType("http://xmlns.com/foaf/0.1/organization")] string Organisation { get; set; } [PropertyType("http://xmlns.com/foaf/0.1/knows")] ICollection<IFoafPerson> Knows { get; set; } } } ``` Fix so that SPARQL query test works
```c# using System; using System.Collections.Generic; using System.Text; using BrightstarDB.EntityFramework; namespace BrightstarDB.PerformanceBenchmarks.Models { [Entity("http://xmlns.com/foaf/0.1/Person")] public interface IFoafPerson { [Identifier("http://www.brightstardb.com/people/")] string Id { get; } [PropertyType("http://xmlns.com/foaf/0.1/name")] string Name { get; set; } [PropertyType("http://xmlns.com/foaf/0.1/givenName")] string GivenName { get; set; } [PropertyType("http://xmlns.com/foaf/0.1/familyName")] string FamilyName { get; set; } [PropertyType("http://xmlns.com/foaf/0.1/age")] int Age { get; set; } [PropertyType("http://xmlns.com/foaf/0.1/organization")] string Organisation { get; set; } [PropertyType("http://xmlns.com/foaf/0.1/knows")] ICollection<IFoafPerson> Knows { get; set; } } } ```
2ab7b418-bf1a-40ef-98ef-4baee82e482c
{ "language": "C#" }
```c# namespace Bakery { using System; using System.ComponentModel; using System.Globalization; public class UuidTypeConverter : TypeConverter { public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(String); } public override Object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) { return new Uuid(Guid.Parse((String)value)); } } } ``` Implement TypeConverter CanConvertTo() and ConvertTo() methods for Uuid.
```c# namespace Bakery { using System; using System.ComponentModel; using System.Globalization; public class UuidTypeConverter : TypeConverter { public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(String); } public override Boolean CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(String); } public override Object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) { return new Uuid(Guid.Parse((String)value)); } public override Object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType) { if (value == null) return null; return value.ToString(); } } } ```
27d9fcc7-4150-45f3-a5b2-17d3a23f2ad0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ForumModels { public static class Helpers { public static DateTimeOffset GetStartOfWeek(string date) { var dt = DateTimeOffset.Now; if (!String.IsNullOrEmpty(date)) { dt = DateTimeOffset.Parse(date); } dt = dt.ToLocalTime(); var dayOfWeekLocal = (int)dt.DayOfWeek; // +1 because we want to start the week on Monday and not Sunday (local time) return dt.Date.AddDays(-dayOfWeekLocal + 1); } public static string GetDataFileNameFromDate(DateTimeOffset startOfPeriod) { return startOfPeriod.ToString("yyyy-MM-dd") + ".json"; } } } ``` Fix start of week calculation
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ForumModels { public static class Helpers { public static DateTimeOffset GetStartOfWeek(string date) { var dt = DateTimeOffset.Now; if (!String.IsNullOrEmpty(date)) { dt = DateTimeOffset.Parse(date); } dt = dt.ToLocalTime(); var dayOfWeekLocal = (int)dt.DayOfWeek; // Adjust it so the week starts Monday instead of Sunday dayOfWeekLocal = (dayOfWeekLocal + 6) % 7; // Go back to the start of the current week return dt.Date.AddDays(-dayOfWeekLocal); } public static string GetDataFileNameFromDate(DateTimeOffset startOfPeriod) { return startOfPeriod.ToString("yyyy-MM-dd") + ".json"; } } } ```
028166b7-0961-4b3b-ba50-740056251ff3
{ "language": "C#" }
```c# using System; using System.Net.Http; using Newtonsoft.Json; namespace PexelsNet { public class PexelsClient { private readonly string _apiKey; private const string BaseUrl = "http://api.pexels.com/v1/"; public PexelsClient(string apiKey) { _apiKey = apiKey; } private HttpClient InitHttpClient() { var client = new HttpClient(); client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", _apiKey); return client; } public Page Search(string query, int page = 1, int perPage = 15) { var client = InitHttpClient(); HttpResponseMessage response = client.GetAsync(BaseUrl + "search?query=" + Uri.EscapeDataString(query) + "&per_page="+ perPage + "&page=" + page).Result; return GetResult(response); } public Page Popular(int page = 1, int perPage = 15) { var client = InitHttpClient(); HttpResponseMessage response = client.GetAsync(BaseUrl + "popular?per_page=" + perPage + "&page=" + page).Result; return GetResult(response); } private static Page GetResult(HttpResponseMessage response) { var body = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<Page>(body); } throw new PexelsNetException(response.StatusCode, body); } } } ``` Make use of asynchronous methods
```c# using System; using System.Net.Http; using Newtonsoft.Json; using System.Threading.Tasks; namespace PexelsNet { public class PexelsClient { private readonly string _apiKey; private const string BaseUrl = "http://api.pexels.com/v1/"; public PexelsClient(string apiKey) { _apiKey = apiKey; } private HttpClient InitHttpClient() { var client = new HttpClient(); client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", _apiKey); return client; } public async Task<Page> SearchAsync(string query, int page = 1, int perPage = 15) { var client = InitHttpClient(); HttpResponseMessage response = await client.GetAsync(BaseUrl + "search?query=" + Uri.EscapeDataString(query) + "&per_page=" + perPage + "&page=" + page); return await GetResultAsync(response); } public async Task<Page> PopularAsync(int page = 1, int perPage = 15) { var client = InitHttpClient(); HttpResponseMessage response = await client.GetAsync(BaseUrl + "popular?per_page=" + perPage + "&page=" + page); return await GetResultAsync(response); } private static async Task<Page> GetResultAsync(HttpResponseMessage response) { var body = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<Page>(body); } throw new PexelsNetException(response.StatusCode, body); } } } ```