text:
#include <boost/test/included/unit_test_framework.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>

#include <sstream>

#include "DataFile.hh"
#include "Generic.hh"
#include "Stream.hh"
#include "Compiler.hh"

using std::auto_ptr;
using std::string;
using std::pair;
using std::vector;
using std::map;
using std::istringstream;
using std::ostringstream;

using boost::array;
using boost::shared_ptr;
using boost::unit_test::test_suite;

using avro::ValidSchema;
using avro::GenericDatum;
using avro::GenericRecord;

const int count = 1000;

template <typename T>
struct Complex {
    T re;
    T im;
    Complex() : re(0), im(0) { }
    Complex(T r, T i) : re(r), im(i) { }
};

struct Integer {
    int64_t re;
    Integer() : re(0) { }
    Integer(int64_t r) : re(r) { }
};

typedef Complex<int64_t> ComplexInteger;
typedef Complex<double> ComplexDouble;

struct Double {
    double re;
    Double() : re(0) { }
    Double(double r) : re(r) { }
};

namespace avro {

template <typename T> struct codec_traits<Complex<T> > {
    static void encode(Encoder& e, const Complex<T>& c) {
        avro::encode(e, c.re);
        avro::encode(e, c.im);
    }

    static void decode(Decoder& d, Complex<T>& c) {
        avro::decode(d, c.re);
        avro::decode(d, c.im);
    }
};

template <> struct codec_traits<Integer> {
    static void decode(Decoder& d, Integer& c) {
        avro::decode(d, c.re);
    }
};

template <> struct codec_traits<Double> {
    static void decode(Decoder& d, Double& c) {
        avro::decode(d, c.re);
    }
};

}

static ValidSchema makeValidSchema(const char* schema)
{
    istringstream iss(schema);
    ValidSchema vs;
    compileJsonSchema(iss, vs);
    return ValidSchema(vs);
}

static const char sch[] = "{\"type\": \"record\","
    "\"name\":\"ComplexInteger\", \"fields\": ["
        "{\"name\":\"re\", \"type\":\"long\"},"
        "{\"name\":\"im\", \"type\":\"long\"}"
    "]}";
static const char isch[] = "{\"type\": \"record\","
    "\"name\":\"ComplexInteger\", \"fields\": ["
        "{\"name\":\"re\", \"type\":\"long\"}"
    "]}";
static const char dsch[] = "{\"type\": \"record\","
    "\"name\":\"ComplexDouble\", \"fields\": ["
        "{\"name\":\"re\", \"type\":\"double\"},"
        "{\"name\":\"im\", \"type\":\"double\"}"
    "]}";
static const char dblsch[] = "{\"type\": \"record\","
    "\"name\":\"ComplexDouble\", \"fields\": ["
        "{\"name\":\"re\", \"type\":\"double\"}"
    "]}";

string toString(const ValidSchema& s)
{
    ostringstream oss;
    s.toJson(oss);
    return oss.str();
}

class DataFileTest {
    const char* filename;
    const ValidSchema writerSchema;
    const ValidSchema readerSchema;

public:
    DataFileTest(const char* f, const char* wsch, const char* rsch) :
        filename(f), writerSchema(makeValidSchema(wsch)),
        readerSchema(makeValidSchema(rsch)) { }

    typedef pair<ValidSchema, GenericDatum> Pair;

    void testCleanup() {
        BOOST_CHECK(boost::filesystem::remove(filename));
    }

    void testWrite() {
        avro::DataFileWriter<ComplexInteger> df(filename, writerSchema, 100);
        int64_t re = 3;
        int64_t im = 5;
        for (int i = 0; i < count; ++i, re *= im, im += 3) {
            ComplexInteger c(re, im);
            df.write(c);
        }
        df.close();
    }

    void testWriteGeneric() {
        avro::DataFileWriter<Pair> df(filename, writerSchema, 100);
        int64_t re = 3;
        int64_t im = 5;
        Pair p(writerSchema, GenericDatum());

        GenericDatum& c = p.second;
        c = GenericDatum(writerSchema.root());
        GenericRecord& r = c.value<GenericRecord>();

        for (int i = 0; i < count; ++i, re *= im, im += 3) {
            r.fieldAt(0) = re;
            r.fieldAt(1) = im;
            df.write(p);
        }
        df.close();
    }

    void testWriteGenericByName() {
        avro::DataFileWriter<Pair> df(filename, writerSchema, 100);
        int64_t re = 3;
        int64_t im = 5;
        Pair p(writerSchema, GenericDatum());

        GenericDatum& c = p.second;
        c = GenericDatum(writerSchema.root());
        GenericRecord& r = c.value<GenericRecord>();

        for (int i = 0; i < count; ++i, re *= im, im += 3) {
            r.field("re") = re;
            r.field("im") = im;
            df.write(p);
        }
        df.close();
    }

    void testWriteDouble() {
        avro::DataFileWriter<ComplexDouble> df(filename, writerSchema, 100);
        double re = 3.0;
        double im = 5.0;
        for (int i = 0; i < count; ++i, re += im - 0.7, im += 3.1) {
            ComplexDouble c(re, im);
            df.write(c);
        }
        df.close();
    }

    void testTruncate() {
        testWriteDouble();
        uintmax_t size = boost::filesystem::file_size(filename);
        {
            avro::DataFileWriter<Pair> df(filename, writerSchema, 100);
            df.close();
        }
        uintmax_t new_size = boost::filesystem::file_size(filename);
        BOOST_CHECK(size > new_size);
    }

    void testReadFull() {
        avro::DataFileReader<ComplexInteger> df(filename, writerSchema);
        int i = 0;
        ComplexInteger ci;
        int64_t re = 3;
        int64_t im = 5;
        while (df.read(ci)) {
            BOOST_CHECK_EQUAL(ci.re, re);
            BOOST_CHECK_EQUAL(ci.im, im);
            re *= im;
            im += 3;
            ++i;
        }
        BOOST_CHECK_EQUAL(i, count);
    }

    void testReadProjection() {
        avro::DataFileReader<Integer> df(filename, readerSchema);
        int i = 0;
        Integer integer;
        int64_t re = 3;
        int64_t im = 5;
        while (df.read(integer)) {
            BOOST_CHECK_EQUAL(integer.re, re);
            re *= im;
            im += 3;
            ++i;
        }
        BOOST_CHECK_EQUAL(i, count);
    }

    void testReaderGeneric() {
        avro::DataFileReader<Pair> df(filename, writerSchema);
        int i = 0;
        Pair p(writerSchema, GenericDatum());
        int64_t re = 3;
        int64_t im = 5;

        const GenericDatum& ci = p.second;
        while (df.read(p)) {
            BOOST_REQUIRE_EQUAL(ci.type(), avro::AVRO_RECORD);
            const GenericRecord& r = ci.value<GenericRecord>();
            const size_t n = 2;
            BOOST_REQUIRE_EQUAL(r.fieldCount(), n);
            const GenericDatum& f0 = r.fieldAt(0);
            BOOST_REQUIRE_EQUAL(f0.type(), avro::AVRO_LONG);
            BOOST_CHECK_EQUAL(f0.value<int64_t>(), re);

            const GenericDatum& f1 = r.fieldAt(1);
            BOOST_REQUIRE_EQUAL(f1.type(), avro::AVRO_LONG);
            BOOST_CHECK_EQUAL(f1.value<int64_t>(), im);
            re *= im;
            im += 3;
            ++i;
        }
        BOOST_CHECK_EQUAL(i, count);
    }

    void testReaderGenericByName() {
        avro::DataFileReader<Pair> df(filename, writerSchema);
        int i = 0;
        Pair p(writerSchema, GenericDatum());
        int64_t re = 3;
        int64_t im = 5;

        const GenericDatum& ci = p.second;
        while (df.read(p)) {
            BOOST_REQUIRE_EQUAL(ci.type(), avro::AVRO_RECORD);
            const GenericRecord& r = ci.value<GenericRecord>();
            const size_t n = 2;
            BOOST_REQUIRE_EQUAL(r.fieldCount(), n);
            const GenericDatum& f0 = r.field("re");
            BOOST_REQUIRE_EQUAL(f0.type(), avro::AVRO_LONG);
            BOOST_CHECK_EQUAL(f0.value<int64_t>(), re);

            const GenericDatum& f1 = r.field("im");
            BOOST_REQUIRE_EQUAL(f1.type(), avro::AVRO_LONG);
            BOOST_CHECK_EQUAL(f1.value<int64_t>(), im);
            re *= im;
            im += 3;
            ++i;
        }
        BOOST_CHECK_EQUAL(i, count);
    }

    void testReaderGenericProjection() {
        avro::DataFileReader<Pair> df(filename, readerSchema);
        int i = 0;
        Pair p(readerSchema, GenericDatum());
        int64_t re = 3;
        int64_t im = 5;

        const GenericDatum& ci = p.second;
        while (df.read(p)) {
            BOOST_REQUIRE_EQUAL(ci.type(), avro::AVRO_RECORD);
            const GenericRecord& r = ci.value<GenericRecord>();
            const size_t n = 1;
            BOOST_REQUIRE_EQUAL(r.fieldCount(), n);
            const GenericDatum& f0 = r.fieldAt(0);
            BOOST_REQUIRE_EQUAL(f0.type(), avro::AVRO_LONG);
            BOOST_CHECK_EQUAL(f0.value<int64_t>(), re);

            re *= im;
            im += 3;
            ++i;
        }
        BOOST_CHECK_EQUAL(i, count);
    }

    void testReadDouble() {
        avro::DataFileReader<ComplexDouble> df(filename, writerSchema);
        int i = 0;
        ComplexDouble ci;
        double re = 3.0;
        double im = 5.0;
        while (df.read(ci)) {
            BOOST_CHECK_CLOSE(ci.re, re, 0.0001);
            BOOST_CHECK_CLOSE(ci.im, im, 0.0001);
            re += (im - 0.7);
            im += 3.1;
            ++i;
        }
        BOOST_CHECK_EQUAL(i, count);
    }

