text:
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
  def database_size(name)
    select_value("SELECT pg_database_size(#{quote(name)})").to_i
  end

  def database_version_details
    select_value("SELECT version()")
  end

  def spid
    select_value("SELECT pg_backend_pid()").to_i
  end

  def xlog_location
    select_value("SELECT pg_current_wal_insert_lsn()::varchar")
  end

  def xlog_location_diff(lsn1, lsn2)
    select_value("SELECT pg_wal_lsn_diff(#{quote(lsn1)}, #{quote(lsn2)})").to_i
  end

  def client_connections
    select(<<-SQL, "Client Connections").to_a
                  SELECT client_addr   AS client_address
                       , datname       AS database
                       , pid           AS spid
                       , wait_event_type
                       , wait_event
                       , query
                    FROM pg_stat_activity
                   ORDER BY 1, 2
                  SQL
  end

  # Taken from: https://github.com/bucardo/check_postgres/blob/2.19.0/check_postgres.pl#L3492
  # and referenced here: http://wiki.postgresql.org/wiki/Show_database_bloat
  # check_postgres is Copyright (C) 2007-2012, Greg Sabino Mullane
  #
  # Changes applied:
  # Removed  schemaname and totalwastedbytes columns from the original to fit our requirements.
  # Reformatted the SQL and renamed some columns to make them more easier to id.
  # Removed some CASE... logic statements as not needed for our requirements.
  def table_bloat
    data = select(<<-SQL, "Table Bloat")
                SELECT tablename                                                    AS table_name
                     , reltuples::bigint                                            AS rows
                     , relpages::bigint                                             AS pages
                     , otta
                     , ROUND(CASE WHEN otta = 0 OR sml.relpages = 0 OR sml.relpages = otta THEN 0.0
                             ELSE sml.relpages / otta::numeric END, 1)              AS percent_bloat
                     , CASE WHEN relpages < otta THEN 0
                             ELSE relpages::bigint - otta                    END    AS wasted_pages
                     , CASE WHEN relpages < otta THEN 0
                             ELSE (blocksize * (relpages - otta))::bigint    END    AS wasted_size
                     , CASE WHEN relpages < otta THEN 0
                             ELSE blocksize * (sml.relpages - otta)::bigint  END    AS wasted_bytes
                  FROM ( SELECT schemaname
                              , tablename
                              , cc.reltuples
                              , cc.relpages
                              , blocksize
                              , CEIL((cc.reltuples * ((datahdr + pagesize - (CASE WHEN datahdr%pagesize = 0 THEN pagesize
                                                                                ELSE datahdr%pagesize END)) + nullhdr2 + 4)) / (blocksize - 20::float)
                                    ) AS otta
                           FROM ( SELECT pagesize
                                       , blocksize
                                       , schemaname
                                       , tablename
                                       , (datawidth + (hdr + pagesize - (CASE WHEN hdr%pagesize = 0 THEN pagesize
                                                                              ELSE hdr%pagesize END)))::numeric
                                                                                AS datahdr
                                       , (maxfracsum * (nullhdr + pagesize - (CASE WHEN nullhdr%pagesize = 0 THEN pagesize
                                                                                ELSE nullhdr%pagesize END)))
                                                                                AS nullhdr2
                                    FROM ( SELECT schemaname
                                                , tablename
                                                , hdr
                                                , pagesize
                                                , blocksize
                                                , SUM((1 - null_frac) * avg_width)  AS datawidth
                                                , MAX(null_frac) AS maxfracsum
                                                , hdr + ( SELECT 1 + count(*) / 8
                                                            FROM pg_stats s2
                                                           WHERE null_frac     <> 0
                                                             AND s2.schemaname  = s.schemaname
                                                             AND s2.tablename   = s.tablename
                                                        ) AS nullhdr
                                             FROM pg_stats s
                                                , ( SELECT
                                                     ( SELECT current_setting('block_size')::numeric)     AS blocksize
                                                            , CASE WHEN SUBSTRING(SPLIT_PART(v, ' ', 2)
                                                         FROM '#"[0-9]+.[0-9]+#"%' for '#')
                                                           IN ('8.0','8.1','8.2') THEN 27 ELSE 23 END      AS hdr
                                                            , CASE WHEN v ~ 'mingw32' OR v ~ '64-bit' THEN 8
                                                                   ELSE 4 END                              AS pagesize
                                                      FROM ( SELECT version() AS v)                        AS foo
                                                  ) AS constants
                                             GROUP BY 1, 2, 3, 4, 5
                                          ) AS foo
                                ) AS rs
                        JOIN pg_class cc
                          ON cc.relname = rs.tablename
                        JOIN pg_namespace nn
                          ON cc.relnamespace = nn.oid
                         AND nn.nspname = rs.schemaname AND nn.nspname <> 'information_schema'
                ) AS sml
                WHERE schemaname = 'public'
                ORDER BY  1
            SQL

    integer_columns = %w(
      otta
      pages
      pagesize
      rows
      wasted_bytes
      wasted_pages
      wasted_size
    )

    float_columns = %w(
      percent_bloat
    )

    data.each do |datum|
      integer_columns.each   { |c| datum[c] = datum[c].to_i }
      float_columns.each     { |c| datum[c] = datum[c].to_f }
    end

    data.to_a
  end

  # Taken from: https://github.com/bucardo/check_postgres/blob/2.19.0/check_postgres.pl#L3492
  # and referenced here: http://wiki.postgresql.org/wiki/Show_database_bloat
  # check_postgres is Copyright (C) 2007-2012, Greg Sabino Mullane
  #
  # Changes applied:
  # Removed  schemaname and totalwastedbytes columns from the original to fit our requirements.
  # Reformatted the SQL and renamed some columns to make them more easier to id.
  def index_bloat
    data = select(<<-SQL, "Index Bloat")
                SELECT   tablename                                         AS table_name
                       , iname                                             AS index_name
                       , ituples::bigint                                   AS rows
                       , ipages::bigint                                    AS pages
                       , iotta                                             AS otta
                       , ROUND(CASE WHEN iotta = 0 OR ipages = 0 OR ipages = iotta THEN 0.0 ELSE ipages / iotta::numeric END, 1)   AS percent_bloat
                       , CASE WHEN ipages < iotta THEN 0 ELSE ipages::bigint - iotta                      END                      AS wasted_pages
                       , CASE WHEN ipages < iotta THEN 0 ELSE (blocksize * (ipages - iotta))::bigint      END                      AS wasted_size
                       , CASE WHEN ipages < iotta THEN 0 ELSE blocksize * (ipages - iotta)                END                      AS wasted_bytes

                 FROM ( SELECT   schemaname
                               , tablename
                               , cc.reltuples
                               , cc.relpages
                               , blocksize
                               , CEIL((cc.reltuples * ((datahdr + pagesize - (CASE WHEN datahdr%pagesize = 0 THEN pagesize
                                                                                ELSE datahdr%pagesize END)) + nullhdr2 + 4)) / (blocksize - 20::float)
                                     )                                                                                AS otta
                               , COALESCE(c2.relname,'?') AS iname, COALESCE(c2.reltuples, 0) AS ituples, COALESCE(c2.relpages, 0) AS ipages
                               , COALESCE(CEIL((c2.reltuples * (datahdr - 12)) / (blocksize - 20::float)), 0)                      AS iotta
                          FROM ( SELECT   pagesize
                                        , blocksize
                                        , schemaname
                                        , tablename
                                        , (datawidth + (hdr + pagesize - (case when hdr%pagesize = 0 THEN pagesize ELSE hdr%pagesize END)))::numeric       AS datahdr
                                        , (maxfracsum * (nullhdr + pagesize - (case when nullhdr%pagesize = 0 THEN pagesize ELSE nullhdr%pagesize END)))   AS nullhdr2
                                   FROM ( SELECT   schemaname
                                                 , tablename
                                                 , hdr
                                                 , pagesize
                                                 , blocksize
                                                 , SUM((1 - null_frac) * avg_width) AS datawidth
                                                 , MAX(null_frac) AS maxfracsum
                                                 , hdr + ( SELECT 1 + count(*) / 8
                                                             FROM pg_stats s2
                                                            WHERE null_frac     <> 0
                                                              AND s2.schemaname  = s.schemaname
                                                              AND s2.tablename   = s.tablename
                                                         ) AS nullhdr
                                            FROM  pg_stats s
                                                 , ( SELECT
                                                        (SELECT   current_setting('block_size')::numeric) AS blocksize
                                                                , CASE WHEN SUBSTRING(SPLIT_PART(v, ' ', 2) FROM '#"[0-9]+.[0-9]+#"%' for '#')
                                                                    IN ('8.0','8.1','8.2') THEN 27 ELSE 23 END AS hdr
                                                                , CASE WHEN v ~ 'mingw32' OR v ~ '64-bit' THEN 8 ELSE 4 END AS pagesize
                                                           FROM (SELECT version() AS v) AS foo
                                                  ) AS constants
                                            GROUP BY 1, 2, 3, 4, 5
                                        ) AS foo
                               ) AS rs
                          JOIN pg_class cc
                            ON cc.relname      = rs.tablename
                          JOIN pg_namespace nn
                            ON cc.relnamespace = nn.oid
                           AND nn.nspname      = rs.schemaname AND nn.nspname <> 'information_schema'
                          LEFT JOIN pg_index i
                            ON indrelid        = cc.oid
                          LEFT JOIN pg_class c2
                            ON c2.oid          = i.indexrelid
                        ) AS sml
                WHERE schemaname = 'public'
                ORDER BY  1, 2
           SQL

    integer_columns = %w(
      otta
      pages
      pagesize
      rows
      wasted_bytes
      wasted_pages
      wasted_size
    )

    float_columns = %w(
      percent_bloat
    )

    data.each do |datum|
      integer_columns.each   { |c| datum[c] = datum[c].to_i }
      float_columns.each     { |c| datum[c] = datum[c].to_f }
    end

    data.to_a
  end

  # Taken from: https://github.com/bucardo/check_postgres/blob/2.19.0/check_postgres.pl#L3492
  # and referenced here: http://wiki.postgresql.org/wiki/Show_database_bloat
  # check_postgres is Copyright (C) 2007-2012, Greg Sabino Mullane
  #
  # Changes applied:
  # Removed  schemaname and totalwastedbytes columns from the original to fit our requirements.
  # Reformatted the SQL and renamed some columns to make them more easier to id.
  # Changed to a UNION so that it is easier to read the output and to separate table stats from idx stats.
  def database_bloat
    data = select(<<-SQL, "Database Bloat")
              SELECT   tablename                                         AS table_name
                     , ' '                                               AS index_name
                     , reltuples::bigint                                 AS rows
                     , relpages::bigint                                  AS pages
                     , otta
                     , ROUND(CASE WHEN otta = 0 OR sml.relpages = 0 OR sml.relpages = otta THEN 0.0 ELSE sml.relpages / otta::numeric END, 1) AS percent_bloat
                     , CASE WHEN relpages < otta THEN 0 ELSE relpages::bigint - otta                    END                                   AS wasted_pages
                     , CASE WHEN relpages < otta THEN 0 ELSE (blocksize * (relpages - otta))::bigint    END                                   AS wasted_size
                     , CASE WHEN relpages < otta THEN 0 ELSE blocksize * (sml.relpages - otta)::bigint  END                                   AS wasted_bytes
               FROM ( SELECT   schemaname
                             , tablename
                             , cc.reltuples
                             , cc.relpages
                             , blocksize
                             , CEIL((cc.reltuples * ((datahdr + pagesize - (CASE WHEN datahdr % pagesize = 0 THEN pagesize
                                                                                ELSE datahdr % pagesize END)) + nullhdr2 + 4)) / (blocksize - 20::float)
                                   )                                                                                AS otta
                        FROM ( SELECT   pagesize
                                      , blocksize
                                      , schemaname
                                      , tablename
                                      , (datawidth + (hdr + pagesize - (CASE WHEN hdr%pagesize = 0 THEN pagesize
                                                                             ELSE hdr%pagesize END)))::numeric                                AS datahdr
                                      , (maxfracsum * (nullhdr + pagesize - (CASE WHEN nullhdr % pagesize = 0 THEN pagesize
                                                                                ELSE nullhdr % pagesize END)))                              AS nullhdr2
                                 FROM ( SELECT   schemaname
                                               , tablename
                                               , hdr
                                               , pagesize
                                               , blocksize
                                               , SUM((1 - null_frac) * avg_width)                                                             AS datawidth
                                               , MAX(null_frac)                                                                               AS maxfracsum
                                               , hdr + ( SELECT 1 + count(*) / 8
                                                           FROM pg_stats s2
                                                          WHERE null_frac     <> 0
                                                            AND s2.schemaname  = s.schemaname
                                                            AND s2.tablename   = s.tablename
                                                       )                                                                                AS nullhdr
                                          FROM  pg_stats s
                                               , ( SELECT
                                                      ( SELECT   current_setting('block_size')::numeric)                                      AS blocksize
                                                               , CASE WHEN SUBSTRING(SPLIT_PART(v, ' ', 2) FROM '#"[0-9]+.[0-9]+#"%' for '#')
                                                                   IN ('8.0','8.1','8.2') THEN 27 ELSE 23 END                                 AS hdr
                                                               , CASE WHEN v ~ 'mingw32' OR v ~ '64-bit' THEN 8 ELSE 4 END                    AS pagesize
                                                          FROM ( SELECT version() AS v) AS foo
                                                ) AS constants
                                          GROUP BY 1, 2, 3, 4, 5
                                      ) AS foo
                             ) AS rs
                        JOIN pg_class cc
                          ON cc.relname = rs.tablename
                        JOIN pg_namespace nn
                          ON cc.relnamespace = nn.oid
                         AND nn.nspname      = rs.schemaname
                         AND nn.nspname     <> 'information_schema'
                      ) AS sml
              WHERE schemaname = 'public'

            UNION

              SELECT   tablename                                           AS table_name
                     , iname                                               AS index_name
                     , ituples::bigint                                     AS rows
                     , ipages::bigint                                      AS pages
                     , iotta                                               AS otta
                     , ROUND(CASE WHEN iotta = 0 OR ipages = 0 OR ipages = iotta THEN 0.0 ELSE ipages / iotta::numeric END, 1)                AS percent_bloat
                     , CASE WHEN ipages < iotta THEN 0 ELSE ipages::bigint - iotta                      END                                   AS wasted_pages
                     , CASE WHEN ipages < iotta THEN 0 ELSE (blocksize * (ipages - iotta))::bigint      END                                   AS wasted_size
                     , CASE WHEN ipages < iotta THEN 0 ELSE blocksize * (ipages - iotta)                END                                   AS wasted_bytes

               FROM ( SELECT   schemaname
                             , tablename
                             , cc.reltuples
                             , cc.relpages
                             , blocksize
                             , CEIL((cc.reltuples * ((datahdr + pagesize - (CASE WHEN datahdr % pagesize = 0 THEN pagesize
                                                                                ELSE datahdr % pagesize END)) + nullhdr2 + 4)) / (blocksize - 20::float)
                                   )                                                                                AS otta
                             , COALESCE(c2.relname,'?') AS iname, COALESCE(c2.reltuples, 0) AS ituples, COALESCE(c2.relpages, 0)              AS ipages
                             , COALESCE(CEIL((c2.reltuples * (datahdr - 12)) / (blocksize - 20::float)), 0)                                   AS iotta
                        FROM ( SELECT   pagesize
                                      , blocksize
                                      , schemaname
                                      , tablename
                                      , (datawidth + (hdr + pagesize - ( CASE WHEN hdr%pagesize = 0 THEN pagesize
                                                                              ELSE hdr%pagesize END)))::numeric                               AS datahdr
                                      , (maxfracsum * (nullhdr + pagesize - ( CASE WHEN nullhdr % pagesize = 0 THEN pagesize
                                                                                ELSE nullhdr % pagesize END)))                             AS nullhdr2
                                 FROM ( SELECT   schemaname
                                               , tablename
                                               , hdr
                                               , pagesize
                                               , blocksize
                                               , SUM((1 - null_frac) * avg_width)                                                             AS datawidth
                                               , MAX(null_frac)                                                                               AS maxfracsum
                                               , hdr + ( SELECT 1 + count(*) / 8
                                                           FROM pg_stats s2
                                                          WHERE null_frac     <> 0
                                                            AND s2.schemaname  = s.schemaname
                                                            AND s2.tablename   = s.tablename
                                                       )                                                                                AS nullhdr
                                          FROM  pg_stats s
                                               , ( SELECT
                                                      ( SELECT   current_setting('block_size')::numeric)                                      AS blocksize
                                                               , CASE WHEN SUBSTRING(SPLIT_PART(v, ' ', 2) FROM '#"[0-9]+.[0-9]+#"%' for '#')
                                                                   IN ('8.0','8.1','8.2') THEN 27 ELSE 23 END                                 AS hdr
                                                               , CASE WHEN v ~ 'mingw32' OR v ~ '64-bit' THEN 8 ELSE 4 END                    AS pagesize
                                                          FROM ( SELECT version() AS v) AS foo
                                                ) AS constants
                                          GROUP BY 1, 2, 3, 4, 5
                                      ) AS foo
                             ) AS rs
                        JOIN pg_class cc
                          ON cc.relname      = rs.tablename
                        JOIN pg_namespace nn
                          ON cc.relnamespace = nn.oid
                         AND nn.nspname      = rs.schemaname
                         AND nn.nspname     <> 'information_schema'
                        LEFT JOIN pg_index i
                          ON indrelid        = cc.oid
                        LEFT JOIN pg_class c2
                          ON c2.oid          = i.indexrelid
                      ) AS sml
              WHERE schemaname = 'public'
              ORDER BY  1, 2
           SQL

    integer_columns = %w(
      otta
      pages
      pagesize
      rows
      wasted_bytes
      wasted_pages
      wasted_size
    )

    float_columns = %w(
      percent_bloat
    )

    data.each do |datum|
      integer_columns.each   { |c| datum[c] = datum[c].to_i }
      float_columns.each     { |c| datum[c] = datum[c].to_f }
    end

    data.to_a
  end

  def table_statistics
    data = select(<<-SQL, "Table Statistics")
                SELECT relname            AS table_name
                     , seq_scan           AS table_scans
                     , seq_tup_read       AS sequential_rows_read
                     , idx_scan           AS index_scans
                     , idx_tup_fetch      AS index_rows_fetched
                     , n_tup_ins          AS rows_inserted
                     , n_tup_upd          AS rows_updated
                     , n_tup_del          AS rows_deleted
                     , n_tup_hot_upd      AS rows_hot_updated
                     , n_live_tup         AS rows_live
                     , n_dead_tup         AS rows_dead
                     , last_vacuum        AS last_vacuum_date
                     , last_autovacuum    AS last_autovacuum_date
                     , last_analyze       AS last_analyze_date
                     , last_autoanalyze   AS last_autoanalyze_date
                  FROM pg_stat_all_tables
                 WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
                 ORDER BY relname ASC ;
                 SQL

    integer_columns = %w(
      table_scans
      sequential_rows_read
      index_scans
      index_rows_fetched
      rows_inserted
      rows_updated
      rows_deleted
      rows_hot_updated
      rows_live
      rows_dead
    )

    timestamp_columns = %w(
      last_vacuum_date
      last_autovacuum_date
      last_analyze_date
      last_autoanalyze_date
    )

    data.each do |datum|
      integer_columns.each   { |c| datum[c] = datum[c].to_i }
      timestamp_columns.each { |c| datum[c] = ActiveRecord::Type::Time.new.deserialize(datum[c]) }
    end

    data.to_a
  end

  # Provide the database statistics for all tables and indexes
  def statistics
    stats = select(<<-SQL, "Statistics")
      SELECT relname           AS name,
             reltuples         AS rows,
             relpages          AS pages
      FROM pg_class
      ORDER BY reltuples DESC, relpages DESC
    SQL

    stats.each do |s|
      s["rows"]  = s["rows"].to_f.to_i
      s["pages"] = s["pages"].to_f.to_i
      s["size"]  = s["pages"] * 8 * 1024
      s["average_row_size"] = s["pages"].to_f / (s["rows"] + 1) * 8 * 1024
    end

    stats.to_a
  end

  def table_size
    stats = select(<<-SQL, "Table Size")
                SELECT relname                                                           AS table_name
                     , reltuples                                                         AS rows
                     , relpages                                                          AS pages
                  FROM pg_class
                 WHERE reltuples > 1
                   AND relname NOT LIKE 'pg_%'
              ORDER BY reltuples DESC
                     , relpages  DESC ;
                 SQL

    stats.each do |s|
      s["rows"]  = s["rows"].to_f.to_i
      s["pages"] = s["pages"].to_f.to_i
      s["size"]  = s["pages"] * 8 * 1024
      s["average_row_size"] = s["pages"].to_f / (s["rows"] + 1) * 8 * 1024
    end

    stats.to_a
  end

  def table_total_size(table)
    select_value("SELECT pg_total_relation_size('#{table}')").to_i
  end

  # @return [Hash<String,String>] a hash of {table_name => text_table_name}
  def text_table_names
    data = select_rows(<<-SQL, "Text Table Names")
      SELECT t.relname AS table_name, tt.relname AS text_table_name
      FROM pg_class t
        JOIN pg_class tt ON t.reltoastrelid = tt.oid
    SQL

    data.to_h
  end

  # @return [Hash<String,Array<String>>] a hash of {table_name => [index_names]}
  def index_names
    data = select_rows(<<-SQL, "Index Names")
      SELECT DISTINCT t.relname AS table_name, i.relname AS index_name
      FROM pg_class t
        JOIN pg_index d ON t.oid = d.indrelid
        JOIN pg_class i ON d.indexrelid = i.oid
      WHERE i.relkind = 'i'
    SQL

    result = Hash.new { |h, k| h[k] = [] }
    data.each_with_object(result) { |(k, v), h| h[k] << v }
  end

  def primary_key?(table_name)
    select_value(<<-SQL)
      SELECT EXISTS(
        SELECT 1
        FROM pg_index
        WHERE indrelid = '#{table_name}'::regclass AND indisprimary = true
      )
    SQL
  end

  def table_metrics_bloat(table_name)
    data = select(<<-SQL, "Table Metrics Bloat Analysis")
            SELECT tablename                                                    AS table_name
                 , reltuples::bigint                                            AS rows
                 , relpages::bigint                                             AS pages
                 , otta
                 , ROUND(CASE WHEN otta = 0 OR sml.relpages = 0 OR sml.relpages = otta THEN 0.0
                         ELSE sml.relpages / otta::numeric END, 1)              AS percent_bloat
                 , CASE WHEN relpages < otta THEN 0
                         ELSE relpages::bigint - otta                    END    AS wasted_pages
                 , CASE WHEN relpages < otta THEN 0
                         ELSE (blocksize * (relpages - otta))::bigint    END    AS wasted_size
                 , CASE WHEN relpages < otta THEN 0
                         ELSE blocksize * (sml.relpages - otta)::bigint  END    AS wasted_bytes
              FROM ( SELECT schemaname
                          , tablename
                          , cc.reltuples
                          , cc.relpages
                          , blocksize
                          , CEIL((cc.reltuples * ((datahdr + pagesize - (CASE WHEN datahdr%pagesize = 0 THEN pagesize
                                                                              ELSE datahdr%pagesize END)) + nullhdr2 + 4)) / (blocksize - 20::float)
                                ) AS otta
                       FROM ( SELECT pagesize
                                   , blocksize
                                   , schemaname
                                   , tablename
                                   , (datawidth + (hdr + pagesize - (CASE WHEN hdr%pagesize = 0 THEN pagesize
                                                                          ELSE hdr%pagesize END)))::numeric
                                                                                AS datahdr
                                   , (maxfracsum * (nullhdr + pagesize - (CASE WHEN nullhdr%pagesize = 0 THEN pagesize
                                                                               ELSE nullhdr%pagesize END)))
                                                                                AS nullhdr2
                                FROM ( SELECT schemaname
                                            , tablename
                                            , hdr
                                            , pagesize
                                            , blocksize
                                            , SUM((1 - null_frac) * avg_width)  AS datawidth
                                            , MAX(null_frac) AS maxfracsum
                                            , hdr + ( SELECT 1 + count(*) / 8
                                                        FROM pg_stats s2
                                                       WHERE null_frac     <> 0
                                                         AND s2.schemaname  = s.schemaname
                                                         AND s2.tablename   = s.tablename
                                                    ) AS nullhdr
                                         FROM pg_stats s
                                            , ( SELECT
                                                 ( SELECT current_setting('block_size')::numeric)     AS blocksize
                                                        , CASE WHEN SUBSTRING(SPLIT_PART(v, ' ', 2)
                                                     FROM '#"[0-9]+.[0-9]+#"%' for '#')
                                                       IN ('8.0','8.1','8.2') THEN 27 ELSE 23 END      AS hdr
                                                        , CASE WHEN v ~ 'mingw32' OR v ~ '64-bit' THEN 8
                                                               ELSE 4 END                              AS pagesize
                                                  FROM ( SELECT version() AS v)                        AS foo
                                              ) AS constants
                                         GROUP BY 1, 2, 3, 4, 5
                                      ) AS foo
                            ) AS rs
                    JOIN pg_class cc
                      ON cc.relname = rs.tablename
                    JOIN pg_namespace nn
                      ON cc.relnamespace = nn.oid
                     AND nn.nspname = rs.schemaname AND nn.nspname <> 'information_schema'
            ) AS sml
            WHERE schemaname = 'public'
              AND tablename  = '#{table_name}'
            ORDER BY  1
        SQL

    integer_columns = %w(
      otta
      pages
      rows
      wasted_bytes
      wasted_pages
      wasted_size
    )

    float_columns = %w(
      percent_bloat
    )

    data.each do |datum|
      integer_columns.each   { |c| datum[c] = datum[c].to_i }
      float_columns.each     { |c| datum[c] = datum[c].to_f }
    end

    data.to_a
  end

  def table_metrics_analysis(table_name)
    data = select(<<-SQL, "Table Metrics Stats Analysis")
              SELECT seq_scan           AS table_scans
                   , seq_tup_read       AS sequential_rows_read
                   , idx_scan           AS index_scans
                   , idx_tup_fetch      AS index_rows_fetched
                   , n_tup_ins          AS rows_inserted
                   , n_tup_upd          AS rows_updated
                   , n_tup_del          AS rows_deleted
                   , n_tup_hot_upd      AS rows_hot_updated
                   , n_live_tup         AS rows_live
                   , n_dead_tup         AS rows_dead
                   , last_vacuum        AS last_vacuum_date
                   , last_autovacuum    AS last_autovacuum_date
                   , last_analyze       AS last_analyze_date
                   , last_autoanalyze   AS last_autoanalyze_date
                FROM pg_stat_all_tables
               WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
                 AND relname = '#{table_name}'
               ORDER BY relname ASC ;
            SQL

    integer_columns = %w(
      table_scans
      sequential_rows_read
      index_scans
      index_rows_fetched
      rows_inserted
      rows_updated
      rows_deleted
      rows_hot_updated
      rows_live
      rows_dead
    )

    timestamp_columns = %w(
      last_vacuum_date
      last_autovacuum_date
      last_analyze_date
      last_autoanalyze_date
    )

    data.each do |datum|
      integer_columns.each   { |c| datum[c] = datum[c].to_i }
      timestamp_columns.each { |c| datum[c] = ActiveRecord::Type::Time.new.deserialize(datum[c]) }
    end

    data.to_a
  end

  def table_metrics_total_size(table_name)
    select_value(<<-SQL, "Table Metrics Total Size").to_i
            SELECT pg_total_relation_size('#{table_name}'::regclass) AS total_table_size;
           SQL
  end

  def number_of_db_connections
    select_value(<<-SQL, "DB Client Connections").to_i
            SELECT count(*) as active_connections
              FROM pg_stat_activity
           SQL
  end

  def index_metrics_bloat(index_name)
    data = select(<<-SQL, "Index Metrics Bloat Analysis")
                SELECT   tablename                                         AS table_name
                       , iname                                             AS index_name
                       , ituples::bigint                                   AS rows
                       , ipages::bigint                                    AS pages
                       , iotta                                             AS otta
                       , ROUND(CASE WHEN iotta = 0 OR ipages = 0 OR ipages = iotta THEN 0.0 ELSE ipages / iotta::numeric END, 1)   AS percent_bloat
                       , CASE WHEN ipages < iotta THEN 0 ELSE ipages::bigint - iotta                      END                      AS wasted_pages
                       , CASE WHEN ipages < iotta THEN 0 ELSE (blocksize * (ipages - iotta))::bigint      END                      AS wasted_size
                       , CASE WHEN ipages < iotta THEN 0 ELSE blocksize * (ipages - iotta)                END                      AS wasted_bytes

                 FROM ( SELECT   schemaname
                               , tablename
                               , cc.reltuples
                               , cc.relpages
                               , blocksize
                               , CEIL((cc.reltuples * ((datahdr + pagesize - (CASE WHEN datahdr%pagesize = 0 THEN pagesize
                                                                                ELSE datahdr%pagesize END)) + nullhdr2 + 4)) / (blocksize - 20::float)
                                     )                                                                                AS otta
                               , COALESCE(c2.relname,'?') AS iname, COALESCE(c2.reltuples, 0) AS ituples, COALESCE(c2.relpages, 0) AS ipages
                               , COALESCE(CEIL((c2.reltuples * (datahdr - 12)) / (blocksize - 20::float)), 0)                      AS iotta
                          FROM ( SELECT   pagesize
                                        , blocksize
                                        , schemaname
                                        , tablename
                                        , (datawidth + (hdr + pagesize - (case when hdr%pagesize = 0 THEN pagesize ELSE hdr%pagesize END)))::numeric       AS datahdr
                                        , (maxfracsum * (nullhdr + pagesize - (case when nullhdr%pagesize = 0 THEN pagesize ELSE nullhdr%pagesize END)))   AS nullhdr2
                                   FROM ( SELECT   schemaname
                                                 , tablename
                                                 , hdr
                                                 , pagesize
                                                 , blocksize
                                                 , SUM((1 - null_frac) * avg_width) AS datawidth
                                                 , MAX(null_frac) AS maxfracsum
                                                 , hdr + ( SELECT 1 + count(*) / 8
                                                             FROM pg_stats s2
                                                            WHERE null_frac     <> 0
                                                              AND s2.schemaname  = s.schemaname
                                                              AND s2.tablename   = s.tablename
                                                         ) AS nullhdr
                                            FROM  pg_stats s
                                                 , ( SELECT
                                                        (SELECT   current_setting('block_size')::numeric) AS blocksize
                                                                , CASE WHEN SUBSTRING(SPLIT_PART(v, ' ', 2) FROM '#"[0-9]+.[0-9]+#"%' for '#')
                                                                    IN ('8.0','8.1','8.2') THEN 27 ELSE 23 END AS hdr
                                                                , CASE WHEN v ~ 'mingw32' OR v ~ '64-bit' THEN 8 ELSE 4 END AS pagesize
                                                           FROM (SELECT version() AS v) AS foo
                                                  ) AS constants
                                            GROUP BY 1, 2, 3, 4, 5
                                        ) AS foo
                               ) AS rs
                          JOIN pg_class cc
                            ON cc.relname      = rs.tablename
                          JOIN pg_namespace nn
                            ON cc.relnamespace = nn.oid
                           AND nn.nspname      = rs.schemaname AND nn.nspname <> 'information_schema'
                          LEFT JOIN pg_index i
                            ON indrelid        = cc.oid
                          LEFT JOIN pg_class c2
                            ON c2.oid          = i.indexrelid
                        ) AS sml
                WHERE iname  = '#{index_name}'
                ORDER BY  1, 2
           SQL

    integer_columns = %w(
      otta
      pages
      pagesize
      rows
      wasted_bytes
      wasted_pages
      wasted_size
    )

    float_columns = %w(
      percent_bloat
    )

    data.each do |datum|
      integer_columns.each   { |c| datum[c] = datum[c].to_i }
      float_columns.each     { |c| datum[c] = datum[c].to_f }
    end

    data.to_a
  end

  def index_metrics_analysis(index_name)
    data = select(<<-SQL, "Index Metrics Stats Analysis")
              SELECT relid                    AS table_id
                   , indexrelid               AS index_id
                   , schemaname
                   , relname                  AS table_name
                   , indexrelname             AS index_name
                   , idx_scan                 AS index_scans
                   , idx_tup_read             AS index_rows_read
                   , idx_tup_fetch            AS index_rows_fetched
                FROM pg_stat_user_indexes
               WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
                 AND indexrelname = '#{index_name}' ;
            SQL

    integer_columns = %w(
      table_id
      index_id
      index_scans
      index_rows_read
      index_rows_fetched
    )

    data.each do |datum|
      integer_columns.each   { |c| datum[c] = datum[c].to_i }
    end

    data.to_a
  end

  def index_metrics_total_size(_index_name)
    select_value(<<-SQL, "Index Metrics -  Size").to_i
            SELECT pg_total_relation_size('#{table_name}'::regclass) - pg_relation_size('#{table_name}') AS index_size;
           SQL
  end
  #

  # DBA operations
  #

  # Fetch data directory
  def data_directory
    select_value(<<-SQL, "Select data directory")
                    SELECT setting AS path
                      FROM pg_settings
                     WHERE name = 'data_directory'
                 SQL
  end

  # Fetch PostgreSQL last start date/time
  def last_start_time
    start_time = select_value(<<-SQL, "Select last start date/time")
                                 SELECT pg_postmaster_start_time()
                              SQL
    ActiveRecord::Type::DateTime.new.deserialize(start_time)
  end

  def analyze_table(table)
    execute("ANALYZE #{quote_table_name(table)}")
  end

  def reindex_table(table)
    execute("REINDEX TABLE #{quote_table_name(table)}")
  end

  def vacuum_analyze_table(table)
    execute("VACUUM ANALYZE #{quote_table_name(table)}")
  end

  def vacuum_full_analyze_table(table)
    execute("VACUUM FULL ANALYZE #{quote_table_name(table)}")
  end
