text:
require 'wice/wice_grid_misc.rb'
require 'wice/wice_grid_core_ext.rb'
require 'wice/grid_renderer.rb'
require 'wice/table_column_matrix.rb'
require 'wice/active_record_column_wrapper.rb'
require 'wice/helpers/wice_grid_view_helpers.rb'
require 'wice/helpers/wice_grid_misc_view_helpers.rb'
require 'wice/helpers/wice_grid_serialized_queries_view_helpers.rb'
require 'wice/helpers/wice_grid_view_helpers.rb'
require 'wice/helpers/bs_calendar_helpers.rb'
require 'wice/helpers/js_calendar_helpers.rb'
require 'wice/grid_output_buffer.rb'
require 'wice/wice_grid_controller.rb'
require 'wice/wice_grid_spreadsheet.rb'
require 'wice/wice_grid_serialized_queries_controller.rb'
require 'wice/columns/column_processor_index.rb'
require 'wice/columns.rb'
require 'kaminari.rb'

ActionController::Base.send(:helper_method, :wice_grid_custom_filter_params)

module Wice

  class WiceGridEngine < ::Rails::Engine #:nodoc:

    initializer "wice_grid_railtie.configure_rails_initialization" do |app|

      ActiveSupport.on_load :action_controller do
        ActionController::Base.send(:include, Wice::Controller)
      end

      ActiveSupport.on_load :active_record do
        ActiveRecord::ConnectionAdapters::Column.send(:include, ::Wice::WiceGridExtentionToActiveRecordColumn)
        ActiveRecord::Base.send(:include, ::Wice::MergeConditions)
      end

      ActiveSupport.on_load :action_view do
        ::ActionView::Base.class_eval { include Wice::GridViewHelper }
        [ActionView::Helpers::AssetTagHelper,
         ActionView::Helpers::TagHelper,
         ActionView::Helpers::JavaScriptHelper,
         ActionView::Helpers::FormTagHelper].each do |m|
          JsCalendarHelpers.send(:include, m)
        end

        Columns.load_column_processors
        require 'wice/wice_grid_serialized_query.rb'

        # It is here only until this pull request is pulled: https://github.com/amatsuda/kaminari/pull/267
        require 'wice/kaminari_monkey_patching.rb'
      end
    end

    initializer "wice_grid_railtie.configure_rails_assets_precompilation" do |app|
      app.config.assets.precompile << 'icons/grid/*'
    end
  end

  class WiceGrid

    attr_reader :klass, :name, :resultset, :custom_order, :query_store_model #:nodoc:
    attr_reader :ar_options, :status, :export_to_csv_enabled, :csv_file_name, :csv_field_separator, :saved_query #:nodoc:
    attr_writer :renderer #:nodoc:
    attr_accessor :output_buffer, :view_helper_finished, :csv_tempfile #:nodoc:

    # core workflow methods START

    def initialize(klass_or_relation, controller, opts = {})  #:nodoc:
      @controller = controller

      @relation = klass_or_relation
      @klass = @relation.kind_of?(Class) && @relation.ancestors.index(ActiveRecord::Base) ?
        klass_or_relation :
        klass_or_relation.klass

      unless @klass.kind_of?(Class) && @klass.ancestors.index(ActiveRecord::Base)
        raise WiceGridArgumentError.new("ActiveRecord model class (second argument) must be a Class derived from ActiveRecord::Base")
      end

      # validate :with_resultset & :with_paginated_resultset
      [:with_resultset, :with_paginated_resultset].each do |callback_symbol|
        unless [NilClass, Symbol, Proc].index(opts[callback_symbol].class)
          raise WiceGridArgumentError.new(":#{callback_symbol} must be either a Proc or Symbol object")
        end
      end

      opts[:order_direction].downcase! if opts[:order_direction].kind_of?(String)

      # validate :order_direction
      if opts[:order_direction] && ! (opts[:order_direction] == 'asc'  ||
                                      opts[:order_direction] == :asc   ||
                                      opts[:order_direction] == 'desc' ||
                                      opts[:order_direction] == :desc)
        raise WiceGridArgumentError.new(":order_direction must be either 'asc' or 'desc'.")
      end

      begin
        # options that are understood
        @options = {
          conditions:                 nil,
          csv_file_name:              nil,
          csv_field_separator:        Defaults::CSV_FIELD_SEPARATOR,
          custom_order:               {},
          enable_export_to_csv:       Defaults::ENABLE_EXPORT_TO_CSV,
          group:                      nil,
          include:                    nil,
          joins:                      nil,
          name:                       Defaults::GRID_NAME,
          order:                      nil,
          order_direction:            Defaults::ORDER_DIRECTION,
          page:                       1,
          page_method_name:           Defaults::PAGE_METHOD_NAME,
          per_page:                   Defaults::PER_PAGE,
          saved_query:                nil,
          total_entries:              nil,
          with_paginated_resultset:   nil,
          with_resultset:             nil
        }
      rescue NameError
        raise NameError.new('A constant is missing in wice_grid_config.rb: ' + $!.message +
          '. This can happen when you upgrade the WiceGrid to a newer version with a new configuration constant. ' +
          'Add the constant manually or re-run `bundle exec rails g wice_grid:install`.')
      end
      # validate parameters
      opts.assert_valid_keys(@options.keys)

      @options.merge!(opts)
      @export_to_csv_enabled = @options[:enable_export_to_csv]
      @csv_file_name = @options[:csv_file_name]
      @csv_field_separator = @options[:csv_field_separator]

      case @name = @options[:name]
      when String
      when Symbol
        @name = @name.to_s
      else
        raise WiceGridArgumentError.new("name of the grid should be a string or a symbol")
      end
      raise WiceGridArgumentError.new("name of the grid can only contain alphanumeruc characters") unless @name =~ /^[a-zA-Z\d_]*$/

      @table_column_matrix = TableColumnMatrix.new
      @table_column_matrix.default_model_class = @klass

      @ar_options = {}
      @status = HashWithIndifferentAccess.new

      if @options[:order]
        @options[:order]           = @options[:order].to_s
        @options[:order_direction] = @options[:order_direction].to_s

        @status[:order_direction]  = @options[:order_direction]
        @status[:order]            = @options[:order]

      end
      @status[:per_page]      = @options[:per_page]
      @status[:page]          = @options[:page]
      @status[:conditions]    = @options[:conditions]
      @status[:f]             = @options[:f]

      process_loading_query
      process_params

      @ar_options_formed = false

    end

    # A block executed from within the plugin to process records of the current page.
    # The argument to the callback is the array of the records. See the README for more details.
    def with_paginated_resultset(&callback)
      @options[:with_paginated_resultset] = callback
    end

    # A block executed from within the plugin to process all records browsable through
    # all pages with the current filters. The argument to
    # the callback is a lambda object which returns the list of records when called. See the README for the explanation.
    def with_resultset(&callback)
      @options[:with_resultset] = callback
    end

    def process_loading_query #:nodoc:
      @saved_query = nil
      if params[name] && params[name][:q]
        @saved_query = load_query(params[name][:q])
        params[name].delete(:q)
      elsif @options[:saved_query]
        if @options[:saved_query].is_a? ActiveRecord::Base
          @saved_query = @options[:saved_query]
        else
          @saved_query = load_query(@options[:saved_query])
        end
      else
        return
      end

      unless @saved_query.nil?
        params[name] = HashWithIndifferentAccess.new if params[name].blank?
        [:f, :order, :order_direction].each do |key|
          if @saved_query.query[key].blank?
            params[name].delete(key)
          else
            params[name][key] = @saved_query.query[key]
          end
        end
      end
    end

    def process_params  #:nodoc:
      if this_grid_params
        @status.merge!(this_grid_params)
        @status.delete(:export) unless self.export_to_csv_enabled
      end
    end

    def declare_column(column_name, model, custom_filter_active, table_alias, filter_type)  #:nodoc:
      if model # this is an included table
        column = @table_column_matrix.get_column_by_model_class_and_column_name(model, column_name)
        raise WiceGridArgumentError.new("Column '#{column_name}' is not found in table '#{model.table_name}'!") if column.nil?
        main_table = false
        table_name = model.table_name
      else
        column = @table_column_matrix.get_column_in_default_model_class_by_column_name(column_name)
        if column.nil?
          raise WiceGridArgumentError.new("Column '#{column_name}' is not found in table '#{@klass.table_name}'! " +
            "If '#{column_name}' belongs to another table you should declare it in :include or :join when initialising " +
            "the grid, and specify :model in column declaration.")
        end
        main_table = true
        table_name = @table_column_matrix.default_model_class.table_name
      end

      if column
        conditions_generator = ActiveRecordColumnWrapper.new(column, @status[:f], main_table, table_alias, custom_filter_active, filter_type)
        conditions, current_parameter_name = conditions_generator.wg_initialize_request_parameters

        if @status[:f] && conditions.blank?
          @status[:f].delete(current_parameter_name)
        end

        @table_column_matrix.add_condition(column, conditions)
        [column, table_name , main_table]
      else
        nil
      end
    end

    def form_ar_options(opts = {})  #:nodoc:

      return if @ar_options_formed
      @ar_options_formed = true unless opts[:forget_generated_options]

      # validate @status[:order_direction]
      @status[:order_direction] = case @status[:order_direction]
      when /desc/i
        'desc'
      when /asc/i
        'asc'
      else
        ''
      end

      # conditions
      # do not delete for a while
      # https://github.com/leikind/wice_grid/issues/144
      # if @table_column_matrix.generated_conditions.size == 0
      #   @status.delete(:f)
      # end

      @ar_options[:conditions] = klass.send(:merge_conditions, @status[:conditions], * @table_column_matrix.conditions )

      # conditions processed

      if (! opts[:skip_ordering]) && ! @status[:order].blank?
        @ar_options[:order] = add_custom_order_sql(complete_column_name(@status[:order]))

        @ar_options[:order] += ' ' + @status[:order_direction]
      end

      @ar_options[:joins]   = @options[:joins]
      @ar_options[:include] = @options[:include]
      @ar_options[:group]   = @options[:group]

      if self.output_html?
        @ar_options[:per_page]      = @status[:per_page]
        @ar_options[:page]          = @status[:page]

        if (show_all_limit = Wice::ConfigurationProvider.value_for(:SHOW_ALL_ALLOWED_UP_TO, strict: false)) && all_record_mode?
          if do_count > show_all_limit # force-reset SHOW-ALL to pagination
            @status[:pp] = nil
          else
            # no resetting
          end
        end

      end

    end

    def add_references relation
      if @ar_options[:include] && relation.respond_to?(:references)
        refs = [@ar_options[:include]] unless @ar_options[:include].is_a?(Array)
        relation =  relation.references(* @ar_options[:include])
      end
      relation
    end

    # TO DO: what to do with other @ar_options values?
    def read  #:nodoc:
      form_ar_options
      @klass.unscoped do
        @resultset = if self.output_csv? || all_record_mode?
          relation = @relation.
            includes(@ar_options[:include]).
            joins(   @ar_options[:joins]).
            order(   @ar_options[:order]).
            group(   @ar_options[:group]).
            where(   @ar_options[:conditions])
          relation = add_references relation

          relation
        else
          # p @ar_options
          relation = @relation.
            send(    @options[:page_method_name], @ar_options[:page]).
            per(     @ar_options[:per_page]).
            includes(@ar_options[:include]).
            joins(   @ar_options[:joins]).
            order(   @ar_options[:order]).
            group(   @ar_options[:group]).
            where(   @ar_options[:conditions])

          relation = add_references relation

          relation
        end
      end
      invoke_resultset_callbacks
    end

    # core workflow methods END

    # Getters

    def filter_params(view_column)  #:nodoc:
      column_name = view_column.attribute_name_fully_qualified_for_all_but_main_table_columns
      if @status[:f] && @status[:f][column_name]
        @status[:f][column_name]
      else
        {}
      end
    end

    def resultset  #:nodoc:
      self.read unless @resultset # database querying is late!
      @resultset
    end

    def each   #:nodoc:
      self.read unless @resultset # database querying is late!
      @resultset.each do |r|
        yield r
      end
    end

    def ordered_by?(column)  #:nodoc:
      return nil if @status[:order].blank?
      if column.main_table && ! offs = @status[:order].index('.')
        @status[:order] == column.attribute
      else
        @status[:order] == column.table_alias_or_table_name + '.' + column.attribute
      end
    end

    def ordered_by  #:nodoc:
      @status[:order]
    end

    def order_direction  #:nodoc:
      @status[:order_direction]
    end

    def filtering_on?  #:nodoc:
      not @status[:f].blank?
    end

    def filtered_by  #:nodoc:
      @status[:f].nil? ? [] : @status[:f].keys
    end

    def filtered_by?(view_column)  #:nodoc:
      @status[:f].nil? ? false : @status[:f].has_key?(view_column.attribute_name_fully_qualified_for_all_but_main_table_columns)
    end

    def get_state_as_parameter_value_pairs(including_saved_query_request = false) #:nodoc:
      res = []
      unless status[:f].blank?
        Wice::WgHash.parameter_names_and_values(status[:f], [name, 'f']).collect do |param_name, value|
          if value.is_a?(Array)
            param_name_ar = param_name + '[]'
            value.each do |v|
              res << [param_name_ar, v]
            end
          else
            res << [param_name, value]
          end
        end
      end

      if including_saved_query_request && @saved_query
        res << ["#{name}[q]", @saved_query.id ]
      end

      [:order, :order_direction].select{|parameter|
        status[parameter]
      }.collect do |parameter|
        res << ["#{name}[#{parameter}]", status[parameter] ]
      end

      res
    end

    def count  #:nodoc:
      form_ar_options(skip_ordering: true, forget_generated_options: true)
      do_count
    end

    def do_count
      @relation.count(
        conditions: @ar_options[:conditions],
        joins:      @ar_options[:joins],
        include:    @ar_options[:include],
        group:      @ar_options[:group]
      )
    end

    alias_method :size, :count

    def empty?  #:nodoc:
      self.count == 0
    end

    # with this variant we get even those values which do not appear in the resultset
    def distinct_values_for_column(column)  #:nodoc:
      res = column.model.select("distinct #{column.name}").order("#{column.name} asc").collect{|ar|
        ar[column.name]
      }.reject{|e| e.blank?}.map{|i|[i,i]}
    end

    def distinct_values_for_column_in_resultset(messages)  #:nodoc:
      uniq_vals = Set.new

      resultset_without_paging_without_user_filters.each do |ar|
        v = ar.deep_send(*messages)
        uniq_vals << v unless v.nil?
      end
      return uniq_vals.to_a.map{|i|
        if i.is_a?(Array) && i.size == 2
          i
        elsif i.is_a?(Hash) && i.size == 1
          i.to_a.flatten
        else
          [i,i]
        end
      }.sort{|a,b| a[0]<=>b[0]}
    end

    def output_csv? #:nodoc:
      @status[:export] == 'csv'
    end

    def output_html? #:nodoc:
      @status[:export].blank?
    end

    def all_record_mode? #:nodoc:
      @status[:pp]
    end

    def dump_status #:nodoc:
      "   params: #{params[name].inspect}\n"  +
      "   status: #{@status.inspect}\n" +
      "   ar_options #{@ar_options.inspect}\n"
    end

    # Returns the list of objects browsable through all pages with the current filters.
    # Should only be called after the +grid+ helper.
    def all_pages_records
      raise WiceGridException.new("all_pages_records can only be called only after the grid view helper") unless self.view_helper_finished
      resultset_without_paging_with_user_filters
    end

    # Returns the list of objects displayed on current page. Should only be called after the +grid+ helper.
    def current_page_records
      raise WiceGridException.new("current_page_records can only be called only after the grid view helper") unless self.view_helper_finished
      @resultset
    end

    protected

    def invoke_resultset_callback(callback, argument) #:nodoc:
      case callback
      when Proc
        callback.call(argument)
      when Symbol
        @controller.send(callback, argument)
      end
    end

    def invoke_resultset_callbacks #:nodoc:
      invoke_resultset_callback(@options[:with_paginated_resultset], @resultset)
      invoke_resultset_callback(@options[:with_resultset], self.active_relation_for_resultset_without_paging_with_user_filters)
    end

    def add_custom_order_sql(fully_qualified_column_name) #:nodoc:
      custom_order = if @options[:custom_order].has_key?(fully_qualified_column_name)
        @options[:custom_order][fully_qualified_column_name]
      else
        if view_column = @renderer[fully_qualified_column_name]
          view_column.custom_order
        else
          nil
        end
      end

      if custom_order.blank?
        if ActiveRecord::ConnectionAdapters.const_defined?(:SQLite3Adapter) && ActiveRecord::Base.connection.is_a?(ActiveRecord::ConnectionAdapters::SQLite3Adapter)
          fully_qualified_column_name.strip.split('.').map{|chunk| ActiveRecord::Base.connection.quote_table_name(chunk)}.join('.')
        else
          ActiveRecord::Base.connection.quote_table_name(fully_qualified_column_name.strip)
        end
      else
        if custom_order.is_a? String
          custom_order.gsub(/\?/, fully_qualified_column_name)
        elsif custom_order.is_a? Proc
          custom_order.call(fully_qualified_column_name)
        else
          raise WiceGridArgumentError.new("invalid custom order #{custom_order.inspect}")
        end
      end
    end

    def complete_column_name(col_name)  #:nodoc:
      if col_name.index('.') # already has a table name
        col_name
      else # add the default table
        "#{@klass.table_name}.#{col_name}"
      end
    end

    def params  #:nodoc:
      @controller.params
    end

    def this_grid_params  #:nodoc:
      params[name]
    end

    def resultset_without_paging_without_user_filters  #:nodoc:
      form_ar_options
      @klass.unscoped do
        relation = @relation.joins(@ar_options[:joins]).
          includes(@ar_options[:include]).
          group(@ar_options[:group]).
          where(@options[:conditions])

        relation = add_references relation

        relation
      end
    end

    # not used right now
    # def count_resultset_without_paging_without_user_filters  #:nodoc:
    #   form_ar_options
    #   @klass.unscoped do
    #     @relation.count(
    #       joins:      @ar_options[:joins],
    #       include:    @ar_options[:include],
    #       group:      @ar_options[:group],
    #       conditions: @options[:conditions]
    #     )
    #   end
    # end

    def resultset_without_paging_with_user_filters  #:nodoc:
      @klass.unscoped do
        active_relation_for_resultset_without_paging_with_user_filters.to_a
      end
    end

    def active_relation_for_resultset_without_paging_with_user_filters  #:nodoc:
      form_ar_options
      relation = nil
      @klass.unscoped do
        relation = @relation.
          where(@ar_options[:conditions]).
          joins(@ar_options[:joins]).
          includes(@ar_options[:include]).
          order(@ar_options[:order])

        relation = add_references relation
      end
      relation
    end

    def load_query(query_id) #:nodoc:
      @query_store_model ||= Wice::get_query_store_model
      query = @query_store_model.find_by_id_and_grid_name(query_id, self.name)
      Wice::log("Query with id #{query_id} for grid '#{self.name}' not found!!!") if query.nil?
      query
    end

  end

  # routines called from WiceGridExtentionToActiveRecordColumn (ActiveRecord::ConnectionAdapters::Column) or ConditionsGeneratorColumn classes
  module GridTools   #:nodoc:
    class << self
      def special_value(str)   #:nodoc:
        str =~ /^\s*(not\s+)?null\s*$/i
      end

      # create a Time instance out of parameters
      def params_2_datetime(par)   #:nodoc:
        return nil if par.blank?
        params =  [par[:year], par[:month], par[:day], par[:hour], par[:minute]].collect{|v| v.blank? ? nil : v.to_i}
        begin
          Time.local(*params)
        rescue ArgumentError, TypeError
          nil
        end
      end

      # create a Date instance out of parameters
      def params_2_date(par)   #:nodoc:
        return nil if par.blank?
        params =  [par[:year], par[:month], par[:day]].collect{|v| v.blank? ? nil : v.to_i}
        begin
          Date.civil(*params)
        rescue ArgumentError, TypeError
          nil
        end
      end

    end
  end

