text:
.biggrin{
	width: 40px;
	height: 40px;
	background: url('images/smilies/emoji/biggrin.png');
}
.confused{
	width: 40px;
	height: 40px;
	background: url('images/smilies/emoji/confused.png');
}
.cok-clearfix:before, .cok-clearfix:after {
    display: table;
    content: " ";
}
.cok-clearfix:after {
    clear: both;
}
.cok-emoji-wrapper {
    position: absolute;
    border: 1px solid #ccc;
    padding: 10px !important;
    background: #fff !important;
}
.cok-emoji-wrapper, .cok-emoji-wrapper * {
    box-sizing: content-box;
    margin: 0;
    padding: 0;
    text-decoration: none !important;
    font-size: 12px;
    cursor: default;
    z-index: 9999;
    background: #fff;
}
.cok-emoji-wrapper li {
    list-style: none;
}
.cok-emoji-wrapper.cok-hidden {
    display: none;
}
.cok-emoji-wrapper.cok-show {
    display: block;
}
/*title*/
/*向上箭头*/
.cok-emoji-wrapper .caret-down, .cok-emoji-wrapper .caret-down div{
    border-width: 10px;
    border-style: dashed dashed solid dashed;
    border-color: transparent transparent #ccc transparent;
    position: absolute;
    left: 10px;
    top: -20px;
    height: 0;
    width: 0;
    line-height: 0;
    background: transparent;
}
.cok-emoji-wrapper .caret-down div{
    top: -9px;
    left: -10px;
    border-bottom-color: #fff;
}
/*向下箭头*/
.cok-emoji-wrapper .caret-up, .cok-emoji-wrapper .caret-up div{
    border-width: 10px;
    border-style: solid dashed dashed dashed;
    border-color: #ccc transparent transparent transparent;
    position: absolute;
    left: 10px;
    bottom: -20px;
    height: 0;
    width: 0;
    line-height: 0;
    background: transparent;
}
.cok-emoji-wrapper .caret-up div{
    bottom: -9px;
    left: -10px;
    border-top-color: #fff;
}
/*向左箭头*/
.cok-emoji-wrapper .caret-right, .cok-emoji-wrapper .caret-right div{
    border-width: 10px;
    border-style: dashed solid dashed dashed;
    border-color: transparent #ccc transparent transparent;
    position: absolute;
    top: 10px;
    left: -20px;
    height: 0;
    width: 0;
    line-height: 0;
    background: transparent;
}
.cok-emoji-wrapper .caret-right div{
    left: -9px;
    top: -10px;
    border-right-color: #fff;
}
/*向右箭头*/
.cok-emoji-wrapper .caret-left, .cok-emoji-wrapper .caret-left div{
    border-width: 10px;
    border-style: dashed dashed dashed solid;
    border-color: transparent transparent transparent #ccc;
    position: absolute;
    top: 10px;
    right: -20px;
    height: 0;
    width: 0;
    line-height: 0;
    background: transparent;
}
.cok-emoji-wrapper .caret-left div{
    left: -9px;
    top: -10px;
    border-left-color: #fff;
}

.cok-emoji-wrapper .tab-nav {
    border-bottom: 1px solid #ddd;
}
.cok-emoji-wrapper .tab-item {
    position: static;
    float: left;
}
.cok-emoji-wrapper .tab-item.active>a {
    border: 1px solid #ddd;
    border-bottom-color: transparent;
    background: #fff;
    margin-top: 1px;
    margin-bottom: -1px;
    color: #555;
}
.cok-emoji-wrapper .tab-item>a {
    display: block;
    padding: 8px 12px;
    color: #08c;
    outline: 0;
    cursor: pointer;
}
/*content*/

.cok-emoji-wrapper .tab-pane {
    display: none;
    margin: 15px 0 5px 0;
}
.cok-emoji-wrapper .tab-pane.active {
    display: block;
}
.cok-emoji-wrapper .emojis{
    border-collapse: collapse;
}
.cok-emoji-wrapper .emojis td {
    background: #fff;
    border: solid 1px #ccc;
    width: 39px;
    height: 39px;
    text-align: center;
}
.cok-emoji-wrapper .emoji {
    cursor: pointer;
}
.cok-emoji-wrapper .emoji:hover {
    background: #ddd;
}
.cok-emoji-wrapper .emoji>img {
    max-width: 36px;
    max-height: 36px;
    cursor: pointer;
}


text:
/*!
 * \file
 * \brief The Mean and Standard Deviation Kernel
 * \author Erik Rainey <erik.rainey@gmail.com>
 */

#include <VX/vx.h>
#include <VX/vx_helper.h>

#include <vx_internal.h>
#include <c_model.h>

static vx_status VX_CALLBACK vxMeanStdDevKernel(vx_node node, vx_reference *parameters, vx_uint32 num)
{
    if (num == 3)
    {
        vx_image  input    = (vx_image) parameters[0];
        vx_scalar s_mean   = (vx_scalar)parameters[1];
        vx_scalar s_stddev = (vx_scalar)parameters[2];
        return vxMeanStdDev(input, s_mean, s_stddev);
    }
    return VX_ERROR_INVALID_PARAMETERS;
}

static vx_status VX_CALLBACK vxMeanStdDevInputValidator(vx_node node, vx_uint32 index)
{
    vx_status status = VX_ERROR_INVALID_PARAMETERS;
    if (index == 0)
    {
        vx_parameter param = vxGetParameterByIndex(node, index);
        vx_image image = 0;
        vx_df_image format = 0;

        vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &image, sizeof(image));
        if (image == 0)
        {
            status = VX_ERROR_INVALID_PARAMETERS;
        }
        else
        {
            status = VX_SUCCESS;
            vxQueryImage(image, VX_IMAGE_ATTRIBUTE_FORMAT, &format, sizeof(format));
            if (format != VX_DF_IMAGE_U8
#if defined(EXPERIMENTAL_USE_S16)
                && format != VX_DF_IMAGE_U16
#endif
                )
            {
                status = VX_ERROR_INVALID_PARAMETERS;
            }
            vxReleaseImage(&image);
        }
        vxReleaseParameter(&param);
    }
    return status;
}

static vx_status VX_CALLBACK vxMeanStdDevOutputValidator(vx_node node, vx_uint32 index, vx_meta_format_t *ptr)
{
    vx_status status = VX_ERROR_INVALID_PARAMETERS;
    if (index == 1 || index == 2)
    {
        ptr->type = VX_TYPE_SCALAR;
        ptr->dim.scalar.type = VX_TYPE_FLOAT32;
        status = VX_SUCCESS;
    }
    VX_PRINT(VX_ZONE_API, "%s:%u returned %d\n", __FUNCTION__, index, status);
    return status;
}

/*! \brief Declares the parameter types for \ref vxuColorConvert.
 * \ingroup group_implementation
 */
static vx_param_description_t mean_stddev_kernel_params[] = {
    {VX_INPUT,  VX_TYPE_IMAGE,   VX_PARAMETER_STATE_REQUIRED},
    {VX_OUTPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED},
    {VX_OUTPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED},
};

/*! \brief The exported kernel table entry */
vx_kernel_description_t mean_stddev_kernel = {
    VX_KERNEL_MEAN_STDDEV,
    "org.khronos.openvx.mean_stddev",
    vxMeanStdDevKernel,
    mean_stddev_kernel_params, dimof(mean_stddev_kernel_params),
    vxMeanStdDevInputValidator,
    vxMeanStdDevOutputValidator,
    NULL,
    NULL,
};

redpajama_set_name: RedPajamaGithub


text:
using NUnit.Framework;
using Shouldly;

namespace Serilog.Sinks.Amazon.Kinesis.Tests.PersistedBookmarkTests
{
    class WhenFileNameAndPositionAreUpdated : PersistedBookmarkTestBase
    {
        [TestCase(true, false, TestName = "Given empty file exists")]
        [TestCase(true, true, TestName = "Given bookmark with garbage exists")]
        [TestCase(false, false, TestName = "Given bookmark does not exist")]
        public void AfterOpening_ThenCanReadSameFileNameAndPosition(
            bool fileExists,
            bool containsGarbage
            )
        {
            if (fileExists) { GivenFileExist(); } else { GivenFileDoesNotExist(); }
            if (containsGarbage) GivenFileContainsGarbage(1000);

            WhenBookmarkIsCreated();
            WhenUpdatedWithFileNameAndPosition();

            Target.ShouldSatisfyAllConditions(
                () => Target.Position.ShouldBe(Position),
                () => Target.FileName.ShouldBe(FileName)
                );
        }

        [TestCase(true, false, TestName = "Given empty file exists")]
        [TestCase(true, true, TestName = "Given bookmark with garbage exists")]
        [TestCase(false, false, TestName = "Given bookmark does not exist")]
        public void AfterClosedAndReOpened_ThenCanReadSameFileNameAndPosition(
            bool fileExists,
            bool containsGarbage
            )
        {
            if (fileExists) { GivenFileExist(); } else { GivenFileDoesNotExist(); }
            if (containsGarbage) GivenFileContainsGarbage(1000);

            WhenBookmarkIsCreated();
            WhenUpdatedWithFileNameAndPosition();
            WhenBookmarkIsClosed();
            WhenBookmarkIsCreated();

            Target.ShouldSatisfyAllConditions(
                () => Target.Position.ShouldBe(Position),
                () => Target.FileName.ShouldBe(FileName)
                );
        }
    }
}


text:
require 'spec_helper'