end


text:
@implementation SpecificOnlyV1CoreDataManager

- (NSURL *)modelURL
{
  NSString *s = [NSString stringWithFormat:@"%@.momd", self.resourceBaseName];
  NSURL *url =
    [[NSBundle bundleForClass:[self class]]
      URLForResource:@"SpecificOnly"
       withExtension:@"mom"
        subdirectory:s];
  return url;
}

- (NSString *)resourceBaseName
{
  return @"SpecificOnly";
}

@end

// EOF

redpajama_set_name: RedPajamaGithub


text:
std::shared_ptr<IGenerationListener> generationListener;
std::list<boost::signals2::connection> coreGenerationSignalConnections;

void IGenerationController::setListener(const std::shared_ptr<IGenerationListener>& generationListener_)
{
    generationListener = generationListener_;

    // Disconnect all already connected signals
    for (auto& connection: coreGenerationSignalConnections)
    {
        connection.disconnect();
    }
    coreGenerationSignalConnections.clear();

    if (pactiveWallet && generationListener)
    {
        coreGenerationSignalConnections.push_back(pactiveWallet->NotifyGenerationStarted.connect([]()
        {
            generationListener->onGenerationStarted();
        }));
        coreGenerationSignalConnections.push_back(pactiveWallet->NotifyGenerationStopped.connect([]()
        {
            generationListener->onGenerationStopped();
        }));
        coreGenerationSignalConnections.push_back(pactiveWallet->NotifyGenerationStatisticsUpdate.connect([]()
        {
            //fixme: (DEDUP) - Share this code with RPC if possible
            double dHashPerSecLog = dHashesPerSec;
            std::string sHashPerSecLogLabel = " h";
            selectLargesHashUnit(dHashPerSecLog, sHashPerSecLogLabel);
            double dRollingHashPerSecLog = dRollingHashesPerSec;
            std::string sRollingHashPerSecLogLabel = " h";
            selectLargesHashUnit(dRollingHashPerSecLog, sRollingHashPerSecLogLabel);
            double dBestHashPerSecLog = dBestHashesPerSec;
            std::string sBestHashPerSecLogLabel = " h";
            selectLargesHashUnit(dBestHashPerSecLog, sBestHashPerSecLogLabel);
            generationListener->onStatsUpdated(dHashPerSecLog, sHashPerSecLogLabel, dRollingHashPerSecLog, sRollingHashPerSecLogLabel, dBestHashPerSecLog, sBestHashPerSecLogLabel, nArenaSetupTime/1000.0);
        }));
    }
}