end


text:
namespace Splunk.Client
{
    using System.Runtime.Serialization;

    /// <summary>
    /// Specifies whether to track the actions triggered by a scheduled search.
    /// </summary>
    public enum AlertTrack
    {
        /// <summary>
        /// Determine whether to track based on the tracking setting of each
        /// action. Do not track scheduled searches that always trigger
        /// actions.
        /// </summary>
        [EnumMember(Value = "auto")]
        Automatic,

        /// <summary>
        /// Force tracking.
        /// </summary>
        [EnumMember(Value = "1")]
        True,

        /// <summary>
        /// Disable tracking.
        /// </summary>
        [EnumMember(Value = "0")]
        False
    }
}

redpajama_set_name: RedPajamaGithub


text:
var ActionButton = require('../utils/button');
var RESTWrapper = require('../utils/REST');
var state = require('../state');

module.exports = {
    template: require('./snippets-list.template.html'),

    data: function() {
        return {
            parsedData: {
                columns: null,
                data: null,
                title: 'Snippets List',
            },
            state: state,
            request: null
        };
    },

    attached: function() {
        this.request = new RESTWrapper(this, 'api/snippets', this.state.token);
        this.init();
    },

    methods: {
        init: function() {
            this.request.getAll(this.initData.bind(this));
        },

        initButtons: function() {
            var actionsList = [];
            var button;

            button = new ActionButton();
            button.initButton('Create', ['blue', 'left'], this.add);
            actionsList.push(button);

            button = new ActionButton();
            button.initButton('Delete Selected', ['red', 'left'], this.delete);
            actionsList.push(button);

            this.$dispatch('buttons-update', actionsList);
        },

        initData: function(responseData) {
            this.parsedData.data = responseData.data;
            this.parsedData.columns = [];
            this.initButtons();
            if (this.parsedData.data.length >= 1) {
                for (var key in this.parsedData.data[0]) this.parsedData.columns.push(key);
                for (var item in this.parsedData.data) this.parsedData.data[item].$set('selected', false);
            }
        },

        add: function() {
            this.$route.router.go('/snippets/create');
        },

        delete: function() {
            var selectedIDs = [];
            for (var item in this.parsedData.data)
                if (this.parsedData.data[item].selected)
                    selectedIDs.push(this.parsedData.data[item].id);
            if (selectedIDs.length == 0) this.$dispatch('warning-message', 'You haven\'t selected any items to be deleted. Select the items you want to delete by clicking on the checkbox next to them.');
            else if (selectedIDs.length > 50) this.$dispatch('warning-message', 'You are not allowed to delete more than 50 items at one time.');
            else this.request.delete(selectedIDs.join(','), function() {
                    this.$dispatch('deleted');
                    this.init();
                }.bind(this));
        },

        back: function() {
            this.$dispatch('back');
        }
    },

    components: {
        'paginated-list': require('../components/paginatedList')
    }
};


