text:
package frontEnd;

import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;

import org.jnativehook.GlobalScreen;

import staticResources.BootStrapResources;
import utilities.DateUtility;
import utilities.FileUtility;
import utilities.Function;
import utilities.NumberUtility;
import utilities.OSIdentifier;
import utilities.Pair;
import utilities.ZipUtility;
import utilities.swing.KeyChainInputPanel;
import utilities.swing.SwingUtil;
import core.config.Config;
import core.controller.Core;
import core.ipc.IPCServiceManager;
import core.ipc.IPCServiceName;
import core.ipc.repeatClient.PythonIPCClientService;
import core.ipc.repeatServer.processors.TaskProcessorManager;
import core.keyChain.GlobalEventsManager;
import core.keyChain.KeyChain;
import core.keyChain.TaskActivation;
import core.languageHandler.Language;
import core.languageHandler.compiler.AbstractNativeCompiler;
import core.languageHandler.compiler.DynamicCompilerOutput;
import core.languageHandler.compiler.PythonRemoteCompiler;
import core.languageHandler.sourceGenerator.AbstractSourceGenerator;
import core.recorder.Recorder;
import core.userDefinedTask.TaskGroup;
import core.userDefinedTask.TaskSourceManager;
import core.userDefinedTask.UserDefinedAction;

public class MainBackEndHolder {

	private static final Logger LOGGER = Logger.getLogger(MainBackEndHolder.class.getName());

	protected ScheduledThreadPoolExecutor executor;
	protected Thread compiledExecutor;

	protected Recorder recorder;

	protected UserDefinedAction customFunction;

	protected final List<TaskGroup> taskGroups;
	protected TaskGroup currentGroup;
	protected int selectedTaskIndex;

	protected final GlobalEventsManager keysManager;
	protected final Config config;

	protected final UserDefinedAction switchRecord, switchReplay, switchReplayCompiled;
	protected boolean isRecording, isReplaying, isRunning;

	protected final MainFrame main;

	public MainBackEndHolder(MainFrame main) {
		this.main = main;
		config = new Config(this);

		executor = new ScheduledThreadPoolExecutor(5);

		keysManager = new GlobalEventsManager(config);
		recorder = new Recorder(keysManager);

		taskGroups = new ArrayList<>();
		selectedTaskIndex = -1;

		switchRecord = new UserDefinedAction() {
			@Override
			public void action(Core controller) throws InterruptedException {
				switchRecord();
			}
		};

		switchReplay = new UserDefinedAction() {
			@Override
			public void action(Core controller) throws InterruptedException {
				switchReplay();
			}
		};

		switchReplayCompiled = new UserDefinedAction() {
			@Override
			public void action(Core controller) throws InterruptedException {
				switchRunningCompiledAction();
			}
		};

		TaskProcessorManager.setProcessorIdentifyCallback(new Function<Language, Void>(){
			@Override
			public Void apply(Language language) {
				for (TaskGroup group : taskGroups) {
					List<UserDefinedAction> tasks = group.getTasks();
					for (int i = 0; i < tasks.size(); i++) {
						UserDefinedAction task = tasks.get(i);
						if (task.getCompiler() != language) {
							continue;
						}

						AbstractNativeCompiler compiler = config.getCompilerFactory().getCompiler(task.getCompiler());
						UserDefinedAction recompiled = task.recompile(compiler, false);
						if (recompiled == null) {
							continue;
						}

						tasks.set(i, recompiled);

						if (recompiled.isEnabled()) {
							if (keysManager.isTaskRegistered(recompiled).isEmpty()) {
								keysManager.registerTask(recompiled);
							}
						}
					}
				}
				renderTasks();
				return null;
			}
		});
	}

	/*************************************************************************************************************/
	/************************************************Config*******************************************************/
	protected void loadConfig(File file) {
		config.loadConfig(file);

		File pythonExecutable = ((PythonRemoteCompiler) (config.getCompilerFactory()).getCompiler(Language.PYTHON)).getPath();
		((PythonIPCClientService)IPCServiceManager.getIPCService(IPCServiceName.PYTHON)).setExecutingProgram(pythonExecutable);

		applyDebugLevel();
		renderSettings();
	}

	/*************************************************************************************************************/
	/************************************************IPC**********************************************************/
	protected void initiateBackEndActivities() {
		executor.scheduleWithFixedDelay(new Runnable(){
			@Override
			public void run() {
				final Point p = Core.getInstance().mouse().getPosition();
				SwingUtilities.invokeLater(new Runnable() {
					@Override
					public void run() {
						main.tfMousePosition.setText(p.x + ", " + p.y);
					}
				});
			}
		}, 0, 500, TimeUnit.MILLISECONDS);

		executor.scheduleWithFixedDelay(new Runnable(){
			@Override
			public void run() {
				SwingUtilities.invokeLater(new Runnable() {
					@Override
					public void run() {
						long time = 0;
						for (TaskGroup group : taskGroups) {
							for (UserDefinedAction action : group.getTasks()) {
								time += action.getStatistics().getTotalExecutionTime();
							}
						}
						main.lSecondsSaved.setText((time/1000f) + "");
						renderTasks();
					}
				});
			}
		}, 0, 1500, TimeUnit.MILLISECONDS);

		try {
			IPCServiceManager.initiateServices();
		} catch (IOException e) {
			LOGGER.log(Level.WARNING, "Unable to launch ipcs.", e);
		}
	}

	protected void stopBackEndActivities() {
		try {
			IPCServiceManager.stopServices();
		} catch (IOException e) {
			LOGGER.log(Level.WARNING, "Unable to stop ipcs.", e);
		}
	}

	protected void exit() {
		stopBackEndActivities();

		if (!writeConfigFile()) {
			JOptionPane.showMessageDialog(main, "Error saving configuration file.");
			System.exit(2);
		}

		System.exit(0);
	}

