text:
package registry

import (
	"context"
	"errors"
	"net/url"

	"github.com/manifoldco/torus-cli/envelope"
	"github.com/manifoldco/torus-cli/identity"
	"github.com/manifoldco/torus-cli/primitive"
)

// MembershipsClient represents the `/memberships` registry
// endpoint, used for accessing the relationship between users,
// organization, and teams.
type MembershipsClient struct {
	client RoundTripper
}

// List returns all memberships for a given organization, team, or user/machine
func (m *MembershipsClient) List(ctx context.Context, orgID *identity.ID,
	teamID *identity.ID, ownerID *identity.ID) ([]envelope.Membership, error) {

	query := &url.Values{}
	if orgID != nil {
		query.Set("org_id", orgID.String())
	}
	if teamID != nil {
		query.Set("team_id", teamID.String())
	}
	if ownerID != nil {
		query.Set("owner_id", ownerID.String())
	}

	var memberships []envelope.Membership
	err := m.client.RoundTrip(ctx, "GET", "/memberships", query, nil, &memberships)
	return memberships, err
}

// Create requests addition of a user to a team
func (m *MembershipsClient) Create(ctx context.Context, userID, orgID, teamID *identity.ID) error {
	if orgID == nil {
		return errors.New("invalid org")
	}
	if userID == nil {
		return errors.New("invalid user")
	}
	if teamID == nil {
		return errors.New("invalid team")
	}

	membershipBody := primitive.Membership{
		OwnerID: userID,
		OrgID:   orgID,
		TeamID:  teamID,
	}

	ID, err := identity.NewMutable(&membershipBody)
	if err != nil {
		return err
	}

	membership := envelope.Membership{
		ID:      &ID,
		Version: 1,
		Body:    &membershipBody,
	}

	return m.client.RoundTrip(ctx, "POST", "/memberships", nil, &membership, nil)
}

// Delete requests deletion of a specific membership row by ID
func (m *MembershipsClient) Delete(ctx context.Context, membership *identity.ID) error {
	return m.client.RoundTrip(ctx, "DELETE", "/memberships/"+membership.String(), nil, nil, nil)
}


text:
DROP VIEW IF EXISTS view_kartu_barang3_awayan CASCADE;

CREATE VIEW view_kartu_barang3_awayan AS

SELECT
nama_provinsi,
id_provinsi,

nama_kabupaten,
id_kabupaten,

nama_lokasi_bidang,
id_lokasi_bidang,

nama_skpd,
id_skpd,

nama_barang,
kode_barang,

satuan,
id_satuan,

jenis_barang,
id_jenis_barang,

sum(pra_saldo) AS saldo_barang

FROM
view_kartu_barang2_awayan

WHERE
1 = 1  AND
id_skpd = 34

GROUP BY
nama_provinsi,
id_provinsi,
nama_kabupaten,
id_kabupaten,
nama_lokasi_bidang,
id_lokasi_bidang,
nama_skpd,
id_skpd,
nama_barang,
kode_barang,
satuan,
id_satuan,
jenis_barang,
id_jenis_barang

;

GRANT ALL PRIVILEGES ON view_kartu_barang3_awayan TO lap_awayan;
REVOKE INSERT, UPDATE, DELETE ON view_kartu_barang3_awayan FROM lap_awayan;

redpajama_set_name: RedPajamaGithub


text:
namespace google {
namespace protobuf {
namespace compiler {
namespace csharp {

struct Options;

class SourceGeneratorBase {
 protected:
  SourceGeneratorBase(const Options* options);
  virtual ~SourceGeneratorBase();

  SourceGeneratorBase(const SourceGeneratorBase&) = delete;
  SourceGeneratorBase& operator=(const SourceGeneratorBase&) = delete;

  std::string class_access_level();
  const Options* options();

  // Write any attributes used to decorate generated function members (methods and properties).
  // Should not be used to decorate types.
  void WriteGeneratedCodeAttributes(io::Printer* printer);

 private:
  const Options *options_;
};

}  // namespace csharp
}  // namespace compiler
}  // namespace protobuf
}  // namespace google

#endif  // GOOGLE_PROTOBUF_COMPILER_CSHARP_SOURCE_GENERATOR_BASE_H__


text:
require 'google/protobuf'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("google/cloud/vision/v1p3beta1/web_detection.proto", :syntax => :proto3) do
    add_message "google.cloud.vision.v1p3beta1.WebDetection" do
      repeated :web_entities, :message, 1, "google.cloud.vision.v1p3beta1.WebDetection.WebEntity"
      repeated :full_matching_images, :message, 2, "google.cloud.vision.v1p3beta1.WebDetection.WebImage"
      repeated :partial_matching_images, :message, 3, "google.cloud.vision.v1p3beta1.WebDetection.WebImage"
      repeated :pages_with_matching_images, :message, 4, "google.cloud.vision.v1p3beta1.WebDetection.WebPage"
      repeated :visually_similar_images, :message, 6, "google.cloud.vision.v1p3beta1.WebDetection.WebImage"
      repeated :best_guess_labels, :message, 8, "google.cloud.vision.v1p3beta1.WebDetection.WebLabel"
    end
    add_message "google.cloud.vision.v1p3beta1.WebDetection.WebEntity" do
      optional :entity_id, :string, 1
      optional :score, :float, 2
      optional :description, :string, 3
    end
    add_message "google.cloud.vision.v1p3beta1.WebDetection.WebImage" do
      optional :url, :string, 1
      optional :score, :float, 2
    end
    add_message "google.cloud.vision.v1p3beta1.WebDetection.WebPage" do
      optional :url, :string, 1
      optional :score, :float, 2
      optional :page_title, :string, 3
      repeated :full_matching_images, :message, 4, "google.cloud.vision.v1p3beta1.WebDetection.WebImage"
      repeated :partial_matching_images, :message, 5, "google.cloud.vision.v1p3beta1.WebDetection.WebImage"
    end
    add_message "google.cloud.vision.v1p3beta1.WebDetection.WebLabel" do
      optional :label, :string, 1
      optional :language_code, :string, 2
    end
  end
end

module Google
  module Cloud
    module Vision
      module V1p3beta1
        WebDetection = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.vision.v1p3beta1.WebDetection").msgclass
        WebDetection::WebEntity = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.vision.v1p3beta1.WebDetection.WebEntity").msgclass
        WebDetection::WebImage = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.vision.v1p3beta1.WebDetection.WebImage").msgclass
        WebDetection::WebPage = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.vision.v1p3beta1.WebDetection.WebPage").msgclass
        WebDetection::WebLabel = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.vision.v1p3beta1.WebDetection.WebLabel").msgclass
      end
    end
  end
end


text:
namespace mojo {
class NetworkService;
}

namespace html_viewer {

// The concrete type of WebURLRequest::ExtraData.
class WebURLRequestExtraData : public blink::WebURLRequest::ExtraData {
 public:
  WebURLRequestExtraData();
  virtual ~WebURLRequestExtraData();

  mojo::URLResponsePtr synthetic_response;
};

class WebURLLoaderImpl : public blink::WebURLLoader {
 public:
  explicit WebURLLoaderImpl(mojo::NetworkService* network_service);

 private:
  virtual ~WebURLLoaderImpl();

  // blink::WebURLLoader methods:
  virtual void loadSynchronously(
      const blink::WebURLRequest& request, blink::WebURLResponse& response,
      blink::WebURLError& error, blink::WebData& data) override;
  virtual void loadAsynchronously(
      const blink::WebURLRequest&, blink::WebURLLoaderClient* client) override;
  virtual void cancel() override;
  virtual void setDefersLoading(bool defers_loading) override;

  void OnReceivedResponse(mojo::URLResponsePtr response);
  void OnReceivedError(mojo::URLResponsePtr response);
  void OnReceivedRedirect(mojo::URLResponsePtr response);
  void ReadMore();
  void WaitToReadMore();
  void OnResponseBodyStreamReady(MojoResult result);

  blink::WebURLLoaderClient* client_;
  GURL url_;
  mojo::URLLoaderPtr url_loader_;
  mojo::ScopedDataPipeConsumerHandle response_body_stream_;
  mojo::common::HandleWatcher handle_watcher_;

  base::WeakPtrFactory<WebURLLoaderImpl> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(WebURLLoaderImpl);
};

}  // namespace html_viewer

#endif  // MOJO_SERVICES_HTML_VIEWER_WEBURLLOADER_IMPL_H_


text:
Capybara::SpecHelper.spec '#save_page' do
  let(:alternative_path) { File.join(Dir.pwd, 'save_and_open_page_tmp') }
  before do
    @old_save_path = Capybara.save_path
    Capybara.save_path = nil
    @session.visit('/foo')
  end

  after do
    Capybara.save_path = @old_save_path
    Dir.glob('capybara-*.html').each do |file|
      FileUtils.rm(file)
    end
    FileUtils.rm_rf alternative_path
  end

  it 'saves the page in the root directory' do
    @session.save_page
    path = Dir.glob('capybara-*.html').first
    expect(File.read(path)).to include('Another World')
  end

  it 'generates a sensible filename' do
    @session.save_page
    filename = Dir.glob('capybara-*.html').first
    expect(filename).to match(/^capybara-\d+\.html$/)
  end

  it 'can store files in a specified directory' do
    Capybara.save_path = alternative_path
    @session.save_page
    path = Dir.glob("#{alternative_path}/capybara-*.html").first
    expect(File.read(path)).to include('Another World')
  end

  it 'uses the given filename' do
    @session.save_page('capybara-001122.html')
    expect(File.read('capybara-001122.html')).to include('Another World')
  end

  it 'can store files in a specified directory with a given filename' do
    Capybara.save_path = alternative_path
    @session.save_page('capybara-001133.html')
    path = "#{alternative_path}/capybara-001133.html"
    expect(File.read(path)).to include('Another World')
  end

  it 'can store files in a specified directory with a given relative filename' do
    Capybara.save_path = alternative_path
    @session.save_page('tmp/capybara-001144.html')
    path = "#{alternative_path}/tmp/capybara-001144.html"
    expect(File.read(path)).to include('Another World')
  end

  it 'returns an absolute path in pwd' do
    result = @session.save_page
    path = File.expand_path(Dir.glob('capybara-*.html').first, Dir.pwd)
    expect(result).to eq(path)
  end

  it 'returns an absolute path in given directory' do
    Capybara.save_path = alternative_path
    result = @session.save_page
    path = File.expand_path(Dir.glob("#{alternative_path}/capybara-*.html").first, alternative_path)
    expect(result).to eq(path)
  end

  context 'asset_host contains a string' do
    before { Capybara.asset_host = 'http://example.com' }

    after { Capybara.asset_host = nil }

    it 'prepends base tag with value from asset_host to the head' do
      @session.visit('/with_js')
      path = @session.save_page

      result = File.read(path)
      expect(result).to include("<head><base href='http://example.com' />")
    end

    it "doesn't prepend base tag to pages when asset_host is nil" do
      Capybara.asset_host = nil
      @session.visit('/with_js')
      path = @session.save_page

      result = File.read(path)
      expect(result).to include('<html')
      expect(result).not_to include('http://example.com')
    end

    it "doesn't prepend base tag to pages which already have it" do
      @session.visit('/with_base_tag')
      path = @session.save_page

      result = File.read(path)
      expect(result).to include('<html')
      expect(result).not_to include('http://example.com')
    end

    it 'executes successfully even if the page is missing a <head>' do
      @session.visit('/with_simple_html')
      path = @session.save_page

      result = File.read(path)
      expect(result).to include('Bar')
    end
  end
