text:
require_relative "../../../base"

require Vagrant.source_root.join("plugins/provisioners/ansible/config")
require Vagrant.source_root.join("plugins/provisioners/ansible/provisioner")

#
# Helper Functions
#

def find_last_argument_after(ref_index, ansible_playbook_args, arg_pattern)
  subset = ansible_playbook_args[(ref_index + 1)..(ansible_playbook_args.length-2)].reverse
  subset.each do |i|
    return true if i =~ arg_pattern
  end
  return false
end

describe VagrantPlugins::Ansible::Provisioner do
  include_context "unit"

  subject { described_class.new(machine, config) }

  let(:iso_env) do
    # We have to create a Vagrantfile so there is a Vagrant Environment to provide:
    # - a location for the generated inventory
    # - multi-machines configuration

    env = isolated_environment
    env.vagrantfile(<<-VF)
Vagrant.configure("2") do |config|
  config.vm.box = "base"
  config.vm.define :machine1
  config.vm.define :machine2
end
VF
    env.create_vagrant_env
  end

  let(:machine) { iso_env.machine(iso_env.machine_names[0], :dummy) }
  let(:config)  { VagrantPlugins::Ansible::Config.new }
  let(:ssh_info) {{
    private_key_path: ['/path/to/my/key'],
    username: 'testuser',
    host: '127.0.0.1',
    port: 2223
  }}

  let(:existing_file) { File.expand_path(__FILE__) }
  let(:generated_inventory_dir) { File.join(machine.env.local_data_path, %w(provisioners ansible inventory)) }
  let(:generated_inventory_file) { File.join(generated_inventory_dir, 'vagrant_ansible_inventory') }

  before do
    Vagrant::Util::Platform.stub(solaris?: false)
    subject.instance_variable_get(:@logger).stub(:debug?).and_return(false)

    machine.stub(ssh_info: ssh_info)
    machine.env.stub(active_machines: [[iso_env.machine_names[0], :dummy], [iso_env.machine_names[1], :dummy]])

    stubbed_ui = Vagrant::UI::Colored.new
    stubbed_ui.stub(detail: "")
    machine.env.stub(ui: stubbed_ui)

    config.playbook = 'playbook.yml'
  end

  #
  # Class methods for code reuse across examples
  #

  def self.it_should_set_arguments_and_environment_variables(
    expected_args_count = 7, expected_vars_count = 4, expected_host_key_checking = false, expected_transport_mode = "ssh")

    it "sets implicit arguments in a specific order" do
      expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|

        expect(args[0]).to eq("ansible-playbook")
        expect(args[1]).to eq("--private-key=#{machine.ssh_info[:private_key_path][0]}")
        expect(args[2]).to eq("--user=#{machine.ssh_info[:username]}")
        expect(args[3]).to eq("--connection=ssh")
        expect(args[4]).to eq("--timeout=30")

        inventory_count = args.count { |x| x =~ /^--inventory-file=.+$/ }
        expect(inventory_count).to be > 0

        expect(args[args.length-2]).to eq("playbook.yml")
      }
    end

    it "sets --limit argument" do
      expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
        all_limits = args.select { |x| x =~ /^(--limit=|-l)/ }
        if config.raw_arguments
          raw_limits = config.raw_arguments.select { |x| x =~ /^(--limit=|-l)/ }
          expect(all_limits.length - raw_limits.length).to eq(1)
          expect(all_limits.last).to eq(raw_limits.last)
        else
          if config.limit
            limit = config.limit.kind_of?(Array) ? config.limit.join(',') : config.limit
            expect(all_limits.last).to eq("--limit=#{limit}")
          else
            expect(all_limits.first).to eq("--limit=#{machine.name}")
          end
        end
      }
    end

    it "exports environment variables" do
      expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
        cmd_opts = args.last

        if expected_host_key_checking
          expect(cmd_opts[:env]['ANSIBLE_SSH_ARGS']).to_not include("-o UserKnownHostsFile=/dev/null")
        else
          expect(cmd_opts[:env]['ANSIBLE_SSH_ARGS']).to include("-o UserKnownHostsFile=/dev/null")
        end
        expect(cmd_opts[:env]['ANSIBLE_SSH_ARGS']).to include("-o IdentitiesOnly=yes")
        expect(cmd_opts[:env]['ANSIBLE_FORCE_COLOR']).to eql("true")
        expect(cmd_opts[:env]).to_not include("ANSIBLE_NOCOLOR")
        expect(cmd_opts[:env]['ANSIBLE_HOST_KEY_CHECKING']).to eql(expected_host_key_checking.to_s)
        expect(cmd_opts[:env]['PYTHONUNBUFFERED']).to eql(1)
      }
    end

    # "roughly" verify that only expected args/vars have been defined by the provisioner
    it "sets the expected number of arguments and environment variables" do
      expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
        expect(args.length-2).to eq(expected_args_count)
        expect(args.last[:env].length).to eq(expected_vars_count)
      }
    end

    it "enables '#{expected_transport_mode}' transport mode" do
      expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
        index = args.rindex("--connection=#{expected_transport_mode}")
        expect(index).to be > 0
        expect(find_last_argument_after(index, args, /--connection=\w+/)).to be_false
      }
    end

  end

  def self.it_should_set_optional_arguments(arg_map)
    it "sets optional arguments" do
      expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
        arg_map.each_pair do |vagrant_option, ansible_argument|
          index = args.index(ansible_argument)
          if config.send(vagrant_option)
            expect(index).to be > 0
          else
            expect(index).to be_nil
          end
        end
      }
    end
  end

  def self.it_should_explicitly_enable_ansible_ssh_control_persist_defaults
    it "configures ControlPersist (like Ansible defaults) via ANSIBLE_SSH_ARGS" do
      expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
        cmd_opts = args.last
        expect(cmd_opts[:env]['ANSIBLE_SSH_ARGS']).to include("-o ControlMaster=auto")
        expect(cmd_opts[:env]['ANSIBLE_SSH_ARGS']).to include("-o ControlPersist=60s")
      }
    end
  end

  def self.it_should_create_and_use_generated_inventory
    it "generates an inventory with all active machines" do
      expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
        expect(config.inventory_path).to be_nil
        expect(File.exists?(generated_inventory_file)).to be_true
        inventory_content = File.read(generated_inventory_file)
        expect(inventory_content).to include("#{machine.name} ansible_ssh_host=#{machine.ssh_info[:host]} ansible_ssh_port=#{machine.ssh_info[:port]}\n")
        expect(inventory_content).to include("# MISSING: '#{iso_env.machine_names[1]}' machine was probably removed without using Vagrant. This machine should be recreated.\n")
      }
    end

    it "sets as ansible inventory the directory containing the auto-generated inventory file" do
      expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
        inventory_index = args.rindex("--inventory-file=#{generated_inventory_dir}")
        expect(inventory_index).to be > 0
        expect(find_last_argument_after(inventory_index, args, /--inventory-file=\w+/)).to be_false
      }
    end
  end

  describe "#provision" do

    before do
      unless example.metadata[:skip_before]
        config.finalize!
        Vagrant::Util::Subprocess.stub(execute: Vagrant::Util::Subprocess::Result.new(0, "", ""))
      end
    end

    after do
      unless example.metadata[:skip_after]
        subject.provision
      end
    end

    describe 'when ansible-playbook fails' do
      it "raises an error", skip_before: true, skip_after: true do
        config.finalize!
        Vagrant::Util::Subprocess.stub(execute: Vagrant::Util::Subprocess::Result.new(1, "", ""))

        expect {subject.provision}.to raise_error(Vagrant::Errors::AnsibleFailed)
      end
    end

    describe "with default options" do
      it_should_set_arguments_and_environment_variables
      it_should_create_and_use_generated_inventory

      it "does not add any group section to the generated inventory" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          inventory_content = File.read(generated_inventory_file)
          expect(inventory_content).to_not match(/^\s*\[^\\+\]\s*$/)

          # Note:
          # The expectation below is a workaround to a possible misuse (or bug) in RSpec/Ruby stack.
          # If 'args' variable is not required by in this block, the "Vagrant::Util::Subprocess).to receive"
          # surprisingly expects to receive "no args".
          # This problem can be "solved" by using args the "unnecessary" (but harmless) expectation below:
          expect(args.length).to be > 0
        }
      end

      it "does not show the ansible-playbook command" do
        expect(machine.env.ui).not_to receive(:detail).with { |full_command|
          expect(full_command).to include("ansible-playbook")
        }
      end
    end

    describe "with groups option" do
      it_should_create_and_use_generated_inventory

      it "adds group sections to the generated inventory" do
        config.groups = {
          "group1" => "#{machine.name}",
          "group1:children" => 'bar',
          "group2" => [iso_env.machine_names[1]],
          "group3" => ["unknown", "#{machine.name}"],
          "bar" => ["#{machine.name}", "group3"],
          "bar:children" => ["group1", "group2", "group3", "group4"],
          "bar:vars" => ["myvar=foo"],
        }

        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          inventory_content = File.read(generated_inventory_file)

          # Group variables are intentionally not supported in generated inventory
          expect(inventory_content).not_to match(/^\[.*:vars\]$/)

          # Accept String instead of Array for group that contains a single item
          expect(inventory_content).to include("[group1]\n#{machine.name}\n")
          expect(inventory_content).to include("[group1:children]\nbar\n")

          # Skip "lost" machines
          expect(inventory_content).to include("[group2]\n\n")

          # Skip "unknown" machines
          expect(inventory_content).to include("[group3]\n#{machine.name}\n")

          # Don't mix group names and host names
          expect(inventory_content).to include("[bar]\n#{machine.name}\n")

          # A group of groups only includes declared groups
          expect(inventory_content).not_to match(/^group4$/)
          expect(inventory_content).to include("[bar:children]\ngroup1\ngroup2\ngroup3\n")
        }
      end
    end

    describe "with host_key_checking option enabled" do
      before do
        config.host_key_checking = true
      end

      it_should_set_arguments_and_environment_variables 7, 4, true
    end

    describe "with boolean (flag) options disabled" do
      before do
        config.sudo = false
        config.ask_sudo_pass = false
        config.ask_vault_pass = false

        config.sudo_user = 'root'
      end

      it_should_set_arguments_and_environment_variables 8
      it_should_set_optional_arguments({ "sudo_user" => "--sudo-user=root" })

      it "it does not set boolean flag when corresponding option is set to false" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          expect(args.index("--sudo")).to be_nil
          expect(args.index("--ask-sudo-pass")).to be_nil
          expect(args.index("--ask-vault-pass")).to be_nil
        }
      end
    end

    describe "with raw_arguments option" do
      before do
        config.sudo = false
        config.skip_tags = %w(foo bar)
        config.limit = "all"
        config.raw_arguments = ["--connection=paramiko",
                                "--skip-tags=ignored",
                                "--module-path=/other/modules",
                                "--sudo",
                                "-l localhost",
                                "--limit=foo",
                                "--limit=bar",
                                "--inventory-file=/forget/it/my/friend",
                                "--user=lion",
                                "--new-arg=yeah"]
      end

      it_should_set_arguments_and_environment_variables 18, 4, false, "paramiko"

      it "sets all raw arguments" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          config.raw_arguments.each do |raw_arg|
            expect(args).to include(raw_arg)
          end
        }
      end

      it "sets raw arguments after arguments related to supported options" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          expect(args.index("--user=lion")).to be > args.index("--user=testuser")
          expect(args.index("--inventory-file=/forget/it/my/friend")).to be > args.index("--inventory-file=#{generated_inventory_dir}")
          expect(args.index("--limit=bar")).to be > args.index("--limit=all")
          expect(args.index("--skip-tags=ignored")).to be > args.index("--skip-tags=foo,bar")
        }
      end

      it "sets boolean flag (e.g. --sudo) defined in raw_arguments, even if corresponding option is set to false" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          expect(args).to include('--sudo')
        }
      end

    end

    describe "with limit option" do
      before do
        config.limit = %w(foo !bar)
      end

      it_should_set_arguments_and_environment_variables
    end

    describe "with inventory_path option" do
      before do
        config.inventory_path = existing_file
      end

      it_should_set_arguments_and_environment_variables

      it "does not generate the inventory and uses given inventory path instead" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          expect(args).to include("--inventory-file=#{existing_file}")
          expect(args).not_to include("--inventory-file=#{generated_inventory_file}")
          expect(File.exists?(generated_inventory_file)).to be_false
        }
      end
    end

    describe "with ask_vault_pass option" do
      before do
        config.ask_vault_pass = true
      end

      it_should_set_arguments_and_environment_variables 8

      it "should ask the vault password" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          expect(args).to include("--ask-vault-pass")
        }
      end
    end

    describe "with vault_password_file option" do
      before do
        config.vault_password_file = existing_file
      end

      it_should_set_arguments_and_environment_variables 8

      it "uses the given vault password file" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          expect(args).to include("--vault-password-file=#{existing_file}")
        }
      end
    end

    describe "with raw_ssh_args" do
      before do
        config.raw_ssh_args = ['-o ControlMaster=no', '-o ForwardAgent=no']
      end

      it_should_set_arguments_and_environment_variables 7, 4
      it_should_explicitly_enable_ansible_ssh_control_persist_defaults

      it "passes custom SSH options via ANSIBLE_SSH_ARGS with the highest priority" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          cmd_opts = args.last
          raw_opt_index = cmd_opts[:env]['ANSIBLE_SSH_ARGS'].index("-o ControlMaster=no")
          default_opt_index = cmd_opts[:env]['ANSIBLE_SSH_ARGS'].index("-o ControlMaster=auto")
          expect(raw_opt_index).to be < default_opt_index
        }
      end

      describe "and with ssh forwarding enabled" do
        before do
          ssh_info[:forward_agent] = true
        end

        it "sets '-o ForwardAgent=yes' via ANSIBLE_SSH_ARGS with higher priority than raw_ssh_args values" do
          expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
            cmd_opts = args.last
            forwardAgentYes = cmd_opts[:env]['ANSIBLE_SSH_ARGS'].index("-o ForwardAgent=yes")
            forwardAgentNo = cmd_opts[:env]['ANSIBLE_SSH_ARGS'].index("-o ForwardAgent=no")
            expect(forwardAgentYes).to be < forwardAgentNo
          }
        end
      end

    end

    describe "with multiple SSH identities" do
      before do
        ssh_info[:private_key_path] = ['/path/to/my/key', '/an/other/identity', '/yet/an/other/key']
      end

      it_should_set_arguments_and_environment_variables 7, 4
      it_should_explicitly_enable_ansible_ssh_control_persist_defaults

      it "passes additional Identity Files via ANSIBLE_SSH_ARGS" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          cmd_opts = args.last
          expect(cmd_opts[:env]['ANSIBLE_SSH_ARGS']).to include("-o IdentityFile=/an/other/identity")
          expect(cmd_opts[:env]['ANSIBLE_SSH_ARGS']).to include("-o IdentityFile=/yet/an/other/key")
        }
      end
    end

    describe "with ssh forwarding enabled" do
      before do
        ssh_info[:forward_agent] = true
      end

      it_should_set_arguments_and_environment_variables 7, 4
      it_should_explicitly_enable_ansible_ssh_control_persist_defaults

      it "enables SSH-Forwarding via ANSIBLE_SSH_ARGS" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          cmd_opts = args.last
          expect(cmd_opts[:env]['ANSIBLE_SSH_ARGS']).to include("-o ForwardAgent=yes")
        }
      end
    end

    describe "with VAGRANT_LOG=debug, but without verbose option" do
      before do
        subject.instance_variable_get(:@logger).stub(:debug?).and_return(true)
        config.verbose = false
      end

      it "shows the ansible-playbook command" do
        expect(machine.env.ui).to receive(:detail).with { |full_command|
          expect(full_command).to eq("PYTHONUNBUFFERED=1 ANSIBLE_HOST_KEY_CHECKING=false ANSIBLE_FORCE_COLOR=true ANSIBLE_SSH_ARGS='-o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ControlMaster=auto -o ControlPersist=60s' ansible-playbook --private-key=/path/to/my/key --user=testuser --connection=ssh --timeout=30 --limit='machine1' --inventory-file=#{generated_inventory_dir} playbook.yml")
        }
      end
    end

    describe "with verbose option" do
      before do
        config.verbose = 'v'
      end

      it_should_set_arguments_and_environment_variables 8
      it_should_set_optional_arguments({ "verbose" => "-v" })

      it "shows the ansible-playbook command" do
        expect(machine.env.ui).to receive(:detail).with { |full_command|
          expect(full_command).to eq("PYTHONUNBUFFERED=1 ANSIBLE_HOST_KEY_CHECKING=false ANSIBLE_FORCE_COLOR=true ANSIBLE_SSH_ARGS='-o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ControlMaster=auto -o ControlPersist=60s' ansible-playbook --private-key=/path/to/my/key --user=testuser --connection=ssh --timeout=30 --limit='machine1' --inventory-file=#{generated_inventory_dir} -v playbook.yml")
        }
      end
    end

    describe "without colorized output" do
      before do
        machine.env.stub(ui: Vagrant::UI::Basic.new)
      end

      it "disables ansible-playbook colored output" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          cmd_opts = args.last
          expect(cmd_opts[:env]).to_not include("ANSIBLE_FORCE_COLOR")
          expect(cmd_opts[:env]['ANSIBLE_NOCOLOR']).to eql("true")
        }
      end
    end

    # Note:
    # The Vagrant Ansible provisioner does not validate the coherency of argument combinations,
    # and let ansible-playbook complain.
    describe "with a maximum of options" do
      before do
        # vagrant general options
        ssh_info[:forward_agent] = true
        ssh_info[:private_key_path] = ['/my/key1', '/my/key2']

        # command line arguments
        config.extra_vars = "@#{existing_file}"
        config.sudo = true
        config.sudo_user = 'deployer'
        config.verbose = "vvv"
        config.ask_sudo_pass = true
        config.ask_vault_pass = true
        config.vault_password_file = existing_file
        config.tags = %w(db www)
        config.skip_tags = %w(foo bar)
        config.limit = 'machine*:&vagrant:!that_one'
        config.start_at_task = 'an awesome task'
        config.raw_arguments = ["--why-not", "--su-user=foot", "--ask-su-pass", "--limit=all"]

        # environment variables
        config.host_key_checking = true
        config.raw_ssh_args = ['-o ControlMaster=no']
      end

      it_should_set_arguments_and_environment_variables 21, 4, true
      it_should_explicitly_enable_ansible_ssh_control_persist_defaults
      it_should_set_optional_arguments({  "extra_vars"          => "--extra-vars=@#{File.expand_path(__FILE__)}",
                                          "sudo"                => "--sudo",
                                          "sudo_user"           => "--sudo-user=deployer",
                                          "verbose"             => "-vvv",
                                          "ask_sudo_pass"       => "--ask-sudo-pass",
                                          "ask_vault_pass"      => "--ask-vault-pass",
                                          "vault_password_file" => "--vault-password-file=#{File.expand_path(__FILE__)}",
                                          "tags"                => "--tags=db,www",
                                          "skip_tags"           => "--skip-tags=foo,bar",
                                          "limit"               => "--limit=machine*:&vagrant:!that_one",
                                          "start_at_task"       => "--start-at-task=an awesome task",
                                        })

      it "also includes given raw arguments" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          expect(args).to include("--su-user=foot")
          expect(args).to include("--ask-su-pass")
          expect(args).to include("--why-not")
        }
      end

      it "shows the ansible-playbook command, with additional quotes when required" do
        expect(machine.env.ui).to receive(:detail).with { |full_command|
          expect(full_command).to eq("PYTHONUNBUFFERED=1 ANSIBLE_HOST_KEY_CHECKING=true ANSIBLE_FORCE_COLOR=true ANSIBLE_SSH_ARGS='-o IdentitiesOnly=yes -o IdentityFile=/my/key2 -o ForwardAgent=yes -o ControlMaster=no -o ControlMaster=auto -o ControlPersist=60s' ansible-playbook --private-key=/my/key1 --user=testuser --connection=ssh --timeout=30 --limit='machine*:&vagrant:!that_one' --inventory-file=#{generated_inventory_dir} --extra-vars=@#{File.expand_path(__FILE__)} --sudo --sudo-user=deployer -vvv --ask-sudo-pass --ask-vault-pass --vault-password-file=#{File.expand_path(__FILE__)} --tags=db,www --skip-tags=foo,bar --start-at-task='an awesome task' --why-not --su-user=foot --ask-su-pass --limit='all' playbook.yml")
        }
      end
    end

    #
    # Special cases related to the VM provider context
    #

    context "with Docker provider on a non-Linux host" do

      let(:fake_host_ssh_info) {{
        private_key_path: ['/path/to/docker/host/key'],
        username: 'boot9docker',
        host: '127.0.0.1',
        port: 2299
      }}
      let(:fake_host_vm) {
        double("host_vm").tap do |h|
          h.stub(ssh_info: fake_host_ssh_info)
        end
      }

      before do
        machine.stub(provider_name: :docker)
        machine.provider.stub(host_vm?: true)
        machine.provider.stub(host_vm: fake_host_vm)
      end

      it "uses an SSH ProxyCommand to reach the VM" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          cmd_opts = args.last
          expect(cmd_opts[:env]['ANSIBLE_SSH_ARGS']).to include("-o ProxyCommand='ssh boot9docker@127.0.0.1 -p 2299 -i /path/to/docker/host/key -o Compression=yes -o ConnectTimeout=5 -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no exec nc %h %p 2>/dev/null'")
        }
      end
    end

    #
    # Special cases related to the Vagrant Host operating system in use
    #

    context "with a Solaris-like host" do
      before do
        Vagrant::Util::Platform.stub(solaris?: true)
      end

      it "does not set IdentitiesOnly=yes in ANSIBLE_SSH_ARGS" do
        expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
          cmd_opts = args.last
          expect(cmd_opts[:env]['ANSIBLE_SSH_ARGS']).to_not include("-o IdentitiesOnly=yes")

          # Note:
          # The expectation below is a workaround to a possible misuse (or bug) in RSpec/Ruby stack.
          # If 'args' variable is not required by in this block, the "Vagrant::Util::Subprocess).to receive"
          # surprisingly expects to receive "no args".
          # This problem can be "solved" by using args the "unnecessary" (but harmless) expectation below:
          expect(true).to be_true
        }
      end

      describe "and with host_key_checking option enabled" do
        it "does not set ANSIBLE_SSH_ARGS environment variable" do
          config.host_key_checking = true

          expect(Vagrant::Util::Subprocess).to receive(:execute).with { |*args|
            cmd_opts = args.last
            expect(cmd_opts[:env]).to_not include('ANSIBLE_SSH_ARGS')

            # Note:
            # The expectation below is a workaround to a possible misuse (or bug) in RSpec/Ruby stack.
            # If 'args' variable is not required by in this block, the "Vagrant::Util::Subprocess).to receive"
            # surprisingly expects to receive "no args".
            # This problem can be "solved" by using args the "unnecessary" (but harmless) expectation below:
            expect(true).to be_true
          }
        end
      end

    end
  end