module Alchemy
  describe Element do
    # to prevent memoization
    before { Element.instance_variable_set("@definitions", nil) }

    # ClassMethods

    describe '.new_from_scratch' do
      it "should initialize an element by name from scratch" do
        el = Element.new_from_scratch(name: 'article')
        expect(el).to be_valid
      end

      it "should raise an error if the given name is not defined in the elements.yml" do
        expect {
          Element.new_from_scratch(name: 'foobar')
        }.to raise_error(ElementDefinitionError)
      end

      it "should take the first part of an given name containing a hash (#)" do
        el = Element.new_from_scratch(name: 'article#header')
        expect(el.name).to eq("article")
      end

      it "should merge given attributes into defined ones" do
        el = Element.new_from_scratch(name: 'article', page_id: 1)
        expect(el.page_id).to eq(1)
      end

      it "should not have forbidden attributes from definition" do
        el = Element.new_from_scratch(name: 'article')
        expect(el.contents).to eq([])
      end
    end

    describe '.copy' do
      let(:element) { FactoryGirl.create(:element, :create_contents_after_create => true, :tag_list => 'red, yellow') }

      it "should not create contents from scratch" do
        copy = Element.copy(element)
        expect(copy.contents.count).to eq(element.contents.count)
      end

      it "should create a new record with all attributes of source except given differences" do
        copy = Element.copy(element, {:name => 'foobar'})
        expect(copy.name).to eq('foobar')
      end

      it "should make copies of all contents of source" do
        copy = Element.copy(element)
        expect(copy.contents.pluck(:id)).not_to eq(element.contents.pluck(:id))
      end

      it "the copy should include source element tags" do
        copy = Element.copy(element)
        expect(copy.tag_list).to eq(element.tag_list)
      end
    end

    describe '.definitions' do
      it "should allow erb generated elements" do
        expect(Element.definitions.collect { |el| el['name']} ).to include('erb_element')
      end

      context "without existing yml files" do
        before { allow(File).to receive(:exists?).and_return(false) }

        it "should raise an error" do
          expect { Element.definitions }.to raise_error(LoadError)
        end
      end

      context "without any definitions in elements.yml" do
        # Yes, YAML.load returns false if an empty file exists.
        before { allow(YAML).to receive(:load).and_return(false) }

        it "should return an empty array" do
          expect(Element.definitions).to eq([])
        end
      end
    end

    describe '.display_name_for' do
      it "should return the translation for the given name" do
        expect(I18n).to receive(:t).with('subheadline', scope: "element_names", default: 'Subheadline').and_return('Überschrift')
        expect(Element.display_name_for('subheadline')).to eq('Überschrift')
      end

      it "should return the humanized name if no translation found" do
        expect(Element.display_name_for('not_existing_one')).to eq('Not existing one')
      end
    end

    describe '.excluded' do
      it "should return all elements but excluded ones" do
        FactoryGirl.create(:element, :name => 'article')
        FactoryGirl.create(:element, :name => 'article')
        excluded = FactoryGirl.create(:element, :name => 'claim')
        expect(Element.excluded(['claim'])).not_to include(excluded)
      end
    end

    describe '.named' do
      it "should return all elements by name" do
        element_1 = FactoryGirl.create(:element, :name => 'article')
        element_2 = FactoryGirl.create(:element, :name => 'article')
        elements = Element.named(['article'])
        expect(elements).to include(element_1)
        expect(elements).to include(element_2)
      end
    end

    describe '.not_in_cell' do
      it "should return all elements that are not in a cell" do
        Element.delete_all
        FactoryGirl.create(:element, :cell_id => 6)
        FactoryGirl.create(:element, :cell_id => nil)
        expect(Element.not_in_cell.size).to eq(1)
      end
    end

    describe '.published' do
      it "should return all public elements" do
        element_1 = FactoryGirl.create(:element, :public => true)
        element_2 = FactoryGirl.create(:element, :public => true)
        elements = Element.published
        expect(elements).to include(element_1)
        expect(elements).to include(element_2)
      end
    end

    context 'trash' do
      let(:element) { FactoryGirl.create(:element, page_id: 1) }

      describe '.not_trashed' do
        before { element }

        it "should return a collection of not trashed elements" do
          expect(Element.not_trashed.to_a).to eq([element])
        end
      end

      describe ".trashed" do
        before { element.trash! }

        it "should return a collection of trashed elements" do
          expect(Element.trashed.to_a).to eq([element])
        end
      end
    end

    describe '.all_from_clipboard_for_page' do
      let(:element_1) { FactoryGirl.build_stubbed(:element) }
      let(:element_2) { FactoryGirl.build_stubbed(:element, name: 'news') }
      let(:page)      { FactoryGirl.build_stubbed(:public_page) }
      let(:clipboard) { [{'id' => element_1.id.to_s}, {'id' => element_2.id.to_s}] }

      before do
        allow(Element).to receive(:all_from_clipboard).and_return([element_1, element_2])
      end

      it "return all elements from clipboard that could be placed on page" do
        elements = Element.all_from_clipboard_for_page(clipboard, page)
        expect(elements).to eq([element_1])
        expect(elements).not_to eq([element_2])
      end

      context "page nil" do
        it "returns empty array" do
          expect(Element.all_from_clipboard_for_page(clipboard, nil)).to eq([])
        end
      end

      context "clipboard nil" do
        it "returns empty array" do
          expect(Element.all_from_clipboard_for_page(nil, page)).to eq([])
        end
      end
    end

    # InstanceMethods

    describe '#all_contents_by_type' do
      let(:element) { FactoryGirl.create(:element, create_contents_after_create: true) }
      let(:expected_contents) { element.contents.essence_texts }

      context "with namespaced essence type" do
        subject { element.all_contents_by_type('Alchemy::EssenceText') }
        it { is_expected.not_to be_empty }
        it('should return the correct list of essences') { is_expected.to eq(expected_contents) }
      end

      context "without namespaced essence type" do
        subject { element.all_contents_by_type('EssenceText') }
        it { is_expected.not_to be_empty }
        it('should return the correct list of essences') { is_expected.to eq(expected_contents) }
      end
    end

    describe '#available_page_cell_names' do
      let(:page)    { FactoryGirl.create(:public_page) }
      let(:element) { FactoryGirl.create(:element, page: page) }

      context "with page having cells defining the correct elements" do
        before do
          allow(Cell).to receive(:definitions).and_return([
            {'name' => 'header', 'elements' => ['article', 'headline']},
            {'name' => 'footer', 'elements' => ['article', 'text']},
            {'name' => 'sidebar', 'elements' => ['teaser']}
          ])
        end

        it "should return a list of all cells from given page this element could be placed in" do
          FactoryGirl.create(:cell, name: 'header', page: page)
          FactoryGirl.create(:cell, name: 'footer', page: page)
          FactoryGirl.create(:cell, name: 'sidebar', page: page)
          expect(element.available_page_cell_names(page)).to include('header')
          expect(element.available_page_cell_names(page)).to include('footer')
        end

        context "but without any cells" do
          it "should return the 'nil cell'" do
            expect(element.available_page_cell_names(page)).to eq(['for_other_elements'])
          end
        end

      end

      context "with page having cells defining the wrong elements" do
        before do
          allow(Cell).to receive(:definitions).and_return([
            {'name' => 'header', 'elements' => ['download', 'headline']},
            {'name' => 'footer', 'elements' => ['contactform', 'text']},
            {'name' => 'sidebar', 'elements' => ['teaser']}
          ])
        end

        it "should return the 'nil cell'" do
          FactoryGirl.create(:cell, name: 'header', page: page)
          FactoryGirl.create(:cell, name: 'footer', page: page)
          FactoryGirl.create(:cell, name: 'sidebar', page: page)
          expect(element.available_page_cell_names(page)).to eq(['for_other_elements'])
        end
      end
    end

    describe '#content_by_type' do
      before(:each) do
        @element = FactoryGirl.create(:element, :name => 'headline')
        @content = @element.contents.first
      end

      context "with namespaced essence type" do
        it "should return content by passing a essence type" do
          expect(@element.content_by_type('Alchemy::EssenceText')).to eq(@content)
        end
      end

      context "without namespaced essence type" do
        it "should return content by passing a essence type" do
          expect(@element.content_by_type('EssenceText')).to eq(@content)
        end
      end
    end

    describe '#display_name' do
      let(:element) { Element.new(name: 'article') }

      it "should call .display_name_for" do
        expect(Element).to receive(:display_name_for).with(element.name)
        element.display_name
      end
    end

    describe '#essence_error_messages' do
      let(:element) { Element.new(name: 'article') }

      it "should return the translation with the translated content label" do
        expect(I18n).to receive(:t)
          .with('content_names.content', default: 'Content')
          .and_return('Content')
        expect(I18n).to receive(:t)
          .with('content', scope: "content_names.article", default: 'Content')
          .and_return('Contenido')
        expect(I18n).to receive(:t)
          .with('article.content.invalid', {
            scope: "content_validations",
            default: [:"fields.content.invalid", :"errors.invalid"],
            field: "Contenido"})
        expect(element).to receive(:essence_errors)
          .and_return({'content' => [:invalid]})

        element.essence_error_messages
      end
    end

    describe '#display_name_with_preview_text' do
      let(:element) { FactoryGirl.build_stubbed(:element, name: 'Foo') }

      it "returns a string with display name and preview text" do
        allow(element).to receive(:preview_text).and_return('Fula')
        expect(element.display_name_with_preview_text).to eq("Foo: Fula")
      end
    end

    describe '#dom_id' do
      let(:element) { FactoryGirl.build_stubbed(:element) }

      it "returns an string from element name and id" do
        expect(element.dom_id).to eq("#{element.name}_#{element.id}")
      end
    end

    describe '#preview_text' do
      let(:element) { FactoryGirl.build_stubbed(:element) }
      let(:content) { mock_model(Content, preview_text: 'Lorem', preview_content?: false) }
      let(:content_2) { mock_model(Content, preview_text: 'Lorem', preview_content?: false) }
      let(:preview_content) { mock_model(Content, preview_text: 'Lorem', preview_content?: true) }

      context "without a content marked as preview" do
        let(:contents) { [content, content_2] }
        before { allow(element).to receive(:contents).and_return(contents) }

        it "returns the preview text of first content found" do
          expect(content).to receive(:preview_text).with(30)
          element.preview_text
        end
      end

      context "with a content marked as preview" do
        let(:contents) { [content, preview_content] }
        before { allow(element).to receive(:contents).and_return(contents) }

        it "should return the preview_text of this content" do
          expect(preview_content).to receive(:preview_text).with(30)
          element.preview_text
        end
      end

      context "without any contents present" do
        before { allow(element).to receive(:contents).and_return([]) }

        it "should return nil" do
          expect(element.preview_text).to be_nil
        end
      end
    end

    context 'previous and next elements.' do
      let(:page) { FactoryGirl.create(:language_root_page) }

      before(:each) do
        @element1 = FactoryGirl.create(:element, :page => page, :name => 'headline')
        @element2 = FactoryGirl.create(:element, :page => page)
        @element3 = FactoryGirl.create(:element, :page => page, :name => 'text')
      end

      describe '#prev' do
        it "should return previous element on same page" do
          expect(@element3.prev).to eq(@element2)
        end

        context "with name as parameter" do
          it "should return previous of this kind" do
            expect(@element3.prev('headline')).to eq(@element1)
          end
        end
      end

      describe '#next' do
        it "should return next element on same page" do
          expect(@element2.next).to eq(@element3)
        end

        context "with name as parameter" do
          it "should return next of this kind" do
            expect(@element1.next('text')).to eq(@element3)
          end
        end
      end
    end

    context 'retrieving contents, essences and ingredients' do
      let(:element) { FactoryGirl.create(:element, :name => 'news', :create_contents_after_create => true) }

      it "should return an ingredient by name" do
        expect(element.ingredient('news_headline')).to eq(EssenceText.first.ingredient)
      end

      it "should return the content for rss title" do
        expect(element.content_for_rss_title).to eq(element.contents.find_by_name('news_headline'))
      end

      it "should return the content for rss descdefinitionription" do
        expect(element.content_for_rss_description).to eq(element.contents.find_by_name('body'))
      end

      context 'if no content is defined as rss title' do
        before { expect(element).to receive(:content_descriptions).and_return([]) }

        it "should return nil" do
          expect(element.content_for_rss_title).to be_nil
        end
      end

      context 'if no content is defined as rss description' do
        before { expect(element).to receive(:content_descriptions).and_return([]) }

        it "should return nil" do
          expect(element.content_for_rss_description).to be_nil
        end
      end
    end

    describe '#update_contents' do
      subject { element.update_contents(params) }

      let(:page)     { build_stubbed(:page) }
      let(:element)  { build_stubbed(:element, page: page) }
      let(:content1) { double(:content, id: 1) }
      let(:content2) { double(:content, id: 2) }

      before { allow(element).to receive(:contents).and_return([content1]) }

      context "with attributes hash is nil" do
        let(:params) { nil }
        it { is_expected.to be_truthy }
      end

      context "with valid attributes hash" do
        let(:params) { {"#{content1.id}" => {body: 'Title'}} }

        context 'when certain content is not part of the attributes hash (cause it was not filled by the user)' do
          before do
            allow(element).to receive(:contents).and_return([content1, content2])
          end

          it 'does not try to update that content' do
            expect(content1).to receive(:update_essence).with({body: 'Title'}).and_return(true)
            expect(content2).to_not receive(:update_essence)
            subject
          end
        end

        context 'with passing validations' do
          before do
            expect(content1).to receive(:update_essence).with({body: 'Title'}).and_return(true)
          end

          it { is_expected.to be_truthy }

          it "does not add errors" do
            subject
            expect(element.errors).to be_empty
          end
        end

        context 'with failing validations' do
          it "adds error and returns false" do
            expect(content1).to receive(:update_essence).with({body: 'Title'}).and_return(false)
            is_expected.to be_falsey
            expect(element.errors).not_to be_empty
          end
        end
      end
    end

    describe '.after_update' do
      let(:page)    { create(:page) }
      let(:element) { create(:element, page: page) }
      let(:now)     { Time.now }

      before do
        allow(Time).to receive(:now).and_return(now)
      end

      context 'with touchable pages' do
        let(:locker)  { mock_model('DummyUser') }
        let(:pages)   { [page] }

        before do
          expect(Alchemy.user_class).to receive(:stamper).at_least(:once).and_return(locker.id)
        end

        it "updates page timestamps" do
          expect(element).to receive(:touchable_pages).and_return(pages)
          expect(pages).to receive(:update_all).with({updated_at: now, updater_id: locker.id})
          element.save
        end

        it "updates page userstamps" do
          element.save
          page.reload
          expect(page.updater_id).to eq(locker.id)
        end
      end

      context 'with cell associated' do
        let(:cell) { mock_model('Cell') }

        before do
          expect(element).to receive(:cell).at_least(:once).and_return(cell)
        end

        it "updates timestamp of cell" do
          expect(element.cell).to receive(:touch)
          element.save
        end
      end

      context 'without cell associated' do
        it "does not update timestamp of cell" do
          expect { element.save }.to_not raise_error
        end
      end
    end

    describe '#taggable?' do
      let(:element) { FactoryGirl.build(:element) }

      context "definition has 'taggable' key with true value" do
        it "should return true" do
          expect(element).to receive(:definition).and_return({
            'name' => 'article',
            'taggable' => true
          })
          expect(element.taggable?).to be_truthy
        end
      end

      context "definition has 'taggable' key with foo value" do
        it "should return false" do
          expect(element).to receive(:definition).and_return({
            'name' => 'article',
            'taggable' => 'foo'
          })
          expect(element.taggable?).to be_falsey
        end
      end

      context "definition has no 'taggable' key" do
        it "should return false" do
          expect(element).to receive(:definition).and_return({
            'name' => 'article'
          })
          expect(element.taggable?).to be_falsey
        end
      end
    end

    describe '#trash!' do
      let(:element)         { FactoryGirl.create(:element, page_id: 1, cell_id: 1) }
      let(:trashed_element) { element.trash! ; element }
      subject               { trashed_element }

      it             { is_expected.not_to be_public }
      it             { is_expected.to be_folded }

      describe '#position' do
        subject { super().position }
        it { is_expected.to be_nil }
      end
      specify        { expect { element.trash! }.to_not change(element, :page_id) }
      specify        { expect { element.trash! }.to_not change(element, :cell_id) }

      context "with already one trashed element on the same page" do
        let(:element_2) { FactoryGirl.create(:element, page_id: 1) }

        before do
          trashed_element
          element_2
        end

        it "it should be possible to trash another" do
          element_2.trash!
          expect(Element.trashed.to_a).to include(trashed_element, element_2)
        end
      end
    end

    describe "#to_partial_path" do
      it "should return a String in the format of 'alchemy/elements/#{name}_view'" do
        expect(Element.new(name: 'mock').to_partial_path).to eq('alchemy/elements/mock_view')
      end
    end

    describe '#cache_key' do
      let(:page) { stub_model(Page, published_at: Time.now - 1.week) }
      let(:element) { stub_model(Element, page: page, updated_at: Time.now) }

      subject { element.cache_key }

      before do
        expect(Page).to receive(:current_preview).and_return(preview)
      end

      context "when current page rendered in preview mode" do
        let(:preview) { page }

        it { is_expected.to eq("alchemy/elements/#{element.id}-#{element.updated_at}") }
      end

      context "when current page not in preview mode" do
        let(:preview) { nil }

        it { is_expected.to eq("alchemy/elements/#{element.id}-#{page.published_at}") }
      end
    end

    it_behaves_like "having a hint" do
      let(:subject) { Element.new }
    end
  end