CAccount* findMiningAccount(CWallet* pWallet)
{
    for (const auto& [accountUUID, account] : pWallet->mapAccounts)
    {
        (unused) accountUUID;
        if (account->IsMiningAccount() && account->m_State == AccountState::Normal)
        {
            return account;
        }
    }
    return nullptr;
}

bool IGenerationController::startGeneration(int32_t numThreads, int32_t numArenaThreads, const std::string& memoryLimit)
{
    if (!pactiveWallet)
    {
        return false;
    }

    DS_LOCK2(cs_main, pactiveWallet->cs_wallet);
    CAccount* forAccount = findMiningAccount(pactiveWallet);
    if (!forAccount)
    {
        return false;
    }

    std::string overrideAccountAddress;
    CWalletDB(*pactiveWallet->dbw).ReadMiningAddressString(overrideAccountAddress);

    // Allow user to override default memory selection.
    uint64_t nGenMemoryLimitBytes = GetMemLimitInBytesFromFormattedStringSpecifier(memoryLimit);

    // Normalise for SIGMA arena expectations (arena size must be a multiple of 16mb)
    normaliseBufferSize(nGenMemoryLimitBytes);

    std::thread([=]
    {
        try
        {
            PoWGenerateBlocks(true, numThreads, numArenaThreads, nGenMemoryLimitBytes/1024, Params(), forAccount, overrideAccountAddress);
        }
        catch(...)
        {
        }
    }).detach();

    if (overrideAccountAddress.length() > 0)
    {
        LogPrintf("Block generation enabled into account [%s] using target address [%s], thread limit: [%d threads], memory: [%d Mb].", pactiveWallet->mapAccountLabels[forAccount->getUUID()], overrideAccountAddress ,numThreads, nGenMemoryLimitBytes/1024/1024);
    }
    else
    {
        LogPrintf("Block generation enabled into account [%s], thread limit: [%d threads], memory: [%d Mb].", pactiveWallet->mapAccountLabels[forAccount->getUUID()] ,numThreads, nGenMemoryLimitBytes/1024/1024);
    }
    return true;
}

