text:
local log = require "kong.cmd.utils.log"
local cassandra = require "cassandra"
local Cluster   = require "resty.cassandra.cluster"
local pl_stringx = require "pl.stringx"

local ngx = ngx

local CassandraConnector   = {}
CassandraConnector.__index = CassandraConnector

function CassandraConnector.new(kong_config)
  local resolved_contact_points = {}

  do
    -- Resolve contact points before instantiating cluster, since the
    -- driver does not support hostnames in the contact points list.
    --
    -- The below logic includes a hack so that we are able to run our DNS
    -- resolver in init_by_lua:
    --
    -- 1. We override ngx.socket.tcp/udp so that resty.dns.resolver will run
    --    in init_by_lua (which has no cosockets)
    -- 2. We force the dns_no_sync option so that resty.dns.client will not
    --    spawn an ngx.timer (not supported in init_by_lua)
    --
    -- TODO: replace fallback logic with lua-resty-socket once it supports
    --       ngx.socket.udp

    local tcp_old = ngx.socket.tcp
    local udp_old = ngx.socket.udp

    local dns_no_sync_old = kong_config.dns_no_sync

    package.loaded["socket"] = nil
    package.loaded["kong.tools.dns"] = nil
    package.loaded["kong.resty.dns.client"] = nil
    package.loaded["resty.dns.resolver"] = nil

    ngx.socket.tcp = function(...) -- luacheck: ignore
      local tcp = require("socket").tcp(...)
      return setmetatable({}, {
        __newindex = function(_, k, v)
          tcp[k] = v
        end,
        __index = function(_, k)
          if type(tcp[k]) == "function" then
            return function(_, ...)
              if k == "send" then
                local value = select(1, ...)
                if type(value) == "table" then
                  return tcp.send(tcp, table.concat(value))
                end

                return tcp.send(tcp, ...)

              elseif k == "settimeout" then
                return tcp.settimeout(tcp, select(1, ...)/1000)
              end

              return tcp[k](tcp, ...)
            end
          end

          return tcp[k]
        end
      })
    end

    ngx.socket.udp = function(...) -- luacheck: ignore
      local udp = require("socket").udp(...)
      return setmetatable({}, {
        __newindex = function(_, k, v)
          udp[k] = v
        end,
        __index = function(_, k)
          if type(udp[k]) == "function" then
            return function(_, ...)
              if k == "send" then
                local value = select(1, ...)
                if type(value) == "table" then
                  return udp.send(udp, table.concat(value))
                end

                return udp.send(udp, ...)

              elseif k == "settimeout" then
                return udp.settimeout(udp, select(1, ...)/1000)
              end

              return udp[k](udp, ...)
            end
          end

          return udp[k]
        end
      })
    end

    local dns_tools = require "kong.tools.dns"

    kong_config.dns_no_sync = true

    local dns = dns_tools(kong_config)

    for i, cp in ipairs(kong_config.cassandra_contact_points) do
      local ip, err, try_list = dns.toip(cp)
      if not ip then
        log.error("[cassandra] DNS resolution failed for contact " ..
                  "point '%s': %s. Tried: %s", cp, err, tostring(try_list))

      else
        log.debug("resolved Cassandra contact point '%s' to: %s", cp, ip)
        resolved_contact_points[i] = ip
      end
    end

    kong_config.dns_no_sync = dns_no_sync_old

    package.loaded["resty.dns.resolver"] = nil
    package.loaded["kong.resty.dns.client"] = nil
    package.loaded["kong.tools.dns"] = nil
    package.loaded["socket"] = nil

    ngx.socket.udp = udp_old -- luacheck: ignore
    ngx.socket.tcp = tcp_old -- luacheck: ignore
  end

  if #resolved_contact_points == 0 then
    return nil, "could not resolve any of the provided Cassandra " ..
                "contact points (cassandra_contact_points = '" ..
                table.concat(kong_config.cassandra_contact_points, ", ") .. "')"
  end

  local cluster_options       = {
    shm                       = "kong_cassandra",
    contact_points            = resolved_contact_points,
    default_port              = kong_config.cassandra_port,
    keyspace                  = kong_config.cassandra_keyspace,
    timeout_connect           = kong_config.cassandra_timeout,
    timeout_read              = kong_config.cassandra_timeout,
    max_schema_consensus_wait = kong_config.cassandra_schema_consensus_timeout,
    ssl                       = kong_config.cassandra_ssl,
    verify                    = kong_config.cassandra_ssl_verify,
    cafile                    = kong_config.lua_ssl_trusted_certificate_combined,
    lock_timeout              = 30,
    silent                    = ngx.IS_CLI,
  }

  if ngx.IS_CLI then
    local policy = require("resty.cassandra.policies.reconnection.const")
    cluster_options.reconn_policy = policy.new(100)

    -- Force LuaSocket usage in the CLI in order to allow for self-signed
    -- certificates to be trusted (via opts.cafile) in the resty-cli
    -- interpreter (no way to set lua_ssl_trusted_certificate).
    local socket = require "cassandra.socket"
    socket.force_luasocket("timer", true)
  end

  if kong_config.cassandra_username and kong_config.cassandra_password then
    cluster_options.auth = cassandra.auth_providers.plain_text(
      kong_config.cassandra_username,
      kong_config.cassandra_password
    )
  end

  if kong_config.cassandra_lb_policy == "RoundRobin" then
    local policy = require("resty.cassandra.policies.lb.rr")
    cluster_options.lb_policy = policy.new()

  elseif kong_config.cassandra_lb_policy == "RequestRoundRobin" then
    local policy = require("resty.cassandra.policies.lb.req_rr")
    cluster_options.lb_policy = policy.new()

  elseif kong_config.cassandra_lb_policy == "DCAwareRoundRobin" then
    local policy = require("resty.cassandra.policies.lb.dc_rr")
    cluster_options.lb_policy = policy.new(kong_config.cassandra_local_datacenter)

  elseif kong_config.cassandra_lb_policy == "RequestDCAwareRoundRobin" then
    local policy = require("resty.cassandra.policies.lb.req_dc_rr")
    cluster_options.lb_policy = policy.new(kong_config.cassandra_local_datacenter)
  end

  local serial_consistency

  if string.find(kong_config.cassandra_lb_policy, "DCAware", nil, true) then
    serial_consistency = cassandra.consistencies.local_serial

  else
    serial_consistency = cassandra.consistencies.serial
  end

  local cluster, err = Cluster.new(cluster_options)
  if not cluster then
    return nil, err
  end

  local self   = {
    cluster    = cluster,
    keyspace   = cluster_options.keyspace,
    opts       = {
      write_consistency =
        cassandra.consistencies[kong_config.cassandra_write_consistency:lower()],
      read_consistency =
        cassandra.consistencies[kong_config.cassandra_read_consistency:lower()],
      serial_consistency = serial_consistency,
    },
    refresh_frequency = kong_config.cassandra_refresh_frequency,
    connection = nil, -- created by connect()
  }

  return setmetatable(self, CassandraConnector)
end

local function extract_major_minor(release_version)
  return string.match(release_version, "^((%d+)%.%d+)")
end