    /**
     * Constructs the DataFileReader in two steps.
     */
    void testReadDoubleTwoStep() {
        auto_ptr<avro::DataFileReaderBase>
            base(new avro::DataFileReaderBase(filename));
        avro::DataFileReader<ComplexDouble> df(base);
        BOOST_CHECK_EQUAL(toString(writerSchema), toString(df.readerSchema()));
        BOOST_CHECK_EQUAL(toString(writerSchema), toString(df.dataSchema()));
        int i = 0;
        ComplexDouble ci;
        double re = 3.0;
        double im = 5.0;
        while (df.read(ci)) {
            BOOST_CHECK_CLOSE(ci.re, re, 0.0001);
            BOOST_CHECK_CLOSE(ci.im, im, 0.0001);
            re += (im - 0.7);
            im += 3.1;
            ++i;
        }
        BOOST_CHECK_EQUAL(i, count);
    }

    /**
     * Constructs the DataFileReader in two steps using a different
     * reader schema.
     */
    void testReadDoubleTwoStepProject() {
        auto_ptr<avro::DataFileReaderBase>
            base(new avro::DataFileReaderBase(filename));
        avro::DataFileReader<Double> df(base, readerSchema);

        BOOST_CHECK_EQUAL(toString(readerSchema), toString(df.readerSchema()));
        BOOST_CHECK_EQUAL(toString(writerSchema), toString(df.dataSchema()));
        int i = 0;
        Double ci;
        double re = 3.0;
        double im = 5.0;
        while (df.read(ci)) {
            BOOST_CHECK_CLOSE(ci.re, re, 0.0001);
            re += (im - 0.7);
            im += 3.1;
            ++i;
        }
        BOOST_CHECK_EQUAL(i, count);
    }
    /**
     * Test writing DataFiles into other streams operations.
     */
    void testZip() {
        const size_t number_of_objects = 100;
        // first create a large file
        ValidSchema dschema = avro::compileJsonSchemaFromString(sch);
        {
            avro::DataFileWriter<ComplexInteger> writer(
              filename, dschema, 16 * 1024, avro::DEFLATE_CODEC);

            for (size_t i = 0; i < number_of_objects; ++i) {
                ComplexInteger d;
                d.re = i;
                d.im = 2 * i;
                writer.write(d);
            }
        }
        {
            avro::DataFileReader<ComplexInteger> reader(filename, dschema);
            std::vector<int> found;
            ComplexInteger record;
            while (reader.read(record)) {
                found.push_back(record.re);
            }
            BOOST_CHECK_EQUAL(found.size(), number_of_objects);
            for (unsigned int i = 0; i < found.size(); ++i) {
                BOOST_CHECK_EQUAL(found[i], i);
            }
        }
    }
};

void addReaderTests(test_suite* ts, const shared_ptr<DataFileTest>& t)
{
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testReadFull, t));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testReadProjection, t));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testReaderGeneric, t));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testReaderGenericByName, t));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testReaderGenericProjection,
        t));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testCleanup, t));

}

test_suite*
init_unit_test_suite( int argc, char* argv[] )
{
    test_suite* ts= BOOST_TEST_SUITE("DataFile tests");
    shared_ptr<DataFileTest> t1(new DataFileTest("test1.df", sch, isch));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testWrite, t1));
    addReaderTests(ts, t1);

    shared_ptr<DataFileTest> t2(new DataFileTest("test2.df", sch, isch));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testWriteGeneric, t2));
    addReaderTests(ts, t2);

    shared_ptr<DataFileTest> t3(new DataFileTest("test3.df", dsch, dblsch));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testWriteDouble, t3));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testReadDouble, t3));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testReadDoubleTwoStep, t3));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testReadDoubleTwoStepProject,
        t3));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testCleanup, t3));

    shared_ptr<DataFileTest> t4(new DataFileTest("test4.df", dsch, dblsch));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testTruncate, t4));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testCleanup, t4));

    shared_ptr<DataFileTest> t5(new DataFileTest("test5.df", sch, isch));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testWriteGenericByName, t5));
    addReaderTests(ts, t5);

    shared_ptr<DataFileTest> t6(new DataFileTest("test6.df", dsch, dblsch));
    ts->add(BOOST_CLASS_TEST_CASE(&DataFileTest::testZip, t6));

    return ts;
}


text:
package com.ocs.dynamo.filter;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

import com.ocs.dynamo.domain.TestEntity;

public class GreaterPredicateTest {