bool IGenerationController::stopGeneration()
{
    std::thread([=]
    {
        PoWStopGeneration();
    }).detach();
    return true;
}

std::string IGenerationController::getGenerationAddress()
{
    CAccount* forAccount = findMiningAccount(pactiveWallet);
    if (forAccount)
    {
        CReserveKeyOrScript* receiveAddress = new CReserveKeyOrScript(pactiveWallet, forAccount, KEYCHAIN_EXTERNAL);
        CPubKey pubKey;
        if (receiveAddress->GetReservedKey(pubKey))
        {
            CKeyID keyID = pubKey.GetID();
            return CNativeAddress(keyID).ToString();
        }
    }
    return "";
}

std::string IGenerationController::getGenerationOverrideAddress()
{
    std::string overrideAccountAddress;
    if (CWalletDB(*pactiveWallet->dbw).ReadMiningAddressString(overrideAccountAddress))
    {
        return overrideAccountAddress;
    }
    else
    {
        return "";
    }
}

bool IGenerationController::setGenerationOverrideAddress(const std::string& overrideAddress)
{
    if (!pactiveWallet)
        return false;

    DS_LOCK2(cs_main, pactiveWallet->cs_wallet);

    if (!findMiningAccount(pactiveWallet))
        return false;

    if (!overrideAddress.empty())
    {
        CNativeAddress address(overrideAddress);
        if (!address.IsValid())
        {
            return false;
        }
    }
    return CWalletDB(*pactiveWallet->dbw).WriteMiningAddressString(overrideAddress);
}

int64_t IGenerationController::getAvailableCores()
{
    return std::max((uint32_t)2, (uint32_t)std::thread::hardware_concurrency());
}

int64_t IGenerationController::getMinimumMemory()
{
    return 128;
}

int64_t IGenerationController::getMaximumMemory()
{
    uint64_t systemMemoryInMb = systemPhysicalMemoryInBytes()/1024/1024;
    if (systemMemoryInMb < 2048)
        return std::min(systemMemoryInMb, (uint64_t)256);

    systemMemoryInMb -= 2048;
    uint64_t nMaxMemoryInMb = std::min(systemMemoryInMb, defaultSigmaSettings.arenaSizeKb/1024);
    // 32 bit windows can only address 2gb of memory per process (3gb if /largeaddressaware)
    // 32 bit linux is 4gb per process.
    // Limit both accordingly
    #ifdef ARCH_X86
        #ifdef WIN32
            nMaxMemoryInMb = std::min((uint64_t)nMaxMemoryInMb, (uint64_t)1*1024);
        #else
            nMaxMemoryInMb = std::min((uint64_t)nMaxMemoryInMb, (uint64_t)2*1024);
        #endif
    #endif
    return nMaxMemoryInMb;
}


text:
package org.apache.directory.shared.kerberos;

/**
 * An cass to define Kerberos constants
 *
 * @author Apache Directory Project
 */
public class KerberosConstants
{
    /** The Kerberos version 5 */
    public static final int KERBEROS_V5 = 5;

    //-------------------------------------------------------------------------
    // Messages
    //-------------------------------------------------------------------------
    /** Ticket message's tags */
    public static final int TICKET_TAG = 0x61;
    public static final int TICKET_TKT_VNO_TAG = 0xA0;
    public static final int TICKET_REALM_TAG = 0xA1;
    public static final int TICKET_SNAME_TAG = 0xA2;
    public static final int TICKET_ENC_PART_TAG = 0xA3;