function CassandraConnector:init()
  local ok, err = self.cluster:refresh()
  if not ok then
    return nil, err
  end

  -- get cluster release version

  local peers, err = self.cluster:get_peers()
  if err then
    return nil, err
  end

  if not peers then
    return nil, "no peers in shm"
  end

  local major_version
  local major_minor_version

  for i = 1, #peers do
    local release_version = peers[i].release_version
    if not release_version then
      log.warn("no release_version for peer ", peers[i].host)

    else
      local major_minor, major = extract_major_minor(release_version)
      major = tonumber(major)
      if not (major_minor and major) then
        return nil, "failed to extract major version for peer " .. peers[i].host
                    .. " with version: " .. tostring(peers[i].release_version)
      end

      if not major_version then
        major_version = major
        major_minor_version = major_minor

      elseif major ~= major_version then
        return nil, "different major versions detected"
      end
    end
  end

  self.major_version = major_version
  self.major_minor_version = major_minor_version

  return true
end

function CassandraConnector:init_worker()
  if self.refresh_frequency > 0 then
    local hdl, err = ngx.timer.every(self.refresh_frequency, function()
      local ok, err, topology = self.cluster:refresh(self.refresh_frequency)
      if not ok then
        ngx.log(ngx.ERR, "[cassandra] failed to refresh cluster topology: ",
                         err)

      elseif topology then
        if #topology.added > 0 then
          ngx.log(ngx.NOTICE, "[cassandra] peers added to cluster topology: ",
                              table.concat(topology.added, ", "))
        end

        if #topology.removed > 0 then
          ngx.log(ngx.NOTICE, "[cassandra] peers removed from cluster topology: ",
                              table.concat(topology.removed, ", "))
        end
      end
    end)
    if not hdl then
      return nil, "failed to initialize Cassandra topology refresh timer: " ..
                  err
    end
  end

  return true
end

function CassandraConnector:infos()
  local db_ver
  if self.major_minor_version then
    db_ver = extract_major_minor(self.major_minor_version)
  end

  return {
    strategy = "Cassandra",
    db_name = self.keyspace,
    db_desc = "keyspace",
    db_ver = db_ver or "unknown",
  }
end

function CassandraConnector:connect()
  local conn = self:get_stored_connection()
  if conn then
    return conn
  end

  local peer, err = self.cluster:next_coordinator()
  if not peer then
    return nil, err
  end

  self:store_connection(peer)

  return peer
end

-- open a connection from the first available contact point,
-- without a keyspace
function CassandraConnector:connect_migrations(opts)
  local conn = self:get_stored_connection()
  if conn then
    return conn
  end

  opts = opts or {}

  local peer, err = self.cluster:first_coordinator()
  if not peer then
    return nil, "failed to acquire contact point: " .. err
  end

  if not opts.no_keyspace then
    local ok, err = peer:change_keyspace(self.keyspace)
    if not ok then
      return nil, err
    end
  end

  self:store_connection(peer)

  return peer
end

function CassandraConnector:setkeepalive()
  local conn = self:get_stored_connection()
  if not conn then
    return true
  end

  local _, err = conn:setkeepalive()

  self:store_connection(nil)

  if err then
    return nil, err
  end

  return true
end

function CassandraConnector:close()
  local conn = self:get_stored_connection()
  if not conn then
    return true
  end

  local _, err = conn:close()

  self:store_connection(nil)

  if err then
    return nil, err
  end

  return true
end

function CassandraConnector:wait_for_schema_consensus()
  local conn = self:get_stored_connection()
  if not conn then
    error("no connection")
  end

  log.verbose("waiting for Cassandra schema consensus (%dms timeout)...",
              self.cluster.max_schema_consensus_wait)

  ngx.update_time()

  local ok, err
  local start = ngx.now() * 1000
  local max_wait = self.cluster.max_schema_consensus_wait
  local waited

  while true do
    -- we want to run the library function not try more than
    -- once as we implement our own timeout here with a proper
    -- sleep in between, and we don't care about errors as
    -- we want to try until the timeout
    ok, err = self.cluster:wait_schema_consensus(conn, -1)

    ngx.update_time()
    waited = ngx.now() * 1000 - start

    if ok then
      break
    end

    if waited >= max_wait then
      break
    end

    -- just some arbitrary sleep (100ms) between the tries
    ngx.sleep(0.1)
  end

  log.verbose("Cassandra schema consensus: %s in %dms",
              ok and "reached" or "not reached",
              waited)

  if err then
    return nil, "failed to wait for schema consensus: " .. err
  end

  return true
end

function CassandraConnector:query(query, args, opts, operation)
  if operation ~= nil and operation ~= "read" and operation ~= "write" then
    error("operation must be 'read' or 'write', was: " .. tostring(operation), 2)
  end

  if not opts then
    opts = {}
  end

  if operation == "write" then
    opts.consistency = self.opts.write_consistency

  else
    opts.consistency = self.opts.read_consistency
  end

  opts.serial_consistency = self.opts.serial_consistency

  local conn = self:get_stored_connection()

  local coordinator = conn

  if not conn then
    local err
    coordinator, err = self.cluster:next_coordinator()
    if not coordinator then
      return nil, err
    end
  end

  local t_cql = pl_stringx.split(query, ";")

  local res, err

  if #t_cql == 1 then
    -- TODO: prepare queries
    res, err = coordinator:execute(query, args, opts)

  else
    for i = 1, #t_cql do
      local cql = pl_stringx.strip(t_cql[i])
      if cql ~= "" then
        res, err = coordinator:execute(cql, nil, opts)
        if not res then
          break
        end
      end
    end
  end

  if not conn then
    coordinator:setkeepalive()
  end

  if err then
    return nil, err
  end

  return res
end

function CassandraConnector:batch(query_args, opts, operation, logged)
  if operation ~= nil and operation ~= "read" and operation ~= "write" then
    error("operation must be 'read' or 'write', was: " .. tostring(operation), 2)
  end

  if not opts then
    opts = {}
  end

  if operation == "write" then
    opts.consistency = self.opts.write_consistency

  else
    opts.consistency = self.opts.read_consistency
  end

  opts.serial_consistency = self.opts.serial_consistency

  opts.logged = logged

  local conn = self:get_stored_connection()

  local coordinator = conn

  if not conn then
    local err
    coordinator, err = self.cluster:next_coordinator()
    if not coordinator then
      return nil, err
    end
  end

  local res, err = coordinator:batch(query_args, opts)

  if not conn then
    coordinator:setkeepalive()
  end

  if err then
    return nil, err
  end

  return res
end

local function select_keyspaces(self)
  local conn = self:get_stored_connection()
  if not conn then
    error("no connection")
  end

  if not self.major_version then
    return nil, "missing self.major_version"
  end

  local cql

  if self.major_version >= 3 then
    cql = [[SELECT * FROM system_schema.keyspaces
              WHERE keyspace_name = ?]]

  else
    cql = [[SELECT * FROM system.schema_keyspaces
              WHERE keyspace_name = ?]]
  end

  return conn:execute(cql, { self.keyspace })
end

local function select_tables(self)
  local conn = self:get_stored_connection()
  if not conn then
    error("no connection")
  end

  if not self.major_version then
    return nil, "missing self.major_version"
  end

  local cql

  -- Assume a release version number of 3 & greater will use the same schema.
  if self.major_version >= 3 then
    cql = [[SELECT * FROM system_schema.tables WHERE keyspace_name = ?]]

  else
    cql = [[SELECT * FROM system.schema_columnfamilies
            WHERE keyspace_name = ?]]
  end

  return conn:execute(cql, { self.keyspace })