end


text:
#include "prng/single_thread_chacha_prng.h"

#include <vector>

#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "status_macros.h"

namespace rlwe {

SingleThreadChaChaPrng::SingleThreadChaChaPrng(absl::string_view in_key,
                                               int position_in_buffer,
                                               int salt_counter,
                                               std::vector<Uint8> buffer)
    : key_(in_key),
      position_in_buffer_(position_in_buffer),
      salt_counter_(salt_counter),
      buffer_(std::move(buffer)) {}

rlwe::StatusOr<std::unique_ptr<SingleThreadChaChaPrng>>
SingleThreadChaChaPrng::Create(absl::string_view in_key) {
  if (in_key.length() != SeedLength()) {
    return absl::InvalidArgumentError(
        absl::StrCat("Cannot create Prng with key of the "
                     "wrong size. Real ",
                     "key length of ", in_key.length(), " instead of expected ",
                     "key length of ", SeedLength(), "."));
  }
  int position_in_buffer = 0;
  int salt_counter = 0;
  std::vector<Uint8> buffer;
  RLWE_RETURN_IF_ERROR(
      internal::ChaChaPrngResalt(in_key, internal::kChaChaOutputBytes,
                                 &salt_counter, &position_in_buffer, &buffer));
  return absl::WrapUnique<SingleThreadChaChaPrng>(new SingleThreadChaChaPrng(
      in_key, position_in_buffer, salt_counter, std::move(buffer)));
}

rlwe::StatusOr<Uint8> SingleThreadChaChaPrng::Rand8() {
  return internal::ChaChaPrngRand8(key_, &position_in_buffer_, &salt_counter_,
                                   &buffer_);
}

rlwe::StatusOr<Uint64> SingleThreadChaChaPrng::Rand64() {
  return internal::ChaChaPrngRand64(key_, &position_in_buffer_, &salt_counter_,
                                    &buffer_);
}

}  // namespace rlwe