text:
package com.wsn.chapter18javaio;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.BitSet;

/**
 * Created by Doun on 2017/8/21.
 *
 * 23
 * Create and test a utility method to print the contents
 * of a CharBuffer up to the point where the characters
 * are no longer printable.
 *
 * 从习题答案抄的,看完答案才理解题意。。。
 */

public class Practise23 {
    static BitSet isPrintable = new BitSet(127);
    static String encoding =
            System.getProperty("file.encoding");

    static {
// Assume an encoding that obeys ASCII eg.ISO-8859-1.
// Characters 32 to 127 represent printable characters.
        for (int i = 32; i <= 127; i++)
            isPrintable.set(i);
    }

    // Set the position to the last printable character
    public static void setPrintableLimit(CharBuffer cb) {
        cb.rewind();
        while (isPrintable.get(cb.get())) ;
        cb.limit(cb.position() - 1);
        cb.rewind();
    }

    public static void main(String[] args) {
        System.out.println("Default Encoding is: " + encoding);
        CharBuffer buffer =
                ByteBuffer.allocate(16).asCharBuffer();
        buffer.put("ABCDE" + (char) 0x01 + "FG");
        buffer.rewind();
        System.out.println(buffer); // Print everything
        setPrintableLimit(buffer);
        System.out.println(buffer); // Print printable
    }

}


text:
/**
 * @file        test/common/protocols/admin/listrequest.cpp
 * @author      Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
 * @version     1.0
 * @brief       Tests for Cynara::ListRequest usage in Cynara::ProtocolAdmin
 */

#include <gtest/gtest.h>

#include <protocol/ProtocolAdmin.h>
#include <request/ListRequest.h>

#include <RequestTestHelper.h>
#include <TestDataCollection.h>

namespace {

template<>
void compare(const Cynara::ListRequest &req1, const Cynara::ListRequest &req2) {
    EXPECT_EQ(req1.bucket(), req2.bucket());
    EXPECT_EQ(req1.filter(), req2.filter());
}

} /* namespace anonymous */

using namespace Cynara;
using namespace RequestTestHelper;
using namespace TestDataCollection;

/* *** compare by objects test cases *** */

TEST(ProtocolAdmin, ListRequest01) {
    auto request = std::make_shared<ListRequest>(Buckets::empty, Keys::k_nun, SN::min);
    auto protocol = std::make_shared<ProtocolAdmin>();
    testRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequest02) {
    auto request = std::make_shared<ListRequest>(Buckets::not_empty, Keys::k_cup, SN::min_1);
    auto protocol = std::make_shared<ProtocolAdmin>();
    testRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequest03) {
    auto request = std::make_shared<ListRequest>(Buckets::empty, Keys::k_www, SN::min_2);
    auto protocol = std::make_shared<ProtocolAdmin>();
    testRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequest04) {
    auto request = std::make_shared<ListRequest>(Buckets::not_empty, Keys::k_wuw, SN::max);
    auto protocol = std::make_shared<ProtocolAdmin>();
    testRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequest05) {
    auto request = std::make_shared<ListRequest>(Buckets::empty, Keys::k_aaa, SN::max_1);
    auto protocol = std::make_shared<ProtocolAdmin>();
    testRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequest06) {
    auto request = std::make_shared<ListRequest>(Buckets::not_empty, Keys::k_wua, SN::max_2);
    auto protocol = std::make_shared<ProtocolAdmin>();
    testRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequest07) {
    auto request = std::make_shared<ListRequest>(Buckets::empty, Keys::k_nua, SN::mid);
    auto protocol = std::make_shared<ProtocolAdmin>();
    testRequest(request, protocol);
}

/* *** compare by serialized data test cases *** */

TEST(ProtocolAdmin, ListRequestBinary01) {
    auto request = std::make_shared<ListRequest>(Buckets::empty, Keys::k_nun, SN::min);
    auto protocol = std::make_shared<ProtocolAdmin>();
    binaryTestRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequestBinary02) {
    auto request = std::make_shared<ListRequest>(Buckets::not_empty, Keys::k_cup, SN::min_1);
    auto protocol = std::make_shared<ProtocolAdmin>();
    binaryTestRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequestBinary03) {
    auto request = std::make_shared<ListRequest>(Buckets::empty, Keys::k_www, SN::min_2);
    auto protocol = std::make_shared<ProtocolAdmin>();
    binaryTestRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequestBinary04) {
    auto request = std::make_shared<ListRequest>(Buckets::not_empty, Keys::k_wuw, SN::max);
    auto protocol = std::make_shared<ProtocolAdmin>();
    binaryTestRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequestBinary05) {
    auto request = std::make_shared<ListRequest>(Buckets::empty, Keys::k_aaa, SN::max_1);
    auto protocol = std::make_shared<ProtocolAdmin>();
    binaryTestRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequestBinary06) {
    auto request = std::make_shared<ListRequest>(Buckets::not_empty, Keys::k_wua, SN::max_2);
    auto protocol = std::make_shared<ProtocolAdmin>();
    binaryTestRequest(request, protocol);
}

TEST(ProtocolAdmin, ListRequestBinary07) {
    auto request = std::make_shared<ListRequest>(Buckets::empty, Keys::k_nua, SN::mid);
    auto protocol = std::make_shared<ProtocolAdmin>();
    binaryTestRequest(request, protocol);
}


text:
using System;
using AgathaSample.Services.Security;
using Ninject;

namespace AgathaSample.Services
{
    public class KernelContainer
    {
        private static IKernel _kernel;