end


text:
var config = require('../package').pdnUi;
var filterPath = prefix => {
    var trash = /\/+\s*$|^\s+|\s+$/g;
    return `${(prefix || '').replace(trash, '')}`;
};
['src', 'target'].forEach(pathType=> {
    config[pathType] = filterPath(config[pathType]);
});

var trash = /^\s*\/+|\/+\s*$|^\s+|\s+$/g;
config.deployModes = Object.keys(config.inEnv).map(item=>(item || '').replace(trash, ''));
config.basics = config.basics.map(basic=>(basic || '').replace(trash, ''));
config.targetPathFor = {};
config.deployModes.forEach(mode=> {
    config.targetPathFor[mode] = `${config.target}/${mode}`;
});
module.exports = config;


text:
package org.danyuan.application.softm.roles.controller;

import java.util.List;

import org.danyuan.application.common.base.BaseController;
import org.danyuan.application.common.base.BaseControllerImpl;
import org.danyuan.application.common.base.BaseResult;
import org.danyuan.application.common.base.ResultUtil;
import org.danyuan.application.softm.roles.po.SysRolesInfo;
import org.danyuan.application.softm.roles.service.SysRolesInfoService;
import org.danyuan.application.softm.roles.vo.SysRolesVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 文件名 : SysRolesController.java
 * 包 名 : tk.ainiyue.admin.roles.controller
 * 描 述 : TODO(用一句话描述该文件做什么)
 * 机能名称:
 * 技能ID :
 * 作 者 : Tenghui.Wang
 * 时 间 : 2016年7月17日 下午3:54:27
 * 版 本 : V1.0
 */
@RestController
@RequestMapping("/sysRoles")
public class SysRolesController extends BaseControllerImpl<SysRolesInfo> implements BaseController<SysRolesInfo> {
	//
	private static final Logger	logger	= LoggerFactory.getLogger(SysRolesController.class);

	//
	@Autowired
	private SysRolesInfoService	sysRolesInfoService;

	/**
	 * 方法名: findAll
	 * 功 能: TODO(这里用一句话描述这个方法的作用)
	 * 参 数: @return
	 * 返 回: List<SysRolesJurisdictionInfo>
	 * 作 者 : Tenghui.Wang
	 * @throws
	 */
	@Override
	@RequestMapping(path = "/findAll", method = RequestMethod.POST)
	public BaseResult<List<SysRolesInfo>> findAll(@RequestBody SysRolesInfo info) {
		logger.info("sysRolesList", SysRolesController.class);
		return ResultUtil.success(sysRolesInfoService.findAll());
	}

	@GetMapping("/detail/{uuid}")
	public ModelAndView name(@PathVariable("uuid") String uuid) {
		logger.info("detail", SysRolesController.class);
		ModelAndView modelAndView = new ModelAndView("softm/roles/sysrolesinfodetail");
		SysRolesInfo info = new SysRolesInfo();
		info.setUuid(uuid);
		modelAndView.addObject("sysRolesInfo", sysRolesInfoService.findOne(info));
		return modelAndView;
	}

	@RequestMapping(path = "/findAllRoleBySearchText", method = RequestMethod.POST)
	public List<SysRolesInfo> findAllRoleBySearchText(@RequestBody SysRolesVo info) {
		logger.info("findAllBySearchText", SysRolesController.class);
		return sysRolesInfoService.findAllRoleBySearchText(info.getUserId());
	}
}


text:
typedef void(^WYXMLParserOperationCompleteBlock)(BOOL isSuccess,id obj,NSError *error);

@interface WYXMLParserContext : NSObject

@property (nonatomic, strong) NSString *xpath;
@property (nonatomic, strong) NSDictionary *elementsMap;

@end

@interface WYXMLParserOperation : NSObject

@property (nonatomic, strong) dispatch_queue_t completeQueue;
@property (nonatomic, strong) dispatch_queue_t processQueue;

+ (instancetype)operationForParsingXMLData:(NSData *)data completeBlock:(WYXMLParserOperationCompleteBlock)block;
+ (instancetype)operationForParsingXMLData:(NSData *)data context:(WYXMLParserContext *)ctx completeBlock:(WYXMLParserOperationCompleteBlock)block;
- (void)start;

@end

@interface WYLibXMLParserOperation : WYXMLParserOperation
@end

@interface WYCocoaXMLParserOperation : WYXMLParserOperation
@end

@interface WYTreeNodeXMLParserOperation : WYXMLParserOperation
@end


text: echo "Finishing end2"


