text:
package org.assertj.core.internal.int2darrays;

import static org.assertj.core.data.Index.atIndex;
import static org.mockito.Mockito.verify;

import org.assertj.core.api.AssertionInfo;
import org.assertj.core.data.Index;
import org.assertj.core.internal.Int2DArrays;
import org.assertj.core.internal.Int2DArraysBaseTest;
import org.junit.jupiter.api.Test;

/**
 * Tests for <code>{@link Int2DArrays#assertContains(AssertionInfo, int[][], int[], Index)}</code>.
 *
 * @author Maciej Wajcht
 */
class Int2DArrays_assertContains_at_Index_Test extends Int2DArraysBaseTest {

  @Test
  void should_delegate_to_Arrays2D() {
    // GIVEN
    int[] ints = new int[] { 6, 8, 10 };
    // WHEN
    int2DArrays.assertContains(info, actual, ints, atIndex(1));
    // THEN
    verify(arrays2d).assertContains(info, failures, actual, ints, atIndex(1));
  }
}


text:
import mock
import unittest

from sts.entities.controllers import Controller
from sts.entities.controllers import ControllerAbstractClass
from sts.entities.controllers import ControllerState

class ControllerAbstractClassTest(unittest.TestCase):
  def get_concrete_class(self):
    """Simple mock for the abstract methods and properties"""
    class ControllerImpl(ControllerAbstractClass):
      def is_remote(self):
        return True

      @property
      def blocked_peers(self):
        return True

      def start(self, multiplex_sockets=False):
        return True

      def block_peer(self, peer_controller):
        return True

      def unblock_peer(self, peer_controller):
        return True

      def check_status(self, simulation):
        return ControllerState.ALIVE, "ALIVE"

    return ControllerImpl

  def test_init(self):
    # Arrange
    config = mock.MagicMock()
    label = "dummy_controller"
    cid = 123
    config.label = label
    config.cid = cid
    controller_cls = self.get_concrete_class()
    # Act
    c = controller_cls(config)
    # Assert
    self.assertEquals(c.config, config)
    self.assertEquals(c.state, ControllerState.DEAD)
    self.assertEquals(c.cid, cid)
    self.assertEquals(c.label, label)

class ControllerTest(unittest.TestCase):
  """
  TODO: test restart, snapshot_proceed, and check_status methods
  """
  def get_config(self):
    config = mock.MagicMock()
    label = "dummy_controller"
    cid = 123
    config.label = label
    config.cid = cid
    config.address = "localhost"
    config.launch_in_network_namespace = False
    config.start_cmd = ":" # NOP
    config.expanded_start_cmd = ["ls"] # NOP
    config.kill_cmd = ":" # NOP
    config.expanded_kill_cmd = ["ls"] # NOP
    config.cwd = "."
    config.snapshot_address = False
    return config

  def test_init(self):
    # Arrange
    config = self.get_config()
    c = Controller(config)
    # Act
    con = c.config
    state = c.state
    cid = c.cid
    label = c.label
    # Assert
    self.assertEquals(con, config)
    self.assertEquals(state, ControllerState.DEAD)
    self.assertEquals(cid, config.cid)
    self.assertEquals(label, config.label)

  def test_remote(self):
    # Arrange
    config1 = self.get_config()
    config2 = self.get_config()
    config2.address = "192.168.56.1"
    c1 = Controller(config1)
    c2 = Controller(config2)
    # Act
    is_remote1 = c1.is_remote
    is_remote2 = c2.is_remote
    # Assert
    self.assertFalse(is_remote1)
    self.assertTrue(is_remote2)

  def test_start(self):
    # Arrange
    config = self.get_config()
    Controller._check_snapshot_connect = mock.Mock()
    Controller._register_proc = mock.Mock()
    Controller._check_snapshot_connect = mock.Mock()
    Controller.kill = mock.Mock()
    c = Controller(config)
    # Act
    c.start()
    state = c.state
    del c # To make sure the clean up was done properly
    # Assert
    self.assertEquals(state, ControllerState.ALIVE)
    self.assertEquals(Controller._register_proc.call_count, 1)
    self.assertEquals(Controller.kill.call_count, 1)

  def test_kill(self):
    # Arrange
    config = self.get_config()
    Controller._check_snapshot_connect = mock.Mock()
    Controller._unregister_proc = mock.Mock()
    Controller._check_snapshot_connect = mock.Mock()
    c = Controller(config)
    c.state = ControllerState.ALIVE
    # Act
    c.kill()
    state = c.state
    # Assert
    self.assertEquals(state, ControllerState.DEAD)
    self.assertEquals(Controller._unregister_proc.call_count, 1)
    self.assertIsNone(c.process)

redpajama_set_name: RedPajamaGithub


text:
($imported ||= {})["IEO-ZeronTitle"] = true
#==============================================================================#
# $ieo_script - This is a hash specific to IEO scripts
#               they work just like the $imported, but there key is slightly
#               different, it is an array conatining an integer
#               and a string, since IEO script all have an ID, the value
#               is the scripts version number.
#               A version number of nil, or 0 means the script isn't present
# EG. $ieo_script[[ScriptID, "ScriptName"]]
($ieo_script = {})[[29, "ZeronTitle"]] = 1.0
#-*--------------------------------------------------------------------------*-#
#==============================================================================#
#==============================================================================#
# IEO::TITLE_SCREEN
#==============================================================================#
module IEO
  module TITLE_SCREEN
#==============================================================================#
#                      Start Primary Customization
#------------------------------------------------------------------------------#
#==============================================================================#
  #--------------------------------------------------------------------------#
  # * TITLE_LAYOUT
  #--------------------------------------------------------------------------#
  # This controls the order in which commands appear in the menu
  # Default commands
  # :newgame, :continue, :shutdown
  #--------------------------------------------------------------------------#
    TITLE_LAYOUT = [
      :newgame,
      :continue,
      :shutdown,
      :iconview
    ]
#==============================================================================#
#                        End Primary Customization
#------------------------------------------------------------------------------#
#==============================================================================#
  end
end

#==============================================================================#
# Scene_Title - IEO029-Lunatic
#==============================================================================#
class Scene_Title < Scene_Base

  attr_accessor :continue_enabled

  #--------------------------------------------------------------------------#
  # * new method :title_command
  #--------------------------------------------------------------------------#
  def title_command(command)
    titlelay = IEO::TITLE_SCREEN::TITLE_LAYOUT
    case command
    when :newgame
      command_new_game()
    when :continue
      command_continue()
    when :shutdown
      command_shutdown()
    when :iconview
      command_iconview()
    end
  end

  #--------------------------------------------------------------------------#
  # * new class method :hide_command?
  #--------------------------------------------------------------------------#
  def self.hide_command?(com)
    case com
    when :newgame  ; return false
    when :continue ; return $scene.continue_enabled
    when :shutdown ; return false
    when :iconview ; return !$TEST
    end
    return false
  end

  #--------------------------------------------------------------------------#
  # * new class method :command_index
  #--------------------------------------------------------------------------#
  def self.command_index(com)
    return IEO::TITLE_SCREEN::TITLE_LAYOUT.index(com)
  end

end

#==============================================================================#
# IEO::Vocab
#==============================================================================#
module IEO
  module Vocab

    module_function

    def title(command)
      case command
      when :newgame  ; return ::Vocab.new_game
      when :continue ; return ::Vocab.continue
      when :shutdown ; return ::Vocab.shutdown
      #when :iconview ; return ::YEM::ICONVIEW::COMMAND_NAME
      else           ; return ""
      end
    end

  end
end

#==============================================================================#
# IEO::Icon
#==============================================================================#
module IEO
  module Icon
    module_function
    def title(command) ; return 0 end
  end
end

#==============================================================================#
# Window_TitleCommand
#==============================================================================#
class Window_TitleCommand < Window_Command

  #--------------------------------------------------------------------------#
  # * new method :get_current_command
  #--------------------------------------------------------------------------#
  def get_current_command ; return @commands[self.index] end

  #--------------------------------------------------------------------------#
  # * overwrite method :refresh
  #--------------------------------------------------------------------------#
  def refresh
    self.contents.clear
    for i in 0...@item_max
      draw_item(i, !Scene_Title.hide_command?(@commands[i]))
    end
  end

  #--------------------------------------------------------------------------#
  # * overwrite method :item_rect
  #--------------------------------------------------------------------------#
  def item_rect(index, adapt=true)
    rect = Rect.new(0, 0, 0, 0)
    rect.width = (contents.width + @spacing) / @column_max - @spacing
    rect.height = WLH
    rect.x = index % @column_max * (rect.width + @spacing)
    rect.y = index / @column_max * WLH
    if $imported["IEO-BugFixesUpgrades"]
      if IEO::UPGRADE::ADAPTIVE_CURSOR
        if adapt
          tx = IEO::Vocab.title(@commands[index])
          rect.width = self.contents.text_size(tx).width+12
          icon = IEO::Icon.title(@commands[index])
          rect.width += 24 if icon > 0
        end
      end
    end
    return rect
  end

  #--------------------------------------------------------------------------#
  # * overwrite method :draw_item
  #--------------------------------------------------------------------------#
  def draw_item(index, enabled = true)
    self.contents.font.size = Font.default_size
    rect = item_rect(index, false)
    rect.x += 4
    rect.width -= 8
    self.contents.clear_rect(rect)
    self.contents.font.color = normal_color
    self.contents.font.color.alpha = enabled ? 255 : 128
    icon = IEO::Icon.title(@commands[index])
    if icon > 0
      draw_icon(icon, rect.x, rect.y)
      rect.x += 24 ; rect.width -= 24
    end
    self.contents.draw_text(rect, IEO::Vocab.title( @commands[index] ))
  end

end

#==============================================================================#
# Scene_Title
#==============================================================================#
class Scene_Title < Scene_Base

  #--------------------------------------------------------------------------#
  # * overwrite method :create_command_window
  #--------------------------------------------------------------------------#
  def create_command_window()
    commands = IEO::TITLE_SCREEN::TITLE_LAYOUT
    @command_window = Window_TitleCommand.new(172, commands)
    @command_window.x = (544 - @command_window.width) / 2
    @command_window.y = 288
    if @continue_enabled                    # If continue is enabled
      @command_window.index = 1             # Move cursor over command
    end
    @command_window.openness = 0
    @command_window.open
  end

  #--------------------------------------------------------------------------#
  # * overwrite method :update
  #--------------------------------------------------------------------------#
  def update()
    super()
    @command_window.update()
    if Input.trigger?(Input::C)
      com = @command_window.get_current_command()
      title_command(com)
    end
  end

end

IEO::REGISTER.log_script(29, "ZeronTitle", 1.0) if $imported["IEO-Register"]
#=*==========================================================================*=#
# ** END OF FILE
#=*==========================================================================*=#


text:
package com.patrick.id.util;

import com.fasterxml.uuid.EthernetAddress;
import com.fasterxml.uuid.Generators;
import com.fasterxml.uuid.impl.TimeBasedGenerator;

public class KeyUtil {

    public static String generatorUUID() {
        TimeBasedGenerator timeBasedGenerator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
        return timeBasedGenerator.generate().toString();
    }

    public static void main(String[] args) {
        System.out.println(KeyUtil.generatorUUID());
        System.out.println(KeyUtil.generatorUUID());
    }
}


text:
import * as Mof from "../Mof"
import * as Settings from "../Settings"
import * as ApiConnection from "../ApiConnection"