redpajama_set_name: RedPajamaGithub


text:
FOUNDATION_EXPORT double QorumLogsVersionNumber;
FOUNDATION_EXPORT const unsigned char QorumLogsVersionString[];


text:
package com.liferay.portal.settings.authentication.iam.web.internal.servlet.
    taglib;

import javax.servlet.ServletContext;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.taglib.BaseJSPDynamicInclude;
import com.liferay.portal.kernel.servlet.taglib.DynamicInclude;

/**
 * @author Marco Fargetta
 */
@Component(
        immediate = true,
        property = { "portal.settings.authentication.tabs.name=iam" },
        service = DynamicInclude.class)
public class PortalSettingsIAMAuthenticationDynamicInclude extends
        BaseJSPDynamicInclude {

    @Override
    protected final String getJspPath() {
        return "/com.liferay.portal.settings.web/iam.jsp";
    }

    @Override
    protected final Log getLog() {
        return log;
    }

    @Override
    @Reference(
            target =
                "(osgi.web.symbolicname=com.liferay.portal.settings."
                        + "authentication.iam.web)",
            unbind = "-")
    protected final void setServletContext(
            final ServletContext servletContext) {
        super.setServletContext(servletContext);
    }

    /**
     * The logger.
     */
    private final Log log = LogFactoryUtil.getLog(
            PortalSettingsIAMAuthenticationDynamicInclude.class);
}


text:
'use strict'

const helpers = require('./helpers')
const domains = require('./domains')
const util = require('../../lib/util')

/**
 * Route groups to keep configuration DRY for bunch of
 * routes.
 * @class
 * @alias Route.Group
 */
class Group {

  constructor (routes) {
    this.routes = routes
  }

  /**
   * @see module:Route~middlewares
   */
  middlewares () {
    helpers.appendMiddleware(
      this.routes,
      util.spread.apply(this, arguments)
    )
    return this
  }

  /**
   * @see module:Route~middleware
   */
  middleware () {
    return this.middlewares.apply(this, arguments)
  }

  /**
   * prefix group of routes with a given pattern
   *
   * @param  {String} pattern
   *
   * @return {Object} - reference to this for chaining
   *
   * @example
   * Route.group('...').prefix('/v1')
   *
   * @public
   */
  prefix (pattern) {
    helpers.prefixRoute(this.routes, pattern)
    return this
  }

  /**
   * add domain to group of routes. All routes inside the group
   * will be matched on define domain
   *
   * @param  {String} domain
   * @return {Object} - reference to this for chaining
   *
   * @example
   * Route.group('...').domain(':user.example.com')
   *
   * @public
   */
  domain (domain) {
    domains.add(helpers.makeRoutePattern(domain))
    helpers.addDomain(this.routes, domain)
  }

  /**
   * @see module:Route~formats
   */
  formats (formats, strict) {
    helpers.addFormats(this.routes, formats, strict)
    return this
  }

}

module.exports = Group


text:
<?php defined('BASEPATH') or die('No direct access allowed');

/**
 *---------------------------------------------------------------
 * Load the DB packages and environment preparation
 *---------------------------------------------------------------
 */

// Set error level
if (ENVIRONMENT === 'testing') error_reporting(E_STRICT);

// Check the environment var
if ( ! defined('DB_GROUP'))
{
	define('DB_GROUP', 'default');
}
else
{
	unset($DB);
}

// Define this root folder as Gas ORM base path
defined('GASPATH') or define('GASPATH', __DIR__.DIRECTORY_SEPARATOR);

// Load everything on base gas directory
require_once GASPATH.'classes'.DIRECTORY_SEPARATOR.'core.php';
require_once GASPATH.'classes'.DIRECTORY_SEPARATOR.'data.php';
require_once GASPATH.'classes'.DIRECTORY_SEPARATOR.'janitor.php';
require_once GASPATH.'classes'.DIRECTORY_SEPARATOR.'orm.php';
require_once GASPATH.'interfaces'.DIRECTORY_SEPARATOR.'extension.php';

// Load needed DB files
require_once Gas\Janitor::path('base').'database'.DIRECTORY_SEPARATOR.'DB.php';
require_once Gas\Janitor::path('base').'database'.DIRECTORY_SEPARATOR.'DB_forge.php';
require_once Gas\Janitor::path('base').'database'.DIRECTORY_SEPARATOR.'DB_utility.php';

// Define DB path
define('DBPATH', Gas\Janitor::path('base').'database'.DIRECTORY_SEPARATOR);
define('DBDRIVERSPATH', DBPATH.'drivers'.DIRECTORY_SEPARATOR);

// Mock internal CI instance and low-level functions,
// in case we run Gas ORM outside CI scope
if ( ! function_exists('get_instance'))
{
	// Build our own TRON!
	class Tron {
		/**
		 * @var object Tron super-object
		 */
		private static $instance;

		/**
		 * Constructor
		 *
		 * @param   mixed   CI DB instance
		 * @return  void
		 */
		function __construct($DB)
		{
			$this->db         = $DB;
			static::$instance = $this;
		}

		/**
		 * Get Tron super-object
		 *
		 * @return  object
		 */
		public static function &get_instance()
		{
			return static::$instance;
		}

		/**
		 * Serve static call for TRON instantiation
		 *
		 * @return  object
		 */
		public static function make()
		{
			return new static(NULL);
		}

		/**
		 * Serve loader
		 *
		 * @param   mixed
		 * @return  object
		 */
		public static function load($args)
		{
			// TODO : resolve this loader to perform any necessarily
			// action, to load the real requested class.
			return static::$instance;
		}

		/**
		 * Serve undefined Core CI properties
		 */
		public function __get($name)
		{
			if ($name == 'load')
			{
				return static::$instance;
			}
		}

		/**
		 * Serve other methods, to capture the error for the very least
		 *
		 * @param   string
		 * @param   mixed
		 * @throws  LogicException Serve show error method
		 * @return  mixed
		 */
		public function __call($name, $arguments)
		{
			// Only response for error
			if ($name == 'show_error')
			{
				// Get any meaning information
				$internal_error = (array_key_exists(2, $arguments)) ? $arguments[2] : 'Undefined CI Error';

				// Good bye
				throw new LogicException('CI Internal Error with message : '.$internal_error);
			}
			// For package path
			elseif ($name == 'get_package_paths')
			{
				return array();
			}
		}
	}

	/**
	 * global is_php method
	 */
	function is_php($version = '5.0.0')
	{
		static $_is_php;
		$version = (string)$version;

		if ( ! isset($_is_php[$version]))
		{
			$_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
		}

		return $_is_php[$version];
	}

	/**
	 * global get_instance method
	 */
	function &get_instance() {

		$instance =& Tron::get_instance();

		// If Tron not initialized yet, build a mock
		if (is_null($instance))
		{
			$instance = new stdClass();
			$instance->load = new Tron('undefined');
		}

		return $instance;
	}

	/**
	 * global log_message method
	 */
	function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered')
	{
		// Good bye
		throw new LogicException('CI Internal Error with message : '.$message);
	}

	/**
	 * global log_message method
	 */
	function log_message(){}

	/**
	 * global load_class method
	 */
	function load_class(){
		// Capture argument
		$args = func_get_args();

		// Return new TRON to resolve any possible error
		return Tron::make()->load($args);
	}
}

// Validate DB instance
if ( ! class_exists('CI_DB'))
{
	try{
		$DB = &DB(DB_GROUP);
	} catch (Exception $e) {
		die('Cant connect to database : '.$e->getMessage().', please check config/testing/database.php.'."\n");
	}
}

if ( ! $DB instanceof CI_DB_Driver)
{
	throw new InvalidArgumentException('db_connection_error:default');
}

// Load required utility files once
require_once(DBPATH.'DB_forge.php');
require_once(DBPATH.'DB_utility.php');
require_once(DBDRIVERSPATH.$DB->dbdriver.DIRECTORY_SEPARATOR.$DB->dbdriver.'_utility.php');
require_once(DBDRIVERSPATH.$DB->dbdriver.DIRECTORY_SEPARATOR.$DB->dbdriver.'_forge.php');