    /** Authenticator tags */
    public static final int AUTHENTICATOR_TAG = 0x62;
    public static final int AUTHENTICATOR_AUTHENTICATOR_VNO_TAG = 0xA0;
    public static final int AUTHENTICATOR_CREALM_TAG = 0xA1;
    public static final int AUTHENTICATOR_CNAME_TAG = 0xA2;
    public static final int AUTHENTICATOR_CKSUM_TAG = 0xA3;
    public static final int AUTHENTICATOR_CUSEC_TAG = 0xA4;
    public static final int AUTHENTICATOR_CTIME_TAG = 0xA5;
    public static final int AUTHENTICATOR_SUBKEY_TAG = 0xA6;
    public static final int AUTHENTICATOR_SEQ_NUMBER_TAG = 0xA7;
    public static final int AUTHENTICATOR_AUTHORIZATION_DATA_TAG = 0xA8;

    /** AS-REQ's tags */
    public static final int AS_REQ_TAG = 0x6A;

    /** AS-REP's tags */
    public static final int AS_REP_TAG = 0x6B;

    /** TGS-REQ's tags */
    public static final int TGS_REQ_TAG = 0x6C;

    /** TGS-REP's tags */
    public static final int TGS_REP_TAG = 0x6D;

    /** AP-REQ tags */
    public static final int AP_REQ_TAG = 0x6E;
    public static final int AP_REQ_PVNO_TAG = 0xA0;
    public static final int AP_REQ_MSG_TYPE_TAG = 0xA1;
    public static final int AP_REQ_AP_OPTIONS_TAG = 0xA2;
    public static final int AP_REQ_TICKET_TAG = 0xA3;
    public static final int AP_REQ_AUTHENTICATOR_TAG = 0xA4;

    /** AP-REP tags */
    public static final int AP_REP_TAG = 0x6F;
    public static final int AP_REP_PVNO_TAG = 0xA0;
    public static final int AP_REP_MSG_TYPE_TAG = 0xA1;
    public static final int AP_REP_ENC_PART_TAG = 0xA2;

    /** KrbSafe tags */
    public static final int KRB_SAFE_TAG = 0x74;
    public static final int KRB_SAFE_PVNO_TAG = 0xA0;
    public static final int KRB_SAFE_MSGTYPE_TAG = 0xA1;
    public static final int KRB_SAFE_SAFE_BODY_TAG = 0xA2;
    public static final int KRB_SAFE_CKSUM_TAG = 0xA3;

    /** KrbPriv */
    public static final int KRB_PRIV_TAG = 0x75;
    public static final int KRB_PRIV_PVNO_TAG = 0xA0;
    public static final int KRB_PRIV_MSGTYPE_TAG = 0xA1;
    public static final int KRB_PRIV_ENC_PART_TAG = 0xA3;

    /** EncAsRepPart's tags */
    public static final int ENC_AS_REP_PART_TAG = 0x79;

    /** EncTgsRepPart's tags */
    public static final int ENC_TGS_REP_PART_TAG = 0x7A;

    /** EncAPRepPart's tags */
    public static final int ENC_AP_REP_PART_TAG = 0x7B;
    public static final int ENC_AP_REP_PART_CTIME_TAG = 0xA0;
    public static final int ENC_AP_REP_PART_CUSEC_TAG = 0xA1;
    public static final int ENC_AP_REP_PART_SUB_KEY_TAG = 0xA2;
    public static final int ENC_AP_REP_PART_SEQ_NUMBER_TAG = 0xA3;

    /** EncKrbPrivPart */
    public static final int ENC_KRB_PRIV_PART_TAG = 0x7C;
    public static final int ENC_KRB_PRIV_PART_USER_DATA_TAG = 0xA0;
    public static final int ENC_KRB_PRIV_PART_TIMESTAMP_TAG = 0xA1;
    public static final int ENC_KRB_PRIV_PART_USEC_TAG = 0xA2;
    public static final int ENC_KRB_PRIV_PART_SEQ_NUMBER_TAG = 0xA3;
    public static final int ENC_KRB_PRIV_PART_SENDER_ADDRESS_TAG = 0xA4;
    public static final int ENC_KRB_PRIV_PART_RECIPIENT_ADDRESS_TAG = 0xA5;

    /** KRB-ERROR tags */
    public static final int KRB_ERROR_TAG = 0x7E;
    public static final int KRB_ERROR_PVNO_TAG = 0xA0;
    public static final int KRB_ERROR_MSGTYPE_TAG = 0xA1;
    public static final int KRB_ERROR_CTIME_TAG = 0xA2;
    public static final int KRB_ERROR_CUSEC_TAG = 0xA3;
    public static final int KRB_ERROR_STIME_TAG = 0xA4;
    public static final int KRB_ERROR_SUSEC_TAG = 0xA5;
    public static final int KRB_ERROR_ERROR_CODE_TAG = 0xA6;
    public static final int KRB_ERROR_CREALM_TAG = 0xA7;
    public static final int KRB_ERROR_CNAME_TAG = 0xA8;
    public static final int KRB_ERROR_REALM_TAG = 0xA9;
    public static final int KRB_ERROR_SNAME_TAG = 0xAA;
    public static final int KRB_ERROR_ETEXT_TAG = 0xAB;
    public static final int KRB_ERROR_EDATA_TAG = 0xAC;

    /** KRB-CRED tags */
    public static final int KRB_CRED_TAG = 0x76;
    public static final int KRB_CRED_PVNO_TAG = 0xA0;
    public static final int KRB_CRED_MSGTYPE_TAG = 0xA1;
    public static final int KRB_CRED_TICKETS_TAG = 0xA2;
    public static final int KRB_CRED_ENCPART_TAG = 0xA3;

    //-------------------------------------------------------------------------
    // Components
    //-------------------------------------------------------------------------
    /** AD-AND-OR */
    public static final int AD_AND_OR_CONDITION_COUNT_TAG = 0xA0;
    public static final int AD_AND_OR_ELEMENTS_TAG = 0xA1;

    /** AD-KDCIssued */
    public static final int AD_KDC_ISSUED_AD_CHECKSUM_TAG = 0xA0;
    public static final int AD_KDC_ISSUED_I_REALM_TAG = 0xA1;
    public static final int AD_KDC_ISSUED_I_SNAME_TAG = 0xA2;
    public static final int AD_KDC_ISSUED_ELEMENTS_TAG = 0xA3;

    /** AuthorizationData tags */
    public static final int AUTHORIZATION_DATA_ADTYPE_TAG = 0xA0;
    public static final int AUTHORIZATION_DATA_ADDATA_TAG = 0xA1;

    /** Checksum tags */
    public static final int CHECKSUM_TYPE_TAG = 0xA0;
    public static final int CHECKSUM_CHECKSUM_TAG = 0xA1;

    /** EncKdcRepPart tags */
    public static final int ENC_KDC_REP_PART_KEY_TAG = 0xA0;
    public static final int ENC_KDC_REP_PART_LAST_REQ_TAG = 0xA1;
    public static final int ENC_KDC_REP_PART_NONCE_TAG = 0xA2;
    public static final int ENC_KDC_REP_PART_KEY_EXPIRATION_TAG = 0xA3;
    public static final int ENC_KDC_REP_PART_FLAGS_TAG = 0xA4;
    public static final int ENC_KDC_REP_PART_AUTH_TIME_TAG = 0xA5;
    public static final int ENC_KDC_REP_PART_START_TIME_TAG = 0xA6;
    public static final int ENC_KDC_REP_PART_END_TIME_TAG = 0xA7;
    public static final int ENC_KDC_REP_PART_RENEW_TILL_TAG = 0xA8;
    public static final int ENC_KDC_REP_PART_SREALM_TAG = 0xA9;
    public static final int ENC_KDC_REP_PART_SNAME_TAG = 0xAA;
    public static final int ENC_KDC_REP_PART_CADDR_TAG = 0xAB;

    /** EncKrbCredPart tags */
    public static final int ENC_KRB_CRED_PART_TAG = 0x7D;
    public static final int ENC_KRB_CRED_TICKET_INFO_TAG = 0xA0;
    public static final int ENC_KRB_CRED_PART_NONCE_TAG = 0xA1;
    public static final int ENC_KRB_CRED_PART_TIMESTAMP_TAG = 0xA2;
    public static final int ENC_KRB_CRED_PART_USEC_TAG = 0xA3;
    public static final int ENC_KRB_CRED_PART_SENDER_ADDRESS_TAG = 0xA4;
    public static final int ENC_KRB_CRED_PART_RECIPIENT_ADDRESS_TAG = 0xA5;

    /** Encrypteddata's tags */
    public static final int ENCRYPTED_DATA_ETYPE_TAG = 0xA0;
    public static final int ENCRYPTED_DATA_KVNO_TAG = 0xA1;
    public static final int ENCRYPTED_DATA_CIPHER_TAG = 0xA2;

    /** EncryptionKey tags */
    public static final int ENCRYPTION_KEY_TYPE_TAG = 0xA0;
    public static final int ENCRYPTION_KEY_VALUE_TAG = 0xA1;

    /** EncTicketPart tags */
    public static final int ENC_TICKET_PART_TAG = 0x63;
    public static final int ENC_TICKET_PART_FLAGS_TAG = 0xA0;
    public static final int ENC_TICKET_PART_KEY_TAG = 0xA1;
    public static final int ENC_TICKET_PART_CREALM_TAG = 0xA2;
    public static final int ENC_TICKET_PART_CNAME_TAG = 0xA3;
    public static final int ENC_TICKET_PART_TRANSITED_TAG = 0xA4;
    public static final int ENC_TICKET_PART_AUTHTIME_TAG = 0xA5;
    public static final int ENC_TICKET_PART_STARTTIME_TAG = 0xA6;
    public static final int ENC_TICKET_PART_ENDTIME_TAG = 0xA7;
    public static final int ENC_TICKET_PART_RENEWTILL_TAG = 0xA8;
    public static final int ENC_TICKET_PART_CADDR_TAG = 0xA9;
    public static final int ENC_TICKET_PART_AUTHORIZATION_DATA_TAG = 0xAA;

    /** ETYPE-INFO-ENTRY tags */
    public static final int ETYPE_INFO_ENTRY_ETYPE_TAG = 0xA0;
    public static final int ETYPE_INFO_ENTRY_SALT_TAG = 0xA1;