/*
    Gets the default form for an extent uri by the webserver
 */
export async function getCollectionFormForExtent(workspace: string, extentUri: string, viewMode: string) {
    const resultFromServer = await ApiConnection.get<object>(
        Settings.baseUrl +
        "api/forms/default_for_extent/" +
        encodeURIComponent(workspace) +
        "/" +
        encodeURIComponent(extentUri) +
        "/" +
        encodeURIComponent(viewMode)
    );

    return Mof.convertJsonObjectToDmObject(resultFromServer);
}

/*
    Gets the default form for an extent uri by the webserver
 */
export async function getObjectFormForMetaClass(metaClassUri: string) {

    const resultFromServer = await ApiConnection.get<object>(
        Settings.baseUrl +
        "api/forms/default_object_for_metaclass/" +
        encodeURIComponent(metaClassUri)
    );

    return Mof.convertJsonObjectToDmObject(resultFromServer);
}

/**
 * Defines the form types
 */
export enum FormType
{
    Object= "object",
    Collection = "collection",
    Row = "row",
    Table = "table"
}

export async function getForm(formUri: string, formType?: FormType): Promise<Mof.DmObject> {
    const resultFromServer = await ApiConnection.get<object>(
        Settings.baseUrl +
        "api/forms/get/" +
        encodeURIComponent(formUri) +
        (formType === undefined ? "" : "?formtype=" + encodeURIComponent(formType))
    );

    return Mof.convertJsonObjectToDmObject(resultFromServer);
}

/*
    Gets the default form for a certain item by the webserver
 */
export async function getObjectFormForItem(workspace: string, item: string, viewMode: string) {
    const resultFromServer = await ApiConnection.get<object>(
        Settings.baseUrl +
        "api/forms/default_for_item/" +
        encodeURIComponent(workspace) +
        "/" +
        encodeURIComponent(item) +
        "/" +
        encodeURIComponent(viewMode)
    );
    return Mof.convertJsonObjectToDmObject(resultFromServer);
}

export interface GetViewModesResultServer{
    viewModes: Array<string>;
}

export interface GetViewModesResult{
    viewModes: Array<Mof.DmObject>;
}

export async function getViewModes() : Promise<GetViewModesResult> {
    const resultFromServer = await ApiConnection.get<GetViewModesResultServer>(
        Settings.baseUrl +
        "api/forms/get_viewmodes");

    const result =
        {
            viewModes: new Array<Mof.DmObject>()
        };

    for (let n in resultFromServer.viewModes) {
        const value = resultFromServer.viewModes[n];

        result.viewModes.push(Mof.convertJsonObjectToDmObject(value));
    }

    return result;
}


text:
package org.apache.commons.vfs2.provider.ftp;

import java.net.Proxy;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.Range;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemOptions;

/**
 * The config builder for various FTP configuration options.
 */
public class FtpFileSystemConfigBuilder extends FileSystemConfigBuilder {

    private static final String PREFIX = FtpFileSystemConfigBuilder.class.getName();

    private static final FtpFileSystemConfigBuilder BUILDER = new FtpFileSystemConfigBuilder();

    private static final String AUTODETECT_UTF8 = PREFIX + ".AUTODETECT_UTF8";
    private static final String CONNECT_TIMEOUT = PREFIX + ".CONNECT_TIMEOUT";
    private static final String DATA_TIMEOUT = PREFIX + ".DATA_TIMEOUT";
    private static final String DEFAULT_DATE_FORMAT = PREFIX + ".DEFAULT_DATE_FORMAT";
    private static final String ENCODING = PREFIX + ".ENCODING";
    private static final String FACTORY_KEY = FTPFileEntryParserFactory.class.getName() + ".KEY";
    private static final String FILE_TYPE = PREFIX + ".FILE_TYPE";
    private static final String PASSIVE_MODE = PREFIX + ".PASSIVE";
    private static final String ACTIVE_PORT_RANGE = PREFIX + ".ACTIVE_PORT_RANGE";
    private static final String PROXY = PREFIX + ".PROXY";
    private static final String RECENT_DATE_FORMAT = PREFIX + ".RECENT_DATE_FORMAT";
    private static final String REMOTE_VERIFICATION = PREFIX + ".REMOTE_VERIFICATION";
    private static final String SERVER_LANGUAGE_CODE = PREFIX + ".SERVER_LANGUAGE_CODE";
    private static final String SERVER_TIME_ZONE_ID = PREFIX + ".SERVER_TIME_ZONE_ID";
    private static final String SHORT_MONTH_NAMES = PREFIX + ".SHORT_MONTH_NAMES";
    private static final String SO_TIMEOUT = PREFIX + ".SO_TIMEOUT";
    private static final String CONTROL_KEEP_ALIVE_TIMEOUT = PREFIX + ".CONTROL_KEEP_ALIVE_TIMEOUT";
    private static final String CONTROL_KEEP_ALIVE_REPLY_TIMEOUT = PREFIX + ".CONTROL_KEEP_ALIVE_REPLY_TIMEOUT";
    private static final String USER_DIR_IS_ROOT = PREFIX + ".USER_DIR_IS_ROOT";
    private static final String TRANSFER_ABORTED_OK_REPLY_CODES = PREFIX + ".TRANSFER_ABORTED_OK_REPLY_CODES";
    private static final String MDTM_LAST_MODIFED_TIME = PREFIX + ".MDTM_LAST_MODIFED_TIME";

    private FtpFileSystemConfigBuilder() {
        super("ftp.");
    }

    /**
     * Create new config builder with specified prefix string.
     *
     * @param prefix prefix string to use for parameters of this config builder.
     * @since 2.1
     */
    protected FtpFileSystemConfigBuilder(final String prefix) {
        super(prefix);
    }

    /**
     * Gets the singleton instance.
     *
     * @return the singleton instance.
     */
    public static FtpFileSystemConfigBuilder getInstance() {
        return BUILDER;
    }

    /**
     * Gets special retry code.
     *
     * See VFS-674, its accompanying PR and https://github.com/apache/commons-vfs/pull/51 as to why 426 and 550 are here.
     *
     * @return special retry code.
     */
    public static List<Integer> getSaneTransferAbortedOkReplyCodes() {
        // See VFS-674, its accompanying PR and https://github.com/apache/commons-vfs/pull/51 as to why 426 and 550 are here
        return new ArrayList<>(Arrays.asList(FTPReply.TRANSFER_ABORTED, FTPReply.FILE_UNAVAILABLE));
    }

    /**
     * Gets whether to try to autodetect the server encoding (only UTF8 is supported).
     *
     * @param options The FileSystemOptions.
     * @return True if autodetection should be done.
     * @since 2.4
     */
    public Boolean getAutodetectUtf8(final FileSystemOptions options) {
        return getBoolean(options, AUTODETECT_UTF8);
    }

    @Override
    protected Class<? extends FileSystem> getConfigClass() {
        return FtpFileSystem.class;
    }

    /**
     * Gets the timeout in milliseconds to use for the socket connection.
     *
     * @param options The FileSystemOptions.
     * @return The timeout in milliseconds to use for the socket connection.
     * @since 2.1
     * @deprecated Use {@link #getConnectTimeoutDuration(FileSystemOptions)}.
     */
    @Deprecated
    public Integer getConnectTimeout(final FileSystemOptions options) {
        return getDurationInteger(options, CONNECT_TIMEOUT);
    }

    /**
     * Gets the timeout in milliseconds to use for the socket connection.
     *
     * @param options The FileSystemOptions.
     * @return The timeout in milliseconds to use for the socket connection.
     * @since 2.8.0
     */
    public Duration getConnectTimeoutDuration(final FileSystemOptions options) {
        return getDuration(options, CONNECT_TIMEOUT);
    }

    /**
     * @param options The FileSystemOptions.
     * @return The encoding.
     * @since 2.0
     */
    public String getControlEncoding(final FileSystemOptions options) {
        return getString(options, ENCODING);
    }

    /**
     * @param options The FileSystem options
     * @return The controlKeepAliveReplyTimeout value.
     * @since 2.8.0
     */
    public Duration getControlKeepAliveReplyTimeout(final FileSystemOptions options) {
        return getDuration(options, CONTROL_KEEP_ALIVE_REPLY_TIMEOUT);
    }

    /**
     * @param options The FileSystem options
     * @return The controlKeepAliveTimeout value.
     * @since 2.8.0
     */
    public Duration getControlKeepAliveTimeout(final FileSystemOptions options) {
        return getDuration(options, CONTROL_KEEP_ALIVE_TIMEOUT);
    }

    /**
     * @param options The FileSystemOptions.
     * @return The timeout for opening the data channel in milliseconds.
     * @see #setDataTimeout
     * @deprecated Use {@link #getDataTimeoutDuration(FileSystemOptions)}.
     */
    @Deprecated
    public Integer getDataTimeout(final FileSystemOptions options) {
        return getDurationInteger(options, DATA_TIMEOUT);
    }

    /**
     * Gets the timeout for opening the data channel.
     *
     * @param options The FileSystemOptions.
     * @return The timeout for opening the data channel.
     * @see #setDataTimeout
     * @since 2.8.0
     */
    public Duration getDataTimeoutDuration(final FileSystemOptions options) {
        return getDuration(options, DATA_TIMEOUT);
    }

    /**
     * Get the default date format used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig} for
     * details and examples.
     *
     * @param options The FileSystemOptions
     * @return The default date format.
     */
    public String getDefaultDateFormat(final FileSystemOptions options) {
        return getString(options, DEFAULT_DATE_FORMAT);
    }

    /**
     * @param options The FileSystemOptions.
     * @see #setEntryParser
     * @return the key to the EntryParser.
     */
    public String getEntryParser(final FileSystemOptions options) {
        return getString(options, FACTORY_KEY);
    }

    /**
     * @param options The FileSystemOptions.
     * @see #setEntryParserFactory
     * @return An FTPFileEntryParserFactory.
     */
    public FTPFileEntryParserFactory getEntryParserFactory(final FileSystemOptions options) {
        return getParam(options, FTPFileEntryParserFactory.class.getName());
    }

    /**
     * Gets the file type parameter.
     *
     * @param options The FileSystemOptions.
     * @return A FtpFileType
     * @since 2.1
     */
    public FtpFileType getFileType(final FileSystemOptions options) {
        return getEnum(FtpFileType.class, options, FILE_TYPE);
    }

    /**
     * Gets the option to use FTP MDTM for {@link FileContent#getLastModifiedTime()}.
     *
     * @param options The FileSystemOptions.
     * @return true if MDTM should be used.
     * @since 2.8.0
     */
    public Boolean getMdtmLastModifiedTime(final FileSystemOptions options) {
        return getBoolean(options, MDTM_LAST_MODIFED_TIME);
    }

    /**
     * @param options The FileSystemOptions.
     * @return true if passive mode is set.
     * @see #setPassiveMode
     */
    public Boolean getPassiveMode(final FileSystemOptions options) {
        return getBoolean(options, PASSIVE_MODE);
    }

    /**
     * Gets the active port range.
     *
     * @param options The FileSystemOptions.
     * @return the Range of active ports
     * @since 2.10.0
     */
    public Range<Integer> getActivePortRange(final FileSystemOptions options) {
        return getParam(options, ACTIVE_PORT_RANGE);
    }

    /**
     * Gets the Proxy.
     *
     * @param options The FileSystemOptions.
     * @return the Proxy
     * @since 2.1
     */
    public Proxy getProxy(final FileSystemOptions options) {
        return getParam(options, PROXY);
    }