        public static IKernel Kernel
        {
            get
            {
                if (_kernel == null)
                {
                    CreateDefaultKernel();
                }
                return _kernel;
            }
            set
            {
                if (_kernel != null)
                {
                    throw new NotSupportedException("Kernel has already been set!");
                }
                _kernel = value;
            }
        }

        private static void CreateDefaultKernel()
        {
            _kernel = new StandardKernel();
            _kernel.Bind<IUserValidator>().To<DummyUserValidator>();
        }
    }
}


text:
set(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
  "E:/Solo/Solo/main.cpp" "E:/Solo/Solo/cmake-build-debug/CMakeFiles/Solo.dir/main.cpp.obj"
  )
set(CMAKE_CXX_COMPILER_ID "GNU")

# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
  )

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  )

# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FFLTask.BLL.Entity;

namespace FFLTask.BLL.NHMap.Account
{
    class AuthorizationMap : EntityMap<Authorization>
    {
        public AuthorizationMap()
        {
            References(m => m.User).ForeignKey("FK_Auth_User");
            References(m => m.Project).ForeignKey("FK_Auth_Project");
            Map(m => m.IsFounder);
            Map(m => m.IsPublisher);
            Map(m => m.IsOwner);
            Map(m => m.IsAdmin);

            Cache.ReadWrite();
        }
    }
}


text:
<?php

namespace Kunstmaan\LeadGenerationBundle\Tests\DependencyInjection;

use Kunstmaan\LeadGenerationBundle\DependencyInjection\Configuration;
use Matthias\SymfonyConfigTest\PhpUnit\ConfigurationTestCaseTrait;
use PHPUnit\Framework\TestCase;

/**
 * Class ConfigurationTest
 */
class ConfigurationTest extends TestCase
{
    use ConfigurationTestCaseTrait;

    /**
     * @return \Symfony\Component\Config\Definition\ConfigurationInterface
     */
    protected function getConfiguration()
    {
        return new Configuration();
    }

    public function testConfigGeneratesAsExpected()
    {
        $array = [
            'popup_types' => ['one element'],
            'debug' => true,
        ];

        $this->assertProcessedConfigurationEquals([$array], $array);
    }

    public function testConfigDoesntGenerateAsExpected()
    {
        $array = [];

        $this->assertPartialConfigurationIsInvalid([$array], 'popup_types');
    }
}


text:
package tom.hui.ren.core;

import android.support.v7.widget.RecyclerView;

import com.google.android.agera.Result;
import com.google.android.agera.Supplier;
import com.google.android.agera.Updatable;

/**
 * @author renhui
 * @date 16-10-28
 * @desc 抽象的recycle item与adapter之间的helper
 */

public abstract class BaseAdapterHelper<T> implements Supplier<Result<T>>, Updatable {
    protected RecyclerView.Adapter mAdapter;
    protected int                  mIndex;
    protected BaseView             mBaseView;

    public abstract BaseAdapterHelper<T> with(RecyclerView.ViewHolder holder);

    public abstract void load(T object);

    public abstract BaseAdapterHelper<T> on(RecyclerView.Adapter adapter);

    public abstract BaseAdapterHelper<T> indexOf(int position);

    public abstract BaseAdapterHelper<T> inView(BaseView view);
}


text:
package org.apache.nifi.web.api.dto.action.details;

import javax.xml.bind.annotation.XmlType;

/**
 * Configuration details for an Action.
 */
@XmlType(name = "configureDetails")
public class ConfigureDetailsDTO extends ActionDetailsDTO {

    private String name;
    private String previousValue;
    private String value;

    /**
     * The name of the property that was modified.
     *
     * @return
     */
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * The previous value.
     *
     * @return
     */
    public String getPreviousValue() {
        return previousValue;
    }

    public void setPreviousValue(String previousValue) {
        this.previousValue = previousValue;
    }

    /**
     * The new value.
     *
     * @return
     */
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}


text:
class WithoutValidationModel
  include Hanami::Validations

  validations do
    optional(:email)
  end
end


text:
	  ID
	  Barangay
	  Municipality

	  {{barangay.barangay_id>0?barangay.barangay_id:''}}
	  {{barangay.barangay_description}}
	  {{barangay.municipality_description}}

			<button type="button" class="btn btn-default btn-sm" ng-click="editItem(barangay)"></button>
			<button type="button" class="btn btn-default btn-sm" ng-click="delItem(barangay)" ng-show="accountProfile.pages[module]['delete']"></button>


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _classnames = require("classnames");

var _classnames2 = _interopRequireDefault(_classnames);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var BlockContent = function (_Component) {
  _inherits(BlockContent, _Component);

  function BlockContent() {
    _classCallCheck(this, BlockContent);

    return _possibleConstructorReturn(this, (BlockContent.__proto__ || Object.getPrototypeOf(BlockContent)).apply(this, arguments));
  }

  _createClass(BlockContent, [{
    key: "render",
    value: function render() {
      var className = (0, _classnames2.default)("block__content", _defineProperty({}, "block__content--" + this.props.className, this.props.className));

      return _react2.default.createElement(
        "div",
        { className: className },
        this.props.children
      );
    }
  }]);

  return BlockContent;
}(_react.Component);

exports.default = BlockContent;


text:
package com.vityuk.ginger.provider.plural.impl;

/**
 * Plural rules for Kako language.
 *
 * @author Andriy Vityuk
 */
public final class PluralRule_kkj extends PluralRule_1_0n {
}


text:
module Kramdown
  module Parser
    class Kramdown

      EOB_MARKER = /^\^\s*?\n/

      # Parse the EOB marker at the current location.
      def parse_eob_marker
        @src.pos += @src.matched_size
        @tree.children << new_block_el(:eob)
        true
      end
      define_parser(:eob_marker, EOB_MARKER)

    end
  end
end


text:
START_ATF_NAMESPACE
    #pragma pack(push, 2)
    struct  _TOOL_COL_LEAF
    {
        unsigned int start_id;
        unsigned __int16 line_num;
    };
    #pragma pack(pop)
END_ATF_NAMESPACE


text:
package org.keycloak.migration.migrators;

import org.jboss.logging.Logger;
import org.keycloak.migration.MigrationProvider;
import org.keycloak.migration.ModelVersion;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.RealmRepresentation;

/**
 * @author Marek Posolda
 */
public class MigrateTo4_6_0 implements Migration {

    public static final ModelVersion VERSION = new ModelVersion("4.6.0");

    private static final Logger LOG = Logger.getLogger(MigrateTo4_6_0.class);

    @Override
    public ModelVersion getVersion() {
        return VERSION;
    }

    @Override
    public void migrate(KeycloakSession session) {
        session.realms().getRealmsStream().forEach(realm -> migrateRealm(session, realm, false));
    }

    @Override
    public void migrateImport(KeycloakSession session, RealmModel realm, RealmRepresentation rep, boolean skipUserDependent) {
        migrateRealm(session, realm, true);
    }

    protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean json) {
        MigrationProvider migrationProvider = session.getProvider(MigrationProvider.class);

        // Create "roles" and "web-origins" clientScopes
        ClientScopeModel rolesScope = migrationProvider.addOIDCRolesClientScope(realm);
        ClientScopeModel webOriginsScope = migrationProvider.addOIDCWebOriginsClientScope(realm);

        LOG.debugf("Added '%s' and '%s' default client scopes", rolesScope.getName(), webOriginsScope.getName());

        // Assign "roles" and "web-origins" clientScopes to all the OIDC clients
        realm.getClientsStream()
                .filter(MigrationUtils::isOIDCNonBearerOnlyClient)
                .forEach(c -> {
                    c.addClientScope(rolesScope, true);
                    c.addClientScope(webOriginsScope, true);
                });

        LOG.debugf("Client scope '%s' assigned to all the clients", rolesScope.getName());
    }
}


text:
with (open("bla.txt")):
    pass

with (open("bla.txt")), (open("bla.txt")):
    pass

with (open("bla.txt") as f):
    pass

# Remove brackets within alias expression
with (open("bla.txt")) as f:
    pass

# Remove brackets around one-line context managers
with (open("bla.txt") as f, (open("x"))):
    pass

with ((open("bla.txt")) as f, open("x")):
    pass

with (CtxManager1() as example1, CtxManager2() as example2):
    ...

# Brackets remain when using magic comma
with (CtxManager1() as example1, CtxManager2() as example2,):
    ...

# Brackets remain for multi-line context managers
with (CtxManager1() as example1, CtxManager2() as example2, CtxManager2() as example2, CtxManager2() as example2, CtxManager2() as example2):
    ...

# Don't touch assignment expressions
with (y := open("./test.py")) as f:
    pass

# Deeply nested examples
# N.B. Multiple brackets are only possible
# around the context manager itself.
# Only one brackets is allowed around the
# alias expression or comma-delimited context managers.
with (((open("bla.txt")))):
    pass

with (((open("bla.txt")))), (((open("bla.txt")))):
    pass

with (((open("bla.txt")))) as f:
    pass

with ((((open("bla.txt")))) as f):
    pass

with ((((CtxManager1()))) as example1, (((CtxManager2()))) as example2):
    ...

# output
with open("bla.txt"):
    pass

with open("bla.txt"), open("bla.txt"):
    pass

with open("bla.txt") as f:
    pass

# Remove brackets within alias expression
with open("bla.txt") as f:
    pass

# Remove brackets around one-line context managers
with open("bla.txt") as f, open("x"):
    pass

with open("bla.txt") as f, open("x"):
    pass

with CtxManager1() as example1, CtxManager2() as example2:
    ...

# Brackets remain when using magic comma
with (
    CtxManager1() as example1,
    CtxManager2() as example2,
):
    ...