    /** ETYPE-INFO2-ENTRY tags */
    public static final int ETYPE_INFO2_ENTRY_ETYPE_TAG = 0xA0;
    public static final int ETYPE_INFO2_ENTRY_SALT_TAG = 0xA1;
    public static final int ETYPE_INFO2_ENTRY_S2KPARAMS_TAG = 0xA2;

    /** HostAddress' tags */
    public static final int HOST_ADDRESS_ADDR_TYPE_TAG = 0xA0;
    public static final int HOST_ADDRESS_ADDRESS_TAG = 0xA1;

    /** KrbCredInfo tags */
    public static final int KRB_CRED_INFO_KEY_TAG = 0xA0;
    public static final int KRB_CRED_INFO_PREALM_TAG = 0xA1;
    public static final int KRB_CRED_INFO_PNAME_TAG = 0xA2;
    public static final int KRB_CRED_INFO_FLAGS_TAG = 0xA3;
    public static final int KRB_CRED_INFO_AUTHTIME_TAG = 0xA4;
    public static final int KRB_CRED_INFO_STARTTIME_TAG = 0xA5;
    public static final int KRB_CRED_INFO_ENDTIME_TAG = 0xA6;
    public static final int KRB_CRED_INFO_RENEWTILL_TAG = 0xA7;
    public static final int KRB_CRED_INFO_SREALM_TAG = 0xA8;
    public static final int KRB_CRED_INFO_SNAME_TAG = 0xA9;
    public static final int KRB_CRED_INFO_CADDR_TAG = 0xAA;

    /** KRB-REP's tags */
    public static final int KDC_REP_PVNO_TAG = 0xA0;
    public static final int KDC_REP_MSG_TYPE_TAG = 0xA1;
    public static final int KDC_REP_PA_DATA_TAG = 0xA2;
    public static final int KDC_REP_CREALM_TAG = 0xA3;
    public static final int KDC_REP_CNAME_TAG = 0xA4;
    public static final int KDC_REP_TICKET_TAG = 0xA5;
    public static final int KDC_REP_ENC_PART_TAG = 0xA6;

    /** KRB-REQ's tags */
    public static final int KDC_REQ_PVNO_TAG = 0xA1;
    public static final int KDC_REQ_MSG_TYPE_TAG = 0xA2;
    public static final int KDC_REQ_PA_DATA_TAG = 0xA3;
    public static final int KDC_REQ_KDC_REQ_BODY_TAG = 0xA4;

    /** KRB-REQ-BODY's tags */
    public static final int KDC_REQ_BODY_KDC_OPTIONS_TAG = 0xA0;
    public static final int KDC_REQ_BODY_CNAME_TAG = 0xA1;
    public static final int KDC_REQ_BODY_REALM_TAG = 0xA2;
    public static final int KDC_REQ_BODY_SNAME_TAG = 0xA3;
    public static final int KDC_REQ_BODY_FROM_TAG = 0xA4;
    public static final int KDC_REQ_BODY_TILL_TAG = 0xA5;
    public static final int KDC_REQ_BODY_RTIME_TAG = 0xA6;
    public static final int KDC_REQ_BODY_NONCE_TAG = 0xA7;
    public static final int KDC_REQ_BODY_ETYPE_TAG = 0xA8;
    public static final int KDC_REQ_BODY_ADDRESSES_TAG = 0xA9;
    public static final int KDC_REQ_BODY_ENC_AUTHZ_DATA_TAG = 0xAA;
    public static final int KDC_REQ_BODY_ADDITIONAL_TICKETS_TAG = 0xAB;

    /** KrbSafeBody tags */
    public static final int KRB_SAFE_BODY_USER_DATA_TAG = 0xA0;
    public static final int KRB_SAFE_BODY_TIMESTAMP_TAG = 0xA1;
    public static final int KRB_SAFE_BODY_USEC_TAG = 0xA2;
    public static final int KRB_SAFE_BODY_SEQ_NUMBER_TAG = 0xA3;
    public static final int KRB_SAFE_BODY_SENDER_ADDRESS_TAG = 0xA4;
    public static final int KRB_SAFE_BODY_RECIPIENT_ADDRESS_TAG = 0xA5;

    /** LastRequest tags */
    public static final int LAST_REQ_LR_TYPE_TAG = 0xA0;
    public static final int LAST_REQ_LR_VALUE_TAG = 0xA1;

    /** PaData tags */
    public static final int PADATA_TYPE_TAG = 0xA1;
    public static final int PADATA_VALUE_TAG = 0xA2;

    /** PA-ENC-TS-ENC tags */
    public static final int PA_ENC_TS_ENC_PA_TIMESTAMP_TAG = 0xA0;
    public static final int PA_ENC_TS_ENC_PA_USEC_TAG = 0xA1;

    /** PrincipalName's tags */
    public static final int PRINCIPAL_NAME_NAME_TYPE_TAG = 0xA0;
    public static final int PRINCIPAL_NAME_NAME_STRING_TAG = 0xA1;

    /** TransitedEncoding tags */
    public static final int TRANSITED_ENCODING_TR_TYPE_TAG = 0xA0;
    public static final int TRANSITED_ENCODING_CONTENTS_TAG = 0xA1;

    /** TypedData tags */
    public static final int TYPED_DATA_TDTYPE_TAG = 0xA0;
    public static final int TYPED_DATA_TDDATA_TAG = 0xA1;

    /** CHangePasswdData tags */
    public static final int CHNGPWD_NEWPWD_TAG = 0xA0;
    public static final int CHNGPWD_TARGNAME_TAG = 0xA1;
    public static final int CHNGPWD_TARGREALM_TAG = 0xA2;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Episodes</title>

    <link href="../../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="../../css/clean-blog.min.css" rel="stylesheet">
    <link href="../../css/style.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Nosifer" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation
                    Menu
                </button>
                Log

                        Home

                        About

                        Contact

Episode: 1

Logs

                        Posted by Tanay Agrawal

                            Entry-1

Posted by Tanay Agrawal on October --, 2016

                            Entry-2

Posted by Tanay Agrawal on October --, 2016

Copyright © Tanay Agrawal 2016


text:
package com.opengamma.sesame.config;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import javax.annotation.Nullable;
import javax.inject.Provider;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.ImmutableConstructor;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.opengamma.sesame.function.Parameter;
import com.opengamma.sesame.function.scenarios.ScenarioFunction;
import com.opengamma.util.ArgumentChecker;

/**
 * Configuration for individual functions in the function model.
 *

 * Provides the implementation types for function interfaces and the
 * arguments for creating function instances.
 */
@BeanDefinition(builderScope = "private")
public class FunctionModelConfig implements ImmutableBean {

  /**
   * Singleton instance of an empty configuration.
   *

   * Always returns a null implementation class and empty arguments.
   */
  public static final FunctionModelConfig EMPTY =
      new FunctionModelConfig(ImmutableMap.<Class<?>, Class<?>>of(), ImmutableMap.<Class<?>, FunctionArguments>of());

  /**
   * The function implementation classes keyed by function interface.
   * This only needs to be populated if the implementation is not the default.
   */
  @PropertyDefinition(validate = "notNull")
  private final ImmutableMap<Class<?>, Class<?>> _implementations;

  /** The user-specified function arguments keyed by function implementation. */
  @PropertyDefinition(validate = "notNull")
  private final ImmutableMap<Class<?>, FunctionArguments> _arguments;

  /**
   * Decorator types, keyed by the type of the function interface they decorate.
   *

   * The first decorator in the set is the first one that is invoked, i.e. the outermost. Each decorator
   * delegates to the next decorator except the last, which delegates to the underlying function.
   */
  @PropertyDefinition(validate = "notNull", get = "private")
  private final Map<Class<?>, LinkedHashSet<Class<?>>> _decoratorsByFn;

  /**
   * Function implementation classes keyed by the parameter where they are injected.
   * The parameter is a constructor parameter of a decorator and the class is the type being decorated.
   * The value class can be a decorator if there are multiple decorators attached to the same function.
   */
  private final ImmutableMap<Parameter, Class<?>> _implementationByParameter;

  @ImmutableConstructor
  private FunctionModelConfig(Map<Class<?>, Class<?>> implementations,
                              Map<Class<?>, FunctionArguments> arguments,
                              Map<Class<?>, LinkedHashSet<Class<?>>> decoratorsByFn) {
    _implementations = ImmutableMap.copyOf(implementations);
    _arguments = ImmutableMap.copyOf(arguments);
    _decoratorsByFn = ImmutableMap.copyOf(decoratorsByFn);

    ImmutableMap.Builder<Parameter, Class<?>> builder = ImmutableMap.builder();

    for (Map.Entry<Class<?>, LinkedHashSet<Class<?>>> entry : decoratorsByFn.entrySet()) {
      Class<?> functionInterface = entry.getKey();
      Set<Class<?>> decorators = entry.getValue();
      // make a list of decorators because we need random access
      List<Class<?>> decoratorList = new ArrayList<>(decorators);

      // use (size - 1) because we want to skip the last element in the list
      // the last decorator in the list is the one that delegates to the real function
      for (int i = 0; i < decoratorList.size() - 1; i++) {
        Class<?> firstDecoratorType = decoratorList.get(i);
        Class<?> secondDecoratorType = decoratorList.get(i + 1);
        Constructor<?> constructor = EngineUtils.getConstructor(firstDecoratorType);
        // the constructor parameter where the delegate is passed to the decorator
        Parameter delegateParameter = Parameter.ofType(functionInterface, constructor);
        builder.put(delegateParameter, secondDecoratorType);
      }
      Class<?> lastDecoratorType = decoratorList.get(decoratorList.size() - 1);
      Constructor<?> constructor = EngineUtils.getConstructor(lastDecoratorType);
      Parameter delegateParameter = Parameter.ofType(functionInterface, constructor);
      Class<?> functionImpl = _implementations.get(functionInterface);

      // for the last decorator I want to use the function type to look up in implementations
      if (functionImpl != null) {
        builder.put(delegateParameter, functionImpl);
      }
    }
    _implementationByParameter = builder.build();
  }

  /**
   * Creates new configuration using the specified function implementations and arguments.
   *
   * @param implementations  the implementation classes to use for functions, keyed by function interface
   * @param arguments  the arguments for the function implementations, keyed by implementation type
   */
  public FunctionModelConfig(Map<Class<?>, Class<?>> implementations, Map<Class<?>, FunctionArguments> arguments) {
    this(implementations, arguments, Collections.<Class<?>, LinkedHashSet<Class<?>>>emptyMap());
  }

  /**
   * Creates new configuration using the specified function implementations.
   *
   * @param implementations  the implementation classes to use for functions, keyed by function interface
   */
  public FunctionModelConfig(Map<Class<?>, Class<?>> implementations) {
    this(implementations, Collections.<Class<?>, FunctionArguments>emptyMap());
  }