    /**
     * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
     *
     * @param options The FileSystemOptions.
     * @return The recent date format.
     */
    public String getRecentDateFormat(final FileSystemOptions options) {
        return getString(options, RECENT_DATE_FORMAT);
    }

    /**
     * Gets whether to use remote verification.
     *
     * @param options The FileSystemOptions.
     * @return True if remote verification should be done.
     */
    public Boolean getRemoteVerification(final FileSystemOptions options) {
        return getBoolean(options, REMOTE_VERIFICATION);
    }

    /**
     * Get the language code used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and
     * examples.
     *
     * @param options The FilesystemOptions.
     * @return The language code of the server.
     */
    public String getServerLanguageCode(final FileSystemOptions options) {
        return getString(options, SERVER_LANGUAGE_CODE);
    }

    /**
     * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
     *
     * @param options The FileSystemOptions.
     * @return The server timezone id.
     */
    public String getServerTimeZoneId(final FileSystemOptions options) {
        return getString(options, SERVER_TIME_ZONE_ID);
    }

    /**
     * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
     *
     * @param options The FileSystemOptions.
     * @return An array of short month names.
     */
    public String[] getShortMonthNames(final FileSystemOptions options) {
        return getParam(options, SHORT_MONTH_NAMES);
    }

    /**
     * Gets The so timeout duration in milliseconds.
     *
     * @param options The FileSystem options.
     * @return The so timeout duration in milliseconds.
     * @see #getDataTimeout
     * @since 2.0
     * @deprecated Use {@link #getSoTimeoutDuration(FileSystemOptions)}.
     */
    @Deprecated
    public Integer getSoTimeout(final FileSystemOptions options) {
        return getDurationInteger(options, SO_TIMEOUT);
    }

    /**
     * Gets The so timeout duration.
     *
     * @param options The FileSystem options.
     * @return The timeout value in milliseconds.
     * @see #getDataTimeout
     * @since 2.8.0
     */
    public Duration getSoTimeoutDuration(final FileSystemOptions options) {
        return getDuration(options, SO_TIMEOUT);
    }

    /**
     * @param options The FileSystem options.
     * @return The list of reply codes (apart from 200) that are considered as OK when prematurely
     * closing a stream.
     * @since 2.4
     */
    public List<Integer> getTransferAbortedOkReplyCodes(final FileSystemOptions options) {
        return getParam(options, TRANSFER_ABORTED_OK_REPLY_CODES);
    }

    /**
     * Returns {@link Boolean#TRUE} if VFS should treat the user directory as the root directory. Defaults to
     * {@code Boolean.TRUE} if the method {@link #setUserDirIsRoot(FileSystemOptions, boolean)} has not been
     * invoked.
     *
     * @param options The FileSystemOptions.
     * @return {@code Boolean.TRUE} if VFS treats the user directory as the root directory.
     * @see #setUserDirIsRoot
     */
    public Boolean getUserDirIsRoot(final FileSystemOptions options) {
        return getBoolean(options, USER_DIR_IS_ROOT, Boolean.TRUE);
    }

    /**
     * Sets whether to try to autodetect the server encoding (only UTF8 is supported).
     *
     * @param options The FileSystemOptions.
     * @param autodetectUTF8 true if autodetection should be done.
     * @since 2.4
     */
    public void setAutodetectUtf8(final FileSystemOptions options, final Boolean autodetectUTF8) {
        setParam(options, AUTODETECT_UTF8, autodetectUTF8);
    }

    /**
     * Sets the timeout for the initial control connection.
     *

     * If you set the connectTimeout to {@code null} no connectTimeout will be set.
     *

     *
     * @param options The FileSystemOptions.
     * @param duration the timeout duration in milliseconds
     * @since 2.8.0
     */
    public void setConnectTimeout(final FileSystemOptions options, final Duration duration) {
        setParam(options, CONNECT_TIMEOUT, duration);
    }

    /**
     * Sets the timeout for the initial control connection.
     *

     * If you set the connectTimeout to {@code null} no connectTimeout will be set.
     *

     *
     * @param options The FileSystemOptions.
     * @param duration the timeout duration.
     * @since 2.1
     * @deprecated Use {@link #setConnectTimeout(FileSystemOptions, Duration)}.
     */
    @Deprecated
    public void setConnectTimeout(final FileSystemOptions options, final Integer duration) {
        setConnectTimeout(options, Duration.ofMillis(duration));
    }

    /**
     * See {@link org.apache.commons.net.ftp.FTP#setControlEncoding} for details and examples.
     *
     * @param options The FileSystemOptions.
     * @param encoding the encoding to use
     * @since 2.0
     */
    public void setControlEncoding(final FileSystemOptions options, final String encoding) {
        setParam(options, ENCODING, encoding);
    }

    /**
     * Sets the control keep alive reply timeout for the FTP client.
     *
     * @param options The FileSystem options.
     * @param duration timeout duration.
     * @since 2.8.0
     */
    public void setControlKeepAliveReplyTimeout(final FileSystemOptions options, final Duration duration) {
        setParam(options, CONTROL_KEEP_ALIVE_REPLY_TIMEOUT, duration);
    }

    /**
     * Sets the control keep alive timeout for the FTP client.
     *

     * Set the {@code controlKeepAliveTimeout} to ensure the socket be alive after download huge file.
     *

     *
     * @param options The FileSystem options.
     * @param duration The timeout duration.
     * @since 2.8.0
     */
    public void setControlKeepAliveTimeout(final FileSystemOptions options, final Duration duration) {
        setParam(options, CONTROL_KEEP_ALIVE_TIMEOUT, duration);
    }

    /**
     * Set the data timeout for the FTP client.
     *

     * If you set the {@code dataTimeout} to {@code null}, no dataTimeout will be set on the FTP client.
     *

     *
     * @param options The FileSystemOptions.
     * @param duration The timeout duration.
     * @since 2.8.0
     */
    public void setDataTimeout(final FileSystemOptions options, final Duration duration) {
        setParam(options, DATA_TIMEOUT, duration);
    }

    /**
     * Set the data timeout for the FTP client.
     *

     * If you set the {@code dataTimeout} to {@code null}, no dataTimeout will be set on the FTP client.
     *

     *
     * @param options The FileSystemOptions.
     * @param duration The timeout value.
     * @deprecated Use {@link #setDataTimeout(FileSystemOptions, Duration)}.
     */
    @Deprecated
    public void setDataTimeout(final FileSystemOptions options, final Integer duration) {
        setDataTimeout(options, Duration.ofMillis(duration));
    }

    /**
     * Set the default date format used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig} for
     * details and examples.
     *
     * @param options The FileSystemOptions.
     * @param defaultDateFormat The default date format.
     */
    public void setDefaultDateFormat(final FileSystemOptions options, final String defaultDateFormat) {
        setParam(options, DEFAULT_DATE_FORMAT, defaultDateFormat);
    }

    /**
     * Set the FQCN of your FileEntryParser used to parse the directory listing from your server.
     *

     * If you do not use the default commons-net FTPFileEntryParserFactory e.g. by using {@link #setEntryParserFactory}
     * this is the "key" parameter passed as argument into your custom factory.
     *

     *
     * @param options The FileSystemOptions.
     * @param key The key.
     */
    public void setEntryParser(final FileSystemOptions options, final String key) {
        setParam(options, FACTORY_KEY, key);
    }

    /**
     * FTPFileEntryParserFactory which will be used for ftp-entry parsing.
     *
     * @param options The FileSystemOptions.
     * @param factory instance of your factory
     */
    public void setEntryParserFactory(final FileSystemOptions options, final FTPFileEntryParserFactory factory) {
        setParam(options, FTPFileEntryParserFactory.class.getName(), factory);
    }

    /**
     * Sets the file type parameter.
     *
     * @param options The FileSystemOptions.
     * @param ftpFileType A FtpFileType
     * @since 2.1
     */
    public void setFileType(final FileSystemOptions options, final FtpFileType ftpFileType) {
        setParam(options, FILE_TYPE, ftpFileType);
    }

    /**
     * Sets the option to use FTP MDTM for {@link FileContent#getLastModifiedTime()}.
     *
     * @param options The FileSystemOptions.
     * @param mdtm true if MDTM should be used.
     * @since 2.8.0
     */
    public void setMdtmLastModifiedTime(final FileSystemOptions options, final boolean mdtm) {
        setParam(options, MDTM_LAST_MODIFED_TIME, toBooleanObject(mdtm));
    }

    /**
     * Enter into passive mode.
     *
     * @param options The FileSystemOptions.
     * @param passiveMode true if passive mode should be used.
     */
    public void setPassiveMode(final FileSystemOptions options, final boolean passiveMode) {
        setParam(options, PASSIVE_MODE, toBooleanObject(passiveMode));
    }

    /**
     * Sets the active port range.
     *
     * @param options   The FileSystemOptions.
     * @param portRange the Range of active ports
     * @since 2.10.0
     */
    public void setActivePortRange(final FileSystemOptions options, final Range<Integer> portRange) {
        setParam(options, ACTIVE_PORT_RANGE, portRange);
    }

    /**
     * Sets the Proxy.
     *

     * You might need to make sure that {@link #setPassiveMode(FileSystemOptions, boolean) passive mode} is activated.
     *

     *
     * @param options the FileSystem options.
     * @param proxy the Proxy
     * @since 2.1
     */
    public void setProxy(final FileSystemOptions options, final Proxy proxy) {
        setParam(options, PROXY, proxy);
    }

    /**
     * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
     *
     * @param options The FileSystemOptions.
     * @param recentDateFormat The recent date format.
     */
    public void setRecentDateFormat(final FileSystemOptions options, final String recentDateFormat) {
        setParam(options, RECENT_DATE_FORMAT, recentDateFormat);
    }

    /**
     * Sets whether to use remote verification.
     *
     * @param options The FileSystemOptions.
     * @param remoteVerification True if verification should be done.
     */
    public void setRemoteVerification(final FileSystemOptions options, final boolean remoteVerification) {
        setParam(options, REMOTE_VERIFICATION, remoteVerification);
    }

    /**
     * Set the language code used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and
     * examples.
     *
     * @param options The FileSystemOptions.
     * @param serverLanguageCode The servers language code.
     */
    public void setServerLanguageCode(final FileSystemOptions options, final String serverLanguageCode) {
        setParam(options, SERVER_LANGUAGE_CODE, serverLanguageCode);
    }

    /**
     * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
     *
     * @param options The FileSystemOptions.
     * @param serverTimeZoneId The server timezone id.
     */
    public void setServerTimeZoneId(final FileSystemOptions options, final String serverTimeZoneId) {
        setParam(options, SERVER_TIME_ZONE_ID, serverTimeZoneId);
    }

    /**
     * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
     *
     * @param options The FileSystemOptions.
     * @param shortMonthNames an array of short month name Strings.
     */
    public void setShortMonthNames(final FileSystemOptions options, final String[] shortMonthNames) {
        String[] clone = null;
        if (shortMonthNames != null) {
            clone = new String[shortMonthNames.length];
            System.arraycopy(shortMonthNames, 0, clone, 0, shortMonthNames.length);
        }

        setParam(options, SHORT_MONTH_NAMES, clone);
    }