end

function CassandraConnector:reset()
  local ok, err = self:connect()
  if not ok then
    return nil, err
  end

  local rows, err = select_tables(self)
  if not rows then
    return nil, err
  end

  for i = 1, #rows do
    -- Assume a release version number of 3 & greater will use the same schema.
    local table_name = self.major_version >= 3
                       and rows[i].table_name
                       or rows[i].columnfamily_name

    -- deletes table and indexes
    local cql = string.format("DROP TABLE %s.%s",
                              self.keyspace, table_name)

    local ok, err = self:query(cql)
    if not ok then
      self:setkeepalive()
      return nil, err
    end
  end

  ok, err = self:wait_for_schema_consensus()
  if not ok then
    self:setkeepalive()
    return nil, err
  end

  ok, err = self:setkeepalive()
  if not ok then
    return nil, err
  end

  return true
end

function CassandraConnector:truncate()
  local ok, err = self:connect()
  if not ok then
    return nil, err
  end

  local rows, err = select_tables(self)
  if not rows then
    return nil, err
  end

  for i = 1, #rows do
    -- Assume a release version number of 3 & greater will use the same schema.
    local table_name = self.major_version >= 3
                       and rows[i].table_name
                       or rows[i].columnfamily_name

    if table_name ~= "schema_migrations" and
       table_name ~= "schema_meta" and
       table_name ~= "parameters" and
       table_name ~= "locks"
    then
      local cql = string.format("TRUNCATE TABLE %s.%s",
                                self.keyspace, table_name)

      local ok, err = self:query(cql, nil, nil, "write")
      if not ok then
        self:setkeepalive()
        return nil, err
      end
    end
  end

  ok, err = self:setkeepalive()
  if not ok then
    return nil, err
  end

  return true
end

function CassandraConnector:truncate_table(table_name)
  local cql = string.format("TRUNCATE TABLE %s.%s",
                            self.keyspace, table_name)

  return self:query(cql, nil, nil, "write")
end

function CassandraConnector:setup_locks(default_ttl, no_schema_consensus)
  local ok, err = self:connect()
  if not ok then
    return nil, err
  end

  log.debug("creating 'locks' table if not existing...")

  local cql = string.format([[
    CREATE TABLE IF NOT EXISTS locks(
      key text PRIMARY KEY,
      owner text
    ) WITH default_time_to_live = %d
  ]], default_ttl)

  local ok, err = self:query(cql)
  if not ok then
    self:setkeepalive()
    return nil, err
  end

  log.debug("successfully created 'locks' table")

  if not no_schema_consensus then
    -- called from tests, ignored when called from bootstrapping, since
    -- we wait for schema consensus as part of bootstrap
    ok, err = self:wait_for_schema_consensus()
    if not ok then
      self:setkeepalive()
      return nil, err
    end

    self:setkeepalive()
  end

  return true
end

function CassandraConnector:insert_lock(key, ttl, owner)
  local cql = string.format([[
    INSERT INTO locks(key, owner)
      VALUES(?, ?)
      IF NOT EXISTS
      USING TTL %d
  ]], ttl)

  local res, err = self:query(cql, { key, owner }, {
    consistency = cassandra.consistencies.quorum,
  })
  if not res then
    return nil, err
  end

  res = res[1]
  if not res then
    return nil, "unexpected result"
  end

  return res["[applied]"]
end

function CassandraConnector:read_lock(key)
  local res, err = self:query([[
    SELECT * FROM locks WHERE key = ?
  ]], { key }, {
    consistency = cassandra.consistencies.serial,
  })
  if not res then
    return nil, err
  end

  return res[1] ~= nil
end

function CassandraConnector:remove_lock(key, owner)
  local res, err = self:query([[
    DELETE FROM locks WHERE key = ? IF owner = ?
  ]], { key, owner }, {
    consistency = cassandra.consistencies.quorum,
  })
  if not res then
    return nil, err
  end

  return true
end