# Brackets remain for multi-line context managers
with (
    CtxManager1() as example1,
    CtxManager2() as example2,
    CtxManager2() as example2,
    CtxManager2() as example2,
    CtxManager2() as example2,
):
    ...

# Don't touch assignment expressions
with (y := open("./test.py")) as f:
    pass

# Deeply nested examples
# N.B. Multiple brackets are only possible
# around the context manager itself.
# Only one brackets is allowed around the
# alias expression or comma-delimited context managers.
with open("bla.txt"):
    pass

with open("bla.txt"), open("bla.txt"):
    pass

with open("bla.txt") as f:
    pass

with open("bla.txt") as f:
    pass

with CtxManager1() as example1, CtxManager2() as example2:
    ...


text:
<?php

namespace Shared\FileField;

use Nova\Database\ORM\Model;
use Nova\Support\Facades\File;
use Nova\Support\Facades\Log;
use Nova\Support\Str;

use Shared\FileField\FileField;

use Symfony\Component\HttpFoundation\File\UploadedFile;

trait HasFileFieldsTrait
{
    /**
     * Listen to ORM events.
     *
     * Cleanup properly on update and delete
     */
    public static function boot()
    {
        parent::boot();

        static::saving(function (Model $model)
        {
            $files = (array) $model->files;

            if (count($files) > 0) {
                foreach ($files as $key => $options) {
                    $filePath = $model->getOriginal($key);

                    if (is_null($filePath)) continue;

                    $fileField = $model->getAttributeValue($key);

                    if ($fileField->path == $filePath) {
                        continue;
                    }

                    try {
                        File::delete($filePath);
                    }

                    // Catch all exceptions.
                    catch (Exception $e) {
                        Log::error($e->getMessage());
                    }
                }
            }
        });

        static::deleting(function (Model $model)
        {
            // Don't delete the file if you are doing a soft delete!
            if (! method_exists($model, 'restore') || $model->forceDeleting) {
                $files = (array) $model->files;

                if (count($files) > 0) {
                    foreach ($files as $key => $options) {
                        $file = $model->getAttribute($key);

                        $file->delete();
                    }
                }
            }
        });
    }

    /**
     * Instead of database column, return the FileField object.
     *
     * @param $key
     * @return FileField
     */
    public function getAttributeValue($key)
    {
        if (in_array($key, array_keys($this->files))) {
            return new FileField($this, $key);
        }

        return parent::getAttributeValue($key);
    }

    /**
     * Determine if it is a URL upload or file upload.
     * Upload the file and set file name
     *
     * @param $key
     * @param $value
     */
    public function setAttribute($key, $value)
    {
        if (! in_array($key, array_keys($this->files)) || is_null($value)) {
            parent::setAttribute($key, $value);
        }

        // Handle the values which are UploadedFile instances.
        else if ($value instanceof UploadedFile) {
            $name = Str::slug(pathinfo($value->getClientOriginalName(), PATHINFO_FILENAME));

            $extension = $value->getClientOriginalExtension();

            $fileName = join('.', array($name, $extension));

            //
            $fileField = new FileField($this, $key, $fileName);

            $this->attributes[$key] = $fileField->uploadFile($value);
        }

        // Handle the string values - files specified by path.
        else if (is_string($value)) {
            if (! Str::startsWith($value, 'raw:')) {
                $name = pathinfo($value, PATHINFO_FILENAME);

                $extension = pathinfo($value, PATHINFO_EXTENSION);

                $fileName = join('.', array($name, $extension));

                //
                $fileField = new FileField($this, $key, $fileName);

                $value = $fileField->copyLocal($value);
            }

            // A raw file path was given as value.
            else {
                $value = substr($value, 4);
            }

            $this->attributes[$key] = $value;
        }
    }
}


text:
![Testing - main](https://github.com/TRI-AMDD/piro/workflows/Testing%20-%20main/badge.svg)
![Linting](https://github.com/TRI-AMDD/piro/workflows/Linting/badge.svg)
[![Coverage Status](https://coveralls.io/repos/github/TRI-AMDD/piro/badge.svg?branch=test)](https://coveralls.io/github/TRI-AMDD/piro?branch=test)

_piro_ is a recommendation system for navigation and planning of synthesis of
inorganic materials based on classical nucleation theory
and semi-empirical, data-driven approximations to its parts. Currently it
works with Materials Project data via its Rester API.

- _piro_ creates synthesis reaction planning plots for target polymorphs under a specific set of thermodynamic conditions and a precursor library,
where favorable routes are those that are (nearly) Pareto optimal in terms of two metrics: nucleation barrier and phase-selection.

- _piro_ allows retrosynthetic analysis of target inorganic materials to generate a synthesis reaction tree.
(i.e. laying out the reaction pathways necessary to arrive at the target from practical/purchasable reagents/starting materials)

- _piro_ supports generation of interactive plots and a web-UI for easy-navigation.

Tutorial jupyter notebooks showing how to use _piro_ locally are provided in the [notebooks](piro/notebooks) folder.

## Prerequisites

### Python 3.7
 - `piro` uses Python 3.7.  If you wish to develop or run a local server, we recommend following the Docker instructions below to create your own `piro` container instead of configuring your local environment.

### Pymatgen API key
 - `piro` has a dependency on `pymatgen` which requires you to generate an API key.  Go [here](https://materialsproject.org/open) and follow the instructions to generate your API key.
 - Use the API key by either
    - A) adding the environment variable MAPI_KEY to your current environment
    ```
    # for example in the terminal
    export MAPI_KEY=<your API key>
    ```
    - B) using pymatgen's command line to set a global key (note: it's PMG_MAPI_KEY instead of just MAPI_KEY)
    ```
    pmg config --add PMG_MAPI_KEY <your API key>
    ```

### Access to MongoDB Cached Database (optional)
 - Once you get the credential, set up the environment variable as follow:
      ```
      MONGODB_URI = mongodb://{username}:{password}@{host}:{port}/{database}
      ```
 - If you use conda for your development, you can do like this:
      ```
      conda env config vars set MONGODB_URI="mongodb://{username}:{password}@{host}:{port}/{database}"
      ```
 - You will need to reactive the conda environment so the change will take effective.

## Setup
There are a few options to install and run `piro` on your machine:

###  A) Get `piro` from PyPI
The most recent stable version of `piro` can be installed from [PyPI](https://pypi.org/project/piro/). We recommend installing `piro` in a dedicated environment to avoid any version conflicts for its dependencies.
```
pip install piro
```

###  B) For development, install the source from this repo in development mode
```
python setup.py develop
```

## Piro Module Usage
 - Try out a Jupyter notebook:
    ```
    jupyter notebook
    ```
   See the notebooks in piro/notebooks

## Web app

[README](web/README.md)

## Citation
If you use `piro`, we kindly ask you to cite the following publication:
* Aykol, M., Montoya, J.H., Hummelshøj, J. "Rational Solid-State Synthesis Routes for Inorganic Materials" J. Am. Chem. Soc. (2021): [https://doi.org/10.1021/jacs.1c04888](https://doi.org/10.1021/jacs.1c04888)


text:
namespace RedmineLog.UI
{
    partial class frmSubIssue
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.tbSubject = new System.Windows.Forms.TextBox();
            this.tbDescription = new System.Windows.Forms.TextBox();
            this.btnAccept = new System.Windows.Forms.Button();
            this.cbTracker = new System.Windows.Forms.ComboBox();
            this.cbPriority = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.cbPerson = new System.Windows.Forms.ComboBox();
            this.SuspendLayout();
            //
            // tbSubject
            //
            this.tbSubject.Location = new System.Drawing.Point(12, 22);
            this.tbSubject.Multiline = true;
            this.tbSubject.Name = "tbSubject";
            this.tbSubject.Size = new System.Drawing.Size(308, 30);
            this.tbSubject.TabIndex = 0;
            //
            // tbDescription
            //
            this.tbDescription.Location = new System.Drawing.Point(11, 74);
            this.tbDescription.Multiline = true;
            this.tbDescription.Name = "tbDescription";
            this.tbDescription.Size = new System.Drawing.Size(309, 62);
            this.tbDescription.TabIndex = 1;
            //
            // btnAccept
            //
            this.btnAccept.Location = new System.Drawing.Point(192, 197);
            this.btnAccept.Name = "btnAccept";
            this.btnAccept.Size = new System.Drawing.Size(128, 39);
            this.btnAccept.TabIndex = 2;
            this.btnAccept.Text = "Accept";
            this.btnAccept.UseVisualStyleBackColor = true;
            //
            // cbTracker
            //
            this.cbTracker.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cbTracker.FormattingEnabled = true;
            this.cbTracker.Location = new System.Drawing.Point(12, 162);
            this.cbTracker.Name = "cbTracker";
            this.cbTracker.Size = new System.Drawing.Size(174, 21);
            this.cbTracker.TabIndex = 3;
            //
            // cbPriority
            //
            this.cbPriority.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cbPriority.FormattingEnabled = true;
            this.cbPriority.Location = new System.Drawing.Point(192, 162);
            this.cbPriority.Name = "cbPriority";
            this.cbPriority.Size = new System.Drawing.Size(128, 21);
            this.cbPriority.TabIndex = 5;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(13, 3);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(43, 13);
            this.label1.TabIndex = 6;
            this.label1.Text = "Subject";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 55);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(60, 13);
            this.label2.TabIndex = 7;
            this.label2.Text = "Description";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(12, 146);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(44, 13);
            this.label3.TabIndex = 8;
            this.label3.Text = "Tracker";
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(189, 146);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(38, 13);
            this.label5.TabIndex = 10;
            this.label5.Text = "Priority";
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(11, 197);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(62, 13);
            this.label4.TabIndex = 12;
            this.label4.Text = "Assigned to";
            //
            // cbPerson
            //
            this.cbPerson.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cbPerson.FormattingEnabled = true;
            this.cbPerson.Location = new System.Drawing.Point(11, 213);
            this.cbPerson.Name = "cbPerson";
            this.cbPerson.Size = new System.Drawing.Size(175, 21);
            this.cbPerson.TabIndex = 11;
            //
            // frmSubIssue
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(332, 250);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.cbPerson);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.cbPriority);
            this.Controls.Add(this.cbTracker);
            this.Controls.Add(this.btnAccept);
            this.Controls.Add(this.tbDescription);
            this.Controls.Add(this.tbSubject);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "frmSubIssue";
            this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
            this.Text = "Add sub issue";
            this.TopMost = true;
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label4;
        internal System.Windows.Forms.TextBox tbSubject;
        internal System.Windows.Forms.TextBox tbDescription;
        internal System.Windows.Forms.ComboBox cbTracker;
        internal System.Windows.Forms.ComboBox cbPriority;
        internal System.Windows.Forms.ComboBox cbPerson;
        public System.Windows.Forms.Button btnAccept;
    }
}