// if we run Gas ORM outside CI scope
if ( class_exists('Tron'))
{
	// MayDay!! Call TRON
	$tron = new Tron($DB);
}

/**
 *---------------------------------------------------------------
 * Instantiate Gas ORM Core classes
 *---------------------------------------------------------------
 */

// Instantiate core class then clean up global variables
Gas\Core::make($DB, $config)->init();
unset($DB, $config);


text:
namespace P3D.Legacy.Launcher.Forms
{
    partial class PerFileUpdaterForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

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

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PerFileUpdaterForm));
            this.Label_ProgressBar1 = new P3D.Legacy.Launcher.Controls.LocalizableLabel();
            this.Label_ProgressBar2 = new P3D.Legacy.Launcher.Controls.LocalizableLabel();
            this.Label_ProgressBar3 = new P3D.Legacy.Launcher.Controls.LocalizableLabel();
            this.PercentageProgressBar = new System.Windows.Forms.ProgressBar();
            this.SuspendLayout();
            //
            // Label_ProgressBar1
            //
            this.Label_ProgressBar1.AutoSize = true;
            this.Label_ProgressBar1.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.Label_ProgressBar1.Location = new System.Drawing.Point(12, 9);
            this.Label_ProgressBar1.Name = "Label_ProgressBar1";
            this.Label_ProgressBar1.Size = new System.Drawing.Size(146, 13);
            this.Label_ProgressBar1.TabIndex = 4;
            this.Label_ProgressBar1.Text = "pfu_label_updateinfoprogress";
            //
            // Label_ProgressBar2
            //
            this.Label_ProgressBar2.AutoSize = true;
            this.Label_ProgressBar2.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.Label_ProgressBar2.Location = new System.Drawing.Point(13, 9);
            this.Label_ProgressBar2.Name = "Label_ProgressBar2";
            this.Label_ProgressBar2.Size = new System.Drawing.Size(150, 13);
            this.Label_ProgressBar2.TabIndex = 5;
            this.Label_ProgressBar2.Text = "pfu_label_comparisonprogress";
            this.Label_ProgressBar2.Visible = false;
            //
            // Label_ProgressBar3
            //
            this.Label_ProgressBar3.AutoSize = true;
            this.Label_ProgressBar3.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.Label_ProgressBar3.Location = new System.Drawing.Point(13, 9);
            this.Label_ProgressBar3.Name = "Label_ProgressBar3";
            this.Label_ProgressBar3.Size = new System.Drawing.Size(142, 13);
            this.Label_ProgressBar3.TabIndex = 6;
            this.Label_ProgressBar3.Text = "pfu_label_downloadprogress";
            this.Label_ProgressBar3.Visible = false;
            //
            // PercentageProgressBar
            //
            this.PercentageProgressBar.Location = new System.Drawing.Point(12, 25);
            this.PercentageProgressBar.Name = "PercentageProgressBar";
            this.PercentageProgressBar.Size = new System.Drawing.Size(260, 23);
            this.PercentageProgressBar.TabIndex = 0;
            //
            // PerFileUpdaterForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 66);
            this.Controls.Add(this.PercentageProgressBar);
            this.Controls.Add(this.Label_ProgressBar1);
            this.Controls.Add(this.Label_ProgressBar2);
            this.Controls.Add(this.Label_ProgressBar3);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximumSize = new System.Drawing.Size(300, 100);
            this.MinimumSize = new System.Drawing.Size(300, 100);
            this.Name = "PerFileUpdaterForm";
            this.StringID_Title = "pfu_title";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.CustomUpdaterForm_FormClosing);
            this.Shown += new System.EventHandler(this.CustomUpdaterForm_Shown);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private P3D.Legacy.Launcher.Controls.LocalizableLabel Label_ProgressBar1;
        private P3D.Legacy.Launcher.Controls.LocalizableLabel Label_ProgressBar2;
        private P3D.Legacy.Launcher.Controls.LocalizableLabel Label_ProgressBar3;
        private System.Windows.Forms.ProgressBar PercentageProgressBar;
    }
}


text:
<?php

class Producer extends CI_Controller {

    public function __construct(){
        parent::__construct();
    }

    public function index(){

        $data['producers'] = $this->db->get("producer")->result();

        //parsing title producers
        $data['title'] = 'Producers';

        //parsing information to the view
        $this->load->view('producer/list', $data);

    }

    public function addProducer(){
        //validating producer's name
        $this->form_validation->set_rules('producer_name', "Producer's name", 'trim|required');

        if($this->form_validation->run() == true){
            //get producer's name from the form field
            $data['producer_name'] = $this->input->post('producer_name');

            //inserting producers name in db
            $this->db->insert("producer", $data);

            //redirect back to the producer list
            redirect('producer/index');
        }else{
            $data['producer_name'] = $this->input->post('producer_name');

            //load add_edit view and display
            $this->load->view("producer/add_edit", $data);
        }
    }

    public function editProducer($id){
        $this->form_validation->set_rules('producer_name', "Producer's name", 'trim|required');
         if($this->form_validation->run() == true){

            $data['producer_name'] = $this->input->post('producer_name');
            $this->db->where("producer_id", $id);
            $this->db->update("producer", $data);

            redirect('producer/index');

        }else{

            $this->db->where("producer_id", $id);
            $producer = $this->db->get("producer")->row();

            $data['producer_name'] = $producer->producer_name;
            $this->load->view("producer/add_edit", $data);
        }
    }
    public function deleteProducer($id){
        $this->db->where("producer_id", $id);
        $this->db->delete("producer");

        redirect('producer/index');
    }

}

?>


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ownCloud Android client application

  Copyright (C) 2012  Bartek Przybylski
  Copyright (C) 2016 ownCloud GmbH.

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License version 2,
  as published by the Free Software Foundation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="72dp"
    android:background="@drawable/list_selector"
    android:orientation="horizontal"
    android:filterTouchesWhenObscured="true"
    >

    <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="@dimen/file_icon_size"
        android:layout_height="@dimen/file_icon_size"
        android:layout_gravity="center_vertical"
        android:layout_margin="12dp"
        android:src="@drawable/ic_menu_archive" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="72dp"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:orientation="vertical">

        <TextView
            android:id="@+id/filename"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="4dp"
            android:ellipsize="middle"
            android:singleLine="true"
            android:text="TextView"
            android:textColor="@color/textColor"
            android:textSize="16dip" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="4dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/file_size"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Size MB"
                android:textColor="@color/list_item_lastmod_and_filesize_text"
                android:textSize="@dimen/two_line_secondary_text_size"/>

            <TextView
                android:id="@+id/file_separator"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:text=", "
                android:textColor="@color/list_item_lastmod_and_filesize_text"
                android:textSize="@dimen/two_line_secondary_text_size"/>

            <TextView
                android:id="@+id/last_mod"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:text="Mod Date"
                android:textColor="@color/list_item_lastmod_and_filesize_text"
                android:textSize="@dimen/two_line_secondary_text_size"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Torrey bot. Club 93: 309 (1966)

#### Original name
Cephalosporium candidum var. arachnoides Sukapure & Thirum.

### Remarks
null


text:
package com.kyriakosalexandrou.bluetoothtoolkit.adapters;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.kyriakosalexandrou.bluetoothtoolkit.R;
import com.kyriakosalexandrou.bluetoothtoolkit.managers.HtmDeviceManager;

public class HtmMultipleDevicesAdapter extends
        BleBaseMultipleDevicesAdapter {
    private HtmDeviceManager mHtmDeviceManager;

    public HtmMultipleDevicesAdapter(Activity par) {
        super(par);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        super.getView(position, convertView, parent);

        FieldReferences fields;
        if (convertView == null) {
            convertView = mInflater.inflate(
                    R.layout.item_multiple_htm_devices,
                    parent, false);

            fields = new FieldReferences();
            bindViews(fields, convertView);
            convertView.setTag(fields);
        } else {
            fields = (FieldReferences) convertView.getTag();
        }

        mHtmDeviceManager = (HtmDeviceManager) mDevices.get(position);

        if (mHtmDeviceManager != null) {
            setGenericViews(fields, position);
            setThermometerViews(fields);
        }
        return convertView;
    }

    private class FieldReferences extends CommonFieldReferences {
        TextView tempMeasurementValue;
    }

    private void bindViews(FieldReferences fields, View convertView) {
        bindCommonViews(fields, convertView);

        fields.tempMeasurementValue = (TextView) convertView
                .findViewById(R.id.tempMeasurementValue);
    }

    private void setThermometerViews(final FieldReferences fields) {
        fields.tempMeasurementValue.setText(mHtmDeviceManager.getFormattedHtmValue());
    }
}


text:
package com.netflix.simianarmy.chaos;

import com.netflix.simianarmy.MonkeyConfiguration;

/**
 * Adds entries to /etc/hosts so that S3 API endpoints are unreachable.
 */
public class FailS3ChaosType extends ScriptChaosType {
    /**
     * Constructor.
     *
     * @param config
     *            Configuration to use
     */
    public FailS3ChaosType(MonkeyConfiguration config) {
        super(config, "FailS3");
    }
}


text:
<?php

namespace Anax\HTMLForm;

/**
 * Anax base class for wrapping sessions.
 *
 */
class CFormAddQuestion extends \Mos\HTMLForm\CForm
{
    use \Anax\DI\TInjectionaware,
        \Anax\MVC\TRedirectHelpers;

    /**
     * Constructor
     *
     */
    public function __construct($user, $tags)
    {
        parent::__construct([], [
            'user' => [
                'type' => 'hidden',
                'value' => $user,
            ],
            'title' => [
                'type'        => 'text',
                'label'       => 'Titel: ',
                'required'    => true,
                'validation'  => ['not_empty'],

            ],
            'content' => [
                'type'        => 'textarea',
                'label'       => 'Din fråga: ',
                'required'    => true,
                'validation'  => ['not_empty'],
            ],
            'tags' => [
                'type'        => 'text',
                'label'       => 'Taggar: ',
            ],
            'submit' => [
                'type'      => 'submit',
                'callback'  => [$this, 'callbackSubmit'],
            ],
        ]);
    }

    /**
     * Customise the check() method.
     *
     * @param callable $callIfSuccess handler to call if function returns true.
     * @param callable $callIfFail    handler to call if function returns true.
     */
    public function check($callIfSuccess = null, $callIfFail = null)
    {
        return parent::check([$this, 'callbackSuccess'], [$this, 'callbackFail']);
    }