do
  -- migrations

  local SCHEMA_META_KEY = "schema_meta"

  function CassandraConnector:schema_migrations()
    local conn, err = self:connect()
    if not conn then
      error(err)
    end

    do
      -- has keyspace table?

      local rows, err = select_keyspaces(self)
      if not rows then
        return nil, err
      end

      local has_keyspace

      for _, row in ipairs(rows) do
        if row.keyspace_name == self.keyspace then
          has_keyspace = true
          break
        end
      end

      if not has_keyspace then
        -- no keyspace needs bootstrap
        return nil
      end
    end

    do
      -- has schema_meta table?

      local rows, err = select_tables(self)
      if not rows then
        return nil, err
      end

      local has_schema_meta_table

      for _, row in ipairs(rows) do
        -- Cassandra 3: table_name
        -- Cassadra 2: columnfamily_name
        if row.table_name == "schema_meta"
          or row.columnfamily_name == "schema_meta" then
          has_schema_meta_table = true
          break
        end
      end

      if not has_schema_meta_table then
        -- keyspace, but no schema: needs bootstrap
        return nil
      end
    end

    local ok, err = conn:change_keyspace(self.keyspace)
    if not ok then
      return nil, err
    end

    do
      -- has migrations?

      local rows, err = conn:execute([[
        SELECT * FROM schema_meta WHERE key = ?
      ]], {
        SCHEMA_META_KEY,
      })
      if not rows then
        return nil, err
      end

      -- no migrations: is bootstrapped but not migrated
      -- migrations: has some migrations
      return rows
    end
  end

  function CassandraConnector:schema_bootstrap(kong_config, default_locks_ttl)
    -- compute keyspace creation CQL

    local cql_replication
    local cass_repl_strategy = kong_config.cassandra_repl_strategy

    if cass_repl_strategy == "SimpleStrategy" then
      cql_replication = string.format([[
        {'class': 'SimpleStrategy', 'replication_factor': %d}
      ]], kong_config.cassandra_repl_factor)

    elseif cass_repl_strategy == "NetworkTopologyStrategy" then
      local dcs = {}

      for _, dc_conf in ipairs(kong_config.cassandra_data_centers) do
        local dc_name, dc_repl = string.match(dc_conf, "([^:]+):(%d+)")
        if dc_name and dc_repl then
          table.insert(dcs, string.format("'%s': %s", dc_name, dc_repl))
        end
      end

      if #dcs < 1 then
        return nil, "invalid cassandra_data_centers configuration"
      end

      cql_replication = string.format([[
        {'class': 'NetworkTopologyStrategy', %s}
      ]], table.concat(dcs, ", "))

    else
      error("unknown replication_strategy: " .. tostring(cass_repl_strategy))
    end

    -- get a contact point connection (no keyspace set)

    local conn = self:get_stored_connection()
    if not conn then
      error("no connection")
    end

    -- create keyspace if not exists

    local keyspace = kong_config.cassandra_keyspace
    local ok = conn:change_keyspace(keyspace)
    if not ok then
      log.debug("creating '%s' keyspace if not existing...", keyspace)

      local res, err = conn:execute(string.format([[
        CREATE KEYSPACE IF NOT EXISTS %q
        WITH REPLICATION = %s
      ]], keyspace, cql_replication))
      if not res then
        return nil, err
      end

      log.debug("successfully created '%s' keyspace", keyspace)
    end

    local ok, err = conn:change_keyspace(keyspace)
    if not ok then
      return nil, err
    end

    -- create schema meta table if not exists

    log.debug("creating 'schema_meta' table if not existing...")

    local res, err = conn:execute([[
      CREATE TABLE IF NOT EXISTS schema_meta(
        key             text,
        subsystem       text,
        last_executed   text,
        executed        set<text>,
        pending         set<text>,

        PRIMARY KEY (key, subsystem)
      )
    ]])
    if not res then
      return nil, err
    end

    log.debug("successfully created 'schema_meta' table")

    ok, err = self:setup_locks(default_locks_ttl, true) -- no schema consensus
    if not ok then
      return nil, err
    end

    ok, err = self:wait_for_schema_consensus()
    if not ok then
      return nil, err
    end

    return true
  end

  function CassandraConnector:schema_reset()
    local conn = self:get_stored_connection()
    if not conn then
      error("no connection")
    end

    local ok, err = conn:execute(string.format([[
      DROP KEYSPACE IF EXISTS %q
    ]], self.keyspace))
    if not ok then
      return nil, err
    end

    log("dropped '%s' keyspace", self.keyspace)

    ok, err = self:wait_for_schema_consensus()
    if not ok then
      return nil, err
    end

    return true
  end

  function CassandraConnector:run_up_migration(name, up_cql)
    if type(name) ~= "string" then
      error("name must be a string", 2)
    end

    if type(up_cql) ~= "string" then
      error("up_cql must be a string", 2)
    end

    local conn = self:get_stored_connection()
    if not conn then
      error("no connection")
    end

    local t_cql = pl_stringx.split(up_cql, ";")

    for i = 1, #t_cql do
      local cql = pl_stringx.strip(t_cql[i])
      if cql ~= "" then
        local res, err = conn:execute(cql)
        if not res then
          if string.find(err, "Column .- was not found in table")
          or string.find(err, "[Ii]nvalid column name")
          or string.find(err, "[Uu]ndefined column name")
          or string.find(err, "No column definition found for column")
          or string.find(err, "Undefined name .- in selection clause")
          or string.find(err, "Column with name .- already exists")
          then
            log.warn("ignored error while running '%s' migration: %s (%s)",
                     name, err, cql:gsub("\n", " "):gsub("%s%s+", " "))
          else
            return nil, err
          end
        end
      end
    end

    return true
  end

  function CassandraConnector:record_migration(subsystem, name, state)
    if type(subsystem) ~= "string" then
      error("subsystem must be a string", 2)
    end

    if type(name) ~= "string" then
      error("name must be a string", 2)
    end

    local conn = self:get_stored_connection()
    if not conn then
      error("no connection")
    end

    local cql
    local args
    local opts = { consistency = self.opts.write_consistency }

    if state == "executed" then
      cql = [[UPDATE schema_meta
              SET last_executed = ?, executed = executed + ?
              WHERE key = ? AND subsystem = ?]]
      args = {
        name,
        cassandra.set({ name }),
      }

    elseif state == "pending" then
      cql = [[UPDATE schema_meta
              SET pending = pending + ?
              WHERE key = ? AND subsystem = ?]]
      args = {
        cassandra.set({ name }),
      }

    elseif state == "teardown" then
      cql = [[UPDATE schema_meta
              SET pending = pending - ?, executed = executed + ?,
                  last_executed = ?
              WHERE key = ? AND subsystem = ?]]
      args = {
        cassandra.set({ name }),
        cassandra.set({ name }),
        name,
      }

    else
      error("unknown 'state' argument: " .. tostring(state))
    end

    table.insert(args, SCHEMA_META_KEY)
    table.insert(args, subsystem)

    local res, err = conn:execute(cql, args, opts)
    if not res then
      return nil, err
    end

    return true
  end
end

return CassandraConnector


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.drip.sample.spline Class Hierarchy</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.drip.sample.spline

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.drip.sample.spline.BasisBSplineSet

org.drip.sample.spline.BasisMonicBSpline

org.drip.sample.spline.BasisMonicHatComparison

org.drip.sample.spline.BasisMulticBSpline

org.drip.sample.spline.BasisSplineSet

org.drip.sample.spline.BasisTensionSplineSet

org.drip.sample.spline.BSplineSequence

org.drip.sample.spline.PolynomialBasisSpline

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/cloudfront/CloudFront_EXPORTS.h>
#include <aws/cloudfront/CloudFrontRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/cloudfront/model/FunctionConfig.h>
#include <aws/core/utils/Array.h>
#include <utility>

namespace Aws
{
namespace CloudFront
{
namespace Model
{

  /**
   */
  class AWS_CLOUDFRONT_API CreateFunction2020_05_31Request : public CloudFrontRequest
  {
  public:
    CreateFunction2020_05_31Request();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateFunction"; }

    Aws::String SerializePayload() const override;

    /**
     *
A name to identify the function.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
A name to identify the function.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
A name to identify the function.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
A name to identify the function.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
A name to identify the function.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
A name to identify the function.

     */
    inline CreateFunction2020_05_31Request& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
A name to identify the function.

     */
    inline CreateFunction2020_05_31Request& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
A name to identify the function.

     */
    inline CreateFunction2020_05_31Request& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
Configuration information about the function, including an optional comment
     * and the function's runtime.

     */
    inline const FunctionConfig& GetFunctionConfig() const{ return m_functionConfig; }

    /**
     *
Configuration information about the function, including an optional comment
     * and the function's runtime.

     */
    inline bool FunctionConfigHasBeenSet() const { return m_functionConfigHasBeenSet; }

    /**
     *
Configuration information about the function, including an optional comment
     * and the function's runtime.

     */
    inline void SetFunctionConfig(const FunctionConfig& value) { m_functionConfigHasBeenSet = true; m_functionConfig = value; }

    /**
     *
Configuration information about the function, including an optional comment
     * and the function's runtime.

     */
    inline void SetFunctionConfig(FunctionConfig&& value) { m_functionConfigHasBeenSet = true; m_functionConfig = std::move(value); }

    /**
     *
Configuration information about the function, including an optional comment
     * and the function's runtime.

     */
    inline CreateFunction2020_05_31Request& WithFunctionConfig(const FunctionConfig& value) { SetFunctionConfig(value); return *this;}

    /**
     *
Configuration information about the function, including an optional comment
     * and the function's runtime.

     */
    inline CreateFunction2020_05_31Request& WithFunctionConfig(FunctionConfig&& value) { SetFunctionConfig(std::move(value)); return *this;}

    /**
     *
The function code. For more information about writing a CloudFront function,
     * see Writing
     * function code for CloudFront Functions in the Amazon CloudFront Developer
     * Guide.

     */
    inline const Aws::Utils::CryptoBuffer& GetFunctionCode() const{ return m_functionCode; }

    /**
     *
The function code. For more information about writing a CloudFront function,
     * see Writing
     * function code for CloudFront Functions in the Amazon CloudFront Developer
     * Guide.

     */
    inline bool FunctionCodeHasBeenSet() const { return m_functionCodeHasBeenSet; }