	/*************************************************************************************************************/
	/****************************************Main hotkeys*********************************************************/
	protected void configureMainHotkeys() {
		keysManager.reRegisterTask(switchRecord, TaskActivation.newBuilder().withHotKey(config.getRECORD()).build());
		keysManager.reRegisterTask(switchReplay, TaskActivation.newBuilder().withHotKey(config.getREPLAY()).build());
		keysManager.reRegisterTask(switchReplayCompiled, TaskActivation.newBuilder().withHotKey(config.getCOMPILED_REPLAY()).build());
	}

	/*************************************************************************************************************/
	/****************************************Record and replay****************************************************/
	protected void switchRecord() {
		if (!isRecording) { // Start record
			recorder.clear();
			recorder.record();
			isRecording = true;
			main.bRecord.setIcon(BootStrapResources.STOP);

			setEnableReplay(false);
		} else { // Stop record
			recorder.stopRecord();
			isRecording = false;
			main.bRecord.setIcon(BootStrapResources.RECORD);

			setEnableReplay(true);
		}
	}

	protected void switchReplay() {
		if (isReplaying) {
			isReplaying = false;
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					main.bReplay.setIcon(BootStrapResources.PLAY);
					setEnableRecord(true);
				}
			});
			recorder.stopReplay();
		} else {
			isReplaying = true;
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					main.bReplay.setIcon(BootStrapResources.STOP);
					setEnableRecord(false);
				}
			});

			String repeatText = main.tfRepeatCount.getText();
			String delayText = main.tfRepeatDelay.getText();
			if (NumberUtility.isPositiveInteger(repeatText) && NumberUtility.isNonNegativeInteger(delayText)) {
				long repeatCount = Long.parseLong(repeatText);
				long delay = Long.parseLong(delayText);

				recorder.replay(repeatCount, delay, new Function<Void, Void>() {
					@Override
					public Void apply(Void r) {
						switchReplay();
						return null;
					}
				}, 5, false);
			}
		}
	}

	protected void switchRunningCompiledAction() {
		if (isRunning) {
			isRunning = false;
			if (compiledExecutor != null) {
				if (compiledExecutor != Thread.currentThread()) {
					while (compiledExecutor.isAlive()) {
						compiledExecutor.interrupt();
					}
				}
			}

			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					main.bRun.setText("Run Compiled Action");
				}
			});
		} else {
			if (customFunction == null) {
				JOptionPane.showMessageDialog(main, "No compiled action in memory");
				return;
			}

			isRunning = true;

			compiledExecutor = new Thread(new Runnable() {
			    @Override
				public void run() {
			    	try {
						customFunction.action(Core.getInstance());
					} catch (InterruptedException e) { // Stopped prematurely
						return;
					} catch (Exception e) {
						LOGGER.log(Level.WARNING, "Exception caught while executing custom function", e);
					}

					switchRunningCompiledAction();
			    }
			});
			compiledExecutor.start();

			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					main.bRun.setText("Stop running");
				}
			});
		}
	}

	/*************************************************************************************************************/
	/*****************************************Task group related**************************************************/
	protected void renderTaskGroup() {
		main.taskGroup.renderTaskGroup();

		for (TaskGroup group : taskGroups) {
			if (!group.isEnabled()) {
				continue;
			}

			for (UserDefinedAction task : group.getTasks()) {
				Set<UserDefinedAction> collisions = keysManager.isTaskRegistered(task);
				if (task.isEnabled() && (collisions.isEmpty())) {
					keysManager.registerTask(task);
				}
			}
		}
	}

	/*************************************************************************************************************/
	/*****************************************Task related********************************************************/

	private void removeTask(UserDefinedAction task) {
		keysManager.unregisterTask(task);
		if (!TaskSourceManager.removeTask(task)) {
			JOptionPane.showMessageDialog(main, "Encountered error removing source file " + task.getSourcePath());
		}
	}

	protected void addCurrentTask() {
		if (customFunction != null) {
			customFunction.setName("New task");
			currentGroup.getTasks().add(customFunction);

			customFunction = null;

			renderTasks();
			writeConfigFile();
		} else {
			JOptionPane.showMessageDialog(main, "Nothing to add. Compile first?");
		}

		int selectedRow = main.tTasks.getSelectedRow();
		selectedTaskIndex = selectedRow;
	}

	protected void removeCurrentTask() {
		int selectedRow = main.tTasks.getSelectedRow();
		selectedTaskIndex = selectedRow;

		if (selectedRow >= 0 && selectedRow < currentGroup.getTasks().size()) {
			UserDefinedAction selectedTask = currentGroup.getTasks().get(selectedRow);
			removeTask(selectedTask);

			currentGroup.getTasks().remove(selectedRow);
			selectedTaskIndex = - 1; // Reset selected index

			renderTasks();
			writeConfigFile();
		} else {
			JOptionPane.showMessageDialog(main, "Select a row from the table to remove");
		}
	}

	protected void moveTaskUp() {
		int selected = main.tTasks.getSelectedRow();
		if (selected >= 1) {
			Collections.swap(currentGroup.getTasks(), selected, selected - 1);
			main.tTasks.setRowSelectionInterval(selected - 1, selected - 1);
			renderTasks();
		}
	}

	protected void moveTaskDown() {
		int selected = main.tTasks.getSelectedRow();
		if (selected >= 0 && selected < currentGroup.getTasks().size() - 1) {
			Collections.swap(currentGroup.getTasks(), selected, selected + 1);
			main.tTasks.setRowSelectionInterval(selected + 1, selected + 1);
			renderTasks();
		}
	}

	protected void changeTaskGroup() {
		int selected = main.tTasks.getSelectedRow();
		if (selected >= 0 && selected < currentGroup.getTasks().size()) {
			int newGroupIndex = SwingUtil.DialogUtil.getSelection(null, "Select new group",
				new Function<TaskGroup, String>() {
					@Override
					public String apply(TaskGroup d) {
						return d.getName();
					}
				}.map(taskGroups).toArray(new String[taskGroups.size()]), -1);

			if (newGroupIndex < 0) {
				return;
			}

			TaskGroup destination = taskGroups.get(newGroupIndex);
			if (destination == currentGroup) {
				JOptionPane.showMessageDialog(main, "Cannot move to the same group...");
				return;
			}

			if (currentGroup.isEnabled() ^ destination.isEnabled()) {
				JOptionPane.showMessageDialog(main, "Two groups must be both enabled or disabled to move...");
				return;
			}

			UserDefinedAction toMove = currentGroup.getTasks().remove(selected);
			destination.getTasks().add(toMove);

			renderTasks();
			writeConfigFile();
		}
	}

	protected void overrideTask() {
		int selected = main.tTasks.getSelectedRow();
		if (selected >= 0) {
			if (customFunction == null) {
				JOptionPane.showMessageDialog(main, "Nothing to override. Compile first?");
				return;
			}

			UserDefinedAction toRemove = currentGroup.getTasks().get(selected);
			customFunction.override(toRemove);

			removeTask(toRemove);
			keysManager.registerTask(customFunction);
			currentGroup.getTasks().set(selected, customFunction);

			LOGGER.info("Successfully overridden task " + customFunction.getName());
			customFunction = null;
			if (!config.writeConfig()) {
				LOGGER.warning("Unable to update config.");
			}
		} else {
			JOptionPane.showMessageDialog(main, "Select a task to override");
		}
	}

	protected void changeHotkeyTask(int row) {
		final UserDefinedAction action = currentGroup.getTasks().get(row);
		TaskActivation newActivation = KeyChainInputPanel.getInputActivation(main, action.getActivation());
		if (newActivation == null) {
			return;
		}

		Set<UserDefinedAction> collisions = keysManager.isActivationRegistered(newActivation);
		collisions.remove(action);
		if (!collisions.isEmpty()) {
			GlobalEventsManager.showCollisionWarning(main, collisions);
			return;
		}

		keysManager.reRegisterTask(action, newActivation);

		KeyChain representative = action.getRepresentativeHotkey();
		main.tTasks.setValueAt(representative.getKeys().isEmpty() ? "None" : representative.toString(), row, MainFrame.TTASK_COLUMN_TASK_HOTKEY);
	}

	protected void switchEnableTask(int row) {
		final UserDefinedAction action = currentGroup.getTasks().get(row);

		if (action.isEnabled()) { // Then disable it
			action.setEnabled(false);
			keysManager.unregisterTask(action);
		} else { // Then enable it
			Set<UserDefinedAction> collisions = keysManager.isTaskRegistered(action);
			if (!collisions.isEmpty()) {
				GlobalEventsManager.showCollisionWarning(main, collisions);
				return;
			}

			action.setEnabled(true);
			keysManager.registerTask(action);
		}

		main.tTasks.setValueAt(action.isEnabled(), row, MainFrame.TTASK_COLUMN_ENABLED);
	}

	protected void renderTasks() {
		main.bTaskGroup.setText(currentGroup.getName());
		SwingUtil.TableUtil.setRowNumber(main.tTasks, currentGroup.getTasks().size());
		SwingUtil.TableUtil.clearTable(main.tTasks);

		int row = 0;
		for (UserDefinedAction task : currentGroup.getTasks()) {
			main.tTasks.setValueAt(task.getName(), row, MainFrame.TTASK_COLUMN_TASK_NAME);

			KeyChain representative = task.getRepresentativeHotkey();
			if (representative != null && !representative.getKeys().isEmpty()) {
				main.tTasks.setValueAt(representative.toString(), row, MainFrame.TTASK_COLUMN_TASK_HOTKEY);
			} else {
				main.tTasks.setValueAt("None", row, MainFrame.TTASK_COLUMN_TASK_HOTKEY);
			}

			main.tTasks.setValueAt(task.isEnabled(), row, MainFrame.TTASK_COLUMN_ENABLED);
			main.tTasks.setValueAt(task.getStatistics().getCount(), row, MainFrame.TTASK_COLUMN_USE_COUNT);
			main.tTasks.setValueAt(DateUtility.calendarToDateString(task.getStatistics().getLastUse()), row, MainFrame.TTASK_COLUMN_LAST_USE);
			row++;
		}
	}

	protected void keyReleaseTaskTable(KeyEvent e) {
		int row = main.tTasks.getSelectedRow();
		int column = main.tTasks.getSelectedColumn();

		if (column == MainFrame.TTASK_COLUMN_TASK_NAME && row >= 0) {
			currentGroup.getTasks().get(row).setName(SwingUtil.TableUtil.getStringValueTable(main.tTasks, row, column));
		} else if (column == MainFrame.TTASK_COLUMN_TASK_HOTKEY && row >= 0) {
			if (e.getKeyCode() == Config.HALT_TASK) {
				final UserDefinedAction action = currentGroup.getTasks().get(row);
				keysManager.unregisterTask(action);
				action.getActivation().getHotkeys().clear();
				main.tTasks.setValueAt("None", row, column);
			} else {
				changeHotkeyTask(row);
			}
		} else if (column == MainFrame.TTASK_COLUMN_ENABLED && row >= 0) {
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				switchEnableTask(row);
			}
		}

		loadSource(row);
		selectedTaskIndex = row;
	}

	protected void mouseReleaseTaskTable(MouseEvent e) {
		int row = main.tTasks.getSelectedRow();
		int column = main.tTasks.getSelectedColumn();

		if (column == MainFrame.TTASK_COLUMN_TASK_HOTKEY && row >= 0) {
			changeHotkeyTask(row);
		} else if (column == MainFrame.TTASK_COLUMN_ENABLED && row >= 0) {
			switchEnableTask(row);
		}

		loadSource(row);
		selectedTaskIndex = row;
	}

	private void loadSource(int row) {
		// Load source if possible
		if (row < 0 || row >= currentGroup.getTasks().size()) {
			return;
		}
		if (selectedTaskIndex == row) {
			return;
		}

		UserDefinedAction task = currentGroup.getTasks().get(row);
		String source = task.getSource();

		if (source == null) {
			JOptionPane.showMessageDialog(main, "Cannot retrieve source code for task " + task.getName() + ".\nTry recompiling and add again");
			return;
		}

		if (!task.getCompiler().equals(getCompiler().getName())) {
			main.languageSelection.get(task.getCompiler()).setSelected(true);
		}

		main.taSource.setText(source);
	}

	/*************************************************************************************************************/
	/********************************************Source code related**********************************************/

	protected void promptSource() {
		StringBuffer sb = new StringBuffer();
		sb.append(AbstractSourceGenerator.getReferenceSource(getSelectedLanguage()));
		main.taSource.setText(sb.toString());
	}

	protected void generateSource() {
		main.taSource.setText(recorder.getGeneratedCode(getSelectedLanguage()));
	}

	protected void importTasks(File inputFile) {
		ZipUtility.unZipFile(inputFile.getAbsolutePath(), ".");
		FileUtility.moveFiles(new File("tmp"), new File("."));

		boolean result = config.importTaskConfig();
		FileUtility.deleteFile(new File("tmp"));

		if (result) {
			JOptionPane.showMessageDialog(main, "Successfully imported tasks");
		} else {
			JOptionPane.showMessageDialog(main, "Encountered error while importing tasks");
		}
	}

	protected void exportTasks(File outputDirectory) {
		File destination = new File(FileUtility.joinPath(outputDirectory.getAbsolutePath(), "tmp"));
		String zipPath = FileUtility.joinPath(outputDirectory.getAbsolutePath(), "repeat_export.zip");

		FileUtility.createDirectory(destination.getAbsolutePath());
		config.exportTasksConfig(destination);
		// Now create a zip file containing all source codes together with the config file
		for (TaskGroup group : taskGroups) {
			for (UserDefinedAction task : group.getTasks()) {
				File sourceFile = new File(task.getSourcePath());
				String destPath = FileUtility.joinPath(destination.getAbsolutePath(), FileUtility.getRelativePwdPath(sourceFile));
				File destFile = new File(destPath);
				FileUtility.copyFile(sourceFile, destFile);
			}
		}

		File zipFile = new File(zipPath);
		ZipUtility.zipDir(destination, zipFile);
		FileUtility.deleteFile(destination);

		JOptionPane.showMessageDialog(main, "Data exported to " + zipPath);
	}

	protected void cleanUnusedSource() {
		List<File> files = FileUtility.walk(FileUtility.joinPath("data", "source"));
		Set<String> allNames = new HashSet<>(new Function<File, String>() {
			@Override
			public String apply(File file) {
				return file.getAbsolutePath();
			}
		}.map(files));

		Set<String> using = new HashSet<>();
		for (TaskGroup group : taskGroups) {
			using.addAll(new Function<UserDefinedAction, String>() {
				@Override
				public String apply(UserDefinedAction task) {
					return new File(task.getSourcePath()).getAbsolutePath();
				}
			}.map(group.getTasks()));
		}

		allNames.removeAll(using);
		if (allNames.size() == 0) {
			JOptionPane.showMessageDialog(main, "Nothing to clean...");
			return;
		}

		String[] titles = new String[allNames.size()];
		Arrays.fill(titles, "Deleting");
		int confirmDelete = SwingUtil.OptionPaneUtil.confirmValues("Delete these files?", titles, allNames.toArray(new String[0]));
		if (confirmDelete == JOptionPane.OK_OPTION) {
			int count = 0, failed = 0;
			for (String name : allNames) {
				if (FileUtility.removeFile(new File(name))) {
					count++;
				} else {
					failed++;
				}
			}

			JOptionPane.showMessageDialog(main, "Successfully cleaned " + count + " files.\n Failed to clean " + failed + " files.");
		}
	}

	/*************************************************************************************************************/
	/***************************************Source compilation****************************************************/

	protected Language getSelectedLanguage() {
		for (JRadioButtonMenuItem rbmi : main.rbmiSelection.keySet()) {
			if (rbmi.isSelected()) {
				return main.rbmiSelection.get(rbmi);
			}
		}

		throw new IllegalStateException("Undefined state. No language selected.");
	}

	protected AbstractNativeCompiler getCompiler() {
		return config.getCompilerFactory().getCompiler(getSelectedLanguage());
	}

	protected void refreshCompilingLanguage() {
		customFunction = null;
		getCompiler().changeCompilationButton(main.bCompile);
		promptSource();
	}

	protected void changeCompilerPath() {
		getCompiler().promptChangePath(main);
	}

	protected void compileSource() {
		String source = main.taSource.getText();

		AbstractNativeCompiler compiler = getCompiler();
		Pair<DynamicCompilerOutput, UserDefinedAction> compilationResult = compiler.compile(source);
		DynamicCompilerOutput compilerStatus = compilationResult.getA();
		UserDefinedAction createdInstance = compilationResult.getB();

		if (compilerStatus != DynamicCompilerOutput.COMPILATION_SUCCESS) {
			return;
		}

		customFunction = createdInstance;
		customFunction.setCompiler(compiler.getName());

		if (!TaskSourceManager.submitTask(customFunction, source)) {
			JOptionPane.showMessageDialog(main, "Error writing source file...");
		}
	}

	/*************************************************************************************************************/
	/***************************************Configurations********************************************************/
	// Write configuration file
	protected boolean writeConfigFile() {
		boolean result = config.writeConfig();
		if (!result) {
			LOGGER.warning("Unable to update config.");
		}

		return result;
	}

	private final Level[] DEBUG_LEVELS = {Level.SEVERE, Level.WARNING, Level.INFO, Level.FINE};

	protected void applyDebugLevel() {
		Level debugLevel = config.getNativeHookDebugLevel();
		final JRadioButtonMenuItem[] buttons = {main.rbmiDebugSevere, main.rbmiDebugWarning, main.rbmiDebugInfo, main.rbmiDebugFine};

		for (int i = 0; i < DEBUG_LEVELS.length; i++) {
			if (debugLevel == DEBUG_LEVELS[i]) {
				buttons[i].setSelected(true);
				break;
			}
		}
	}

	protected void changeDebugLevel() {
		Level debugLevel = Level.WARNING;
		final JRadioButtonMenuItem[] buttons = {main.rbmiDebugSevere, main.rbmiDebugWarning, main.rbmiDebugInfo, main.rbmiDebugFine};

		for (int i = 0; i < DEBUG_LEVELS.length; i++) {
			if (buttons[i].isSelected()) {
				debugLevel = DEBUG_LEVELS[i];
				break;
			}
		}
		config.setNativeHookDebugLevel(debugLevel);

		// Get the logger for "org.jnativehook" and set the level to appropriate level.
		Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
		logger.setLevel(config.getNativeHookDebugLevel());
	}

	protected void renderSettings() {
		if (!OSIdentifier.IS_WINDOWS) {
			main.rbmiCompileCS.setEnabled(false);
		}
		main.cbmiUseTrayIcon.setSelected(config.isUseTrayIcon());
		main.cbmiHaltByKey.setSelected(config.isEnabledHaltingKeyPressed());
		main.cbmiExecuteOnReleased.setSelected(config.isExecuteOnKeyReleased());
	}

	protected void switchTrayIconUse() {
		boolean trayIconEnabled = main.cbmiUseTrayIcon.isSelected();
		config.setUseTrayIcon(trayIconEnabled);
	}

	protected void haltAllTasks() {
		keysManager.haltAllTasks();
	}

	protected void switchHaltByKey() {
		config.setEnabledHaltingKeyPressed(main.cbmiHaltByKey.isSelected());
	}

	protected void switchExecuteOnReleased() {
		config.setExecuteOnKeyReleased(main.cbmiExecuteOnReleased.isSelected());
	}

	/*************************************************************************************************************/
	private void setEnableRecord(boolean state) {
		main.bRecord.setEnabled(state);
	}

	private void setEnableReplay(boolean state) {
		main.bReplay.setEnabled(state);
		main.tfRepeatCount.setEnabled(state);
		main.tfRepeatDelay.setEnabled(state);

		if (state) {
			main.tfRepeatCount.setText("1");
			main.tfRepeatDelay.setText("0");
		}
	}

	/*************************************************************************************************************/
	/***************************************JFrame operations*****************************************************/
	protected void focusMainFrame() {
		if (main.taskGroup.isVisible()) {
			main.taskGroup.setVisible(false);
		}

		if (main.hotkey.isVisible()) {
			main.hotkey.setVisible(false);
		}

		if (main.ipcs.isVisible()) {
			main.ipcs.setVisible(false);
		}
	}

	/*************************************************************************************************************/
	public List<TaskGroup> getTaskGroups() {
		return taskGroups;
	}

	protected TaskGroup getCurrentTaskGroup() {
		return this.currentGroup;
	}

	public void setCurrentTaskGroup(TaskGroup currentTaskGroup) {
		if (currentTaskGroup != this.currentGroup) {
			this.selectedTaskIndex = -1;
			this.currentGroup = currentTaskGroup;
			keysManager.setCurrentTaskGroup(currentTaskGroup);
		}
	}
}


