text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using NuPattern.Modeling;
using DslModeling = global::Microsoft.VisualStudio.Modeling;

namespace NuPattern.Runtime.Store
{
    /// <summary>
    /// The persistence state for all current products in the solution.
    /// </summary>
    partial class ProductState
    {
        /// <summary>
        /// Key in the <see cref="PropertyBag"/> that flags
        /// whether the state is being deserialized.
        /// </summary>
        public const string IsSerializingKey = "IsSerializing";

        /// <summary>
        /// Key in the <see cref="PropertyBag"/> that flags
        /// whether an element is being created.
        /// </summary>
        public const string IsCreatingElementKey = "IsCreatingElement";

        /// <summary>
        /// Initializes a new instance of the <see cref="ProductState"/> class.
        /// </summary>
        /// <param name="store">Store where new element is to be created.</param>
        /// <param name="propertyAssignments">List of domain property id/value pairs to set once the element is created.</param>
        public ProductState(DslModeling::Store store, params DslModeling::PropertyAssignment[] propertyAssignments)
            : this(store != null ? store.DefaultPartitionForClass(DomainClassId) : null, propertyAssignments)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ProductState"/> class.
        /// </summary>
        /// <param name="partition">Partition where new element is to be created.</param>
        /// <param name="propertyAssignments">List of domain property id/value pairs to set once the element is created.</param>
        public ProductState(DslModeling::Partition partition, params DslModeling::PropertyAssignment[] propertyAssignments)
            : base(partition, propertyAssignments)
        {
            this.Store.EventManagerDirectory.TransactionCommitted.Add(new EventHandler<DslModeling.TransactionCommitEventArgs>(this.OnTransactionCommited));

            this.Store.EventManagerDirectory.ElementEventsBegun.Add(new EventHandler<DslModeling.ElementEventsBegunEventArgs>(this.OnElementEventsBegun));
            this.Store.EventManagerDirectory.ElementEventsEnded.Add(new EventHandler<DslModeling.ElementEventsEndedEventArgs>(this.OnElementEventsEnded));

            this.Store.EventManagerDirectory.ElementDeleted.Add(new EventHandler<DslModeling.ElementDeletedEventArgs>(this.OnElementDeleted));
            this.Store.EventManagerDirectory.ElementAdded.Add(new EventHandler<DslModeling.ElementAddedEventArgs>(this.OnElementAdded));
            this.Store.EventManagerDirectory.ElementPropertyChanged.Add(new EventHandler<DslModeling.ElementPropertyChangedEventArgs>(this.OnElementPropertyChanged));
        }

        /// <summary>
        /// Event raised whenever a dynamic element was deleted at runtime.
        /// </summary>
        public event EventHandler<ValueEventArgs<IInstanceBase>> ElementDeleted = (s, e) => { };

        /// <summary>
        /// Event raised whenever a dynamic element is being deleted at runtime.
        /// </summary>
        public event EventHandler<ValueEventArgs<IInstanceBase>> ElementDeleting = (s, e) => { };

        /// <summary>
        /// Event raised whenever a dynamic element is instantiated at runtime, except on serialization.
        /// </summary>
        public event EventHandler<ValueEventArgs<IInstanceBase>> ElementInstantiated = (s, e) => { };

        /// <summary>
        /// Event raised whenever a dynamic element is instantiated at runtime.
        /// </summary>
        public event EventHandler<ValueEventArgs<IInstanceBase>> ElementCreated = (s, e) => { };

        /// <summary>
        /// Event raised whenever a dynamic element is serialized at runtime.
        /// </summary>
        public event EventHandler<ValueEventArgs<IInstanceBase>> ElementLoaded = (s, e) => { };

        /// <summary>
        /// Event raised whenever a dynamic element property is changed, where the sender is the changed element.
        /// </summary>
        public event EventHandler<PropertyChangedEventArgs> ElementPropertyChanged = (s, e) => { };

        /// <summary>
        /// Event raised whenever the state is saved to the file system.
        /// </summary>
        public event EventHandler Saved = (s, e) => { };

        /// <summary>
        /// Event raised whenever a top-level transaction is commited to the state.
        /// </summary>
        public event EventHandler TransactionCommited = (s, e) => { };

        // A transaction that we initiate on element events begin so that
        // all events always run within a single parent transaction.
        private Stack<ITransaction> eventsTransactions = new Stack<ITransaction>();

        /// <summary>
        /// Gets instances of a given type.
        /// </summary>
        /// <typeparam name="T">The Given Type.</typeparam>
        public IEnumerable<T> FindAll<T>() where T : IInstanceBase
        {
            return this.Store.ElementDirectory.AllElements.OfType<T>();
        }

        /// <summary>
        /// Validates this instance.
        /// </summary>
        public void Validate()
        {
            var patternManager = this.Store.GetService<IPatternManager>();

            patternManager.ValidateProductState(this);
        }

        /// <summary>
        /// Returns whether the state containing this instance is currently
        /// in a transaction or not.
        /// </summary>
        public bool InTransaction
        {
            get { return this.Store.TransactionActive; }
        }

        /// <summary>
        /// Returns whether the state is currently being serialized or not.
        /// </summary>
        public bool IsSerializing
        {
            get
            {
                object isSerializing;

                return this.Store.PropertyBag.TryGetValue(IsSerializingKey, out isSerializing) && (bool)isSerializing;
            }
        }

        /// <summary>
        /// Begins the transaction.
        /// </summary>
        public ITransaction BeginTransaction()
        {
            return new ModelingTransaction(this.Store.TransactionManager.BeginTransaction());
        }

        /// <summary>
        /// Begins the transaction.
        /// </summary>
        public ITransaction BeginTransaction(string name)
        {
            return new ModelingTransaction(this.Store.TransactionManager.BeginTransaction(name));
        }

        /// <summary>
        /// Gets the service.
        /// </summary>
        /// <param name="serviceType">Type of the service.</param>
        public object GetService(Type serviceType)
        {
            Guard.NotNull(() => serviceType, serviceType);

            return this.Store.GetService(serviceType);
        }

        /// <summary>
        /// Deletes a single pattern from the state.
        /// </summary>
        public void Delete(IProduct product)
        {
            this.WithTransaction(s => s.Products.Remove((Product)product));
        }

        /// <summary>
        /// Gets the property bag.
        /// </summary>
        public Dictionary<object, object> PropertyBag
        {
            get { return this.Store.PropertyBag; }
        }

        internal void RaiseSaved()
        {
            this.Saved(this, EventArgs.Empty);
        }

        private void OnElementEventsBegun(object sender, DslModeling.ElementEventsBegunEventArgs e)
        {
            this.eventsTransactions.Push(this.BeginTransaction());
        }

        private void OnElementEventsEnded(object sender, DslModeling.ElementEventsEndedEventArgs e)
        {
            if (this.eventsTransactions.Count > 0)
            {
                // A second round of events from this commit
                // should still be wrapped in another transaction
                // until we are completely done.
                var transaction = this.eventsTransactions.Pop();
                transaction.Commit();
                transaction.Dispose();
            }
        }

        internal void OnElementDeleting(object sender, DslModeling.ElementDeletingEventArgs e)
        {
            var element = e.ModelElement as IInstanceBase;
            if (element != null && !this.IsSerializing)
            {
                StoreEventBufferingScope.RaiseOrBufferEvent(() =>
                {
                    var eventArgs = ValueEventArgs.Create(element);
                    this.ElementDeleting(this, eventArgs);
                });
            }
        }

        private void OnTransactionCommited(object sender, DslModeling.TransactionCommitEventArgs e)
        {
            if (!this.IsSerializing && !e.Transaction.IsNested && !e.Transaction.IsSerializing)
            {
                StoreEventBufferingScope.RaiseOrBufferEvent(() =>
                {
                    this.TransactionCommited(this, e);
                });
            }
        }

        private void OnElementDeleted(object sender, DslModeling.ElementDeletedEventArgs e)
        {
            var element = e.ModelElement as IInstanceBase;
            if (element != null && !this.IsSerializing)
            {
                StoreEventBufferingScope.RaiseOrBufferEvent(() =>
                {
                    var eventArgs = ValueEventArgs.Create(element);
                    this.ElementDeleted(this, eventArgs);
                });
            }
        }

        private void OnElementAdded(object sender, DslModeling.ElementAddedEventArgs e)
        {
            var element = e.ModelElement as IInstanceBase;
            if (element != null)
            {
                // ElementCreated is raised always, regardless of how the element was created.
                StoreEventBufferingScope.RaiseOrBufferEvent(() =>
                {
                    var eventArgs = ValueEventArgs.Create(element);
                    this.ElementCreated(this, eventArgs);
                });

                if (!this.IsSerializing)
                {
                    // We only invoke this event if the element has not been marked in the state.
                    // it wants instantiation events (the default is true, see StoreEventBufferingScope ctor).
                    if (ShouldRaiseInstantiate(e.ModelElement))
                    {
                        StoreEventBufferingScope.RaiseOrBufferEvent(() =>
                        {
                            var eventArgs = ValueEventArgs.Create(element);
                            this.ElementInstantiated(this, eventArgs);
                        });
                    }
                }
                else
                {
                    // We're deserializing the element, so we raise the Loaded event.
                    StoreEventBufferingScope.RaiseOrBufferEvent(() =>
                    {
                        var eventArgs = ValueEventArgs.Create(element);
                        this.ElementLoaded(this, eventArgs);
                    });
                }
            }
        }

        /// <summary>
        /// Raises the <see cref="ElementPropertyChanged"/> event as long as the state has not been flagged as
        /// being deserialized.
        /// </summary>
        private void OnElementPropertyChanged(object sender, DslModeling.ElementPropertyChangedEventArgs args)
        {
            // For element-specific automation, this is not used. This is only for automation
            // that wants to listen to changes on everything.

            // Note that we don't raise the property changed events if the element is either being deserialized
            // of if it's marked as a creation of the element by the calling code (i.e. ElementContainerImplementation on all its Create
            // overloads).
            if (!this.IsSerializing && !this.IsCreatingElement())
            {
                StoreEventBufferingScope.RaiseOrDropEvent(() =>
                {
                    this.ElementPropertyChanged(args.ModelElement, new PropertyChangedEventArgs(args.DomainProperty.Name));

                    var property = args.ModelElement as Property;
                    if (property != null && property.Info != null)
                    {
                        // For our variable properties, we also raise the "logical" property
                        // changed event on the element for its variable property name.
                        this.ElementPropertyChanged(property.Owner, new PropertyChangedEventArgs(property.Info.Name));
                    }
                });
            }
        }

        private bool IsCreatingElement()
        {
            object isCreating;

            return this.Store.PropertyBag.TryGetValue(IsCreatingElementKey, out isCreating) && (bool)isCreating;
        }