end


text:
namespace GafferScene
{

class OpenGLShader : public GafferScene::Shader
{

	public :

		OpenGLShader( const std::string &name=defaultName<OpenGLShader>() );
		virtual ~OpenGLShader();

		IE_CORE_DECLARERUNTIMETYPEDEXTENSION( GafferScene::OpenGLShader, OpenGLShaderTypeId, GafferScene::Shader );

		void loadShader( const std::string &shaderName );

	protected :

		/// Reimplemented to allow ImageNodes to be plugged in to texture parameters.
		virtual void parameterHash( const Gaffer::Plug *parameterPlug, NetworkBuilder &network, IECore::MurmurHash &h ) const;
		virtual IECore::DataPtr parameterValue( const Gaffer::Plug *parameterPlug, NetworkBuilder &network ) const;

};

IE_CORE_DECLAREPTR( OpenGLShader )

} // namespace GafferScene

#endif // GAFFERSCENE_OPENGLSHADER_H


text:
/**
 * @fileoverview This test suite runs tests on the V2 to V1 converter.
 */

var expect = require('chai').expect,
    requireAll = require('require-all'),
    path = require('path'),
    tv4 = require('tv4'),
    _ = require('lodash').noConflict(),
    agent = require('superagent');

describe('v2.1.0 ==> v1.0.0', function () {
    var converter = require('../../../lib/converters/v2.1.0/converter-v21-to-v1'),
        schemaUrl = require('../../../lib/constants').SCHEMA_V1_URL,
        examplesDir = path.join(__dirname, '../../../examples/v2.1.0');

    describe('sample conversions', function () {
        var schema,
            samples = requireAll(examplesDir);

        before(function (done) {
            agent
                .get(schemaUrl)
                .set('Cache-Control', 'no-cache; no-store; must-revalidate')
                .end(function (error, response) {
                    schema = _.isString(response.body) ? JSON.parse(response.body) : response.body;
                    done(error);
                });
        });

        _.forEach(samples, function (sample, sampleName) {
            it('must create a valid V1 collection from ' + sampleName + '.json', function (done) {
                converter.convert(sample, {}, function (err, converted) {
                    var validator = tv4.freshApi(),
                        result;

                    validator.addSchema(schema);
                    // Some of the converter functions assign "undefined" value to some properties,
                    // It is necessary to get rid of them (otherwise schema validation sees an "undefined" and fails).
                    // Converting to and parsing from JSON does this.
                    converted = JSON.parse(JSON.stringify(converted));
                    result = validator.validate(converted, schema);
                    if (!result && process.env.CI) { // eslint-disable-line no-process-env
                        console.error(JSON.stringify(validator.error, null, 4)); // Helps debug on CI
                    }
                    if (validator.missing.length) {
                        console.error(validator.missing);
                        result = false;
                    }
                    expect(result).to.equal(true);
                    expect(err).to.equal(null);
                    done();
                });
            });
        });

        _.forEach(samples, function (sample, sampleName) {
            it('must create a valid V1 collection from ' + sampleName + '.json with synchronous API', function (done) {
                var validator = tv4.freshApi(),
                    result,
                    converted;

                validator.addSchema(schema);
                converted = converter.convert(sample);

                // Some of the converter functions assign "undefined" value to some properties,
                // It is necessary to get rid of them (otherwise schema validation sees an "undefined" and fails).
                // Converting to and parsing from JSON does this.
                converted = JSON.parse(JSON.stringify(converted));

                result = validator.validate(converted, schema);
                if (!result && process.env.CI) { // eslint-disable-line no-process-env
                    console.error(JSON.stringify(validator.error, null, 4)); // Helps debug on CI
                }
                if (validator.missing.length) {
                    console.error(validator.missing);
                    result = false;
                }
                expect(result).to.equal(true);
                done();
            });
        });
    });

    describe('Exceptional cases', function () {
        describe('Binary File reference', function () {
            it('should be converted to v1 correctly', function () {
                var v21 = require('../../../examples/v2.1.0/binary-upload.json'),
                    v1 = JSON.parse(JSON.stringify(converter.convert(v21)));

                expect(_.get(v1, 'requests[0].dataMode')).to.equal('binary');
                expect(_.get(v1, 'requests[0].rawModeData')).to.equal('sample.txt');
                expect(_.isEmpty(_.get(v1, 'requests[0].data'))).to.equal(true);
            });
        });
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?>
<root>
  <document>
    <sentences>
      <sentence id="1">
        <tokens>
          <token id="1">
            <word>an</word>
            <lemma>a</lemma>
            <CharacterOffsetBegin>0</CharacterOffsetBegin>
            <CharacterOffsetEnd>2</CharacterOffsetEnd>
            <POS>DT</POS>
          </token>
          <token id="2">
            <word>ordained</word>
            <lemma>ordain</lemma>
            <CharacterOffsetBegin>3</CharacterOffsetBegin>
            <CharacterOffsetEnd>11</CharacterOffsetEnd>
            <POS>VBN</POS>
          </token>
          <token id="3">
            <word>or</word>
            <lemma>or</lemma>
            <CharacterOffsetBegin>12</CharacterOffsetBegin>
            <CharacterOffsetEnd>14</CharacterOffsetEnd>
            <POS>CC</POS>
          </token>
          <token id="4">
            <word>consecrated</word>
            <lemma>consecrate</lemma>
            <CharacterOffsetBegin>15</CharacterOffsetBegin>
            <CharacterOffsetEnd>26</CharacterOffsetEnd>
            <POS>VBN</POS>
          </token>
          <token id="5">
            <word>member</word>
            <lemma>member</lemma>
            <CharacterOffsetBegin>27</CharacterOffsetBegin>
            <CharacterOffsetEnd>33</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
          <token id="6">
            <word>of</word>
            <lemma>of</lemma>
            <CharacterOffsetBegin>34</CharacterOffsetBegin>
            <CharacterOffsetEnd>36</CharacterOffsetEnd>
            <POS>IN</POS>
          </token>
          <token id="7">
            <word>the</word>
            <lemma>the</lemma>
            <CharacterOffsetBegin>37</CharacterOffsetBegin>
            <CharacterOffsetEnd>40</CharacterOffsetEnd>
            <POS>DT</POS>
          </token>
          <token id="8">
            <word>Christian</word>
            <lemma>Christian</lemma>
            <CharacterOffsetBegin>41</CharacterOffsetBegin>
            <CharacterOffsetEnd>50</CharacterOffsetEnd>
            <POS>NNP</POS>
          </token>
          <token id="9">
            <word>clergy</word>
            <lemma>clergy</lemma>
            <CharacterOffsetBegin>51</CharacterOffsetBegin>
            <CharacterOffsetEnd>57</CharacterOffsetEnd>
            <POS>NNS</POS>
          </token>
          <token id="10">
            <word>who</word>
            <lemma>who</lemma>
            <CharacterOffsetBegin>58</CharacterOffsetBegin>
            <CharacterOffsetEnd>61</CharacterOffsetEnd>
            <POS>WP</POS>
          </token>
          <token id="11">
            <word>is</word>
            <lemma>be</lemma>
            <CharacterOffsetBegin>62</CharacterOffsetBegin>
            <CharacterOffsetEnd>64</CharacterOffsetEnd>
            <POS>VBZ</POS>
          </token>
          <token id="12">
            <word>generally</word>
            <lemma>generally</lemma>
            <CharacterOffsetBegin>65</CharacterOffsetBegin>
            <CharacterOffsetEnd>74</CharacterOffsetEnd>
            <POS>RB</POS>
          </token>
          <token id="13">
            <word>entrusted</word>
            <lemma>entrust</lemma>
            <CharacterOffsetBegin>75</CharacterOffsetBegin>
            <CharacterOffsetEnd>84</CharacterOffsetEnd>
            <POS>VBN</POS>
          </token>
          <token id="14">
            <word>with</word>
            <lemma>with</lemma>
            <CharacterOffsetBegin>85</CharacterOffsetBegin>
            <CharacterOffsetEnd>89</CharacterOffsetEnd>
            <POS>IN</POS>
          </token>
          <token id="15">
            <word>a</word>
            <lemma>a</lemma>
            <CharacterOffsetBegin>90</CharacterOffsetBegin>
            <CharacterOffsetEnd>91</CharacterOffsetEnd>
            <POS>DT</POS>
          </token>
          <token id="16">
            <word>position</word>
            <lemma>position</lemma>
            <CharacterOffsetBegin>92</CharacterOffsetBegin>
            <CharacterOffsetEnd>100</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
          <token id="17">
            <word>of</word>
            <lemma>of</lemma>
            <CharacterOffsetBegin>101</CharacterOffsetBegin>
            <CharacterOffsetEnd>103</CharacterOffsetEnd>
            <POS>IN</POS>
          </token>
          <token id="18">
            <word>authority</word>
            <lemma>authority</lemma>
            <CharacterOffsetBegin>104</CharacterOffsetBegin>
            <CharacterOffsetEnd>113</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
          <token id="19">
            <word>and</word>
            <lemma>and</lemma>
            <CharacterOffsetBegin>114</CharacterOffsetBegin>
            <CharacterOffsetEnd>117</CharacterOffsetEnd>
            <POS>CC</POS>
          </token>
          <token id="20">
            <word>oversight</word>
            <lemma>oversight</lemma>
            <CharacterOffsetBegin>118</CharacterOffsetBegin>
            <CharacterOffsetEnd>127</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
          <token id="21">
            <word>priest</word>
            <lemma>priest</lemma>
            <CharacterOffsetBegin>128</CharacterOffsetBegin>
            <CharacterOffsetEnd>134</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
        </tokens>
        <parse>(ROOT (S (NP (DT an)) (VP (VP (VBN ordained)) (CC or) (VP (VBN consecrated) (NP (NP (NN member)) (PP (IN of) (NP (DT the) (NNP Christian) (NNS clergy))) (SBAR (WHNP (WP who)) (S (VP (VBZ is) (ADVP (RB generally)) (VP (VBN entrusted) (PP (IN with) (NP (NP (DT a) (NN position)) (PP (IN of) (NP (NP (NN authority) (CC and) (NN oversight)) (NN priest)))))))))))))) </parse>
        <dependencies type="basic-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="2">ordained</dependent>
          </dep>
          <dep type="nsubj">
            <governor idx="2">ordained</governor>
            <dependent idx="1">an</dependent>
          </dep>
          <dep type="cc">
            <governor idx="2">ordained</governor>
            <dependent idx="3">or</dependent>
          </dep>
          <dep type="conj">
            <governor idx="2">ordained</governor>
            <dependent idx="4">consecrated</dependent>
          </dep>
          <dep type="dobj">
            <governor idx="4">consecrated</governor>
            <dependent idx="5">member</dependent>
          </dep>
          <dep type="prep">
            <governor idx="5">member</governor>
            <dependent idx="6">of</dependent>
          </dep>
          <dep type="det">
            <governor idx="9">clergy</governor>
            <dependent idx="7">the</dependent>
          </dep>
          <dep type="nn">
            <governor idx="9">clergy</governor>
            <dependent idx="8">Christian</dependent>
          </dep>
          <dep type="pobj">
            <governor idx="6">of</governor>
            <dependent idx="9">clergy</dependent>
          </dep>
          <dep type="nsubjpass">
            <governor idx="13">entrusted</governor>
            <dependent idx="10">who</dependent>
          </dep>
          <dep type="auxpass">
            <governor idx="13">entrusted</governor>
            <dependent idx="11">is</dependent>
          </dep>
          <dep type="advmod">
            <governor idx="13">entrusted</governor>
            <dependent idx="12">generally</dependent>
          </dep>
          <dep type="rcmod">
            <governor idx="5">member</governor>
            <dependent idx="13">entrusted</dependent>
          </dep>
          <dep type="prep">
            <governor idx="13">entrusted</governor>
            <dependent idx="14">with</dependent>
          </dep>
          <dep type="det">
            <governor idx="16">position</governor>
            <dependent idx="15">a</dependent>
          </dep>
          <dep type="pobj">
            <governor idx="14">with</governor>
            <dependent idx="16">position</dependent>
          </dep>
          <dep type="prep">
            <governor idx="16">position</governor>
            <dependent idx="17">of</dependent>
          </dep>
          <dep type="nn">
            <governor idx="21">priest</governor>
            <dependent idx="18">authority</dependent>
          </dep>
          <dep type="cc">
            <governor idx="18">authority</governor>
            <dependent idx="19">and</dependent>
          </dep>
          <dep type="conj">
            <governor idx="18">authority</governor>
            <dependent idx="20">oversight</dependent>
          </dep>
          <dep type="pobj">
            <governor idx="17">of</governor>
            <dependent idx="21">priest</dependent>
          </dep>
        </dependencies>
        <dependencies type="collapsed-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="2">ordained</dependent>
          </dep>
          <dep type="nsubj">
            <governor idx="2">ordained</governor>
            <dependent idx="1">an</dependent>
          </dep>
          <dep type="conj_or">
            <governor idx="2">ordained</governor>
            <dependent idx="4">consecrated</dependent>
          </dep>
          <dep type="dobj">
            <governor idx="4">consecrated</governor>
            <dependent idx="5">member</dependent>
          </dep>
          <dep type="det">
            <governor idx="9">clergy</governor>
            <dependent idx="7">the</dependent>
          </dep>
          <dep type="nn">
            <governor idx="9">clergy</governor>
            <dependent idx="8">Christian</dependent>
          </dep>
          <dep type="prep_of">
            <governor idx="5">member</governor>
            <dependent idx="9">clergy</dependent>
          </dep>
          <dep type="nsubjpass">
            <governor idx="13">entrusted</governor>
            <dependent idx="10">who</dependent>
          </dep>
          <dep type="auxpass">
            <governor idx="13">entrusted</governor>
            <dependent idx="11">is</dependent>
          </dep>
          <dep type="advmod">
            <governor idx="13">entrusted</governor>
            <dependent idx="12">generally</dependent>
          </dep>
          <dep type="rcmod">
            <governor idx="5">member</governor>
            <dependent idx="13">entrusted</dependent>
          </dep>
          <dep type="det">
            <governor idx="16">position</governor>
            <dependent idx="15">a</dependent>
          </dep>
          <dep type="prep_with">
            <governor idx="13">entrusted</governor>
            <dependent idx="16">position</dependent>
          </dep>
          <dep type="nn">
            <governor idx="21">priest</governor>
            <dependent idx="18">authority</dependent>
          </dep>
          <dep type="conj_and">
            <governor idx="18">authority</governor>
            <dependent idx="20">oversight</dependent>
          </dep>
          <dep type="prep_of">
            <governor idx="16">position</governor>
            <dependent idx="21">priest</dependent>
          </dep>
        </dependencies>
        <dependencies type="collapsed-ccprocessed-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="2">ordained</dependent>
          </dep>
          <dep type="nsubj">
            <governor idx="2">ordained</governor>
            <dependent idx="1">an</dependent>
          </dep>
          <dep type="nsubj">
            <governor idx="4">consecrated</governor>
            <dependent idx="1">an</dependent>
          </dep>
          <dep type="conj_or">
            <governor idx="2">ordained</governor>
            <dependent idx="4">consecrated</dependent>
          </dep>
          <dep type="dobj">
            <governor idx="4">consecrated</governor>
            <dependent idx="5">member</dependent>
          </dep>
          <dep type="det">
            <governor idx="9">clergy</governor>
            <dependent idx="7">the</dependent>
          </dep>
          <dep type="nn">
            <governor idx="9">clergy</governor>
            <dependent idx="8">Christian</dependent>
          </dep>
          <dep type="prep_of">
            <governor idx="5">member</governor>
            <dependent idx="9">clergy</dependent>
          </dep>
          <dep type="nsubjpass">
            <governor idx="13">entrusted</governor>
            <dependent idx="10">who</dependent>
          </dep>
          <dep type="auxpass">
            <governor idx="13">entrusted</governor>
            <dependent idx="11">is</dependent>
          </dep>
          <dep type="advmod">
            <governor idx="13">entrusted</governor>
            <dependent idx="12">generally</dependent>
          </dep>
          <dep type="rcmod">
            <governor idx="5">member</governor>
            <dependent idx="13">entrusted</dependent>
          </dep>
          <dep type="det">
            <governor idx="16">position</governor>
            <dependent idx="15">a</dependent>
          </dep>
          <dep type="prep_with">
            <governor idx="13">entrusted</governor>
            <dependent idx="16">position</dependent>
          </dep>
          <dep type="nn">
            <governor idx="21">priest</governor>
            <dependent idx="18">authority</dependent>
          </dep>
          <dep type="conj_and">
            <governor idx="18">authority</governor>
            <dependent idx="20">oversight</dependent>
          </dep>
          <dep type="nn">
            <governor idx="21">priest</governor>
            <dependent idx="20">oversight</dependent>
          </dep>
          <dep type="prep_of">
            <governor idx="16">position</governor>
            <dependent idx="21">priest</dependent>
          </dep>
        </dependencies>
      </sentence>
    </sentences>
  </document>
</root>


text:
import os
import copy
from random import shuffle
import itertools

import numpy as np

from .utils import pickle_dump, pickle_load
from .utils.patches import compute_patch_indices, get_random_nd_index, get_patch_from_3d_data
from .augment import augment_data, random_permutation_x_y

def get_training_and_validation_generators(data_file, batch_size, n_labels, training_keys_file, validation_keys_file,
                                           data_split=0.8, overwrite=False, labels=None, augment=False,
                                           augment_flip=True, augment_distortion_factor=0.25, patch_shape=None,
                                           validation_patch_overlap=0, training_patch_start_offset=None,
                                           validation_batch_size=None, skip_blank=True, permute=False):
    """
    Creates the training and validation generators that can be used when training the model.
    :param skip_blank: If True, any blank (all-zero) label images/patches will be skipped by the data generator.
    :param validation_batch_size: Batch size for the validation data.
    :param training_patch_start_offset: Tuple of length 3 containing integer values. Training data will randomly be
    offset by a number of pixels between (0, 0, 0) and the given tuple. (default is None)
    :param validation_patch_overlap: Number of pixels/voxels that will be overlapped in the validation data. (requires
    patch_shape to not be None)
    :param patch_shape: Shape of the data to return with the generator. If None, the whole image will be returned.
    (default is None)
    :param augment_flip: if True and augment is True, then the data will be randomly flipped along the x, y and z axis
    :param augment_distortion_factor: if augment is True, this determines the standard deviation from the original
    that the data will be distorted (in a stretching or shrinking fashion). Set to None, False, or 0 to prevent the
    augmentation from distorting the data in this way.
    :param augment: If True, training data will be distorted on the fly so as to avoid over-fitting.
    :param labels: List or tuple containing the ordered label values in the image files. The length of the list or tuple
    should be equal to the n_labels value.
    Example: (10, 25, 50)
    The data generator would then return binary truth arrays representing the labels 10, 25, and 30 in that order.
    :param data_file: hdf5 file to load the data from.
    :param batch_size: Size of the batches that the training generator will provide.
    :param n_labels: Number of binary labels.
    :param training_keys_file: Pickle file where the index locations of the training data will be stored.
    :param validation_keys_file: Pickle file where the index locations of the validation data will be stored.
    :param data_split: How the training and validation data will be split. 0 means all the data will be used for
    validation and none of it will be used for training. 1 means that all the data will be used for training and none
    will be used for validation. Default is 0.8 or 80%.
    :param overwrite: If set to True, previous files will be overwritten. The default mode is false, so that the
    training and validation splits won't be overwritten when rerunning model training.
    :param permute: will randomly permute the data (data must be 3D cube)
    :return: Training data generator, validation data generator, number of training steps, number of validation steps
    """
    if not validation_batch_size:
        validation_batch_size = batch_size

    training_list, validation_list = get_validation_split(data_file,
                                                          data_split=data_split,
                                                          overwrite=overwrite,
                                                          training_file=training_keys_file,
                                                          validation_file=validation_keys_file)

    training_generator = data_generator(data_file, training_list,
                                        batch_size=batch_size,
                                        n_labels=n_labels,
                                        labels=labels,
                                        augment=augment,
                                        augment_flip=augment_flip,
                                        augment_distortion_factor=augment_distortion_factor,
                                        patch_shape=patch_shape,
                                        patch_overlap=0,
                                        patch_start_offset=training_patch_start_offset,
                                        skip_blank=skip_blank,
                                        permute=permute)
    validation_generator = data_generator(data_file, validation_list,
                                          batch_size=validation_batch_size,
                                          n_labels=n_labels,
                                          labels=labels,
                                          patch_shape=patch_shape,
                                          patch_overlap=validation_patch_overlap,
                                          skip_blank=skip_blank)

    # Set the number of training and testing samples per epoch correctly
    num_training_steps = get_number_of_steps(get_number_of_patches(data_file, training_list, patch_shape,
                                                                   skip_blank=skip_blank,
                                                                   patch_start_offset=training_patch_start_offset,
                                                                   patch_overlap=0), batch_size)
    print("Number of training steps: ", num_training_steps)

    num_validation_steps = get_number_of_steps(get_number_of_patches(data_file, validation_list, patch_shape,
                                                                     skip_blank=skip_blank,
                                                                     patch_overlap=validation_patch_overlap),
                                               validation_batch_size)
    print("Number of validation steps: ", num_validation_steps)

    return training_generator, validation_generator, num_training_steps, num_validation_steps

def get_number_of_steps(n_samples, batch_size):
    if n_samples <= batch_size:
        return n_samples
    elif np.remainder(n_samples, batch_size) == 0:
        return n_samples//batch_size
    else:
        return n_samples//batch_size + 1

def get_validation_split(data_file, training_file, validation_file, data_split=0.8, overwrite=False):
    """
    Splits the data into the training and validation indices list.
    :param data_file: pytables hdf5 data file
    :param training_file:
    :param validation_file:
    :param data_split:
    :param overwrite:
    :return:
    """
    if overwrite or not os.path.exists(training_file):
        print("Creating validation split...")
        nb_samples = data_file.root.data.shape[0]
        sample_list = list(range(nb_samples))
        training_list, validation_list = split_list(sample_list, split=data_split)
        pickle_dump(training_list, training_file)
        pickle_dump(validation_list, validation_file)
        return training_list, validation_list
    else:
        print("Loading previous validation split...")
        return pickle_load(training_file), pickle_load(validation_file)

def split_list(input_list, split=0.8, shuffle_list=True):
    if shuffle_list:
        shuffle(input_list)
    n_training = int(len(input_list) * split)
    training = input_list[:n_training]
    testing = input_list[n_training:]
    return training, testing

def data_generator(data_file, index_list, batch_size=1, n_labels=1, labels=None, augment=False, augment_flip=True,
                   augment_distortion_factor=0.25, patch_shape=None, patch_overlap=0, patch_start_offset=None,
                   shuffle_index_list=True, skip_blank=True, permute=False):
    orig_index_list = index_list
    while True:
        x_list = list()
        y_list = list()
        if patch_shape:
            index_list = create_patch_index_list(orig_index_list, data_file.root.data.shape[-3:], patch_shape,
                                                 patch_overlap, patch_start_offset)
        else:
            index_list = copy.copy(orig_index_list)

        if shuffle_index_list:
            shuffle(index_list)
        while len(index_list) > 0:
            index = index_list.pop()
            add_data(x_list, y_list, data_file, index, augment=augment, augment_flip=augment_flip,
                     augment_distortion_factor=augment_distortion_factor, patch_shape=patch_shape,
                     skip_blank=skip_blank, permute=permute)
            if len(x_list) == batch_size or (len(index_list) == 0 and len(x_list) > 0):
                yield convert_data(x_list, y_list, n_labels=n_labels, labels=labels)
                x_list = list()
                y_list = list()

def get_number_of_patches(data_file, index_list, patch_shape=None, patch_overlap=0, patch_start_offset=None,
                          skip_blank=True):
    if patch_shape:
        index_list = create_patch_index_list(index_list, data_file.root.data.shape[-3:], patch_shape, patch_overlap,
                                             patch_start_offset)
        count = 0
        for index in index_list:
            x_list = list()
            y_list = list()
            add_data(x_list, y_list, data_file, index, skip_blank=skip_blank, patch_shape=patch_shape)
            if len(x_list) > 0:
                count += 1
        return count
    else:
        return len(index_list)

def create_patch_index_list(index_list, image_shape, patch_shape, patch_overlap, patch_start_offset=None):
    patch_index = list()
    for index in index_list:
        if patch_start_offset is not None:
            random_start_offset = np.negative(get_random_nd_index(patch_start_offset))
            patches = compute_patch_indices(image_shape, patch_shape, overlap=patch_overlap, start=random_start_offset)
        else:
            patches = compute_patch_indices(image_shape, patch_shape, overlap=patch_overlap)
        patch_index.extend(itertools.product([index], patches))
    return patch_index

def add_data(x_list, y_list, data_file, index, augment=False, augment_flip=False, augment_distortion_factor=0.25,
             patch_shape=False, skip_blank=True, permute=False):
    """
    Adds data from the data file to the given lists of feature and target data
    :param skip_blank: Data will not be added if the truth vector is all zeros (default is True).
    :param patch_shape: Shape of the patch to add to the data lists. If None, the whole image will be added.
    :param x_list: list of data to which data from the data_file will be appended.
    :param y_list: list of data to which the target data from the data_file will be appended.
    :param data_file: hdf5 data file.
    :param index: index of the data file from which to extract the data.
    :param augment: if True, data will be augmented according to the other augmentation parameters (augment_flip and
    augment_distortion_factor)
    :param augment_flip: if True and augment is True, then the data will be randomly flipped along the x, y and z axis
    :param augment_distortion_factor: if augment is True, this determines the standard deviation from the original
    that the data will be distorted (in a stretching or shrinking fashion). Set to None, False, or 0 to prevent the
    augmentation from distorting the data in this way.
    :param permute: will randomly permute the data (data must be 3D cube)
    :return:
    """
    data, truth = get_data_from_file(data_file, index, patch_shape=patch_shape)
    if augment:
        if patch_shape is not None:
            affine = data_file.root.affine[index[0]]
        else:
            affine = data_file.root.affine[index]
        data, truth = augment_data(data, truth, affine, flip=augment_flip, scale_deviation=augment_distortion_factor)

    if permute:
        if data.shape[-3] != data.shape[-2] or data.shape[-2] != data.shape[-1]:
            raise ValueError("To utilize permutations, data array must be in 3D cube shape with all dimensions having "
                             "the same length.")
        data, truth = random_permutation_x_y(data, truth[np.newaxis])
    else:
        truth = truth[np.newaxis]

    if not skip_blank or np.any(truth != 0):
        x_list.append(data)
        y_list.append(truth)

def get_data_from_file(data_file, index, patch_shape=None):
    if patch_shape:
        index, patch_index = index
        data, truth = get_data_from_file(data_file, index, patch_shape=None)
        x = get_patch_from_3d_data(data, patch_shape, patch_index)
        y = get_patch_from_3d_data(truth, patch_shape, patch_index)
    else:
        x, y = data_file.root.data[index], data_file.root.truth[index, 0]
    return x, y

def convert_data(x_list, y_list, n_labels=1, labels=None):
    x = np.asarray(x_list)
    y = np.asarray(y_list)
    if n_labels == 1:
        y[y > 0] = 1
    elif n_labels > 1:
        y = get_multi_class_labels(y, n_labels=n_labels, labels=labels)
    return x, y

def get_multi_class_labels(data, n_labels, labels=None):
    """
    Translates a label map into a set of binary labels.
    :param data: numpy array containing the label map with shape: (n_samples, 1, ...).
    :param n_labels: number of labels.
    :param labels: integer values of the labels.
    :return: binary numpy array of shape: (n_samples, n_labels, ...)
    """
    new_shape = [data.shape[0], n_labels] + list(data.shape[2:])
    y = np.zeros(new_shape, np.int8)
    for label_index in range(n_labels):
        if labels is not None:
            y[:, label_index][data[:, 0] == labels[label_index]] = 1
        else:
            y[:, label_index][data[:, 0] == (label_index + 1)] = 1
    return y


text:
Represents a type parameter type.~~~var value:T;~~~

### Extends
* [Type](td.models.type.md)

## Index

### Properties
* [constraint](td.models.typeparametertype.md#constraint)
* [isArray](td.models.typeparametertype.md#isarray)
* [name](td.models.typeparametertype.md#name)

### Methods
* [clone](td.models.typeparametertype.md#clone)
* [equals](td.models.typeparametertype.md#equals)
* [toObject](td.models.typeparametertype.md#toobject)
* [toString](td.models.typeparametertype.md#tostring)
* [isTypeListEqual](td.models.typeparametertype.md#istypelistequal)
* [isTypeListSimiliar](td.models.typeparametertype.md#istypelistsimiliar)

## Properties

### constraint: [Type](td.models.type.md)

* Defined in [td/models/types/TypeParameterType.ts:17](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/types/TypeParameterType.ts#L17)

### isArray: boolean
Is this an array type?
* Inherited from [Type](td.models.type.md).[isArray](td.models.type.md#isarray)
* Defined in [td/models/Type.ts:13](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Type.ts#L13)

### name: string

* Defined in [td/models/types/TypeParameterType.ts:15](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/types/TypeParameterType.ts#L15)

## Methods

### clone(): [Type](td.models.type.md)
Clone this type.
* Overwrites [Type](td.models.type.md).[clone](td.models.type.md#clone)
* Defined in [td/models/types/TypeParameterType.ts:26](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/types/TypeParameterType.ts#L26)

#### Returns: [Type](td.models.type.md)
A clone of this type.

### equals(type: [TypeParameterType](td.models.typeparametertype.md)): boolean
Test whether this type equals the given type.
* Overwrites [Type](td.models.type.md).[equals](td.models.type.md#equals)
* Defined in [td/models/types/TypeParameterType.ts:41](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/types/TypeParameterType.ts#L41)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| type | [TypeParameterType](td.models.typeparametertype.md)| The type that should be checked for equality. |

#### Returns: boolean
TRUE if the given type equals this type, FALSE otherwise.

### toObject(): any
Return a raw object representation of this type.
* Overwrites [Type](td.models.type.md).[toObject](td.models.type.md#toobject)
* Defined in [td/models/types/TypeParameterType.ts:63](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/types/TypeParameterType.ts#L63)

#### Returns: any

### toString(): string
Return a string representation of this type.
* Overwrites [Type](td.models.type.md).[toString](td.models.type.md#tostring)
* Defined in [td/models/types/TypeParameterType.ts:79](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/types/TypeParameterType.ts#L79)

#### Returns: string

### Static isTypeListEqual(a: [Type](td.models.type.md)[], b: [Type](td.models.type.md)[]): boolean
Test whether the two given list of types are equal.
* Inherited from [Type](td.models.type.md).[isTypeListEqual](td.models.type.md#istypelistequal)
* Defined in [td/models/Type.ts:90](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Type.ts#L90)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| a | [Type](td.models.type.md)[]|  |
| b | [Type](td.models.type.md)[]|  |

#### Returns: boolean

### Static isTypeListSimiliar(a: [Type](td.models.type.md)[], b: [Type](td.models.type.md)[]): boolean
Test whether the two given list of types contain equal types.
* Inherited from [Type](td.models.type.md).[isTypeListSimiliar](td.models.type.md#istypelistsimiliar)
* Defined in [td/models/Type.ts:69](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Type.ts#L69)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| a | [Type](td.models.type.md)[]|  |
| b | [Type](td.models.type.md)[]|  |

#### Returns: boolean

Generated using [TypeDoc](http://typedoc.io)


text:
package com.sylvanaar.idea.Lua.lang.psi.statements;

import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import com.sylvanaar.idea.Lua.lang.InferenceCapable;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaExpression;
import com.sylvanaar.idea.Lua.lang.psi.lists.LuaExpressionList;
import com.sylvanaar.idea.Lua.lang.psi.lists.LuaIdentifierList;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaSymbol;
import com.sylvanaar.idea.Lua.lang.psi.util.LuaAssignment;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public interface LuaAssignmentStatement extends LuaMaybeDeclarationAssignmentStatement, LuaStatementElement, LuaDeclarationStatement, InferenceCapable {
    public LuaIdentifierList getLeftExprs();
    public LuaExpressionList getRightExprs();

    @NotNull
    public LuaAssignment[] getAssignments();

    @Nullable
    public LuaExpression getAssignedValue(LuaSymbol symbol);

    public IElementType getOperationTokenType();
    public PsiElement getOperatorElement();
}


text:
/**
 * A bank Account
 *
 * @author rosspa. Created Jun 30, 2014.
 */
public class Account {
	private static long idGenerator = -1;

	private String username;
	private String accountType;
	private String encryptedCents;
	private long accountId;

	/**
	 *
	 * Only used by the server
	 *
	 * @param user
	 * @param accountType
	 * @param encryptedMoney
	 */
	public Account(String username, String accountType, String encryptedMoney) {
		this.username = username;
		this.accountType = accountType;
		this.encryptedCents = encryptedMoney;
		this.accountId = ++idGenerator;
	}

	protected String getAccountType() {
		return this.accountType;
	}

	protected String getEncryptedMoney() {
		return this.encryptedCents;
	}

	protected String getUsername() {
		return this.username;
	}
	protected long getId() {
		return this.accountId;
	}

	protected void deposit(long number) {
//		System.out.println(number + Encrypter.Decrypte(this.encryptedMoney));
		this.encryptedCents = Encrypter.Encrypte(number + Encrypter.Decrypte(this.encryptedCents));
	}
	protected void withdraw(long number) {
		this.encryptedCents = Encrypter.Encrypte(Encrypter.Decrypte(this.encryptedCents) - number);
	}
	protected void setMoney(int number) {
		this.encryptedCents = Encrypter.Encrypte(number);
	}

	protected boolean update() {
		return Server.updateAccount(this);
	}

	protected boolean update(Account otherAccount) {
		return Server.updateAccount(this, otherAccount);
	}

	@Override
	public String toString() {
		return this.accountType; //+ " ($" + Encrypter.Decrypte(this.encryptedMoney) + ")";
	}

}


text:
package org.apache.aries.transaction.internal;

import org.junit.Test;

import static org.junit.Assert.assertNotNull;

public class NLSTest {

    @Test
    public void message() {
        assertNotNull(NLS.MESSAGES.getMessage("log.file.dir"));
    }

}


text:
TUW-IMP at the NTCIR-11 Math2
=============================

This repository contains the Information Retrieval (IR) system developed by the TUW-IMP group for the NTCIR-11 Math2 challenge.
Details about its implementation are available in the following
[Technical Report, Presentation and Poster](https://www.researchgate.net/publication/269988341).

How to use the system
---------------------

To run the commands explained below it is needed the jar file downloadable from the folder
[out/artifacts/tuw_imp_at_the_ntcir_11_math2_jar](https://github.com/aldolipani/TUW-IMP_at_the_NTCIR-11_Math2/tree/master/out/artifacts/tuw_imp_at_the_ntcir_11_math2_jar).
Each command, described below, needs to be preceded by the following command: `java -jar tuw-imp_at_the_ntcir-11_math2.jar`

Help
----

The command `--help` shows the following instructions:

```
Search:    --cmd search --name-run <name> --topics <path> --expansions <path> --formula-index <path> --text-index <path>
Index
 Text:     --cmd index-text     --test-collection <path> --index-folder <path>
 Formulae: --cmd index-formulae --test-collection <path> --index-folder <path>
```

Search
------
After having created the indices (as explained below) the search command search over them. The parameter `--topics` needs the
topics in the XML file, with the format as given by the organizers of the Math challenge. Each topic is composed of a set
of formulae and a set of keywords that are filed respectively to the two indices passed through `--formula-index` for the
index of formulae and `--text-index` for the index of text.
If the text index is omitted the system will search only over the formulae index. However if it is not omitted and there are
keywords in the topics to be searched, it is possible to apply a topic expansion to each of them through an XML file passed
through the parameter `--expansions`.
The expansions used for the challenge NTCIR-11 Math2 are provided in
[input/NTCIR11-Math2-Query_Expansions.xml](https://github.com/aldolipani/TUW-IMP_at_the_NTCIR-11_Math2/tree/master/input).

At the moment, the only settings about the parameters of the system are the ones used in the challenge that can be set up
throng the name of the run. The characteristic of each run are described in the
[technical report](https://www.researchgate.net/publication/269988341),
which are: FLA, FLASM, FLAN and FLASL.

Index Text and Formulae
-----------------------
As we have seen the Search command needs two indices, one for formulae and one for text that can be respectively created using the
two commands `--index-formulae` and `--index-text`. These two commands need as input the compressed test collection (tar.gz)
as provided by the organizers of the Math challenge, which is passed through the parameter `--test-collection`.
And generate as output a Lucene index in the folder specified with the parameter `--index-folder`.


text:
<?xml version="1.0" standalone="no"?>
<!--
  Openbizx Cubi Application Platform
  LICENSE http://code.google.com/p/openbiz-cubi/wiki/CubiLicense
  Copyright (c) 2005-2011, Openbiz Technology LLC
  Version $Id: GeneralDefaultView.xml 3372 2012-05-31 06:19:06Z rockyswen@gmail.com $
-->
<WebPage Name="GeneralDefaultView"
         Description="System Administration"
         Access="Site.Administer_General"
         class="WebPage"
         Tab=""
         TemplateEngine="Smarty"
         TemplateFile="view_dashboard.tpl">
    <FormReferences>
        <!-- <Reference Name="menu.widget.GeneralDashboard"/> -->
        <Reference Name="menu.widget.SitemapMenu"/>
    </FormReferences>
</WebPage>


text:
package mongo

import (
	"fmt"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/x/mongo/driver/operation"
)

// BulkWriteResult is the result type returned by a BulkWrite operation.
type BulkWriteResult struct {
	// The number of documents inserted.
	InsertedCount int64

	// The number of documents matched by filters in update and replace operations.
	MatchedCount int64

	// The number of documents modified by update and replace operations.
	ModifiedCount int64

	// The number of documents deleted.
	DeletedCount int64

	// The number of documents upserted by update and replace operations.
	UpsertedCount int64

	// A map of operation index to the _id of each upserted document.
	UpsertedIDs map[int64]interface{}
}

// InsertOneResult is the result type returned by an InsertOne operation.
type InsertOneResult struct {
	// The _id of the inserted document. A value generated by the driver will be of type primitive.ObjectID.
	InsertedID interface{}
}

// InsertManyResult is a result type returned by an InsertMany operation.
type InsertManyResult struct {
	// The _id values of the inserted documents. Values generated by the driver will be of type primitive.ObjectID.
	InsertedIDs []interface{}
}

// DeleteResult is the result type returned by DeleteOne and DeleteMany operations.
type DeleteResult struct {
	DeletedCount int64 `bson:"n"` // The number of documents deleted.
}

// ListDatabasesResult is a result of a ListDatabases operation.
type ListDatabasesResult struct {
	// A slice containing one DatabaseSpecification for each database matched by the operation's filter.
	Databases []DatabaseSpecification

	// The total size of the database files of the returned databases in bytes.
	// This will be the sum of the SizeOnDisk field for each specification in Databases.
	TotalSize int64
}

func newListDatabasesResultFromOperation(res operation.ListDatabasesResult) ListDatabasesResult {
	var ldr ListDatabasesResult
	ldr.Databases = make([]DatabaseSpecification, 0, len(res.Databases))
	for _, spec := range res.Databases {
		ldr.Databases = append(
			ldr.Databases,
			DatabaseSpecification{Name: spec.Name, SizeOnDisk: spec.SizeOnDisk, Empty: spec.Empty},
		)
	}
	ldr.TotalSize = res.TotalSize
	return ldr
}

// DatabaseSpecification contains information for a database. This type is returned as part of ListDatabasesResult.
type DatabaseSpecification struct {
	Name       string // The name of the database.
	SizeOnDisk int64  // The total size of the database files on disk in bytes.
	Empty      bool   // Specfies whether or not the database is empty.
}

// UpdateResult is the result type returned from UpdateOne, UpdateMany, and ReplaceOne operations.
type UpdateResult struct {
	MatchedCount  int64       // The number of documents matched by the filter.
	ModifiedCount int64       // The number of documents modified by the operation.
	UpsertedCount int64       // The number of documents upserted by the operation.
	UpsertedID    interface{} // The _id field of the upserted document, or nil if no upsert was done.
}

// UnmarshalBSON implements the bson.Unmarshaler interface.
func (result *UpdateResult) UnmarshalBSON(b []byte) error {
	elems, err := bson.Raw(b).Elements()
	if err != nil {
		return err
	}

	for _, elem := range elems {
		switch elem.Key() {
		case "n":
			switch elem.Value().Type {
			case bson.TypeInt32:
				result.MatchedCount = int64(elem.Value().Int32())
			case bson.TypeInt64:
				result.MatchedCount = elem.Value().Int64()
			default:
				return fmt.Errorf("Received invalid type for n, should be Int32 or Int64, received %s", elem.Value().Type)
			}
		case "nModified":
			switch elem.Value().Type {
			case bson.TypeInt32:
				result.ModifiedCount = int64(elem.Value().Int32())
			case bson.TypeInt64:
				result.ModifiedCount = elem.Value().Int64()
			default:
				return fmt.Errorf("Received invalid type for nModified, should be Int32 or Int64, received %s", elem.Value().Type)
			}
		case "upserted":
			switch elem.Value().Type {
			case bson.TypeArray:
				e, err := elem.Value().Array().IndexErr(0)
				if err != nil {
					break
				}
				if e.Value().Type != bson.TypeEmbeddedDocument {
					break
				}
				var d struct {
					ID interface{} `bson:"_id"`
				}
				err = bson.Unmarshal(e.Value().Document(), &d)
				if err != nil {
					return err
				}
				result.UpsertedID = d.ID
			default:
				return fmt.Errorf("Received invalid type for upserted, should be Array, received %s", elem.Value().Type)
			}
		}
	}

	return nil
}


text:
import numpy as np
from numba import vectorize
from numba.cuda.testing import skip_on_cudasim, CUDATestCase
import unittest

@skip_on_cudasim('ufunc API unsupported in the simulator')
class TestVectorizeComplex(CUDATestCase):
    def test_vectorize_complex(self):
        @vectorize(['complex128(complex128)'], target='cuda')
        def vcomp(a):
            return a * a + 1.

        A = np.arange(5, dtype=np.complex128)
        B = vcomp(A)
        self.assertTrue(np.allclose(A * A + 1., B))

if __name__ == '__main__':
    unittest.main()


text:
/* eslint-disable no-use-before-define */

import mongoose, { Document } from 'mongoose';
import type { Schema, Model } from 'mongoose';
import type {
  SchemaComposer,
  ObjectTypeComposer,
  EnumTypeComposer,
  ComposeOutputTypeDefinition,
  ObjectTypeComposerFieldConfigAsObjectDefinition,
} from 'graphql-compose';
import { upperFirst } from 'graphql-compose';
import type { GraphQLScalarType } from 'graphql-compose/lib/graphql';
import GraphQLMongoID from './types/MongoID';
import GraphQLBSONDecimal from './types/BSONDecimal';

type MongooseFieldT = {
  path?: string;
  instance: string;
  caster?: any;
  options?: {
    description?: string;
    alias?: string;
  };
  originalRequiredValue?: string | (() => any);
  isRequired?: boolean;
  defaultValue?: any;
  enumValues?: string[];
  schema?: Schema;
  _index?: { [optionName: string]: any };
};
type MongooseFieldMapT = { [fieldName: string]: MongooseFieldT };
type ComposeScalarType = string | GraphQLScalarType;

export type MongoosePseudoModelT = {
  schema: Schema<any>;
};

export enum ComplexTypes {
  ARRAY = 'ARRAY',
  EMBEDDED = 'EMBEDDED',
  DOCUMENT_ARRAY = 'DOCUMENT_ARRAY',
  ENUM = 'ENUM',
  REFERENCE = 'REFERENCE',
  SCALAR = 'SCALAR',
  MIXED = 'MIXED',
  DECIMAL = 'DECIMAL',
}

function _getFieldName(field: MongooseFieldT): string {
  return field.path || '__unknownField__';
}

function _getFieldType(field: MongooseFieldT): string {
  return field.instance;
}

function _getFieldDescription(field: MongooseFieldT): string | undefined {
  if (field.options && field.options.description) {
    return field.options.description;
  }

  return undefined;
}

function _getFieldEnums(field: MongooseFieldT): string[] | undefined {
  if (field.enumValues && field.enumValues.length > 0) {
    return field.enumValues;
  }

  return undefined;
}

export function dotPathsToEmbedded(fields: MongooseFieldMapT): MongooseFieldMapT {
  // convert only one dot-level on this step to EmbeddedModel
  // further when converting EmbeddedModel to GQL, it internally
  // call this method to extract deep fields with dots

  const result: MongooseFieldMapT = {};

  Object.keys(fields).forEach((fieldName) => {
    const dotIdx = fieldName.indexOf('.');
    if (dotIdx === -1) {
      result[fieldName] = fields[fieldName];
    } else if (fieldName.substr(dotIdx, 3) === '.$*') {
      // skip { type: Map of: String }
      // do not add this field to result
    } else {
      // create pseudo sub-model
      const name = fieldName.substr(0, dotIdx);
      if (!result[name]) {
        const embeddedField = {
          instance: 'Embedded',
          path: name,
          schema: {
            paths: {},
          },
        } as MongooseFieldT;
        result[name] = embeddedField;
      }
      const subName = fieldName.substr(dotIdx + 1);

      const fieldSchema = result[name].schema;
      if (!fieldSchema) {
        throw new Error(`Field ${name} does not have schema property`);
      }
      fieldSchema.paths[subName] = { ...fields[fieldName], path: subName } as any;
    }
  });

  return result;
}

export function getFieldsFromModel(model: Model<any> | MongoosePseudoModelT): MongooseFieldMapT {
  if (!model || !model.schema || !model.schema.paths) {
    throw new Error(
      'You provide incorrect mongoose model to `getFieldsFromModel()`. ' +
        'Correct model should contain `schema.paths` properties.'
    );
  }

  const fields: Record<string, MongooseFieldT> = {};
  const paths = dotPathsToEmbedded((model as any).schema.paths);

  Object.keys(paths)
    .filter((path) => !path.startsWith('__')) // skip hidden fields
    .forEach((path: string) => {
      fields[path] = paths[path];
    });

  return fields;
}

export function convertModelToGraphQL<TDoc extends Document, TContext>(
  model: Model<TDoc> | MongoosePseudoModelT,
  typeName: string,
  schemaComposer: SchemaComposer<TContext>
): ObjectTypeComposer<TDoc, TContext> {
  const sc = schemaComposer;

  if (!typeName) {
    throw new Error('You provide empty name for type. `name` argument should be non-empty string.');
  }

  // if model already has generated ObjectTypeComposer early, then return it
  if (sc.has(model.schema)) {
    return sc.getOTC(model.schema);
  }

  // add type to registry before fields creation
  // it helps to avoid circuit dependencies, eg. `User { friends: [User] }`
  const typeComposer = sc.getOrCreateOTC(typeName);
  sc.set(model.schema, typeComposer);
  sc.set(typeName, typeComposer);

  const mongooseFields = getFieldsFromModel(model);
  const graphqlFields = {} as Record<
    string,
    ObjectTypeComposerFieldConfigAsObjectDefinition<any, any>
  >;
  const requiredFields = [] as string[];

  Object.keys(mongooseFields).forEach((key) => {
    const mongooseField: MongooseFieldT = mongooseFields[key];

    let fieldName = key;
    if (typeof mongooseField?.options?.alias === 'string') {
      fieldName = mongooseField?.options?.alias;
    }

    if (
      mongooseField.isRequired &&
      // conditional required field in mongoose cannot be NonNullable in GraphQL
      typeof mongooseField?.originalRequiredValue !== 'function'
    ) {
      requiredFields.push(fieldName);
    }

    let type = convertFieldToGraphQL(mongooseField, typeName, sc);

    // in mongoose schema we use javascript `Number` object which casted to `Float` type
    // so in most cases _id field is `Int`
    if (fieldName === '_id' && type === 'Float') {
      type = 'Int';
    }

    graphqlFields[fieldName] = {
      type,
      description: _getFieldDescription(mongooseField),
    };

    if (mongooseField?.defaultValue !== null && mongooseField?.defaultValue !== undefined) {
      if (!graphqlFields[fieldName].extensions) graphqlFields[fieldName].extensions = {};
      (graphqlFields as any)[fieldName].extensions.defaultValue = mongooseField?.defaultValue;
    }
  });

  typeComposer.addFields(graphqlFields);
  typeComposer.makeFieldNonNull(requiredFields);
  return typeComposer;
}

export function convertSchemaToGraphQL(
  schema: Schema<any>,
  typeName: string,
  schemaComposer: SchemaComposer<any>
): ObjectTypeComposer<any, any> {
  const sc = schemaComposer;

  if (!typeName) {
    throw new Error('You provide empty name for type. `name` argument should be non-empty string.');
  }

  if (sc.has(schema)) {
    return sc.getOTC(schema);
  }

  const tc = convertModelToGraphQL({ schema }, typeName, sc);
  // also generate InputType
  tc.getInputTypeComposer();

  sc.set(schema, tc);
  return tc;
}

export function convertFieldToGraphQL(
  field: MongooseFieldT,
  prefix: string = '',
  schemaComposer: SchemaComposer<any>
): ComposeOutputTypeDefinition<any> {
  if (!schemaComposer.has('MongoID')) {
    schemaComposer.add(GraphQLMongoID);
  }

  const complexType = deriveComplexType(field);
  switch (complexType) {
    case ComplexTypes.SCALAR:
      return scalarToGraphQL(field);
    case ComplexTypes.ARRAY:
      return arrayToGraphQL(field, prefix, schemaComposer);
    case ComplexTypes.EMBEDDED:
      return embeddedToGraphQL(field, prefix, schemaComposer);
    case ComplexTypes.ENUM:
      return enumToGraphQL(field, prefix, schemaComposer);
    case ComplexTypes.REFERENCE:
      return referenceToGraphQL(field);
    case ComplexTypes.DOCUMENT_ARRAY:
      return documentArrayToGraphQL(field, prefix, schemaComposer);
    case ComplexTypes.MIXED:
      return 'JSON';
    case ComplexTypes.DECIMAL:
      if (!schemaComposer.has('BSONDecimal')) {
        schemaComposer.add(GraphQLBSONDecimal);
      }
      return 'BSONDecimal';
    default:
      return scalarToGraphQL(field);
  }
}

export function deriveComplexType(field: MongooseFieldT): ComplexTypes {
  if (!field || !field.path || !field.instance) {
    throw new Error(
      'You provide incorrect mongoose field to `deriveComplexType()`. ' +
        'Correct field should contain `path` and `instance` properties.'
    );
  }

  const fieldType = _getFieldType(field);
  if (
    field instanceof mongoose.Schema.Types.DocumentArray ||
    (fieldType === 'Array' && field?.schema?.paths)
  ) {
    return ComplexTypes.DOCUMENT_ARRAY;
  } else if (field instanceof mongoose.Schema.Types.Embedded || fieldType === 'Embedded') {
    return ComplexTypes.EMBEDDED;
  } else if (field instanceof mongoose.Schema.Types.Array || field?.caster?.instance) {
    return ComplexTypes.ARRAY;
  } else if (field instanceof mongoose.Schema.Types.Mixed) {
    return ComplexTypes.MIXED;
  } else if (fieldType === 'ObjectID') {
    return ComplexTypes.REFERENCE;
  } else if (fieldType === 'Decimal128') {
    return ComplexTypes.DECIMAL;
  }

  const enums = _getFieldEnums(field);
  if (enums) {
    return ComplexTypes.ENUM;
  }

  return ComplexTypes.SCALAR;
}

export function scalarToGraphQL(field: MongooseFieldT): ComposeScalarType {
  const typeName = _getFieldType(field);

  switch (typeName) {
    case 'String':
      return 'String';
    case 'Number':
      return 'Float';
    case 'Date':
      return 'Date';
    case 'Buffer':
      return 'Buffer';
    case 'Boolean':
      return 'Boolean';
    case 'ObjectID':
      return 'MongoID';
    default:
      return 'JSON';
  }
}

export function arrayToGraphQL(
  field: MongooseFieldT,
  prefix: string = '',
  schemaComposer: SchemaComposer<any>
): ComposeOutputTypeDefinition<any> {
  if (!field || !field.caster) {
    throw new Error(
      'You provide incorrect mongoose field to `arrayToGraphQL()`. ' +
        'Correct field should contain `caster` property.'
    );
  }

  const unwrappedField = { ...field.caster };

  const outputType: any = convertFieldToGraphQL(unwrappedField, prefix, schemaComposer);
  return [outputType];
}

export function embeddedToGraphQL(
  field: MongooseFieldT,
  prefix: string = '',
  schemaComposer: SchemaComposer<any>
): ObjectTypeComposer<any, any> {
  const fieldName = _getFieldName(field);
  const fieldType = _getFieldType(field);

  if (fieldType !== 'Embedded') {
    throw new Error(
      `You provide incorrect field '${prefix}.${fieldName}' to 'embeddedToGraphQL()'. ` +
        'This field should has `Embedded` type. '
    );
  }

  const fieldSchema = field.schema;
  if (!fieldSchema) {
    throw new Error(`Mongoose field '${prefix}.${fieldName}' should have 'schema' property`);
  }

  const typeName = `${prefix}${upperFirst(fieldName)}`;
  return convertSchemaToGraphQL(fieldSchema, typeName, schemaComposer);
}

export function enumToGraphQL(
  field: MongooseFieldT,
  prefix: string = '',
  schemaComposer: SchemaComposer<any>
): EnumTypeComposer<any> {
  const valueList = _getFieldEnums(field);
  if (!valueList) {
    throw new Error(
      'You provide incorrect mongoose field to `enumToGraphQL()`. ' +
        'Correct field should contain `enumValues` property'
    );
  }

  const typeName = `Enum${prefix}${upperFirst(_getFieldName(field))}`;

  return schemaComposer.getOrCreateETC(typeName, (etc) => {
    const desc = _getFieldDescription(field);
    if (desc) etc.setDescription(desc);

    const fields = valueList.reduce((result, value) => {
      const key = value.replace(/[^_a-zA-Z0-9]/g, '_');
      result[key] = { value };
      return result;
    }, {} as Record<string, { value: any }>);
    etc.setFields(fields);
  });
}

export function documentArrayToGraphQL(
  field: MongooseFieldT,
  prefix: string = '',
  schemaComposer: SchemaComposer<any>
): [ObjectTypeComposer<any, any>] {
  if (!(field instanceof mongoose.Schema.Types.DocumentArray) && !field?.schema?.paths) {
    throw new Error(
      'You provide incorrect mongoose field to `documentArrayToGraphQL()`. ' +
        'Correct field should be instance of `mongoose.Schema.Types.DocumentArray`'
    );
  }

  const typeName = `${prefix}${upperFirst(_getFieldName(field))}`;

  const tc = convertModelToGraphQL(field as any, typeName, schemaComposer);

  return [tc];
}

export function referenceToGraphQL(field: MongooseFieldT): ComposeScalarType {
  return scalarToGraphQL(field);
}


text:
package org.innovateuk.ifs.category.builder;

import org.innovateuk.ifs.category.resource.InnovationAreaResource;
import org.innovateuk.ifs.category.resource.InnovationSectorResource;

import java.util.List;
import java.util.function.BiConsumer;

import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.uniqueIds;

public class InnovationSectorResourceBuilder extends CategoryResourceBuilder<InnovationSectorResource, InnovationSectorResourceBuilder> {
    protected InnovationSectorResourceBuilder(List<BiConsumer<Integer, InnovationSectorResource>> multiActions) {
        super(multiActions);
    }

    public static InnovationSectorResourceBuilder newInnovationSectorResource() {
        return new InnovationSectorResourceBuilder(emptyList()).with(uniqueIds());
    }

    @Override
    protected InnovationSectorResourceBuilder createNewBuilderWithActions(List<BiConsumer<Integer, InnovationSectorResource>> actions) {
        return new InnovationSectorResourceBuilder(actions);
    }

    @Override
    protected InnovationSectorResource createInitial() {
        return new InnovationSectorResource();
    }

    public InnovationSectorResourceBuilder withChildren(List<InnovationAreaResource>... innovationAreaResourceLists) {
        return withArraySetFieldByReflection("children", innovationAreaResourceLists);
    }
}


text:
class MiqPolicy < ApplicationRecord
  TOWHAT_APPLIES_TO_CLASSES = %w(ContainerGroup
                                 ContainerImage
                                 ContainerNode
                                 ContainerProject
                                 ContainerReplicator
                                 ExtManagementSystem
                                 Host
                                 PhysicalServer
                                 Vm).freeze

  POLICY_TOWHAT_APPLIES_TO_CLASSES = TOWHAT_APPLIES_TO_CLASSES.inject({}) { |hsh, key| hsh[key] = ui_lookup(:model => key); hsh }.freeze

  POLICY_MODES = {
    "control" => _("Control"),
    "compliance" => _("Compliance")
  }.freeze

  acts_as_miq_taggable
  acts_as_miq_set_member
  include_concern 'ImportExport'

  include UuidMixin
  include YAMLImportExportMixin
  before_validation :default_name_to_guid, :on => :create

  default_value_for :towhat, 'Vm'
  default_value_for :active, true
  default_value_for :mode,   'control'

  # NOTE: If another class references MiqPolicy through an ActiveRecord association,
  #   particularly has_one and belongs_to, calling .conditions will result in
  #   that method being directly called on the proxy object, as opposed to the
  #   target object, since that method is defined on the proxy object.  The
  #   workaround is to call .target on the proxy first before calling .conditions.
  #   Additionally, this reflection could be renamed to not cause a conflict.
  has_and_belongs_to_many :conditions

  has_many                :miq_policy_contents, :dependent => :destroy
  has_many                :policy_events

  virtual_has_many :miq_event_definitions, :uses => {:miq_policy_contents => :miq_event_definition}

  validates :description, :presence => true, :uniqueness_when_changed => true
  validates :name, :presence => true, :uniqueness_when_changed => true
  validates :mode, :inclusion => { :in => %w(compliance control) }
  validates :towhat, :inclusion => { :in      => TOWHAT_APPLIES_TO_CLASSES,
                                     :message => "should be one of #{TOWHAT_APPLIES_TO_CLASSES.join(", ")}" }

  scope :with_mode,   ->(mode)   { where(:mode => mode) }
  scope :with_towhat, ->(towhat) { where(:towhat => towhat) }

  serialize :expression

  virtual_column :display_name, :type => :string

  @@associations_to_get_policies = [:parent_enterprise, :ext_management_system, :parent_datacenter, :ems_cluster, :parent_resource_pool, :host]

  attr_accessor :reserved

  class_attribute :associations_to_get_policies

  @@built_in_policies = nil

  def self.built_in_policies
    return @@built_in_policies.dup unless @@built_in_policies.nil?

    policy_hashes = YAML.load_file(Rails.root.join("product", "policy", "built_in_policies.yml"))

    @@built_in_policies = policy_hashes.collect do |p_hash|
      policy = OpenStruct.new(p_hash)
      policy.attributes =
        {
          "name"        => "(Built-in) #{p_hash[:name]}",
          "description" => "(Built-in) #{p_hash[:description]}",
          :applies_to?  => p_hash[:applies_to?]
        }
      policy.events = [MiqEventDefinition.find_by(:name => policy.event)]
      policy.conditions =
        if policy.condition
          [Condition.new(
            :name        => policy.attributes["name"],
            :description => policy.attributes["description"],
            :expression  => MiqExpression.new(policy.condition),
            :towhat      => "Vm"
          )]
        else
          []
        end
      policy.actions_for_event = [MiqAction.find_by(:name => policy.action)]

      p_metaclass = class << policy; self; end
      p_metaclass.send(:define_method, :applies_to?) { |*_args| p_hash[:applies_to?] }
      policy
    end
    @@built_in_policies.dup
  end

  CLEAN_ATTRS = %w(id guid name created_on updated_on miq_policy_id description)
  def self.clean_attrs(attrs)
    CLEAN_ATTRS.each { |a| attrs.delete(a) }
    attrs
  end

  def display_name
    "#{towhat.constantize.display_name} #{mode.capitalize}: #{description}"
  end

  def copy(new_fields)
    npolicy = self.class.new(self.class.clean_attrs(attributes).merge(new_fields))
    npolicy.conditions = conditions
    npolicy.miq_policy_contents = miq_policy_contents.collect do |pc|
      MiqPolicyContent.new(self.class.clean_attrs(pc.attributes))
    end
    npolicy.tap(&:save!)
  end

  def miq_event_definitions
    miq_policy_contents.collect(&:miq_event_definition).compact.uniq
  end
  alias_method :events, :miq_event_definitions

  def miq_actions
    miq_policy_contents.collect(&:miq_action).compact.uniq
  end
  alias_method :actions, :miq_actions

  def actions_for_event(event, on = :failure)
    order = on == :success ? "success_sequence" : "failure_sequence"
    miq_policy_contents.where(:miq_event_definition => event).order(order).collect do |pe|
      next unless pe.qualifier == on.to_s
      pe.get_action(on)
    end.compact
  end

  def delete_event(event)
    MiqPolicyContent.where(:miq_policy => self, :miq_event_definition => event).destroy_all
  end

  def add_event(event)
    MiqPolicyContent.create(:miq_policy => self, :miq_event_definition => event)
  end

  def sync_events(events)
    cevents = miq_event_definitions
    adds = events - cevents
    deletes = cevents - events
    deletes.each { |e| delete_event(e) }
    adds.each    { |e| add_event(e) }
  end

  def replace_actions_for_event(event, action_list)
    delete_event(event)
    return if action_list.blank?

    succes_seq = 0
    fail_seq = 0
    action_list.each do |action, opts|
      opts[:qualifier] ||= "failure"
      opts[:sequence]  = opts[:qualifier].to_s == "success" ? succes_seq += 1 : fail_seq += 1
      add_action_for_event(event, action, opts)
    end
  end

  def self.enforce_policy(target, event, inputs = {})
    return unless target.respond_to?(:get_policies)

    result = {:result => true, :details => []}

    erec = find_event_def(event)
    if erec.nil?
      logger.info("MIQ(policy-enforce_policy): Event: [#{event}], not defined, skipping policy enforcement")
      return result
    end

    logger.info("MIQ(policy-enforce_policy): Event: [#{event}], To: [#{target.name}]")

    mode = event.ends_with?("compliance_check") ? "compliance" : "control"

    profiles, plist = get_policies_for_target(target, mode, erec, inputs)
    return result if plist.blank?

    succeeded, failed = evaluate_conditions(plist, target, mode, inputs, result)

    # inject policy results into errors attribute of "target" object
    target.errors.clear
    # TODO: If we need this validation on the object, create a real/virtual attribute so ActiveModel doesn't yell
    target.errors.add(:smart, result[:result])

    actions = invoke_actions(target, mode, profiles, succeeded, failed, inputs.merge(:event => erec))
    result[:actions] = actions if actions
    result
  end

  def self.find_event_def(event)
    # rsop event doesn't exist. It's used to run rsop without taking any actions
    if event == 'rsop'
      MiqEventDefinition.new(:name => event)
    else
      MiqEventDefinition.find_by(:name => event)
    end
  end

  def self.display_name(number = 1)
    n_('Policy', 'Policies', number)
  end

  private_class_method :find_event_def

  def self.evaluate_conditions(plist, target, mode, inputs, result)
    failed = []
    succeeded = []
    plist.each do |p|
      logger.info("MIQ(policy-enforce_policy): Resolving policy [#{p.description}]...")
      if p.conditions.empty?
        always_condition = {"id" => nil, "description" => "always", "result" => "allow"}
        result[:details].push(p.attributes.merge("result" => true, "conditions" => [always_condition]))
        succeeded.push(p)
        next
      end

      cond_result, clist = evaluate_conditions_for_policy(target, p, mode, inputs)

      if cond_result == "deny"
        result[:result] = false
        result[:details].push(p.attributes.merge("result" => false, "conditions" => clist))
        failed.push(p)
      else
        result[:details].push(p.attributes.merge("result" => true, "conditions" => clist))
        succeeded.push(p)
      end
    end
    [succeeded, failed]
  end
  private_class_method :evaluate_conditions

  def self.evaluate_conditions_for_policy(target, policy, mode, inputs)
    cond_result = "allow"
    clist = []
    policy.conditions.uniq.each do |c|
      unless c.applies_to?(target, inputs)
        # skip conditions that do not apply based on applies_to_exp
        logger.info("MIQ(policy-enforce_policy): Resolving policy [#{policy.description}], Condition: [#{c.description}] does not apply, skipping...")
        next
      end

      eval_result = eval_condition(c, target, inputs)
      cond_result = eval_result if eval_result == "deny"
      clist.push(c.attributes.merge("result" => eval_result))

      break if eval_result == "deny" && mode == "control"
    end
    [cond_result, clist]
  end
  private_class_method :evaluate_conditions_for_policy

  def self.invoke_actions(target, mode, profiles, succeeded, failed, inputs)
    # don't create policy events or invoke actions if we're doing rsop
    event = inputs[:event]
    return if event.name == 'rsop'

    if mode == 'control'
      pevent = build_results(failed, profiles, event, :failure) + build_results(succeeded, profiles, event, :success)
      PolicyEvent.create_events(target, event, pevent)
    end
    MiqAction.invoke_actions(target, inputs, succeeded, failed)
  end
  private_class_method :invoke_actions

  def self.build_results(policies, profiles, event, status)
    # [
    #   :miq_policy => MiqPolicy#Object
    #   :result => ...,
    #   :miq_actions => [...],
    #   :miq_policy_sets => [...]
    # ]
    policies.collect do |p|
      next unless p.kind_of?(self) # skip built-in policies
      {
        :miq_policy      => p,
        :result          => status.to_s,
        :miq_actions     => p.actions_for_event(event, status).uniq,
        :miq_policy_sets => p.memberof.select { |ps| profiles.include?(ps) }
      }
    end.compact
  end
  private_class_method :build_results

  def self.resolve(rec, list = nil, event = nil)
    # list is expected to be a list of policies, not profiles.
    policies = list.nil? ? all : where(:name => list)
    policies.collect do |p|
      next if event && !p.events.include?(event)

      policy_hash = {"result" => "N/A", "conditions" => [], "actions" => []}
      policy_hash["scope"] = MiqExpression.evaluate_atoms(p.expression, rec) unless p.expression.nil?
      if policy_hash["scope"].nil? || policy_hash["scope"]["result"]
        policy_hash['result'], policy_hash['conditions'] = resolve_policy_conditions(p, rec)

        action_on = policy_hash["result"] == "deny" ? :failure : :success
        policy_hash["actions"] =
          p.actions_for_event(event, action_on).uniq.collect do |a|
            {"id" => a.id, "name" => a.name, "description" => a.description, "result" => policy_hash["result"]}
          end unless event.nil?
      end
      p.attributes.merge(policy_hash)
    end.compact
  end

  def self.resolve_policy_conditions(policy, rec)
    policy_result = 'allow'
    conditions =
      policy.conditions.collect do |c|
        rec_model = rec.class.base_model.name
        rec_model = "Vm" if rec_model.downcase.match("template")
        next unless rec_model == c["towhat"]

        resolve_condition(c, rec).tap do |cond_hash|
          policy_result = cond_hash["result"] if cond_hash["result"] == "deny"
        end
      end.compact

    if policy.active == true
      result_list = conditions.collect { |c| c["result"] }.uniq
      policy_result = result_list.first if result_list.length == 1 && result_list.first == "N/A"
    else
      policy_result = "N/A" # Ignore condition result if policy is inactive
    end
    [policy_result, conditions]
  end
  private_class_method :resolve_policy_conditions

  def self.resolve_condition(cond, rec)
    cond_hash = {"id" => cond.id, "name" => cond.name, "description" => cond.description}
    cond_hash["scope"] = MiqExpression.evaluate_atoms(cond.applies_to_exp, rec) unless cond.applies_to_exp.nil?
    if cond_hash["scope"].nil? || cond_hash["scope"]["result"]
      cond_hash["result"] = eval_condition(cond, rec)
      cond_hash["expression"] = MiqExpression.evaluate_atoms(cond.expression, rec)
    else
      cond_hash["result"] = "N/A"
      cond_hash["expression"] = cond.expression.exp
    end
    cond_hash
  end
  private_class_method :resolve_condition

  def applies_to?(rec, inputs = {})
    rec_model = rec.class.base_model.name
    rec_model = "Vm" if rec_model.downcase.match("template")

    return false if towhat && rec_model != towhat
    return true  if expression.nil?

    Condition.evaluate(self, rec, inputs)
  end

  def self.eval_condition(c, rec, inputs = {})
    Condition.evaluate(c, rec, inputs) ? 'allow' : 'deny'
  rescue => err
    logger.log_backtrace(err)
  end
  private_class_method :eval_condition

  EVENT_GROUPS_EXCLUDED = ["evm_operations", "ems_operations"]
  def self.all_policy_events
    MiqEventDefinition.all_events.select { |e| !e.memberof.empty? && !EVENT_GROUPS_EXCLUDED.include?(e.memberof.first.name) }
  end

  def self.all_policy_events_filter
    # Todo Convert to SQL if possible
    filter_hash = {
       "AND" => [
           {"="  => {"field" => "MiqEventDefinition-event_type",       "value" => "Default"}},
           {"!=" => {"field" => "MiqEventDefinition-event_group_name", "value" => ""}}
          ]
        }
        EVENT_GROUPS_EXCLUDED.each do |e|
          filter_hash["AND"] << {"!=" => {"field" => "MiqEventDefinition-event_group_name", "value" => e}}
        end

        MiqExpression.new(filter_hash)
  end

  def self.logger
    $policy_log
  end

  def last_event
    policy_events.last.try(:created_on)
  end

  def first_event
    policy_events.first.try(:created_on)
  end

  def first_and_last_event
    [first_event, last_event].compact
  end

  def self.get_policies_for_target(target, mode, event, inputs = {})
    event = find_event_def(event) if event.kind_of?(String)

    # collect policies expand profiles (sets)
    profiles, plist = get_expanded_profiles_and_policies(target)
    plist = built_in_policies.concat(plist).uniq

    towhat = target.class.base_model.name
    towhat = "Vm" if towhat.downcase.match("template")
    plist.keep_if do |p|
      p.mode == mode &&
      p.towhat == towhat &&
      policy_for_event?(p, event) &&
      policy_active?(p) &&
      policy_applicable?(p, target, inputs)
    end

    [profiles, plist]
  end

  def self.policy_for_event?(policy, event)
    event.name == 'rsop' || policy.events.include?(event)
  end
  private_class_method :policy_for_event?

  def self.policy_active?(policy)
    return true if policy.active

    logger.info("MIQ(policy-enforce_policy): Policy [#{policy.description}] is not active, skipping...")
    false
  end
  private_class_method :policy_active?

  def self.policy_applicable?(policy, target, inputs)
    return true if policy.applies_to?(target, inputs)

    logger.info("MIQ(policy-enforce_policy): Policy [#{policy.description}] does not apply, skipping...")
    false
  end
  private_class_method :policy_applicable?

  def self.get_expanded_profiles_and_policies(target)
    # get profiles and policies from target object
    target_policies = target.get_policies
    target_profiles = separate_profiles_from_policies(target_policies)

    # get profiles and policies from associations
    assoc_policies =
      @@associations_to_get_policies.collect do |assoc|
        next unless target.respond_to?(assoc)

        obj = target.send(assoc)
        next unless obj

        obj.get_policies
      end.compact.flatten
    assoc_profiles = separate_profiles_from_policies(assoc_policies)

    [target_profiles.concat(assoc_profiles), target_policies.concat(assoc_policies).flatten.compact.uniq]
  end
  private_class_method :get_expanded_profiles_and_policies

  def self.separate_profiles_from_policies(policies)
    profiles = []
    policies.collect! do |p|
      if p.kind_of?(MiqPolicySet)
        profiles.push(p)
        p = p.members
      end
      p
    end

    profiles
  end
  private_class_method :separate_profiles_from_policies

  def add_action_for_event(event, action, opt_hash = nil)
    # we now expect an options hash provided by the UI, merge the qualifier with the options_hash
    # overwriting with the values from the options hash
    opt_hash = {:qualifier => :failure}.merge(opt_hash)

    # update the correct DB sequence and synchronous value with the value from the UI
    opt_hash[:qualifier] = opt_hash[:qualifier].to_s
    case opt_hash[:qualifier]
    when "success"
      opt_hash[:success_sequence]    = opt_hash[:sequence]
      opt_hash[:success_synchronous] = opt_hash[:synchronous]
    when "failure"
      opt_hash[:failure_sequence]    = opt_hash[:sequence]
      opt_hash[:failure_synchronous] = opt_hash[:synchronous]
    when "both"
      opt_hash[:success_sequence]    = opt_hash[:sequence]
      opt_hash[:failure_sequence]    = opt_hash[:sequence]
      opt_hash[:success_synchronous] = opt_hash[:synchronous]
      opt_hash[:failure_synchronous] = opt_hash[:synchronous]
    end
    opt_hash.delete(:sequence)
    opt_hash.delete(:synchronous)

    pevent = miq_policy_contents.build(opt_hash)
    pevent.miq_event_definition  = event
    pevent.miq_action = action
    pevent.save

    self.save!
  end
  private :add_action_for_event
end


text:
package ul

trait GetArgs extends Props {

    //parse array of arguments and place result to props
    def argsParse(args: Array[String], sep:String = "=") {
        for (a <- args) {
            val as = a.split(sep)
            if (as.length <= 2) {
                argFind(as(0)) match {
                    case Some(attr) =>
                        try {
                            props.updateString(attr.tag, if (as.length == 2) as(1) else "true")
                        } catch { case _:Throwable => }
                    case None =>
                }
            }
        }
    }

    //find property with name
    def argFind(name:String, sep:String = ";"):Option[PropAttr] =
        props.attrs.find( _.name.split(sep).contains(name))

    //generate help text
    def argsHelp:String = {
        val s = new StringBuilder
        for (p <- props.attrs) {
            s.append(p.name).append(" [").append(props.typeStr(p.tag)).append(" = ").append(props.get(p.tag)).append("] - ").append(p.descr).append("\n")
        }
        s.toString
    }

}


text:
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<style>
		body {
			font-family: Helvetica, Arial, sans-serif;
			font-size: 12px;
			background-color: #000;
			margin: 0px;
			overflow: hidden;
		}
		#edit {
			position: absolute;
			bottom: 20px;
			right: 20px;
			padding: 8px;
			color: #555;
			background-color: #fff;
			opacity: 0.5;
		}
		#edit:hover {
			cursor: pointer;
			opacity: 1;
		}
		</style>
	</head>
	<body ontouchstart="">
		<script src="js/three.min.js"></script>
		<script src="js/app.js"></script>
		<script>

			var loader = new THREE.XHRLoader();
			loader.load( 'app.json', function ( text ) {

				var json = JSON.parse( text );

				var player = new APP.Player();
				player.load( json );
				player.setSize( window.innerWidth, window.innerHeight );
				player.play();

				document.body.appendChild( player.dom );

				if ( json.project.editable === true ) {

					var button = document.createElement( 'div' );
					button.id = 'edit';
					button.textContent = 'EDIT';
					button.addEventListener( 'click', function ( event ) {

						var url = location.href.split( '/' ).slice( 0, - 1 ).join( '/' );
						window.open( 'http://threejs.org/editor/#file=https://crossorigin.me/' + url + '/app.json' );

					}, false );
					document.body.appendChild( button );

				}

				window.addEventListener( 'resize', function () {
					player.setSize( window.innerWidth, window.innerHeight );
				} );

			} );

		</script>
	</body>
</html>


text:
<!DOCTYPE html>

    <title>AnotherTaskInProgress Enum Reference</title>
    <link rel="stylesheet" type="text/css" href="../../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../../css/highlight.css" />
    <meta charset='utf-8'>

GlobalMessageService Docs (100% documented)

        GlobalMessageService Reference

        AnotherTaskInProgress Enum Reference

            Classes

                GlobalMessageService

                GlobalMessageServiceCoreDataHelper

                GlobalMessageServiceInboxViewController

                GlobalMessageServiceMessageJSQ

                GlobalMessageServiceMessagesFetcher

            Enums

                GlobalMessageServiceError

                GlobalMessageServiceMessageType

            Functions

                ==(_:_:)

            Protocols

                CustomLocalizedDescriptionConvertible

                GlobalMessageServiceGoogleCloudMessagingHelper

                GlobalMessageServiceRemoteNotificationReciever

            Structs

                GlobalMessageServiceMessage

                GlobalMessageServicePushNotification

AnotherTaskInProgress

public enum AnotherTaskInProgress: ErrorType, CustomLocalizedDescriptionConvertible

Enum represents errors occured when you trying launch

AddSubscriber: Adding new subscriber

UpdateSubscriber: Updating subscriber’s info

UpdateGCMToken: Updating Google Cloud Messaging token

                    AddSubscriber

Adding new subscriber

Declaration

Swift

case AddSubscriber

                    UpdateSubscriber

Updating subscriber’s info

Declaration

Swift

case UpdateSubscriber

                    localizedDescription

A string containing the localized description of the object. (read-only)

Declaration

Swift

public var localizedDescription: String

© 2016 Global Message Services AG. All rights reserved. (Last updated: 2016-03-09)

Generated by jazzy ♪♫ v0.5.0, a Realm project.


text:
const message: string = "A mensagem a ser enviada precisa ter texto ou anexos.";

export class InvalidMessageError extends Error {
    constructor() {
        super(message);
        this.name = "InvalidMessageError";
        this.stack = (<any> new Error()).stack;
    }
}


text:
require_dependency "my_nagios/application_controller"

module MyNagios
  class ChecksController < ApplicationController
    before_filter :find_check,  only: [:run_now, :toggle, :edit, :update]
    before_filter :find_groups, only: [:new, :create, :edit]

    def new
      @check = Check.new
    end

    def create
      @check = Check.create(params_check)
      redirect_to root_path
    end

    def edit
    end

    def update
      @check.update(params_check)
      redirect_to root_path
    end

    def run_now
      @check.run!

      respond_to do |format|
        format.js { render layout: false }
      end
    end

    def toggle
      @check.toggle! :enabled

      respond_to do |format|
        format.js { render layout: false }
      end
    end

    def group_action
      check_ids = params["group_action_check_ids"].split(',')
      redirect_to root_path and return if check_ids.blank?

      case params['check_group_action'].downcase
      when 'disable'
        Check.where(id: check_ids).update_all(enabled: false)
      when 'enable'
        Check.where(id: check_ids).update_all(enabled: true)
      when 'snooze for'
        Check.where(id: check_ids).update_all(snooze_for: (Time.now + params['snooze_time_select'].to_i.minutes))
      end

      redirect_to root_path
    end

    private

    def find_check
      @check = Check.find(params[:id])
    end

    def find_groups
      @groups = MyNagios::Group.all
    end

    def params_check
      params.require(:check).permit(:host, :user, :pem_key, :description, :interval, :command, :additional_command, :regexp, :group_id)
    end
  end
end