    /**
     *
The function code. For more information about writing a CloudFront function,
     * see Writing
     * function code for CloudFront Functions in the Amazon CloudFront Developer
     * Guide.

     */
    inline void SetFunctionCode(const Aws::Utils::CryptoBuffer& value) { m_functionCodeHasBeenSet = true; m_functionCode = value; }

    /**
     *
The function code. For more information about writing a CloudFront function,
     * see Writing
     * function code for CloudFront Functions in the Amazon CloudFront Developer
     * Guide.

     */
    inline void SetFunctionCode(Aws::Utils::CryptoBuffer&& value) { m_functionCodeHasBeenSet = true; m_functionCode = std::move(value); }

    /**
     *
The function code. For more information about writing a CloudFront function,
     * see Writing
     * function code for CloudFront Functions in the Amazon CloudFront Developer
     * Guide.

     */
    inline CreateFunction2020_05_31Request& WithFunctionCode(const Aws::Utils::CryptoBuffer& value) { SetFunctionCode(value); return *this;}

    /**
     *
The function code. For more information about writing a CloudFront function,
     * see Writing
     * function code for CloudFront Functions in the Amazon CloudFront Developer
     * Guide.

     */
    inline CreateFunction2020_05_31Request& WithFunctionCode(Aws::Utils::CryptoBuffer&& value) { SetFunctionCode(std::move(value)); return *this;}

  private:

    Aws::String m_name;
    bool m_nameHasBeenSet = false;

    FunctionConfig m_functionConfig;
    bool m_functionConfigHasBeenSet = false;

    Aws::Utils::CryptoBuffer m_functionCode;
    bool m_functionCodeHasBeenSet = false;
  };

} // namespace Model
} // namespace CloudFront
} // namespace Aws


text:
<?xml version="1.0" encoding="utf-8" ?>
<Suite Title="Twingly" Id="Twingly" Category="Social" RequireVersion="8.2" SourceUrl="https://github.com/nielsbosma/SeoTools-for-Excel-Connectors/blob/master/Twingly.xml" HelpUrl="https://seotoolsforexcel.com/twingly/" HelpText="Documentation">

  <Settings HelpText="What's this?">
    <Text Id="ApiKey" Title="ApiKey" Required="true" HelpUrl="https://seotoolsforexcel.com/twingly/"/>
  </Settings>

  <RestConnector Id="Twingly" HelpUrl="https://developer.twingly.com/resources/search/">
    <Parameters>
      <Text Id="Query" Title="Query" Required="false" Debug.DefaultValue="almedalen" HelpText="https://developer.twingly.com/resources/search-language/"/>
      <Text Id="Domain" Title="Published on Domain" Required="false"/>
      <Text Id="PageLinking" Title="Contains Link to URL/Domain" Required="false"/>
      <Text Id="Author" Title="Author" Required="false"/>
      <Text Id="Tags" Title="Contains Tag" Required="false"/>
      <Select Id="Country" Title="Country" DefaultValue="all">
        <DataSource>
					<Item Id="all" Title="All"/>
          <ISOCountryCodes/>
        </DataSource>
      </Select>
      <Select Id="Language" Title="Language" DefaultValue="all">
        <DataSource>
					<Item Id="all" Title="All"/>
          <ISOLanguageCodes/>
        </DataSource>
      </Select>
      <DateInterval Id="DateInterval" Title="Date Interval" Required="true" Nullable="false" DefaultValue="ThisYear"/>
      <Select Id="Sort" Title="Sort" DefaultValue="published%20sort-order:desc" Required="false">
        <DataSource>
					<Item Id="published%20sort-order:desc" Title="Published Descending"/>
					<Item Id="published%20sort-order:asc" Title="Published Ascending"/>
					<Item Id="inlinks%20sort-order:desc" Title="Inbound Links Descending"/>
					<Item Id="inlinks%20sort-order:asc" Title="Inbound Links Ascending"/>
					<Item Id="twinglyrank%20sort-order:desc" Title="Twingly Rank Descending"/>
					<Item Id="twinglyrank%20sort-order:asc" Title="Twingly Rank Ascending"/>
        </DataSource>
      </Select>
    </Parameters>
    <Paging PageSize="100">
      <Parse>
        <XPath Id="AvaliableRows" Expr="twinglydata" Attribute="numberOfMatchesTotal" Converter="Int"/>
      </Parse>
    </Paging>
    <Fetch>
      <Fetch.Url>
        <![CDATA[
			https://api.twingly.com/blog/search/api/v3/search?apikey=@(Model.ApiKey)
			&q=
       @(!string.IsNullOrEmpty(Model.Domain) ? "site:" + Utils.UrlEncode(Model.Domain) + "%20" : "")
       @(!string.IsNullOrEmpty(Model.PageLinking) ? "link:" + Utils.UrlEncode(Model.PageLinking) + "%20" : "")
       @(!string.IsNullOrEmpty(Model.Tags) ? "tag:" + Utils.UrlEncode(Model.Tags) + "%20" : "")
       @(!string.IsNullOrEmpty(Model.Author) ? "author:" + Utils.UrlEncode(Model.Author) + "%20" : "")
			%20start-date:%22 @Utils.UrlEncode(((DateTime)Model.DateInterval.StartDate).ToString("yyyy-MM-dd"))%2000:00:00%22
			%20end-date:%22 @Utils.UrlEncode(((DateTime)Model.DateInterval.EndDate).ToString("yyyy-MM-dd"))%2023:59:59%22%20
			@Utils.UrlEncode(Model.Query)%20
			@(Model.Country != "all" ? "location:" + Model.Country + "%20" : "")
			@(Model.Language != "all" ? "lang:" + Model.Language + "%20" : "")
      page:@(Model.PageCursor.Page+1)%20page-size:@(Model.PageCursor.PageSize)%20
      sort:@(Model.Sort)
			&format=xml
      ]]>
      </Fetch.Url>
    </Fetch>
    <Parse>
      <XPath Expr="//post">
				<XPath Title="URL" Id="Url" Expr="url" Converter="String"/>
				<XPath Title="Date" Id="Date" Expr="publishedat" Converter="DateTime"/>
				<XPath Title="Title" Id="Title" Expr="title" Converter="String"/>
        <Compute Id="Summary" Title="Summary">
          <Compute.Expr>
            <![CDATA[
            @(Model.Summary.Length > 7500 ? Model.Summary.Substring(0, 7500) : Model.Summary)
            ]]>
          </Compute.Expr>
					<XPath Title="Summary" Id="Summary" Expr="text" Converter="String"/>
        </Compute>
				<Compute Expr="@Utils.IsoLanguageCodeToName(Model.Inp)" Id="Language" Converter="Auto">
					<XPath Expr="languagecode" Id="Inp" DefaultValue=""/>
				</Compute>
				<Compute Expr="@Utils.IsoCountryCodeToName(Model.Inp)" Id="Location" Converter="Auto">
					<XPath Expr="locationcode" Id="Inp" DefaultValue=""/>
				</Compute>
				<XPath Title="Tags" Id="Tags" Expr="csv(tags/tag)" Converter="String"/>
				<XPath Title="Blog URL" Id="BlogUrl" Expr="blogurl" Converter="String"/>
				<XPath Title="Blog Name" Id="BlogName" Expr="blogname" Converter="String"/>
				<XPath Title="Blog Author" Id="BlogAuthor" Expr="author" Converter="String"/>
				<XPath Title="Inlinks" Id="InboundLinks" Expr="inlinkscount" Converter="Int"/>
				<XPath Title="BlogRank" Id="BlogRank" Expr="blogrank" Converter="Int"/>
				<XPath Title="Inbounds" Id="Authority" Expr="authority" Converter="Int"/>
			</XPath>
    </Parse>
		<Fail>
			<XPath Expr="error/message"/>
		</Fail>
  </RestConnector>