        private bool ShouldRaiseInstantiate(DslModeling.ModelElement element)
        {
            return !this.Store.PropertyBag.ContainsKey(element);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'rails_helper'

def build_query_test_once(params, expected, opts = nil)
  qb = Solr::QueryBuilder.new(params)
  qb.build
  qb.query[:q].should eq(expected)
  qb.query[opts.keys[0]].should eq(opts.values[0]) if opts
end

def build_page_block_test_once(params, expected)
  qb = Solr::QueryBuilder.new(params)
  qb.send(:page_block).should eq(expected)
end

describe Solr::QueryBuilder do
  it "can build simple queries" do
    build_query_test_once({ everything: "everyFoo" }, "everything:everyFoo")

    build_query_test_once(
      { everything: "foo bar blaz" },
      'everything:"foo bar blaz"'
    )

    build_query_test_once(
      { everything: "everyTitle", title: "titleFoo" },
      "everything:everyTitle AND title:titleFoo"
    )

    build_query_test_once(
      { author: "Joe Bob", subject: "Virology" },
      'author:"Joe Bob" AND subject:Virology'
    )
  end

  it "knows how to deal with empty fields" do
    # Empty fields should not be added.
    build_query_test_once(
      { everything: "ignoreRest", author: "", subject: "  " },
      "everything:ignoreRest"
    )
  end

  it "can handle institution and author_country both mapping to affiliate" do
    # Hack where the "pseudo-fields" author_country and institution both map to
    # the actual solr field affiliate.
    build_query_test_once(
      { author_country: "authorCountry" },
      "affiliate:authorCountry"
    )

    build_query_test_once(
      { everything: "everythingInst", institution: "foo institution" },
      'affiliate:"foo institution" AND everything:everythingInst'
    )

    build_query_test_once(
      { author_country: "france", institution: "university of lyon" },
      'affiliate:(france AND "university of lyon")'
    )

    build_query_test_once(
      {
        everything: "some keywords", author_country: "USA",
        institution: "stanford u", subject: "ebola virus"
      },
      'affiliate:(USA AND "stanford u") AND everything:"some keywords" AND ' \
      'subject:"ebola virus"'
    )
  end

  it "removes All Journals from list of journals" do
    # cross_published_journal_name should be ignored if it equals "All Journals"
    build_query_test_once(
      { everything: "fooCross", filters: ["PLoSONE"] },
      'everything:fooCross',
      {fq: "cross_published_journal_key:PLoSONE"}
    )

    build_query_test_once(
      {
        everything: "fooNoJournal",
        filters: ["All Journals"]
      },
      "everything:fooNoJournal"
    )
  end

  it "can build a simple page block" do
    build_page_block_test_once({}, "rows=25")
    # Page 1 is the default
    build_page_block_test_once({ current_page: "1" }, "rows=25")
    build_page_block_test_once({ current_page: "2" }, "rows=25&start=25")
    build_page_block_test_once({ current_page: "3" }, "rows=25&start=50")
    build_page_block_test_once({ current_page: "4" }, "rows=25&start=75")
  end

  it "rows params override default paging" do
    build_page_block_test_once({ rows: 500 }, "rows=500")
  end

  it "doesn't have interactions between build_page_block and build" do
    params = { everything: "hi", title: "bye" }
    qb = Solr::QueryBuilder.new(params)
    qb.send(:page_block).should eq("rows=25")
    qb.build
    qb.query[:q].should eq("everything:hi AND title:bye")

    params = { everything: "bad", title: "business", current_page: 2, rows: 475 }
    qb = Solr::QueryBuilder.new(params)
    qb.send(:page_block).should eq("rows=475&start=475")
    qb.build
    qb.query[:q].should eq("everything:bad AND title:business")
  end

  it "generates the correct URL for a query" do
    qb = Solr::QueryBuilder.new(everything: "everyTitle", title: "titleFoo")
    qb.build
    url = "http://api.plos.org/search?q=everything%3AeveryTitle+AND+title%3A" \
      "titleFoo&fq=doc_type:full&fq=!article_type_facet:%22Issue%20Image%22&" \
      "fl=id,pmid,publication_date,received_date,accepted_date,title,cross_" \
      "published_journal_name,author_display,editor_display,article_type,affi" \
      "liate,subject,financial_disclosure&wt=json&rows=25&hl=false&" \
      "facet=true&facet.field=journal&facet.field=article_type&facet.field=" \
      "publication_date&facet.date=publication_date&facet.date.start=" \
      "2000-01-01T00:00:00Z&facet.date.end=NOW&facet.date.gap=%2B1YEAR"
    qb.url.should eq(url)
  end

  it "doesn't raise an exception if a param is nil" do
    build_query_test_once(
      {everything: nil, title: "testing"},
      "title:testing"
    )
  end

  it "ignores all sorts that are not whitelisted" do
    sort = "sum(malformed,"
    qb = Solr::QueryBuilder.new(everything: "testing", sort: sort)
    qb.build
    qb.send(:sort).should eq(nil)
  end

  it "takes whitelisted sorts into account" do
    sort = "publication_date desc"
    qb = Solr::QueryBuilder.new(everything: "testing", sort: sort)
    qb.build
    qb.send(:sort).should eq("&sort=publication_date%20desc")
  end

  it "accepts HashWithIndifferentAccess as a parameter" do
    params = ActiveSupport::HashWithIndifferentAccess.new(
      "everything" => "testing"
    )
    qb = Solr::QueryBuilder.new(params)
    qb.build
    qb.query[:q].should eq("everything:testing")
  end

  it "doesn't ignore publication_date parameter (regression test for issue #50)" do
    params = {
      everything: "cancer",
      author: "",
      author_country: "",
      institution: "",
      subject: "",
      filters: ["All Journals"],
      financial_disclosure: "",
      publication_date: "[2014-09-03T14:01:32Z TO 2014-10-03T14:01:32Z]"
    }
    qb = Solr::QueryBuilder.new(params)
    qb.build
    qb.query[:q].should eq(
      "everything:cancer AND publication_date:[2014-09-03T14:01:32Z TO " \
      "2014-10-03T14:01:32Z]"
    )
  end

  it "parses date range '' (all time)" do
    params = {
      publication_days_ago: ""
    }
    qb = Solr::QueryBuilder.new(params)
    qb.build

    assert_nil(qb.start_time)
    assert_nil(qb.end_time)
    assert_nil(qb.params[:publication_date])
  end

  it "parses a specific date range and build the correct string" do
    params = {
      publication_days_ago: "0",
      datepicker1: "09-15-2012",
      datepicker2: "02-28-2013"
    }

    qb = Solr::QueryBuilder.new(params)
    qb.build

    assert_equal("[2012-09-15T00:00:00Z TO 2013-02-28T23:59:59Z]",
        qb.params[:publication_date])
  end

  it "publication_days_ago" do
    Timecop.travel(Date.strptime("2013-03-01", "%Y-%m-%d").to_time)
    params = {
      publication_days_ago: "30"
    }

    qb = Solr::QueryBuilder.new(params)
    qb.build

    assert_equal("[2013-01-30T00:00:00Z TO 2013-03-01T00:00:00Z]",
        qb.params[:publication_date])

    Timecop.return

    # TODO: test end day before start day and other error cases.
  end

  it "adjusts the rows for multiple ids" do
    params = { ids: 103.times.map{ |i| i} }

    qb = Solr::QueryBuilder.new(params)
    qb.build
    expect(qb.url).to include("rows=206")
  end

  it "will allow supplied rows parameter to override" do
    params = { everything: "biology", rows: 200 }

    qb = Solr::QueryBuilder.new(params)
    qb.build

    expect(qb.url).to include("rows=200")
  end
end


text:
require "spec_helper"

def expect_window_with_content(content, window: windows.last)
  page.within_window window do
    expect(page).to have_content(content)
  end
end

def expect_window_without_content(content, window: windows.last)
  page.within_window window do
    expect(page).not_to have_content(content)
  end
end

module Refinery
  module Admin
    describe "Pages", :type => :feature do
      refinery_login_with :refinery_user

      context "when no pages" do
        it "invites to create one" do
          visit refinery.admin_pages_path
          expect(page).to have_content(%q{There are no pages yet. Click "Add new page" to add your first page.})
        end
      end

      describe "action links" do
        it "shows add new page link" do
          visit refinery.admin_pages_path

          within "#actions" do
            expect(page).to have_content("Add new page")
            expect(page).to have_selector("a[href='/#{Refinery::Core.backend_route}/pages/new']")
          end
        end

        context "when no pages" do
          it "doesn't show reorder pages link" do
            visit refinery.admin_pages_path

            within "#actions" do
              expect(page).to have_no_content("Reorder pages")
              expect(page).to have_no_selector("a[href='/#{Refinery::Core.backend_route}/pages']")
            end
          end
        end

        context "when some pages exist" do
          before { 2.times { |i| Page.create :title => "Page #{i}" } }

          it "shows reorder pages link" do
            visit refinery.admin_pages_path

            within "#actions" do
              expect(page).to have_content("Reorder pages")
              expect(page).to have_selector("a[href='/#{Refinery::Core.backend_route}/pages']")
            end
          end
        end

        context "when sub pages exist" do
          let!(:company) { Page.create :title => 'Our Company' }
          let!(:team) { company.children.create :title => 'Our Team' }
          let!(:locations) { company.children.create :title => 'Our Locations' }
          let!(:location) { locations.children.create :title => 'New York' }

          context "with auto expand option turned off" do
            before do
              allow(Refinery::Pages).to receive(:auto_expand_admin_tree).and_return(false)

              visit refinery.admin_pages_path
            end

            it "show parent page" do

              expect(page).to have_content(company.title)
            end

            it "doesn't show children" do
              expect(page).not_to have_content(team.title)
              expect(page).not_to have_content(locations.title)
            end

            it "expands children", :js do
              find("#page_#{company.id} .title.toggle").click

              expect(page).to have_content(team.title)
              expect(page).to have_content(locations.title)
            end

            it "expands children when nested multiple levels deep", :js do
              find("#page_#{company.id} .title.toggle").click
              find("#page_#{locations.id} .title.toggle").click

              expect(page).to have_content("New York")
            end
          end

          context "with auto expand option turned on" do
            before do
              allow(Refinery::Pages).to receive(:auto_expand_admin_tree).and_return(true)

              visit refinery.admin_pages_path
            end

            it "shows children" do
              expect(page).to have_content(team.title)
              expect(page).to have_content(locations.title)
            end
          end
        end
      end

      describe "new/create" do
        it "allows to create page" do
          visit refinery.admin_pages_path

          click_link "Add new page"

          fill_in "Title", :with => "My first page"
          expect { click_button "Save" }.to change(Refinery::Page, :count).from(0).to(1)

          expect(page).to have_content("'My first page' was successfully added.")

          expect(page.body).to match(/Remove this page forever/)
          expect(page.body).to match(/Edit this page/)
          expect(page.body).to match(%r{/#{Refinery::Core.backend_route}/pages/my-first-page/edit})
          expect(page.body).to match(/Add a new child page/)
          expect(page.body).to match(%r{/#{Refinery::Core.backend_route}/pages/new\?parent_id=})
          expect(page.body).to match(/View this page live/)
          expect(page.body).to match(%r{href="/my-first-page"})
        end

        it "includes menu title field", :js => true do
          visit refinery.new_admin_page_path

          fill_in "Title", :with => "My first page"

          click_link "toggle_advanced_options"

          fill_in "Menu title", :with => "The first page"

          expect { click_button "Save" }.to change(Refinery::Page, :count).from(0).to(1)

          expect(page).to have_content("'My first page' was successfully added.")
          expect(page.body).to match(%r{/pages/the-first-page})
        end

        it "allows to easily create nested page" do
          parent_page = Page.create! :title => "Rails 4"

          visit refinery.admin_pages_path

          find("a[href='#{refinery.new_admin_page_path(:parent_id => parent_page.id)}']").click

          fill_in "Title", :with => "Parent page"
          click_button "Save"

          expect(page).to have_content("'Parent page' was successfully added.")
        end
      end

      describe "edit/update" do
        before do
          Page.create :title => "Update me"

          visit refinery.admin_pages_path
          expect(page).to have_content("Update me")
        end

        context 'when saving and returning to index' do
          it "updates page" do
            click_link "Edit this page"

            fill_in "Title", :with => "Updated"
            find("#submit_button").click

            expect(page).to have_content("'Updated' was successfully updated.")
          end
        end

        context 'when saving and continuing to edit' do
          before :each do
            find('a[tooltip^=Edit]').visible?
            find('a[tooltip^=Edit]').click

            fill_in "Title", :with => "Updated"
            find("#submit_continue_button").click
            find('#flash').visible?
          end

          it "updates page", :js do
            expect(page).to have_content("'Updated' was successfully updated.")
          end

          # Regression test for https://github.com/refinery/refinerycms/issues/1892
          context 'when saving to exit (a second time)' do
            it 'updates page', :js do
              find("#submit_button").click
              expect(page).to have_content("'Updated' was successfully updated.")
            end
          end
        end
      end

      describe 'Previewing', :js do
        let(:preview_content) { "Some changes I'm unsure what they will look like".freeze }
        context "an existing page" do
          before { Page.create :title => 'Preview me' }

          it 'will show the preview changes in a new window' do
            visit refinery.admin_pages_path

            find('a[tooltip^=Edit]').click
            fill_in "Title", with: preview_content
            window = window_opened_by do
              click_button "Preview"
            end

            expect_window_with_content(preview_content, window: window)

            window.close
          end

          it 'will not show the site bar' do
            visit refinery.admin_pages_path

            find('a[tooltip^=Edit]').click
            fill_in "Title", with: preview_content
            window = window_opened_by do
              click_button "Preview"
            end

            expect_window_without_content(
              ::I18n.t('switch_to_website', scope: 'refinery.site_bar'),
              window: window
            )
            expect_window_without_content(
              ::I18n.t('switch_to_website_editor', scope: 'refinery.site_bar'),
              window: window
            )

            window.close
          end

          it 'will not save the preview changes' do
            visit refinery.admin_pages_path

            find('a[tooltip^=Edit]').click
            fill_in "Title", with: preview_content
            window = window_opened_by do
              click_button "Preview"
            end

            expect_window_with_content(
              preview_content,
              window: window
            )

            window.close

            expect(Page.by_title(preview_content)).to be_empty
          end

          # Regression test for previewing after save-and_continue
          it 'will show the preview in a new window after save-and-continue' do
            visit refinery.admin_pages_path

            find('a[tooltip^=Edit]').click
            fill_in "Title", :with => "Save this"
            click_button "Save & continue editing"
            expect(page).to have_content("'Save this' was successfully updated")

            window = window_opened_by do
              click_button "Preview"
            end

            expect_window_with_content("Save this", window: window)
            expect_window_without_content(
              ::I18n.t('switch_to_website', :scope => 'refinery.site_bar'),
              window: window
            )

            window.close
          end

          it 'will show pages with inherited templates' do
            visit refinery.admin_pages_path

            find('a[tooltip^=Edit]').click
            fill_in 'Title', :with => 'Searchable'
            click_link 'Advanced options'
            select 'Searchable', :from => 'View template'
            click_button 'Preview'

            expect_window_with_content('Form application/search_form')
          end
        end

        context 'a brand new page' do
          it "will not save when just previewing" do
            visit refinery.admin_pages_path

            click_link "Add new page"
            fill_in "Title", :with => "My first page"
            window = window_opened_by do
              click_button "Preview"
            end

            expect_window_with_content("My first page", window: window)

            expect(Page.count).to eq(0)
            window.close
          end
        end

        context 'a nested page' do
          let!(:parent_page) { Page.create :title => "Our Parent Page" }
          let!(:nested_page) { parent_page.children.create :title => 'Preview Me' }

          it "works like an un-nested page" do
            visit refinery.admin_pages_path

            within "#page_#{nested_page.id}" do
              find('a[tooltip^=Edit]').click
            end

            fill_in "Title", with: preview_content
            window = window_opened_by do
              click_button "Preview"
            end

            expect_window_with_content(preview_content)
          end
        end
      end

      describe "destroy" do
        context "when page can be deleted" do
          before { Page.create :title => "Delete me" }

          it "will show delete button" do
            visit refinery.admin_pages_path

            click_link "Remove this page forever"

            expect(page).to have_content("'Delete me' was successfully removed.")

            expect(Refinery::Page.count).to eq(0)
          end
        end

        context "when page can't be deleted" do
          before { Page.create :title => "Indestructible", :deletable => false }

          it "wont show delete button" do
            visit refinery.admin_pages_path

            expect(page).to have_no_content("Remove this page forever")
            expect(page).to have_no_selector("a[href='/#{Refinery::Core.backend_route}/pages/indestructible']")
          end
        end
      end

      context "duplicate page titles" do
        before { Page.create :title => "I was here first" }

        it "will append nr to url path" do
          visit refinery.new_admin_page_path

          fill_in "Title", :with => "I was here first"
          click_button "Save"

          expect(Refinery::Page.last.url[:path].first).to match(%r{\Ai-was-here-first-.+?})
        end
      end

      context "with translations" do
        before do
          allow(Refinery::I18n).to receive(:frontend_locales).and_return([:en, :ru])

          # Create a home page in both locales (needed to test menus)
          home_page = Globalize.with_locale(:en) do
            Page.create :title => 'Home',
                        :link_url => '/',
                        :menu_match => "^/$"
          end

          Globalize.with_locale(:ru) do
            home_page.title = 'Домашняя страница'
            home_page.save
          end
        end

        describe "add a page with title for default locale" do
          before do
            visit refinery.admin_pages_path
            click_link "Add new page"
            fill_in "Title", :with => "News"
            click_button "Save"
          end

          it "succeeds" do
            expect(page).to have_content("'News' was successfully added.")
            expect(Refinery::Page.count).to eq(2)
          end

          it "shows locale flag for page" do
            p = ::Refinery::Page.by_slug('news').first
            within "#page_#{p.id}" do
              expect(page).to have_css(".locale_icon.en")
            end
          end

          it "shows title in the admin menu" do
            p = ::Refinery::Page.by_slug('news').first
            within "#page_#{p.id}" do
              expect(page).to have_content('News')
              expect(page.find_link('Edit this page')[:href]).to include('news')
            end
          end

          it "shows in frontend menu for 'en' locale" do
            visit "/"

            within "#menu" do
              expect(page).to have_content('News')
              expect(page).to have_selector("a[href='/news']")
            end
          end

          it "doesn't show in frontend menu for 'ru' locale" do
            visit "/ru"

            within "#menu" do
              # we should only have the home page in the menu
              expect(page).to have_css('li', :count => 1)
            end
          end
        end

        describe "add a page with title for both locales" do
          let(:en_page_title) { 'News' }
          let(:en_page_slug) { 'news' }
          let(:ru_page_title) { 'Новости' }
          let(:ru_page_slug_encoded) { '%D0%BD%D0%BE%D0%B2%D0%BE%D1%81%D1%82%D0%B8' }
          let!(:news_page) do
            allow(Refinery::I18n).to receive(:frontend_locales).and_return([:en, :ru])

            _page = Globalize.with_locale(:en) {
              Page.create :title => en_page_title
            }
            Globalize.with_locale(:ru) do
              _page.title = ru_page_title
              _page.save
            end

            _page
          end

          it "succeeds" do
            news_page.destroy!
            visit refinery.admin_pages_path

            click_link "Add new page"
            within "#switch_locale_picker" do
              click_link "ru"
            end
            fill_in "Title", :with => ru_page_title
            click_button "Save"

            within "#page_#{Page.last.id} .actions" do
              find("a[href^='/#{Refinery::Core.backend_route}/pages/#{ru_page_slug_encoded}/edit']").click
            end
            within "#switch_locale_picker" do
              click_link "en"
            end
            fill_in "Title", :with => en_page_title
            find("#submit_button").click

            expect(page).to have_content("'#{en_page_title}' was successfully updated.")
            expect(Refinery::Page.count).to eq(2)
          end

          it "shows both locale flags for page" do
            visit refinery.admin_pages_path

            within "#page_#{news_page.id}" do
              expect(page).to have_css(".locale_icon.en")
              expect(page).to have_css(".locale_icon.ru")
            end
          end

          it "shows title in admin menu in current admin locale" do
            visit refinery.admin_pages_path

            within "#page_#{news_page.id}" do
              expect(page).to have_content(en_page_title)
            end
          end

          it "uses the slug from the default locale in admin" do
            visit refinery.admin_pages_path

            within "#page_#{news_page.id}" do
              expect(page.find_link('Edit this page')[:href]).to include(en_page_slug)
            end
          end

          it "shows correct language and slugs for default locale" do
            visit "/"

            within "#menu" do
              expect(page.find_link(news_page.title)[:href]).to include(en_page_slug)
            end
          end

          it "shows correct language and slugs for second locale" do
            visit "/ru"

            within "#menu" do
              expect(page.find_link(ru_page_title)[:href]).to include(ru_page_slug_encoded)
            end
          end
        end

        describe "add a page with title only for secondary locale" do
          let(:ru_page) {
            Globalize.with_locale(:ru) {
              Page.create :title => ru_page_title
            }
          }
          let(:ru_page_id) { ru_page.id }
          let(:ru_page_title) { 'Новости' }
          let(:ru_page_slug_encoded) { '%D0%BD%D0%BE%D0%B2%D0%BE%D1%81%D1%82%D0%B8' }

          before do
            ru_page
            visit refinery.admin_pages_path
          end

          it "succeeds" do
            ru_page.destroy!
            click_link "Add new page"
            within "#switch_locale_picker" do
              click_link "ru"
            end
            fill_in "Title", :with => ru_page_title
            click_button "Save"

            expect(page).to have_content("'#{ru_page_title}' was successfully added.")
            expect(Refinery::Page.count).to eq(2)
          end

          it "shows locale flag for page" do
            within "#page_#{ru_page_id}" do
              expect(page).to have_css(".locale_icon.ru")
            end
          end

          it "doesn't show locale flag for primary locale" do
            within "#page_#{ru_page_id}" do
              expect(page).not_to have_css("img[src='/assets/refinery/icons/flags/en.png']")
            end
          end

          it "shows title in the admin menu" do
            within "#page_#{ru_page_id}" do
              expect(page).to have_content(ru_page_title)
            end
          end

          it "uses slug in admin" do
            within "#page_#{ru_page_id}" do
              expect(page.find_link('Edit this page')[:href]).to include(ru_page_slug_encoded)
            end
          end

          it "shows in frontend menu for 'ru' locale" do
            visit "/ru"

            within "#menu" do
              expect(page).to have_content(ru_page_title)
              expect(page).to have_selector("a[href*='/#{ru_page_slug_encoded}']")
            end
          end

          it "won't show in frontend menu for 'en' locale" do
            visit "/"

            within "#menu" do
              # we should only have the home page in the menu
              expect(page).to have_css('li', :count => 1)
            end
          end

          context "when page is a child page" do
            it 'succeeds' do
              ru_page.destroy!
              parent_page = Page.create(:title => "Parent page")
              sub_page = Globalize.with_locale(:ru) {
                Page.create :title => ru_page_title
                Page.create :title => ru_page_title, :parent_id => parent_page.id
              }
              expect(sub_page.parent).to eq(parent_page)
              visit refinery.admin_pages_path
              within "#page_#{sub_page.id}" do
                click_link "Application edit"
              end
              fill_in "Title", :with => ru_page_title
              click_button "Save"
              expect(page).to have_content("'#{ru_page_title}' was successfully updated")
            end
          end
        end
      end

      describe "new page part", :js do
        before do
          allow(Refinery::Pages).to receive(:new_page_parts).and_return(true)
        end

        it "adds new page part" do
          visit refinery.new_admin_page_path
          click_link "add_page_part"

          within "#new_page_part_dialog" do
            fill_in "new_page_part_title", :with => "testy"
            click_button "Save"
          end

          within "#page_parts" do
            expect(page).to have_content("testy")
          end
        end
      end

      describe "delete existing page part", :js do
        let!(:some_page) { Page.create! :title => "Some Page" }

        before do
          some_page.parts.create! :title => "First Part", :position => 1
          some_page.parts.create! :title => "Second Part", :position => 2
          some_page.parts.create! :title => "Third Part", :position => 3

          allow(Refinery::Pages).to receive(:new_page_parts).and_return(true)
        end

        it "deletes page parts" do
          visit refinery.edit_admin_page_path(some_page.id)

          within "#page_parts" do
            expect(page).to have_content("First Part")
            expect(page).to have_content("Second Part")
            expect(page).to have_content("Third Part")
          end

          2.times do
            click_link "delete_page_part"
            # Poltergeist automatically accepts dialogues.
            if Capybara.javascript_driver != :poltergeist
              page.driver.browser.switch_to.alert.accept
            end
          end

          within "#page_parts" do
            expect(page).to have_no_content("First Part")
            expect(page).to have_no_content("Second Part")
            expect(page).to have_content("Third Part")
          end

          click_button "submit_button"

          visit refinery.edit_admin_page_path(some_page.id)

          within "#page_parts" do
            expect(page).to have_no_content("First Part")
            expect(page).to have_no_content("Second Part")
            expect(page).to have_content("Third Part")
          end
        end
      end

      describe 'advanced options' do
        describe 'view and layout templates' do
          context 'when parent page has templates set' do
            before do
              allow(Refinery::Pages).to receive(:use_layout_templates).and_return(true)
              allow(Refinery::Pages).to receive(:layout_template_whitelist).and_return(['abc', 'refinery'])
              allow(Refinery::Pages).to receive(:valid_templates).and_return(['abc', 'refinery'])
              parent_page = Page.create :title => 'Parent Page',
                                        :view_template => 'refinery',
                                        :layout_template => 'refinery'
              @page = parent_page.children.create :title => 'Child Page'
            end

            specify 'sub page should inherit them', :js => true do
              visit refinery.edit_admin_page_path(@page.id)

              click_link 'toggle_advanced_options'

              within '#page_layout_template' do
                expect(page.find('option[value=refinery]')).to be_selected
              end

              within '#page_view_template' do
                expect(page.find('option[value=refinery]')).to be_selected
              end
            end
          end
        end
      end

      # regression spec for https://github.com/refinery/refinerycms/issues/1891
      describe "page part body" do
        before do
          page = Refinery::Page.create! :title => "test"
          Refinery::Pages.default_parts.each_with_index do |default_page_part, index|
            page.parts.create(:title => default_page_part,
                              :body => "<header class='regression'>test</header>",
                              :position => index)
          end
        end

        specify "html shouldn't be stripped" do
          visit refinery.admin_pages_path
          click_link "Edit this page"
          expect(page).to have_content("header class='regression'")
        end
      end
    end

    describe "TranslatePages", :type => :feature do
      before { Globalize.locale = :en }
      refinery_login_with :refinery_user

      describe "add page to second locale" do
        before do
          allow(Refinery::I18n).to receive(:frontend_locales).and_return([:en, :lv])
          Page.create :title => 'First Page'
        end

        it "succeeds" do
          visit refinery.admin_pages_path

          click_link "Add new page"

          within "#switch_locale_picker" do
            click_link "lv"
          end
          fill_in "Title", :with => "Brīva vieta reklāmai"
          click_button "Save"

          expect(page).to have_content("'Brīva vieta reklāmai' was successfully added.")
          expect(Refinery::Page.count).to eq(2)
        end
      end

      describe "Pages Link-to Dialog" do
        before do
          allow(Refinery::I18n).to receive(:frontend_locales).and_return [:en, :ru]

          # Create a page in both locales
          about_page = Globalize.with_locale(:en) do
            Page.create :title => 'About'
          end

          Globalize.with_locale(:ru) do
            about_page.title = 'About Ru'
            about_page.save
          end
        end

        let(:about_page) do
          page = Refinery::Page.last
          # we need page parts so that there's a visual editor
          Refinery::Pages.default_parts.each_with_index do |default_page_part, index|
            page.parts.create(:title => default_page_part, :body => nil, :position => index)
          end
          page
        end

        describe "adding page link" do
          describe "with relative urls" do
            before { Refinery::Pages.absolute_page_links = false }

            it "shows Russian pages if we're editing the Russian locale" do
              visit refinery.link_to_admin_pages_dialogs_path(:visual_editor => true, :switch_locale => :ru)

              expect(page).to have_content("About Ru")
              expect(page).to have_selector("a[href='/ru/about-ru']")
            end

            it "shows default to the default locale if no query string is added" do
              visit refinery.link_to_admin_pages_dialogs_path(:visual_editor => true)

              expect(page).to have_content("About")
              expect(page).to have_selector("a[href='/about']")
            end
          end

          describe "with absolute urls" do
            before { Refinery::Pages.absolute_page_links = true }

            it "shows Russian pages if we're editing the Russian locale" do
              visit refinery.link_to_admin_pages_dialogs_path(:visual_editor => true, :switch_locale => :ru)

              expect(page).to have_content("About Ru")
              expect(page).to have_selector("a[href='http://www.example.com/ru/about-ru']")
            end

            it "shows default to the default locale if no query string is added" do
              visit refinery.link_to_admin_pages_dialogs_path(:visual_editor => true)

              expect(page).to have_content("About")
              expect(page).to have_selector("a[href='http://www.example.com/about']")
            end
          end
        end
      end
    end
  end
end


text:
package auth

import check "gopkg.in/check.v1"

func (s *S) TestGetAPIToken(c *check.C) {
	user := User{Email: "para@xmen.com", APIKey: "Quenço"}
	err := user.Create()
	c.Assert(err, check.IsNil)
	APIKey, err := user.RegenerateAPIKey()
	c.Assert(err, check.IsNil)
	t, err := getAPIToken("bearer " + APIKey)
	c.Assert(err, check.IsNil)
	c.Assert(t.Token, check.Equals, APIKey)
	c.Assert(t.UserEmail, check.Equals, user.Email)
}

func (s *S) TestGetAPITokenNotFound(c *check.C) {
	t, err := getAPIToken("bearer invalid")
	c.Assert(t, check.IsNil)
	c.Assert(err, check.Equals, ErrInvalidToken)
}


text:
import { path7za } from "7zip-bin"
import BluebirdPromise from "bluebird-lst"
import { debug7z, debug7zArgs, exec } from "builder-util"
import { exists, unlinkIfExists } from "builder-util/out/fs"
import { move } from "fs-extra-p"
import * as path from "path"
import { TmpDir } from "temp-file"
import { CompressionLevel } from "../core"
import { getLinuxToolsPath } from "./tools"

/** @internal */
export async function tar(compression: CompressionLevel | any | any, format: string, outFile: string, dirToArchive: string, isMacApp: boolean, tempDirManager: TmpDir): Promise<void> {
  const tarFile = await tempDirManager.getTempFile({suffix: ".tar"})
  const tarArgs = debug7zArgs("a")
  tarArgs.push(tarFile)
  tarArgs.push(path.basename(dirToArchive))

  await BluebirdPromise.all([
    exec(path7za, tarArgs, {cwd: path.dirname(dirToArchive)}),
    // remove file before - 7z doesn't overwrite file, but update
    unlinkIfExists(outFile),
  ])

  if (!isMacApp) {
    await exec(path7za, ["rn", tarFile, path.basename(dirToArchive), path.basename(outFile, `.${format}`)])
  }

  if (format === "tar.lz") {
    // noinspection SpellCheckingInspection
    let lzipPath = "lzip"
    if (process.platform === "darwin") {
      lzipPath = path.join(await getLinuxToolsPath(), "bin", lzipPath)
    }
    await exec(lzipPath, [compression === "store" ? "-1" : "-9", "--keep" /* keep (don't delete) input files */, tarFile])
    // bloody lzip creates file in the same dir where input file with postfix `.lz`, option --output doesn't work
    await move(`${tarFile}.lz`, outFile)
    return
  }

  const args = compute7zCompressArgs(format === "tar.xz" ? "xz" : (format === "tar.bz2" ? "bzip2" : "gzip"), {
    isRegularFile: true,
    method: "DEFAULT",
    compression,
  })
  args.push(outFile, tarFile)
  await exec(path7za, args, {
    cwd: path.dirname(dirToArchive),
  }, debug7z.enabled)
}

export interface ArchiveOptions {
  compression?: CompressionLevel | null

  /**
   * @default false
   */
  withoutDir?: boolean

  /**
   * @default true
   */
  solid?: boolean

  /**
   * @default true
   */
  isArchiveHeaderCompressed?: boolean

  listFile?: string

  dictSize?: number
  excluded?: Array<string>

  // DEFAULT allows to disable custom logic and do not pass method switch at all
  method?: "Copy" | "LZMA" | "Deflate" | "DEFAULT"

  isRegularFile?: boolean
}

export function compute7zCompressArgs(format: string, options: ArchiveOptions = {}) {
  let storeOnly = options.compression === "store"
  const args = debug7zArgs("a")

  let isLevelSet = false
  if (process.env.ELECTRON_BUILDER_COMPRESSION_LEVEL != null) {
    storeOnly = false
    args.push(`-mx=${process.env.ELECTRON_BUILDER_COMPRESSION_LEVEL}`)
    isLevelSet = true
  }

  if (format === "zip" && options.compression === "maximum") {
    // http://superuser.com/a/742034
    args.push("-mfb=258", "-mpass=15")
  }

  if (!isLevelSet && !storeOnly) {
    args.push("-mx=9")
  }

  if (options.dictSize != null) {
    args.push(`-md=${options.dictSize}m`)
  }

  // https://sevenzip.osdn.jp/chm/cmdline/switches/method.htm#7Z
  // https://stackoverflow.com/questions/27136783/7zip-produces-different-output-from-identical-input
  // tc and ta are off by default, but to be sure, we explicitly set it to off
  // disable "Stores NTFS timestamps for files: Modification time, Creation time, Last access time." to produce the same archive for the same data
  if (!options.isRegularFile) {
    args.push("-mtc=off")
  }

  if (format === "7z" || format.endsWith(".7z")) {
    if (options.solid === false) {
      args.push("-ms=off")
    }

    if (options.isArchiveHeaderCompressed === false) {
      args.push("-mhc=off")
    }

    // args valid only for 7z
    // -mtm=off disable "Stores last Modified timestamps for files."
    args.push("-mtm=off", "-mta=off")
  }

  if (options.method != null) {
    if (options.method !== "DEFAULT") {
      args.push(`-mm=${options.method}`)
    }
  }
  else if (format === "zip" || storeOnly) {
    args.push(`-mm=${storeOnly ? "Copy" : "Deflate"}`)
  }

  if (format === "zip") {
    // -mcu switch:  7-Zip uses UTF-8, if there are non-ASCII symbols.
    // because default mode: 7-Zip uses UTF-8, if the local code page doesn't contain required symbols.
    // but archive should be the same regardless where produced
    args.push("-mcu")
  }
  return args
}

// 7z is very fast, so, use ultra compression
/** @internal */
export async function archive(format: string, outFile: string, dirToArchive: string, options: ArchiveOptions = {}): Promise<string> {
  const args = compute7zCompressArgs(format, options)
  // remove file before - 7z doesn't overwrite file, but update
  await unlinkIfExists(outFile)

  args.push(outFile, options.listFile == null ? (options.withoutDir ? "." : path.basename(dirToArchive)) : `@${options.listFile}`)
  if (options.excluded != null) {
    args.push(...options.excluded)
  }

  try {
    await exec(path7za, args, {
      cwd: options.withoutDir ? dirToArchive : path.dirname(dirToArchive),
    }, debug7z.enabled)
  }
  catch (e) {
    if (e.code === "ENOENT" && !(await exists(dirToArchive))) {
      throw new Error(`Cannot create archive: "${dirToArchive}" doesn't exist`)
    }
    else {
      throw e
    }
  }

  return outFile
}


text:
package br.com.delogic.asd.repository.jpa;

import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.history.HistoryPolicy;

public class History implements DescriptorCustomizer {

    public void customize(ClassDescriptor descriptor) {
        HistoryPolicy policy = new HistoryPolicy();
        policy.addHistoryTableName(descriptor.getTableName() + "_HIST");
        policy.addStartFieldName("START_DATE");
        policy.addEndFieldName("END_DATE");
        policy.setShouldHandleWrites(true);
        descriptor.setHistoryPolicy(policy);
    }
}


text:
package matchers_test

import (
	. "github.com/gopkg/database/leveldb/internal/ginkgo"
	. "github.com/gopkg/database/leveldb/internal/gomega"
	. "github.com/gopkg/database/leveldb/internal/gomega/matchers"
)

var _ = Describe("AssignableToTypeOf", func() {
	Context("When asserting assignability between types", func() {
		It("should do the right thing", func() {
			Ω(0).Should(BeAssignableToTypeOf(0))
			Ω(5).Should(BeAssignableToTypeOf(-1))
			Ω("foo").Should(BeAssignableToTypeOf("bar"))
			Ω(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{}))

			Ω(0).ShouldNot(BeAssignableToTypeOf("bar"))
			Ω(5).ShouldNot(BeAssignableToTypeOf(struct{ Foo string }{}))
			Ω("foo").ShouldNot(BeAssignableToTypeOf(42))
		})
	})

	Context("When asserting nil values", func() {
		It("should error", func() {
			success, err := (&AssignableToTypeOfMatcher{Expected: nil}).Match(nil)
			Ω(success).Should(BeFalse())
			Ω(err).Should(HaveOccurred())
		})
	})
})


text:
#include "CCPACSControlSurfaceOuterShapeTrailingEdge.h"
#include "CCPACSControlSurfaceBorderTrailingEdge.h"
#include "CCPACSTrailingEdgeDevice.h"
#include "generated/CPACSTrailingEdgeDevices.h"
#include "CNamedShape.h"
#include "CTiglLogging.h"
#include "CBopCommon.h"
#include "Debugging.h"

#include <BRepOffsetAPI_ThruSections.hxx>

namespace tigl
{

CCPACSControlSurfaceOuterShapeTrailingEdge::CCPACSControlSurfaceOuterShapeTrailingEdge(CCPACSTrailingEdgeDevice* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSControlSurfaceOuterShapeTrailingEdge(parent, uidMgr)
{
}

PNamedShape CCPACSControlSurfaceOuterShapeTrailingEdge::GetLoft(PNamedShape wingCleanShape, gp_Vec upDir) const
{
    DLOG(INFO) << "Building " << _uid << " loft";
    PNamedShape shapeBox = CutoutShape(wingCleanShape, upDir);
    assert(shapeBox);
    if (NeedsWingIntersection()) {

        // perform the boolean intersection of the flap box with the wing
        PNamedShape outerShape = CBopCommon(wingCleanShape, shapeBox);

        for (int iFace = 0; iFace < static_cast<int>(outerShape->GetFaceCount()); ++iFace) {
            CFaceTraits ft = outerShape->GetFaceTraits(iFace);
            ft.SetOrigin(shapeBox);
            outerShape->SetFaceTraits(iFace, ft);
        }

#ifdef DEBUG
        DEBUG_SCOPE(debug);
        debug.dumpShape(outerShape->Shape(), _uid);
#endif

        return outerShape;
    }
    else {
        return shapeBox;
    }
}

PNamedShape CCPACSControlSurfaceOuterShapeTrailingEdge::CutoutShape(PNamedShape wingShape, gp_Vec upDir) const
{

    DLOG(INFO) << "Building " << _uid << " cutter shape";

    // Get Wires definng the Shape of the more complex CutOutShape.
    TopoDS_Wire innerWire = GetInnerBorder().GetWire(wingShape, upDir);
    TopoDS_Wire outerWire = GetOuterBorder().GetWire(wingShape, upDir);

    // make one shape out of the 2 wires and build connections inbetween.
    // TODO: Replace by own lofting algo
    BRepOffsetAPI_ThruSections thrusections(true,true);
    thrusections.AddWire(outerWire);
    thrusections.AddWire(innerWire);
    thrusections.Build();

    PNamedShape cutterShape = PNamedShape(new CNamedShape(thrusections.Shape(), GetParent()->GetUID().c_str()));
    cutterShape->SetShortName(GetParent()->GetShortName().c_str());

    assert(cutterShape);

#ifdef DEBUG
    DEBUG_SCOPE(debug);
    debug.dumpShape(cutterShape->Shape(), _uid + "_cutter");
#endif

    return cutterShape;
}

void CCPACSControlSurfaceOuterShapeTrailingEdge::SetUID(const std::string& uid)
{
    _uid = uid;
    //GetOuterBorder().SetUID(uid + "_OuterBorder");
    //GetInnerBorder().SetUID(uid + "_InnerBorder");
}

bool CCPACSControlSurfaceOuterShapeTrailingEdge::NeedsWingIntersection() const
{
    if (GetInnerBorder().GetShapeType() == CCPACSControlSurfaceBorderTrailingEdge::ShapeType::AIRFOIL) {
        return false;
    }
    else {
        return true;
    }
}

} // namespace tigl


text:
type MyType = {
    arguments: Array<string>
}

declare function use(s: any);

function myFunction(myType: MyType) {
    for (let i = 0; i < 10; i++) {
        use(myType.arguments[i]);
        // create closure so that tsc will turn loop body into function
        const x = 5;
        [1, 2, 3].forEach(function(j) { use(x); })
    }
}

//// [argumentsAsPropertyName.js]
function myFunction(myType) {
    var _loop_1 = function (i) {
        use(myType.arguments[i]);
        // create closure so that tsc will turn loop body into function
        var x = 5;
        [1, 2, 3].forEach(function (j) { use(x); });
    };
    for (var i = 0; i < 10; i++) {
        _loop_1(i);
    }
}


text:
from __future__ import unicode_literals

from django.contrib.contenttypes.models import ContentType
try:
    from django.contrib.contenttypes.fields import GenericForeignKey
except ImportError:
    # Django < 1.9
    from django.contrib.contenttypes.generic import GenericForeignKey
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class MaatRanking(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField(db_index=True)
    content_object = GenericForeignKey('content_type', 'object_id')

    typology = models.CharField(max_length=255, db_index=True)
    usable = models.BooleanField(default=False)
    position = models.PositiveIntegerField(default=0)

    class Meta:
        # This index is fundamental to avoid MySQL filesorting.
        # The first portion of the index is used to filter rows and, being
        # constant, the second can be used to order:
        # http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html
        unique_together = ('content_type', 'typology', 'usable', 'position')

    def __str__(self):
        return 'Rank for {}'.format(self.content_object)


text:
<?php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * Administradores Model
 *
 * @method \App\Model\Entity\Administradore get($primaryKey, $options = [])
 * @method \App\Model\Entity\Administradore newEntity($data = null, array $options = [])
 * @method \App\Model\Entity\Administradore[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\Administradore|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Administradore patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\Administradore[] patchEntities($entities, array $data, array $options = [])
 * @method \App\Model\Entity\Administradore findOrCreate($search, callable $callback = null)
 */
class AdministradoresTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('administradores');
        $this->displayField('id');
        $this->primaryKey('id');
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmpty('id', 'create');

        $validator
            ->requirePresence('nome', 'create')
            ->notEmpty('nome');

        $validator
            ->email('email')
            ->requirePresence('email', 'create')
            ->notEmpty('email');

        $validator
            ->requirePresence('senha', 'create')
            ->notEmpty('senha');

        $validator
            ->boolean('status')
            ->requirePresence('status', 'create')
            ->notEmpty('status');

        $validator
            ->dateTime('data_cadastro')
            ->requirePresence('data_cadastro', 'create')
            ->notEmpty('data_cadastro');

        $validator
            ->dateTime('data_ultimo_acesso')
            ->requirePresence('data_ultimo_acesso', 'create')
            ->notEmpty('data_ultimo_acesso');

        $validator
            ->boolean('excluido')
            ->requirePresence('excluido', 'create')
            ->notEmpty('excluido');

        $validator
            ->boolean('invisivel')
            ->requirePresence('invisivel', 'create')
            ->notEmpty('invisivel');

        return $validator;
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->isUnique(['email']));

        return $rules;
    }
}


text:
/* eslint-disable */
/**
 * Copyright 2017 The AMP Start Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS-IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const gulp = require('gulp-help')(require('gulp'));
const config = require('./config');
const util = require('gulp-util');
const runSequence = require('run-sequence');
const postcss = require('postcss');
const gulpPostcss = require('gulp-postcss');
const replace = require('gulp-replace');
const csstree = require('css-tree');
const rename = require('gulp-rename');
const through = require('through2');
const webpack = require('webpack');
const webpackProdConfig = require('../webpack.config.js')({
  prod: true
});
const webpackDevConfig = require('../webpack.config.js')({
  dev: true
});
const webpackTestConfig = require('../webpack.config.js')({
  test: true
});
const WebpackDevServer = require('webpack-dev-server');
const KarmaServer = require('karma').Server;
const argv = require('minimist')(process.argv.slice(2));

const CONFIGURATOR_PORT = 8080;

function configuratorWebpackProd() {
  webpack(webpackProdConfig, function(err, stats) {
    if (err) {
      throw new util.PluginError('webpack', err);
    }

    // Output the webpack stats
    util.log('[webpack]', stats.toString({}));
  });
}

function runWebpackDevServer(webpackConfig) {
  if(webpackConfig.entry && Array.isArray(webpackConfig.entry)) {
    webpackConfig.entry.unshift(`webpack-dev-server/client?http://localhost:${argv.port || CONFIGURATOR_PORT}`);
  }
  const webpackCompiler = webpack(webpackConfig);
  new WebpackDevServer(webpackCompiler, {
        publicPath: '/'
    }).listen(argv.port || CONFIGURATOR_PORT, 'localhost', function(err) {
        if (err) {
          throw new util.PluginError('webpack-dev-server', err);
        }

        // Inform the user of the url they can reach the server
        util.log('[webpack-dev-server]', `Development Server: http://localhost:${argv.port || CONFIGURATOR_PORT}`);
        util.log('[webpack-dev-server]', `Directory Listing for current server: http://localhost:${argv.port || CONFIGURATOR_PORT}/webpack-dev-server`);
    });
}

function configuratorServe() {
  runWebpackDevServer(webpackDevConfig);
}

function configuratorWatchProd() {
  return gulp.watch(
      [
        `${config.src.configurator}/**/*`
      ],
      function(event) {
        runSequence('configurator:webpack');
      });
}

function runKarma(options, callback) {

  // Parse our karma config
  karmaServerConfig = {
    configFile: `${__dirname}/../karma.conf.js`
  };

  // Pass in our options
  karmaServerConfig = Object.assign({}, karmaServerConfig, options)

  new KarmaServer(karmaServerConfig, callback).start();
}

function configuratorTest(callback) {
  runKarma({}, callback);
}

function configuratorTestWatch(callback) {
  runKarma({
    singleRun: false,
    autoWatch: true
  }, callback);
}

function postCssWithVars() {
  // Filtering out warning messages
  const silentPostCSS = postcss.plugin('messages', () => (css, result) => {
    const warnings = result.warnings();
    result.messages = result.messages.filter(msg => msg.type !== 'warning');
  });

  const plugins = [
    require('postcss-import')(),
    require('autoprefixer')(),
    require('postcss-calc')(),
    require('postcss-color-function')(),
    require('postcss-custom-properties')({
      preserve: true,
      appendVariables: true,
    }),
    require('postcss-discard-comments')(),
    require('postcss-custom-media')(),
    silentPostCSS()
  ];
  const options = {};
  const gulpConfiguratorCssSrc = config.src.css;
  gulpConfiguratorCssSrc.push('!css/**/_*.css');

  return gulp.src(config.src.css)
      .pipe(gulpPostcss(plugins, options))
      .pipe(replace('!important', ''))
      .pipe(gulp.dest(config.dest.uncompiled_css))
}

function cssVarsJson() {
  return gulp.src(config.dest.uncompiled_css + '/**/*.css')
      .pipe(through.obj(function(file, enc, cb) {
        if(file.isNull()) {
          cb(null, file);
          return;
        }
        const cssVarObj = {};
        const ast = csstree.parse(file.contents.toString());
        csstree.walk(ast, function(node) {
          if(node.type === 'Declaration' && node.property.indexOf('--') === 0) {
            cssVarObj[node.property] = {
              value: node.value.value
            }
          }
        });
        // Place the json into the file
        file.contents = new Buffer(JSON.stringify(cssVarObj, null, 2));
        cb(null, file);
      }))
      .pipe(rename(function(path) {
        path.extname = '.json';
      }))
      .pipe(gulp.dest(config.dest.uncompiled_css))
}

// Define our gulp tasks
gulp.task('configurator', 'Runs the default, configurator:build for prod deployment', ['configurator:build']);
gulp.task('configurator:build', 'Builds the configurator for deployment, analyzes the templates css, converts to json, and then builds the configurator webapp', ['configurator:css', 'configurator:json', 'configurator:webpack']);
gulp.task('configurator:webpack', 'Builds only the configurator webapp using webpack, and passing the prod environment', configuratorWebpackProd);
gulp.task('configurator:serve', 'Opens a dev server at localhost:8080 for the configurator, and watches/livreloads on changes. Port can be changed with --port="PORT_NUMBER_HERE"', configuratorServe);
gulp.task('configurator:watch', 'Watches the configurator src directory, and runs prod webpack builds on changes. Useful for eveloping both the configurator and ampstart', configuratorWatchProd);
gulp.task('configurator:test', 'Runs the tests for configurator, only once', configuratorTest);
gulp.task('configurator:test:watch', 'Runs and watches the tests for the configurator', configuratorTestWatch);
gulp.task('configurator:css', 'Runs postcss on templates, and preserves their variables', postCssWithVars);
gulp.task('configurator:json', 'Converts CSS from configurator:css, into digestable JSON by the configurator webapp', cssVarsJson);


text:
![Imagination Technologies Limited logo](images/img.png)

----

# Awa LightweightM2M

----

## Quick start guide

### Building the code

#### Building under Linux

Install the dependencies:

```
 sudo apt-get update
 sudo apt-get install build-essential gcc git mercurial python cmake python-nose python-lxml
```

Run make in the root directory of the Awa LWM2M repository

```$ make```

This will produce the following executable files:

* build/daemon/src/client/awa_clientd
* build/daemon/src/server/awa_serverd
* build/daemon/src/bootstrap/awa_bootstrapd

For usage information see the [User guide](userguide.md)

##### Additional commands

The variable `INSTALL_PREFIX` can be specified to modify the path where the build results will be installed *at configuration time*. For example:

```$ make INSTALL_PREFIX=/usr```

Note that this must be set at the very first invocation of make, or after `make clean`. Setting it later will not affect the install path.

By default, this is set to `/` which will result in build artefacts being installed into /bin, /lib and /include.

The variable `DESTDIR` can be set at the time `make install` is called. The final path is a combination of `INSTALL_PREFIX` and `DESTDIR`.

For example, the following will build and install such that binaries are placed in /tmp/usr/bin:

```
    $ make INSTALL_PREFIX=/usr
    $ make install DESTDIR=/tmp
```

If you want to install Awa into /usr/local/bin, the following commands are suggested:

```
    $ make
    $ make install DESTDIR=/usr/local
```

#### The cmake build

The build can be created out-of-source, such that all build artefacts are placed in a dedicated directory.

First, create a suitable directory for the build output:

```$ mkdir build ```

From this directory, run cmake, passing the path to the root directory of the repository as a parameter:

```
    $ cd build
    $ cmake ..
```

This generates a Makefile in the build directory, which can be run to generate the build artefacts:

```$ make ```

Once the build is complete you may optionally *install* the resulting binaries to a specified directory, for example:

```$ make DESTDIR=./install install ```

Cmake options can be passed to cmake from the top-level makefile with the variable `CMAKE_OPTIONS`. For example:

```$ make CMAKE_OPTIONS=-DBUILD_TESTS=OFF```

----

----


text:
<?xml version="1.0" encoding="utf-8"?>
<EriFile VersionNumber="1357" NumberOfEriEntries="12" EriFileType="1">
    <CallPromptId Id="0" CallPromptText="CallPromptId0" />
    <CallPromptId Id="1" CallPromptText="CallPromptId1" />
    <CallPromptId Id="2" CallPromptText="CallPromptId2" />
    <EriInfo RoamingIndicator="64" IconIndex="1" IconMode="0" EriText="T-CDMA 64" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="65" IconIndex="65" IconMode="0" EriText="T-CDMA 65" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="66" IconIndex="1" IconMode="0" EriText="T-CDMA Ext 66" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="67" IconIndex="67" IconMode="0" EriText="T-CDMA Ext 67" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="68" IconIndex="68" IconMode="0" EriText="T-CDMA Roam 68" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="69" IconIndex="69" IconMode="1" EriText="T-CDMA Ext 69" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="70" IconIndex="70" IconMode="1" EriText="T-CDMA Roam 70" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="71" IconIndex="1" IconMode="0" EriText="T-CDMA Ext 71" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="72" IconIndex="72" IconMode="0" EriText="T-CDMA Ext 72" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="73" IconIndex="73" IconMode="0" EriText="T-CDMA Roam 73" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="74" IconIndex="74" IconMode="1" EriText="T-CDMA Ext 74" CallPromptId="0" AlertId="0" />
    <EriInfo RoamingIndicator="75" IconIndex="75" IconMode="1" EriText="T-CDMA Roam 75" CallPromptId="0" AlertId="0" />
</EriFile>


text:
/*! `bnf` grammar compiled for Highlight.js 11.4.0 */
(()=>{var e=(()=>{"use strict";return e=>({name:"Backus\u2013Naur Form",
contains:[{className:"attribute",begin:/</,end:/>/},{begin:/::=/,end:/$/,
contains:[{begin:/</,end:/>/
},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]
}]})})();hljs.registerLanguage("bnf",e)})();


text:
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using BuiltToRoam.Navigation;

namespace RealEstateInspector
{
    public class WindowsPlatformNavigationService : CoreNavigateService<Page>
    {
        protected override void NavigateToView(Type viewType)
        {
            (Window.Current.Content as Frame).Navigate(viewType);
        }
    }
}


text:
const React = require('react')
const styles = require('./Frontpage.css')
const Entry = require('../components/Frontpage/Entry.js')
const { connect } = require('react-redux')

const entries = [
  { id: 0, commentCount: 0, upvotes: 12, title: 'Hello World', submittedAt: new Date(2015, 10, 11) },
  { id: 1, commentCount: 2, upvotes: 10, title: 'Hello Other World', submittedAt: new Date(2015, 10, 10) },
  { id: 2, commentCount: 0, upvotes: 8, title: 'Hello Other World', submittedAt: new Date(2015, 10, 1) },
]

const Frontpage = React.createClass({
  propTypes: {
    isAuthenticated: React.PropTypes.bool.isRequired,
    me: React.PropTypes.object.isRequired,
  },
  render() {
    const entriesLength = entries.length
    return (

            {this.props.isAuthenticated ? (Signed in as {this.props.me.emailAddress}.) : ''} View: Top.

          {entries.map((entry, index) => (
            <Entry
              key={entry.id}
              isFirstItem={index === 0}
              isLastItem={index === entriesLength - 1}
              commentCount={entry.commentCount}
              upvotes={entry.upvotes}
              title={entry.title}
              submittedAt={entry.submittedAt}
            />
          ))}

    )
  },
})

if (SERVER) {
  Frontpage.styles = [styles.source, ...Entry.styles]
}

const mapStateToProps = state => {
  const { userId, isAuthenticated } = state.auth
  return {
    isAuthenticated,
    me: isAuthenticated ? state.users[userId] : {},
  }
}
module.exports = connect(mapStateToProps)(Frontpage)


text:
package de.nko;

import static org.junit.Assert.assertEquals;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.search.Attribute;
import net.sf.ehcache.search.Query;
import net.sf.ehcache.search.Results;
import net.sf.ehcache.search.expression.Criteria;

import org.junit.BeforeClass;
import org.junit.Test;

@Slf4j
public class CacheTest {
    private static Cache cache = CacheManager.getInstance().getCache("persons");
    private static Attribute<String> lastname = cache.getSearchAttribute("lastname");
    private static Attribute<String> gender = cache.getSearchAttribute("gender");
    private static Attribute<String> country = cache.getSearchAttribute("country");

    @BeforeClass
    public static void init() throws Exception {
        List<Person> persons = createPersons();
        populateCache(persons);
    }

    @Test
    public void searchLastnameSmith() throws Exception {
        log.info("Preparing search for lastname='Smith'...");
        int n = performSearch(lastname.eq("Smith"));
        assertEquals(3890, n);
    }

    @Test
    public void searchGenderM() throws Exception {
        log.info("Preparing search for gender='M'...");
        int n = performSearch(gender.eq("M"));
        assertEquals(499530, n);
    }

    @Test
    public void searchCountryGermany() throws Exception {
        log.info("Preparing search for country='Germany'...");
        int n = performSearch(country.eq("Germany"));
        assertEquals(4010, n);
    }

    @Test
    public void searchGenderFCountryFrance() throws Exception {
        log.info("Preparing search for gender='F' and country='France'...");
        int n = performSearch(gender.eq("F"), country.eq("France"));
        assertEquals(1940, n);
    }

    @Test
    public void searchGenderMLastnameSchmidt() throws Exception {
        log.info("Preparing search for gender='M' and lastname='Schmidt'...");
        int n = performSearch(gender.eq("M"), lastname.eq("Schmidt"));
        assertEquals(2240, n);
    }

    @Test
    public void searchLastnameJonesCountryUSA() throws Exception {
        log.info("Preparing search for lastname='Jones' and country = 'United States of America'");
        int n = performSearch(lastname.eq("Jones"), country.eq("United States of America"));
        assertEquals(30, n);
    }

    private int performSearch(Criteria... criteria) {
        Query query = createQuery(criteria);
        long start = System.currentTimeMillis();
        Results results = query.execute();
        int count = results.size();
        long duration = System.currentTimeMillis() - start;
        log.info("Searchresult: found {} persons in {} ms.", count, duration);
        results.discard();
        return count;
    }

    private Query createQuery(Criteria... criteria) {
        Query query = cache.createQuery().includeValues();
        for (Criteria crit : criteria) {
            query.addCriteria(crit);
        }
        query.end();
        return query;
    }

    private static void populateCache(List<Person> persons) {
        log.info("Put persons into cache...");
        int n = persons.size();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            for (Person p : persons) {
                int k = p.getId() + n * i;
                Element e = new Element(k, p);
                cache.put(e);
            }
        }
        long duration = System.currentTimeMillis() - start;
        log.info("All persons cached in {}ms.", duration);
        log.info("Cache size is {} elements", cache.getStatistics().getLocalHeapSize());
        // log.info("Cache size is {}MB", cache.getStatistics().getLocalHeapSizeInBytes() / 1024 / 1024);
    }

    private static List<Person> createPersons() throws Exception {
        log.info("Creating persons from repository...");
        List<Person> persons = new ArrayList<Person>();

        InputStream is = CacheTest.class.getResourceAsStream("/mock_persons.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line;
        while ((line = br.readLine()) != null) {
            String[] strings = line.split(",");
            Person p = new Person();
            p.setId(Integer.parseInt(strings[0]));
            p.setFirstname(strings[1]);
            p.setLastname(strings[2]);
            p.setGender(strings[3]);
            p.setCountry(strings[4]);
            persons.add(p);
        }

        br.close();
        is.close();

        log.info("Created {} persons from repository.", persons.size());
        return persons;
    }

}


text:
Basically, PEP8

- NEVER tabs. 4 spaces to indent.
- Max line width: 79 chars (with flexibility to overflow by a "few chars" if
  the overflowing content is not semantically significant and avoids an
  explosion of vertical whitespace).
- Use camel case for class and type names
- Use underscores for functions and variables.
- Use double quotes.
- Use parentheses instead of '\\' for line continuation where ever possible
  (which is pretty much everywhere)
- There should be max a single new line between:
    - statements
    - functions in a class
- There should be two new lines between:
    - definitions in a module (e.g., between different classes)
- There should be spaces where spaces should be and not where there shouldn't be:
    - a single space after a comma
    - a single space before and after for '=' when used as assignment
    - no spaces before and after for '=' for default values and keyword arguments.
- Indenting must follow PEP8; either hanging indent or multiline-visual indent
  depending on the size and shape of the arguments and what makes more sense to
  the author. In other words, both this::

    print("I am a fish %s" % "moo")

  and this::

    print("I am a fish %s" %
          "moo")

  and this::

    print(
        "I am a fish %s" %
        "moo"
    )

  ...are valid, although given each one takes up 2x more vertical space than
  the previous, it's up to the author's discretion as to which layout makes most
  sense for their function invocation.  (e.g. if they want to add comments
  per-argument, or put expressions in the arguments, or group related arguments
  together, or want to deliberately extend or preserve vertical/horizontal
  space)

Comments should follow the `google code style <http://google.github.io/styleguide/pyguide.html?showone=Comments#Comments>`_.
This is so that we can generate documentation with
`sphinx <http://sphinxcontrib-napoleon.readthedocs.org/en/latest/>`_. See the
`examples <http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html>`_
in the sphinx documentation.

Code should pass pep8 --max-line-length=100 without any warnings.


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/publications-and-documents/auxilarity-organizations/i-know-my-savior-lives-2010-outline-for-sharing-time-publication" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/publications-and-documents/auxilarity-organizations/i-know-my-savior-lives-2010-outline-for-sharing-time-publication</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">I Know My Savior Lives : 2010 Outline for Sharing Time (Publication)</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/publications-and-documents/auxilarity-organizations/i-know-my-savior-lives-2010-outline-for-sharing-time-publication</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/publications-and-documents/auxilarity-organizations/i-know-my-savior-lives-2010-outline-for-sharing-time-publication</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
"""Representation of calls in ELAPS:PlayMat."""

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import pyqtSlot

import elaps
from elaps import signature
from elaps.qt.dataarg import QDataArg

class QCall(QtGui.QListWidgetItem):

    """Representation of a call in ELAPS:PlayMat."""

    def __init__(self, playmat, callid):
        """Initialize the call representation."""
        QtGui.QListWidgetItem.__init__(self)
        self.playmat = playmat
        self.sig = None

        self.UI_init()

    @property
    def callid(self):
        """Get the callid."""
        return self.playmat.UI_calls.row(self)

    @property
    def call(self):
        """Get the associated Call (or BasicCall)."""
        return self.playmat.experiment.calls[self.callid]

    def UI_init(self):
        """Initialize the GUI elements."""
        routines = list(self.playmat.experiment.sampler["kernels"])

        # layout
        self.widget = QtGui.QWidget()
        layout = QtGui.QGridLayout()
        self.widget.setLayout(layout)

        # routine label
        routinelabel = QtGui.QLabel()
        layout.addWidget(routinelabel, 0, 0)

        # routine
        routine = QtGui.QLineEdit(textChanged=self.on_arg_change)
        layout.addWidget(routine, 1, 0)
        routine.argid = 0
        completer = QtGui.QCompleter(routines, routine)
        routine.setCompleter(completer)

        # spaces
        layout.setColumnStretch(100, 1)

        # shortcuts

        # attributes
        self.UI_args = [routine]
        self.UI_arglabels = [routinelabel]

    def update_size(self):
        """Update the size of the call item from its widget."""
        def update():
            """Update the size (asynchronous callback)."""
            try:
                self.setSizeHint(self.widget.sizeHint())
            except:
                pass
        QtCore.QTimer.singleShot(0, update)

    def UI_args_set(self, force=False):
        """Set all arguments."""
        for argid in range(len(self.call)):
            self.UI_arg_set(argid, force)

    def UI_arg_set(self, argid=None, force=False):
        """Set an argument."""
        value = self.call[argid]
        UI_arg = self.UI_args[argid]
        UI_arglabel = self.UI_arglabels[argid]
        if force or not UI_arg.hasFocus():
            if isinstance(UI_arg, QtGui.QLineEdit):
                if type(value) is list:
                    UI_arg.setText("[%s]" % value[0])
                else:
                    UI_arg.setText(str(value))
            elif isinstance(UI_arg, QtGui.QComboBox):
                UI_arg.setCurrentIndex(UI_arg.findText(str(value)))

        if isinstance(self.call, signature.BasicCall):
            self.playmat.UI_set_invalid(UI_arg, False)

        if isinstance(self.call, signature.Call):
            # apply hideargs
            show = not isinstance(
                self.sig[argid], tuple(self.playmat.hideargs) + (type(None),)
            )
            UI_arg.setVisible(show)
            UI_arglabel.setVisible(show)

            # viz
            if isinstance(self.sig[argid], signature.Data):
                UI_arg.viz()

        # validity
        if argid > 0:
            try:
                self.playmat.experiment.set_arg(self.callid, argid, value,
                                                check_only=True)
                self.playmat.UI_set_invalid(UI_arg, False)
            except:
                self.playmat.UI_set_invalid(UI_arg)
        self.update_size()

    def setall(self, force=False):
        """Set all UI elements."""
        self.playmat.UI_setting += 1
        self.fixcallid = self.callid
        if isinstance(self.call, signature.BasicCall):
            if self.sig != self.call.sig:
                self.args_clear()
                self.args_init()
                self.sig = self.call.sig
        else:
            if self.sig:
                self.args_clear()
                self.sig = None
        self.setToolTip(
            "<tt>calls[%d]</tt>: Call number %d to be measured" %
            (self.fixcallid, self.fixcallid)
        )

        self.UI_args_set(force)
        self.playmat.UI_setting -= 1

    def args_init(self):
        """Initialize the arguments."""
        Qroutine = self.UI_args[0]
        assert(isinstance(self.call, signature.BasicCall))
        sig = self.call.sig
        try:
            doc = elaps.io.load_doc(self.call[0])
        except:
            doc = None
        if doc:
            Qroutine.setToolTip(doc[0][1])
        for argid, arg in enumerate(sig):
            if argid == 0:
                continue
            tooltip = ""
            if isinstance(sig, signature.Signature):
                argname = sig[argid].name
                if doc and argid < len(doc):
                    tooltip = doc[argid][1]
            else:
                argname = sig[argid].replace("*", " *")
                if doc and argid < len(doc):
                    argname += doc[argid][0]
                    tooltip = doc[argid][1]
                if argname in ("int *", "float *", "double *"):
                    if doc:
                        tooltip += "\n\n*Format*:\n"
                    tooltip += ("Scalar:\tvalue\t\te.g. 1, -0.5\n"
                                "Array:\t[#elements]"
                                "\te.g. [10000] for a 100x100 matrix")
            # arglabel
            UI_arglabel = QtGui.QLabel(
                argname, toolTip=tooltip, alignment=QtCore.Qt.AlignCenter
            )
            self.UI_arglabels.append(UI_arglabel)
            self.widget.layout().addWidget(UI_arglabel, 0, argid)
            # arg
            if isinstance(sig, signature.Signature):
                arg = sig[argid]
                if isinstance(arg, signature.Flag):
                    UI_arg = QtGui.QComboBox()
                    UI_arg.addItems(map(str, arg.flags))
                    UI_arg.currentIndexChanged[str].connect(self.on_arg_change)
                elif isinstance(arg, signature.Data):
                    UI_arg = QDataArg(
                        self,
                        editingFinished=self.on_dataarg_focusout
                    )
                else:
                    UI_arg = QtGui.QLineEdit(
                        textChanged=self.on_arg_change,
                        editingFinished=self.on_arg_focusout
                    )
            else:
                UI_arg = QtGui.QLineEdit("", textChanged=self.on_arg_change)
            UI_arg.pyqtConfigure(
                toolTip=tooltip,
                contextMenuPolicy=QtCore.Qt.CustomContextMenu,
                customContextMenuRequested=self.on_arg_rightclick
            )
            UI_arg.argid = argid
            self.UI_args.append(UI_arg)
            self.widget.layout().addWidget(UI_arg, 1, argid,
                                           QtCore.Qt.AlignCenter)

    def args_clear(self):
        """Clear the arguments."""
        for UI_arg in self.UI_args[1:]:
            UI_arg.deleteLater()
        self.UI_args = [self.UI_args[0]]
        for UI_arglabel in self.UI_arglabels[1:]:
            UI_arglabel.deleteLater()
        self.UI_arglabels = [self.UI_arglabels[0]]
        self.UI_args[0].setToolTip("")

    def viz(self):
        """Visualize all operands."""
        if not isinstance(self.call, signature.Call):
            return
        for argid in self.call.sig.dataargs():
            self.UI_args[argid].viz()
        self.update_size()

    # event handlers
    # @pyqtSlot(str)  # sender() pyqt bug
    def on_arg_change(self, value):
        """Event: Changed an argument."""
        sender = self.playmat.Qapp.sender()
        value = str(value)
        argid = sender.argid
        if isinstance(sender, QtGui.QLineEdit) and not isinstance(sender,
                                                                  QDataArg):
            # adjust width no matter where the change came from
            self.playmat.UI_edit_autowidth(sender, 1 + (argid == 0))
        if self.playmat.UI_setting:
            return
        self.playmat.on_arg_set(self.callid, argid, value)

    def on_dataarg_focusout(self):
        """Event: Changed a data argument."""
        sender = self.playmat.Qapp.sender()
        value = sender.text()
        self.on_arg_change(value)
        self.on_arg_focusout()

    # @pyqtSlot(QtCore.QPoint)  # sender() pyqt bug
    def on_arg_rightclick(self, pos):
        """Event: right click on arg."""
        if self.playmat.UI_setting:
            return
        sender = self.playmat.Qapp.sender()
        globalpos = sender.mapToGlobal(pos)
        menu = sender.createStandardContextMenu()
        if isinstance(self.call, signature.Call):
            actions = menu.actions()
            if actions[-1].text() == "Insert Unicode control character":
                actions[-1].setVisible(False)
            argid = sender.argid
            if isinstance(self.call.sig[argid], signature.Ld):
                inferld = QtGui.QAction("Infer leading dimension", sender,
                                        triggered=self.on_inferld)
                inferld.argid = argid
                menu.insertAction(actions[0], inferld)
            elif isinstance(self.call.sig[argid], signature.Lwork):
                inferlwork = QtGui.QAction("Infer workspace size", sender,
                                           triggered=self.on_inferlwork)
                inferlwork.argid = argid
                menu.insertAction(actions[0], inferlwork)
            if isinstance(self.call.sig[argid], signature.Data):
                for action in self.playmat.UI_varyactions(self.call[argid]):
                    if action:
                        menu.insertAction(actions[0], action)
                    else:
                        menu.insertSeparator(actions[0])
            if len(menu.actions()) > len(actions):
                menu.insertSeparator(actions[0])
        menu.exec_(globalpos)

    # @pyqtSlot()  # sender() pyqt bug
    def on_inferld(self):
        """Event: infer ld."""
        if self.playmat.UI_setting:
            return
        argid = self.playmat.Qapp.sender().argid
        self.UI_args[argid].clearFocus()
        self.playmat.on_infer_ld(self.callid, argid)

    # @pyqtSlot()  # sender() pyqt bug
    def on_inferlwork(self):
        """Event: infer ld."""
        if self.playmat.UI_setting:
            return
        argid = self.playmat.Qapp.sender().argid
        self.UI_args[argid].clearFocus()
        self.playmat.on_infer_lwork(self.callid, argid)

    @pyqtSlot()
    def on_arg_focusout(self):
        """Argument looses focus."""
        if self.playmat.UI_setting:
            return
        if self.playmat.Qapp.activeModalWidget():
            return
        self.playmat.UI_calls_set()


text:
import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import { join } from 'path';

import Config from '../../config';
import { makeTsProject, TemplateLocalsBuilder } from '../../utils';

const plugins = <any>gulpLoadPlugins();

/**
 * Executes the build process, transpiling the TypeScript files for the production environment.
 */

export = () => {
  const tsProject = makeTsProject({
    target: 'es2015',
    module: 'es2015',
    moduleResolution: 'node'
  }, Config.TMP_DIR);
  const src = [
    join(Config.TOOLS_DIR, '/manual_typings/**/*.d.ts'),
    join(Config.TMP_DIR, '**/*.ts')
  ];
  const result = gulp.src(src)
    .pipe(plugins.plumber())
    .pipe(tsProject())
    .once('error', () => {
      this.once('finish', () => process.exit(1));
    });

  return result.js
    .pipe(plugins.template(new TemplateLocalsBuilder().build(), {interpolate: /<%=([\s\S]+?)%>/g}))
    .pipe(gulp.dest(Config.TMP_DIR))
    .on('error', (e: any) => {
      console.log(e);
    });
};


text:
define([], function() {

  /* Native method shortcuts for methods with the same name as other `lodash` methods */
  var nativeMax = Math.max;

  /**
   * Slices `array` from the `start` index up to, but not including, the `end` index.
   *
   * Note: This function is used instead of `Array#slice` to support node lists
   * in IE < 9 and to ensure dense arrays are returned.
   *
   * @static
   * @memberOf _
   * @category Arrays
   * @param {Array} array The array to slice.
   * @param {number} [start=0] The start index.
   * @param {number} [end=array.length] The end index.
   * @returns {Array} Returns the slice of `array`.
   */
  function slice(array, start, end) {
    var index = -1,
        length = array ? array.length : 0;

    start = start == null ? 0 : (+start || 0);
    if (start < 0) {
      start = nativeMax(length + start, 0);
    } else if (start > length) {
      start = length;
    }
    end = typeof end == 'undefined' ? length : (+end || 0);
    if (end < 0) {
      end = nativeMax(length + end, 0);
    } else if (end > length) {
      end = length;
    }
    length = start > end ? 0 : (end - start);

    var result = Array(length);
    while (++index < length) {
      result[index] = array[start + index];
    }
    return result;
  }

  return slice;
});


text:
<?php
/*
 *	Custom template for the Contact page, to demonstrate how to use custom template files and also how to use
 *	the content_form function to collect information such as contact forms.
 *
 */
?>

<?=$post['title']?>

	<?=content_html($post['body'])?>

<?php
//	we want to have a form that can be used to gather contact info...
	content_form(
		'contact',	//	post type
		'',			//  post id
		'',			//	action
		array('msg'=>'Thank you, we will be in touch')	//	thank you
	);
?>


text:
package org.mengyun.tcctransaction.exception;

/**
 * Created by changming.xie on 7/21/16.
 */
public class CancellingException extends RuntimeException {

    private static final long serialVersionUID = -303017754217525684L;

    public CancellingException(Throwable cause) {
        super(cause);
    }
}