text:
<?php

namespace Amadeus\Client\Struct\Ticket\DisplayTSMP;

/**
 * TattooOfTSM
 *
 * @package Amadeus\Client\Struct\Ticket
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class TattooOfTSM
{
    /**
     * @var string|int
     */
    public $uniqueReference;

    /**
     * TattooOfTSM constructor.
     *
     * @param int|string $uniqueReference
     */
    public function __construct($uniqueReference)
    {
        $this->uniqueReference = $uniqueReference;
    }
}


text:
package com.google.devtools.build.android.desugar;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.android.desugar.io.CoreLibraryRewriter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

// TODO(b/134636762): Test override preservation logic somehow (needs to class-load test input)
@RunWith(JUnit4.class)
public class CorePackageRenamerTest {

  @Test
  public void testSymbolRewrite() throws Exception {
    MockClassVisitor out = new MockClassVisitor();
    CorePackageRenamer renamer =
        new CorePackageRenamer(
            out,
            new CoreLibrarySupport(
                new CoreLibraryRewriter(""),
                null,
                ImmutableList.of("java/time/"),
                ImmutableList.of(),
                ImmutableList.of("java/util/A#m->java/time/B"),
                ImmutableList.of(),
                ImmutableList.of(),
                ImmutableList.of()));
    MethodVisitor mv = renamer.visitMethod(0, "test", "()V", null, null);

    mv.visitMethodInsn(
        Opcodes.INVOKESTATIC, "java/time/Instant", "now", "()Ljava/time/Instant;", false);
    assertThat(out.mv.owner).isEqualTo("j$/time/Instant");
    assertThat(out.mv.desc).isEqualTo("()Lj$/time/Instant;");

    // Ignore moved methods but not their descriptors
    mv.visitMethodInsn(
        Opcodes.INVOKESTATIC, "java/util/A", "m", "()Ljava/time/Instant;", false);
    assertThat(out.mv.owner).isEqualTo("java/util/A");
    assertThat(out.mv.desc).isEqualTo("()Lj$/time/Instant;");

    // Ignore arbitrary other methods but not their descriptors
    mv.visitMethodInsn(
        Opcodes.INVOKESTATIC, "other/time/Instant", "now", "()Ljava/time/Instant;", false);
    assertThat(out.mv.owner).isEqualTo("other/time/Instant");
    assertThat(out.mv.desc).isEqualTo("()Lj$/time/Instant;");

    mv.visitFieldInsn(
        Opcodes.GETFIELD, "other/time/Instant", "now", "Ljava/time/Instant;");
    assertThat(out.mv.owner).isEqualTo("other/time/Instant");
    assertThat(out.mv.desc).isEqualTo("Lj$/time/Instant;");
  }

  @Test
  public void testCorePackageCheck() throws Exception {
    MockClassVisitor out = new MockClassVisitor();
    CorePackageRenamer renamer =
        new CorePackageRenamer(
            out,
            new CoreLibrarySupport(
                new CoreLibraryRewriter(""),
                null,
                ImmutableList.of("java/time/"),
                ImmutableList.of(),
                ImmutableList.of(),
                ImmutableList.of(),
                ImmutableList.of(),
                ImmutableList.of()));
    MethodVisitor mv = renamer.visitMethod(0, "test", "()V", null, null);

    mv.visitMethodInsn(
        Opcodes.INVOKESTATIC, "android/support/Instant", "now", "()Ljava/time/Instant;", false);
    assertThat(out.mv.owner).isEqualTo("android/support/Instant");
    assertThat(out.mv.desc).isEqualTo("()Lj$/time/Instant;");

    mv.visitMethodInsn(
        Opcodes.INVOKESTATIC, "android/arch/Instant", "now", "()Ljava/time/Instant;", false);
    assertThat(out.mv.owner).isEqualTo("android/arch/Instant");
    assertThat(out.mv.desc).isEqualTo("()Lj$/time/Instant;");

    assertThrows(
        IllegalStateException.class,
        () ->
            mv.visitMethodInsn(
                Opcodes.INVOKESTATIC,
                "android/time/Instant",
                "now",
                "()Ljava/time/Instant;",
                false));
    assertThrows(
        IllegalStateException.class,
        () ->
            mv.visitFieldInsn(
                Opcodes.GETFIELD, "android/time/Instant", "now", "Ljava/time/Instant;"));
  }

  private static class MockClassVisitor extends ClassVisitor {

    final MockMethodVisitor mv = new MockMethodVisitor();

    public MockClassVisitor() {
      super(Opcodes.ASM7);
    }

    @Override
    public MethodVisitor visitMethod(
        int access, String name, String desc, String signature, String[] exceptions) {
      return mv;
    }
  }

  private static class MockMethodVisitor extends MethodVisitor {

    String owner;
    String desc;

    public MockMethodVisitor() {
      super(Opcodes.ASM7);
    }

    @Override
    public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
      this.owner = owner;
      this.desc = desc;
    }

    @Override
    public void visitFieldInsn(int opcode, String owner, String name, String desc) {
      this.owner = owner;
      this.desc = desc;
    }
  }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller {

	/**
	 * this is the base controller
	 * all the controller must extends base controller explect login
	 */
	protected $out_data;
	function __construct()
	{
		parent::__construct();
		//self::check_login();
		$this->out_data['site_url'] = $this->get_site_url();
		$this->out_data['current_function'] = '';
		$this->load->database();
		$this->load->library('session');
		header( 'Access-Control-Allow-Origin:http://shike8888.com' );
	}

	public function check_merchant_login(){
		$merchant_login = $this->session->userdata('merchant_login');
		if(!$merchant_login)
		{
			header("Location: /login");
                        exit();
		}
	}

	public function check_shike_login(){
		$shike_login = $this->session->userdata('shike_login');
		if(!$shike_login)
		{
			header("Location: /login");
			exit();
		}
	}

	public function check_admin_login()
	{
		$admin_login = $this->session->userdata('admin_login');
		if(!$admin_login)
		{
			header("Location: /admin_login");
		}
	}
	private function check_login()
	{
		$admin_login = $this->session->userdata('admin_login');
		if(!$admin_login)
		{
			header("Location:".base_url()."login");
		}
	}

	/*连接redis*/
	protected function redis_conn()
	{
		$redis = new Redis();
		$redis->connect('127.0.0.1', 6379);
		return $redis;
	}

	/*检查管理员权限*/
	protected function check_permission($permission = 'base')
	{
		$admin_allow = explode(',', $this->session->userdata('permission') );
		if( in_array($permission, $admin_allow) ) return true;
		else header("Location:".base_url()."login");
	}

	protected function get_site_url()
	{
		$admin_url = base_url();
		$pos = strripos($admin_url, '/',-2);
		return substr($admin_url, 0, $pos).'/';
	}

	protected function is_post()
	{
		return $_SERVER['REQUEST_METHOD' ] === 'POST' ? true : false;
	}

	protected function get_pagin($base_url, $total_rows, $limit = 10, $uri_segment = 3, $page_query_string = false)
	{
		$this->load->library('pagination');
		$config['base_url'] = $base_url;
		$config['total_rows'] = $total_rows;
		$config['per_page'] = $limit;
		$config['uri_segment'] = $uri_segment;
		$config['use_page_numbers'] = TRUE;

		$config['full_tag_open'] = '
';
		$config['full_tag_close'] = '
';
		$config['first_tag_open'] = '
';
		$config['first_tag_close'] = '
';
		$config['last_tag_open'] = '
';
		$config['last_tag_close'] = '
';
		$config['next_tag_open'] = '
';
		$config['next_tag_close'] = '
';
		$config['prev_tag_open'] = '
';
		$config['prev_tag_close'] = '
';
		$config['cur_tag_open'] = '
';
		$config['cur_tag_close'] = '
';
		$config['num_tag_open'] = '
';
		$config['num_tag_close'] = '
';
		$config['page_query_string'] = $page_query_string;

		$this->pagination->initialize($config);

		return '
'.$this->pagination->create_links().'
';
	}
}


text:
"""Abstract syntax for edn.

Roughly speaking, every edn element gets its own terml symbol.  Thus, an edn
stream consisting of a vector of two strings, e.g.::

  ["foo" "bar"]

Will be mapped to::

  Vector((String(u'foo'), String(u'bar')))

Beyond that::

  #foo 42 <=> TaggedValue(Symbol('foo'), 42)
  :my/keyword <=> Keyword(Symbol('keyword', 'my'))
  my/symbol <=> Symbol('symbol', 'my')
"""