    /**
     * Sets the socket timeout for the FTP client.
     *

     * If you set the {@code soTimeout} to {@code null}, no socket timeout will be set on the FTP client.
     *

     *
     * @param options The FileSystem options.
     * @param timeout The timeout value in milliseconds.
     * @since 2.8.0
     */
    public void setSoTimeout(final FileSystemOptions options, final Duration timeout) {
        setParam(options, SO_TIMEOUT, timeout);
    }

    /**
     * Sets the socket timeout for the FTP client.
     *

     * If you set the {@code soTimeout} to {@code null}, no socket timeout will be set on the FTP client.
     *

     *
     * @param options The FileSystem options.
     * @param timeout The timeout value in milliseconds.
     * @since 2.0
     * @deprecated Use {@link #setSoTimeout(FileSystemOptions, Duration)}.
     */
    @Deprecated
    public void setSoTimeout(final FileSystemOptions options, final Integer timeout) {
        setSoTimeout(options, Duration.ofMillis(timeout));
    }

    /**
     * Sets the list of reply codes that are considered as OK when prematurely closing a stream.
     *

     * If you set the {@code replyCodes} to an empty list, all reply codes besides 200 will be
     * considered as an error.
     *

     *
     * @param options The FileSystem options.
     * @param replyCodes The reply codes.
     * @since 2.4
     */
    public void setTransferAbortedOkReplyCodes(final FileSystemOptions options, final List<Integer> replyCodes) {
        setParam(options, TRANSFER_ABORTED_OK_REPLY_CODES, replyCodes);
    }

    /**
     * Use user directory as root (do not change to fs root).
     *
     * @param options The FileSystemOptions.
     * @param userDirIsRoot true if the user directory should be treated as the root.
     */
    public void setUserDirIsRoot(final FileSystemOptions options, final boolean userDirIsRoot) {
        setParam(options, USER_DIR_IS_ROOT, toBooleanObject(userDirIsRoot));
    }
}


text:
import os
import os.path

def get_config_path(filename):
	if os.path.exists(filename):
		return filename
	import sys
	local_path = os.path.join(sys.path[0], filename)
	if os.path.exists(local_path):
		return local_path
	user_home = os.getenv('USERPROFILE') or os.getenv('HOME')
	lixian_home = os.getenv('LIXIAN_HOME') or user_home
	return os.path.join(lixian_home, filename)

LIXIAN_DEFAULT_CONFIG = get_config_path('.xunlei.lixian.config')
LIXIAN_DEFAULT_COOKIES = get_config_path('.xunlei.lixian.cookies')

def load_config(path):
	values = {}
	if os.path.exists(path):
		with open(path) as x:
			for line in x.readlines():
				line = line.strip()
				if line:
					if line.startswith('--'):
						line = line.lstrip('-')
						if line.startswith('no-'):
							values[line[3:]] = False
						elif '=' in line:
							k, v = line.split('=', 1)
							values[k] = v
						else:
							values[line] = True
					else:
						raise NotImplementedError(line)
	return values

def dump_config(path, values):
	with open(path, 'w') as x:
		for k in values:
			v = values[k]
			if v is True:
				x.write('--%s\n'%k)
			elif v is False:
				x.write('--no-%s\n'%k)
			else:
				x.write('--%s=%s\n'%(k, v))

class Config:
	def __init__(self, path=LIXIAN_DEFAULT_CONFIG):
		self.path = path
		self.values = load_config(path)
	def put(self, k, v=True):
		self.values[k] = v
		dump_config(self.path, self.values)
	def get(self, k, v=None):
		return self.values.get(k, v)
	def delete(self, k):
		if k in self.values:
			del self.values[k]
			dump_config(self.path, self.values)
	def source(self):
		if os.path.exists(self.path):
			with open(self.path) as x:
				return x.read()
	def __str__(self):
		return '<Config{%s}>' % self.values

global_config = Config()

def put_config(k, v=True):
	if k.startswith('no-') and v is True:
		k = k[3:]
		v = False
	global_config.put(k, v)

def get_config(k, v=None):
	return global_config.get(k, v)

def delete_config(k):
	return global_config.delete(k)

def source_config():
	return global_config.source()


text:
using System.Windows;
using System.Windows.Media;

namespace HelixToolkit.Wpf.SharpDX.Elements2D
{
    public class Button2D : Clickable2D
    {
        static Button2D()
        {
            DefaultStyleKeyProperty.OverrideMetadata(
                typeof(Button2D), new FrameworkPropertyMetadata(typeof(Button2D)));
        }
    }
}


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInspection.ex;

import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
import com.intellij.codeInspection.InspectionEP;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.concurrency.ConcurrentCollectionFactory;
import com.intellij.configurationStore.SchemeDataHolder;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.options.SchemeState;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectType;
import com.intellij.openapi.project.ProjectTypeService;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.Strings;
import com.intellij.profile.codeInspection.BaseInspectionProfileManager;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager;
import com.intellij.project.ProjectKt;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.scope.packageSet.NamedScope;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.NotNullList;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.util.xmlb.annotations.Tag;
import com.intellij.util.xmlb.annotations.Transient;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.util.*;

public class InspectionProfileImpl extends NewInspectionProfile {
  @NonNls static final String INSPECTION_TOOL_TAG = "inspection_tool";
  @NonNls static final String CLASS_TAG = "class";
  protected static final Logger LOG = Logger.getInstance(InspectionProfileImpl.class);
  @NonNls private static final String VALID_VERSION = "1.0";
  @NonNls private static final String VERSION_TAG = "version";
  @NonNls private static final String USED_LEVELS = "used_levels";
  @TestOnly
  public static boolean INIT_INSPECTIONS;
  protected final @NotNull InspectionToolsSupplier myToolSupplier;
  protected final Map<String, Element> myUninitializedSettings = new TreeMap<>(); // accessed in EDT
   //addTool is possible from any thread at any moment
  protected Map<String, ToolsImpl> myTools = ConcurrentCollectionFactory.createConcurrentMap();
  protected volatile Set<String> myChangedToolNames;
  @Attribute("is_locked")
  protected boolean myLockedProfile;
  protected final InspectionProfileImpl myBaseProfile;
  private volatile String myToolShortName;
  private List<String> myScopesOrder = new ArrayList<>();
  private @NlsContexts.DetailedDescription String myDescription;
  private Disposable myDisposable;

  private SchemeDataHolder<? super InspectionProfileImpl> myDataHolder;

  public InspectionProfileImpl(@NotNull String profileName,
                               @NotNull InspectionToolsSupplier toolSupplier,
                               @NotNull BaseInspectionProfileManager profileManager) {
    this(profileName, toolSupplier, profileManager, InspectionProfileKt.getBASE_PROFILE(), null);
  }

  public InspectionProfileImpl(@NotNull String profileName) {
    this(profileName, InspectionToolRegistrar.getInstance(), (BaseInspectionProfileManager)InspectionProfileManager.getInstance(), null, null);
  }

  public InspectionProfileImpl(@NotNull String profileName,
                               @NotNull InspectionToolsSupplier toolSupplier,
                               @Nullable InspectionProfileImpl baseProfile) {
    this(profileName, toolSupplier, (BaseInspectionProfileManager)InspectionProfileManager.getInstance(), baseProfile, null);
  }

  protected InspectionProfileImpl(@NotNull String profileName,
                                  @NotNull InspectionToolsSupplier toolSupplier,
                                  @NotNull BaseInspectionProfileManager profileManager,
                                  @Nullable InspectionProfileImpl baseProfile,
                                  @Nullable SchemeDataHolder<? super InspectionProfileImpl> dataHolder) {
    super(profileName, profileManager);

    myToolSupplier = toolSupplier;
    myBaseProfile = baseProfile;
    myDataHolder = dataHolder;
    if (dataHolder != null) {
      schemeState = SchemeState.UNCHANGED;
    }
  }

  public InspectionProfileImpl(@NotNull String profileName,
                               @NotNull InspectionToolsSupplier toolSupplier,
                               @NotNull BaseInspectionProfileManager profileManager,
                               @Nullable SchemeDataHolder<? super InspectionProfileImpl> dataHolder) {
    this(profileName, toolSupplier, profileManager, InspectionProfileKt.getBASE_PROFILE(), dataHolder);
  }

  private static boolean toolSettingsAreEqual(@NotNull String toolName, @NotNull InspectionProfileImpl profile1, @NotNull InspectionProfileImpl profile2) {
    Tools toolList1 = profile1.myTools.get(toolName);
    Tools toolList2 = profile2.myTools.get(toolName);
    return Comparing.equal(toolList1, toolList2);
  }

  public static @NotNull InspectionToolWrapper<?, ?> copyToolSettings(@NotNull InspectionToolWrapper<?,?> toolWrapper) {
    InspectionToolWrapper<?, ?> inspectionTool = toolWrapper.createCopy();
    if (toolWrapper.isInitialized()) {
      Element config = new Element("config");
      ScopeToolState.tryWriteSettings(toolWrapper.getTool(), config);
      ScopeToolState.tryReadSettings(inspectionTool.getTool(), config);
    }
    return inspectionTool;
  }