</Suite>


text:
from django.apps import AppConfig

class CompareConfig(AppConfig):
    name = 'compare'


text:
const { MIN_ECMA_VERSION } = require('./constants');

const astTypeToFeatures = getAstTypeToFeatures(require('../data/es-features'));

function getAstTypeToFeatures(esFeatures) {
  const astTypeToFeatures = new Map();
  for (const feature of esFeatures) {
    if (!astTypeToFeatures.has(feature.astType)) {
      astTypeToFeatures.set(feature.astType, []);
    }
    astTypeToFeatures.get(feature.astType).push(feature);
  }
  return astTypeToFeatures;
}

function getNodeEcmaVersion(node) {
  const features = astTypeToFeatures.has(node.type)
    ? astTypeToFeatures.get(node.type)
    : [];
  const matchedEcmaVersions = features
    .filter((feature) => (feature.isMatch ? feature.isMatch(node) : true))
    .map((feature) => feature.ecmaVersion);
  return Math.max(...matchedEcmaVersions, MIN_ECMA_VERSION);
}

module.exports = getNodeEcmaVersion;


text:
<?php

/*
 * This file is part of felpado.
 *
 * (c) Pablo Díez <pablodip@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace felpado;

use felpado as f;

/**
 * f\last($coll)
 *
 * Returns the last value of collection, or null if collection is empty.
 *
 * f\last(array(1, 2, 3));
 * => 3
 *
 * f\last(array());
 * => null
 */
function last($coll) {
    $array = f\to_array($coll);
    $last = end($array);

    return $last !== false ? $last : (count($array) ? false : null);
}


text:
<?php

namespace Opis\Colibri;

abstract class ModuleInstaller
{

    /**
     * Constructor
     */
    final protected function __construct()
    {

    }

    /**
     * Factory
     *
     * @return  \static
     */
    final public static function instance()
    {
        return new static();
    }

    /**
     * Install action
     *
     * @param   \Opis\Colibri\Application   $app
     */
    public function install(Application $app)
    {

    }

    /**
     * Uninstall action
     *
     * @param   \Opis\Colibri\Application   $app
     */
    public function uninstall(Application $app)
    {

    }

    /**
     * Enable action
     *
     * @param   \Opis\Colibri\Application   $app
     */
    public function enable(Application $app)
    {

    }

    /**
     * Disable action
     *
     * @param   \Opis\Colibri\Application   $app
     */
    public function disable(Application $app)
    {

    }
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ServiceStack.Web
{
    [Obsolete("Use IPartialWriterAsync")]
	public interface IPartialWriter
	{
        /// <summary>
        /// Whether this HttpResult allows Partial Response
        /// </summary>
        bool IsPartialRequest { get; }

        /// <summary>
        /// Write a partial content result
        /// </summary>
        void WritePartialTo(IResponse response);
	}

    public interface IPartialWriterAsync
    {
        /// <summary>
        /// Whether this HttpResult allows Partial Response
        /// </summary>
        bool IsPartialRequest { get; }

        /// <summary>
        /// Write a partial content result
        /// </summary>
        Task WritePartialToAsync(IResponse response, CancellationToken token = default(CancellationToken));
    }
}


text:
package com.thebuzzmedia.exiftool.readme.stayopen;

import com.thebuzzmedia.exiftool.ExifTool;
import com.thebuzzmedia.exiftool.ExifToolBuilder;
import com.thebuzzmedia.exiftool.Tag;
import com.thebuzzmedia.exiftool.core.StandardTag;
import com.thebuzzmedia.exiftool.exceptions.UnsupportedFeatureException;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

public class ExifParser {

	private static final ExifTool exifTool = detect();

	private static ExifTool detect() {
		try {
			return new ExifToolBuilder().enableStayOpen().build();
		} catch (UnsupportedFeatureException ex) {
			// Fallback to simple exiftool instance.
			return new ExifToolBuilder().build();
		}
	}

	public static Map<Tag, String> parse(File image) throws IOException {
		return exifTool.getImageMeta(image, Arrays.asList(
				StandardTag.ISO,
				StandardTag.X_RESOLUTION,
				StandardTag.Y_RESOLUTION
		));
	}

	public static void main(String[] args) throws Exception {
		try {
			for (String image : args) {
				System.out.println("Tags: "+ ExifParser.parse(new File(image)));
			}
		} finally {
			exifTool.close();
		}
	}
}


text:
System.register(['./property-observation'], function (_export) {
  'use strict';

  var BreezeObjectObserver, BreezeObservationAdapter;

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

  function createObserverLookup(obj) {
    var value = new BreezeObjectObserver(obj);

    Object.defineProperty(obj, '__breezeObserver__', {
      enumerable: false,
      configurable: false,
      writable: false,
      value: value
    });

    return value;
  }

  function createCanObserveLookup(entityType) {
    var value = {};
    var properties = entityType.getProperties();
    for (var i = 0, ii = properties.length; i < ii; i++) {
      var property = properties[i];

      value[property.name] = property.isDataProperty || property.isScalar;
    }

    Object.defineProperty(entityType, '__canObserve__', {
      enumerable: false,
      configurable: false,
      writable: false,
      value: value
    });

    return value;
  }

  return {
    setters: [function (_propertyObservation) {
      BreezeObjectObserver = _propertyObservation.BreezeObjectObserver;
    }],
    execute: function () {
      BreezeObservationAdapter = (function () {
        function BreezeObservationAdapter() {
          _classCallCheck(this, BreezeObservationAdapter);
        }

        BreezeObservationAdapter.prototype.getObserver = function getObserver(object, propertyName, descriptor) {
          var type = object.entityType;
          if (!type || !(type.__canObserve__ || createCanObserveLookup(type))[propertyName]) {
            return null;
          }

          var observerLookup = object.__breezeObserver__ || createObserverLookup(object);
          return observerLookup.getObserver(propertyName);
        };

        return BreezeObservationAdapter;
      })();

      _export('BreezeObservationAdapter', BreezeObservationAdapter);
    }
  };
});


text:
namespace
{
	class CMapiObjects;
}

namespace dialog
{
	class CProfileListDlg : public CContentsTableDlg
	{
	public:
		CProfileListDlg(_In_ std::shared_ptr<cache::CMapiObjects> lpMapiObjects, _In_ LPMAPITABLE lpMAPITable);
		~CProfileListDlg();

	private:
		// Overrides from base class
		void OnDeleteSelectedItem() override;
		void OnDisplayItem() override;
		void OnRefreshView() override;
		void HandleCopy() override;
		_Check_return_ bool HandlePaste() override;