from functools import partial
import os

from parsley import makeGrammar
from terml.nodes import coerceToTerm, termMaker as t

from ._parsley import iterGrammar, parseGrammar

Character = t.Character
ExactFloat = t.ExactFloat
Keyword = t.Keyword
List = t.List
Map = t.Map
Nil = t.Nil()
Set = t.Set
String = t.String
Symbol = t.Symbol
TaggedValue = t.TaggedValue
Vector = t.Vector

def Float(value, exact):
    if exact:
        return ExactFloat(value)
    return float(value)

_edn_grammar_file = os.path.join(os.path.dirname(__file__), 'edn.parsley')
_edn_grammar_definition = open(_edn_grammar_file).read()

_edn_bindings = {
    'Character': Character,
    'Float': Float,
    'String': String,
    'Symbol': Symbol,
    'Keyword': Keyword,
    'Vector': Vector,
    'TaggedValue': TaggedValue,
    'Map': Map,
    'Nil': Nil,
    'Set': Set,
    'List': List,
}

_parsed_edn = parseGrammar(_edn_grammar_definition, 'edn')
edn = makeGrammar(_edn_grammar_definition, _edn_bindings, name='edn')

def parse(string):
    """Parse a single edn element.

    Returns an abstract representation of a single edn element.
    """
    return edn(string).edn()

def parse_stream(stream):
    """Parse a stream of edn elements from a file-like object.

    Yields the abstract syntax for each edn element in 'stream'.

    :param stream: A file-like object to read edn elements from.
    """
    return iterGrammar(_parsed_edn, _edn_bindings, 'edn', stream)

def _wrap(start, end, *middle):
    return ''.join([start] + list(middle) + [end])

class _Builder(object):

    PRIMITIVES = (
        ((int, float), str),
        (long, lambda x: str(x) + 'N'),
        (unicode, unicode),
        (str, str),
    )

    def _dump_true(self):
        return 'true'

    def _dump_false(self):
        return 'false'

    def _dump_Nil(self):
        return 'nil'

    def _dump_Character(self, obj):
        return '\\' + obj

    def _dump_ExactFloat(self, obj):
        return '%sM' % (obj,)

    def _dump_Keyword(self, obj):
        return ':' + obj

    def _dump_Symbol(self, name, prefix=None):
        if prefix:
            return '%s/%s' % (prefix, name)
        else:
            return name

    def _dump_TaggedValue(self, tag, value):
        return '#%s %s' % (tag, value)

    def _dump_String(self, obj):
        quote = '"'
        escape = {
            '"': r'\"',
            '\\': r'\\',
            '\n': r'\n',
            '\r': r'\r',
            '\t': r'\t',
            '\b': r'\b',
            '\f': r'\f',
        }
        output = [quote]
        encoded = obj.encode('utf8')
        for byte in encoded:
            escaped = escape.get(byte, byte)
            output.append(escaped)
        output.append(quote)
        return ''.join(output)

    _dump_List = partial(_wrap, '(', ')')
    _dump_Vector = partial(_wrap, '[', ']')
    _dump_Set = partial(_wrap, '#{', '}')
    _dump_Map = partial(_wrap, '{', '}')

    def _merge_elements(self, *elements):
        return ' '.join(elements)

    def leafTag(self, tag, span):
        if tag.name == '.tuple.':
            return self._merge_elements
        return getattr(self, '_dump_%s' % (tag.name,))

    def leafData(self, data, span=None):
        for base_type, dump_rule in self.PRIMITIVES:
            if isinstance(data, base_type):
                return lambda *args: dump_rule(data)
        raise ValueError("Cannot encode %r" % (data,))

    def term(self, f, built_terms):
        return f(*built_terms)

def unparse(obj):
    """Turn an abstract edn element into a string.

    Returns a valid edn string representing 'obj'.
    """
    builder = _Builder()
    return coerceToTerm(obj).build(builder)

def unparse_stream(input_elements, output_stream):
    """Write abstract edn elements out as edn to a file-like object.

    Elements will be separated by UNIX newlines.  This may change in future
    versions.
    """
    separator = u'\n'.encode('utf8')
    builder = _Builder()
    for element in input_elements:
        output_stream.write(coerceToTerm(element).build(builder))
        output_stream.write(separator)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 50(8): 1659 (1972)

#### Original name
Podospora multispora R.S. Khan & Cain

### Remarks
null


text:
"""
    Test the ...
"""

from __future__ import absolute_import, unicode_literals, division, print_function

__author__ = "adrn <adrn@astro.columbia.edu>"

# Standard library
import os, sys

# Third-party
import numpy as np
import pytest

from ...util import project_root


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {HttpModule} from '@angular/http';
import {RouterModule} from '@angular/router';

import { AppComponent }  from './app.component';

import {WelcomeComponent} from './home/welcome.component';
import {ProductModule} from './products/product.module';

@NgModule({
  imports: [ BrowserModule ,HttpModule,RouterModule.forRoot([
    {path:'welcome',component:WelcomeComponent},
    {path:'',redirectTo:'welcome',pathMatch:'full'},
    {path:'**',redirectTo:'welcome',pathMatch:'full'},
  ]), ProductModule],
  declarations: [ AppComponent,WelcomeComponent],
  bootstrap: [ AppComponent ]
})
export class AppModule { }


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This file has been trimmed to reduce the size of the test suite. -->

<sport:content xmlns:sport="http://xml.sportsdirectinc.com/sport/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xml.sportsdirectinc.com/sport/v2 sport.xsd">
    <team-sport-content>
        <sport>
            <id>/sport/football</id>
            <name>football</name>
        </sport>
        <league-content>
            <league>
                <id>/sport/football/league:1</id>
                <name>National Football League</name>
                <name type="nick">NFL</name>
            </league>
            <season-content>
                <season>
                    <id>/sport/football/season:96</id>
                    <name>2014-2015</name>
                    <details>
                        <start-date>2014-08-01</start-date>
                        <end-date>2015-02-09</end-date>
                    </details>
                </season>
                <team-content>
                    <meta>
                        <property name="last-played-competition-id">/sport/football/competition:46700</property>
                    </meta>
                    <team>
                        <id>/sport/football/team:23</id>
                        <name>Arizona</name>
                    </team>
                    <player-content>
                        <player>
                            <id>/sport/football/player:338</id>
                            <name type="first">John</name>
                            <name type="last">Abraham</name>
                        </player>
                        <stat-group>
                            <key>regular-season-stats</key>
                            <scope str="Week 1" type="season-phase-from"/>
                            <scope str="Week 18" type="season-phase-to"/>
                            <stat num="1" type="games_played"/>
                            <stat num="1" type="games_started"/>
                        </stat-group>
                    </player-content>
                    <player-content>
                        <player>
                            <id>/sport/football/player:35195</id>
                            <name type="first">Sam</name>
                            <name type="last">Acho</name>
                        </player>
                        <stat-group>
                            <key>regular-season-stats</key>
                            <scope str="Week 1" type="season-phase-from"/>
                            <scope str="Week 18" type="season-phase-to"/>
                            <stat num="16" type="games_played"/>
                            <stat num="3" type="games_started"/>
                            <stat num="3" type="interception_returned_longest_yards"/>
                            <stat num="1" type="defense_interceptions"/>
                            <stat num="3" type="defense_interception_yards"/>
                            <stat num="21" type="defense_solo_tackles"/>
                            <stat num="7" type="defense_assisted_tackles"/>
                            <stat num="2" type="defense_special_teams_solo_tackles"/>
                            <stat num="1" type="defense_special_teams_assisted_tackles"/>
                            <stat num="1.0" type="defense_sacks"/>
                            <stat num="15.0" type="defense_sack_yards"/>
                            <stat num="4.0" type="defense_tackles_for_loss"/>
                            <stat num="3" type="defense_pass_defenses"/>
                        </stat-group>
                        <stat-group>
                            <key>post-season-stats</key>
                            <scope str="Wildcard" type="season-phase-from"/>
                            <scope str="Super Bowl" type="season-phase-to"/>
                            <stat num="1" type="games_played"/>
                            <stat num="1" type="games_started"/>
                            <stat num="2" type="defense_solo_tackles"/>
                            <stat num="5" type="defense_assisted_tackles"/>
                            <stat num="1.0" type="defense_sacks"/>
                            <stat num="1" type="defense_forced_fumbles"/>
                        </stat-group>
                    </player-content>
                </team-content>
            </season-content>
        </league-content>
    </team-sport-content>
</sport:content>


text:
#pragma once

#include "common/common/macros.h"

#include "extensions/common/utility.h"
#include "extensions/filters/http/well_known_names.h"

namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace Common {

/**
 * FilterNameUtil provides utilities for handling HTTP filter
 * extension names (e.g., "envoy.filters.http.buffer").
 */
class FilterNameUtil {
public:
  /**
   * Given a deprecated HTTP filter extension name, return the
   * canonical name. Any name not defined in the deprecated map is
   * returned without modification. If deprecated extension names are
   * disabled, throws EnvoyException.
   *
   * @return const std::string& canonical filter name
   * @throw EnvoyException if deprecated names are disabled
   */
  static const std::string&
  canonicalFilterName(const std::string& name,
                      Runtime::Loader* runtime = Runtime::LoaderSingleton::getExisting()) {
    const auto& it = deprecatedNameMap().find(name);
    if (it == deprecatedNameMap().end()) {
      return name;
    }

    Extensions::Common::Utility::ExtensionNameUtil::checkDeprecatedExtensionName(
        "http filter", name, it->second, runtime);

    return it->second;
  }

private:
  using DeprecatedNameMap = absl::flat_hash_map<std::string, std::string>;

  static const DeprecatedNameMap& deprecatedNameMap() {
    CONSTRUCT_ON_FIRST_USE(
        DeprecatedNameMap,
        {
            {"envoy.buffer", HttpFilters::HttpFilterNames::get().Buffer},
            {"envoy.cors", HttpFilters::HttpFilterNames::get().Cors},
            {"envoy.csrf", HttpFilters::HttpFilterNames::get().Csrf},
            {"envoy.ext_authz", HttpFilters::HttpFilterNames::get().ExtAuthorization},
            {"envoy.fault", HttpFilters::HttpFilterNames::get().Fault},
            {"envoy.grpc_http1_bridge", HttpFilters::HttpFilterNames::get().GrpcHttp1Bridge},
            {"envoy.grpc_json_transcoder", HttpFilters::HttpFilterNames::get().GrpcJsonTranscoder},
            {"envoy.grpc_web", HttpFilters::HttpFilterNames::get().GrpcWeb},
            {"envoy.gzip", HttpFilters::HttpFilterNames::get().EnvoyGzip},
            {"envoy.health_check", HttpFilters::HttpFilterNames::get().HealthCheck},
            {"envoy.http_dynamic_filter", HttpFilters::HttpFilterNames::get().Dynamo},
            {"envoy.ip_tagging", HttpFilters::HttpFilterNames::get().IpTagging},
            {"envoy.lua", HttpFilters::HttpFilterNames::get().Lua},
            {"envoy.rate_limit", HttpFilters::HttpFilterNames::get().RateLimit},
            {"envoy.router", HttpFilters::HttpFilterNames::get().Router},
            {"envoy.squash", HttpFilters::HttpFilterNames::get().Squash},
        });
  }
};

} // namespace Common
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy


text:
function setup() {
  createCanvas(windowWidth,windowHeight);

  println("ready to roll!");
  //roll the dice 10 times
  for(var i=0; i < 10; i++){
    rollDice();
  }
  println("finished rolling the dice");
}

function rollDice(){
  var d = 1+ int(random(6));
  println("Rolled: " + d );
}


text:
// Copyright (C) 2013 The Android Open Source Project
//
// 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.

package com.googlesource.gerrit.plugins.javamelody;

import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.annotations.PluginData;
import com.google.gerrit.extensions.annotations.PluginName;
import com.google.gerrit.httpd.AllRequestFilter;
import com.google.gerrit.server.config.PluginConfig;
import com.google.gerrit.server.config.PluginConfigFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.StringJoiner;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.bull.javamelody.MonitoringFilter;
import net.bull.javamelody.Parameter;
import net.bull.javamelody.internal.common.HttpParameter;
import net.bull.javamelody.internal.common.Parameters;

@Singleton
class GerritMonitoringFilter extends AllRequestFilter {
  private static final FluentLogger log = FluentLogger.forEnclosingClass();
  private final JavamelodyFilter monitoring;

  @Inject
  GerritMonitoringFilter(JavamelodyFilter monitoring) {
    this.monitoring = monitoring;
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
      chain.doFilter(request, response);
      return;
    }

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    if (monitoring.canMonitor(httpRequest)) {
      monitoring.doFilter(request, response, chain);
    } else {
      httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden access");
    }
  }

  @Override
  public void init(FilterConfig config) throws ServletException {
    monitoring.init(config);
  }

  @Override
  public void destroy() {
    monitoring.destroy();
  }

  static class JavamelodyFilter extends MonitoringFilter {
    private static final String JAVAMELODY_PREFIX = "javamelody";
    private static final String HTTP_TRANSFORM_PATTERN = Parameter.HTTP_TRANSFORM_PATTERN.getCode();
    private static final String GLOBAL_HTTP_TRANSFORM_PATTERN =
        String.format("%s.%s", JAVAMELODY_PREFIX, HTTP_TRANSFORM_PATTERN);
    private static final String STORAGE_DIR = Parameter.STORAGE_DIRECTORY.getCode();
    private static final String GLOBAL_STORAGE_DIR =
        String.format("%s.%s", JAVAMELODY_PREFIX, STORAGE_DIR);
    private static final String PROMETHEUS_BEARER_TOKEN = "prometheusBearerToken";
    private static final String FORMAT_PROMETHEUS = "prometheus";
    private static final String AUTHORIZATION_HEADER = "Authorization";
    private final CapabilityChecker capabilityChecker;
    private final boolean useBearerTokenForPrometheus;

    static final String GERRIT_GROUPING =
        new StringJoiner("|")
            .add("[0-9a-f]{64}") // Long SHA for LFS
            .add("[0-9a-f]{40}") // SHA-1
            .add("[0-9A-F]{32}") // GWT cache ID
            .add("(?<=files/)[^/]+") // review files part
            .add("(?<=/projects/)[^/]+") // project name
            .add("(?<=/accounts/)[^/]+") // account id
            .add("(.+)(?=/git-upload-pack)") // Git fetch/clone
            .add("(.+)(?=/git-receive-pack)") // Git push
            .add("(.+)(?=/info/)") // Git and LFS operations
            .add("\\d+") // various ids e.g. change id
            .toString();

    private final PluginConfig cfg;
    private final Path defaultDataDir;
    private String authenticatedMonitoringUrl;

    @Inject
    JavamelodyFilter(
        PluginConfigFactory cfgFactory,
        @PluginName String pluginName,
        @PluginData Path defaultDataDir,
        CapabilityChecker capabilityChecker) {
      this.defaultDataDir = defaultDataDir;
      this.cfg = cfgFactory.getFromGerritConfig(pluginName);
      this.capabilityChecker = capabilityChecker;
      this.useBearerTokenForPrometheus = isPropertyInPluginConfig(PROMETHEUS_BEARER_TOKEN);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
      if (isPropertyInPluginConfig(HTTP_TRANSFORM_PATTERN)
          || isPropertyUndefined(config, HTTP_TRANSFORM_PATTERN, GLOBAL_HTTP_TRANSFORM_PATTERN)) {
        System.setProperty(GLOBAL_HTTP_TRANSFORM_PATTERN, getTransformPattern());
      }

      if (isPropertyInPluginConfig(STORAGE_DIR)
          || isPropertyUndefined(config, STORAGE_DIR, GLOBAL_STORAGE_DIR)) {
        System.setProperty(GLOBAL_STORAGE_DIR, getStorageDir());
      }

      super.init(config);
    }

    public String getJavamelodyUrl(HttpServletRequest httpRequest) {
      return getMonitoringUrl(httpRequest);
    }

    @Override
    protected String getMonitoringUrl(HttpServletRequest httpRequest) {
      if (authenticatedMonitoringUrl == null) {
        authenticatedMonitoringUrl =
            httpRequest.getContextPath() + "/a" + Parameters.getMonitoringPath();
      }

      if (httpRequest.getRequestURI().equals(authenticatedMonitoringUrl)) {
        return authenticatedMonitoringUrl;
      }

      return super.getMonitoringUrl(httpRequest);
    }

    private String getTransformPattern() {
      return cfg.getString(HTTP_TRANSFORM_PATTERN, GERRIT_GROUPING);
    }

    private String getStorageDir() {
      // default to old path for javamelody storage-directory if it exists
      final Path tmp = Paths.get(System.getProperty("java.io.tmpdir")).resolve(JAVAMELODY_PREFIX);
      if (Files.isDirectory(tmp)) {
        log.atWarning().log(
            "Javamelody data exists in 'tmp' [%s]. Configuration (if any) will be ignored.", tmp);
        return tmp.toString();
      }

      // plugin config has the highest priority
      Path storageDir =
          Optional.ofNullable(cfg.getString(STORAGE_DIR)).map(Paths::get).orElse(defaultDataDir);
      if (!Files.isDirectory(storageDir)) {
        try {
          Files.createDirectories(storageDir);
        } catch (IOException e) {
          log.atSevere().withCause(e).log(
              "Creation of javamelody data dir [%s] failed.", storageDir);
          throw new RuntimeException(e);
        }
      }
      return storageDir.toString();
    }

    private boolean isPropertyInPluginConfig(String name) {
      return !Strings.isNullOrEmpty(cfg.getString(name));
    }

    private boolean isPropertyUndefined(FilterConfig config, String name, String globalName) {
      return System.getProperty(globalName) == null
          && config.getServletContext().getInitParameter(globalName) == null
          && config.getInitParameter(name) == null;
    }

    boolean canMonitor(HttpServletRequest httpRequest) {
      if (httpRequest.getRequestURI().equals(getJavamelodyUrl(httpRequest))) {
        /* Exception when access to metrics for Prometheus using Bearer Token
         * without going through any Gerrit Authentication step.
         * Enable to access the Prometheus metrics ONLY and nothing else, skipping
         * any authentication and ACL check.
         */
        if (useBearerTokenForPrometheus
            && httpRequest.getHeader(AUTHORIZATION_HEADER) != null
            && FORMAT_PROMETHEUS.equals(HttpParameter.FORMAT.getParameterFrom(httpRequest))) {
          return canMonitorFromPrometheusUsingBearerToken(httpRequest);
        }
        return capabilityChecker.canMonitor();
      }
      return true;
    }

    private boolean canMonitorFromPrometheusUsingBearerToken(HttpServletRequest httpRequest) {
      return httpRequest
          .getHeader(AUTHORIZATION_HEADER)
          .equals("Bearer " + cfg.getString(PROMETHEUS_BEARER_TOKEN));
    }
  }
}