  @Override
  public @NotNull HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey inspectionToolKey, PsiElement element) {
    Project project = element == null ? null : element.getProject();
    ToolsImpl tools = getToolsOrNull(inspectionToolKey.toString(), project);
    HighlightDisplayLevel level = tools != null ? tools.getLevel(element) : HighlightDisplayLevel.WARNING;
    if (!getProfileManager().getSeverityRegistrar().isSeverityValid(level.getSeverity().getName())) {
      level = HighlightDisplayLevel.WARNING;
      setErrorLevel(inspectionToolKey, level, project);
    }
    return level;
  }

  @Override
  public void readExternal(@NotNull Element element) {
    mySerializer.readExternal(this, element);

    Element highlightElement = element.getChild(USED_LEVELS);
    if (highlightElement != null) {
      // from old profiles
      getProfileManager().getSeverityRegistrar().readExternal(highlightElement);
    }

    String version = element.getAttributeValue(VERSION_TAG);
    if (!VALID_VERSION.equals(version)) {
      List<InspectionToolWrapper<?, ?>> tools = getInspectionTools(null);
      for (Element toolElement : element.getChildren("inspection_tool")) {
        String toolClassName = toolElement.getAttributeValue(CLASS_TAG);
        String shortName = convertToShortName(toolClassName, tools);
        if (shortName == null) {
          continue;
        }
        toolElement.setAttribute(CLASS_TAG, shortName);
        myUninitializedSettings.put(shortName, JDOMUtil.internElement(toolElement));
      }
    }
    else {
      for (Element toolElement : element.getChildren(INSPECTION_TOOL_TAG)) {
        myUninitializedSettings.put(toolElement.getAttributeValue(CLASS_TAG), JDOMUtil.internElement(toolElement));
      }
    }
  }

  private static @Nullable String convertToShortName(@Nullable String displayName, @NotNull List<? extends InspectionToolWrapper<?, ?>> tools) {
    if (displayName == null) return null;
    for (InspectionToolWrapper<?, ?> tool : tools) {
      if (displayName.equals(tool.getDisplayName())) {
        return tool.getShortName();
      }
    }
    return null;
  }

  public @NotNull Set<HighlightSeverity> getUsedSeverities() {
    LOG.assertTrue(wasInitialized());
    Set<HighlightSeverity> result = new HashSet<>();
    for (Tools tools : myTools.values()) {
      for (ScopeToolState state : tools.getTools()) {
        result.add(state.getLevel().getSeverity());
      }
    }
    return result;
  }

  @Override
  public @NotNull Element writeScheme() {
    if (myDataHolder != null) {
      return myDataHolder.read();
    }

    Element element = new Element(PROFILE);
    writeExternal(element);
    if (isProjectLevel()) {
      element.setAttribute("version", "1.0");
    }
    if (isProjectLevel() && ProjectKt.isDirectoryBased(((ProjectInspectionProfileManager)getProfileManager()).getProject())) {
      return new Element("component").setAttribute("name", "InspectionProjectProfileManager").addContent(element);
    }

    schemeState = SchemeState.UNCHANGED;
    return element;
  }

  public void writeExternal(@NotNull Element element) {
    // must be first - compatibility
    writeVersion(element);

    mySerializer.writeExternal(this, element);

    synchronized (lock) {
      if (!wasInitialized()) {
        for (Element el : myUninitializedSettings.values()) {
          element.addContent(el.clone());
        }
        return;
      }
    }

    Set<String> changedToolNames = getChangedToolNames();
    if (changedToolNames == null) {
      return;
    }

    List<String> allToolNames = new ArrayList<>(myTools.keySet());
    allToolNames.addAll(myUninitializedSettings.keySet());
    allToolNames.sort(null);
    for (String toolName : allToolNames) {
      Element toolElement = myUninitializedSettings.get(toolName);
      if (toolElement != null) {
        element.addContent(toolElement.clone());
        continue;
      }

      if (!myLockedProfile && !changedToolNames.contains(toolName)) {
        markSettingsMerged(toolName, element);
        continue;
      }

      ToolsImpl toolList = myTools.get(toolName);
      LOG.assertTrue(toolList != null);
      Element inspectionElement = new Element(INSPECTION_TOOL_TAG);
      inspectionElement.setAttribute(CLASS_TAG, toolName);
      try {
        toolList.writeExternal(inspectionElement);
      }
      catch (WriteExternalException e) {
        LOG.error(e);
        continue;
      }

      if (!areSettingsMerged(toolName, inspectionElement)) {
        element.addContent(inspectionElement);
      }
    }
    getPathMacroManager().collapsePaths(element);
  }

  protected static void writeVersion(@NotNull Element element) {
    element.setAttribute(VERSION_TAG, VALID_VERSION);
  }

  private void markSettingsMerged(@NotNull String toolName, @NotNull Element element) {
    //add marker if already merged but result is now default (-> empty node)
    String mergedName = InspectionElementsMergerBase.getMergedMarkerName(toolName);
    if (!myUninitializedSettings.containsKey(mergedName)) {
      InspectionElementsMergerBase merger = getMerger(toolName);
      if (merger != null && merger.markSettingsMerged(myUninitializedSettings)) {
        element.addContent(new Element(INSPECTION_TOOL_TAG).setAttribute(CLASS_TAG, mergedName));
      }
    }
  }

  private boolean areSettingsMerged(@NotNull String toolName, @NotNull Element inspectionElement) {
    //skip merged settings as they could be restored from already provided data
    InspectionElementsMergerBase merger = getMerger(toolName);
    return merger != null && merger.areSettingsMerged(myUninitializedSettings, inspectionElement);
  }

  public void collectDependentInspections(@NotNull InspectionToolWrapper<?,?> toolWrapper,
                                          @NotNull Set<? super InspectionToolWrapper<?, ?>> dependentEntries,
                                          Project project) {
    String mainToolId = toolWrapper.getMainToolId();

    if (mainToolId != null) {
      InspectionToolWrapper<?,?> dependentEntryWrapper = getInspectionTool(mainToolId, project);
      if (dependentEntryWrapper == null) {
        LOG.error("Can't find main tool: '" + mainToolId+"' which was specified in "+toolWrapper);
        return;
      }
      if (!dependentEntries.add(dependentEntryWrapper)) {
        collectDependentInspections(dependentEntryWrapper, dependentEntries, project);
      }
    }
  }

  @Override
  public @Nullable InspectionToolWrapper<?, ?> getInspectionTool(@NotNull String shortName, @Nullable PsiElement element) {
    Tools toolList = getToolsOrNull(shortName, element == null ? null : element.getProject());
    return toolList == null ? null : toolList.getInspectionTool(element);
  }

  @Override
  public @Nullable InspectionProfileEntry getUnwrappedTool(@NotNull String shortName, @NotNull PsiElement element) {
    InspectionToolWrapper<?, ?> tool = getInspectionTool(shortName, element);
    return tool == null ? null : tool.getTool();
  }

  @Override
  public <T extends InspectionProfileEntry> T getUnwrappedTool(@NotNull Key<T> shortNameKey, @NotNull PsiElement element) {
    //noinspection unchecked
    return (T) getUnwrappedTool(shortNameKey.toString(), element);
  }

  public void modifyProfile(@NotNull Consumer<? super InspectionProfileModifiableModel> modelConsumer) {
    InspectionProfileModifiableModelKt.edit(this, it -> {
      modelConsumer.consume(it);
      return null;
    });
  }

  @Override
  public <T extends InspectionProfileEntry> void modifyToolSettings(@NotNull Key<T> shortNameKey,
                                                                    @NotNull PsiElement psiElement,
                                                                    @NotNull Consumer<? super T> toolConsumer) {
    modifyProfile(model -> {
      InspectionProfileEntry tool = model.getUnwrappedTool(shortNameKey.toString(), psiElement);
      //noinspection unchecked
      toolConsumer.consume((T) tool);
    });
  }

  /**
   * Warning: Usage of this method is discouraged as if separate tool options are defined for different scopes, it just returns
   * the options for the first scope which may lead to unexpected results. Consider using {@link #getInspectionTool(String, PsiElement)} instead.
   *
   * @param shortName an inspection short name
   * @param project   a project
   * @return an InspectionToolWrapper associated with this tool.
   */
  @Override
  public @Nullable InspectionToolWrapper getInspectionTool(@NotNull String shortName, Project project) {
    ToolsImpl tools = getToolsOrNull(shortName, project);
    return tools == null ? null : tools.getTool();
  }

  public InspectionToolWrapper<?,?> getToolById(@NotNull String id, @NotNull PsiElement element) {
    initInspectionTools();
    for (Tools toolList : myTools.values()) {
      InspectionToolWrapper<?,?> tool = toolList.getInspectionTool(element);
      if (id.equals(tool.getID())) return tool;
    }
    return null;
  }

  public @NotNull List<InspectionToolWrapper<?, ?>> findToolsById(@NotNull String id, @NotNull PsiElement element) {
    initInspectionTools();
    List<InspectionToolWrapper<?, ?>> result = null;
    for (Tools toolList : myTools.values()) {
      InspectionToolWrapper<?,?> tool = toolList.getInspectionTool(element);
      if (id.equals(tool.getID())) {
        if (result == null) {
          result = new ArrayList<>();
        }
        result.add(tool);
      }
    }
    return ContainerUtil.notNullize(result);
  }

  @Override
  public @Nullable String getSingleTool() {
    return myToolShortName;
  }

  public void setSingleTool(@NotNull String toolShortName) {
    myToolShortName = toolShortName;
  }

  @NonNls
  @Override
  public @NotNull String getDisplayName() {
    return getName();
  }

  public void scopesChanged() {
    if (!wasInitialized()) {
      return;
    }

    for (ToolsImpl tools : myTools.values()) {
      tools.scopesChanged();
    }

    getProfileManager().fireProfileChanged(this);
  }

  @Transient
  public boolean isProfileLocked() {
    return myLockedProfile;
  }

  public void lockProfile(boolean isLocked) {
    myLockedProfile = isLocked;
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  @Override
  public @NotNull List<InspectionToolWrapper<?, ?>> getInspectionTools(@Nullable PsiElement element) {
    initInspectionTools();
    List<InspectionToolWrapper<?, ?>> result = new ArrayList<>(myTools.size());
    for (Tools toolList : myTools.values()) {
      result.add(toolList.getInspectionTool(element));
    }
    return result;
  }

  @Override
  public @NotNull List<Tools> getAllEnabledInspectionTools(Project project) {
    initInspectionTools();

    List<Tools> result = new ArrayList<>();
    Collection<ProjectType> projectTypes = ProjectTypeService.getProjectTypes(project);

    for (ToolsImpl toolList : myTools.values()) {
      if (toolList.isEnabled()) {
        InspectionToolWrapper<?, ?> toolWrapper = toolList.getTool();
        if (!toolWrapper.isApplicable(projectTypes)) {
          continue;
        }

        result.add(toolList);
      }
    }
    return result;
  }

  public void disableToolByDefault(@NotNull Collection<String> toolShortNames, @Nullable Project project) {
    for (String toolId : toolShortNames) {
      getTools(toolId, project).setDefaultEnabled(false);
    }
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  public @NotNull ScopeToolState getToolDefaultState(@NotNull String toolShortName, @Nullable Project project) {
    return getTools(toolShortName, project).getDefaultState();
  }

  public void enableToolsByDefault(@NotNull List<String> toolShortNames, Project project) {
    for (String shortName : toolShortNames) {
      getTools(shortName, project).setDefaultEnabled(true);
    }
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  protected @NotNull List<InspectionToolWrapper<?, ?>> createTools(@Nullable Project project) {
    return myToolSupplier.createTools();
  }

  @Override
  protected void initialize(@Nullable Project project) {
    SchemeDataHolder<? super InspectionProfileImpl> dataHolder = myDataHolder;
    if (dataHolder != null) {
      myDataHolder = null;
      Element element = dataHolder.read();
      if (element.getName().equals("component")) {
        element = element.getChild("profile");
      }
      assert element != null;
      readExternal(element);
    }

    if (myBaseProfile != null) {
      myBaseProfile.initInspectionTools();
    }

    List<InspectionToolWrapper<?, ?>> tools;
    try {
      tools = createTools(project);
    }
    catch (ProcessCanceledException ignored) {
      return;
    }

    Map<String, List<String>> dependencies = new HashMap<>();
    for (InspectionToolWrapper<?, ?> toolWrapper : tools) {
      addTool(project, toolWrapper, dependencies);
      if (!(toolWrapper instanceof LocalInspectionToolWrapper &&
            ((LocalInspectionToolWrapper)toolWrapper).isDynamicGroup() &&
            //some settings were read for the tool, so it must be initialized,
            //otherwise no dynamic tools are expected
            toolWrapper.isInitialized())) {
        continue;
      }

      ToolsImpl parent = myTools.get(toolWrapper.getShortName());
      if (!parent.isEnabled()) {
        continue;
      }

      List<LocalInspectionToolWrapper> children = ((DynamicGroupTool)toolWrapper.getTool()).getChildren();
      if (tools.stream().anyMatch(i -> children.stream().anyMatch(l -> i.getShortName().equals(l.getShortName())))) {
        continue;
      }

      boolean isLocked = myLockedProfile;
      myLockedProfile = false;
      for (LocalInspectionToolWrapper wrapper : children) {
        addTool(project, wrapper, dependencies);
        String shortName = wrapper.getShortName();
        if (InspectionElementsMerger.getMerger(shortName) != null) {
          continue;
        }

        InspectionElementsMerger.addMerger(shortName, new MyInspectionElementsMerger(shortName, wrapper));
      }
      myLockedProfile = isLocked;
    }

    // initialize is invoked in synchronized block, so we can publish the new value of myDisposable here
    myDisposable = project != null ? Disposer.newDisposable(project, "[" + getClass().getSimpleName() + "] " + myName) : null;
    myToolSupplier.addListener(new InspectionToolsSupplier.Listener() {
      @Override
      public void toolAdded(@NotNull InspectionToolWrapper<?,?> inspectionTool) {
        addTool(project, inspectionTool, null);
        getProfileManager().fireProfileChanged(InspectionProfileImpl.this);
      }

      @Override
      public void toolRemoved(@NotNull InspectionToolWrapper<?,?> inspectionTool) {
        removeTool(inspectionTool);
        getProfileManager().fireProfileChanged(InspectionProfileImpl.this);
      }
    }, myDisposable);

    copyToolsConfigurations(project);

    initialized = true;
    if (dataHolder != null) {
      // should be only after set myInitialized
      dataHolder.updateDigest(this);
    }
  }

  protected void copyToolsConfigurations(@Nullable Project project) {
  }

  public final void addTool(@Nullable Project project, @NotNull InspectionToolWrapper<?, ?> toolWrapper, @Nullable Map<? super String, List<String>> dependencies) {
    String shortName = toolWrapper.getShortName();
    HighlightDisplayKey key = HighlightDisplayKey.find(shortName);
    if (key == null) {
      InspectionEP extension = toolWrapper.getExtension();
      Computable<String> computable = extension == null || extension.displayName == null && extension.key == null
                                      ? new Computable.PredefinedValueComputable<>(toolWrapper.getDisplayName())
                                      : extension::getDisplayName;
      if (toolWrapper instanceof LocalInspectionToolWrapper) {
        key = HighlightDisplayKey.register(shortName, computable, toolWrapper.getID(),
                                           ((LocalInspectionToolWrapper)toolWrapper).getAlternativeID());
      }
      else {
        key = HighlightDisplayKey.register(shortName, computable, shortName);
      }
    }

    if (key == null) {
      LOG.error(shortName + " ; number of initialized tools: " + myTools.size());
      return;
    }

    HighlightDisplayLevel baseLevel = myBaseProfile != null && myBaseProfile.getToolsOrNull(shortName, project) != null
                                   ? myBaseProfile.getErrorLevel(key, project)
                                   : HighlightDisplayLevel.DO_NOT_SHOW;
    HighlightDisplayLevel defaultLevel = toolWrapper.getDefaultLevel();
    HighlightDisplayLevel level = baseLevel.getSeverity().compareTo(defaultLevel.getSeverity()) > 0 ? baseLevel : defaultLevel;
    boolean enabled = myBaseProfile != null && myBaseProfile.getToolsOrNull(shortName, project) != null ? myBaseProfile.isToolEnabled(key) : toolWrapper.isEnabledByDefault();
    ToolsImpl toolsList = new ToolsImpl(toolWrapper, level, !myLockedProfile && enabled, enabled);
    Element element = myUninitializedSettings.remove(shortName);
    try {
      if (element != null) {
        element = element.clone();
        getPathMacroManager().expandPaths(element);
        toolsList.readExternal(element, getProfileManager(), dependencies);
      }
      else if (!myUninitializedSettings.containsKey(InspectionElementsMergerBase.getMergedMarkerName(shortName))) {
        InspectionElementsMergerBase merger = getMerger(shortName);
        Element merged = merger == null ? null : merger.merge(myUninitializedSettings);
        if (merged != null) {
          getPathMacroManager().expandPaths(merged);
          toolsList.readExternal(merged, getProfileManager(), dependencies);
        }
        else if (isProfileLocked()) {
          // https://youtrack.jetbrains.com/issue/IDEA-158936
          toolsList.setEnabled(false);
          if (toolsList.getNonDefaultTools() == null) {
            toolsList.getDefaultState().setEnabled(false);
          }
        }
      }
    }
    catch (InvalidDataException e) {
      LOG.error("Can't read settings for " + toolWrapper, e);
    }
    myTools.put(shortName, toolsList);
  }

  public void removeTool(@NotNull InspectionToolWrapper<?, ?> inspectionTool) {
    String shortName = inspectionTool.getShortName();
    myTools.remove(shortName);
  }

  private static @Nullable InspectionElementsMergerBase getMerger(@NotNull String shortName) {
    InspectionElementsMerger merger = InspectionElementsMerger.getMerger(shortName);
    if (merger instanceof InspectionElementsMergerBase) {
      return (InspectionElementsMergerBase)merger;
    }
    return merger == null ? null : new InspectionElementsMergerBase() {
      @Override
      public @NotNull String getMergedToolName() {
        return merger.getMergedToolName();
      }

      @Override
      public String @NotNull [] getSourceToolNames() {
        return merger.getSourceToolNames();
      }
    };
  }

  public List<String> getScopesOrder() {
    return myScopesOrder;
  }

  public void setScopesOrder(List<String> scopesOrder) {
    myScopesOrder = scopesOrder;
    schemeState = SchemeState.POSSIBLY_CHANGED;

    for (ToolsImpl tools : myTools.values()) {
      tools.changeToolsOrder(myScopesOrder);
    }
  }

  private @NotNull HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey key, @Nullable Project project) {
    return getTools(key.toString(), project).getLevel();
  }

  @TestOnly
  public @NotNull InspectionProfileModifiableModel getModifiableModel() {
    return new InspectionProfileModifiableModel(this);
  }

  public void cleanup(@Nullable Project project) {
    if (!wasInitialized()) {
      return;
    }

    if (myDisposable != null) {
      Disposer.dispose(myDisposable);
    }

    if (project != null) {
      for (ToolsImpl toolList : myTools.values()) {
        if (toolList.isEnabled()) {
          toolList.cleanupTools(project);
        }
      }
    }
  }

  public void enableTool(@NotNull String toolShortName, @Nullable Project project) {
    setToolEnabled(toolShortName, true, project);
  }

  public void enableTool(@NotNull String toolShortName, @NotNull NamedScope namedScope, @NotNull Project project) {
    getTools(toolShortName, project).enableTool(namedScope, project);
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  public void enableTools(@NotNull List<String> toolShortNames, @NotNull NamedScope namedScope, @NotNull Project project) {
    for (String toolShortName : toolShortNames) {
      enableTool(toolShortName, namedScope, project);
    }
  }

  public void disableTools(@NotNull List<String> toolShortNames, @NotNull NamedScope namedScope, @NotNull Project project) {
    for (String toolShortName : toolShortNames) {
      getTools(toolShortName, project).disableTool(namedScope, project);
    }
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  public void setErrorLevel(@NotNull HighlightDisplayKey key, @NotNull HighlightDisplayLevel level, Project project) {
    getTools(key.toString(), project).setLevel(level);
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  @Override
  public boolean isToolEnabled(@Nullable HighlightDisplayKey key, @Nullable PsiElement element) {
    if (key == null) {
      return false;
    }
    Tools toolState = getToolsOrNull(key.toString(), element == null ? null : element.getProject());
    return toolState != null && toolState.isEnabled(element);
  }

  @Override
  public @Nullable TextAttributesKey getEditorAttributes(@NotNull String shortName, @Nullable PsiElement element) {
    ToolsImpl tools = getToolsOrNull(shortName, element != null ? element.getProject() : null);
    return tools != null ? tools.getAttributesKey(element) : null;
  }

  public void setEditorAttributesKey(@NotNull String shortName, @Nullable String keyName, String scopeName, @Nullable Project project) {
    final ToolsImpl tools = getTools(shortName, project);
    final var level = tools.getLevel(scopeName, project);
    if (keyName == null) {
      keyName = SeverityRegistrar.getSeverityRegistrar(project).getHighlightInfoTypeBySeverity(level.getSeverity()).getAttributesKey().getExternalName();
    }
    String attributes = tools.getDefaultState().getTool().getDefaultEditorAttributes();
    tools.setEditorAttributesKey(Objects.equals(attributes, keyName) ? null : keyName, scopeName);
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  @Override
  public boolean isExecutable(@Nullable Project project) {
    initInspectionTools();
    for (Tools tools : myTools.values()) {
      if (tools.isEnabled()) return true;
    }
    return false;
  }

  @Tag
  @NlsContexts.DetailedDescription
  public String getDescription() {
    return myDescription;
  }

  public void setDescription(@NlsContexts.DetailedDescription @Nullable String description) {
    myDescription = Strings.nullize(description);
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  public void resetToBase(@NotNull String toolId, NamedScope scope, @NotNull Project project) {
    ToolsImpl tools = myBaseProfile.getToolsOrNull(toolId, project);
    if (tools == null) return;
    InspectionToolWrapper<?, ?> baseDefaultWrapper = tools.getDefaultState().getTool();
    ScopeToolState state = myTools.get(toolId).getTools().stream().filter(s -> scope == s.getScope(project)).findFirst().orElseThrow(IllegalStateException::new);
    state.setTool(copyToolSettings(baseDefaultWrapper));
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  public void convert(@NotNull Element element, @NotNull Project project) {
    Element scopes = element.getChild("scopes");
    if (scopes == null) {
      return;
    }

    initInspectionTools();

    for (Element scopeElement : scopes.getChildren(SCOPE)) {
      String profile = scopeElement.getAttributeValue(PROFILE);
      InspectionProfileImpl inspectionProfile = profile == null ? null : getProfileManager().getProfile(profile);
      NamedScope scope = inspectionProfile == null ? null : getProfileManager().getScopesManager().getScope(scopeElement.getAttributeValue(NAME));
      if (scope == null) {
        continue;
      }

      for (InspectionToolWrapper<?, ?> toolWrapper : inspectionProfile.getInspectionTools(null)) {
        HighlightDisplayKey key = HighlightDisplayKey.find(toolWrapper.getShortName());
        try {
          InspectionToolWrapper<?, ?> toolWrapperCopy = copyToolSettings(toolWrapper);
          HighlightDisplayLevel errorLevel = inspectionProfile.getErrorLevel(key, null, project);
          getTools(toolWrapper.getShortName(), project)
            .addTool(scope, toolWrapperCopy, inspectionProfile.isToolEnabled(key), errorLevel);
        }
        catch (Exception e) {
          LOG.error(e);
        }
      }
    }
    reduceConvertedScopes();
  }

  private void reduceConvertedScopes() {
    for (ToolsImpl tools : myTools.values()) {
      ScopeToolState toolState = tools.getDefaultState();
      List<ScopeToolState> nonDefaultTools = tools.getNonDefaultTools();
      if (nonDefaultTools != null) {
        boolean equal = true;
        boolean isEnabled = toolState.isEnabled();
        for (ScopeToolState state : nonDefaultTools) {
          isEnabled |= state.isEnabled();
          if (!state.equalTo(toolState)) {
            equal = false;
          }
        }
        tools.setEnabled(isEnabled);
        if (equal) {
          tools.removeAllScopes();
        }
      }
    }
  }

  public @NotNull List<ScopeToolState> getAllTools() {
    initInspectionTools();

    List<ScopeToolState> result = new NotNullList<>();
    for (Tools tools : myTools.values()) {
      tools.collectTools(result);
    }
    return result;
  }

  public @NotNull List<ScopeToolState> getDefaultStates(@Nullable Project project) {
    initInspectionTools();
    List<ScopeToolState> result = new ArrayList<>();
    for (Tools tools : myTools.values()) {
      result.add(tools.getDefaultState());
    }
    return result;
  }

  public @NotNull List<ScopeToolState> getNonDefaultTools(@NotNull String shortName, Project project) {
    List<ScopeToolState> result = new ArrayList<>();
    List<ScopeToolState> nonDefaultTools = getTools(shortName, project).getNonDefaultTools();
    if (nonDefaultTools != null) {
      result.addAll(nonDefaultTools);
    }
    return result;
  }

  public boolean isToolEnabled(@NotNull HighlightDisplayKey key, NamedScope namedScope, Project project) {
    return getTools(key.toString(), project).isEnabled(namedScope,project);
  }

  public void removeScope(@NotNull String toolShortName, @NotNull String scopeName, Project project) {
    getTools(toolShortName, project).removeScope(scopeName);
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  public void removeScopes(@NotNull List<String> shortNames, @NotNull String scopeName, Project project) {
    for (String shortName : shortNames) {
      removeScope(shortName, scopeName, project);
    }
  }

  /**
   * @return null if it has no base profile
   */
  private @Nullable Set<String> getChangedToolNames() {
    if (myBaseProfile == null) {
      return null;
    }
    if (myChangedToolNames == null) {
      synchronized (lock) {
        if (myChangedToolNames == null) {
          initInspectionTools(null);
          Set<String> names = myTools.keySet();
          Set<String> map = new HashSet<>(names.size());
          for (String toolId : names) {
            if (!toolSettingsAreEqual(toolId, myBaseProfile, this)) {
              map.add(toolId);
            }
          }
          myChangedToolNames = map;
          return map;
        }
      }
    }
    return myChangedToolNames;
  }

  public void profileChanged() {
    myChangedToolNames = null;
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  @Transient
  public @NotNull HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey key, NamedScope scope, Project project) {
    ToolsImpl tools = getToolsOrNull(key.toString(), project);
    return tools != null ? tools.getLevel(scope, project) : HighlightDisplayLevel.WARNING;
  }

  @Transient
  public @Nullable TextAttributesKey getEditorAttributesKey(@NotNull HighlightDisplayKey key, NamedScope scope, Project project) {
    ToolsImpl tools = getToolsOrNull(key.toString(), project);
    return tools != null ? tools.getEditorAttributesKey(scope, project) : null;
  }

  public ScopeToolState addScope(@NotNull InspectionToolWrapper<?,?> toolWrapper,
                                 NamedScope scope,
                                 @NotNull HighlightDisplayLevel level,
                                 boolean enabled,
                                 Project project) {
    return getTools(toolWrapper.getShortName(), project).prependTool(scope, toolWrapper, enabled, level);
  }

  public void setErrorLevel(@NotNull HighlightDisplayKey key, @NotNull HighlightDisplayLevel level, String scopeName, Project project) {
    getTools(key.toString(), project).setLevel(level, scopeName, project);
    schemeState = SchemeState.POSSIBLY_CHANGED;
  }

  public void setErrorLevel(@NotNull List<? extends HighlightDisplayKey> keys, @NotNull HighlightDisplayLevel level, String scopeName, Project project) {
    for (HighlightDisplayKey key : keys) {
      setErrorLevel(key, level, scopeName, project);
    }
  }

  public void setEditorAttributesKey(@NotNull List<? extends HighlightDisplayKey> keys, @Nullable TextAttributesKey attributesKey, String scopeName, Project project) {
    for (HighlightDisplayKey key : keys) {
      setEditorAttributesKey(key.toString(), attributesKey == null ? null : attributesKey.getExternalName(), scopeName, project);
    }
  }

  @Override
  public @Nullable ToolsImpl getToolsOrNull(@NotNull String name, @Nullable Project project) {
    initInspectionTools();
    return myTools.get(name);
  }

  public Collection<ToolsImpl> getTools() {
    initInspectionTools();
    return myTools.values();
  }

  public void enableAllTools(Project project) {
    for (InspectionToolWrapper<?,?> entry : getInspectionTools(null)) {
      enableTool(entry.getShortName(), project);
    }
  }

  public void disableAllTools(Project project) {
    for (InspectionToolWrapper<?,?> entry : getInspectionTools(null)) {
      setToolEnabled(entry.getShortName(), false, project);
    }
  }

  public static void setToolEnabled(boolean newState,
                                    @NotNull InspectionProfileImpl profile,
                                    @NotNull String shortName,
                                    @NotNull Project project) {
    setToolEnabled(newState, profile, shortName, false, project);
  }

  public static void setToolEnabled(boolean newState,
                                    @NotNull InspectionProfileImpl profile,
                                    @NotNull String shortName,
                                    boolean fireEvents,
                                    @NotNull Project project) {
    profile.setToolEnabled(shortName, newState, project, fireEvents);
    for (ScopeToolState scopeToolState : profile.getTools(shortName, project).getTools()) {
      scopeToolState.setEnabled(newState);
    }
  }

  private static final class MyInspectionElementsMerger extends InspectionElementsMergerBase {

    private final String myShortName;
    private final LocalInspectionToolWrapper myWrapper;

    private MyInspectionElementsMerger(@NotNull String shortName, @NotNull LocalInspectionToolWrapper wrapper) {
      myShortName = shortName;
      myWrapper = wrapper;
    }

    @Override
    public @NotNull String getMergedToolName() {
      return myShortName;
    }

    @Override
    public String @NotNull [] getSourceToolNames() {
      return ArrayUtil.EMPTY_STRING_ARRAY;
    }

    @Override
    protected boolean areSettingsMerged(@NotNull Map<String, Element> settings, @NotNull Element element) {
      // returns true when settings are default, so defaults will not be saved in profile
      return Boolean.parseBoolean(element.getAttributeValue("enabled")) == myWrapper.isEnabledByDefault() &&
             myWrapper.getDefaultLevel().toString().equals(element.getAttributeValue("level")) &&
             Boolean.parseBoolean(element.getAttributeValue("enabled_by_default")) == myWrapper.isEnabledByDefault();
    }
  }
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Newsletter extends CI_Controller {

	public function __construct(){
		parent::__construct();
		$this->load->model('Member_model','member_model');
	}

	public function signup(){
		$this->load->view('newsletter/signup_view');
	}

	public function signupprocess(){
		$data = '';
		if(isset($_POST['Submit']))
		{
			$email=$_POST["email"];
			$fname=$_POST["fname"];
			$lname=$_POST["lname"];
			$postcode=$_POST["postcode"];
			$gender=$_POST['gender'];
			$check_user = $this->member_model->check_newsletter_login($email,$fname,$lname,$postcode,$gender);
			$data['msg'] = $check_user;
		}

		$this->load->view('newsletter/signup_view',$data);
	}

	public function success(){
		if(isset($_GET['email'])){
			$data['view_file_name'] = 'newsletter/confirm_view';
			$this->template->success_view('newsletter/confirm_view',$data);
		} else {
			echo "You cannot access this page directly";
		}
	}

	public function footer_newsletter_signup(){
		$email=$_POST["email"];
		$check_user = $this->member_model->check_newsletter_login($email);
		echo $check_user;
	}

}


text:
# Runs every time a package is uninstalled

param($installPath, $toolsPath, $package, $project)

# $installPath is the path to the folder where the package is installed.
# $toolsPath is the path to the tools directory in the folder where the package is installed.
# $package is a reference to the package object.
# $project is a reference to the project the package was installed to.

# Remove the scripts file(s)
$tasksFolder = $project.ProjectItems.Item(".Tasks");
if ($tasksFolder -ne $null) {
	Get-ChildItem $installPath\scripts\* | % {
			$tasksFolder.ProjectItems.Item($_.Name).Remove();
			if ($tasksFolder.ProjectItems.Count -eq 0) {
				$tasksFolder.Delete();
			}
	}
	$project.Save();
}


text:
Program* Program::CreateFromFile(const char *vertFilename, const char *fragFilename) {
	Shader *vs = Shader::CreateFromFile(GL_VERTEX_SHADER, vertFilename);
	if (!vs) return 0;
	Shader *fs = Shader::CreateFromFile(GL_FRAGMENT_SHADER, fragFilename);
	if (!fs) {
		delete vs;
		return 0;
	}

	GLuint program = glCreateProgram();
	if (!program) {
		delete vs;
		delete fs;
		return 0;
	}

	glAttachShader(program, vs->getShader());
	glAttachShader(program, fs->getShader());
	glLinkProgram(program);

	int result = GL_FALSE;
	glGetProgramiv(program, GL_LINK_STATUS, &result);
	if (GL_FALSE == result) {
		glDeleteProgram(program);
		delete vs;
		delete fs;
		return 0;
	}

	Program* ret = new Program(vs, fs, program);
	ret->reflect();
	return ret;
}

Program::~Program() {
	if (m_program) glDeleteProgram(m_program);
	m_program = 0;
	if (m_vs) delete m_vs;
	if (m_fs) delete m_fs;
}

// void Program::link() {
// 	if (!m_vs || !m_fs) return;

// 	if (!m_program) m_program = glCreateProgram();
// 	if (!m_program) return;
// 	glAttachShader(m_program, m_vs->getShader());
// 	glAttachShader(m_program, m_fs->getShader());
// 	glLinkProgram(m_program);
// }

void Program::reflect() {
	m_attributes.clear();
	m_uniforms.clear();
	m_uniformBlocks.clear();

	if (!getProgram()) return;

	char name[1024] = {0};
	int length = 0, size = 0;
	GLenum type;

	int nAttrib = 0;
	glGetProgramiv(m_program, GL_ACTIVE_ATTRIBUTES, &nAttrib);
	for (int i = 0; i < nAttrib; ++i) {
		glGetActiveAttrib(m_program, i, sizeof(name), &length, &size, &type, name);
		m_attributes[name] = i;
	}

	int nUniforms = 0;
	glGetProgramiv(m_program, GL_ACTIVE_UNIFORMS, &nUniforms);
	for (GLuint i = 0; i < nUniforms; ++i) {
		int idx = 0;
		glGetActiveUniform(m_program, i, sizeof(name), &length, &size, &type, name);
		glGetActiveUniformsiv(m_program, 1, &i, GL_UNIFORM_BLOCK_INDEX, &idx);
		if (idx < 0) { // uniforms out of an uniform block
			GLint loc = glGetUniformLocation(m_program, name);
			m_uniforms[name] = UniformDesc{ idx, loc, size, type };
		} else { // uniforms in an uniform block
			GLint offset = 0;
			glGetActiveUniformsiv(m_program, 1, &i, GL_UNIFORM_OFFSET, &offset);
			m_uniforms[name] = UniformDesc{ idx, offset, size, type };
		}
	}

	int nBlocks = 0;
	glGetProgramiv(m_program, GL_ACTIVE_UNIFORM_BLOCKS, &nBlocks);
	for (GLuint i = 0; i < nBlocks; ++i) {
		glGetActiveUniformBlockName(m_program, i, sizeof(name), &length, name);
		glGetActiveUniformBlockiv(m_program, i, GL_UNIFORM_BLOCK_DATA_SIZE, &size);
		m_uniformBlocks.push_back( std::make_pair(name, size) );
	}
}

GLuint Program::getProgram() const {
	int result = GL_FALSE;
	if (!m_program) return 0;
	glGetProgramiv(m_program, GL_LINK_STATUS, &result);
	if (GL_FALSE == result) return 0;
	return m_program;
}

GLint Program::getAttributeLocation(const std::string& name) const {
	if (!getProgram()) return -1;
	if (m_attributes.find(name) == m_attributes.cend()) return -1;
	return m_attributes.at(name);
}

const UniformDesc* Program::getUniform(const std::string& name) const {
	if (!getProgram()) return 0;
	if (m_uniforms.find(name) == m_uniforms.cend()) return 0;
	return &(m_uniforms.at(name));
}


text:
<?php include_once(APPPATH."views/fe/common/breadcrumb.tpl.php"); ?>

	<?php include_once(APPPATH.'views/fe/common/message.tpl.php'); ?>

Contact Us

Thank you for contact. You will get reply soon.


text:
"""
Tests that TSan correctly reports the filename and line number of a racy global C++ variable.
"""

import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbutil as lldbutil
import json

class TsanCPPGlobalLocationTestCase(TestBase):

    mydir = TestBase.compute_mydir(__file__)

    @expectedFailureAll(
        oslist=["linux"],
        bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)")
    @expectedFailureNetBSD
    @skipIfFreeBSD  # llvm.org/pr21136 runtimes not yet available by default
    @skipIfRemote
    @skipUnlessThreadSanitizer
    def test(self):
        self.build()
        self.tsan_tests()

    def tsan_tests(self):
        exe = self.getBuildArtifact("a.out")
        self.expect(
            "file " + exe,
            patterns=["Current executable set to .*a.out"])

        self.runCmd("run")

        stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason()
        if stop_reason == lldb.eStopReasonExec:
            # On OS X 10.10 and older, we need to re-exec to enable
            # interceptors.
            self.runCmd("continue")

        # the stop reason of the thread should be breakpoint.
        self.expect("thread list", "A data race should be detected",
                    substrs=['stopped', 'stop reason = Data race detected'])

        self.expect(
            "thread info -s",
            "The extended stop info should contain the TSan provided fields",
            substrs=[
                "instrumentation_class",
                "description",
                "mops"])

        output_lines = self.res.GetOutput().split('\n')
        json_line = '\n'.join(output_lines[2:])
        data = json.loads(json_line)
        self.assertEqual(data["instrumentation_class"], "ThreadSanitizer")
        self.assertEqual(data["issue_type"], "data-race")

        self.assertTrue(data["location_filename"].endswith("/main.cpp"))
        self.assertEqual(
            data["location_line"],
            line_number(
                'main.cpp',
                '// global variable'))


text:
package com.estproject.estmember.core.service.impl;

import com.estproject.estmember.common.domain.User;
import com.estproject.estmember.core.dao.UserDao;
import com.sun.xml.internal.bind.v2.model.core.ID;
import org.springframework.stereotype.Service;

import com.estproject.estmember.core.service.EstMemberService;

import javax.annotation.Resource;

/**
 * @author: 谭锡标
 * @since: 2016年6月12日下午2:34:52
 * @version: 1.0
 */
@Service("estMemberService")
public class EstMemberServiceImpl implements EstMemberService {

	@Resource
	private UserDao userDao;

	public void queryById(Long id) {
		userDao.queryUserById(id);
	}

	public User queryByUserId(Long id) {
		User u =userDao.queryUserById(id);
		return u;
	}
}


text:
layout: post
title: "Interning among the minions"
excerpt: "Spinderihallerne Vejle Interning"
categories: interning
tags: [journal, vejle]
comments: true
share: true
---

The first day as an intern was all about the new people, the new names, the new faces and the new place. Yet, in the middle of all this madness, a couple of things were familiar; my internship coordinator Lars Henrik Nielsen and ... the minions. :smile: The cutest message, from the team and the minions, greeted me on the new office.

 It may appear that the minions have changed their strategy and forgot all about finding the most despicable master. The ultimate purpose for the minions in our office was to ease this interns first day. See for yourself my new minion friends.

The building is decorated in such a manner that it is vocal and speaks to you, wherever you look you get to learn from everything that surrounds you, the walls, the floors.

Today I met the colleagues that make Spinderihallerne "spinning", from the financial department to the top leader, people with beautiful minds that create unbelievable projects. Today I was introduced to two projects, one who deals with using philosophical paradigms in solving social problems and business issues and the second one was a quick tour of Dystopia's team haunted house that is placed right on Spinderihallerne's yard.

The building, the people,...the minions are such an inspiration! The entire environment is the best place for being creative, innovate and learn from the best.


text:
from oslo_serialization import jsonutils
import pecan
import requests
import wsme
from wsme import types as wtypes

from aodh.api.controllers.v2 import base
from aodh.api.controllers.v2 import utils as v2_utils
from aodh import keystone_client

class GnocchiUnavailable(Exception):
    code = 503

class AlarmGnocchiThresholdRule(base.AlarmRule):
    comparison_operator = base.AdvEnum('comparison_operator', str,
                                       'lt', 'le', 'eq', 'ne', 'ge', 'gt',
                                       default='eq')
    "The comparison against the alarm threshold"

    threshold = wsme.wsattr(float, mandatory=True)
    "The threshold of the alarm"

    aggregation_method = wsme.wsattr(wtypes.text, mandatory=True)
    "The aggregation_method to compare to the threshold"

    evaluation_periods = wsme.wsattr(wtypes.IntegerType(minimum=1), default=1)
    "The number of historical periods to evaluate the threshold"

    granularity = wsme.wsattr(wtypes.IntegerType(minimum=1), default=60)
    "The time range in seconds over which query"

    @classmethod
    def validate_alarm(cls, alarm):
        alarm_rule = getattr(alarm, "%s_rule" % alarm.type)
        aggregation_method = alarm_rule.aggregation_method
        if aggregation_method not in cls._get_aggregation_methods():
            raise base.ClientSideError(
                'aggregation_method should be in %s not %s' % (
                    cls._get_aggregation_methods(), aggregation_method))

    # NOTE(sileht): once cachetools is in the requirements
    # enable it
    # @cachetools.ttl_cache(maxsize=1, ttl=600)
    @staticmethod
    def _get_aggregation_methods():
        ks_client = keystone_client.get_client(pecan.request.cfg)
        gnocchi_url = pecan.request.cfg.gnocchi_url
        headers = {'Content-Type': "application/json",
                   'X-Auth-Token': ks_client.auth_token}
        try:
            r = requests.get("%s/v1/capabilities" % gnocchi_url,
                             headers=headers)
        except requests.ConnectionError as e:
            raise GnocchiUnavailable(e)
        if r.status_code // 200 != 1:
            raise GnocchiUnavailable(r.text)

        return jsonutils.loads(r.text).get('aggregation_methods', [])

class MetricOfResourceRule(AlarmGnocchiThresholdRule):
    metric = wsme.wsattr(wtypes.text, mandatory=True)
    "The name of the metric"

    resource_id = wsme.wsattr(wtypes.text, mandatory=True)
    "The id of a resource"

    resource_type = wsme.wsattr(wtypes.text, mandatory=True)
    "The resource type"

    def as_dict(self):
        rule = self.as_dict_from_keys(['granularity', 'comparison_operator',
                                       'threshold', 'aggregation_method',
                                       'evaluation_periods',
                                       'metric',
                                       'resource_id',
                                       'resource_type'])
        return rule

    @classmethod
    def validate_alarm(cls, alarm):
        super(MetricOfResourceRule,
              cls).validate_alarm(alarm)

        rule = alarm.gnocchi_resources_threshold_rule
        ks_client = keystone_client.get_client(pecan.request.cfg)
        gnocchi_url = pecan.request.cfg.gnocchi_url
        headers = {'Content-Type': "application/json",
                   'X-Auth-Token': ks_client.auth_token}
        try:
            r = requests.get("%s/v1/resource/%s/%s" % (
                gnocchi_url, rule.resource_type,
                rule.resource_id),
                headers=headers)
        except requests.ConnectionError as e:
            raise GnocchiUnavailable(e)
        if r.status_code == 404:
            raise base.EntityNotFound('gnocchi resource',
                                      rule.resource_id)
        elif r.status_code // 200 != 1:
            raise base.ClientSideError(r.content, status_code=r.status_code)

class AggregationMetricByResourcesLookupRule(AlarmGnocchiThresholdRule):
    metric = wsme.wsattr(wtypes.text, mandatory=True)
    "The name of the metric"

    query = wsme.wsattr(wtypes.text, mandatory=True)
    ('The query to filter the metric, Don\'t forget to filter out '
     'deleted resources (example: {"and": [{"=": {"ended_at": null}}, ...]}), '
     'Otherwise Gnocchi will try to create the aggregate against obsolete '
     'resources')

    resource_type = wsme.wsattr(wtypes.text, mandatory=True)
    "The resource type"

    def as_dict(self):
        rule = self.as_dict_from_keys(['granularity', 'comparison_operator',
                                       'threshold', 'aggregation_method',
                                       'evaluation_periods',
                                       'metric',
                                       'query',
                                       'resource_type'])
        return rule

    @classmethod
    def validate_alarm(cls, alarm):
        super(AggregationMetricByResourcesLookupRule,
              cls).validate_alarm(alarm)

        rule = alarm.gnocchi_aggregation_by_resources_threshold_rule

        # check the query string is a valid json
        try:
            query = jsonutils.loads(rule.query)
        except ValueError:
            raise wsme.exc.InvalidInput('rule/query', rule.query)

        # Scope the alarm to the project id if needed
        auth_project = v2_utils.get_auth_project(alarm.project_id)
        if auth_project:
            rule.query = jsonutils.dumps({
                "and": [{"=": {"created_by_project_id": auth_project}},
                        query]})

        # Delegate the query validation to gnocchi
        ks_client = keystone_client.get_client(pecan.request.cfg)
        request = {
            'url': "%s/v1/aggregation/resource/%s/metric/%s" % (
                pecan.request.cfg.gnocchi_url,
                rule.resource_type,
                rule.metric),
            'headers': {'Content-Type': "application/json",
                        'X-Auth-Token': ks_client.auth_token},
            'params': {'aggregation': rule.aggregation_method,
                       'needed_overlap': 0},
            'data': rule.query,
        }

        try:
            r = requests.post(**request)
        except requests.ConnectionError as e:
            raise GnocchiUnavailable(e)
        if r.status_code // 200 != 1:
            raise base.ClientSideError(r.content, status_code=r.status_code)

class AggregationMetricsByIdLookupRule(AlarmGnocchiThresholdRule):
    metrics = wsme.wsattr([wtypes.text], mandatory=True)
    "A list of metric Ids"

    def as_dict(self):
        rule = self.as_dict_from_keys(['granularity', 'comparison_operator',
                                       'threshold', 'aggregation_method',
                                       'evaluation_periods',
                                       'metrics'])
        return rule


text:
package org.ng200.openolympus.validation;

import org.ng200.openolympus.dto.ContestUserTimeAdditionDto;
import org.ng200.openolympus.jooq.tables.pojos.Contest;
import org.ng200.openolympus.services.contest.ContestUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;

@Component
public class ContestUserTimeAdditionDtoValidator {

	@Autowired
	private ContestUsersService contestUsersService;

	public void validate(final Contest contest,
			final ContestUserTimeAdditionDto contestTimeAddition,
			final Errors errors) {
		if (errors.hasErrors()) {
			return;
		}
		if (contestTimeAddition.getUser() == null) {
			errors.rejectValue("username", "",
					"contest.addUserTime.form.errors.userDoesntExist");
			return;
		}
		if (!this.contestUsersService.isUserParticipatingIn(
				contestTimeAddition.getUser(), contest)) {
			errors.rejectValue("username", "",
					"contest.addUserTime.form.errors.userNotInContest");
			return;
		}

	}
}