    @Test
    public void test() {
        GreaterThanPredicate<TestEntity> p1 = new GreaterThanPredicate<>("age", 20L);

        assertFalse(p1.test(null));

        TestEntity t1 = new TestEntity();
        t1.setAge(20L);
        assertFalse(p1.test(t1));

        t1.setAge(24L);
        assertTrue(p1.test(t1));

        t1.setAge(18L);
        assertFalse(p1.test(t1));
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace onnxruntime {
GPUDataTransfer::GPUDataTransfer(hipStream_t stream, bool do_copy_in_default_stream) {
  // create streams, default is nullptr
  do_copy_in_default_stream_ = do_copy_in_default_stream;
  streams_[kHipStreamDefault] = stream;
  if (do_copy_in_default_stream) {
    streams_[kHipStreamCopyIn] = stream;
    streams_[kHipStreamCopyOut] = stream;
  } else {
    HIP_CALL_THROW(hipStreamCreateWithFlags(&streams_[kHipStreamCopyIn], hipStreamNonBlocking));
    HIP_CALL_THROW(hipStreamCreateWithFlags(&streams_[kHipStreamCopyOut], hipStreamNonBlocking));
  }
}

GPUDataTransfer::~GPUDataTransfer() {
  if (!do_copy_in_default_stream_ && streams_[kHipStreamCopyIn] != nullptr) {
    ORT_IGNORE_RETURN_VALUE(HIP_CALL(hipStreamDestroy(streams_[kHipStreamCopyIn])));
  }
  if (!do_copy_in_default_stream_ && streams_[kHipStreamCopyOut] != nullptr) {
    ORT_IGNORE_RETURN_VALUE(HIP_CALL(hipStreamDestroy(streams_[kHipStreamCopyOut])));
  }
}

bool GPUDataTransfer::CanCopy(const OrtDevice& src_device, const OrtDevice& dst_device) const {
  return src_device.Type() == OrtDevice::GPU || src_device.MemType() == OrtDevice::MemType::HIP_PINNED ||
         dst_device.Type() == OrtDevice::GPU || dst_device.MemType() == OrtDevice::MemType::HIP_PINNED;
}

common::Status GPUDataTransfer::CopyTensor(const Tensor& src, Tensor& dst, int exec_queue_id) const {
  size_t bytes = src.SizeInBytes();
  const void* src_data = src.DataRaw();
  void* dst_data = dst.MutableDataRaw();

  auto& src_device = src.Location().device;
  auto& dst_device = dst.Location().device;

  if (dst_device.Type() == OrtDevice::GPU) {
    if (src_device.Type() == OrtDevice::CPU && src_device.MemType() == OrtDevice::MemType::HIP_PINNED) {
      // copy from pinned memory to GPU, this is non-blocking
      HIP_RETURN_IF_ERROR(hipMemcpyAsync(dst_data, src_data, bytes, hipMemcpyHostToDevice, GetStream(exec_queue_id)));
    } else if (src_device.Type() == OrtDevice::GPU) {
      // copying between GPU, this is non-blocking
      // Copy only if the two addresses are different.
      if (dst_data != src_data) {
        HIP_RETURN_IF_ERROR(hipMemcpyAsync(dst_data, src_data, bytes, hipMemcpyDeviceToDevice, GetStream(kHipStreamDefault)));
      }
    } else {
      // copy from other CPU memory to GPU, this is blocking
      HIP_RETURN_IF_ERROR(hipMemcpyAsync(dst_data, src_data, bytes, hipMemcpyHostToDevice, GetStream(kHipStreamDefault)));
      HIP_RETURN_IF_ERROR(hipStreamSynchronize(GetStream(kHipStreamDefault)));
    }
  } else if (src_device.Type() == OrtDevice::GPU) {
    if (dst_device.Type() == OrtDevice::CPU && dst_device.MemType() == OrtDevice::MemType::HIP_PINNED) {
      // copying from GPU to pinned memory, this is non-blocking
      HIP_RETURN_IF_ERROR(hipMemcpyAsync(dst_data, src_data, bytes, hipMemcpyDeviceToHost, GetStream(exec_queue_id)));
    } else {
      // copying from GPU to CPU memory, this is blocking
      HIP_RETURN_IF_ERROR(hipMemcpyAsync(dst_data, src_data, bytes, hipMemcpyDeviceToHost, GetStream(kHipStreamDefault)));
      HIP_RETURN_IF_ERROR(hipStreamSynchronize(GetStream(kHipStreamDefault)));
    }
  } else {
    // copying between cpu memory
    memcpy(dst_data, src_data, bytes);
  }

  return Status::OK();
}
}  // namespace onnxruntime


text:
mod child_properties;
#[allow(clippy::module_inception)]
pub mod config;
pub mod constants;
pub mod derives;
pub mod error;
mod external_libraries;
pub mod functions;
pub mod gobjects;
pub mod ident;
pub mod matchable;
pub mod members;
pub mod parameter_matchable;
pub mod parsable;
pub mod properties;
pub mod property_generate_flags;
pub mod signals;
pub mod string_type;
pub mod work_mode;

pub use self::{
    child_properties::{ChildProperties, ChildProperty},
    config::Config,
    external_libraries::ExternalLibrary,
    gobjects::GObject,
    property_generate_flags::PropertyGenerateFlags,
    string_type::StringType,
    work_mode::WorkMode,
};


text:
<head>
    {% if site.google_tag_manager %}
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','{{ site.google_tag_manager }}');</script>
    {% endif %}
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{% if page.title %}{{ page.title | strip_html }} – {% endif %}{{ site.title | strip_html }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Vier traktate über die keltischen sprache – von Fred Grupp, Mössingen">
    {% if page.meta_robots %}<meta name="robots" content="{{ page.meta_robots }}">
    {% else %}<meta name="robots" content="all">{% endif %}
    <meta name="author" content="{{ site.author }}">
    {% if site.fb_page %}<meta property="fb:pages" content="{{ site.fb_page_id }}" />{% endif %}
    {% if page.categories %}<meta name="keywords" content="{{ page.categories | join: ', ' }}">{% endif %}
    <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
    <link rel="alternate" type="application/rss+xml" title="RSS Feed for {{ site.title }}" href="{{ "/feed.xml" | prepend: site.baseurl }}" />

    <!-- Custom CSS -->
    <link rel="stylesheet" href="{{ "/css/pixyll.css" | prepend: site.baseurl }}?{{ site.time | date: "%Y%m%d%H%M" }}" type="text/css">

    <!-- Fonts -->
    {% if site.extended_fonts %}
    <link href='//fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic&subset=latin-ext,latin' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Lato:900,300&subset=latin-ext,latin' rel='stylesheet' type='text/css'>
    {% else %}
    <link href='//fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Lato:900,300' rel='stylesheet' type='text/css'>
    {% endif %}
    {% if site.show_social_icons or site.show_sharing_icons %}
      <link href="//maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet">
    {% endif %}

    <!-- MathJax -->
    {% if site.enable_mathjax %}
    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
    </script>
    {% endif %}

    <!-- Verifications -->
    {% if site.google_verification %}
      <meta name="google-site-verification" content="{{ site.google_verification }}" />
    {% endif %}
    {% if site.bing_verification %}
      <meta name="msvalidate.01" content="{{ site.bing_verification }}" />
    {% endif %}

    <!-- Open Graph -->
    <!-- From: https://github.com/mmistakes/hpstr-jekyll-theme/blob/master/_includes/head.html -->
    <meta property="og:locale" content="{{ site.text.og_locale }}">
    <meta property="og:type" content="article">
    <meta property="og:title" content="{% if page.title %}{{ page.title | xml_escape }}{% else %}{{ site.title | xml_escape }}{% endif %}">
    <meta property="og:description" content="{% if page.description %}{{ page.description | xml_escape }}{% else %}{{ site.description | xml_escape }}{% endif %}">
    <meta property="og:url" content="{{ site.url }}{{ page.url }}">
    <meta property="og:site_name" content="{{ site.title | xml_escape }}">

    <!-- Twitter Card -->
    <meta name="twitter:card" content="summary" />
    {% if site.twitter_username %}
        <meta name="twitter:site" content="@{{ site.twitter_username }}" />
    {% endif %}
    <meta name="twitter:title" content="{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}" />
    <meta name="twitter:description" content="{% if page.summary %}{{ page.summary }}{% else %}{{ site.description }}{% endif %}" />
    <meta name="twitter:url" content="{{ site.url }}{{ page.url }}" />

    <!-- Icons -->
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <link rel="manifest" href="/manifest.json">
    <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#000000">
    <meta name="theme-color" content="#ffffff">

    {% if site.google_analytics %}
    <script type="text/javascript">
       (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
       (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
       m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
       })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
       ga('create', '{{ site.google_analytics }}', 'auto');
       ga('send', 'pageview');
    </script>
    {% endif %}
</head>


text:
require_relative '../../spec_helper'
require 'trick_bag/enumerables/compound_enumerable'

module TrickBag
module Enumerables

  describe CompoundEnumerable do

    context 'input validations' do

      specify 'an initialization error will be raised if no enumerables are specified' do
        expect(->{ CompoundEnumerable.array_enumerable() }).to raise_error(ArgumentError)
        expect(->{ CompoundEnumerable.hash_enumerable([:key]) }).to raise_error(ArgumentError)
      end

      specify 'an initialization error will be raised if mode is not :yields_arrays or :yields_hashes' do
        expect(->{ CompoundEnumerable.new(:bad_mode, [], [])}).to raise_error(ArgumentError)
      end

      specify 'an initialization error will be raised if key array size != enumerables size in :yields_hashes mode' do
        expect(->{ CompoundEnumerable.new(:yields_hashes, [:key1, :key2], [])}).to raise_error(ArgumentError)
        expect(->{ CompoundEnumerable.hash_enumerable([:key1, :key2], [])}).to raise_error(ArgumentError)
      end
    end

    context "as array" do

      context 'with 1 enumerable' do
        specify 'Gets its values then raises a StopIteration error' do
          array = [1, 2]
          e = CompoundEnumerable.array_enumerable(array).each
          expect(e.next).to eq(1)
          expect(e.next).to eq(2)
          expect(->{ e.next }).to raise_error(StopIteration)
        end
      end

      context 'with 2 enumerables' do
        specify 'offers correct values in the correct order' do
          outer = %w(A B)
          inner = [1, 2]
          e = CompoundEnumerable.array_enumerable(outer, inner).each
          expect(e.next).to eq(['A', 1])
          expect(e.next).to eq(['A', 2])
          expect(e.next).to eq(['B', 1])
          expect(e.next).to eq(['B', 2])
          expect(->{ e.next }).to raise_error(StopIteration)
        end
      end

      context 'with 3 enumerables' do
        specify 'offers correct values in the correct order' do
          domains = %w(aaa.com  zzz.com)
          qtypes = %w(A  NS)
          qclasses = %w(IN  CH)
          e = CompoundEnumerable.array_enumerable(domains, qtypes, qclasses).each

          expect(e.next).to eq(['aaa.com', 'A', 'IN'])
          expect(e.next).to eq(['aaa.com', 'A', 'CH'])
          expect(e.next).to eq(['aaa.com', 'NS', 'IN'])
          expect(e.next).to eq(['aaa.com', 'NS', 'CH'])
          expect(e.next).to eq(['zzz.com', 'A', 'IN'])
          expect(e.next).to eq(['zzz.com', 'A', 'CH'])
          expect(e.next).to eq(['zzz.com', 'NS', 'IN'])
          expect(e.next).to eq(['zzz.com', 'NS', 'CH'])
          expect(->{ e.next }).to raise_error(StopIteration)
        end
      end

      context 'is an Enumerable' do
        it "provides the 'take' method" do
          expect(->{ CompoundEnumerable.array_enumerable([1, 2, 3]).take(2)}).not_to raise_error
        end

        it 'returns an Enumerator when each is called without a block' do
          expect(CompoundEnumerable.array_enumerable([1, 2, 3]).each).to be_a(Enumerator)
        end
      end
    end

    context "as hash" do

      context 'with 1 enumerable' do
        specify 'Gets its values then raises a StopIteration error' do
          array = [1, 2]
          e = CompoundEnumerable.hash_enumerable([:number], array).each
          expect(e.next).to eq({ number: 1 })
          expect(e.next).to eq({ number: 2 })
          expect(->{ e.next }).to raise_error(StopIteration)
        end
      end

      context 'with 2 enumerables' do
        specify 'offers correct values in the correct order' do
          outer = %w(A B)
          inner = [1, 2]
          e = CompoundEnumerable.hash_enumerable([:outer, :inner], outer, inner).each
          expect(e.next).to eq({ outer: 'A', inner: 1 })
          expect(e.next).to eq({ outer: 'A', inner: 2 })
          expect(e.next).to eq({ outer: 'B', inner: 1 })
          expect(e.next).to eq({ outer: 'B', inner: 2 })
          expect(->{ e.next }).to raise_error(StopIteration)
        end
      end

      context 'with 3 enumerables' do
        specify 'offers correct values in the correct order' do
          domains = %w(aaa.com  zzz.com)
          qtypes = %w(A  NS)
          qclasses = %w(IN  CH)
          keys = [:domain, :qtype, :qclass]
          e = CompoundEnumerable.hash_enumerable(keys, domains, qtypes, qclasses).each

          expect(e.next).to eq({ domain: 'aaa.com', qtype: 'A', qclass: 'IN' })
          expect(e.next).to eq({ domain: 'aaa.com', qtype: 'A', qclass: 'CH' })
          expect(e.next).to eq({ domain: 'aaa.com', qtype: 'NS', qclass: 'IN' })
          expect(e.next).to eq({ domain: 'aaa.com', qtype: 'NS', qclass: 'CH' })

          expect(e.next).to eq({ domain: 'zzz.com', qtype: 'A', qclass: 'IN' })
          expect(e.next).to eq({ domain: 'zzz.com', qtype: 'A', qclass: 'CH' })
          expect(e.next).to eq({ domain: 'zzz.com', qtype: 'NS', qclass: 'IN' })
          expect(e.next).to eq({ domain: 'zzz.com', qtype: 'NS', qclass: 'CH' })
          expect(->{ e.next }).to raise_error(StopIteration)
        end
      end

      context 'is an Enumerable' do
        it "provides the 'take' method" do
          expect(->{ CompoundEnumerable.hash_enumerable([:num], [1, 2, 3]).take(2)}).not_to raise_error

          values = CompoundEnumerable.hash_enumerable([:num], [1, 2, 3]).take(2)
          expect(values).to eq([{ num: 1 }, { num: 2 }])
        end
      end
    end
  end
end
end


text:
<link href="example6.css" rel="stylesheet"/>

    External

        Internal

        BOX

    External

        Internal

        BOX


text:
@interface HTY360PlayerVC : UIViewController

@property (strong, nonatomic) NSURL *videoURL;
@property (weak, nonatomic) IBOutlet UIImageView *thumbnailImageView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil url:(NSURL*)url;
- (CVPixelBufferRef)retrievePixelBufferToDraw;
- (void)toggleControls;

// to be implemented in subclass
-(void)showThumbnailFor:(UISlider*)scrubber atTime:(CMTime)time withPlayerItem:(AVPlayerItem*)player;
-(void)hideThumbnail;

@end


text:
using namespace leap::ipc;

class IPCFormatTest :
  public testing::Test
{};

static_assert(sizeof(IPCEndpoint::Header) == 8, "Header size mismatch");

TEST_F(IPCFormatTest, HeaderFormat) {
  // Known-good data, we need to be able to parse this one:
  static const uint8_t data[8] = {0x64, 0x37, 0x83, 8, 0xDE, 0xAD, 0xBE, 0xEF};
  const IPCEndpoint::Header& hdr = *(IPCEndpoint::Header*)data;

  ASSERT_TRUE(hdr.Validate());
  ASSERT_EQ(4u, hdr.Version());
  ASSERT_EQ(1u, hdr.Channel());
  ASSERT_TRUE(hdr.IsEndOfMessage());
  ASSERT_EQ(8u, hdr.Size());
  ASSERT_EQ(0xDEADBEEF, hdr.PayloadSize());

  IPCEndpoint::Header refHdr;
  refHdr.SetVersion(4);
  refHdr.SetChannel(1);
  refHdr.SetEndOfMessage();
  refHdr.SetPayloadSize(0xDEADBEEF);
  ASSERT_EQ(0, memcmp(&hdr, &refHdr, sizeof(hdr))) << "Header mutator methods must result in a binary-equivalent header to the reference";
}


text:
using BrokerDsLinkTest = SetUpBase;

void clean_config_files(dsa::ProtocolType protocol) {
  switch (protocol) {
  case ProtocolType::PROT_DSS:
  case ProtocolType::PROT_WSS:
    Storage::get_config_bucket().remove("client-manager.json");
    break;
  default:
    Storage::get_config_bucket().remove_all();
  }
}

TEST_F(BrokerDsLinkTest, ClientRemoveTest) {
  clean_config_files(protocol());
  TestConfig::create_pem_files();

  // First Create Broker
  auto app = make_shared_<App>();
  auto broker = broker_dslink_test::create_broker(app);
  broker->run();
  ASYNC_EXPECT_TRUE(1000, *broker->strand,
                    [&]() { return broker->get_active_server_port() != 0; });
  int32_t port;

  switch (protocol()) {
    case dsa::ProtocolType::PROT_DSS:
      port = broker->get_active_secure_port();
      break;
    default:
      port = broker->get_active_server_port();
  }

  EXPECT_TRUE(port != 0);

  auto link_1 =
      broker_dslink_test::create_dslink(app, port, "test1", false, protocol());
  auto link_2 =
      broker_dslink_test::create_dslink(app, port, "test2", true, protocol());

  int downstream_listed = 0, clients_listed = 0;
  bool link1_connected = false, allow_all_set = false;
  link_1->connect([&](const shared_ptr_<Connection> connection,
                      ref_<DsLinkRequester> link_req) {
    link1_connected = true;

    // set request to change value
    auto set_request = make_ref_<SetRequestMessage>();
    set_request->set_value(Var(false));
    set_request->set_target_path("sys/clients/allow-all");

    // send set request
    link_req->set(
        [&, link_req](IncomingSetStream &stream,
                      ref_<const SetResponseMessage> &&msg) {
          EXPECT_TRUE(msg->get_status() == Status::DONE);
          allow_all_set = true;

          link_req->list("downstream", [&, link_req](
                                           IncomingListCache &cache,
                                           const std::vector<string_> &str) {
            auto map = cache.get_map();
            downstream_listed++;
            if (downstream_listed == 1) {
              EXPECT_TRUE(map.find("test1") != map.end());
              EXPECT_TRUE(map.find("test2") != map.end());

              link_req->list(
                  "sys/clients",
                  [&, link_req](IncomingListCache &cache,
                                const std::vector<string_> &str) {
                    auto map = cache.get_map();
                    bool test1_client = false;
                    string_ test2_id;
                    for (auto &items : map) {
                      if (items.first.substr(0, 5) == "test1")
                        test1_client = true;
                      else if (items.first.substr(0, 5) == "test2") {
                        test2_id = items.first;
                      }
                    }
                    clients_listed++;
                    if (clients_listed == 1) {
                      EXPECT_TRUE(test1_client && !test2_id.empty());
                      auto invoke_request = make_ref_<InvokeRequestMessage>();
                      invoke_request->set_target_path("sys/clients/" +
                                                      test2_id + "/remove");

                      link_req->invoke(
                          [&](IncomingInvokeStream &stream,
                              ref_<const InvokeResponseMessage> &&msg) {
                            auto response = std::move(msg);
                            EXPECT_TRUE(response != nullptr);
                            stream.close();
                          },
                          copy_ref_(invoke_request));
                    } else {
                      EXPECT_TRUE(test1_client && test2_id.empty());
                      cache.close();
                    }
                  });

            } else {
              EXPECT_TRUE(map.find("test1") != map.end());
              EXPECT_TRUE(map.find("test2") == map.end());
              cache.close();
            }
          });

        },
        std::move(set_request));

  });
  WAIT_EXPECT_TRUE(1000, [&]() -> bool {
    return (link1_connected && (downstream_listed >= 2) &&
            (clients_listed >= 2) && allow_all_set);
  });

  link_1->strand->post([link_1]() { link_1->destroy(); });
  link_2->strand->post([link_2]() { link_2->destroy(); });
  broker->strand->post([broker]() { broker->destroy(); });
  app->close();

  WAIT_EXPECT_TRUE(1000, [&]() -> bool { return app->is_stopped(); });

  if (!app->is_stopped()) {
    app->force_stop();
  }
  app->wait();

  Storage::get_config_bucket().remove_all();
}

TEST_F(BrokerDsLinkTest, ClientPathTest) {
  clean_config_files(protocol());
  TestConfig::create_pem_files();

  // First Create Broker
  auto app = make_shared_<App>();
  auto broker = broker_dslink_test::create_broker(app);
  broker->run();
  ASYNC_EXPECT_TRUE(1000, *broker->strand,
                    [&]() { return broker->get_active_server_port() != 0; });
  int32_t port;

  switch (protocol()) {
    case dsa::ProtocolType::PROT_DSS:
      port = broker->get_active_secure_port();
      break;
    default:
      port = broker->get_active_server_port();
  }

  EXPECT_TRUE(port != 0);

  auto link_1 =
      broker_dslink_test::create_dslink(app, port, "test1", false, protocol());

  int downstream_listed = 0;
  bool link1_connected = false, test_end = false;
  link_1->connect([&](const shared_ptr_<Connection> connection,
                      ref_<DsLinkRequester> link_req) {
    link1_connected = true;

    link_req->list(
        "downstream", [&, link_req](IncomingListCache &cache,
                                    const std::vector<string_> &str) {
          auto map = cache.get_map();
          downstream_listed++;
          if (downstream_listed == 1) {
            EXPECT_TRUE(map.find("test1") != map.end());

            link_req->list("sys/clients", [&, link_req](
                                              IncomingListCache &cache,
                                              const std::vector<string_> &str) {
              auto map = cache.get_map();
              string_ test1_id;
              for (auto &items : map) {
                if (items.first.substr(0, 5) == "test1") {
                  test1_id = items.first;
                }
              }
              EXPECT_TRUE(!test1_id.empty());

              // change path
              auto set_request = make_ref_<SetRequestMessage>();
              set_request->set_value(Var("downstream/test-changed"));
              set_request->set_target_path("sys/clients/" + test1_id + "/path");
              link_req->set(
                  [&, link_req](IncomingSetStream &stream,
                                ref_<const SetResponseMessage> &&msg) {
                    EXPECT_EQ(msg->get_status(), Status::DONE);

                  },
                  std::move(set_request));
              cache.close();

            });

          } else {
            EXPECT_TRUE(map.find("test1") == map.end());
            EXPECT_TRUE(map.find("test-changed") != map.end());
            cache.close();
            test_end = true;
          }
        });

  });
  WAIT_EXPECT_TRUE(1000, [&]() -> bool {
    return (link1_connected && (downstream_listed >= 2) && test_end);
  });

  link_1->strand->post([link_1]() { link_1->destroy(); });
  broker->strand->post([broker]() { broker->destroy(); });
  app->close();

  WAIT_EXPECT_TRUE(1000, [&]() -> bool { return app->is_stopped(); });

  if (!app->is_stopped()) {
    app->force_stop();
  }
  app->wait();

  Storage::get_config_bucket().remove_all();
}

bool get_connected(const shared_ptr_<Connection> &connection) {
  if (!connection) {
    return false;
  } else {
    auto session = connection->session();
    if (!session) {
      return false;
    } else {
      return session->is_connected();
    }
  }
}

TEST_F(BrokerDsLinkTest, QuarantineTest) {
  clean_config_files(protocol());
  TestConfig::create_pem_files();

  // First Create Broker
  auto app = make_shared_<App>();
  auto broker = broker_dslink_test::create_broker(app);
  broker->run();
  ASYNC_EXPECT_TRUE(1000, *broker->strand,
                    [&]() { return broker->get_active_server_port() != 0; });
  int32_t port;

  switch (protocol()) {
    case dsa::ProtocolType::PROT_DSS:
      port = broker->get_active_secure_port();
      break;
    default:
      port = broker->get_active_server_port();
  }

  EXPECT_TRUE(port != 0);

  auto link_1 =
      broker_dslink_test::create_dslink(app, port, "test1", false, protocol());
  auto link_2 =
      broker_dslink_test::create_dslink(app, port, "test2", false, protocol());

  int downstream_listed = 0, quarantine_listed = 0;
  bool link1_connected = false, link2_connected = false;
  link_1->connect([&](const shared_ptr_<Connection> connection,
                      ref_<DsLinkRequester> link_req) {
    link1_connected = get_connected(connection);
    EXPECT_TRUE(link1_connected);

    // set request to change value
    auto set_request = make_ref_<SetRequestMessage>();
    set_request->set_value(Var(false));
    set_request->set_target_path("sys/clients/allow-all");

    link_req->set(
        [&, link_req](IncomingSetStream &stream,
                      ref_<const SetResponseMessage> &&msg) {
          EXPECT_EQ(msg->get_status(), Status::DONE);

          // set request to change value
          auto set_request = make_ref_<SetRequestMessage>();
          set_request->set_value(Var(true));
          set_request->set_target_path("sys/quarantine/enabled");

          // send set request
          link_req->set(
              [&, link_req](IncomingSetStream &stream,
                            ref_<const SetResponseMessage> &&msg) {
                EXPECT_EQ(msg->get_status(), Status::DONE);

                link_2->connect([&, link1_req = link_req ](
                    const shared_ptr_<Connection> connection2,
                    ref_<DsLinkRequester> link2_req) {
                  link2_connected = get_connected(connection2);
                  EXPECT_TRUE(link2_connected);
                  link1_req->list(
                      "downstream",
                      [&, link1_req](IncomingListCache &cache,
                                     const std::vector<string_> &str) {
                        auto map = cache.get_map();
                        downstream_listed++;
                        if (downstream_listed == 1) {
                          EXPECT_TRUE(map.find("test2") == map.end());
                        } else {
                          EXPECT_TRUE(map.find("test2") != map.end());
                        }
                      });
                  link1_req->list(
                      "sys/quarantine",
                      [&, link1_req](IncomingListCache &cache,
                                     const std::vector<string_> &str) {
                        auto map = cache.get_map();
                        quarantine_listed++;
                        string_ test2_id;
                        for (auto &items : map) {
                          if (items.first.substr(0, 5) == "test2") {
                            test2_id = items.first;
                          }
                        }
                        if (quarantine_listed == 1) {
                          EXPECT_TRUE(!test2_id.empty());
                          // invoke authorize
                          auto invoke_request =
                              make_ref_<InvokeRequestMessage>();
                          invoke_request->set_target_path(
                              "sys/quarantine/" + test2_id + "/authorize");
                          invoke_request->set_value(
                              Var({{"Path", Var("downstream/test2")}}));

                          link1_req->invoke(
                              [&](IncomingInvokeStream &stream,
                                  ref_<const InvokeResponseMessage> &&msg) {
                                auto response = std::move(msg);
                                EXPECT_EQ(response->get_status(),
                                          Status::DONE);
                                EXPECT_TRUE(response != nullptr);
                                stream.close();
                              },
                              copy_ref_(invoke_request));
                        } else {
                          EXPECT_TRUE(test2_id.empty());
                        }
                      });

                });

              },
              std::move(set_request));
        },
        std::move(set_request));

  });
  WAIT_EXPECT_TRUE(3000, [&]() -> bool {
    return (link1_connected && link2_connected && (downstream_listed >= 2) &&
            (quarantine_listed >= 2));
  });

  link_1->strand->post([link_1]() { link_1->destroy(); });
  link_2->strand->post([link_2]() { link_2->destroy(); });
  broker->strand->post([broker]() { broker->destroy(); });
  app->close();

  WAIT_EXPECT_TRUE(1000, [&]() -> bool { return app->is_stopped(); });

  if (!app->is_stopped()) {
    app->force_stop();
  }
  app->wait();

  Storage::get_config_bucket().remove_all();
}

TEST_F(BrokerDsLinkTest, IdenticalClientTest) {
  clean_config_files(protocol());
  TestConfig::create_pem_files();

  // First Create Broker
  auto app = make_shared_<App>();
  auto broker = broker_dslink_test::create_broker(app);
  broker->run();
  ASYNC_EXPECT_TRUE(1000, *broker->strand,
                    [&]() { return broker->get_active_server_port() != 0; });
  int32_t port;

  switch (protocol()) {
    case dsa::ProtocolType::PROT_DSS:
      port = broker->get_active_secure_port();
      break;
    default:
      port = broker->get_active_server_port();
  }

  EXPECT_TRUE(port != 0);

  auto link_1 =
      broker_dslink_test::create_dslink(app, port, "test1", false, protocol());
  auto link_2 =
      broker_dslink_test::create_dslink(app, port, "test1", false, protocol());

  bool link1_connected = false;
  bool link2_connected = false;
  link_1->connect([&](const shared_ptr_<Connection> connection,
                      ref_<DsLinkRequester> link_req) {
    link1_connected |= get_connected(connection);

    if (link1_connected) {
      link_2->connect([&](const shared_ptr_<Connection> connection,
                          ref_<DsLinkRequester> link_req) {
        link2_connected |= get_connected(connection);
      });
    }

  });
  WAIT_EXPECT_TRUE(
      1000, [&]() -> bool { return link1_connected && link2_connected; });

  link_1->strand->post([link_1]() { link_1->destroy(); });
  link_2->strand->post([link_2]() { link_2->destroy(); });
  broker->strand->post([broker]() { broker->destroy(); });
  app->close();

  WAIT_EXPECT_TRUE(1000, [&]() -> bool { return app->is_stopped(); });

  if (!app->is_stopped()) {
    app->force_stop();
  }
  app->wait();

  Storage::get_config_bucket().remove_all();
}


text:
import urllib.request
from bs4 import BeautifulSoup

def scrape_list(site):
    hdr = {'User-Agent': 'Mozilla/5.0'}
    req = urllib.request.Request(site, headers=hdr)
    page = urllib.request.urlopen(req)
    soup = BeautifulSoup(page, "html.parser")

    table = soup.find('table', {'class': 'wikitable sortable'})
    sector_tickers = dict()
    for row in table.findAll('tr'):
        col = row.findAll('td')
        if len(col) > 0:
            sector = str(col[3].string.strip()).lower().replace(' ', '_')
            ticker = str(col[0].string.strip())
            if sector not in sector_tickers:
                sector_tickers[sector] = list()
            sector_tickers[sector].append(ticker)
    return sector_tickers

def get_snp500_by_sector():
    sector_tickers = scrape_list("http://en.wikipedia.org/wiki/List_of_S%26P_500_companies")
    return sector_tickers

def get_snp500():
    by_sec = get_snp500_by_sector()
    all = []
    for key in by_sec:
        all += by_sec[key]
    return all


text:
package com.crazyhitty.chdev.ks.munch.ui.views;

import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.widget.Toast;

import com.crazyhitty.chdev.ks.munch.utils.DatabaseUtil;

/**
 * Created by Kartik_ch on 12/16/2015.
 */
public class CustomPreferenceDialog extends DialogPreference {
    public CustomPreferenceDialog(Context context, AttributeSet attrs) {
        super(context, attrs);

        setPositiveButtonText(android.R.string.ok);
        setNegativeButtonText(android.R.string.cancel);

        setDialogIcon(null);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        // When the user selects "OK", persist the new value
        if (positiveResult) {
            // User selected OK
            try {
                new DatabaseUtil(getContext()).deleteAll();
                Toast.makeText(getContext(), "Database reset", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } else {
            // User selected Cancel
        }
    }

}


text:
import javafx.scene.Group;
import javafx.scene.text.Text;

public class StatsDisplay {
	private Group root;
	private int score; //TODO:SOMEHOW MAKE THIS NOT PUBLIC
	private int lives;
	private Text scoreText;
	private Text lifeText;
	private Text levelText;
	private UIController myUI;

	public StatsDisplay(UIController ui, Group g, int level){
		root = g;
		score = 0;
		lives = 3;
		myUI = ui;

		scoreText = new Text();
		lifeText = new Text();
        levelText = new Text();

        myUI.writeWhiteText(root,scoreText, "Score: "+score,Main.WIDTH-80,20);
        myUI.writeWhiteText(root,lifeText, "Lives: "+lives,Main.WIDTH-180,20);
        myUI.writeWhiteText(root,levelText, "Level: "+level,Main.WIDTH-280,20);
	}
	public void setScore(int newscore){
		score = newscore;
        scoreText.setText("Score: "+score);
	}
	public int getScore(){
		return score;
	}
	public void loseLife(){
		lives = lives-1;
		lifeText.setText("Lives: "+lives);
	}
	public int getLives(){
		return lives;
	}
}


text:
__all__ = ["normSquared"]

import numpy as np

def normSquared(x, A, At, b=0, c=0, constant=0):
	"""
	f, g = normSquared(x,A,At,b,c,constant)
	returns the objective function f and its gradient

	A is a function that computes the matrix-vector product
	At is a function that computes the matrix-vector product for the transposed matrix

	By default, b=0 and c=0

	March 4 2014, Stephen Becker, stephen.beckr@gmail.com

	See also quadraticFunction.m

	Python version: A. Asensio Ramos (March 12, 2015)

	"""
	res = A(x) - b
	cx = 0.0
	if (c != 0):
		cx = np.dot(c, x)

	f = 0.5 * np.linalg.norm(res)**2 + cx + constant
	g   = At(res) + c

	return f, g


text:
package org.sagebionetworks.bridge.sdk.integration;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.sagebionetworks.bridge.util.IntegTestUtils.TEST_APP_ID;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.common.collect.ImmutableList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import org.sagebionetworks.bridge.rest.api.ForConsentedUsersApi;
import org.sagebionetworks.bridge.rest.api.InternalApi;
import org.sagebionetworks.bridge.rest.api.NotificationsApi;
import org.sagebionetworks.bridge.rest.model.Criteria;
import org.sagebionetworks.bridge.rest.model.NotificationProtocol;
import org.sagebionetworks.bridge.rest.model.NotificationRegistration;
import org.sagebionetworks.bridge.rest.model.NotificationTopic;
import org.sagebionetworks.bridge.rest.model.Role;
import org.sagebionetworks.bridge.rest.model.SignUp;
import org.sagebionetworks.bridge.rest.model.StudyParticipant;
import org.sagebionetworks.bridge.rest.model.SubscriptionRequest;
import org.sagebionetworks.bridge.rest.model.SubscriptionStatus;
import org.sagebionetworks.bridge.user.TestUser;
import org.sagebionetworks.bridge.user.TestUserHelper;
import org.sagebionetworks.bridge.util.IntegTestUtils;

@SuppressWarnings("ConstantConditions")
public class SmsNotificationRegistrationTest {
    private static String autoTopicGuid1;
    private static String autoTopicGuid2;
    private static String manualTopicGuid;
    private static TestUser developer;
    private static TestUser researcher;

    private TestUser phoneUser;

    @BeforeClass
    public static void setup() throws Exception {
        // Ensure that we have the following notification topics:
        // 1. auto-topic-1 (assigned to data group sdk-int-1)
        // 2. auto-topic-2 (assigned to data group sdk-int-2)
        // 3. manual-topic (not managed by criteria)
        developer = TestUserHelper.createAndSignInUser(SmsNotificationRegistrationTest.class, false,
                Role.DEVELOPER);
        NotificationsApi notificationsApi = developer.getClient(NotificationsApi.class);

        List<NotificationTopic> topicList = notificationsApi.getNotificationTopics(false).execute().body().getItems();
        for (NotificationTopic oneTopic : topicList) {
            if ("auto-topic-1".equals(oneTopic.getName())) {
                autoTopicGuid1 = oneTopic.getGuid();
            } else if ("auto-topic-2".equals(oneTopic.getName())) {
                autoTopicGuid2 = oneTopic.getGuid();
            } else if ("manual-topic".equals(oneTopic.getName())) {
                manualTopicGuid = oneTopic.getGuid();
            }
        }

        if (autoTopicGuid1 == null) {
            Criteria criteria = new Criteria().addAllOfGroupsItem("sdk-int-1");
            NotificationTopic topicToCreate = new NotificationTopic().name("auto-topic-1").shortName("auto-1")
                    .criteria(criteria);
            autoTopicGuid1 = notificationsApi.createNotificationTopic(topicToCreate).execute().body().getGuid();
        }

        if (autoTopicGuid2 == null) {
            Criteria criteria = new Criteria().addAllOfGroupsItem("sdk-int-2");
            NotificationTopic topicToCreate = new NotificationTopic().name("auto-topic-2").shortName("auto-2")
                    .criteria(criteria);
            autoTopicGuid2 = notificationsApi.createNotificationTopic(topicToCreate).execute().body().getGuid();
        }

        if (manualTopicGuid == null) {
            NotificationTopic topicToCreate = new NotificationTopic().name("manual-topic").shortName("manual");
            manualTopicGuid = notificationsApi.createNotificationTopic(topicToCreate).execute().body().getGuid();
        }

        // Create researcher.
        researcher = TestUserHelper.createAndSignInUser(SmsNotificationRegistrationTest.class, false,
                Role.RESEARCHER);
    }

    @Before
    public void createUser() throws Exception {
        // Create phone user, initially with data group sdk-int-1.
        SignUp phoneSignUp = new SignUp().appId(TEST_APP_ID).consent(true).phone(IntegTestUtils.PHONE);
        phoneSignUp.addDataGroupsItem("sdk-int-1");
        phoneUser = new TestUserHelper.Builder(SmsNotificationRegistrationTest.class).withConsentUser(true)
                .withSignUp(phoneSignUp).createAndSignInUser();
    }

    @AfterClass
    public static void deleteDeveloperAndResearcher() throws Exception {
        if (developer != null) {
            developer.signOutAndDeleteUser();
        }
        if (researcher != null) {
            researcher.signOutAndDeleteUser();
        }
    }

    @After
    public void deletePhoneUser() throws Exception {
        if (phoneUser != null) {
            phoneUser.signOutAndDeleteUser();
        }
    }

    @Test
    public void userCreateRegistration() throws Exception {
        ForConsentedUsersApi api = phoneUser.getClient(ForConsentedUsersApi.class);

        // Create notification.
        NotificationRegistration registration = new NotificationRegistration()
                .protocol(NotificationProtocol.SMS).endpoint(IntegTestUtils.PHONE.getNumber());
        String registrationGuid = api.createNotificationRegistration(registration).execute().body().getGuid();

        // Test get API.
        registration = api.getNotificationRegistration(registrationGuid).execute().body();
        assertEquals(registrationGuid, registration.getGuid());
        assertEquals(NotificationProtocol.SMS, registration.getProtocol());
        assertEquals(IntegTestUtils.PHONE.getNumber(), registration.getEndpoint());

        // Test list API.
        List<NotificationRegistration> registrationList = api.getNotificationRegistrations().execute().body()
                .getItems();
        assertEquals(1, registrationList.size());

        registration = registrationList.get(0);
        assertEquals(registrationGuid, registration.getGuid());
        assertEquals(NotificationProtocol.SMS, registration.getProtocol());
        assertEquals(IntegTestUtils.PHONE.getNumber(), registration.getEndpoint());

        // We automatically subscribed to autoTopic1.
        Tests.retryHelper(() -> api.getTopicSubscriptions(registrationGuid).execute().body().getItems().stream()
                        .collect(Collectors.toMap(SubscriptionStatus::getTopicGuid, SubscriptionStatus::isSubscribed)),
                map -> map.get(autoTopicGuid1) && !map.get(autoTopicGuid2) && !map.get(manualTopicGuid));

        // Manually subscribe to the manual topic. This doesn't affect the auto-topics.
        SubscriptionRequest subscriptionRequest = new SubscriptionRequest().addTopicGuidsItem(manualTopicGuid);
        api.subscribeToTopics(registrationGuid, subscriptionRequest).execute();

        Tests.retryHelper(() -> api.getTopicSubscriptions(registrationGuid).execute().body().getItems().stream()
                        .collect(Collectors.toMap(SubscriptionStatus::getTopicGuid, SubscriptionStatus::isSubscribed)),
                map -> map.get(autoTopicGuid1) && !map.get(autoTopicGuid2) && map.get(manualTopicGuid));

        // Switch to data group sdk-int-2. This flips the auto topics, but doesn't touch the manual topic.
        StudyParticipant participant = api.getUsersParticipantRecord(false).execute().body();
        participant.setDataGroups(ImmutableList.of("sdk-int-2"));
        api.updateUsersParticipantRecord(participant).execute();

        Tests.retryHelper(() -> api.getTopicSubscriptions(registrationGuid).execute().body().getItems().stream()
                        .collect(Collectors.toMap(SubscriptionStatus::getTopicGuid, SubscriptionStatus::isSubscribed)),
                map -> !map.get(autoTopicGuid1) && map.get(autoTopicGuid2) && map.get(manualTopicGuid));

        // Test delete API.
        api.deleteNotificationRegistration(registrationGuid).execute();
        registrationList = api.getNotificationRegistrations().execute().body().getItems();
        assertTrue(registrationList.stream().noneMatch(t -> t.getGuid().equals(registrationGuid)));
    }

    @Test
    public void researcherCreatesRegistration() throws Exception {
        // Create registration.
        String userId = phoneUser.getUserId();
        researcher.getClient(InternalApi.class).createSmsRegistration(userId).execute();

        // Verify the user's registration.
        List<NotificationRegistration> registrationList = researcher.getClient(NotificationsApi.class)
                .getParticipantPushNotificationRegistrations(userId).execute().body().getItems();
        assertEquals(1, registrationList.size());

        NotificationRegistration registration = registrationList.get(0);
        assertEquals(NotificationProtocol.SMS, registration.getProtocol());
        assertEquals(IntegTestUtils.PHONE.getNumber(), registration.getEndpoint());

        // Verify auto-subscriptions.
        Map<String, Boolean> subscriptionsByGuid = phoneUser.getClient(ForConsentedUsersApi.class)
                .getTopicSubscriptions(registration.getGuid()).execute().body().getItems().stream()
                .collect(Collectors.toMap(SubscriptionStatus::getTopicGuid, SubscriptionStatus::isSubscribed));
        assertTrue(subscriptionsByGuid.get(autoTopicGuid1));
        assertFalse(subscriptionsByGuid.get(autoTopicGuid2));
        assertFalse(subscriptionsByGuid.get(manualTopicGuid));
    }
}


text:
package it.prisma.presentationlayer.webui.controllers.accounting;

public class ProfilingController {

}


text:
                <a href="<?= Ice\Core\Route::getInstance('ice_security_login')->getUrl() ?>"><?= $resource['Security_Login']->get('Login form', null, 'Ice\Action\Security_Login') ?>

                <?= $resource['Security_Login']->get('Register form') ?>

<?= $resource['Security_Login']->get('sign out') ?>

                <?= $form ?>


text:
/**
 * @fileOverview
 *
 * 提供 Kity 的 OOP 支持
 */

define(function(require, exports) {

    /**
     * @class kity.Class
     * @catalog core
     * @description 所有 kity 类的基类
     * @abstract
     */
    function Class() {}

    exports.Class = Class;

    Class.__KityClassName = 'Class';

    /**
     * @method base()
     * @for kity.Class
     * @protected
     * @grammar base(name, args...) => {any}
     * @description 调用父类指定名称的函数
     * @param {string} name 函数的名称
     * @param {parameter} args... 传递给父类函数的参数
     *
     * @example
     *
     * ```js
     * var Person = kity.createClass('Person', {
     *     toString: function() {
     *         return 'I am a person';
     *     }
     * });
     *
     * var Male = kity.createClass('Male', {
     *     base: Person,
     *
     *     toString: function() {
     *         return 'I am a man';
     *     },
     *
     *     speak: function() {
     *         return this.base('toString') + ',' + this.toString();
     *     }
     * })
     * ```
     */
    Class.prototype.base = function(name) {
        var caller = arguments.callee.caller;
        var method = caller.__KityMethodClass.__KityBaseClass.prototype[name];
        return method.apply(this, Array.prototype.slice.call(arguments, 1));
    };

    /**
     * @method callBase()
     * @for kity.Class
     * @protected
     * @grammar callBase(args...) => {any}
     * @description 调用父类同名函数
     * @param {parameter} args... 传递到父类同名函数的参数
     *
     * @example
     *
     * ```js
     * var Animal = kity.createClass('Animal', {
     *     constructor: function(name) {
     *         this.name = name;
     *     },
     *     toString: function() {
     *         return 'I am an animal name ' + this.name;
     *     }
     * });
     *
     * var Dog = kity.createClass('Dog', {
     *     constructor: function(name) {
     *         this.callBase(name);
     *     },
     *     toString: function() {
     *         return this.callBase() + ', a dog';
     *     }
     * });
     *
     * var dog = new Dog('Dummy');
     * console.log(dog.toString()); // "I am an animal name Dummy, a dog";
     * ```
     */
    Class.prototype.callBase = function() {
        var caller = arguments.callee.caller;
        var method = caller.__KityMethodClass.__KityBaseClass.prototype[caller.__KityMethodName];
        return method.apply(this, arguments);
    };

    Class.prototype.mixin = function(name) {
        var caller = arguments.callee.caller;
        var mixins = caller.__KityMethodClass.__KityMixins;
        if (!mixins) {
            return this;
        }
        var method = mixins[name];
        return method.apply(this, Array.prototype.slice.call(arguments, 1));
    };

    Class.prototype.callMixin = function() {
        var caller = arguments.callee.caller;
        var methodName = caller.__KityMethodName;
        var mixins = caller.__KityMethodClass.__KityMixins;
        if (!mixins) {
            return this;
        }
        var method = mixins[methodName];
        if (methodName == 'constructor') {
            for (var i = 0, l = method.length; i < l; i++) {
                method[i].call(this);
            }
            return this;
        } else {
            return method.apply(this, arguments);
        }
    };

    /**
     * @method pipe()
     * @for kity.Class
     * @grammar pipe() => {this}
     * @description 以当前对象为上线文以及管道函数的第一个参数,执行一个管道函数
     * @param  {Function} fn 进行管道操作的函数
     *
     * @example
     *
     * ```js
     * var rect = new kity.Rect().pipe(function() {
     *     this.setWidth(500);
     *     this.setHeight(300);
     * });
     * ```
     */
    Class.prototype.pipe = function(fn) {
        if (typeof(fn) == 'function') {
            fn.call(this, this);
        }
        return this;
    };

    /**
     * @method getType()
     * @for kity.Class
     * @grammar getType() => {string}
     * @description 获得对象的类型
     *
     * @example
     *
     * ```js
     * var rect = new kity.Rect();
     * var circle = new kity.Circle();
     *
     * console.log(rect.getType()); // "Rect"
     * console.log(rect.getType()); // "Circle"
     * ```
     */
    Class.prototype.getType = function() {
        return this.__KityClassName;
    };

    /**
     * @method getClass()
     * @for kity.Class
     * @grammar getClass() => {Class}
     * @description 获得对象的类
     *
     * @example
     *
     * ```js
     * var rect = new kity.Rect();
     *
     * console.log(rect.getClass() === kity.Rect); // true
     * console.log(rect instanceof kity.Rect); // true
     * ```
     */
    Class.prototype.getClass = function() {
        return this.constructor;
    };

    // 检查基类是否调用了父类的构造函数
    // 该检查是弱检查,假如调用的代码被注释了,同样能检查成功(这个特性可用于知道建议调用,但是出于某些原因不想调用的情况)
    function checkBaseConstructorCall(targetClass, classname) {
        var code = targetClass.toString();
        if (!/this\.callBase/.test(code)) {
            throw new Error(classname + ' : 类构造函数没有调用父类的构造函数!为了安全,请调用父类的构造函数');
        }
    }

    var KITY_INHERIT_FLAG = '__KITY_INHERIT_FLAG_' + (+new Date());

    function inherit(constructor, BaseClass, classname) {
        var KityClass = eval('(function ' + classname + '( __inherit__flag ) {' +
            'if( __inherit__flag != KITY_INHERIT_FLAG ) {' +
            'KityClass.__KityConstructor.apply(this, arguments);' +
            '}' +
            'this.__KityClassName = KityClass.__KityClassName;' +
            '})');
        KityClass.__KityConstructor = constructor;

        KityClass.prototype = new BaseClass(KITY_INHERIT_FLAG);

        for (var methodName in BaseClass.prototype) {
            if (BaseClass.prototype.hasOwnProperty(methodName) && methodName.indexOf('__Kity') !== 0) {
                KityClass.prototype[methodName] = BaseClass.prototype[methodName];
            }
        }

        KityClass.prototype.constructor = KityClass;

        return KityClass;
    }

    function mixin(NewClass, mixins) {
        if (false === mixins instanceof Array) {
            return NewClass;
        }

        var i, length = mixins.length,
            proto, method;

        NewClass.__KityMixins = {
            constructor: []
        };

        for (i = 0; i < length; i++) {
            proto = mixins[i].prototype;

            for (method in proto) {
                if (false === proto.hasOwnProperty(method) || method.indexOf('__Kity') === 0) {
                    continue;
                }
                if (method === 'constructor') {
                    // constructor 特殊处理
                    NewClass.__KityMixins.constructor.push(proto[method]);
                } else {
                    NewClass.prototype[method] = NewClass.__KityMixins[method] = proto[method];
                }
            }
        }

        return NewClass;
    }

    function extend(BaseClass, extension) {
        if (extension.__KityClassName) {
            extension = extension.prototype;
        }
        for (var methodName in extension) {
            if (extension.hasOwnProperty(methodName) &&
                methodName.indexOf('__Kity') &&
                methodName != 'constructor') {
                var method = BaseClass.prototype[methodName] = extension[methodName];
                method.__KityMethodClass = BaseClass;
                method.__KityMethodName = methodName;
            }
        }
        return BaseClass;
    }

    /**
     * @method kity.createClass()
     * @grammar kity.createClass(classname, defines) => {Class}
     * @description 创建一个类
     * @param  {string} classname 类名,用于调试的时候查看,可选
     * @param  {object} defines   类定义
     *      defines.base {Class}
     *          定义的类的基类,如果不配置,则表示基类为 kity.Class
     *      defines.mixins {Class[]}
     *          定义的类要融合的类列表
     *      defines.constructor {Function}
     *          定义类的构造函数,如果父类显式定义了构造函数,需要在构造函数中使用 callBase() 方法调用父类的构造函数
     *      defines.* {Function}
     *          定义类的其它函数
     *
     * @example 创建一个类
     *
     * ```js
     * var Animal = kity.createClass('Animal', {
     *     constructor: function(name) {
     *         this.name = name;
     *     },
     *     toString: function() {
     *         return this.name;
     *     }
     * });
     *
     * var a = new Animal('kity');
     * console.log(a.toString()); // "kity"
     * ```
     *
     * @example 继承一个类
     *
     * ```js
     * var Cat = kity.createClass('Cat', {
     *     base: Animal,
     *     constructor: function(name, color) {
     *         // 调用父类构造函数
     *         this.callBase(name);
     *     },
     *     toString: function() {
     *         return 'A ' + this.color + ' cat, ' + this.callBase();
     *     }
     * });
     *
     * var cat = new Cat('kity', 'black');
     * console.log(cat.toString()); // "A black cat, kity"
     * ```
     *
     * @example 混合类的能力
     * ```js
     * var Walkable = kity.createClass('Walkable', {
     *     constructor: function() {
     *         this.speed = 'fast';
     *     },
     *     walk: function() {
     *         console.log('I am walking ' + this.speed);
     *     }
     * });
     *
     * var Dog = kity.createClass('Dog', {
     *     base: Animal,
     *     mixins: [Walkable],
     *     constructor: function(name) {
     *         this.callBase(name);
     *         this.callMixins();
     *     }
     * });
     *
     * var dog = new Dog('doggy');
     * console.log(dog.toString() + ' say:');
     * dog.walk();
     * ```
     */
    exports.createClass = function(classname, defines) {
        var constructor, NewClass, BaseClass;

        if (arguments.length === 1) {
            defines = arguments[0];
            classname = 'AnonymousClass';
        }

        BaseClass = defines.base || Class;

        if (defines.hasOwnProperty('constructor')) {
            constructor = defines.constructor;
            if (BaseClass != Class) {
                checkBaseConstructorCall(constructor, classname);
            }
        } else {
            constructor = function() {
                this.callBase.apply(this, arguments);
                this.callMixin.apply(this, arguments);
            };
        }

        NewClass = inherit(constructor, BaseClass, classname);
        NewClass = mixin(NewClass, defines.mixins);

        NewClass.__KityClassName = constructor.__KityClassName = classname;
        NewClass.__KityBaseClass = constructor.__KityBaseClass = BaseClass;

        NewClass.__KityMethodName = constructor.__KityMethodName = 'constructor';
        NewClass.__KityMethodClass = constructor.__KityMethodClass = NewClass;

        // 下面这些不需要拷贝到原型链上
        delete defines.mixins;
        delete defines.constructor;
        delete defines.base;

        NewClass = extend(NewClass, defines);

        return NewClass;
    };

    /**
     * @method kity.extendClass()
     * @grammar kity.extendClass(clazz, extension) => {Class}
     * @description 拓展一个已有的类
     *
     * @example
     *
     * ```js
     * kity.extendClass(Dog, {
     *     spark: function() {
     *         console.log('wao wao wao!');
     *     }
     * });
     *
     * new Dog().spark(); // "wao wao wao!";
     * ```
     */
    exports.extendClass = extend;

});


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for VirtualPCIControllerOption complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="VirtualPCIControllerOption">
 *   <complexContent>
 *     <extension base="{urn:vim25}VirtualControllerOption">
 *       <sequence>
 *         <element name="numSCSIControllers" type="{urn:vim25}IntOption"/>
 *         <element name="numEthernetCards" type="{urn:vim25}IntOption"/>
 *         <element name="numVideoCards" type="{urn:vim25}IntOption"/>
 *         <element name="numSoundCards" type="{urn:vim25}IntOption"/>
 *         <element name="numVmiRoms" type="{urn:vim25}IntOption"/>
 *         <element name="numVmciDevices" type="{urn:vim25}IntOption" minOccurs="0"/>
 *         <element name="numPCIPassthroughDevices" type="{urn:vim25}IntOption" minOccurs="0"/>
 *         <element name="numSasSCSIControllers" type="{urn:vim25}IntOption" minOccurs="0"/>
 *         <element name="numVmxnet3EthernetCards" type="{urn:vim25}IntOption" minOccurs="0"/>
 *         <element name="numParaVirtualSCSIControllers" type="{urn:vim25}IntOption" minOccurs="0"/>
 *         <element name="numSATAControllers" type="{urn:vim25}IntOption" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VirtualPCIControllerOption", propOrder = {
    "numSCSIControllers",
    "numEthernetCards",
    "numVideoCards",
    "numSoundCards",
    "numVmiRoms",
    "numVmciDevices",
    "numPCIPassthroughDevices",
    "numSasSCSIControllers",
    "numVmxnet3EthernetCards",
    "numParaVirtualSCSIControllers",
    "numSATAControllers"
})
public class VirtualPCIControllerOption
    extends VirtualControllerOption
{

    @XmlElement(required = true)
    protected IntOption numSCSIControllers;
    @XmlElement(required = true)
    protected IntOption numEthernetCards;
    @XmlElement(required = true)
    protected IntOption numVideoCards;
    @XmlElement(required = true)
    protected IntOption numSoundCards;
    @XmlElement(required = true)
    protected IntOption numVmiRoms;
    protected IntOption numVmciDevices;
    protected IntOption numPCIPassthroughDevices;
    protected IntOption numSasSCSIControllers;
    protected IntOption numVmxnet3EthernetCards;
    protected IntOption numParaVirtualSCSIControllers;
    protected IntOption numSATAControllers;

    /**
     * Gets the value of the numSCSIControllers property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumSCSIControllers() {
        return numSCSIControllers;
    }

    /**
     * Sets the value of the numSCSIControllers property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumSCSIControllers(IntOption value) {
        this.numSCSIControllers = value;
    }

    /**
     * Gets the value of the numEthernetCards property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumEthernetCards() {
        return numEthernetCards;
    }

    /**
     * Sets the value of the numEthernetCards property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumEthernetCards(IntOption value) {
        this.numEthernetCards = value;
    }

    /**
     * Gets the value of the numVideoCards property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumVideoCards() {
        return numVideoCards;
    }

    /**
     * Sets the value of the numVideoCards property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumVideoCards(IntOption value) {
        this.numVideoCards = value;
    }

    /**
     * Gets the value of the numSoundCards property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumSoundCards() {
        return numSoundCards;
    }

    /**
     * Sets the value of the numSoundCards property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumSoundCards(IntOption value) {
        this.numSoundCards = value;
    }

    /**
     * Gets the value of the numVmiRoms property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumVmiRoms() {
        return numVmiRoms;
    }

    /**
     * Sets the value of the numVmiRoms property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumVmiRoms(IntOption value) {
        this.numVmiRoms = value;
    }

    /**
     * Gets the value of the numVmciDevices property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumVmciDevices() {
        return numVmciDevices;
    }

    /**
     * Sets the value of the numVmciDevices property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumVmciDevices(IntOption value) {
        this.numVmciDevices = value;
    }

    /**
     * Gets the value of the numPCIPassthroughDevices property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumPCIPassthroughDevices() {
        return numPCIPassthroughDevices;
    }

    /**
     * Sets the value of the numPCIPassthroughDevices property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumPCIPassthroughDevices(IntOption value) {
        this.numPCIPassthroughDevices = value;
    }

    /**
     * Gets the value of the numSasSCSIControllers property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumSasSCSIControllers() {
        return numSasSCSIControllers;
    }

    /**
     * Sets the value of the numSasSCSIControllers property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumSasSCSIControllers(IntOption value) {
        this.numSasSCSIControllers = value;
    }

    /**
     * Gets the value of the numVmxnet3EthernetCards property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumVmxnet3EthernetCards() {
        return numVmxnet3EthernetCards;
    }

    /**
     * Sets the value of the numVmxnet3EthernetCards property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumVmxnet3EthernetCards(IntOption value) {
        this.numVmxnet3EthernetCards = value;
    }

    /**
     * Gets the value of the numParaVirtualSCSIControllers property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumParaVirtualSCSIControllers() {
        return numParaVirtualSCSIControllers;
    }

    /**
     * Sets the value of the numParaVirtualSCSIControllers property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumParaVirtualSCSIControllers(IntOption value) {
        this.numParaVirtualSCSIControllers = value;
    }

    /**
     * Gets the value of the numSATAControllers property.
     *
     * @return
     *     possible object is
     *     {@link IntOption }
     *
     */
    public IntOption getNumSATAControllers() {
        return numSATAControllers;
    }

    /**
     * Sets the value of the numSATAControllers property.
     *
     * @param value
     *     allowed object is
     *     {@link IntOption }
     *
     */
    public void setNumSATAControllers(IntOption value) {
        this.numSATAControllers = value;
    }

}


text:
package com.streamsets.datacollector.execution.snapshot;

import com.streamsets.datacollector.execution.snapshot.file.FileSnapshotStore;
import com.streamsets.datacollector.execution.snapshot.file.dagger.FileSnapshotStoreModule;
import com.streamsets.datacollector.main.RuntimeInfo;
import com.streamsets.datacollector.main.RuntimeModule;

import org.junit.BeforeClass;

import dagger.ObjectGraph;

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

public class TestFileSnapshotStore extends TestSnapshotStore {

  @BeforeClass
  public static void beforeClass() {
    System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.DATA_DIR, "./target/var");
  }

  @AfterClass
  public static void afterClass() {
    System.getProperties().remove(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.DATA_DIR);
  }

  @Before
  public void setUp() throws IOException {
    File f = new File(System.getProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.DATA_DIR));
    FileUtils.deleteDirectory(f);
    ObjectGraph objectGraph = ObjectGraph.create(FileSnapshotStoreModule.class);
    snapshotStore = objectGraph.get(FileSnapshotStore.class);
  }

  @After
  public void tearDown() {

  }

  @Test
  public void testCheckStoreImplementation() {
    Assert.assertTrue(snapshotStore instanceof FileSnapshotStore);
  }

}


text:
package org.jboss.pnc.mock.executor;

import org.jboss.pnc.spi.BuildExecutionStatus;
import org.jboss.pnc.spi.BuildResult;
import org.jboss.pnc.spi.builddriver.BuildDriverResult;
import org.jboss.pnc.spi.environment.RunningEnvironment;
import org.jboss.pnc.spi.events.BuildExecutionStatusChangedEvent;
import org.jboss.pnc.spi.executor.BuildExecutionConfiguration;
import org.jboss.pnc.spi.executor.BuildExecutionSession;
import org.jboss.pnc.spi.executor.exceptions.ExecutorException;
import org.jboss.pnc.spi.repositorymanager.RepositoryManagerResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.util.Date;
import java.util.Optional;
import java.util.function.Consumer;

/**
 * @author Matej Lazar
 */
public class BuildExecutionSessionMock implements BuildExecutionSession {