text:
namespace Autofac.Benchmarks;

public class ChildScopeResolveBenchmark
{
    private IContainer _container;

    [Benchmark]
    public void Resolve()
    {
        using (var requestScope = _container.BeginLifetimeScope("request", b => b.RegisterType<C1>()))
        {
            using (var unitOfWorkScope = requestScope.BeginLifetimeScope())
            {
                var instance = unitOfWorkScope.Resolve<A>();
                GC.KeepAlive(instance);
            }
        }
    }

    [GlobalSetup]
    public void Setup()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<A>();
        builder.RegisterType<B1>();
        builder.RegisterType<B2>().InstancePerMatchingLifetimeScope("request");
        builder.RegisterType<C2>().InstancePerLifetimeScope();
        builder.RegisterType<D1>().SingleInstance();
        builder.RegisterType<D2>().SingleInstance();
        _container = builder.Build();
    }

    internal class A
    {
        public A(B1 b1, B2 b2) { }
    }

    internal class B1
    {
        public B1(B2 b2, C1 c1, C2 c2) { }
    }

    internal class B2
    {
        public B2(C1 c1, C2 c2) { }
    }

    internal class C1
    {
        public C1(C2 c2, D1 d1, D2 d2) { }
    }

    internal class C2
    {
        public C2(D1 d1, D2 d2) { }
    }

    internal class D1 { }

    internal class D2 { }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.LabServices.Models;