		// Menu items
		void OnAddExchangeToProfile();
		void OnAddPSTToProfile();
		void OnAddUnicodePSTToProfile();
		void OnAddServicesToMAPISVC();
		void OnAddServiceToProfile();
		void OnCreateProfile();
		void OnGetMAPISVC();
		void OnGetProfileServiceVersion();
		void OnInitMenu(_In_ CMenu* pMenu) override;
		void OnLaunchProfileWizard();
		void OnRemoveServicesFromMAPISVC();
		void OnSetDefaultProfile();
		void OnOpenProfileByName();
		void OnExportProfile();

		void AddPSTToProfile(bool bUnicodePST);

		DECLARE_MESSAGE_MAP()
	};
} // namespace dialog


text:
public class Foo {
    public Foo getIfReady() {
        return new Foo();
    }
}


text:
/* Test -Wpointer-to-int-cast.  */
/* Origin: Joseph Myers <joseph@codesourcery.com> */
/* { dg-do compile } */
/* { dg-options "-Wpointer-to-int-cast" } */

void *p;

char
f (void)
{
  return (char) p; /* { dg-warning "warning: cast from pointer to integer of different size" } */
}


text:
class Collection < ActiveRecord::Base
  acts_as_tree
  has_many :collection_attributes
  has_many :networks
end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    android:fitsSystemWindows="true"
    tools:context="co.OscarSoft.CPTWC_Frag.ProfileActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_profile"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <!--include layout="@layout/content_profile" /-->

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_below="@+id/toolbar_profile"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/rlUserHeader">

        <ImageView
            android:id="@+id/ivProfileImage"
            android:layout_width="75dp"
            android:layout_height="75dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:adjustViewBounds="true"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvName"
            android:text="\@Name"
            android:layout_toRightOf="@+id/ivProfileImage"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvTagLine"
            android:text="Don't be Maybe. Be a coding monkey"
            android:layout_below="@+id/tvName"
            android:layout_toRightOf="@+id/ivProfileImage"
            android:layout_toEndOf="@+id/ivProfileImage" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/llCounts"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_below="@+id/rlUserHeader"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tvFollowers"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="5 Followers"/>