    private static final Logger log = LoggerFactory.getLogger(BuildExecutionSessionMock.class);

    private final BuildExecutionConfiguration buildExecutionConfiguration;
    private final Consumer<BuildExecutionStatusChangedEvent> onBuildExecutionStatusChangedEvent;
    private BuildExecutionStatus status;
    private ExecutorException executorException;
    private Optional<URI> liveLogsUri;
    private Date startTime;
    private RunningEnvironment runningEnvironment;
    private Date endTime;
    private BuildDriverResult buildDriverResult;
    private RepositoryManagerResult repositoryManagerResult;
    //keep record of first received failed status
    private BuildExecutionStatus failedReasonStatus;

    public BuildExecutionSessionMock(BuildExecutionConfiguration buildExecutionConfiguration, Consumer<BuildExecutionStatusChangedEvent> onBuildExecutionStatusChangedEvent) {
        liveLogsUri = Optional.empty();
        this.buildExecutionConfiguration = buildExecutionConfiguration;
        this.onBuildExecutionStatusChangedEvent = onBuildExecutionStatusChangedEvent;
    }

    @Override
    public Optional<URI> getLiveLogsUri() {
        return liveLogsUri;
    }

    @Override
    public void setLiveLogsUri(Optional<URI> liveLogsUri) {
        this.liveLogsUri = liveLogsUri;
    }