using Azure.ResourceManager.Models;

namespace Azure.ResourceManager.LabServices
{
    public partial class LabPlanData : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Identity))
            {
                writer.WritePropertyName("identity");
                JsonSerializer.Serialize(writer, Identity);
            }
            if (Optional.IsCollectionDefined(Tags))
            {
                writer.WritePropertyName("tags");
                writer.WriteStartObject();
                foreach (var item in Tags)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteStringValue(item.Value);
                }
                writer.WriteEndObject();
            }
            writer.WritePropertyName("location");
            writer.WriteStringValue(Location);
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(DefaultConnectionProfile))
            {
                writer.WritePropertyName("defaultConnectionProfile");
                writer.WriteObjectValue(DefaultConnectionProfile);
            }
            if (Optional.IsDefined(DefaultAutoShutdownProfile))
            {
                writer.WritePropertyName("defaultAutoShutdownProfile");
                writer.WriteObjectValue(DefaultAutoShutdownProfile);
            }
            if (Optional.IsDefined(DefaultNetworkProfile))
            {
                writer.WritePropertyName("defaultNetworkProfile");
                writer.WriteObjectValue(DefaultNetworkProfile);
            }
            if (Optional.IsCollectionDefined(AllowedRegions))
            {
                writer.WritePropertyName("allowedRegions");
                writer.WriteStartArray();
                foreach (var item in AllowedRegions)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(SharedGalleryId))
            {
                writer.WritePropertyName("sharedGalleryId");
                writer.WriteStringValue(SharedGalleryId);
            }
            if (Optional.IsDefined(SupportInfo))
            {
                writer.WritePropertyName("supportInfo");
                writer.WriteObjectValue(SupportInfo);
            }
            if (Optional.IsDefined(LinkedLmsInstance))
            {
                writer.WritePropertyName("linkedLmsInstance");
                writer.WriteStringValue(LinkedLmsInstance.AbsoluteUri);
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static LabPlanData DeserializeLabPlanData(JsonElement element)
        {
            Optional<ManagedServiceIdentity> identity = default;
            Optional<IDictionary<string, string>> tags = default;
            AzureLocation location = default;
            ResourceIdentifier id = default;
            string name = default;
            ResourceType type = default;
            Optional<SystemData> systemData = default;
            Optional<LabConnectionProfile> defaultConnectionProfile = default;
            Optional<LabAutoShutdownProfile> defaultAutoShutdownProfile = default;
            Optional<LabPlanNetworkProfile> defaultNetworkProfile = default;
            Optional<IList<AzureLocation>> allowedRegions = default;
            Optional<ResourceIdentifier> sharedGalleryId = default;
            Optional<LabPlanSupportInfo> supportInfo = default;
            Optional<Uri> linkedLmsInstance = default;
            Optional<LabServicesProvisioningState> provisioningState = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("identity"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    identity = JsonSerializer.Deserialize<ManagedServiceIdentity>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary<string, string> dictionary = new Dictionary<string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = new AzureLocation(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("defaultConnectionProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            defaultConnectionProfile = LabConnectionProfile.DeserializeLabConnectionProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("defaultAutoShutdownProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            defaultAutoShutdownProfile = LabAutoShutdownProfile.DeserializeLabAutoShutdownProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("defaultNetworkProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            defaultNetworkProfile = LabPlanNetworkProfile.DeserializeLabPlanNetworkProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("allowedRegions"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<AzureLocation> array = new List<AzureLocation>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(new AzureLocation(item.GetString()));
                            }
                            allowedRegions = array;
                            continue;
                        }
                        if (property0.NameEquals("sharedGalleryId"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            sharedGalleryId = new ResourceIdentifier(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("supportInfo"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            supportInfo = LabPlanSupportInfo.DeserializeLabPlanSupportInfo(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("linkedLmsInstance"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                linkedLmsInstance = null;
                                continue;
                            }
                            linkedLmsInstance = new Uri(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = property0.Value.GetString().ToLabServicesProvisioningState();
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new LabPlanData(id, name, type, systemData.Value, Optional.ToDictionary(tags), location, identity, defaultConnectionProfile.Value, defaultAutoShutdownProfile.Value, defaultNetworkProfile.Value, Optional.ToList(allowedRegions), sharedGalleryId.Value, supportInfo.Value, linkedLmsInstance.Value, Optional.ToNullable(provisioningState));
        }
    }
}


text:
package com.heliosapm.jmxmp.async;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServerConnection;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;

import com.heliosapm.jmxmp.async.AsyncJMXResponseHandler.MBeanServerConnectionAsync;
import com.heliosapm.utils.time.SystemClock;

import co.paralleluniverse.fibers.Fiber;
import co.paralleluniverse.fibers.FiberExecutorScheduler;
import co.paralleluniverse.fibers.FiberScheduler;
import co.paralleluniverse.fibers.SuspendExecution;
import co.paralleluniverse.fibers.Suspendable;
import co.paralleluniverse.strands.Strand;
import co.paralleluniverse.strands.SuspendableCallable;

/**
 *
Title: SuspendableMBeanServerConnection

 *
Description:

 *
Company: Helios Development Group LLC

 * @author Whitehead (nwhitehead AT heliosdev DOT org)
 *
com.heliosapm.jmxmp.bulk.SuspendableMBeanServerConnection

 */
@SuppressWarnings("serial")
public class SuspendableMBeanServerConnection implements MBeanServerConnection {
	public static final int CORES = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
	final BulkMBeanServerConnection bmc;
	final BulkInvocationBuilder invBuilder;
	final ExecutorService taskExecutor = Executors.newFixedThreadPool(1, new ThreadFactory(){
		@Override
		public Thread newThread(final Runnable r) {
			final Thread t = new Thread(r, "JMXTaskExecutor");
			t.setDaemon(true);
			return t;
		}
	});
	final FiberScheduler scheduler = new FiberExecutorScheduler("asyncjmx", Executors.newFixedThreadPool(CORES, new ThreadFactory(){
		@Override
		public Thread newThread(final Runnable r) {
			final Thread t = new Thread(r, "JMXFiberExecutor");
			t.setDaemon(true);
			return t;
		}
	}));

	/**
	 * Creates a new BulkMBeanServerConnection
	 * @param invBuilder The invocation builder
	 */
	public SuspendableMBeanServerConnection(final BulkInvocationBuilder invBuilder) {
		this.invBuilder = invBuilder;
		bmc = new BulkMBeanServerConnection(invBuilder);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#addNotificationListener(javax.management.ObjectName, javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
	 */
	@Override @Suspendable
	public void addNotificationListener(final ObjectName name, final NotificationListener listener, final NotificationFilter filter, final Object handback) throws InstanceNotFoundException, IOException {
		new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.addNotificationListener(name, listener, filter, handback, this);
			}
		}.inv();
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#addNotificationListener(javax.management.ObjectName, javax.management.ObjectName, javax.management.NotificationFilter, java.lang.Object)
	 */

	@Override @Suspendable
	public void addNotificationListener(final ObjectName name, final ObjectName listener, final NotificationFilter filter, final Object handback) throws InstanceNotFoundException, IOException {
		new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.addNotificationListener(name, listener, filter, handback, this);
			}
		}.inv();
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#createMBean(java.lang.String, javax.management.ObjectName)
	 */

	@Override @Suspendable
	public ObjectInstance createMBean(final String className, final ObjectName name) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.createMBean(className, name, this);

			}
		}.get(ObjectInstance.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#createMBean(java.lang.String, javax.management.ObjectName, javax.management.ObjectName)
	 */

	@Override @Suspendable
	public ObjectInstance createMBean(final String className, final ObjectName name, final ObjectName loaderName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.createMBean(className, name, loaderName, this);

			}
		}.get(ObjectInstance.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#createMBean(java.lang.String, javax.management.ObjectName, java.lang.Object[], java.lang.String[])
	 */

	@Override @Suspendable
	public ObjectInstance createMBean(final String className, final ObjectName name, final Object[] params, final String[] signature) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.createMBean(className, name, params, signature, this);

			}
		}.get(ObjectInstance.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#createMBean(java.lang.String, javax.management.ObjectName, javax.management.ObjectName, java.lang.Object[], java.lang.String[])
	 */

	@Override @Suspendable
	public ObjectInstance createMBean(final String className, final ObjectName name, final ObjectName loaderName, final Object[] params, final String[] signature) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.createMBean(className, name, loaderName, params, signature, this);

			}
		}.get(ObjectInstance.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#getAttribute(javax.management.ObjectName, java.lang.String)
	 */

	@Override @Suspendable
	public Object getAttribute(final ObjectName name, final String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.getAttribute(name, attribute, this);

			}
		}.get(Object.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#getAttributes(javax.management.ObjectName, java.lang.String[])
	 */

	@Override @Suspendable
	public AttributeList getAttributes(final ObjectName name, final String[] attributes) throws InstanceNotFoundException, ReflectionException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.getAttributes(name, attributes, this);

			}
		}.get(AttributeList.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#getDefaultDomain()
	 */

	@Override @Suspendable
	public String getDefaultDomain() throws IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.getDefaultDomain(this);

			}
		}.get(String.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#getDomains()
	 */

	@Override @Suspendable
	public String[] getDomains() throws IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.getDomains(this);

			}
		}.get(String[].class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#getMBeanCount()
	 */

	@Override @Suspendable
	public Integer getMBeanCount() throws IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.getMBeanCount(this);

			}
		}.get(Integer.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#getMBeanInfo(javax.management.ObjectName)
	 */

	@Override @Suspendable
	public MBeanInfo getMBeanInfo(final ObjectName name) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.getMBeanInfo(name, this);

			}
		}.get(MBeanInfo.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#getObjectInstance(javax.management.ObjectName)
	 */

	@Override @Suspendable
	public ObjectInstance getObjectInstance(final ObjectName name) throws InstanceNotFoundException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.getObjectInstance(name, this);

			}
		}.get(ObjectInstance.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#invoke(javax.management.ObjectName, java.lang.String, java.lang.Object[], java.lang.String[])
	 */

	@Override @Suspendable
	public Object invoke(final ObjectName name, final String operationName, final Object[] params, final String[] signature) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.invoke(name, operationName, params, signature, this);

			}
		}.get(Object.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#isInstanceOf(javax.management.ObjectName, java.lang.String)
	 */

	@Override @Suspendable
	public boolean isInstanceOf(final ObjectName name, final String className) throws InstanceNotFoundException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.isInstanceOf(name, className, this);

			}
		}.get(Boolean.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#isRegistered(javax.management.ObjectName)
	 */

	@Override @Suspendable
	public boolean isRegistered(final ObjectName name) throws IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.isRegistered(name, this);

			}
		}.get(Boolean.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#queryMBeans(javax.management.ObjectName, javax.management.QueryExp)
	 */

	@Override @Suspendable
	public Set<ObjectInstance> queryMBeans(final ObjectName name, final QueryExp query) throws IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.queryMBeans(name, query, this);

			}
		}.get(Set.class);
	}

	private final AtomicLong fiberTask = new AtomicLong();
	private final ConcurrentSkipListMap<Long, Fiber<?>> fibers = new ConcurrentSkipListMap<Long, Fiber<?>>();

	public void reset() {
		int cnt = 0;
		log("Waiting on [" + fibers.size() + "] Fibers....");
		for(Fiber<?> f: fibers.values()) {
			try {
				while(f.getState()==Strand.State.RUNNING) {
					SystemClock.sleep(100);
				}
				log("Testing State: %s : %s", f.getName(), f.getState());

				cnt++;
			} catch (Exception ex) {
				ex.printStackTrace(System.err);
			//throw new RuntimeException(ex);
			}
		}
		fiberTask.set(0);
		log("Reset Complete. Tasks:" + cnt);
		invBuilder.build().send();
		log("BulkRequest Dispatched");
	}

	public static void log(final Object fmt, final Object...args) {
		final Fiber f = Fiber.currentFiber();
		if(f!=null) {
			System.out.println("f:[" + f.getName() + "]" + String.format(fmt.toString(), args));
		} else {
			System.out.println("t:[" + Thread.currentThread().getName() + "]" + String.format(fmt.toString(), args));
		}
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#queryNames(javax.management.ObjectName, javax.management.QueryExp)
	 */

	@Override @Suspendable
	public Set<ObjectName> queryNames(final ObjectName name, final QueryExp query) throws IOException {
		if(Fiber.isCurrentFiber()) {
			log("Calling In Fiber: queryNames");
			try {

				final Fiber<Void> f = new Fiber<Void>(scheduler, new SuspendableCallable<Void>() {
					@Override
					public Void run() throws SuspendExecution, InterruptedException {
						log("Starting MBeanServerConnectionAsync...");

						try {
							bmc.queryNames(name, query, new MBeanServerConnectionAsync(){
								@Override
								protected void requestAsync() {
									log("Yo. There's no action here....");
									// No Op
								}
							});
							log("------------------> Op Written");

						} catch (Exception ex) {
							ex.printStackTrace(System.err);
							throw new RuntimeException(ex);
						}
						return null;
					}
				});
				fibers.put(fiberTask.incrementAndGet(), f);
				f.start();
			} catch (Exception ex) {
				throw new RuntimeException(ex);
			}
			return null;
		}
		try {
			log("Calling In Thread: queryNames");
			return (Set<ObjectName>) fibers.remove(fiberTask.incrementAndGet()).get();
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
	}

	public Set<ObjectName> queryNamesX(final ObjectName name, final QueryExp query) throws IOException {
		if(Fiber.isCurrentFiber()) {
			log("Calling In Fiber: queryNames");
			try {
				final Fiber<Void> f = new Fiber<Void>(scheduler, new SuspendableCallable<Void>() {
					@Override
					public Void run() throws SuspendExecution, InterruptedException {
						log("Starting MBeanServerConnectionAsync...");
						try {
							taskExecutor.submit(new Runnable(){
								public void run() {
									bmc.queryNames(name, query, new MBeanServerConnectionAsync(){
										@Override
										protected void requestAsync() {
											// No Op
										}
									});
									log("------------------> Op Written");
								}
							}).get();
						} catch (Exception ex) {
							ex.printStackTrace(System.err);
							throw new RuntimeException(ex);
						}
						return null;
					}
				});
				fibers.put(fiberTask.incrementAndGet(), f);
				f.start();
			} catch (Exception ex) {
				throw new RuntimeException(ex);
			}
			return null;
		}
		try {
			log("Calling In Thread: queryNames");
			return (Set<ObjectName>) fibers.remove(fiberTask.incrementAndGet()).get();
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#removeNotificationListener(javax.management.ObjectName, javax.management.ObjectName)
	 */

	@Override @Suspendable
	public void removeNotificationListener(final ObjectName name, final ObjectName listener) throws InstanceNotFoundException, ListenerNotFoundException, IOException {
		new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.removeNotificationListener(name, listener, this);

			}
		}.inv();
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#removeNotificationListener(javax.management.ObjectName, javax.management.NotificationListener)
	 */

	@Override @Suspendable
	public void removeNotificationListener(final ObjectName name, final NotificationListener listener) throws InstanceNotFoundException, ListenerNotFoundException, IOException {
		new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.removeNotificationListener(name, listener, this);

			}
		}.inv();
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#removeNotificationListener(javax.management.ObjectName, javax.management.ObjectName, javax.management.NotificationFilter, java.lang.Object)
	 */

	@Override @Suspendable
	public void removeNotificationListener(final ObjectName name, final ObjectName listener, final NotificationFilter filter, final Object handback) throws InstanceNotFoundException, ListenerNotFoundException, IOException {
		new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.removeNotificationListener(name, listener, filter, handback, this);

			}
		}.inv();
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#removeNotificationListener(javax.management.ObjectName, javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
	 */

	@Override @Suspendable
	public void removeNotificationListener(final ObjectName name, final NotificationListener listener, final NotificationFilter filter,	final Object handback) throws InstanceNotFoundException, ListenerNotFoundException, IOException {
		new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.removeNotificationListener(name, listener, filter, handback, this);

			}
		}.inv();
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#setAttribute(javax.management.ObjectName, javax.management.Attribute)
	 */

	@Override @Suspendable
	public void setAttribute(final ObjectName name, final Attribute attribute) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException {
		new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.setAttribute(name, attribute, this);

			}
		}.inv();
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#setAttributes(javax.management.ObjectName, javax.management.AttributeList)
	 */

	@Override @Suspendable
	public AttributeList setAttributes(final ObjectName name, final AttributeList attributes) throws InstanceNotFoundException, ReflectionException, IOException {
		return new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.setAttributes(name, attributes, this);

			}
		}.get(AttributeList.class);
	}

	/**
	 * {@inheritDoc}
	 * @see javax.management.MBeanServerConnection#unregisterMBean(javax.management.ObjectName)
	 */

	@Override @Suspendable
	public void unregisterMBean(final ObjectName name) throws InstanceNotFoundException, MBeanRegistrationException, IOException {
		new MBeanServerConnectionAsync() {
			@Override
			protected void requestAsync() {
				bmc.unregisterMBean(name, this);

			}
		}.inv();
	}

}