        <TextView
            android:id="@+id/tvFollowing"
            android:layout_width="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_height="wrap_content"
            android:text="5 Following" />
    </LinearLayout>

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/llCounts"
        android:id="@+id/flContainer"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"></FrameLayout>

</RelativeLayout>


text:
@implementation UIBarButtonItem (Extetion)

+(instancetype)itemWithImageName:(NSString *)imageName target:(id)target action:(SEL)action{
    UIButton *btn =[[UIButton alloc]init];

    //设置高亮图片
    [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@__highlighted",imageName]] forState:UIControlStateHighlighted];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
     //按钮点击事件
    btn.size =btn.currentImage.size;
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    return [[UIBarButtonItem alloc]initWithCustomView:btn];
}

+(instancetype)itemWithImageName:(NSString *)imageName target:(id)target action:(SEL)action titel:(NSString *)titel{

    UIButton *btn =[[UIButton alloc]init];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@__highlighted",imageName]] forState:UIControlStateHighlighted];
    ;
   // btn.size =btn.currentImage.size;

    [btn setTitle:titel forState:UIControlStateNormal];
    UIColor *color =RGB(68, 68, 68);
    [btn setTitleColor:color forState:UIControlStateNormal];

    //这个大小要放在设置了按钮的文字和图片大小以后
    [btn sizeToFit];
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    //注意: UIBarButtonItem 只是一个基本数据模型 是(NSObject类型)不是view   不能直接添加
    return [[UIBarButtonItem alloc]initWithCustomView:btn];

}

@end


text:
(function() {

    game.itemDefinitions = {
        "coins": createItem("coins", {
            imageUrl: 'currency/coins.png',
            name: 'Coin',
            pluralName: 'Coins',
            maxStackSize: 1000000
        }),
        "ringmail": createItem("ringmail", {
            imageUrl: 'equippable/torso/ringmail.png',
            name: 'Ring Mail',
            maxStackSize: 1,
            isEquippable: true,
            equipSlot: 'torso'
        })
    };

    function createItem(id, properties, handler){
        return new game.models.ItemDefinition(id, properties, handler);
    }

})();


text:
import datetime
import inspect
from dogpile.cache import make_region  # @UnresolvedImport
from dogpile.cache.backends.file import AbstractFileLock  # @UnresolvedImport
from dogpile.cache.compat import string_type  # @UnresolvedImport
from dogpile.core.readwrite_lock import ReadWriteMutex  # @UnresolvedImport

#: Subliminal's cache version
CACHE_VERSION = 1

#: Expiration time for show caching
SHOW_EXPIRATION_TIME = datetime.timedelta(weeks=3).total_seconds()

#: Expiration time for episode caching
EPISODE_EXPIRATION_TIME = datetime.timedelta(days=3).total_seconds()

def subliminal_key_generator(namespace, fn, to_str=string_type):
    """Add a :data:`CACHE_VERSION` to dogpile.cache's default function_key_generator"""
    if namespace is None:
        namespace = '%d:%s:%s' % (CACHE_VERSION, fn.__module__, fn.__name__)
    else:
        namespace = '%d:%s:%s|%s' % (CACHE_VERSION, fn.__module__, fn.__name__, namespace)

    args = inspect.getargspec(fn)
    has_self = args[0] and args[0][0] in ('self', 'cls')

    def generate_key(*args, **kw):
        if kw:
            raise ValueError('Keyword arguments not supported')
        if has_self:
            args = args[1:]
        return namespace + '|' + ' '.join(map(to_str, args))
    return generate_key

class MutexLock(AbstractFileLock):
    """:class:`MutexLock` is a thread-based rw lock based on :class:`dogpile.core.ReadWriteMutex`"""
    def __init__(self, filename):
        self.mutex = ReadWriteMutex()

    def acquire_read_lock(self, wait):
        ret = self.mutex.acquire_read_lock(wait)
        return wait or ret

    def acquire_write_lock(self, wait):
        ret = self.mutex.acquire_write_lock(wait)
        return wait or ret

    def release_read_lock(self):
        return self.mutex.release_read_lock()

    def release_write_lock(self):
        return self.mutex.release_write_lock()

# : The dogpile.cache region (long-lived)
region = make_region(function_key_generator=subliminal_key_generator)


text:
package com.ryandw11.structure.api;

import com.ryandw11.structure.loottables.LootTable;
import com.ryandw11.structure.structure.Structure;
import org.bukkit.Location;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;

/**
 * This event is called just before a container is populated with a loot table.
 */
public class LootPopulateEvent extends Event {

    private static final HandlerList handlers = new HandlerList();

    private final Structure structure;
    private final Location location;
    private final LootTable lootTable;
    private boolean canceled;

    /**
     * Construct the loot populate event.
     *
     * @param structure The structure.
     * @param location  The location.
     * @param lootTable The loot table.
     */
    public LootPopulateEvent(Structure structure, Location location, LootTable lootTable) {
        this.structure = structure;
        this.lootTable = lootTable;
        this.location = location;
        this.canceled = false;
    }

    /**
     * Get the structure that spawned.
     *
     * @return The structure that spawned.
     */
    public Structure getStructure() {
        return structure;
    }

    /**
     * Get the selected loot table for the container.
     *
     * @return The selected loot table for the container.
     */
    public LootTable getLootTable() {
        return lootTable;
    }

    /**
     * Get the location of the container.
     *
     * @return The location of the container.
     */
    public Location getLocation() {
        return location;
    }

    /**
     * Set if the event is canceled.
     *
     * @param canceled If the event is canceled.
     */
    public void setCanceled(boolean canceled) {
        this.canceled = canceled;
    }

    /**
     * Get if the event is canceled.
     *
     * @return if the event is canceled.
     */
    public boolean isCanceled() {
        return canceled;
    }

    @NotNull
    @Override
    public HandlerList getHandlers() {
        return handlers;
    }

    public static HandlerList getHandlerList() {
        return handlers;
    }
}


text:
print(__doc__)

from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest

def loadData():
    iris = load_iris()
    X, y = iris.data, iris.target
    return X, y

def computePCA():
    pca = PCA(n_components=2)
    return pca

def selectFeatures():
    selection = SelectKBest(k=1)
    return selection

def combineFeatures(pca, selection):
    combined_features = FeatureUnion([("pca", pca), \
                                      ("univ_select", selection)])  # Univariate selection
    return combined_features

def transformData(combined_features, X, y):
    X_features = combined_features.fit(X, y).transform(X)
    return X_features

def createSVM():
    svm = SVC(kernel='linear')
    return svm

def classify(svm, X_features, y):
    return svm.fit(X_features, y)

def searchGrid(combined_features, svm, X, y):
    pipeline = Pipeline([('features', combined_features), \
                         ('svm', svm)])

    param_grid = dict(features__pca__n_components=[1, 2, 3], \
                      features__univ_select__k=[1, 2], \
                      svm__C=[0.1, 1, 10])

    grid_search = GridSearchCV(pipeline, param_grid=param_grid, verbose=10)
    grid_search.fit(X, y)
    print(grid_search.best_estimator_)
    return grid_search.best_estimator_

def test():

    X, y = loadData()

    pca = computePCA()
    selection = selectFeatures
    combined_features = combineFeatures(pca, selection)

    svm = createSVM()
    X_features = transformData(combined_features, X, y)
    #y_pred = classify(svm, X_features, y)

    #searchGrid(combined_features, svm, X, y)

if __name__ == '__main__':
    test()


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.aurora.scheduler.reconciliation;

import javax.inject.Singleton;

import com.google.inject.AbstractModule;
import com.google.inject.PrivateModule;
import com.google.inject.TypeLiteral;
import com.twitter.common.args.Arg;
import com.twitter.common.args.CmdLine;
import com.twitter.common.args.constraints.Positive;
import com.twitter.common.quantity.Amount;
import com.twitter.common.quantity.Time;
import com.twitter.common.util.BackoffStrategy;
import com.twitter.common.util.TruncatedBinaryBackoff;

import org.apache.aurora.scheduler.SchedulerServicesModule;
import org.apache.aurora.scheduler.events.PubsubEventModule;
import org.apache.aurora.scheduler.reconciliation.TaskReconciler.TaskReconcilerSettings;

/**
 * Binding module for state reconciliation and retry logic.
 */
public class ReconciliationModule extends AbstractModule {

  @CmdLine(name = "transient_task_state_timeout",
      help = "The amount of time after which to treat a task stuck in a transient state as LOST.")
  private static final Arg<Amount<Long, Time>> TRANSIENT_TASK_STATE_TIMEOUT =
      Arg.create(Amount.of(5L, Time.MINUTES));

  @CmdLine(name = "initial_task_kill_retry_interval",
      help = "When killing a task, retry after this delay if mesos has not responded,"
          + " backing off up to transient_task_state_timeout")
  private static final Arg<Amount<Long, Time>> INITIAL_TASK_KILL_RETRY_INTERVAL =
      Arg.create(Amount.of(5L, Time.SECONDS));

  // Reconciliation may create a big surge of status updates in a large cluster. Setting the default
  // initial delay to 1 minute to ease up storage contention during scheduler start up.
  @CmdLine(name = "reconciliation_initial_delay",
      help = "Initial amount of time to delay task reconciliation after scheduler start up.")
  private static final Arg<Amount<Long, Time>> RECONCILIATION_INITIAL_DELAY =
      Arg.create(Amount.of(1L, Time.MINUTES));

  @Positive
  @CmdLine(name = "reconciliation_explicit_interval",
      help = "Interval on which scheduler will ask Mesos for status updates of all non-terminal "
          + "tasks known to scheduler.")
  private static final Arg<Amount<Long, Time>> RECONCILIATION_EXPLICIT_INTERVAL =
      Arg.create(Amount.of(60L, Time.MINUTES));

  @Positive
  @CmdLine(name = "reconciliation_implicit_interval",
      help = "Interval on which scheduler will ask Mesos for status updates of all non-terminal "
          + "tasks known to Mesos.")
  private static final Arg<Amount<Long, Time>> RECONCILIATION_IMPLICIT_INTERVAL =
      Arg.create(Amount.of(60L, Time.MINUTES));

  @CmdLine(name = "reconciliation_schedule_spread",
      help = "Difference between explicit and implicit reconciliation intervals intended to "
          + "create a non-overlapping task reconciliation schedule.")
  private static final Arg<Amount<Long, Time>> RECONCILIATION_SCHEDULE_SPREAD =
      Arg.create(Amount.of(30L, Time.MINUTES));

  @Override
  protected void configure() {
    install(new PrivateModule() {
      @Override
      protected void configure() {
        bind(new TypeLiteral<Amount<Long, Time>>() { })
            .toInstance(TRANSIENT_TASK_STATE_TIMEOUT.get());

        bind(TaskTimeout.class).in(Singleton.class);
        expose(TaskTimeout.class);
      }
    });
    PubsubEventModule.bindSubscriber(binder(), TaskTimeout.class);
    SchedulerServicesModule.addSchedulerActiveServiceBinding(binder()).to(TaskTimeout.class);

    install(new PrivateModule() {
      @Override
      protected void configure() {
        bind(BackoffStrategy.class).toInstance(
            new TruncatedBinaryBackoff(
                INITIAL_TASK_KILL_RETRY_INTERVAL.get(),
                TRANSIENT_TASK_STATE_TIMEOUT.get()));
        bind(KillRetry.class).in(Singleton.class);
        expose(KillRetry.class);
      }
    });
    PubsubEventModule.bindSubscriber(binder(), KillRetry.class);

    install(new PrivateModule() {
      @Override
      protected void configure() {
        bind(TaskReconcilerSettings.class).toInstance(new TaskReconcilerSettings(
            RECONCILIATION_INITIAL_DELAY.get(),
            RECONCILIATION_EXPLICIT_INTERVAL.get(),
            RECONCILIATION_IMPLICIT_INTERVAL.get(),
            RECONCILIATION_SCHEDULE_SPREAD.get()));
        bind(TaskReconciler.class).in(Singleton.class);
        expose(TaskReconciler.class);
      }
    });
    SchedulerServicesModule.addSchedulerActiveServiceBinding(binder()).to(TaskReconciler.class);
  }
}