  /**
   * Gets the implementation that should be used for creating instances of a type for injecting into a constructor.
   *

   * The result implementation can be:
   *

   *
An implementation of an interface

   *
A {@link Provider} that can provide the implementation

   *

   *
   * @param parameter the constructor parameter for which an implementation is required
   * @param functionType the type of the function whose implementation is required, normally an interface
   * @return the implementation that should be used, null if unknown
   */
  public Class<?> getFunctionImplementation(@Nullable Parameter parameter, Class<?> functionType) {
    ArgumentChecker.notNull(functionType, "functionType");

    if (parameter != null) {
      Class<?> type = _implementationByParameter.get(parameter);

      if (type != null) {
        return type;
      }
    }
    LinkedHashSet<Class<?>> decorators = _decoratorsByFn.get(functionType);

    if (decorators != null) {
      return decorators.iterator().next();
    }
    return _implementations.get(functionType);
  }

  /**
   * Gets the arguments for a function.
   *
   * @param functionType  the type of function, not null
   * @return the arguments, empty if not found, not null
   */
  public FunctionArguments getFunctionArguments(Class<?> functionType) {
    FunctionArguments functionArguments = _arguments.get(functionType);
    return functionArguments == null ? FunctionArguments.EMPTY : functionArguments;
  }

  /**
   * Merges this configuration with another set, this configuration takes priority where there are duplicates.
   *
   * @param other configuration to merge with
   * @return the union of the configuration with settings from this instance taking priority
   */
  public FunctionModelConfig mergedWith(FunctionModelConfig other, FunctionModelConfig... others) {
    ArgumentChecker.notNull(other, "other");
    FunctionModelConfig config = this.merge(other);

    for (FunctionModelConfig otherConfig : others) {
      config = config.merge(otherConfig);
    }
    return config;
  }

  private FunctionModelConfig merge(FunctionModelConfig other) {
    Map<Class<?>, Class<?>> implementations = new HashMap<>(other._implementations);
    implementations.putAll(_implementations);

    Set<Class<?>> functionTypesWithArgs = Sets.union(_arguments.keySet(), other._arguments.keySet());
    Map<Class<?>, FunctionArguments> arguments = new HashMap<>();
    for (Class<?> fnType : functionTypesWithArgs) {
      arguments.put(fnType, mergeArguments(_arguments.get(fnType), other._arguments.get(fnType)));
    }

    Set<Class<?>> decoratedFunctionTypes = Sets.union(_decoratorsByFn.keySet(), other._decoratorsByFn.keySet());
    Map<Class<?>, LinkedHashSet<Class<?>>> decoratorsByFn = new HashMap<>();
    for (Class<?> fnType : decoratedFunctionTypes) {
      decoratorsByFn.put(fnType, mergeDecorators(_decoratorsByFn.get(fnType), other._decoratorsByFn.get(fnType)));
    }

    return new FunctionModelConfig(implementations, arguments, decoratorsByFn);
  }

  /**
   * Returns a copy of this configuration decorated with a decorator.
   *
   * @param decorator  a decorator type
   * @return  a copy of this configuration decorated with the decorator
   */
  public FunctionModelConfig decoratedWith(Class<? extends ScenarioFunction<?, ?>> decorator) {
    return decoratedWith(decorator, Collections.<Class<?>, FunctionArguments>emptyMap());
  }

  /**
   * Returns a copy of this configuration decorated with a decorator.
   *
   * @param scenarioFunction  a decorator type
   * @param arguments  function arguments for building the decorator instance
   * @return  a copy of this configuration decorated with the decorator
   */
  public FunctionModelConfig decoratedWith(Class<? extends ScenarioFunction<?, ?>> scenarioFunction,
                                           Map<Class<?>, FunctionArguments> arguments) {
    ArgumentChecker.notNull(scenarioFunction, "decorator");

    Set<Class<?>> functionTypesWithArgs = Sets.union(_arguments.keySet(), arguments.keySet());
    Map<Class<?>, FunctionArguments> mergedArguments = new HashMap<>();
    for (Class<?> fnType : functionTypesWithArgs) {
      mergedArguments.put(fnType, mergeArguments(_arguments.get(fnType), arguments.get(fnType)));
    }

    // get the set of interfaces implemented by the decorator
    // only one is supported at the moment apart from ScenarioDecorator which is mandatory
    Set<Class<?>> interfaces = new HashSet<>(EngineUtils.getInterfaces(scenarioFunction));
    interfaces.remove(ScenarioFunction.class);

    if (interfaces.size() != 1) {
      throw new IllegalArgumentException("Decorator class " + scenarioFunction.getName() + " must implement " +
                                             "ScenarioFunction and one other interface");
    }
    Class<?> interfaceType = interfaces.iterator().next();
    LinkedHashSet<Class<?>> decorators = _decoratorsByFn.get(interfaceType);
    LinkedHashSet<Class<?>> mergedDecorators = new LinkedHashSet<>();

    mergedDecorators.add(scenarioFunction);
    if (decorators != null) {
      mergedDecorators.addAll(decorators);
    }
    Map<Class<?>, LinkedHashSet<Class<?>>> decoratorsByFn = new HashMap<>(_decoratorsByFn);
    decoratorsByFn.put(interfaceType, mergedDecorators);

    return new FunctionModelConfig(_implementations, mergedArguments, decoratorsByFn);
  }

  /**
   * Null safe merge of arguments. Both arguments are nullable but only one can be null in any given call.
   * If there are duplicates the arguments from {@code args1} take priority.
   *
   * @param args1  some arguments
   * @param args2  some arguments
   * @return  the merged arguments
   */
  private static FunctionArguments mergeArguments(@Nullable FunctionArguments args1, @Nullable FunctionArguments args2) {
    if (args1 == null) {
      return args2;
    } else if (args2 == null) {
      return args1;
    } else {
      return args1.mergedWith(args2);
    }
  }

  /**
   * Null safe merge of decorators. Both arguments are nullable but only one can be null in any given call.
   *
   * @param decorators1  the first set of decorator types
   * @param decorators2  the second set of decorator types
   * @return  the merged set of decorator types
   */
  private static LinkedHashSet<Class<?>> mergeDecorators(@Nullable LinkedHashSet<Class<?>> decorators1,
                                                         @Nullable LinkedHashSet<Class<?>> decorators2) {
    if (decorators1 == null) {
      return decorators2;
    } else if (decorators2 == null) {
      return decorators1;
    } else {
      LinkedHashSet<Class<?>> merged = new LinkedHashSet<>();
      merged.addAll(decorators1);
      merged.addAll(decorators2);
      return merged;
    }
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code FunctionModelConfig}.
   * @return the meta-bean, not null
   */
  public static FunctionModelConfig.Meta meta() {
    return FunctionModelConfig.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(FunctionModelConfig.Meta.INSTANCE);
  }

  @Override
  public FunctionModelConfig.Meta metaBean() {
    return FunctionModelConfig.Meta.INSTANCE;
  }

  @Override
  public <R> Property<R> property(String propertyName) {
    return metaBean().<R>metaProperty(propertyName).createProperty(this);
  }