   /**
     * Callback for submit-button.
     *
     */
    public function callbackSubmit()
    {
        $comment = new \Anax\Comment\Comments();
        $comment->setDI($this->di);

        $saved = $comment->saveComment([
            'title'     => $this->Value('title'),
            'content'   => $this->Value('content'),
            'creator'   => $this->Value('user'),
            'created'   => gmdate('Y-m-d H:i:s'),
            'tags'      => $this->Value('tags'),
            'type'      => 'question',
        ]);

        if ($saved == true) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Callback What to do if the form was submitted?
     *
     */
    public function callbackSuccess()
    {
        $this->redirectTo($this->di->url->create(""));
    }

    /**
     * Callback for submit-button.
     *
     */
    public function callbackSubmitFail()
    {
        $this->AddOutput("
DoSubmitFail(): Form was submitted but it failed
");
        return false;
    }

    /**
     * Callback What to do when form could not be processed?
     *
     */
    public function callbackFail()
    {
        $this->AddOutput("
Form was submitted and the Check() method returned false.
");
    }
}


text:
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace Com.Aspose.Words.Model {
  public class DocumentPositionDto {
    public NodeLink Node { get; set; }

    public int Offset { get; set; }

    public override string ToString()  {
      var sb = new StringBuilder();
      sb.Append("class DocumentPositionDto {\n");
      sb.Append("  Node: ").Append(Node).Append("\n");
      sb.Append("  Offset: ").Append(Offset).Append("\n");
      sb.Append("}\n");
      return sb.ToString();
    }
  }
  }


text:
{{node.name}}

            <localize key="general_delete">Remove</localize>

                <localize key="general_add">Add</localize>


text:
package com.easyjf.container.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.easyjf.beans.BeanWrapper;
import com.easyjf.beans.MutablePropertyValues;
import com.easyjf.beans.PropertyValue;
import com.easyjf.beans.exception.BeansException;
import com.easyjf.container.AutoInject;
import com.easyjf.container.BeanDefinition;
import com.easyjf.container.Container;
import com.easyjf.container.InnerContainer;
import com.easyjf.container.Scope;
import com.easyjf.util.I18n;
import com.easyjf.web.Order;

/**
 * EasyJWeb中的默认IOC容器实现
 *
 * @author 大峡,tony,stef_wu
 *
 */
public class DefaultContainer extends SingletonBeanContainer implements
		Container {

	private static final Logger logger = Logger
			.getLogger(DefaultContainer.class);

	private final Map beanDefinitions = new HashMap();

	private final Map guiceDefinitions = new HashMap();

	private final Map scopes = new HashMap();

	private final Map<String, InnerContainer> containers = new HashMap<String, InnerContainer>();

	public DefaultContainer() {

	}

	public boolean containsBean(String name) {

		boolean ret = beanDefinitions.containsKey(name);
		return ret;
	}

	public Object create(BeanDefinition beanDefinition) {

		Object bean = null;
		if ("singleton".equalsIgnoreCase(beanDefinition.getScope())) {
			bean = BeanCreatorUtil.initBean(beanDefinition, this);
			if (bean != null)
				super.register(beanDefinition.getBeanName(), bean);
		} else if ("prototype".equalsIgnoreCase(beanDefinition.getScope()))
			bean = BeanCreatorUtil.initBean(beanDefinition, this);
		else {
			Scope scope = (Scope) scopes.get(beanDefinition.getScope());

			if (scope != null)
				bean = scope.getBean(beanDefinition.getBeanName(),
						beanDefinition);
		}
		// 设值方法注入
		if (bean != null) {
			BeanWrapper wrapper = new BeanWrapper(bean);
			MutablePropertyValues pvs = new MutablePropertyValues();
			// 根据bean配置信息进行设值方法注入
			for (int i = 0; i < beanDefinition.getPropertyValues()
					.getPropertyValues().length; i++) {
				PropertyValue pv = beanDefinition.getPropertyValues()
						.getPropertyValues()[i];
				if (pv.getValue() instanceof BeanDefinition) {
					String beanName = ((BeanDefinition) pv.getValue())
							.getBeanName();
					Object refBean = getBean(beanName);
					if (refBean == null)
						throw new com.easyjf.beans.exception.BeansException(
								I18n
										.getLocaleMessage("core.container.cant.load.bean.property.name.specified")
										+ beanName);
					pvs.addPropertyValue(new PropertyValue(pv.getName(),
							refBean));
				} else if (pv.getValue() instanceof AutoInject)// 处理自动注入
				{
					AutoInject inject = (AutoInject) pv.getValue();
					if (inject.getName() != null)// 按名称自动注入
					{
						Object refBean = getBean(inject.getName());
						if (refBean == null)
							throw new BeansException(
									I18n
											.getLocaleMessage("core.container.cant.load.bean.property.name.specified")
											+ inject.getName());
						pvs.addPropertyValue(new PropertyValue(pv.getName(),
								refBean));
					} else // 按类别自动注入
					{
						Object refBean = getBean(inject.getType());
						if (refBean == null)
							throw new BeansException(
									I18n
											.getLocaleMessage("core.container.cant.load.bean.property.name.specified")
											+ inject.getType());
						pvs.addPropertyValue(new PropertyValue(pv.getName(),
								refBean));
					}
				} else
					pvs.addPropertyValue(pv);
			}

			// 自动按属名称注入
			// wrapper.getPropertyDescriptors()
			// 自动按属性类型注入

			wrapper.setPropertyValues(pvs);
		}

		// 在这里初始化容器信息
		if (bean != null && bean instanceof InnerContainer
				&& !containers.containsKey(beanDefinition.getBeanName())) {
			logger.info(I18n
					.getLocaleMessage("core.container.loaded.a.container")
					+ bean);
			InnerContainer innerContainer = (InnerContainer) bean;
			innerContainer.setParent(this);
			innerContainer.init();
			containers.put(beanDefinition.getBeanName(), innerContainer);
		}
		return bean;
	}

	protected void filterBeanDefinitions() {
		java.util.Iterator it = beanDefinitions.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			BeanDefinition definition = (BeanDefinition) beanDefinitions
					.get(key);
			if ("guice".equals(definition.getInjectType())) {
				guiceDefinitions.put(definition.getBeanName(), definition);
				it.remove();
			}
		}
	}

	@SuppressWarnings("unchecked")
	public <T> T getBean(Class<T> type) {
		T bean = super.getSingletionBean(type);
		if (bean == null) {
			BeanDefinition definition = getBeanDefinition(type);
			if (definition != null)
				bean = (T)create(definition);
			else
				for (Container innerContainer : containers.values()) {
					bean = innerContainer.getBean(type);
					if (bean != null)
						break;
				}
		}
		return bean;
	}

	public Object getBean(String name) {

		Object bean = super.getSingletionBean(name);
		if (bean == null) {
			BeanDefinition definition = (BeanDefinition) beanDefinitions
					.get(name);
			if (definition != null)
				bean = create(definition);
			else
				for (Container innerContainer : containers.values()) {
					bean = innerContainer.getBean(name);
					if (bean != null)
						break;
				}
		}
		return bean;
	}

	public BeanDefinition getBeanDefinition(Class type) {

		BeanDefinition ret = null;
		Iterator it = beanDefinitions.values().iterator();
		while (it.hasNext()) {
			BeanDefinition definition = (BeanDefinition) it.next();
			if (type.isAssignableFrom(definition.getBeanClass())) {
				ret = definition;
				break;
			}
		}
		return ret;
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> getBeans(Class<T> type) {
		List<T> l = new ArrayList<T>();
		List beans = super.getBeansByType(type);
		if (beans != null)
			l.addAll(beans);
		for (Container innerContainer : containers.values()) {
			List<T> innerBeans = innerContainer.getBeans(type);
			if (innerBeans != null)
				l.addAll(innerBeans);
		}
		if (Order.class.isAssignableFrom(type))
			Collections.sort(l, new Comparator() {
				public int compare(Object o1, Object o2) {
					return ((Order) o1).getOrder().intValue()
							- ((Order) o2).getOrder().intValue();
				}
			});
		return l;
	}

	public Collection getBeansName() {

		return java.util.Collections.unmodifiableCollection(beanDefinitions
				.keySet());
	}

	public Map<String, InnerContainer> getContainers() {

		return containers;
	}

	protected void injectGuice() {
		// InnerContainer guiceContainer =
		// containers.get("GuiceContainer");
		// if(guiceContainer instanceof GuiceContainer){
		// ((GuiceContainer)guiceContainer).inject(guiceDefinitions);
		// }
	}

	// 初始化并装截容器
	public void refresh() {

		super.removeAll();

//		filterBeanDefinitions();

		refreshContainer();

//		injectGuice();

		// java.util.Iterator it =
		// beanDefinitions.entrySet().iterator();
		// while (it.hasNext()) {
		// Map.Entry en = (Map.Entry) it.next();
		// BeanDefinition definition = (BeanDefinition)
		// en.getValue();
		// if (BeanCreatorUtil.isCreateOnStart(definition))
		// create(definition);
		// }

		// 初始化Guice容器
		// java.util.Iterator iter =
		// containers.entrySet().iterator();
		// while (iter.hasNext()) {
		// Map.Entry en = (Map.Entry) iter.next();
		// InnerContainer container = (InnerContainer)
		// en.getValue();
		// if (container instanceof GuiceContainer) {
		// ((GuiceContainer)
		// container).inject(beanDefinitions);
		// }
		// }
	}

	protected void refreshContainer() {
		java.util.Iterator it = beanDefinitions.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry en = (Map.Entry) it.next();
			BeanDefinition definition = (BeanDefinition) en.getValue();
			if (BeanCreatorUtil.isCreateOnStart(definition))
				create(definition);
		}
	}

	public void registerBeanDefinition(String name, BeanDefinition definition) {

		beanDefinitions.put(name, definition);
	}

	public void registerBeanDefinitions(List definitions) {
		for (int i = 0; i < definitions.size(); i++) {
			BeanDefinition definition = (BeanDefinition) definitions.get(i);
			registerBeanDefinition(definition.getBeanName(), definition);
		}
	}

	public void registerScope(String name, Scope scope) {

		scopes.put(name, scope);
	}

}


text:
namespace dclass   // open namespace dclass
{

// Forward declarations
class DistributedType;

// parse_value reads a .dc-formatted parameter value and outputs the data in packed form matching
//     the appropriate DistributedType and suitable for a default parameter value.
//     If an error occurs, the error reason is returned instead of the parsed value.
std::string parse_value(const DistributedType*, const std::string &formatted, bool &err);
std::string parse_value(const DistributedType*, std::istream &in, bool &err);

} // close namespace dclass


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using Ilaro.Admin.Core;
using System.Globalization;
using Ilaro.Admin.Core.Extensions;
using Ilaro.Admin.Core.Filters;
using Ilaro.Admin.Core.Models;

namespace Ilaro.Admin.Extensions
{
    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString FilterOptionLink(
            this HtmlHelper htmlHelper,
            string text,
            string value,
            BaseFilter filter,
            object htmlAttributes = null)
        {
            var currentRouteValues =
                htmlHelper.ViewContext.RequestContext.HttpContext.Request.QueryString.ToRouteValueDictionary();
            var newRouteValues = new Dictionary<string, object>
            {
                { "area", "IlaroAdmin" },
                { "page", "1" },
                { filter.Property.Name, value }
            };
            var attr = Merge(currentRouteValues, new RouteValueDictionary(newRouteValues));

            return htmlHelper.ActionLink(
                text,
                htmlHelper.ViewContext.RouteData.Values["action"].ToStringSafe() ?? "Index",
                "Entities",
                Merge(currentRouteValues, new RouteValueDictionary(newRouteValues)),
                HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        }

        private static RouteValueDictionary Merge(
            this RouteValueDictionary original,
            RouteValueDictionary extendedValues)
        {
            var merged = new RouteValueDictionary(original);

            foreach (var pairValue in extendedValues)
            {
                merged[pairValue.Key] = pairValue.Value;
            }

            return merged;
        }

        public static MvcHtmlString SortColumnLink(
            this HtmlHelper htmlHelper,
            Entity entity,
            Column column,
            IEnumerable<BaseFilter> filters,
            string searchQuery,
            int perPage)
        {
            var entityName = entity == null ?
                null :
                entity.Name;
            var routeValues = new Dictionary<string, object>
            {
                { "area", "IlaroAdmin" },
                { "EntityName", entityName },
                { "pp", perPage }
            };
            if (!searchQuery.IsNullOrEmpty())
            {
                routeValues.Add("sq", searchQuery);
            }

            routeValues.Add("o", column.Name);
            if (column.SortDirection == "up")
            {
                routeValues["od"] = "desc";
            }
            else if (column.SortDirection == "down")
            {
                routeValues["od"] = "asc";
            }

            var activeFilters = filters
                .Where(x => x.DisplayInUI && !x.Value.IsNullOrEmpty())
                .ToList();
            foreach (var filter in activeFilters)
            {
                routeValues[filter.Property.Name] = filter.Value;
            }

            return htmlHelper.ActionLink(
                column.DisplayName,
                htmlHelper.ViewContext.RouteData.Values["action"].ToStringSafe() ?? "Index",
                "Entities",
                new RouteValueDictionary(routeValues),
                null);
        }

        /// <summary>
        /// It should by used only for small strings without html,
        /// there is some html it should be used normal if condition
        /// </summary>
        public static MvcHtmlString Condition(
            this HtmlHelper htmlHelper,
            bool condition,
            string trueResult,
            string falseResult = null)
        {
            return MvcHtmlString.Create(condition ? trueResult : falseResult);
        }

        /// <summary>
        /// It should by used only for small strings without html,
        /// there is some html it should be used normal if condition
        /// </summary>
        public static MvcHtmlString Condition(
            this HtmlHelper htmlHelper,
            bool condition,
            Func<string> trueResult,
            Func<string> falseResult)
        {
            return MvcHtmlString.Create(condition ? trueResult() : falseResult());
        }

        /// <summary>
        /// It should by used only for small strings without html,
        /// there is some html it should be used normal if condition
        /// </summary>
        public static MvcHtmlString Condition(
            this HtmlHelper htmlHelper,
            bool condition,
            Func<string> trueResult)
        {
            return MvcHtmlString.Create(condition ? trueResult() : String.Empty);
        }

        public static MvcHtmlString ConcurrencyCheck(
            this HtmlHelper htmlHelper,
            object concurrencyCheckValue)
        {
            if (concurrencyCheckValue == null)
                return MvcHtmlString.Empty;

            if (concurrencyCheckValue is DateTime)
            {
                concurrencyCheckValue = (concurrencyCheckValue as DateTime?).Value
                    .ToString("dd/MM/yyyy HH:mm:ss.fff", CultureInfo.CurrentCulture);
            }

            return htmlHelper.Hidden("__ConcurrencyCheck", concurrencyCheckValue);
        }

        public static string PageUrl(
            this UrlHelper urlHelper,
            int pageNumber)
        {
            var routeDataValues = urlHelper.RequestContext.RouteData.Values
                .Merge(urlHelper.RequestContext.HttpContext.Request.QueryString.ToRouteValueDictionary());

            SetPageNumber(routeDataValues, pageNumber);

            var actionName = routeDataValues["action"].ToStringSafe();

            return urlHelper.Action(actionName, routeDataValues);
        }

        private static void SetPageNumber(
            RouteValueDictionary routeDataValues,
            int pageNumber)
        {
            // Avoid canonical errors when pageNumber is equal to 1.
            if (pageNumber == 1)
            {
                if (routeDataValues.ContainsKey("page"))
                {
                    routeDataValues.Remove("page");
                }
            }
            else
            {
                routeDataValues["page"] = pageNumber;
            }
        }
    }
}


text:
require 'test_helper'

module RestfulSync
  class ApiClientTest < ActiveSupport::TestCase
    # test "the truth" do
    #   assert true
    # end
  end
end


text:
using System.Collections.Generic;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using Xunit;

namespace System.ComponentModel.Tests
{
    public class TimeSpanConverterTests : TypeConverterTestBase
    {
        public override TypeConverter Converter => new TimeSpanConverter();

        public override IEnumerable<ConvertTest> ConvertFromTestData()
        {
            yield return ConvertTest.Valid("  1000.00:00:00  ", new TimeSpan(1000, 0, 0, 0, 0), CultureInfo.InvariantCulture);
            yield return ConvertTest.Valid("1000", new TimeSpan(1000, 0, 0, 0, 0));

            yield return ConvertTest.Throws<FormatException>("invalid");
            yield return ConvertTest.Throws<FormatException>("  ");
            yield return ConvertTest.Throws<FormatException>(string.Empty);

            yield return ConvertTest.CantConvertFrom(1);
            yield return ConvertTest.CantConvertFrom(new object());
        }

        public override IEnumerable<ConvertTest> ConvertToTestData()
        {
            var timeSpan = new TimeSpan(1000, 0, 0, 0, 0);
            yield return ConvertTest.Valid(timeSpan, timeSpan.ToString());

            yield return ConvertTest.Valid(
                timeSpan,
                new InstanceDescriptor(
                    typeof(TimeSpan).GetMethod(nameof(TimeSpan.Parse), new Type[] { typeof(string) }),
                    new object[] { timeSpan.ToString() }
                )
            );

            yield return ConvertTest.CantConvertTo(new TimeSpan(1000, 0, 0, 0, 0), typeof(object));
        }

        [Theory]
        [InlineData(typeof(InstanceDescriptor))]
        [InlineData(typeof(int))]
        public void ConvertTo_InvalidValue_ThrowsNotSupportedException(Type destinationType)
        {
            Assert.Throws<NotSupportedException>(() => Converter.ConvertTo(new object(), destinationType));
        }
    }
}


text:
"""
A parsed token that represents a node test.
"""

from xml.dom import Node

from amara import tree
from amara.xpath import XPathError
from amara.xpath.locationpaths import _nodetests

__all__ = ('node_test', 'name_test')

class node_test(object):

    priority = -0.5
    node_type = None
    # By specifing a name_key of None, this test will fall into the 'general'
    # category for the principal type
    name_key = None

    def __str__(self):
        return self.__unicode__().encode('utf-8')

    def pprint(self, indent='', stream=None):
        print >> stream, indent + repr(self)

    def __repr__(self):
        ptr = id(self)
        if ptr < 0: ptr += 0x100000000L
        return '<%s at 0x%x: %s>' % (self.__class__.__name__, ptr, self)

# -- NodeType classes -------------------------------------------------

class node_type(node_test):

    _classmap = {}

    class __metaclass__(type):
        def __init__(cls, name, bases, namespace):
            if 'name' in namespace:
                cls._classmap[cls.name] = cls

    def __new__(cls, name, *args):
        return object.__new__(cls._classmap[name])

    def get_filter(self, compiler, principal_type):
        return _nodetests.nodefilter(self.node_type)

    def match(self, context, node, principal_type=tree.element):
        """
        The principalType is discussed in section [2.3 Node Tests]
        of the XPath 1.0 spec.  Only attribute and namespace axes
        differ from the default of elements.
        """
        return isinstance(node, self.node_type)

    def __str__(self):
        return self.name + '()'

class any_node_test(node_type):
    name = 'node'
    node_type = tree.node

    def get_filter(self, compiler, principal_type):
        return None

class comment_test(node_type):
    name = 'comment'
    node_type = tree.comment

class text_test(node_type):
    name = 'text'
    node_type = tree.text

class processing_instruction_test(node_type):
    name = 'processing-instruction'
    node_type = tree.processing_instruction

    def __init__(self, name, target=None):
        if target:
            self.priority = 0
            if target[:1] not in ('"', "'"):
                raise SyntaxError("Invalid literal: %r" % target)
            self._target = target[1:-1]
        else:
            self.priority = -0.5
            self._target = None

    def get_filter(self, compiler, principal_type):
        return _nodetests.nodefilter(self.node_type, self._target)

    def match(self, context, node, principal_type=tree.element):
        if isinstance(node, principal_type):
            if self._target:
                return node.target == self._target
            return True
        return False

    def __str__(self):
        if self._target:
            target = self._target.encode('unicode_escape')
            return '%s("%s")' % (self.name, target.replace('"', '\\"'))
        return node_type.__str__(self)

# -- NameTest classes -------------------------------------------------

class name_test(node_test):

    node_type = tree.element

    def __new__(cls, name):
        if name[-1:] == '*':
            if ':' in name:
                cls = namespace_test
            else:
                cls = principal_type_test
        elif ':' in name:
            cls = qualified_name_test
        else:
            cls = local_name_test
        return object.__new__(cls)

class principal_type_test(name_test):

    def get_filter(self, compiler, principal_type):
        return _nodetests.nodefilter(principal_type)

    def match(self, context, node, principal_type=tree.element):
        return isinstance(node, principal_type)

    def __str__(self):
        return '*'

class local_name_test(name_test):

    priority = 0

    def __init__(self, name):
        self._name = name
        self.name_key = (None, name)

    def get_filter(self, compiler, principal_type):
        return _nodetests.nodefilter(principal_type, None, self._name)

    def match(self, context, node, principal_type=tree.element):
        # NameTests do not use the default namespace, just as attributes
        if isinstance(node, principal_type) and not node.xml_namespace:
            return node.xml_local == self._name
        return 0

    def __str__(self):
        return self._name

class namespace_test(name_test):

    priority = -0.25

    def __init__(self, name):
        self._prefix = name[:name.index(':')]

    def get_filter(self, compiler, principal_type):
        try:
            namespace = compiler.namespaces[self._prefix]
        except KeyError:
            raise XPathError(XPathError.UNDEFINED_PREFIX, prefix=self._prefix)
        return _nodetests.nodefilter(principal_type, namespace, None)

    def match(self, context, node, principal_type=tree.element):
        if not isinstance(node, principal_type):
            return False
        try:
            return node.xml_namespace == context.namespaces[self._prefix]
        except KeyError:
            raise XPathError(XPathError.UNDEFINED_PREFIX,
                             prefix=self._prefix)

    def __str__(self):
        return self._prefix + ':*'

class qualified_name_test(name_test):

    priority = 0

    def __init__(self, name):
        self.name_key = name.split(':', 1)

    def get_filter(self, compiler, principal_type):
        prefix, local_name = self.name_key
        try:
            namespace = compiler.namespaces[prefix]
        except KeyError:
            raise XPathError(XPathError.UNDEFINED_PREFIX, prefix=prefix)
        return _nodetests.nodefilter(principal_type, namespace, local_name)

    def match(self, context, node, principal_type=tree.element):
        if isinstance(node, principal_type):
            prefix, local_name = self.name_key
            if node.xml_local == local_name:
                try:
                    return node.xml_namespace == context.namespaces[prefix]
                except KeyError:
                    raise XPathError(XPathError.UNDEFINED_PREFIX,
                                     prefix=prefix)
        return 0

    def __str__(self):
        return ':'.join(self.name_key)


text:
package br.com.elotech.tributacao.oxm.abstractenvioresposta;

import br.com.elotech.tributacao.oxm.nfse.SolicitacaoLote;

public abstract class AbstractConsultarLoteRpsEnvio extends AbstractEnvioMsg implements SolicitacaoLote {

	private Integer numeroLote;

	public Integer getNumeroLote() {
		return numeroLote;
	}

	public void setNumeroLote(Integer numeroLote) {
		this.numeroLote = numeroLote;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("ConsultarLoteRpsEnvio [numeroLote=");
		builder.append(numeroLote);
		builder.append("]");
		return builder.toString()+ super.toString();
	}

	@Override
	public String getTipoSolicitacao() {
		return "ConsultarLoteRpsEnvio";
	}
}


text:
package org.xtreemfs.babudb.replication.service.operations;

import java.util.concurrent.atomic.AtomicReference;

import org.xtreemfs.babudb.pbrpc.GlobalTypes.DBFileMetaData;
import org.xtreemfs.babudb.pbrpc.GlobalTypes.DBFileMetaDatas;
import org.xtreemfs.babudb.pbrpc.GlobalTypes.LSN;
import org.xtreemfs.babudb.pbrpc.ReplicationServiceConstants;
import org.xtreemfs.babudb.replication.BabuDBInterface;
import org.xtreemfs.babudb.replication.transmission.FileIOInterface;
import org.xtreemfs.babudb.replication.transmission.dispatcher.Operation;
import org.xtreemfs.babudb.replication.transmission.dispatcher.Request;
import org.xtreemfs.foundation.logging.Logging;

import com.google.protobuf.Message;

/**
 * {@link Operation} to request a {@link DBFileMetaDataSet} from the master.
 *
 * @since 05/03/2009
 * @author flangner
 */

public class LoadOperation extends Operation {

    private final AtomicReference<org.xtreemfs.babudb.lsmdb.LSN>  lastOnView;

    private final BabuDBInterface                                 babuInterface;

    private final FileIOInterface                                 fileIO;

    private final int                                             maxChunkSize;

    public LoadOperation(AtomicReference<org.xtreemfs.babudb.lsmdb.LSN> lastOnView,
            int maxChunkSize, BabuDBInterface babuInterface, FileIOInterface fileIO) {

        this.fileIO = fileIO;
        this.maxChunkSize = maxChunkSize;
        this.babuInterface = babuInterface;
        this.lastOnView = lastOnView;
    }

    /* (non-Javadoc)
     * @see org.xtreemfs.babudb.replication.service.operations.Operation#
     * getProcedureId()
     */
    @Override
    public int getProcedureId() {
        return ReplicationServiceConstants.PROC_ID_LOAD;
    }

    /* (non-Javadoc)
     * @see org.xtreemfs.babudb.replication.transmission.dispatcher.Operation#getDefaultRequest()
     */
    @Override
    public Message getDefaultRequest() {
        return org.xtreemfs.babudb.pbrpc.GlobalTypes.LSN.getDefaultInstance();
    }

    /* (non-Javadoc)
     * @see org.xtreemfs.babudb.replication.transmission.dispatcher.Operation#
     *          processRequest(org.xtreemfs.babudb.replication.transmission.dispatcher.Request)
     */
    @Override
    public void processRequest(Request rq) {
        LSN request = (LSN) rq.getRequestMessage();
        org.xtreemfs.babudb.lsmdb.LSN lov = lastOnView.get();

        Logging.logMessage(Logging.LEVEL_DEBUG, this, "LOAD from LSN(%s), by %s (LastOnView: LSN(%s))",
                request.toString(), rq.getSenderAddress().toString(), lov.toString());

        if (new org.xtreemfs.babudb.lsmdb.LSN(request.getViewId(), request.getSequenceNo()).equals(lov)) {

            rq.sendSuccess(DBFileMetaDatas.getDefaultInstance());
        } else {
            DBFileMetaDatas.Builder result = DBFileMetaDatas.newBuilder();
            result.setMaxChunkSize(maxChunkSize);

            synchronized (babuInterface.getDBModificationLock()) {
                synchronized (babuInterface.getCheckpointerLock()) {

                    // add the DB-structure-file metadata
                    result.addDbFileMetadatas(convert(fileIO.getConfigFileMetaData()));

                    // add the latest snapshot files for every DB,
                    // if available
                    for (org.xtreemfs.babudb.lsmdb.LSMDatabase.DBFileMetaData md :
                        babuInterface.getAllSnapshotFiles()) {

                        result.addDbFileMetadatas(convert(md));
                    }
                }
            }
            rq.sendSuccess(result.build());
        }
    }

    private DBFileMetaData convert(
            org.xtreemfs.babudb.lsmdb.LSMDatabase.DBFileMetaData metaData) {
        return DBFileMetaData.newBuilder()
                .setFileName(metaData.file)
                .setFileSize(metaData.size).build();
    }
}


text:
class MOPlayerPhysProperties : public FBPhysicalProperties
{
	FBPhysicalPropertiesDeclare( MOPlayerPhysProperties, FBPhysicalProperties );

public:

	//--- Creation & Destruction
	virtual bool			FBCreate() override;						//!< Constructor.
	virtual void			FBDestroy() override;						//!< Destructor.

	static void				AddPropertiesToPropertyViewManager();

public:

	FBPropertyBool			Active;

private:

	bool							mOnline;
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Depazea tiliae Lasch

### Remarks
null


text:
.main-container {
    margin-top: 50px;
}


text:
<?php

class Stripe_Customer extends Stripe_ApiResource
{
  public static function constructFrom($values, $apiKey=null)
  {
    $class = get_class();
    return self::scopedConstructFrom($class, $values, $apiKey);
  }

  public static function retrieve($id, $apiKey=null)
  {
    $class = get_class();
    return self::_scopedRetrieve($class, $id, $apiKey);
  }

  public static function all($params=null, $apiKey=null)
  {
    $class = get_class();
    return self::_scopedAll($class, $params, $apiKey);
  }

  public static function create($params=null, $apiKey=null)
  {
    $class = get_class();
    return self::_scopedCreate($class, $params, $apiKey);
  }

  public function save()
  {
    $class = get_class();
    return self::_scopedSave($class);
  }

  public function delete($params=null)
  {
    $class = get_class();
    return self::_scopedDelete($class, $params);
  }

  public function addInvoiceItem($params=null)
  {
    if (!$params)
      $params = array();
    $params['customer'] = $this->id;
    $ii = Stripe_InvoiceItem::create($params, $this->_apiKey);
    return $ii;
  }

  public function invoices($params=null)
  {
    if (!$params)
      $params = array();
    $params['customer'] = $this->id;
    $invoices = Stripe_Invoice::all($params, $this->_apiKey);
    return $invoices;
  }

  public function invoiceItems($params=null)
  {
    if (!$params)
      $params = array();
    $params['customer'] = $this->id;
    $iis = Stripe_InvoiceItem::all($params, $this->_apiKey);
    return $iis;
  }

  public function charges($params=null)
  {
    if (!$params)
      $params = array();
    $params['customer'] = $this->id;
    $charges = Stripe_Charge::all($params, $this->_apiKey);
    return $charges;
  }

  public function updateSubscription($params=null)
  {
    $requestor = new Stripe_ApiRequestor($this->_apiKey);
    $url = $this->instanceUrl() . '/subscription';
    list($response, $apiKey) = $requestor->request('post', $url, $params);
    $this->refreshFrom(array('subscription' => $response), $apiKey, true);
    return $this->subscription;
  }

  public function cancelSubscription($params=null)
  {
    $requestor = new Stripe_ApiRequestor($this->_apiKey);
    $url = $this->instanceUrl() . '/subscription';
    list($response, $apiKey) = $requestor->request('delete', $url, $params);
    $this->refreshFrom(array('subscription' => $response), $apiKey, true);
    return $this->subscription;
  }
}


text:
from collections import defaultdict
try:
    from itertools import zip_longest
except ImportError:
    from itertools import izip_longest as zip_longest

_NONE_TYPE = type(None)
_EMPTY_TYPE = type('', (object,), {})
_MIXED_TYPE = type('<mixed-type>', (object,), {})

class AttrDict(dict):
    """A dict with keys accessible as attributes."""
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

class Structure(object):
    """An object that reflects the structure of any python data structure.

    Any object may be passed to the constructor and a complete traverse of the
    structure occurs, making all the appropriate links so that the hierarchy
    may be examined. The str function will turn these objects into a simple
    representation of the structure with notations for lists and whether or
    not an attribute will be guaranteed for each particular branch.
    Also supported is adding different Structure objects, which will show only
    the structure common to both. Wherever the structure differs, it will
    be noted as a '<mixed-type>'
    """
    def __init__(self, value, key=None, parent=None):
        """Initialize a structure

        Takes the type of the value, and recursively creates sub-structures
        as children if the type is a list, tuple, or dict.
        """
        self.key = key
        self.parent = parent
        self.type_ = type(value)
        self.key_guaranteed = True
        self.val_guaranteed = True
        self.children = []

        if self.is_list:
            # Make a structure out of each item in the list
            list_items = [Structure(item, parent=self) for item in value]
            if list_items:
                # Add all structures together to get the common structure
                merged_structure = list_items[0]
                for item in list_items[1:]:
                    merged_structure += item
                # Set the only list child to the common structure
                merged_structure.parent = self
                self.children.append(merged_structure)
            else:
                self.children.append(Structure(_EMPTY_TYPE(), parent=self))
        elif self.is_tuple:
            # Make a structure out of each item in the tuple
            tuple_items = [Structure(item, parent=self) for item in value]
            if tuple_items:
                self.children = tuple_items
        elif self.is_dict:
            for key, val in value.items():
                self.children.append(Structure(val, key, self))
            self.children.sort(key=lambda child: child.key)

    def __add__(self, other):
        """Add structures to get a new structure that is common to both.

        The returned structure is a newly created structure that reflects the
        similarities and differences between the two structures added.
        """

        key_guaranteed = self.key_guaranteed and other.key_guaranteed
        val_guaranteed = self.val_guaranteed and other.val_guaranteed

        if self.type_ is other.type_:
            new = Structure(None, key=self.key)
            new.type_ = self.type_
            new.key_guaranteed = key_guaranteed
            new.val_guaranteed = val_guaranteed

            if self.is_list and other.is_list:
                listchild = self.children[0] + other.children[0]
                listchild.parent = new
                new.children.append(listchild)
                return new
            elif self.is_tuple and other.is_tuple:
                zipped = zip_longest(self.children, other.children)
                for schild, ochild in zipped:
                    if schild is None:
                        newchild = ochild.copy(new)
                        newchild.val_guaranteed = False
                        new.children.append(newchild)
                    elif ochild is None:
                        newchild = schild.copy(new)
                        newchild.val_guaranteed = False
                        new.children.append(newchild)
                    else:
                        newchild = schild + ochild
                        newchild.parent = new
                        new.children.append(newchild)
                return new
            elif self.is_dict and other.is_dict:
                keysdict = defaultdict(lambda: [None, None])
                for child in self.children:
                    keysdict[child.key][0] = child
                for child in other.children:
                    keysdict[child.key][1] = child
                for c1, c2 in keysdict.values():
                    if c1 is None:
                        newchild = c2.copy(new)
                        newchild.key_guaranteed = False
                    elif c2 is None:
                        newchild = c1.copy(new)
                        newchild.key_guaranteed = False
                    else:
                        newchild = c1 + c2
                        newchild.parent = new
                    new.children.append(newchild)
                new.children.sort(key=lambda child: child.key)
                return new
            else:
                return new
        else:
            if self.type_ is _EMPTY_TYPE:
                new = other.copy()
            elif other.type_ is _EMPTY_TYPE:
                new = self.copy()
            elif self.type_ is _NONE_TYPE:
                new = other.copy()
                new.key_guaranteed = key_guaranteed
                new.val_guaranteed = False
            elif other.type_ is _NONE_TYPE:
                new = self.copy()
                new.key_guaranteed = key_guaranteed
                new.val_guaranteed = False
            else:
                new = Structure(None, key=self.key)
                new.key_guaranteed = key_guaranteed
                new.val_guaranteed = val_guaranteed
                new.type_ = _MIXED_TYPE
            return new

    def __str__(self):
        """A structured representation of the underlying structure"""
        if self.parent:
            string = '{}{}{} - {}\n'.format(
                '  ' * (self.generation),
                '' if self.key_guaranteed else '*',
                self.key,
                self.type_string)
        else:
            string = '{}\n'.format(self.type_string)
        if self.children:
            if self.is_list:
                sub = self.children[0]
                while sub.is_list:
                    sub = sub.children[0]
                if sub.is_dict:
                    for child in sub.children:
                        string += str(child) + '\n'
            elif self.is_dict:
                for child in self.children:
                    string += str(child) + '\n'
        return string[:-1]

    def copy(self, parent=None):
        """Copies an existing structure and all of it's children"""
        new = Structure(None, parent=parent)
        new.key = self.key
        new.type_ = self.type_
        new.val_guaranteed = self.val_guaranteed
        new.key_guaranteed = self.key_guaranteed
        for child in self.children:
            new.children.append(child.copy(new))
        return new

    @property
    def generation(self):
        """Returns the number of ancestors that are dictionaries"""
        if not self.parent:
            return 0
        elif self.parent.is_dict:
            return 1 + self.parent.generation
        else:
            return self.parent.generation

    @property
    def type_string(self):
        """Returns a string representing the type of the structure"""
        if self.is_tuple:
            subtypes = [item.type_string for item in self.children]
            return '{}({})'.format(
                '' if self.val_guaranteed else '*',
                ', '.join(subtypes))
        elif self.is_list:
            return '{}[{}]'.format(
                '' if self.val_guaranteed else '*',
                self.children[0].type_string)
        else:
            return '{}{}'.format(
                '' if self.val_guaranteed else '*',
                self.type_.__name__)

    @property
    def is_list(self):
        return issubclass(self.type_, list)

    @property
    def is_tuple(self):
        return issubclass(self.type_, tuple)

    @property
    def is_dict(self):
        return issubclass(self.type_, dict)


text:
module ReadDataFile

export Reader, read_str, read_bool, read_int, read_flt, read_int_array, read_flt_array, close_reader

mutable struct Reader

    fname::String
    istream::IOStream
    line::String
    lineno::Int

    # a constructor: opens a file, sets lineno
    function Reader(fname::String)
        istream = open(fname, "r")
        r = new(fname,istream, "", 0)
        return r
    end
end

finalizer(r::Reader, close_reader) = close_reader(r)

function readln(r::Reader)
    skip_rexp = r"^\s*(?:#|$)"
    rexp = r"^\s*(.*?)\s*(?:(#|=:)\s*(.*?)\s*$|$)"

    while true
        r.line = readline(r.istream)
        r.lineno += 1
        # skip empty lines and comments starting from #
        if match(skip_rexp, r.line) == nothing
            break
        end
    end
    m = match(rexp, r.line)
    r.line = m.captures[1]
end

function read_str(r::Reader)
    readln(r)
    return r.line
end

function read_bool(r::Reader)
    readln(r)
    if r.line != "T" && r.line != "F"
        local fname = r.fname, lineno = r.lineno
        error("$fname($lineno): error parsing boolean")
    end
    return r.line == "T"
end

function read_int(r::Reader)
    readln(r)
    return parse(Int,r.line)
end

function read_flt(r::Reader)
    readln(r)
    return parse(Float64, r.line)
end

function read_raw(r::Reader)
    readln(r)
    return split(r.line)
end

function read_array(r::Reader, parser, len)
    buf = read_raw(r)
    buflen = length(buf)
    @assert(buflen == len)
    return [parser(buf[i]) for i = 1:buflen]
end

read_int_array(r::Reader, len::Int) = read_array(r, x -> parse(Int, x), len)
read_flt_array(r::Reader, len::Int) = read_array(r, x -> parse(Float64, x), len)

function close_reader(r::Reader)
    println("closing Reader $(r.fname)")
    Base.close(r.istream)
end

# ```jlcon
# julia> include("ReadDataFile.jl")
#
# julia> using .ReadDataFile
#
# julia> r = Reader("claw.data")
# -I- claw.data 6 blank lines were skipped
# Reader("claw.data",IOStream(<file claw.data>),"1",6,r"^\s*(.*?)\s*(?:#\s*(.*?)\s*$|$)")
#
# julia> readint(r)
# 1
#
# julia> readflt(r)
# -1.0
# ```

end # ReadDataFile


text:
var $ = jQuery.noConflict();

// Progress Bar

$(document).ready(function ($) {
    "use strict";

    $('.skill-shortcode').appear(function () {
        $('.progress').each(function () {
            $('.progress-bar').css('width',  function () { return ($(this).attr('data-percentage') + '%')});
        });
    }, {accY: -100});

});


text:
@interface BBVoice ()
@end

@implementation BBVoice

#pragma mark Initializers
- (id) initWithValues:(NSArray *)values {
    return [self initWithValues:values andVelocities:[self defaultVelocities:values.count]];
}

- (id) initWithValues:(NSArray *)values andVelocities:(NSArray *)velocities {
	self = [super init];

    if (self) {
        if (values.count < BBGrooverBeatMin ||
            values.count > BBGrooverBeatMax ||
            ![NSNumber isPowerOfTwo:values.count]) {
            @throw [NSException exceptionWithName:@"Invalid Values" reason:[NSString stringWithFormat:@"The values array of BBVoice object was %lu, must match a length in BBGrooverBeat enum (4/8/16/32).", (unsigned long)values.count] userInfo:nil];
        }
        _values = [NSMutableArray arrayWithArray:values];
		_velocities = [NSMutableArray arrayWithArray:velocities];

		// Just in case
		if (!_velocities) {
			_velocities = [self defaultVelocities:values.count];
		}

        _subdivision = values.count;
    }

    return self;
}

- (id) initWithSubdivision:(BBGrooverBeat)subdivision {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:subdivision];

    for (NSUInteger i = 0; i < subdivision; i++) {
        array[i] = @NO;
    }

    return [self initWithValues:array];
}

#pragma mark Convenience Contructors
+ (id) voiceWithValues:(NSArray *)values {
	BBVoice *voice = [[self alloc] initWithValues:values];
	return voice;
}

+ (id) voiceWithValues:(NSArray *)values andVelocities:(NSArray *)velocities {
	BBVoice *voice = [[self alloc] initWithValues:values andVelocities:velocities];
	return voice;
}

+ (id) voiceWithSubdivision:(BBGrooverBeat)subdivision {
	BBVoice *voice = [[self alloc] initWithSubdivision:subdivision];
	return voice;
}

#pragma mark Instance Methods
- (void) setValue:(BOOL)value forIndex:(NSUInteger)index {
    [self mutValues][index] = @(value);
}

- (void) setVelocity:(float)velocity forIndex:(NSUInteger)index {
	[self mutVelocities][index] = @(velocity);
}

#pragma mark Private Methods
- (NSMutableArray *) mutValues {
	return (NSMutableArray *)_values;
}

- (NSMutableArray *) mutVelocities {
	return (NSMutableArray *)_velocities;
}

- (NSMutableArray *) defaultVelocities:(NSInteger)count {
	NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];

	for (NSUInteger i = 0; i < count; i++) {
		array[i] = @1.0f;
	}

	return array;
}

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NldbApi.Models
{
    public class CharacterRerollPossibility
    {
        public string Name { get; set; }
        public string ImageName { get; set; }
        public int? CssHorizontalOffset { get; set; }
        public int? CssVerticalOffset { get; set; }
    }
}


text:
import React, { Component } from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import PropTypes from 'prop-types';
import styles from './style';
import Cell from './cell';

class Modal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      options: [],
      id: 0,
    };
    this.rmMsg = this.rmMsg.bind(this);
  }
  remove(arr, id) {
    this.arr = arr;
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].id === id) {
        arr.splice(i, 1);
      }
    }
    return arr;
  }
  toaster(arr) {
    const Newid = this.state.id + 1;
    arr.id = Newid;
    const newOptions = this.state.options;
    newOptions.push(arr);
    this.setState({ id: Newid });
    this.setState({ options: newOptions });
  }
  rmMsg(key) {
    const newOptions = this.state.options;
    const newarr = this.remove(newOptions, key);
    this.setState({ options: newarr });
  }
  render() {
    let contbg = '';
    const self = this;
    if (this.state.options.length > 0) {
      contbg = (
);
    }
    const resumap = this.state.options.map((itm) => {
      const cell = (
        <Cell options={itm} key={itm.id} callbackRM={self.rmMsg} />
      );
      return cell;
    });
    return (

        <ReactCSSTransitionGroup
          transitionName="modal"
          transitionEnterTimeout={400}
          transitionLeaveTimeout={400}
        >
          {resumap}
          {contbg}
        </ReactCSSTransitionGroup>

    );
  }
}

Modal.propTypes = {
  callbackRM: PropTypes.func
  // style: PropTypes.shape({})
};

Modal.defaultProps = {
  options: [],
  callbackRM: () => {}
};

export default Modal;


text:
@implementation MPBannerCustomEvent (Internal)

- (void)trackImpressionsIncludedInMarkup
{
    // no-op.
}

- (void)startViewabilityTracker
{
    // no-op
}

@end