text:
include(ExternalProject)

# Note(zhouwei): extern_cub  has code __FILE_, If the path of extern_cub is changed,
# it will effect about 30+ cu files sccache hit and slow compile speed  on windows.
# Therefore, a fixed CUB_PATH will be input to increase the sccache hit rate.
set(CUB_PATH
    "${THIRD_PARTY_PATH}/cub"
    CACHE STRING "A path setting for external_cub path.")
set(CUB_PREFIX_DIR ${CUB_PATH})

set(CUB_REPOSITORY ${GIT_URL}/NVlabs/cub.git)

if(${CMAKE_CUDA_COMPILER_VERSION} GREATER_EQUAL 11.6)
  # cuda_11.6.2_511.65's own cub is 1.15.0, which will cause compiling error in windows.
  set(CUB_TAG 1.16.0)
  # cub 1.16.0 is not compitable with current thrust version
  add_definitions(-DTHRUST_IGNORE_CUB_VERSION_CHECK)
else()
  set(CUB_TAG 1.8.0)
endif()

set(CUB_INCLUDE_DIR ${CUB_PREFIX_DIR}/src/extern_cub)
message("CUB_INCLUDE_DIR is ${CUB_INCLUDE_DIR}")
include_directories(${CUB_INCLUDE_DIR})

ExternalProject_Add(
  extern_cub
  ${EXTERNAL_PROJECT_LOG_ARGS} ${SHALLOW_CLONE}
  GIT_REPOSITORY ${CUB_REPOSITORY}
  GIT_TAG ${CUB_TAG}
  PREFIX ${CUB_PREFIX_DIR}
  UPDATE_COMMAND ""
  CONFIGURE_COMMAND ""
  BUILD_COMMAND ""
  INSTALL_COMMAND ""
  TEST_COMMAND "")

add_library(cub INTERFACE)

add_dependencies(cub extern_cub)