text:
package com.intellij.ide;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.DefaultLogger;
import com.intellij.openapi.extensions.ExtensionNotApplicableException;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.testFramework.LightPlatformTestCase;
import com.intellij.testFramework.LoggedErrorProcessor;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.Alarm;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.TestTimeOut;
import com.intellij.util.concurrency.EdtExecutorService;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.InvocationEvent;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class IdeEventQueueTest extends LightPlatformTestCase {
  public void testManyEventsStress() {
    int N = 100000;
    PlatformTestUtil.startPerformanceTest("Event queue dispatch", 10000, () -> {
      UIUtil.dispatchAllInvocationEvents();
      AtomicInteger count = new AtomicInteger();
      for (int i = 0; i < N; i++) {
        SwingUtilities.invokeLater(count::incrementAndGet);
      }
      UIUtil.dispatchAllInvocationEvents();
      assertEquals(N, count.get());
    }).assertTiming();
  }

  public void testKeyboardEventsAreDetected() throws InterruptedException {
    assertTrue(EventQueue.isDispatchThread());
    IdeEventQueue ideEventQueue = IdeEventQueue.getInstance();
    assertSame(ideEventQueue, Toolkit.getDefaultToolkit().getSystemEventQueue());
    PlatformTestUtil.dispatchAllEventsInIdeEventQueue();
    Set<AWTEvent> isDispatched = new HashSet<>();
    ideEventQueue.addDispatcher(e -> {
      isDispatched.add(e);
      LOG.debug("dispatch: "+e);
      return false;
    }, getTestRootDisposable());
    ideEventQueue.addPostprocessor(e -> {
      LOG.debug("post dispatch: "+e);
      return false;
    }, getTestRootDisposable());
    ideEventQueue.addPostEventListener(e -> {
      LOG.debug("post event hook: "+e);
      return false;
    }, getTestRootDisposable());

    int posted = ideEventQueue.myKeyboardEventsPosted.get();
    int dispatched = ideEventQueue.myKeyboardEventsDispatched.get();
    KeyEvent pressX = new KeyEvent(new JLabel("mykeypress"), KeyEvent.KEY_PRESSED, 1, InputEvent.ALT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK, 11, 'x');
    postCarefully(pressX);
    assertEquals(posted+1, ideEventQueue.myKeyboardEventsPosted.get());
    assertEquals(dispatched, ideEventQueue.myKeyboardEventsDispatched.get());
    dispatchAllInvocationEventsUntilOtherEvent();
    // either it's dispatched by this method or the f*@$ing VCSRefresh activity stomped in, started modal progress and consumed all events via IdeEventQueue.pumpEventsForHierarchy
    assertTrue(isDispatched.contains(pressX) || isConsumed(pressX));

    assertEquals(posted+1, ideEventQueue.myKeyboardEventsPosted.get());
    assertEquals(dispatched+1, ideEventQueue.myKeyboardEventsDispatched.get());

    // do not react to other events
    AWTEvent ev2 = new ActionEvent(new JLabel(), ActionEvent.ACTION_PERFORMED, "myCommand");
    postCarefully(ev2);

    assertEquals(posted+1, ideEventQueue.myKeyboardEventsPosted.get());
    assertEquals(dispatched+1, ideEventQueue.myKeyboardEventsDispatched.get());
    dispatchAllInvocationEventsUntilOtherEvent();
    // either it's dispatched by this method or the f*@$ing VCSRefresh activity stomped in, started modal progress and dispatched all events via IdeEventQueue.pumpEventsForHierarchy by itself
    assertTrue(isDispatched.contains(ev2));

    assertEquals(posted+1, ideEventQueue.myKeyboardEventsPosted.get());
    assertEquals(dispatched+1, ideEventQueue.myKeyboardEventsDispatched.get());

    KeyEvent keyRelease = new KeyEvent(new JLabel("mykeyrelease"), KeyEvent.KEY_RELEASED, 1, InputEvent.ALT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK, 11, 'x');
    postCarefully(keyRelease);

    assertEquals(posted+2, ideEventQueue.myKeyboardEventsPosted.get());
    assertEquals(dispatched+1, ideEventQueue.myKeyboardEventsDispatched.get());

    dispatchAllInvocationEventsUntilOtherEvent();
    // either it's dispatched by this method or the f*@$ing VCSRefresh activity stomped in, started modal progress and consumed all events via IdeEventQueue.pumpEventsForHierarchy
    assertTrue(isDispatched.contains(keyRelease) || isConsumed(keyRelease));

    assertEquals(posted+2, ideEventQueue.myKeyboardEventsPosted.get());
    assertEquals(dispatched+2, ideEventQueue.myKeyboardEventsDispatched.get());
  }

  private static void postCarefully(AWTEvent event) {
    LOG.debug("posting " + event);
    IdeEventQueue ideEventQueue = IdeEventQueue.getInstance();
    boolean posted = ideEventQueue.doPostEvent(event);
    assertTrue("Was not posted: "+event, posted);
    boolean mustBeConsumed = event.getID() == ActionEvent.ACTION_PERFORMED;
    assertEquals(mustBeConsumed, ReflectionUtil.getField(AWTEvent.class, event, boolean.class, "consumed").booleanValue());
    assertTrue(ReflectionUtil.getField(AWTEvent.class, event, boolean.class, "isPosted"));
  }
  private static boolean isConsumed(InputEvent event) {
    return event.isConsumed();
  }

  // need this because everybody can post some crazy stuff to IdeEventQueue, so we have to filter InvocationEvents out
  private static void dispatchAllInvocationEventsUntilOtherEvent() throws InterruptedException {
    while (true) {
      AWTEvent event = PlatformTestUtil.dispatchNextEventIfAny();
      LOG.debug("event dispatched in dispatchAll() "+event+"; -"+(event instanceof InvocationEvent ? "continuing" : "returning"));
      if (!(event instanceof InvocationEvent)) break;
    }
  }

  private static class MyException extends RuntimeException {
  }
  private static void throwMyException() {
    throw new MyException();
  }

  private static void checkMyExceptionThrownImmediately() {
    TestTimeOut t = TestTimeOut.setTimeout(10, TimeUnit.SECONDS);
    while (true) {
      try {
        UIUtil.dispatchAllInvocationEvents();
      }
      catch (Throwable e) {
        assertTrue(e.toString(), ExceptionUtil.causedBy(e, MyException.class));
        break;
      }
      assertFalse(t.timedOut());
    }
  }

  public void testExceptionInAlarmMustThrowImmediatelyInTests() {
    Alarm alarm = new Alarm();
    alarm.addRequest(()-> throwMyException(), 1);
    checkMyExceptionThrownImmediately();
  }

  public void testExceptionInInvokeLateredRunnableMustThrowImmediatelyInTests() {
    SwingUtilities.invokeLater(() -> throwMyException());
    checkMyExceptionThrownImmediately();
  }

  public void testAppInvokeLateredRunnableMustThrowImmediatelyInTests() {
    SwingUtilities.invokeLater(()->ApplicationManager.getApplication().invokeLater(()->throwMyException()));
    checkMyExceptionThrownImmediately();
  }

  public void testEdtExecutorRunnableMustThrowImmediatelyInTests() {
    ApplicationManager.getApplication().invokeLater(() -> throwMyException(), ModalityState.NON_MODAL);
    checkMyExceptionThrownImmediately();
  }

  public void testEdtScheduledExecutorRunnableMustThrowImmediatelyInTests() {
    EdtExecutorService.getScheduledExecutorInstance().schedule(()->throwMyException(), 1, TimeUnit.MILLISECONDS);
    checkMyExceptionThrownImmediately();
  }

  public void testNoExceptionEvenCreatedByThanosExtensionNotApplicableExceptionMustKillEDT() {
    assert SwingUtilities.isEventDispatchThread();
    DefaultLogger.disableStderrDumping(getTestRootDisposable());
    throwInIdeEventQueueDispatch(ExtensionNotApplicableException.create(), null); // ControlFlowException silently ignored
    throwInIdeEventQueueDispatch(new ProcessCanceledException(), null);  // ControlFlowException silently ignored
    Error error = new Error();
    throwInIdeEventQueueDispatch(error, error);
  }

  private void throwInIdeEventQueueDispatch(@NotNull Throwable toThrow, Throwable expectedToBeLogged) {
    AtomicBoolean run = new AtomicBoolean();
    InvocationEvent event = new InvocationEvent(this, () -> {
      run.set(true);
      ExceptionUtil.rethrow(toThrow);
    });
    Runnable runnable = () -> {
      IdeEventQueue ideEventQueue = IdeEventQueue.getInstance();
      ideEventQueue.executeInProductionModeEvenThoughWeAreInTests(() -> ideEventQueue.dispatchEvent(event));
    };

    Throwable error;
    if (expectedToBeLogged != null) {
      error = LoggedErrorProcessor.executeAndReturnLoggedError(runnable);
    }
    else {
      runnable.run();
      error = null;
    }
    assertTrue(run.get());
    assertSame(expectedToBeLogged, error);
  }

  public void testPumpEventsForHierarchyMustExitOnIsFutureDoneCondition() {
    assert SwingUtilities.isEventDispatchThread();
    IdeEventQueue ideEventQueue = IdeEventQueue.getInstance();
    CompletableFuture<Object> future = new CompletableFuture<>();
    TestTimeOut cancelEventTime = TestTimeOut.setTimeout(2, TimeUnit.SECONDS);
    JLabel component = new JLabel();
    long start = System.currentTimeMillis();
    ideEventQueue.pumpEventsForHierarchy(component, future, __ -> {
      if (cancelEventTime.isTimedOut()) {
        future.complete(null);
      }
      // post InvocationEvent to give getNextEvent work to do
      SwingUtilities.invokeLater(EmptyRunnable.getInstance());
    });
    long elapsedMs = System.currentTimeMillis() - start;
    // check that first, we did exit the pumpEventsForHierarchy and second, at the right moment
    assertTrue(String.valueOf(elapsedMs), cancelEventTime.isTimedOut());
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="description" content="">
  <meta name="keywords" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="author" content="">
  <title>hammerStrike</title>

  <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@100;700&display=swap" rel="stylesheet">

<hammerStrike/>


text:
dep 'colorpicker-antetype.cask'

dep 'gimp.cask'

dep 'osx-media-imaging' do
  requires 'colorpicker-antetype.cask'
  requires 'gimp.cask'
end


text:
package types

// KStemTokenFilter type.
//
// https://github.com/elastic/elasticsearch-specification/blob/4ca0cc05d3ae3fa06c2cd7be91905b656a474334/specification/_types/analysis/token_filters.ts#L238-L240
type KStemTokenFilter struct {
	Type    string  `json:"type,omitempty"`
	Version *string `json:"version,omitempty"`
}

// NewKStemTokenFilter returns a KStemTokenFilter.
func NewKStemTokenFilter() *KStemTokenFilter {
	r := &KStemTokenFilter{}

	r.Type = "kstem"

	return r
}


text:
package com.microsoft.azure.cognitiveservices.search.customimagesearch.models;

import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;

/**
 * Defines values for Freshness.
 */
public final class Freshness extends ExpandableStringEnum<Freshness> {
    /** Static value Day for Freshness. */
    public static final Freshness DAY = fromString("Day");

    /** Static value Week for Freshness. */
    public static final Freshness WEEK = fromString("Week");

    /** Static value Month for Freshness. */
    public static final Freshness MONTH = fromString("Month");

    /**
     * Creates or finds a Freshness from its string representation.
     * @param name a name to look for
     * @return the corresponding Freshness
     */
    @JsonCreator
    public static Freshness fromString(String name) {
        return fromString(name, Freshness.class);
    }

    /**
     * @return known Freshness values
     */
    public static Collection<Freshness> values() {
        return values(Freshness.class);
    }
}


text:
package teams.control;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * {@link Controller} that handles the javascript of a user.
 */
@Controller
public class JSController {

  @RequestMapping("/js/coin-teams.js")
  public String js(ModelMap modelMap, HttpServletRequest request) {
    return "js";
  }

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Backlog4net.Api
{
    using Option;

    /// <summary>
    /// Executes Backlog Notification APIs.
    /// </summary>
    public interface NotificationMethods
    {
        /// <summary>
        /// Returns the notifications.
        /// </summary>
        /// <param name="params">the query parameters</param>
        /// <returns>the notifications in a list.</returns>
        Task<ResponseList<Notification>> GetNotificationsAsync(QueryParams @params = null, CancellationToken? token = null);

        /// <summary>
        /// Returns the count of the notifications.
        /// </summary>
        /// <param name="params">the notification parameters</param>
        /// <returns>the count of the notifications</returns>
        Task<int> GetNotificationCountAsync(GetNotificationCountParams @params, CancellationToken? token = null);

        /// <summary>
        /// Resets the count of the notifications.
        /// </summary>
        /// <returns>the count of the reset notifications</returns>
        Task<int> ResetNotificationCountAsync(CancellationToken? token = null);

        /// <summary>
        /// Marks the notification as already read.
        /// </summary>
        /// <param name="notificationId">the notification identifier</param>
        Task MarkAsReadNotificationAsync(long notificationId, CancellationToken? token = null);
    }
}


text:
<?php

namespace phpManufaktur\Basic\Control\CMS\WebsiteBaker;

class OutputFilter
{
    protected static $cms_type = null;
    protected static $cms_version = null;

    /**
     * Check type and version of the parent CMS, set the values
     * to the class properties
     *
     */
    protected function checkCMS()
    {
        if (defined('LEPTON_VERSION')) {
            self::$cms_type = 'LEPTON';
            self::$cms_version = LEPTON_VERSION;
        }
        elseif (defined('CAT_VERSION')) {
            self::$cms_type = 'BlackCat';
            self::$cms_version = CAT_VERSION;
        }
        elseif (defined('WB_VERSION')) {
            self::$cms_type = 'WebsiteBaker';
            self::$cms_version = WB_VERSION;
            // fix for WB 2.8.4
            if ((self::$cms_version == '2.8.3') && file_exists(WB_PATH.'/setup.ini.php')) {
                self::$cms_version = '2.8.4';
            }
        }
        else {
            self::$cms_type = '- unknown -';
            self::$cms_version = '0.0.0';
        }
    }

    /**
     * Get the URL for the current requested URI
     *
     * @param boolean $remove_parameter - if true strip the parameter string
     * @return string
     */
    public static function getCurrentPageURL($remove_parameter=true)
    {
        $pageURL = 'http';
        if (isset($_SERVER["HTTPS"]) && (!empty($_SERVER['HTTPS']))) {
            $pageURL .= "s";
        }

        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        }
        else {
            $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }

        if ($remove_parameter && strpos($pageURL, '?')) {
            $pageURL = substr($pageURL, 0, strpos($pageURL, '?'));
        }

        return $pageURL;
    }

    /**
     * Get the URL of the submitted PAGE_ID - check for special pages like
     * TOPICS and/or NEWS and return the URL of the TOPIC/NEW page if active
     *
     * @param integer $page_id
     * @return boolean|string
     */
    public static function getURLbyPageID($page_id)
    {
        global $database;
        global $post_id;

        if (defined('TOPIC_ID') && (TOPIC_ID > 0)) {
            // this is a TOPICS page
            $SQL = "SELECT `link` FROM `".TABLE_PREFIX."mod_topics` WHERE `topic_id`='".TOPIC_ID."'";
            $link = $database->get_one($SQL);
            if ($database->is_error()) {
                trigger_error(sprintf('[%s - %s] %s', __FUNCTION__, __LINE__, $database->get_error()), E_USER_ERROR);
                return false;
            }
            // include TOPICS settings
            global $topics_directory;
            include WB_PATH . '/modules/topics/module_settings.php';
            return WB_URL . $topics_directory . $link . PAGE_EXTENSION;
        }

        if (!is_null($post_id) || (defined('POST_ID') && (POST_ID > 0))) {
            // this is a NEWS page
            $id = (defined('POST_ID')) ? POST_ID : $post_id;
            $SQL = "SELECT `link` FROM `".TABLE_PREFIX."mod_news_posts` WHERE `post_id`='$id'";
            $link = $database->get_one($SQL);
            if ($database->is_error()) {
                trigger_error(sprintf('[%s - %s] %s', __FUNCTION__, __LINE__, $database->get_error()), E_USER_ERROR);
                return false;
            }
            return WB_URL.PAGES_DIRECTORY.$link.PAGE_EXTENSION;
        }

        $SQL = "SELECT `link` FROM `".TABLE_PREFIX."pages` WHERE `page_id`='$page_id'";
        $link = $database->get_one($SQL, MYSQL_ASSOC);
        if ($database->is_error()) {
            trigger_error(sprintf('[%s - %s] %s', __FUNCTION__, __LINE__, $database->get_error()), E_USER_ERROR);
            return false;
        }
        return WB_URL.PAGES_DIRECTORY.$link.PAGE_EXTENSION;
    }

    /**
     * Execute the content filter for the kitFramework.
     * Extract CMS parameters like type, version, path, url, id of the calling
     * page and other, additional routes all parameters of a kitCommand and all
     * $_REQUESTs to the kitCommand routine of the kitFramework.
     *
     * @param string $content
     * @return string $content
     */
    public function parse($content)
    {
        global $post_id;
        global $page_id;

        // check CMS type and version
        $this->checkCMS();

        $id = defined('PAGE_ID') ? PAGE_ID : $page_id;

        // collect the main information about CMS, page and user
        $parse = array(
            'cms' => array(
                'type' => self::$cms_type,
                'version' => self::$cms_version,
                'locale' => strtolower(LANGUAGE),
                'page_id' => ($id > 0) ? $id : -1,
                'page_url' => ($id > 0) ? $this->getURLbyPageID($id) : $this->getCurrentPageURL(),
                'page_visibility' => VISIBILITY,
                'remove_commands' => ($id == 0),
                'user' => array(
                    'id' => (isset($_SESSION['USER_ID'])) ? $_SESSION['USER_ID'] : -1,
                    'name' => (isset($_SESSION['USERNAME'])) ? $_SESSION['USERNAME'] : '',
                    'email' => (isset($_SESSION['EMAIL'])) ? $_SESSION['EMAIL'] : ''
                ),
                'special' => array(
                    'post_id' => (!is_null($post_id) || defined('POST_ID')) ? defined('POST_ID') ? POST_ID : $post_id : null,
                    'topic_id' => defined('TOPIC_ID') ? TOPIC_ID : null
                )
            ),
            'GET' => $_GET,
            'POST' => $_POST,
            'content' => $content,
        );

        $options = array(
            CURLOPT_POST => true,
            CURLOPT_HEADER => false,
            CURLOPT_URL => WB_URL.'/kit2/kit_parser',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_POSTFIELDS => http_build_query(array('parse' => $parse), '', '&'),
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false
        );
        // use the connection multiple times by using a cookie to identify
        if (!isset($_SESSION['KIT2_COOKIE_FILE']) || !file_exists($_SESSION['KIT2_COOKIE_FILE'])) {
            $_SESSION['KIT2_COOKIE_FILE'] = WB_PATH.'/kit2/temp/session/'.uniqid('outputfilter_');
            $options[CURLOPT_COOKIEJAR] = $_SESSION['KIT2_COOKIE_FILE'];
        }
        else {
            $options[CURLOPT_COOKIEFILE] = $_SESSION['KIT2_COOKIE_FILE'];
        }

        $ch = curl_init();
        curl_setopt_array($ch, $options);

        if (false === ($content = curl_exec($ch))) {
            trigger_error(curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);
        return $content;
    }
}


text:
package org.apache.hadoop.hbase.client;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hbase.DoNotRetryIOException;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * This subclass of {@link org.apache.hadoop.hbase.client.RetriesExhaustedException}
 * is thrown when we have more information about which rows were causing which
 * exceptions on what servers.  You can call {@link #mayHaveClusterIssues()}
 * and if the result is false, you have input error problems, otherwise you
 * may have cluster issues.  You can iterate over the causes, rows and last
 * known server addresses via {@link #getNumExceptions()} and
 * {@link #getCause(int)}, {@link #getRow(int)} and {@link #getHostnamePort(int)}.
 */
@SuppressWarnings("serial")
@InterfaceAudience.Public
@InterfaceStability.Stable
public class RetriesExhaustedWithDetailsException
extends RetriesExhaustedException {
  List<Throwable> exceptions;
  List<? extends Row> actions;
  List<String> hostnameAndPort;

  public RetriesExhaustedWithDetailsException(List<Throwable> exceptions,
                                              List<? extends Row> actions,
                                              List<String> hostnameAndPort) {
    super("Failed " + exceptions.size() + " action" +
        pluralize(exceptions) + ": " +
        getDesc(exceptions, actions, hostnameAndPort));

    this.exceptions = exceptions;
    this.actions = actions;
    this.hostnameAndPort = hostnameAndPort;
  }

  public List<Throwable> getCauses() {
    return exceptions;
  }

  public int getNumExceptions() {
    return exceptions.size();
  }

  public Throwable getCause(int i) {
    return exceptions.get(i);
  }

  public Row getRow(int i) {
    return actions.get(i);
  }

  public String getHostnamePort(final int i) {
    return this.hostnameAndPort.get(i);
  }

  public boolean mayHaveClusterIssues() {
    boolean res = false;

    // If all of the exceptions are DNRIOE not exception
    for (Throwable t : exceptions) {
      if ( !(t instanceof DoNotRetryIOException)) {
        res = true;
      }
    }
    return res;
  }

  public static String pluralize(Collection<?> c) {
    return pluralize(c.size());
  }

  public static String pluralize(int c) {
    return c > 1 ? "s" : "";
  }

  public static String getDesc(List<Throwable> exceptions,
                               List<? extends Row> actions,
                               List<String> hostnamePort) {
    String s = getDesc(classifyExs(exceptions));
    StringBuilder addrs = new StringBuilder(s);
    addrs.append("servers with issues: ");
    Set<String> uniqAddr = new HashSet<String>();
    uniqAddr.addAll(hostnamePort);

    for(String addr : uniqAddr) {
      addrs.append(addr).append(", ");
    }
    return s;
  }

  public String getExhaustiveDescription() {
    StringWriter errorWriter = new StringWriter();
    PrintWriter pw = new PrintWriter(errorWriter);
    for (int i = 0; i < this.exceptions.size(); ++i) {
      Throwable t = this.exceptions.get(i);
      Row action = this.actions.get(i);
      String server = this.hostnameAndPort.get(i);
      pw.append("exception");
      if (this.exceptions.size() > 1) {
        pw.append(" #" + i);
      }
      pw.append(" from " + server + " for "
        + ((action == null) ? "unknown key" : Bytes.toStringBinary(action.getRow())));
      if (t != null) {
        pw.println();
        t.printStackTrace(pw);
      }
    }
    pw.flush();
    return errorWriter.toString();
  }

  public static Map<String, Integer> classifyExs(List<Throwable> ths) {
    Map<String, Integer> cls = new HashMap<String, Integer>();
    for (Throwable t : ths) {
      if (t == null) continue;
      String name = "";
      if (t instanceof DoNotRetryIOException) {
        name = t.getMessage();
      } else {
        name = t.getClass().getSimpleName();
      }
      Integer i = cls.get(name);
      if (i == null) {
        i = 0;
      }
      i += 1;
      cls.put(name, i);
    }
    return cls;
  }

  public static String getDesc(Map<String,Integer> classificaton) {
    StringBuilder classificatons =new StringBuilder(11);
    for (Map.Entry<String, Integer> e : classificaton.entrySet()) {
      classificatons.append(e.getKey());
      classificatons.append(": ");
      classificatons.append(e.getValue());
      classificatons.append(" time");
      classificatons.append(pluralize(e.getValue()));
      classificatons.append(", ");
    }
    return classificatons.toString();
  }

}


text:
package net.tridentsdk.server.entity.vehicle;

import net.tridentsdk.base.Position;
import net.tridentsdk.entity.types.EntityType;
import net.tridentsdk.entity.vehicle.Boat;
import net.tridentsdk.server.entity.TridentEntity;

import java.util.UUID;

/**
 * Represents a boat
 *
 * @author The TridentSDK Team
 */
public class TridentBoat extends TridentEntity implements Boat {
    public TridentBoat(UUID uuid, Position spawnPosition) {
        super(uuid, spawnPosition);
    }

    @Override
    public EntityType type() {
        return EntityType.BOAT;
    }
}


text:
class AuditTrail
  include Hearsay::Subscriber::ActiveRecord

  subscribe_to :all, :update

  # Track all model changes
  def self.update(event)
    Log.json! event
  end
end


text:
#ifndef MAIL_INDEX_PRIVATE_H
#define MAIL_INDEX_PRIVATE_H

#include "file-lock.h"
#include "mail-index.h"
#include "mail-index-util.h"
#include "mail-index-view-private.h"
#include "mail-index-transaction-private.h"

#include <sys/stat.h>

struct mail_transaction_header;
struct mail_transaction_log_view;
struct mail_index_sync_map_ctx;

/* How large index files to mmap() instead of reading to memory. */
#define MAIL_INDEX_MMAP_MIN_SIZE (1024*64)
/* How many times to retry opening index files if read/fstat returns ESTALE.
   This happens with NFS when the file has been deleted (ie. index file was
   rewritten by another computer than us). */
#define MAIL_INDEX_ESTALE_RETRY_COUNT NFS_ESTALE_RETRY_COUNT
/* Large extension header sizes are probably caused by file corruption, so
   try to catch them by limiting the header size. */
#define MAIL_INDEX_EXT_HEADER_MAX_SIZE (1024*1024*16-1)

/* Write to main index file when bytes-to-be-read-from-log is between these
   values. */
#define MAIL_INDEX_MIN_WRITE_BYTES (1024*8)
#define MAIL_INDEX_MAX_WRITE_BYTES (1024*128)

#define MAIL_INDEX_IS_IN_MEMORY(index) \
	((index)->dir == NULL)

#define MAIL_INDEX_MAP_IS_IN_MEMORY(map) \
	((map)->rec_map->mmap_base == NULL)

#define MAIL_INDEX_MAP_IDX(map, idx) \
	((struct mail_index_record *) \
	 PTR_OFFSET((map)->rec_map->records, (idx) * (map)->hdr.record_size))

#define MAIL_TRANSACTION_FLAG_UPDATE_IS_INTERNAL(u) \
	((((u)->add_flags | (u)->remove_flags) & MAIL_INDEX_FLAGS_MASK) == 0 && \
	 (u)->modseq_inc_flag == 0)

#define MAIL_INDEX_EXT_KEYWORDS "keywords"

typedef int mail_index_expunge_handler_t(struct mail_index_sync_map_ctx *ctx,
					 uint32_t seq, const void *data,
					 void **sync_context, void *context);
typedef int mail_index_sync_handler_t(struct mail_index_sync_map_ctx *ctx,
				      uint32_t seq, void *old_data,
				      const void *new_data, void **context);
typedef void mail_index_sync_lost_handler_t(struct mail_index *index);

#define MAIL_INDEX_HEADER_SIZE_ALIGN(size) \
	(((size) + 7) & ~7)

struct mail_index_ext {
	const char *name;
	uint32_t index_idx; /* index ext_id */
	uint32_t reset_id;
	uint32_t ext_offset; /* points to beginning of mail_index_ext_header */
	uint32_t hdr_offset; /* points to mail_index_ext_header.data[] */
	uint32_t hdr_size; /* size of mail_index_ext_header.data[] */
	uint16_t record_offset;
	uint16_t record_size;
	uint16_t record_align;
};

struct mail_index_ext_header {
	uint32_t hdr_size; /* size of data[] */
	uint32_t reset_id;
	uint16_t record_offset;
	uint16_t record_size;
	uint16_t record_align;
	uint16_t name_size;
	/* unsigned char name[name_size] */
	/* unsigned char data[hdr_size] (starting 64bit aligned) */
};

struct mail_index_keyword_header {
	uint32_t keywords_count;
	/* struct mail_index_keyword_header_rec[] */
	/* char name[][] */
};

struct mail_index_keyword_header_rec {
	uint32_t unused; /* for backwards compatibility */
	uint32_t name_offset; /* relative to beginning of name[] */
};

enum mail_index_sync_handler_type {
	MAIL_INDEX_SYNC_HANDLER_FILE	= 0x01,
	MAIL_INDEX_SYNC_HANDLER_HEAD	= 0x02,
	MAIL_INDEX_SYNC_HANDLER_VIEW	= 0x04
};

struct mail_index_sync_handler {
	mail_index_sync_handler_t *callback;
        enum mail_index_sync_handler_type type;
};

struct mail_index_registered_ext {
	const char *name;
	uint32_t index_idx; /* index ext_id */
	uint32_t hdr_size; /* size of mail_index_ext_header.data[] */
	uint16_t record_size;
	uint16_t record_align;

	struct mail_index_sync_handler sync_handler;
	mail_index_expunge_handler_t *expunge_handler;

	void *expunge_context;
	unsigned int expunge_handler_call_always:1;
};

struct mail_index_record_map {
	ARRAY(struct mail_index_map *) maps;

	void *mmap_base;
	size_t mmap_size, mmap_used_size;

	buffer_t *buffer;

	void *records; /* struct mail_index_record[] */
	unsigned int records_count;

	struct mail_index_map_modseq *modseq;
	uint32_t last_appended_uid;
};

struct mail_index_map {
	struct mail_index *index;
	int refcount;

	struct mail_index_header hdr;
	const void *hdr_base;
	buffer_t *hdr_copy_buf;

	pool_t extension_pool;
	ARRAY(struct mail_index_ext) extensions;
	ARRAY(uint32_t) ext_id_map; /* index -> file */

	ARRAY(unsigned int) keyword_idx_map; /* file -> index */

	struct mail_index_record_map *rec_map;
};

struct mail_index_module_register {
	unsigned int id;
};

union mail_index_module_context {
	struct mail_index_module_register *reg;
};

struct mail_index {
	char *dir, *prefix;

	struct mail_cache *cache;
	struct mail_transaction_log *log;

	unsigned int open_count;
	enum mail_index_open_flags flags;
	enum fsync_mode fsync_mode;
	enum mail_index_fsync_mask fsync_mask;
	mode_t mode;
	gid_t gid;
	char *gid_origin;

	pool_t extension_pool;
	ARRAY(struct mail_index_registered_ext) extensions;

	uint32_t ext_hdr_init_id;
	void *ext_hdr_init_data;

	ARRAY(mail_index_sync_lost_handler_t *) sync_lost_handlers;

	char *filepath;
	int fd;

	struct mail_index_map *map;
	uint32_t indexid;
	unsigned int inconsistency_id;

	/* last_read_log_file_* contains the seq/offsets we last read from
	   the main index file's headers. these are used to figure out when
	   the main index file should be updated, and if we can update it
	   by writing on top of it or if we need to recreate it. */
	uint32_t last_read_log_file_seq;
	uint32_t last_read_log_file_head_offset;
	uint32_t last_read_log_file_tail_offset;
	struct stat last_read_stat;

	/* transaction log head seq/offset when we last fscked */
	uint32_t fsck_log_head_file_seq;
	uoff_t fsck_log_head_file_offset;

	/* syncing will update this if non-NULL */
	struct mail_index_transaction_commit_result *sync_commit_result;

	int lock_type;
	unsigned int lock_id_counter;
	enum file_lock_method lock_method;
	unsigned int max_lock_timeout_secs;

	struct file_lock *file_lock;
	struct dotlock *dotlock;

	pool_t keywords_pool;
	ARRAY_TYPE(keywords) keywords;
	HASH_TABLE(char *, void *) keywords_hash; /* name -> unsigned int idx */

	uint32_t keywords_ext_id;
	uint32_t modseq_ext_id;

	unsigned int view_count;

	/* Module-specific contexts. */
	ARRAY(union mail_index_module_context *) module_contexts;

	char *error;
	unsigned int nodiskspace:1;
	unsigned int index_lock_timeout:1;

	unsigned int index_delete_requested:1; /* next sync sets it deleted */
	unsigned int index_deleted:1; /* no changes allowed anymore */
	unsigned int log_sync_locked:1;
	unsigned int readonly:1;
	unsigned int mapping:1;
	unsigned int syncing:1;
	unsigned int need_recreate:1;
	unsigned int index_min_write:1;
	unsigned int modseqs_enabled:1;
	unsigned int initial_create:1;
	unsigned int initial_mapped:1;
	unsigned int fscked:1;
};

extern struct mail_index_module_register mail_index_module_register;

/* Add/replace sync handler for specified extra record. */
void mail_index_register_expunge_handler(struct mail_index *index,
					 uint32_t ext_id, bool call_always,
					 mail_index_expunge_handler_t *callback,
					 void *context);
void mail_index_unregister_expunge_handler(struct mail_index *index,
					   uint32_t ext_id);
void mail_index_register_sync_handler(struct mail_index *index, uint32_t ext_id,
				      mail_index_sync_handler_t *cb,
				      enum mail_index_sync_handler_type type);
void mail_index_unregister_sync_handler(struct mail_index *index,
					uint32_t ext_id);
void mail_index_register_sync_lost_handler(struct mail_index *index,
					   mail_index_sync_lost_handler_t *cb);
void mail_index_unregister_sync_lost_handler(struct mail_index *index,
					mail_index_sync_lost_handler_t *cb);

int mail_index_create_tmp_file(struct mail_index *index, const char **path_r);

int mail_index_try_open_only(struct mail_index *index);
void mail_index_close_file(struct mail_index *index);
int mail_index_reopen_if_changed(struct mail_index *index);
/* Update/rewrite the main index file from index->map */
void mail_index_write(struct mail_index *index, bool want_rotate);

void mail_index_flush_read_cache(struct mail_index *index, const char *path,
				 int fd, bool locked);

int mail_index_lock_fd(struct mail_index *index, const char *path, int fd,
		       int lock_type, unsigned int timeout_secs,
		       struct file_lock **lock_r);

/* Allocate a new empty map. */
struct mail_index_map *mail_index_map_alloc(struct mail_index *index);
/* Replace index->map with the latest index changes. This may reopen the index
   file and/or it may read the latest changes from transaction log. The log is
   read up to EOF, but non-synced expunges are skipped.

   If we mmap()ed the index file, the map is returned locked.

   Returns 1 = ok, 0 = corrupted, -1 = error. */
int mail_index_map(struct mail_index *index,
		   enum mail_index_sync_handler_type type);
/* Unreference given mapping and unmap it if it's dropped to zero. */
void mail_index_unmap(struct mail_index_map **map);

/* Clone a map. The returned map is always in memory. */
struct mail_index_map *mail_index_map_clone(const struct mail_index_map *map);
void mail_index_record_map_move_to_private(struct mail_index_map *map);
/* Move a mmaped map to memory. */
void mail_index_map_move_to_memory(struct mail_index_map *map);
void mail_index_fchown(struct mail_index *index, int fd, const char *path);

bool mail_index_map_lookup_ext(struct mail_index_map *map, const char *name,
			       uint32_t *idx_r);
uint32_t
mail_index_map_register_ext(struct mail_index_map *map,
			    const char *name, uint32_t ext_offset,
			    const struct mail_index_ext_header *ext_hdr);
bool mail_index_map_get_ext_idx(struct mail_index_map *map,
				uint32_t ext_id, uint32_t *idx_r);
const struct mail_index_ext *
mail_index_view_get_ext(struct mail_index_view *view, uint32_t ext_id);

void mail_index_map_lookup_seq_range(struct mail_index_map *map,
				     uint32_t first_uid, uint32_t last_uid,
				     uint32_t *first_seq_r,
				     uint32_t *last_seq_r);

int mail_index_map_check_header(struct mail_index_map *map);
bool mail_index_check_header_compat(struct mail_index *index,
				    const struct mail_index_header *hdr,
				    uoff_t file_size);
int mail_index_map_parse_extensions(struct mail_index_map *map);
int mail_index_map_parse_keywords(struct mail_index_map *map);

void mail_index_map_init_extbufs(struct mail_index_map *map,
				 unsigned int initial_count);
int mail_index_map_ext_get_next(struct mail_index_map *map,
				unsigned int *offset,
				const struct mail_index_ext_header **ext_hdr_r,
				const char **name_r);
int mail_index_map_ext_hdr_check(const struct mail_index_header *hdr,
				 const struct mail_index_ext_header *ext_hdr,
				 const char *name, const char **error_r);
unsigned int mail_index_map_ext_hdr_offset(unsigned int name_len);

void mail_index_view_transaction_ref(struct mail_index_view *view);
void mail_index_view_transaction_unref(struct mail_index_view *view);

void mail_index_fsck_locked(struct mail_index *index);

void mail_index_set_error(struct mail_index *index, const char *fmt, ...)
	ATTR_FORMAT(2, 3);
/* "%s failed with index file %s: %m" */
void mail_index_set_syscall_error(struct mail_index *index,
				  const char *function);
/* "%s failed with file %s: %m" */
void mail_index_file_set_syscall_error(struct mail_index *index,
				       const char *filepath,
				       const char *function);

#endif


text:
import django_filters
from django_filters.rest_framework import FilterSet

from events.models import SupplementLog, UserActivity, UserActivityLog, SleepLog, DailyProductivityLog

class SupplementLogFilter(FilterSet):
    supplement_uuid = django_filters.UUIDFilter(name='supplement__uuid')
    start_time = django_filters.IsoDateTimeFilter(name='time', lookup_expr='gte')
    end_time = django_filters.IsoDateTimeFilter(name='time', lookup_expr='lte')

    class Meta:
        model = SupplementLog
        fields = [
            'supplement_uuid',
            'quantity',
            'time',
            'source',
            'uuid',
            'start_time',
            'end_time',
        ]

class UserActivityFilter(FilterSet):
    class Meta:
        model = UserActivity
        fields = [
            'name',
            'uuid',
        ]

class UserActivityLogFilter(FilterSet):
    user_activity_uuid = django_filters.UUIDFilter(name='user_activity__uuid')
    start_time = django_filters.IsoDateTimeFilter(name='time', lookup_expr='gte')
    end_time = django_filters.IsoDateTimeFilter(name='time', lookup_expr='lte')

    class Meta:
        model = UserActivityLog
        fields = [
            'uuid',
            'time',
            'duration_minutes',
            'user_activity_uuid',
            'start_time',
            'end_time',
        ]

class SleepLogFilter(FilterSet):
    class Meta:
        model = SleepLog
        fields = [
            'uuid',
            'start_time',
            'end_time',
        ]

class DailyProductivityLogFilter(FilterSet):
    start_date = django_filters.DateFilter(name='date', lookup_expr='gte')
    end_date = django_filters.DateFilter(name='date', lookup_expr='lte')

    class Meta:
        model = DailyProductivityLog
        fields = [
            'uuid',
            'date',
            'source',
            'very_productive_time_minutes',
            'productive_time_minutes',
            'neutral_time_minutes',
            'distracting_time_minutes',
            'very_distracting_time_minutes',
            'start_date',
            'end_date'
        ]


text:
package com.github.antag99.aquarria;

import java.util.Scanner;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.github.antag99.aquarria.ui.IngameScreen;
import com.github.antag99.aquarria.xnb.Steam;

public class Aquarria extends Game {
	private Batch batch;
	private Stage stage;
	private ScreenViewport viewport;
	private Preferences preferences;

	private FileHandle terrariaAssets;
	private FileHandle terrariaDirectory;

	private IngameScreen ingameScreen;

	public Aquarria() {
	}

	private void processAssets() {
		terrariaAssets = Gdx.files.local("assets-terraria");

		System.out.println("Terraria directory: " + terrariaDirectory.path());
		System.out.println("Processing vanilla assets...");
		try {
			long startTime = System.currentTimeMillis();

			ContentExtractor extractor = new ContentExtractor(terrariaDirectory.child("Content"), terrariaAssets);
			extractor.convert();

			long time = System.currentTimeMillis() - startTime;
			System.out.println("Done. Took " + time / 1000f + " seconds");
		} catch (Throwable ex) {
			System.err.println("Error extracting assets. Exiting.");
			ex.printStackTrace();
			Gdx.app.exit();
			return;
		}
	}

	@Override
	public void create() {
		/* load preferences */
		preferences = Gdx.app.getPreferences("aquarria");

		/* locate terraria directory */
		if (!preferences.contains("terrariaDirectory")) {
			terrariaDirectory = Steam.findTerrariaDirectory();
		} else {
			terrariaDirectory = new FileHandle(preferences.getString("terrariaDirectory"));
		}

		while (terrariaDirectory == null || !terrariaDirectory.exists()) {
			System.out.println("Terraria installation directory not found.");
			System.out.print("Enter terraria installation directory: ");
			@SuppressWarnings("resource")
			Scanner scanner = new Scanner(System.in);
			terrariaDirectory = new FileHandle(scanner.nextLine());
			savePreferences();
		}
		savePreferences();

		/* process vanilla terraria assets */
		processAssets();

		batch = new SpriteBatch();
		viewport = new ScreenViewport();
		stage = new Stage(viewport, batch);

		Gdx.input.setInputProcessor(stage);

		Assets.initialize();
		GameRegistry.initialize();
		ingameScreen = new IngameScreen(this);

		setScreen(ingameScreen);
	}

	private void savePreferences() {
		preferences.putString("terrariaDirectory", terrariaDirectory.path());
		preferences.flush();
	}

	@Override
	public void dispose() {
		super.dispose();
		ingameScreen.dispose();
		Assets.dispose();
		batch.dispose();
		savePreferences();
	}

	public Stage getStage() {
		return stage;
	}

	public Batch getBatch() {
		return batch;
	}

	@Override
	public void render() {
		Gdx.gl.glClearColor(0.6f, 0.6f, 1f, 1f);
		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

		super.render();

		stage.act();
		stage.draw();
	}

	@Override
	public void resize(int width, int height) {
		viewport.update(width, height, true);
		super.resize(width, height);
	}
}


text:
@interface ScenarioController : NSObject

- (id)init;
- (void) setVisualFeedback:(VisualFeedback *)f;

@property(retain) VisualFeedback * gVisualFeedback;
@property(retain) ScenarioDrawer * scenarioDrawer;
@end


text:
package net.coding.program.common;

/**
 * Created by chenchao on 15/4/24
 *
 */
public class GlobalSetting {

    private GlobalSetting() {
    }

    private static GlobalSetting sGlobalSetting;

    public static GlobalSetting getInstance() {
        if (sGlobalSetting == null) {
            sGlobalSetting = new GlobalSetting();
        }

        return sGlobalSetting;
    }

    private String mNoNotifyGlobalKey = "";

    public void setMessageNoNotify(String globalKey) {
        mNoNotifyGlobalKey = globalKey;
    }

    public void removeMessageNoNotify() {
        mNoNotifyGlobalKey = "";
    }

    public String getMessageNotify() {
        return mNoNotifyGlobalKey;
    }
}


text:
#ifndef _INDUSTRIAL_IO_H_
#define _INDUSTRIAL_IO_H_

#include <linux/device.h>
#include <linux/cdev.h>
#include <linux/irq.h>
#include "sysfs.h"
#include "chrdev.h"

/* IIO TODO LIST */
/*
 * Provide means of adjusting timer accuracy.
 * Currently assumes nano seconds.
 */

/* Event interface flags */
#define IIO_BUSY_BIT_POS 1

/* naughty temporary hack to match these against the event version
   - need to flattern these together */
enum iio_chan_type {
	/* real channel types */
	IIO_IN,
	IIO_OUT,
	IIO_CURRENT,
	IIO_POWER,
	IIO_ACCEL,
	IIO_IN_DIFF,
	IIO_GYRO,
	IIO_MAGN,
	IIO_LIGHT,
	IIO_INTENSITY,
	IIO_PROXIMITY,
	IIO_TEMP,
	IIO_INCLI,
	IIO_ROT,
	IIO_ANGL,
	IIO_TIMESTAMP,
};

#define IIO_MOD_X			0
#define IIO_MOD_LIGHT_BOTH		0
#define IIO_MOD_Y			1
#define IIO_MOD_LIGHT_IR		1
#define IIO_MOD_Z			2
#define IIO_MOD_X_AND_Y			3
#define IIO_MOD_X_ANX_Z			4
#define IIO_MOD_Y_AND_Z			5
#define IIO_MOD_X_AND_Y_AND_Z		6
#define IIO_MOD_X_OR_Y			7
#define IIO_MOD_X_OR_Z			8
#define IIO_MOD_Y_OR_Z			9
#define IIO_MOD_X_OR_Y_OR_Z		10

/* Could add the raw attributes as well - allowing buffer only devices */
enum iio_chan_info_enum {
	IIO_CHAN_INFO_SCALE_SHARED,
	IIO_CHAN_INFO_SCALE_SEPARATE,
	IIO_CHAN_INFO_OFFSET_SHARED,
	IIO_CHAN_INFO_OFFSET_SEPARATE,
	IIO_CHAN_INFO_CALIBSCALE_SHARED,
	IIO_CHAN_INFO_CALIBSCALE_SEPARATE,
	IIO_CHAN_INFO_CALIBBIAS_SHARED,
	IIO_CHAN_INFO_CALIBBIAS_SEPARATE,
	IIO_CHAN_INFO_PEAK_SHARED,
	IIO_CHAN_INFO_PEAK_SEPARATE,
	IIO_CHAN_INFO_PEAK_SCALE_SHARED,
	IIO_CHAN_INFO_PEAK_SCALE_SEPARATE,
};

/**
 * struct iio_chan_spec - specification of a single channel
 * @type:		What type of measurement is the channel making.
 * @channel:		What number or name do we wish to asign the channel.
 * @channel2:		If there is a second number for a differential
 *			channel then this is it. If modified is set then the
 *			value here specifies the modifier.
 * @address:		Driver specific identifier.
 * @scan_index:	Monotonic index to give ordering in scans when read
 *			from a buffer.
 * @scan_type:		Sign:		's' or 'u' to specify signed or unsigned
 *			realbits:	Number of valid bits of data
 *			storage_bits:	Realbits + padding
 *			shift:		Shift right by this before masking out
 *					realbits.
 * @info_mask:		What information is to be exported about this channel.
 *			This includes calibbias, scale etc.
 * @event_mask:	What events can this channel produce.
 * @extend_name:	Allows labeling of channel attributes with an
 *			informative name. Note this has no effect codes etc,
 *			unlike modifiers.
 * @processed_val:	Flag to specify the data access attribute should be
 *			*_input rather than *_raw.
 * @modified:		Does a modifier apply to this channel. What these are
 *			depends on the channel type.  Modifier is set in
 *			channel2. Examples are IIO_MOD_X for axial sensors about
 *			the 'x' axis.
 * @indexed:		Specify the channel has a numerical index. If not,
 *			the value in channel will be suppressed for attribute
 *			but not for event codes. Typically set it to 0 when
 *			the index is false.
 */
struct iio_chan_spec {
	enum iio_chan_type	type;
	int			channel;
	int			channel2;
	unsigned long		address;
	int			scan_index;
	struct {
		char	sign;
		u8	realbits;
		u8	storagebits;
		u8	shift;
	} scan_type;
	const long		info_mask;
	const long		event_mask;
	const char		*extend_name;
	unsigned		processed_val:1;
	unsigned		modified:1;
	unsigned		indexed:1;
};
/* Meant for internal use only */
void __iio_device_attr_deinit(struct device_attribute *dev_attr);
int __iio_device_attr_init(struct device_attribute *dev_attr,
			   const char *postfix,
			   struct iio_chan_spec const *chan,
			   ssize_t (*readfunc)(struct device *dev,
					       struct device_attribute *attr,
					       char *buf),
			   ssize_t (*writefunc)(struct device *dev,
						struct device_attribute *attr,
						const char *buf,
						size_t len),
			   bool generic);
#define IIO_ST(si, rb, sb, sh)						\
	{ .sign = si, .realbits = rb, .storagebits = sb, .shift = sh }

#define IIO_CHAN(_type, _mod, _indexed, _proc, _name, _chan, _chan2,	\
		 _inf_mask, _address, _si, _stype, _event_mask)		\
	{ .type = _type,						\
	  .modified = _mod,						\
	  .indexed = _indexed,						\
	  .processed_val = _proc,					\
	  .extend_name = _name,						\
	  .channel = _chan,						\
	  .channel2 = _chan2,						\
	  .info_mask = _inf_mask,					\
	  .address = _address,						\
	  .scan_index = _si,						\
	  .scan_type = _stype,						\
	  .event_mask = _event_mask }

#define IIO_CHAN_SOFT_TIMESTAMP(_si)					\
	{ .type = IIO_TIMESTAMP, .channel = -1,				\
			.scan_index = _si, .scan_type = IIO_ST('s', 64, 64, 0) }

int __iio_add_chan_devattr(const char *postfix,
			   const char *group,
			   struct iio_chan_spec const *chan,
			   ssize_t (*func)(struct device *dev,
					   struct device_attribute *attr,
					   char *buf),
			   ssize_t (*writefunc)(struct device *dev,
						struct device_attribute *attr,
						const char *buf,
						size_t len),
			   int mask,
			   bool generic,
			   struct device *dev,
			   struct list_head *attr_list);
/**
 * iio_get_time_ns() - utility function to get a time stamp for events etc
 **/
static inline s64 iio_get_time_ns(void)
{
	struct timespec ts;
	/*
	 * calls getnstimeofday.
	 * If hrtimers then up to ns accurate, if not microsecond.
	 */
	ktime_get_real_ts(&ts);

	return timespec_to_ns(&ts);
}

/* Device operating modes */
#define INDIO_DIRECT_MODE		0x01
#define INDIO_RING_TRIGGERED		0x02
#define INDIO_RING_HARDWARE_BUFFER	0x08

#define INDIO_ALL_RING_MODES (INDIO_RING_TRIGGERED | INDIO_RING_HARDWARE_BUFFER)

/* Vast majority of this is set by the industrialio subsystem on a
 * call to iio_device_register. */
#define IIO_VAL_INT 1
#define IIO_VAL_INT_PLUS_MICRO 2
#define IIO_VAL_INT_PLUS_NANO 3

struct iio_trigger; /* forward declaration */

/**
 * struct iio_info - constant information about device
 * @driver_module:	module structure used to ensure correct
 *			ownership of chrdevs etc
 * @num_interrupt_lines:number of physical interrupt lines from device
 * @event_attrs:	event control attributes
 * @attrs:		general purpose device attributes
 * @read_raw:		function to request a value from the device.
 *			mask specifies which value. Note 0 means a reading of
 *			the channel in question.  Return value will specify the
 *			type of value returned by the device. val and val2 will
 *			contain the elements making up the returned value.
 * @write_raw:		function to write a value to the device.
 *			Parameters are the same as for read_raw.
 * @write_raw_get_fmt:	callback function to query the expected
 *			format/precision. If not set by the driver, write_raw
 *			returns IIO_VAL_INT_PLUS_MICRO.
 * @read_event_config:	find out if the event is enabled.
 * @write_event_config:	set if the event is enabled.
 * @read_event_value:	read a value associated with the event. Meaning
 *			is event dependant. event_code specifies which event.
 * @write_event_value:	write the value associate with the event.
 *			Meaning is event dependent.
 * @validate_trigger:	function to validate the trigger when the
 *			current trigger gets changed.
 **/
struct iio_info {
	struct module			*driver_module;
	int				num_interrupt_lines;
	struct attribute_group		*event_attrs;
	const struct attribute_group	*attrs;

	int (*read_raw)(struct iio_dev *indio_dev,
			struct iio_chan_spec const *chan,
			int *val,
			int *val2,
			long mask);

	int (*write_raw)(struct iio_dev *indio_dev,
			 struct iio_chan_spec const *chan,
			 int val,
			 int val2,
			 long mask);

	int (*write_raw_get_fmt)(struct iio_dev *indio_dev,
			 struct iio_chan_spec const *chan,
			 long mask);

	int (*read_event_config)(struct iio_dev *indio_dev,
				 int event_code);

	int (*write_event_config)(struct iio_dev *indio_dev,
				  int event_code,
				  int state);

	int (*read_event_value)(struct iio_dev *indio_dev,
				int event_code,
				int *val);
	int (*write_event_value)(struct iio_dev *indio_dev,
				 int event_code,
				 int val);
	int (*validate_trigger)(struct iio_dev *indio_dev,
				struct iio_trigger *trig);

};

/**
 * struct iio_dev - industrial I/O device
 * @id:			[INTERN] used to identify device internally
 * @dev_data:		[DRIVER] device specific data
 * @modes:		[DRIVER] operating modes supported by device
 * @currentmode:	[DRIVER] current operating mode
 * @dev:		[DRIVER] device structure, should be assigned a parent
 *			and owner
 * @event_interfaces:	[INTERN] event chrdevs associated with interrupt lines
 * @ring:		[DRIVER] any ring buffer present
 * @mlock:		[INTERN] lock used to prevent simultaneous device state
 *			changes
 * @available_scan_masks: [DRIVER] optional array of allowed bitmasks
 * @trig:		[INTERN] current device trigger (ring buffer modes)
 * @pollfunc:		[DRIVER] function run on trigger being received
 * @channels:		[DRIVER] channel specification structure table
 * @num_channels:	[DRIVER] number of chanels specified in @channels.
 * @channel_attr_list:	[INTERN] keep track of automatically created channel
 *			attributes.
 * @name:		[DRIVER] name of the device.
 **/
struct iio_dev {
	int				id;
	void				*dev_data;
	int				modes;
	int				currentmode;
	struct device			dev;

	struct iio_event_interface	*event_interfaces;

	struct iio_ring_buffer		*ring;
	struct mutex			mlock;

	u32				*available_scan_masks;
	struct iio_trigger		*trig;
	struct iio_poll_func		*pollfunc;

	struct iio_chan_spec const *channels;
	int num_channels;

	struct list_head channel_attr_list;
	const char *name;
	const struct iio_info *info;
};

/**
 * iio_device_register() - register a device with the IIO subsystem
 * @dev_info:		Device structure filled by the device driver
 **/
int iio_device_register(struct iio_dev *dev_info);

/**
 * iio_device_unregister() - unregister a device from the IIO subsystem
 * @dev_info:		Device structure representing the device.
 **/
void iio_device_unregister(struct iio_dev *dev_info);

/**
 * iio_push_event() - try to add event to the list for userspace reading
 * @dev_info:		IIO device structure
 * @ev_line:		Which event line (hardware interrupt)
 * @ev_code:		What event
 * @timestamp:		When the event occurred
 **/
int iio_push_event(struct iio_dev *dev_info,
		  int ev_line,
		  int ev_code,
		  s64 timestamp);

/* Used to distinguish between bipolar and unipolar scan elemenents.
 * Whilst this may seem obvious, we may well want to change the representation
 * in the future!*/
#define IIO_SIGNED(a) -(a)
#define IIO_UNSIGNED(a) (a)

extern dev_t iio_devt;
extern struct bus_type iio_bus_type;

/**
 * iio_put_device() - reference counted deallocation of struct device
 * @dev: the iio_device containing the device
 **/
static inline void iio_put_device(struct iio_dev *dev)
{
	if (dev)
		put_device(&dev->dev);
};

/**
 * to_iio_dev() - get iio_dev for which we have the struct device
 * @d: the struct device
 **/
static inline struct iio_dev *to_iio_dev(struct device *d)
{
	return container_of(d, struct iio_dev, dev);
};

/**
 * iio_dev_get_devdata() - helper function gets device specific data
 * @d: the iio_dev associated with the device
 **/
static inline void *iio_dev_get_devdata(struct iio_dev *d)
{
	return d->dev_data;
}

/* Can we make this smaller? */
#define IIO_ALIGN L1_CACHE_BYTES
/**
 * iio_allocate_device() - allocate an iio_dev from a driver
 * @sizeof_priv: Space to allocate for private structure.
 **/
struct iio_dev *iio_allocate_device(int sizeof_priv);

static inline void *iio_priv(const struct iio_dev *dev)
{
	return (char *)dev + ALIGN(sizeof(struct iio_dev), IIO_ALIGN);
}

static inline struct iio_dev *iio_priv_to_dev(void *priv)
{
	return (struct iio_dev *)((char *)priv -
				  ALIGN(sizeof(struct iio_dev), IIO_ALIGN));
}

/**
 * iio_free_device() - free an iio_dev from a driver
 * @dev: the iio_dev associated with the device
 **/
void iio_free_device(struct iio_dev *dev);

/**
 * iio_put() - internal module reference count reduce
 **/
void iio_put(void);

/**
 * iio_get() - internal module reference count increase
 **/
void iio_get(void);

/**
 * iio_device_get_chrdev_minor() - get an unused minor number
 **/
int iio_device_get_chrdev_minor(void);
void iio_device_free_chrdev_minor(int val);

/**
 * iio_ring_enabled() - helper function to test if any form of ring is enabled
 * @dev_info:		IIO device info structure for device
 **/
static inline bool iio_ring_enabled(struct iio_dev *dev_info)
{
	return dev_info->currentmode
		& (INDIO_RING_TRIGGERED
		   | INDIO_RING_HARDWARE_BUFFER);
};

struct ida;

int iio_get_new_ida_val(struct ida *this_ida);
void iio_free_ida_val(struct ida *this_ida, int id);
#endif /* _INDUSTRIAL_IO_H_ */


text:
package org.apache.flink.runtime.taskexecutor;

import java.util.concurrent.CompletableFuture;

/**
 * Simple adapter for {@link TaskExecutor} to adapt to {@link TaskManagerRunner.TaskExecutorService}.
 */
public class TaskExecutorToServiceAdapter implements TaskManagerRunner.TaskExecutorService {

	private final TaskExecutor taskExecutor;

	private TaskExecutorToServiceAdapter(TaskExecutor taskExecutor) {
		this.taskExecutor = taskExecutor;
	}

	@Override
	public void start() {
		taskExecutor.start();
	}

	@Override
	public CompletableFuture<Void> getTerminationFuture() {
		return taskExecutor.getTerminationFuture();
	}

	@Override
	public CompletableFuture<Void> closeAsync() {
		return taskExecutor.closeAsync();
	}

	public static TaskExecutorToServiceAdapter createFor(TaskExecutor taskExecutor) {
		return new TaskExecutorToServiceAdapter(taskExecutor);
	}
}