  @Override
  public Set<String> propertyNames() {
    return metaBean().metaPropertyMap().keySet();
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the function implementation classes keyed by function interface.
   * This only needs to be populated if the implementation is not the default.
   * @return the value of the property, not null
   */
  public ImmutableMap<Class<?>, Class<?>> getImplementations() {
    return _implementations;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the user-specified function arguments keyed by function implementation.
   * @return the value of the property, not null
   */
  public ImmutableMap<Class<?>, FunctionArguments> getArguments() {
    return _arguments;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets decorator types, keyed by the type of the function interface they decorate.
   *

   * The first decorator in the set is the first one that is invoked, i.e. the outermost. Each decorator
   * delegates to the next decorator except the last, which delegates to the underlying function.
   * @return the value of the property, not null
   */
  private Map<Class<?>, LinkedHashSet<Class<?>>> getDecoratorsByFn() {
    return _decoratorsByFn;
  }

  //-----------------------------------------------------------------------
  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      FunctionModelConfig other = (FunctionModelConfig) obj;
      return JodaBeanUtils.equal(getImplementations(), other.getImplementations()) &&
          JodaBeanUtils.equal(getArguments(), other.getArguments()) &&
          JodaBeanUtils.equal(getDecoratorsByFn(), other.getDecoratorsByFn());
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(getImplementations());
    hash = hash * 31 + JodaBeanUtils.hashCode(getArguments());
    hash = hash * 31 + JodaBeanUtils.hashCode(getDecoratorsByFn());
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(128);
    buf.append("FunctionModelConfig{");
    int len = buf.length();
    toString(buf);
    if (buf.length() > len) {
      buf.setLength(buf.length() - 2);
    }
    buf.append('}');
    return buf.toString();
  }

  protected void toString(StringBuilder buf) {
    buf.append("implementations").append('=').append(JodaBeanUtils.toString(getImplementations())).append(',').append(' ');
    buf.append("arguments").append('=').append(JodaBeanUtils.toString(getArguments())).append(',').append(' ');
    buf.append("decoratorsByFn").append('=').append(JodaBeanUtils.toString(getDecoratorsByFn())).append(',').append(' ');
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code FunctionModelConfig}.
   */
  public static class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code implementations} property.
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    private final MetaProperty<ImmutableMap<Class<?>, Class<?>>> _implementations = DirectMetaProperty.ofImmutable(
        this, "implementations", FunctionModelConfig.class, (Class) ImmutableMap.class);
    /**
     * The meta-property for the {@code arguments} property.
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    private final MetaProperty<ImmutableMap<Class<?>, FunctionArguments>> _arguments = DirectMetaProperty.ofImmutable(
        this, "arguments", FunctionModelConfig.class, (Class) ImmutableMap.class);
    /**
     * The meta-property for the {@code decoratorsByFn} property.
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    private final MetaProperty<Map<Class<?>, LinkedHashSet<Class<?>>>> _decoratorsByFn = DirectMetaProperty.ofImmutable(
        this, "decoratorsByFn", FunctionModelConfig.class, (Class) Map.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "implementations",
        "arguments",
        "decoratorsByFn");

    /**
     * Restricted constructor.
     */
    protected Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 643812097:  // implementations
          return _implementations;
        case -2035517098:  // arguments
          return _arguments;
        case -1632890057:  // decoratorsByFn
          return _decoratorsByFn;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public BeanBuilder<? extends FunctionModelConfig> builder() {
      return new FunctionModelConfig.Builder();
    }

    @Override
    public Class<? extends FunctionModelConfig> beanType() {
      return FunctionModelConfig.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return _metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code implementations} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<ImmutableMap<Class<?>, Class<?>>> implementations() {
      return _implementations;
    }

    /**
     * The meta-property for the {@code arguments} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<ImmutableMap<Class<?>, FunctionArguments>> arguments() {
      return _arguments;
    }

    /**
     * The meta-property for the {@code decoratorsByFn} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<Map<Class<?>, LinkedHashSet<Class<?>>>> decoratorsByFn() {
      return _decoratorsByFn;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 643812097:  // implementations
          return ((FunctionModelConfig) bean).getImplementations();
        case -2035517098:  // arguments
          return ((FunctionModelConfig) bean).getArguments();
        case -1632890057:  // decoratorsByFn
          return ((FunctionModelConfig) bean).getDecoratorsByFn();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code FunctionModelConfig}.
   */
  private static class Builder extends DirectFieldsBeanBuilder<FunctionModelConfig> {

    private Map<Class<?>, Class<?>> _implementations = new HashMap<Class<?>, Class<?>>();
    private Map<Class<?>, FunctionArguments> _arguments = new HashMap<Class<?>, FunctionArguments>();
    private Map<Class<?>, LinkedHashSet<Class<?>>> _decoratorsByFn = new HashMap<Class<?>, LinkedHashSet<Class<?>>>();

    /**
     * Restricted constructor.
     */
    protected Builder() {
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case 643812097:  // implementations
          return _implementations;
        case -2035517098:  // arguments
          return _arguments;
        case -1632890057:  // decoratorsByFn
          return _decoratorsByFn;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @SuppressWarnings("unchecked")
    @Override
    public Builder set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case 643812097:  // implementations
          this._implementations = (Map<Class<?>, Class<?>>) newValue;
          break;
        case -2035517098:  // arguments
          this._arguments = (Map<Class<?>, FunctionArguments>) newValue;
          break;
        case -1632890057:  // decoratorsByFn
          this._decoratorsByFn = (Map<Class<?>, LinkedHashSet<Class<?>>>) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public Builder set(MetaProperty<?> property, Object value) {
      super.set(property, value);
      return this;
    }

    @Override
    public Builder setString(String propertyName, String value) {
      setString(meta().metaProperty(propertyName), value);
      return this;
    }

    @Override
    public Builder setString(MetaProperty<?> property, String value) {
      super.setString(property, value);
      return this;
    }

    @Override
    public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
      super.setAll(propertyValueMap);
      return this;
    }

    @Override
    public FunctionModelConfig build() {
      return new FunctionModelConfig(
          _implementations,
          _arguments,
          _decoratorsByFn);
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(128);
      buf.append("FunctionModelConfig.Builder{");
      int len = buf.length();
      toString(buf);
      if (buf.length() > len) {
        buf.setLength(buf.length() - 2);
      }
      buf.append('}');
      return buf.toString();
    }

    protected void toString(StringBuilder buf) {
      buf.append("implementations").append('=').append(JodaBeanUtils.toString(_implementations)).append(',').append(' ');
      buf.append("arguments").append('=').append(JodaBeanUtils.toString(_arguments)).append(',').append(' ');
      buf.append("decoratorsByFn").append('=').append(JodaBeanUtils.toString(_decoratorsByFn)).append(',').append(' ');
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
'''
Created on 2015年12月1日
判断一个图是不是
   bipartite: https://en.wikipedia.org/wiki/Bipartite_graph

   static class Node {
                public Node() {
                        neighbors = new HashSet<Node>();
                }

                Set<Node> neighbors;
        }

        static class Graph {
                Set<Node> nodes;

                public Graph() {
                        nodes = new HashSet<Node>();
                }

                public void addEdge(Node a, Node b) {
                        a.neighbors.add(b);
                        b.neighbors.add(a);
                        nodes.add(a);
                        nodes.add(b);
                }
                public boolean isBipartite() {
                     // implement here
                     return false;
                }
        }

        public static void main(String[] args) {
                Node a = new Node();
                Node b = new Node();
                Node c = new Node();

                Graph g = new Graph();

                g.addEdge(a, b);
                g.addEdge(b, c);
                g.addEdge(c, a);

                System.out.println("is bipartite: " + g.isBipartite());
        }

@author: Darren
'''
from Python.models.Graph import *

def isBipartiteGraph(g):
    sA=set()
    sB=set()
    for node in g.Nodes:
        if node not in sB:
            sA.add(node)
            if sA&node.neighbor:
                return False
            else:
                sB|=node.neighbor
        else:
            sB.add(node)
            if sB&node.neighbor:
                return False
            else:
                sA|=node.neighbor
    return True
nodeA=GraphNode()
nodeB=GraphNode()
nodeC=GraphNode()
g=Graph()
g.addEdge(nodeA, nodeB)
g.addEdge(nodeA, nodeC)
# g.addEdge(nodeB, nodeC)
print(isBipartiteGraph(g))


text:
require_relative '../../../../../environments/rspec_env'

RSpec.describe 'Directory, Integration' do

  let(:clazz) { CukeModeler::Directory }

  describe 'common behavior' do

    it_should_behave_like 'a model, integration'

  end

  describe 'unique behavior' do

    describe 'modeling directories' do

      context 'with an existing directory' do

        let(:root_test_path) { CukeModeler::FileHelper.create_directory }

        let(:directory_path) { CukeModeler::FileHelper.create_directory(name: 'nested_directory',
                                                                        directory: root_test_path) }
        let(:directory_model) { clazz.new(directory_path) }

        it 'models the path of the directory' do
          expect(directory_model.path).to eq(directory_path)
        end

        it 'models the name of the directory' do
          name = File.basename(directory_path)

          expect(directory_model.name).to eq(name)
        end

        context 'with both files and feature files' do

          let(:feature_files) { ['test_file_1', 'test_file_2'] }
          let(:non_feature_files) { ['test_file_3'] }

          before(:each) do
            feature_files.each do |file_name|
              # Some versions of Gherkin require feature content to be present in feature files
              CukeModeler::FileHelper.create_feature_file(text: "#{FEATURE_KEYWORD}: Test feature",
                                                          name: file_name,
                                                          directory: directory_path)
            end

            non_feature_files.each do |file_name|
              CukeModeler::FileHelper.create_file(text: '',
                                                  name: file_name,
                                                  extension: '.file',
                                                  directory: directory_path)
            end
          end

          it 'models the feature files contained in the directory' do
            modeled_files = directory_model.feature_files.collect { |file| file.name[/test_file_\d/] }

            expect(modeled_files).to match_array(feature_files)
          end

          it 'does not model non-feature files contained in the directory' do
            modeled_files = directory_model.feature_files.collect { |file| file.name[/test_file_\d/] }

            non_feature_files.all? do |file|
              expect(modeled_files).to_not include(file)
            end
          end

        end

        context 'with no feature files' do

          let(:directory_path) { CukeModeler::FileHelper.create_directory(name: 'empty_directory',
                                                                          directory: root_test_path) }
          let(:directory_model) { clazz.new(directory_path) }

          it 'models the feature files contained in the directory' do
            modeled_files = directory_model.feature_files.map(&:name)

            expect(modeled_files).to eq([])
          end

        end

        context 'with a nested directory' do

          let(:directory_path) { CukeModeler::FileHelper.create_directory(name: 'test_directory',
                                                                          directory: root_test_path) }
          let(:directory_model) { clazz.new(directory_path) }

          let(:nested_directories) { ['nested_directory_1', 'nested_directory_2'] }

          before(:each) do
            nested_directories.each do |nested_directory|
              CukeModeler::FileHelper.create_directory(name: nested_directory, directory: directory_path)
            end
          end

          it 'models the directories in the directory' do
            modeled_directories = directory_model.directories.collect { |nested_directory| nested_directory.name[/nested_directory_\d/] } # rubocop:disable Layout/LineLength

            expect(modeled_directories).to match_array(nested_directories)
          end

        end

        context 'with no directories' do

          let(:directory_path) { CukeModeler::FileHelper.create_directory(name: 'empty_directory',
                                                                          directory: root_test_path) }
          let(:directory_model) { clazz.new(directory_path) }

          it 'models the directories contained in the directory' do
            modeled_directories = directory_model.directories.map(&:name)

            expect(modeled_directories).to eq([])
          end

        end

      end

      context 'with a non-existing directory' do

        let(:root_test_path) { CukeModeler::FileHelper.create_directory }
        let(:directory_path) { "#{root_test_path}/this_directory_should_not_exist" }

        it 'cannot model a non-existent directory' do
          expect { clazz.new(directory_path) }.to raise_error(ArgumentError)
        end

      end

    end

    it 'properly sets its child models' do
      directory_path = CukeModeler::FileHelper.create_directory
      _nested_directory_path = CukeModeler::FileHelper.create_directory(name: 'nested_directory',
                                                                        directory: directory_path)

      CukeModeler::FileHelper.create_feature_file(text: "#{FEATURE_KEYWORD}: Test feature",
                                                  name: 'test_file',
                                                  directory: directory_path)

      directory_model = clazz.new(directory_path)
      nested_directory_model = directory_model.directories.first
      file_model = directory_model.feature_files.first

      expect(nested_directory_model.parent_model).to equal(directory_model)
      expect(file_model.parent_model).to equal(directory_model)
    end

    describe 'getting ancestors' do

      before(:each) do
        CukeModeler::FileHelper.create_directory(name: 'nested_directory', directory: test_directory)
      end

      let(:test_directory) { CukeModeler::FileHelper.create_directory }

      let(:directory_model) { clazz.new(test_directory) }
      let(:nested_directory_model) { directory_model.directories.first }

      it 'can get its directory' do
        ancestor = nested_directory_model.get_ancestor(:directory)

        expect(ancestor).to equal(directory_model)
      end

      it 'returns nil if it does not have the requested type of ancestor' do
        ancestor = nested_directory_model.get_ancestor(:example)

        expect(ancestor).to be_nil
      end

    end

    describe 'directory output' do

      context 'from source text' do

        let(:directory_path) { CukeModeler::FileHelper.create_directory }
        let(:directory_model) { clazz.new(directory_path) }

        it 'can output a directory' do
          directory_output = directory_model.to_s

          expect(directory_output).to eq(directory_path)
        end

      end

      it 'can be remade from its own output' do
        source = CukeModeler::FileHelper.create_directory
        directory = clazz.new(source)

        directory_output = directory.to_s
        remade_directory_output = clazz.new(directory_output).to_s

        expect(remade_directory_output).to eq(directory_output)
      end

    end

  end

end