    @Override
    public void getEventLog() {

    }

    @Override
    public BuildExecutionConfiguration getBuildExecutionConfiguration() {
        return buildExecutionConfiguration;
    }

    @Override
    public BuildExecutionStatus getStatus() {
        return status;
    }

    @Override
    public void setStatus(BuildExecutionStatus status) {
        if (status.hasFailed() && failedReasonStatus == null) {
            log.debug("Setting status {} as failed reason for session {}.", status, getId());
            failedReasonStatus = status;
        }

        Optional<BuildResult> buildResult;
        if (status.isCompleted()) {
            buildResult = Optional.of(getBuildResult());
        } else {
            buildResult = Optional.empty();
        }
        BuildExecutionStatusChangedEvent statusChanged = new BuildExecutorStatusChangedEventMock(
                this.status,
                status,
                getId(),
                buildExecutionConfiguration.getId(),
                buildResult);

        log.debug("Updating build execution task {} status to {}.", getId(), statusChanged);
        this.status = status;
        onBuildExecutionStatusChangedEvent.accept(statusChanged);
        log.debug("Fired events after build execution task {} update.", getId());
    }

    private BuildResult getBuildResult() {
        if (executorException == null) {
            if (failedReasonStatus == null) {
                log.trace("Returning result of task {} with no exception.", getId());
                return new BuildResult(Optional.ofNullable(buildExecutionConfiguration),
                        Optional.ofNullable(buildDriverResult),
                        Optional.ofNullable(repositoryManagerResult),
                        Optional.empty(),
                        Optional.empty(),
                        Optional.empty(),
                        Optional.empty(),
                        Optional.empty());
            } else {
                log.trace("Returning result of task " + getId() + " with failed reason {}.", failedReasonStatus);
                return new BuildResult(Optional.ofNullable(buildExecutionConfiguration),
                        Optional.ofNullable(buildDriverResult),
                        Optional.ofNullable(repositoryManagerResult),
                        Optional.empty(),
                        Optional.of(failedReasonStatus),
                        Optional.empty(),
                        Optional.empty(),
                        Optional.empty());
            }
        } else {
            log.trace("Returning result of task " + getId() + " with exception.", executorException);
            return new BuildResult(Optional.ofNullable(buildExecutionConfiguration),
                    Optional.ofNullable(buildDriverResult),
                    Optional.ofNullable(repositoryManagerResult),
                    Optional.of(executorException),
                    Optional.ofNullable(failedReasonStatus),
                    Optional.empty(),
                    Optional.empty(),
                    Optional.empty());
        }
    }

    @Override
    public Date getStartTime() {
        return startTime;
    }

    @Override
    public ExecutorException getException() {
        return executorException;
    }

    @Override
    public void setException(ExecutorException executorException) {
        log.debug("Setting exception: {}", executorException != null ? executorException.getMessage() : "null");
        this.executorException = executorException;
    }

    @Override
    public Date getEndTime() {
        return endTime;
    }

    @Override
    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

    @Override
    public boolean hasFailed() {
        log.debug("Has failed ? executorException: {} || failedReasonStatus: {}", executorException == null ? "" : executorException.getMessage(), failedReasonStatus );
        return executorException != null || failedReasonStatus != null;
    }

    @Override
    public Integer getId() {
        return getBuildExecutionConfiguration().getId();
    }

    @Override
    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    @Override
    public RunningEnvironment getRunningEnvironment() {
        return runningEnvironment;
    }

    @Override
    public void setRunningEnvironment(RunningEnvironment runningEnvironment) {
        this.runningEnvironment = runningEnvironment;
    }

    @Override
    public void setBuildDriverResult(BuildDriverResult buildDriverResult) {
        this.buildDriverResult = buildDriverResult;
    }

    @Override
    public BuildDriverResult getBuildDriverResult() {
        return buildDriverResult;
    }

    @Override
    public void setRepositoryManagerResult(RepositoryManagerResult repositoryManagerResult) {
        this.repositoryManagerResult = repositoryManagerResult;
    }

}