text:
import 'vs/css!./goToDefinitionAtPosition';
import * as nls from 'vs/nls';
import { createCancelablePromise, CancelablePromise } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { onUnexpectedError } from 'vs/base/common/errors';
import { MarkdownString } from 'vs/base/common/htmlContent';
import { IModeService } from 'vs/editor/common/services/modeService';
import { Range, IRange } from 'vs/editor/common/core/range';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { DefinitionProviderRegistry, LocationLink } from 'vs/editor/common/modes';
import { ICodeEditor, MouseTargetType } from 'vs/editor/browser/editorBrowser';
import { registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { getDefinitionsAtPosition } from '../goToSymbol';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { editorActiveLinkForeground } from 'vs/platform/theme/common/colorRegistry';
import { EditorState, CodeEditorStateFlag } from 'vs/editor/browser/core/editorState';
import { DefinitionAction } from '../goToCommands';
import { ClickLinkGesture, ClickLinkMouseEvent, ClickLinkKeyboardEvent } from 'vs/editor/contrib/gotoSymbol/link/clickLinkGesture';
import { IWordAtPosition, IModelDeltaDecoration, ITextModel, IFoundBracket } from 'vs/editor/common/model';
import { Position } from 'vs/editor/common/core/position';
import { withNullAsUndefined } from 'vs/base/common/types';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { PeekContext } from 'vs/editor/contrib/peekView/peekView';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';

export class GotoDefinitionAtPositionEditorContribution implements IEditorContribution {

	public static readonly ID = 'editor.contrib.gotodefinitionatposition';
	static readonly MAX_SOURCE_PREVIEW_LINES = 8;

	private readonly editor: ICodeEditor;
	private readonly toUnhook = new DisposableStore();
	private readonly toUnhookForKeyboard = new DisposableStore();
	private linkDecorations: string[] = [];
	private currentWordAtPosition: IWordAtPosition | null = null;
	private previousPromise: CancelablePromise<LocationLink[] | null> | null = null;

	constructor(
		editor: ICodeEditor,
		@ITextModelService private readonly textModelResolverService: ITextModelService,
		@IModeService private readonly modeService: IModeService
	) {
		this.editor = editor;

		let linkGesture = new ClickLinkGesture(editor);
		this.toUnhook.add(linkGesture);

		this.toUnhook.add(linkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
			this.startFindDefinitionFromMouse(mouseEvent, withNullAsUndefined(keyboardEvent));
		}));

		this.toUnhook.add(linkGesture.onExecute((mouseEvent: ClickLinkMouseEvent) => {
			if (this.isEnabled(mouseEvent)) {
				this.gotoDefinition(mouseEvent.target.position!, mouseEvent.hasSideBySideModifier).then(() => {
					this.removeLinkDecorations();
				}, (error: Error) => {
					this.removeLinkDecorations();
					onUnexpectedError(error);
				});
			}
		}));

		this.toUnhook.add(linkGesture.onCancel(() => {
			this.removeLinkDecorations();
			this.currentWordAtPosition = null;
		}));
	}

	static get(editor: ICodeEditor): GotoDefinitionAtPositionEditorContribution {
		return editor.getContribution<GotoDefinitionAtPositionEditorContribution>(GotoDefinitionAtPositionEditorContribution.ID);
	}

	startFindDefinitionFromCursor(position: Position) {
		// For issue: https://github.com/microsoft/vscode/issues/46257
		// equivalent to mouse move with meta/ctrl key

		// First find the definition and add decorations
		// to the editor to be shown with the content hover widget
		return this.startFindDefinition(position).then(() => {

			// Add listeners for editor cursor move and key down events
			// Dismiss the "extended" editor decorations when the user hides
			// the hover widget. There is no event for the widget itself so these
			// serve as a best effort. After removing the link decorations, the hover
			// widget is clean and will only show declarations per next request.
			this.toUnhookForKeyboard.add(this.editor.onDidChangeCursorPosition(() => {
				this.currentWordAtPosition = null;
				this.removeLinkDecorations();
				this.toUnhookForKeyboard.clear();
			}));

			this.toUnhookForKeyboard.add(this.editor.onKeyDown((e: IKeyboardEvent) => {
				if (e) {
					this.currentWordAtPosition = null;
					this.removeLinkDecorations();
					this.toUnhookForKeyboard.clear();
				}
			}));
		});
	}

	private startFindDefinitionFromMouse(mouseEvent: ClickLinkMouseEvent, withKey?: ClickLinkKeyboardEvent): void {

		// check if we are active and on a content widget
		if (mouseEvent.target.type === MouseTargetType.CONTENT_WIDGET && this.linkDecorations.length > 0) {
			return;
		}

		if (!this.editor.hasModel() || !this.isEnabled(mouseEvent, withKey)) {
			this.currentWordAtPosition = null;
			this.removeLinkDecorations();
			return;
		}

		const position = mouseEvent.target.position!;

		this.startFindDefinition(position);
	}

	private startFindDefinition(position: Position): Promise<number | undefined> {

		// Dispose listeners for updating decorations when using keyboard to show definition hover
		this.toUnhookForKeyboard.clear();

		// Find word at mouse position
		const word = position ? this.editor.getModel()?.getWordAtPosition(position) : null;
		if (!word) {
			this.currentWordAtPosition = null;
			this.removeLinkDecorations();
			return Promise.resolve(0);
		}

		// Return early if word at position is still the same
		if (this.currentWordAtPosition && this.currentWordAtPosition.startColumn === word.startColumn && this.currentWordAtPosition.endColumn === word.endColumn && this.currentWordAtPosition.word === word.word) {
			return Promise.resolve(0);
		}

		this.currentWordAtPosition = word;

		// Find definition and decorate word if found
		let state = new EditorState(this.editor, CodeEditorStateFlag.Position | CodeEditorStateFlag.Value | CodeEditorStateFlag.Selection | CodeEditorStateFlag.Scroll);

		if (this.previousPromise) {
			this.previousPromise.cancel();
			this.previousPromise = null;
		}

		this.previousPromise = createCancelablePromise(token => this.findDefinition(position, token));

		return this.previousPromise.then(results => {
			if (!results || !results.length || !state.validate(this.editor)) {
				this.removeLinkDecorations();
				return;
			}

			// Multiple results
			if (results.length > 1) {
				this.addDecoration(
					new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn),
					new MarkdownString().appendText(nls.localize('multipleResults', "Click to show {0} definitions.", results.length))
				);
			}

			// Single result
			else {
				let result = results[0];

				if (!result.uri) {
					return;
				}

				this.textModelResolverService.createModelReference(result.uri).then(ref => {

					if (!ref.object || !ref.object.textEditorModel) {
						ref.dispose();
						return;
					}

					const { object: { textEditorModel } } = ref;
					const { startLineNumber } = result.range;

					if (startLineNumber < 1 || startLineNumber > textEditorModel.getLineCount()) {
						// invalid range
						ref.dispose();
						return;
					}

					const previewValue = this.getPreviewValue(textEditorModel, startLineNumber, result);

					let wordRange: Range;
					if (result.originSelectionRange) {
						wordRange = Range.lift(result.originSelectionRange);
					} else {
						wordRange = new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
					}

					const modeId = this.modeService.getModeIdByFilepathOrFirstLine(textEditorModel.uri);
					this.addDecoration(
						wordRange,
						new MarkdownString().appendCodeblock(modeId ? modeId : '', previewValue)
					);
					ref.dispose();
				});
			}
		}).then(undefined, onUnexpectedError);
	}

	private getPreviewValue(textEditorModel: ITextModel, startLineNumber: number, result: LocationLink) {
		let rangeToUse = result.targetSelectionRange ? result.range : this.getPreviewRangeBasedOnBrackets(textEditorModel, startLineNumber);
		const numberOfLinesInRange = rangeToUse.endLineNumber - rangeToUse.startLineNumber;
		if (numberOfLinesInRange >= GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES) {
			rangeToUse = this.getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber);
		}

		const previewValue = this.stripIndentationFromPreviewRange(textEditorModel, startLineNumber, rangeToUse);
		return previewValue;
	}

	private stripIndentationFromPreviewRange(textEditorModel: ITextModel, startLineNumber: number, previewRange: IRange) {
		const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
		let minIndent = startIndent;

		for (let endLineNumber = startLineNumber + 1; endLineNumber < previewRange.endLineNumber; endLineNumber++) {
			const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
			minIndent = Math.min(minIndent, endIndent);
		}

		const previewValue = textEditorModel.getValueInRange(previewRange).replace(new RegExp(`^\\s{${minIndent - 1}}`, 'gm'), '').trim();
		return previewValue;
	}

	private getPreviewRangeBasedOnIndentation(textEditorModel: ITextModel, startLineNumber: number) {
		const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
		const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES);
		let endLineNumber = startLineNumber + 1;

		for (; endLineNumber < maxLineNumber; endLineNumber++) {
			let endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);

			if (startIndent === endIndent) {
				break;
			}
		}

		return new Range(startLineNumber, 1, endLineNumber + 1, 1);
	}

	private getPreviewRangeBasedOnBrackets(textEditorModel: ITextModel, startLineNumber: number) {
		const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES);

		const brackets: IFoundBracket[] = [];

		let ignoreFirstEmpty = true;
		let currentBracket = textEditorModel.findNextBracket(new Position(startLineNumber, 1));
		while (currentBracket !== null) {

			if (brackets.length === 0) {
				brackets.push(currentBracket);
			} else {
				const lastBracket = brackets[brackets.length - 1];
				if (lastBracket.open[0] === currentBracket.open[0] && lastBracket.isOpen && !currentBracket.isOpen) {
					brackets.pop();
				} else {
					brackets.push(currentBracket);
				}

				if (brackets.length === 0) {
					if (ignoreFirstEmpty) {
						ignoreFirstEmpty = false;
					} else {
						return new Range(startLineNumber, 1, currentBracket.range.endLineNumber + 1, 1);
					}
				}
			}

			const maxColumn = textEditorModel.getLineMaxColumn(startLineNumber);
			let nextLineNumber = currentBracket.range.endLineNumber;
			let nextColumn = currentBracket.range.endColumn;
			if (maxColumn === currentBracket.range.endColumn) {
				nextLineNumber++;
				nextColumn = 1;
			}

			if (nextLineNumber > maxLineNumber) {
				return new Range(startLineNumber, 1, maxLineNumber + 1, 1);
			}

			currentBracket = textEditorModel.findNextBracket(new Position(nextLineNumber, nextColumn));
		}

		return new Range(startLineNumber, 1, maxLineNumber + 1, 1);
	}

	private addDecoration(range: Range, hoverMessage: MarkdownString): void {

		const newDecorations: IModelDeltaDecoration = {
			range: range,
			options: {
				inlineClassName: 'goto-definition-link',
				hoverMessage
			}
		};

		this.linkDecorations = this.editor.deltaDecorations(this.linkDecorations, [newDecorations]);
	}

	private removeLinkDecorations(): void {
		if (this.linkDecorations.length > 0) {
			this.linkDecorations = this.editor.deltaDecorations(this.linkDecorations, []);
		}
	}

	private isEnabled(mouseEvent: ClickLinkMouseEvent, withKey?: ClickLinkKeyboardEvent): boolean {
		return this.editor.hasModel() &&
			mouseEvent.isNoneOrSingleMouseDown &&
			(mouseEvent.target.type === MouseTargetType.CONTENT_TEXT) &&
			(mouseEvent.hasTriggerModifier || (withKey ? withKey.keyCodeIsTriggerKey : false)) &&
			DefinitionProviderRegistry.has(this.editor.getModel());
	}

	private findDefinition(position: Position, token: CancellationToken): Promise<LocationLink[] | null> {
		const model = this.editor.getModel();
		if (!model) {
			return Promise.resolve(null);
		}

		return getDefinitionsAtPosition(model, position, token);
	}

	private gotoDefinition(position: Position, openToSide: boolean): Promise<any> {
		this.editor.setPosition(position);
		return this.editor.invokeWithinContext((accessor) => {
			const canPeek = !openToSide && this.editor.getOption(EditorOption.definitionLinkOpensInPeek) && !this.isInPeekEditor(accessor);
			const action = new DefinitionAction({ openToSide, openInPeek: canPeek, muteMessage: true }, { alias: '', label: '', id: '', precondition: undefined });
			return action.run(accessor, this.editor);
		});
	}

	private isInPeekEditor(accessor: ServicesAccessor): boolean | undefined {
		const contextKeyService = accessor.get(IContextKeyService);
		return PeekContext.inPeekEditor.getValue(contextKeyService);
	}

	public dispose(): void {
		this.toUnhook.dispose();
	}
}

registerEditorContribution(GotoDefinitionAtPositionEditorContribution.ID, GotoDefinitionAtPositionEditorContribution);

registerThemingParticipant((theme, collector) => {
	const activeLinkForeground = theme.getColor(editorActiveLinkForeground);
	if (activeLinkForeground) {
		collector.addRule(`.monaco-editor .goto-definition-link { color: ${activeLinkForeground} !important; }`);
	}
});


text:
/* Author: Ioan Sucan */

#include <moveit/background_processing/background_processing.h>
#include <ros/console.h>

namespace moveit
{
namespace tools
{
BackgroundProcessing::BackgroundProcessing()
{
  // spin a thread that will process user events
  run_processing_thread_ = true;
  processing_ = false;
  processing_thread_ = std::make_unique<boost::thread>([this] { processingThread(); });
}

BackgroundProcessing::~BackgroundProcessing()
{
  run_processing_thread_ = false;
  new_action_condition_.notify_all();
  processing_thread_->join();
}

void BackgroundProcessing::processingThread()
{
  boost::unique_lock<boost::mutex> ulock(action_lock_);

  while (run_processing_thread_)
  {
    while (actions_.empty() && run_processing_thread_)
      new_action_condition_.wait(ulock);

    while (!actions_.empty())
    {
      JobCallback fn = actions_.front();
      std::string action_name = action_names_.front();
      actions_.pop_front();
      action_names_.pop_front();
      processing_ = true;

      // make sure we are unlocked while we process the event
      action_lock_.unlock();
      try
      {
        ROS_DEBUG_NAMED("background_processing", "Begin executing '%s'", action_name.c_str());
        fn();
        ROS_DEBUG_NAMED("background_processing", "Done executing '%s'", action_name.c_str());
      }
      catch (std::exception& ex)
      {
        ROS_ERROR_NAMED("background_processing", "Exception caught while processing action '%s': %s",
                        action_name.c_str(), ex.what());
      }
      processing_ = false;
      if (queue_change_event_)
        queue_change_event_(COMPLETE, action_name);
      action_lock_.lock();
    }
  }
}

void BackgroundProcessing::addJob(const boost::function<void()>& job, const std::string& name)
{
  {
    boost::mutex::scoped_lock _(action_lock_);
    actions_.push_back(job);
    action_names_.push_back(name);
    new_action_condition_.notify_all();
  }
  if (queue_change_event_)
    queue_change_event_(ADD, name);
}

void BackgroundProcessing::clear()
{
  bool update = false;
  std::deque<std::string> removed;
  {
    boost::mutex::scoped_lock _(action_lock_);
    update = !actions_.empty();
    actions_.clear();
    action_names_.swap(removed);
  }
  if (update && queue_change_event_)
    for (const std::string& it : removed)
      queue_change_event_(REMOVE, it);
}

std::size_t BackgroundProcessing::getJobCount() const
{
  boost::mutex::scoped_lock _(action_lock_);
  return actions_.size() + (processing_ ? 1 : 0);
}

void BackgroundProcessing::setJobUpdateEvent(const JobUpdateCallback& event)
{
  boost::mutex::scoped_lock _(action_lock_);
  queue_change_event_ = event;
}

void BackgroundProcessing::clearJobUpdateEvent()
{
  setJobUpdateEvent(JobUpdateCallback());
}

}  // end of namespace tools
}  // end of namespace moveit

redpajama_set_name: RedPajamaGithub


text:
package org.red5.server.script;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple script engine tests. Some of the hello world scripts found here:
 * http://www.roesler-ac.de/wolfram/hello.htm
 *
 * @author paul.gregoire
 */
public class ScriptEngineTest {

	private static final Logger log = LoggerFactory.getLogger(ScriptEngineTest.class);

	// ScriptEngine manager
	private static boolean java15;

	private static ScriptEngineManager mgr;

	public ScriptEngineTest() {
		String javaVersion = System.getProperty("java.version");
		String javaMajorRev = javaVersion.substring(0, 3);
		if (javaVersion != null && javaMajorRev.compareTo("1.5") == 0) {
			//should disable tests
			java15 = true;
		} else {
			java15 = false;
			mgr = new ScriptEngineManager();
		}
	}

	// Javascript
	@Test
	public void testJavascriptHelloWorld() {
		if (java15) {
			return;
		}
		ScriptEngine jsEngine = null;
		for (ScriptEngineFactory factory : mgr.getEngineFactories()) {
			if (factory.getEngineName().toLowerCase().matches(".*(rhino|javascript|ecma).*")) {
				jsEngine = factory.getScriptEngine();
			}
		}
		if (null == jsEngine) {
			log.error("Javascript is not supported in this build");
		}
		try {
			jsEngine.eval("print('Javascript - Hello, world!\\n')");
		} catch (Throwable ex) {
			System.err.println("Get by name failed for: javascript");
		}
	}

	// Ruby
	@Test
	@Ignore
	public void testRubyHelloWorld() {
		if (java15) {
			return;
		}
		ScriptEngine rbEngine = mgr.getEngineByName("ruby");
		if (rbEngine == null) {
			rbEngine = mgr.getEngineByExtension("rb");
		}
		try {
			rbEngine.eval("puts 'Ruby - Hello, world!'");
		} catch (Exception ex) {
			ex.printStackTrace();
			assertFalse(true);
		}
	}

	// Python
	@Test
	@Ignore
	// Python support seems to not be in tree anymore; aclarke 2008-10-01
	public void testPythonHelloWorld() {
		if (java15) {
			return;
		}
		ScriptEngine pyEngine = mgr.getEngineByName("python");
		try {
			pyEngine.eval("print \"Python - Hello, world!\"");
		} catch (Exception ex) {
			//ex.printStackTrace();
			fail("could not start Python");
		}
	}

	// Groovy
	@Test
	public void testGroovyHelloWorld() {
		if (java15) {
			return;
		}
		ScriptEngine gvyEngine = mgr.getEngineByName("groovy");
		try {
			gvyEngine.eval("println  \"Groovy - Hello, world!\"");
		} catch (Exception ex) {
			//ex.printStackTrace();
			assertFalse(true);
		}
	}

	// Judoscript
	//	@Test
	//	public void testJudoscriptHelloWorld() {
	//		ScriptEngine jdEngine = mgr.getEngineByName("judo");
	//		try {
	//			jdEngine.eval(". \'Judoscript - Hello World\';");
	//		} catch (Exception ex) {
	//			//ex.printStackTrace();
	//			assertFalse(true);
	//		}
	//	}

	// Haskell
	// @Test
	// public void testHaskellHelloWorld()
	// {
	// ScriptEngine hkEngine = mgr.getEngineByName("jaskell");
	// try
	// {
	// StringBuilder sb = new StringBuilder();
	// sb.append("module Hello where ");
	// sb.append("hello::String ");
	// sb.append("hello = 'Haskell - Hello World!'");
	// hkEngine.eval(sb.toString());
	// }
	// catch (Exception ex)
	// {
	// //ex.printStackTrace();
	// assertFalse(true);
	// }
	// }

	// Tcl
	//	@Test
	//	public void testTclHelloWorld() {
	//		ScriptEngine tEngine = mgr.getEngineByName("tcl");
	//		try {
	//			StringBuilder sb = new StringBuilder();
	//			sb.append("#!/usr/local/bin/tclsh\n");
	//			sb.append("puts \"Tcl - Hello World!\"");
	//			tEngine.eval(sb.toString());
	//		} catch (Exception ex) {
	//			//ex.printStackTrace();
	//			assertFalse(true);
	//		}
	//	}

	// Awk
	// @Test
	// public void testAwkHelloWorld()
	// {
	// ScriptEngine aEngine = mgr.getEngineByName("awk");
	// try
	// {
	// StringBuilder sb = new StringBuilder();
	// sb.append("BEGIN { print 'Awk - Hello World!' } END");
	// aEngine.eval(sb.toString());
	// }
	// catch (Exception ex)
	// {
	// //ex.printStackTrace();
	// assertFalse(true);
	// }
	// }

	// E4X
	//	@Test
	//	public void testE4XHelloWorld() {
	//		ScriptEngine eEngine = mgr.getEngineByName("rhino");
	//		try {
	//			//Compilable compiler = (Compilable) eEngine;
	//			//CompiledScript script = compiler.compile("var d = new XML('<d><item>Hello</item><item>World!</item></d>');print(d..item);");
	//			//Namespace ns = eEngine.createNamespace();
	//			//ns.put('d', "new XML('<d><item>Hello</item><item>World!</item></d>');");
	//			//System.out.println("E4X - " + script.eval(ns));
	//			eEngine
	//					.eval("var d = new XML('<d><item>Hello</item><item>World!</item></d>');print('E4X - ' + d..item);");
	//		} catch (Exception ex) {
	//			//ex.printStackTrace();
	//			assertFalse(true);
	//		}
	//	}

	// PHP
	// @Test
	// public void testPHPHelloWorld()
	// {
	// //have to add php lib to java env
	// //java.library.path
	// //System.setProperty("java.library.path", "C:\\PHP;" +
	// System.getProperty("java.library.path"));
	// ScriptEngine pEngine = mgr.getEngineByName("php");
	// try
	// {
	// pEngine.eval("<? echo 'PHP - Hello World'; ?>");
	// }
	// catch (Exception ex)
	// {
	// //ex.printStackTrace();
	// assertFalse(true);
	// }
	// }

	// @Test
	// public void testE4X()
	// {
	// // Javascript
	// ScriptEngine jsEngine = mgr.getEngineByName("rhino");
	// try
	// {
	// System.out.println("Engine: " + jsEngine.getClass().getName());
	// jsEngine.eval(new FileReader("samples/E4X/e4x_example.js"));
	// }
	// catch (Exception ex)
	// {
	// //ex.printStackTrace();
	// assertFalse(true);
	// }
	// }

	//	@Test
	//	public void testJavascriptApplication() {
	//		ScriptEngine jsEngine = mgr.getEngineByName("rhino");
	//		try {
	//			// jsEngine.eval(new FileReader("samples/application.js"));
	//			jsEngine.eval(new FileReader("samples/application2.js"));
	//		} catch (Exception ex) {
	//			//ex.printStackTrace();
	//			assertFalse(true);
	//		}
	//	}
	//
	//	@Test
	//	public void testRubyApplication() {
	//		ScriptEngine rbEngine = mgr.getEngineByName("ruby");
	//		try {
	//			rbEngine.eval(new FileReader("samples/application.rb"));
	//		} catch (Exception ex) {
	//			//ex.printStackTrace();
	//			assertFalse(true);
	//		}
	//	}
	//
	//	@Test
	//	public void testGroovyApplication() {
	//		ScriptEngine gvyEngine = mgr.getEngineByName("groovy");
	//		try {
	//			gvyEngine.eval(new FileReader("samples/application.groovy"));
	//			// gvyEngine.eval("def ap = new Application();println
	//			// ap.toString();");
	//		} catch (Exception ex) {
	//			//ex.printStackTrace();
	//			assertFalse(true);
	//		}
	//	}

	@Test
	public void testEngines() {
		if (java15)
			return;
		Map<String, ScriptEngineFactory> engineFactories = new HashMap<String, ScriptEngineFactory>(7);
		//List<ScriptEngineFactory> factories = mgr.getEngineFactories(); //jdk6
		//ScriptEngineFactory[] factories = mgr.getEngineFactories(); //jdk5
		for (ScriptEngineFactory factory : mgr.getEngineFactories()) {
			try {
				System.out.println("\n--------------------------------------------------------------");
				String engName = factory.getEngineName();
				String engVersion = factory.getEngineVersion();
				String langName = factory.getLanguageName();
				String langVersion = factory.getLanguageVersion();
				System.out.printf("Script Engine: %s (%s) Language: %s (%s)", engName, engVersion, langName, langVersion);
				engineFactories.put(engName, factory);
				System.out.print("\nEngine Alias(es):");
				for (String name : factory.getNames()) {
					System.out.printf("%s ", name);
				}
				System.out.printf("\nExtension: ");
				for (String name : factory.getExtensions()) {
					System.out.printf("%s ", name);
				}
			} catch (Throwable e) {
				log.error("{}", e);
			}
		}
	}

}


text:
module API
  # Git Tags API
  class Tags < Grape::API
    before { authenticate! }
    before { authorize! :download_code, user_project }

    resource :projects do
      # Get a project repository tags
      #
      # Parameters:
      #   id (required) - The ID of a project
      # Example Request:
      #   GET /projects/:id/repository/tags
      get ":id/repository/tags" do
        present user_project.repo.tags.sort_by(&:name).reverse,
                with: Entities::RepoTag, project: user_project
      end

      # Create tag
      #
      # Parameters:
      #   id (required) - The ID of a project
      #   tag_name (required) - The name of the tag
      #   ref (required) - Create tag from commit sha or branch
      #   message (optional) - Specifying a message creates an annotated tag.
      # Example Request:
      #   POST /projects/:id/repository/tags
      post ':id/repository/tags' do
        authorize_push_project
        message = params[:message] || nil
        result = CreateTagService.new(user_project, current_user).
          execute(params[:tag_name], params[:ref], message, params[:release_description])

        if result[:status] == :success
          present result[:tag],
                  with: Entities::RepoTag,
                  project: user_project
        else
          render_api_error!(result[:message], 400)
        end
      end

      # Add release notes to tag
      #
      # Parameters:
      #   id (required) - The ID of a project
      #   tag (required) - The name of the tag
      #   description (required) - Release notes with markdown support
      # Example Request:
      #   PUT /projects/:id/repository/tags
      put ':id/repository/:tag/release', requirements: { tag: /.*/ } do
        authorize_push_project
        required_attributes! [:description]
        release = user_project.releases.find_or_initialize_by(tag: params[:tag])
        release.update_attributes(description: params[:description])

        present release, with: Entities::Release
      end
    end
  end
end


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.Maps.Routing.Models
{
    public partial class RouteMatrixSummary
    {
        internal static RouteMatrixSummary DeserializeRouteMatrixSummary(JsonElement element)
        {
            Optional<int> successfulRoutes = default;
            Optional<int> totalRoutes = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("successfulRoutes"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    successfulRoutes = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("totalRoutes"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    totalRoutes = property.Value.GetInt32();
                    continue;
                }
            }
            return new RouteMatrixSummary(Optional.ToNullable(successfulRoutes), Optional.ToNullable(totalRoutes));
        }
    }
}


text:
<title>strcpy - Untitled</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Untitled">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Strings.html#Strings" title="Strings">
<link rel="prev" href="strcoll.html#strcoll" title="strcoll">
<link rel="next" href="strcspn.html#strcspn" title="strcspn">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<meta http-equiv="Content-Style-Type" content="text/css">

Next: strcspn,
Previous: strcoll,
Up: Strings

5.25 strcpy—copy string

Synopsis

     #include <string.h>
     char *strcpy(char *<var>dst</var>, const char *<var>src</var>);

Description

strcpy copies the string pointed to by <var>src</var>
(including the terminating null character) to the array
pointed to by <var>dst</var>.

Returns

This function returns the initial value of <var>dst</var>.

Portability

strcpy is ANSI C.

strcpy requires no supporting OS subroutines.


text:
from numpy import *
from scipy.linalg import qr,inv,sqrtm,eigh,norm
from scipy.sparse import diags
from scipy.sparse.linalg import eigs
from matplotlib.pyplot import *
import scipy.sparse as sps
import time,pdb

__all__=['icgs','construct_tridmat','tridiagonalize','tridiagonalize_sqrtm','tridiagonalize_qr','tridiagonalize_mpqr','tridiagonalize_mp']

def icgs(u,Q,M=None,return_norm=False,maxiter=3):
    '''
    Iterative Classical M-orthogonal Gram-Schmidt orthogonalization.

    Parameters:
        :u: vector, the column vector to be orthogonalized.
        :Q: matrix, the search space.
        :M: matrix/None, the matrix, if provided, perform M-orthogonal.
        :return_norm: bool, return the norm of u.
        :maxiter: int, the maximum number of iteractions.

    Return:
        vector, orthogonalized vector u.
    '''
    assert(ndim(u)==2)
    uH,QH=u.T.conj(),Q.T.conj()
    alpha=0.5
    it=1
    Mu=M.dot(u) if M is not None else u
    r_pre=norm(uH.dot(Mu))
    for it in range(maxiter):
        u=u-Q.dot(QH.dot(Mu))
        Mu=M.dot(u) if M is not None else u
        r1=norm(uH.dot(Mu))
        if r1>alpha*r_pre:
            break
        r_pre=r1
    if r1<=alpha*r_pre:
        warnings.warn('loss of orthogonality @icgs.')
    return (u,r1) if return_norm else u

def tridiagonalize(A, q, m=None,getbasis=False):
    """
    Use m steps of the lanczos algorithm starting with q to generate
    the tridiagonal form of this matrix(The traditional scalar version).

    Parameters:
        :A: A sparse hermitian matrix.
        :q: The starting vector.
        :m: The steps to run.
        :getbasis: Return basis vectors if True.

    Return:
        Tridiagonal part elements (data,offset),
        | data -> (lower part, middle part, upper part)
        | offset -> (-1, 0, 1) to indicate the value of (j-i) of specific data with i,j the matrix element indices.

    To construct the matrix, set the block-matrix elements with block indices j-i == offset[k] to data[k].
    This is exactly what `construct_tridmat` function do.

    **Note:** The initial vector q will be renormalized to guarant the correctness of result,
    """
    if sps.issparse(A): A=A.toarray()
    if m==None:
        m=A.shape[0]

    #initialize states
    qq=q/sqrt(dot(q,q))
    Q=qq[...,newaxis]
    alpha=[]
    beta=[]

    #run steps
    for i in range(m):
        Q_=Q[:,i]
        z = A.dot(Q_)
        alpha_i = dot(conj(z), Q_)
        tmp = dot(conj(Q.T), z)
        tmp = dot(Q, tmp)
        z = z - tmp
        beta_i = sqrt(dot(conj(z),z))
        alpha.append(alpha_i)
        beta.append(beta_i.item())
        if i==m-1: break
        z=z/beta_i
        Q_i=icgs(z[:,newaxis],Q)
        Q=append(Q,Q_i,axis=-1)
    Bl=array(beta[0:m-1])
    if A.shape[0]==1:
        data = array([zeros(0),alpha,zeros(0)])
    else:
        data = array([conj(Bl), alpha, Bl])
    offsets = array([-1, 0, 1])
    if not getbasis:
        return data,offsets
    else:
        return data,offsets,Q

def tridiagonalize_sqrtm(A,q,m=None,getbasis=False):
    """
    Use block lanczos algorithm to generate the tridiagonal part of matrix.
    This is the symmetric version of block-tridiagonalization in contrast to `qr` version.
    However, only matrices with blocksize p = 2 are currently supported.

    Parameters:
        :A: A sparse Hermitian matrix.
        :q: The starting columnwise orthogonal vector q with shape (n*p,p) with p the block size and n the number of blocks.
        :m: the steps to run.
        :getbasis: Return basis vectors if True.

    Return:
        Tridiagonal part elements (data,offset),
        | data -> (lower part, middle part, upper part)
        | offset -> (-1, 0, 1) to indicate the value of (j-i) of specific data with i,j the matrix element indices.

        To construct the matrix, set the block-matrix elements with block indices j-i == offset[k] to data[k].
        This is exactly what `construct_tridmat` function do.

        **Note:** The orthogonality of initial vector q will be re-inforced to guarant the convergent result,
        meanwhile, the orthogonality of starting vector is also checked.
    """
    n=q.shape[1]
    if sps.issparse(A): A=A.toarray()
    if m==None:
        m=A.shape[0]/n

    #check for othogonality of `q vector`.
    if not allclose(q.T.conj().dot(q),identity(q.shape[1])):
        raise Exception('Error','Othogoanlity check for start vector q failed.')
    #reinforce the orthogonality.
    Q=qr(q,mode='economic')[0]

    #initialize states
    alpha=[]
    beta=[]

    #run steps
    for i in range(m):
        qi_1=Q[:,(i-1)*n:(i+1)*n]
        qi=Q[:,i*n:i*n+n]

        z=A.dot(qi)
        ai=dot(z.T.conj(),qi)
        tmp=dot(qi_1.T.conj(),z)
        tmp=dot(qi_1,tmp)
        z=z-tmp
        bi=sqrtm(dot(z.T.conj(),z))
        alpha.append(ai)
        beta.append(bi)

        if i==m-1: break
        z=dot(z,inv(bi))
        Q_i=icgs(z,Q)
        Q=append(Q,Q_i,axis=-1)
        if sum(abs(bi))<1e-20:
            print('Warning! bad krylov space!')

    Bl=array(beta[:m-1])
    if q.shape[0]/n==1:
        BTl=zeros(0)
    else:
        BTl=swapaxes(Bl,1,2).conj()
    data = array([BTl, alpha, Bl])
    offsets = array([-1, 0, 1])
    if not getbasis:
        return data,offsets
    else:
        return data,offsets,Q

def tridiagonalize_qr(A,q,m=None):
    """
    Use m steps of the lanczos algorithm starting with q - the block QR decomposition version.

    Parameters:
        :A: A sparse Hermitian matrix.
        :q: The starting columnwise orthogonal vector q with shape (n*p,p) with p the block size and n the number of blocks.
        :m: The number of iteractions.

    Return:
        Tridiagonal part elements (data,offset),
        | data -> (lower part, middle part, upper part)
        | offset -> (-1, 0, 1) to indicate the value of (j-i) of specific data with i,j the matrix element indices.

        To construct the matrix, set the block-matrix elements with block indices j-i == offset[k] to data[k].
        This is exactly what `construct_tridmat` function do.

        **Note:** The orthogonality of initial vector q will be re-inforced to guarant the convergent result,
        meanwhile, the orthogonality of starting vector is also checked.
    """
    n=q.shape[1]
    if sps.issparse(A): A=A.toarray()
    if m==None:
        m=A.shape[0]/n

    #check for othogonality of original `q vector`.
    if not allclose(q.T.conj().dot(q),identity(n)):
        raise Exception('Error','Othogoanlity check for starting vector q failed.')

    Al=[]
    Bl=[zeros([n,n])]
    Ql=concatenate([zeros(q.shape),q],axis=-1)
    #run steps
    for i in range(m):
        U_i=A.dot(Ql[:,-n:])-dot(Ql[:,-2*n:-n],Bl[-1].T.conj())
        A_i=dot(Ql[:,-n:].T.conj(),U_i)
        R_i=U_i-dot(Ql[:,-n:],A_i)
        Q_i,B_i=qr(R_i,mode='economic')
        Al.append(A_i)
        Bl.append(B_i)

        #reinforce orthorgonality, Q_i orth- Q
        Q_i=icgs(Q_i,Ql[:,n:],return_norm=False)
        Ql=concatenate([Ql,Q_i],axis=1)
        if i!=m-1 and sum(abs(B_i))<1e-20:
            print('Warning! bad krylov space!')

    Bl=array(Bl[1:m])
    if q.shape[0]/n==1:
        BTl=zeros(0)
    else:
        BTl=swapaxes(Bl,1,2).conj()
    data = array([Bl, Al, BTl])
    offset = array([-1, 0, 1])
    return data,offset

def construct_tridmat(data,offset):
    '''
    Construct tridiagonal matrix.

    Parameters:
        :data: The datas of lower, middle, upper tridiagonal part.
        :offset: The offsets indicating the position of datas.

    Return:
        2D sparse matrix, use res.toarray() to get a dense array.
    '''
    n=len(data[1])
    if ndim(data[1])==1:
        p=1
    else:
        p=len(data[1][0])
    N=n*p
    B=ndarray([n,n],dtype='O')
    #fill datas
    for i in range(n):
        for j in range(n):
            for k in range(3):
                if j-i==offset[k]:
                    B[i,j]=complex128(data[offset[k]+1][min(i,j)])
    B=sps.bmat(B)
    return B

def tridiagonalize_mp(A, q, m=None,prec=5000,getbasis=False):
    """
    Use m steps of the lanczos algorithm starting with q to generate
    the tridiagonal form of this matrix(The traditional scalar version).

    Parameters:
        :A: A sparse hermitian matrix.
        :q: The starting vector.
        :m: The steps to run.
        :prec: The precision in bit, `None` for double precision.
        :getbasis: Return basis vectors if True.

    Return:
        Tridiagonal part elements (data,offset),
        | data -> (lower part, middle part, upper part)
        | offset -> (-1, 0, 1) to indicate the value of (j-i) of specific data with i,j the matrix element indices.

    To construct the matrix, set the block-matrix elements with block indices j-i == offset[k] to data[k].
    This is exactly what `construct_tridmat` function do.

    **Note:** The initial vector q will be renormalized to guarant the correctness of result,
    """
    import gmpy2
    from .mplib import mpqr,mpconj
    gmpy2.get_context().precision=prec
    lin={'conj':mpconj,'tocomplex':vectorize(gmpy2.mpc),'sqrt':vectorize(gmpy2.sqrt)}
    if sps.issparse(A): A=A.toarray()
    if m==None:
        m=A.shape[0]

    #initialize states
    qq=q/lin['sqrt'](dot(q,q))
    Q=qq[...,newaxis]
    alpha=[]
    beta=[]

    #run steps
    for i in range(m):
        Q_=Q[:,i]
        z = A.dot(Q_)
        alpha_i = dot(lin['conj'](z), Q_)
        tmp = dot(lin['conj'](Q.T), z)
        tmp = dot(Q, tmp)
        z = z - tmp
        beta_i = lin['sqrt'](dot(lin['conj'](z),z))
        z=z/beta_i

        alpha.append(alpha_i)
        beta.append(beta_i.item())
        Q=append(Q,z[...,newaxis],axis=-1)
    Bl=array(beta[0:m-1])
    if A.shape[0]==1:
        data = array([zeros(0),alpha,zeros(0)])
    else:
        data = array([lin['conj'](Bl), alpha, Bl])
    offsets = array([-1, 0, 1])
    if not getbasis:
        return data,offsets
    else:
        return data,offsets,Q

def tridiagonalize_mpqr(A,q,m=None,prec=5000):
    """
    High precision version of block tridiagonalization.
    Use m steps of the lanczos algorithm starting with q - the block QR decomposition version.

    Parameters:
        :A: matrix, Hermitian matrix.
        :q: 1d array, starting columnwise orthogonal vector q with shape (n*p,p) with p the block size and n the number of blocks.
        :m: int, number of iteractions.
        :prec: int, precision in bits

    Return:
        Tridiagonal part elements (data,offset),
        | data -> (lower part, middle part, upper part)
        | offset -> (-1, 0, 1) to indicate the value of (j-i) of specific data with i,j the matrix element indices.

        To construct the matrix, set the block-matrix elements with block indices j-i == offset[k] to data[k].
        This is exactly what `construct_tridmat` function do.

        **Note:** The orthogonality of initial vector q will be re-inforced to guarant the convergent result,
        meanwhile, the orthogonality of starting vector is also checked.
    """
    #setup environment
    import gmpy2
    from .mplib import mpqr,mpconj
    gmpy2.get_context().precision=prec
    lin={'conj':mpconj,'qr':mpqr,'tocomplex':vectorize(gmpy2.mpc)}

    n=q.shape[1]
    if sps.issparse(A): A=A.toarray()
    if m==None:
        m=A.shape[0]/n
    A=lin['tocomplex'](A)

    #check and reinforce the orthogonality.
    if not allclose(complex128(q).T.conj().dot(complex128(q)),identity(q.shape[1])):
        raise Exception('Error','Othogoanlity check for start vector q failed.')
    Q=lin['qr'](q)[0]

    Al=[]
    Bl=[zeros([n,n])]
    Ql=[zeros(Q.shape),Q]
    #run steps
    for i in range(m):
        U_i=A.dot(Ql[-1])-dot(Ql[-2],lin['conj'](Bl[-1].T))
        A_i=dot(lin['conj'](Ql[-1].T),U_i)
        R_i=U_i-dot(Ql[-1],A_i)
        Q_i,B_i=lin['qr'](R_i)
        Al.append(A_i)
        Bl.append(B_i)
        Ql.append(Q_i)
        if i!=m-1 and sum(abs(B_i))<1e-20:
            print('Warning! bad krylov space!')

    Bl=array(Bl[1:m])
    if q.shape[0]/n==1:
        BTl=zeros(0)
    else:
        BTl=lin['conj'](swapaxes(Bl,1,2))
    data = array([Bl, Al, BTl])
    offset = array([-1, 0, 1])
    return data,offset


text:
""" ./examples/attachment/attachment_step.rst """

from hamcrest import assert_that
from allure_commons_test.report import has_test_case
from allure_commons_test.result import has_step
from allure_commons_test.result import has_attachment

def test_step_with_attachment(executed_docstring_path):
    assert_that(executed_docstring_path.allure_report,
                has_test_case("test_step_with_attachment",
                              has_step("step_with_attachment",
                                       has_attachment()
                                       ),
                              )
                )

def test_step_with_thread_and_attachment(allured_testdir):
    allured_testdir.testdir.makepyfile(
        """
    from concurrent.futures import ThreadPoolExecutor

    import allure
    import pytest

    @allure.step("thread {x}")
    def parallel_step(x=1):
        allure.attach("text", str(x), allure.attachment_type.TEXT)

    def test_thread():
        with allure.step("Start in thread"):
            with ThreadPoolExecutor(max_workers=2) as executor:
                f_result = executor.map(parallel_step, [1, 2])
    """
    )

    allured_testdir.run_with_allure()

    assert_that(allured_testdir.allure_report,
                has_test_case("test_thread",
                              has_step("Start in thread",
                                       has_step("thread 1", has_attachment(name="1")),
                                       has_step("thread 2", has_attachment(name="2")),
                                       )
                              )
                )


text:
import argparse

import chainer
import chainer.cuda
import chainer.functions as F
import chainer.links as L
from chainer import training
from chainer.training import extensions

import chainermn
import chainermn.datasets
import chainermn.functions

chainer.disable_experimental_feature_warning = True

class MLP0SubA(chainer.Chain):
    def __init__(self, comm, n_out):
        super(MLP0SubA, self).__init__(
            l1=L.Linear(784, n_out))

    def __call__(self, x):
        return F.relu(self.l1(x))

class MLP0SubB(chainer.Chain):
    def __init__(self, comm):
        super(MLP0SubB, self).__init__()

    def __call__(self, y):
        return y

class MLP0(chainermn.MultiNodeChainList):
    # Model on worker 0.
    def __init__(self, comm, n_out):
        super(MLP0, self).__init__(comm=comm)
        self.add_link(MLP0SubA(comm, n_out), rank_in=None, rank_out=1)
        self.add_link(MLP0SubB(comm), rank_in=1, rank_out=None)

class MLP1Sub(chainer.Chain):
    def __init__(self, n_units, n_out):
        super(MLP1Sub, self).__init__(
            l2=L.Linear(None, n_units),
            l3=L.Linear(None, n_out))

    def __call__(self, h0):
        h1 = F.relu(self.l2(h0))
        return self.l3(h1)

class MLP1(chainermn.MultiNodeChainList):
    # Model on worker 1.
    def __init__(self, comm, n_units, n_out):
        super(MLP1, self).__init__(comm=comm)
        self.add_link(MLP1Sub(n_units, n_out), rank_in=0, rank_out=0)

def main():
    parser = argparse.ArgumentParser(
        description='ChainerMN example: pipelined neural network')
    parser.add_argument('--batchsize', '-b', type=int, default=100,
                        help='Number of images in each mini-batch')
    parser.add_argument('--epoch', '-e', type=int, default=20,
                        help='Number of sweeps over the dataset to train')
    parser.add_argument('--gpu', '-g', action='store_true',
                        help='Use GPU')
    parser.add_argument('--out', '-o', default='result',
                        help='Directory to output the result')
    parser.add_argument('--unit', '-u', type=int, default=1000,
                        help='Number of units')
    args = parser.parse_args()

    # Prepare ChainerMN communicator.
    if args.gpu:
        comm = chainermn.create_communicator('pure_nccl')
        data_axis, model_axis = comm.rank % 2, comm.rank // 2
        data_comm = comm.split(data_axis, comm.rank)
        model_comm = comm.split(model_axis, comm.rank)
        device = comm.intra_rank
    else:
        comm = chainermn.create_communicator('naive')
        data_axis, model_axis = comm.rank % 2, comm.rank // 2
        data_comm = comm.split(data_axis, comm.rank)
        model_comm = comm.split(model_axis, comm.rank)
        device = -1

    if model_comm.size != 2:
        raise ValueError(
            'This example can only be executed on the even number '
            'of processes.')

    if comm.rank == 0:
        print('==========================================')
        if args.gpu:
            print('Using GPUs')
        print('Num unit: {}'.format(args.unit))
        print('Num Minibatch-size: {}'.format(args.batchsize))
        print('Num epoch: {}'.format(args.epoch))
        print('==========================================')

    if data_axis == 0:
        model = L.Classifier(MLP0(model_comm, args.unit))
    elif data_axis == 1:
        model = MLP1(model_comm, args.unit, 10)

    if device >= 0:
        chainer.cuda.get_device_from_id(device).use()
        model.to_gpu()

    optimizer = chainermn.create_multi_node_optimizer(
        chainer.optimizers.Adam(), data_comm)
    optimizer.setup(model)

    # Original dataset on worker 0 and 1.
    # Datasets of worker 0 and 1 are split and distributed to all workers.
    if model_axis == 0:
        train, test = chainer.datasets.get_mnist()
        if data_axis == 1:
            train = chainermn.datasets.create_empty_dataset(train)
            test = chainermn.datasets.create_empty_dataset(test)
    else:
        train, test = None, None
    train = chainermn.scatter_dataset(train, data_comm, shuffle=True)
    test = chainermn.scatter_dataset(test, data_comm, shuffle=True)

    train_iter = chainer.iterators.SerialIterator(
        train, args.batchsize, shuffle=False)
    test_iter = chainer.iterators.SerialIterator(
        test, args.batchsize, repeat=False, shuffle=False)

    updater = training.StandardUpdater(train_iter, optimizer, device=device)
    trainer = training.Trainer(updater, (args.epoch, 'epoch'), out=args.out)
    evaluator = extensions.Evaluator(test_iter, model, device=device)
    evaluator = chainermn.create_multi_node_evaluator(evaluator, data_comm)
    trainer.extend(evaluator)

    # Some display and output extensions are necessary only for worker 0.
    if comm.rank == 0:
        trainer.extend(extensions.DumpGraph('main/loss'))
        trainer.extend(extensions.LogReport())
        trainer.extend(extensions.PrintReport(
            ['epoch', 'main/loss', 'validation/main/loss',
             'main/accuracy', 'validation/main/accuracy', 'elapsed_time']))
        trainer.extend(extensions.ProgressBar())

    trainer.run()

if __name__ == '__main__':
    main()


text:
package metadata

import (
	"fmt"
	"net"
	"regexp"
	"strconv"
	"strings"

	"github.com/hashicorp/go-version"
	"github.com/hashicorp/serf/serf"
)

// Key is used in maps and for equality tests.  A key is based on endpoints.
type Key struct {
	name string
}

// Equal compares two Key objects
func (k *Key) Equal(x *Key) bool {
	return k.name == x.name
}

// Server is used to return details of a consul server
type Server struct {
	Name         string
	ID           string
	Datacenter   string
	Segment      string
	Port         int
	SegmentAddrs map[string]string
	SegmentPorts map[string]int
	WanJoinPort  int
	Bootstrap    bool
	Expect       int
	Build        version.Version
	Version      int
	RaftVersion  int
	Addr         net.Addr
	Status       serf.MemberStatus

	// If true, use TLS when connecting to this server
	UseTLS bool
}

// Key returns the corresponding Key
func (s *Server) Key() *Key {
	return &Key{
		name: s.Name,
	}
}

// String returns a string representation of Server
func (s *Server) String() string {
	var addrStr, networkStr string
	if s.Addr != nil {
		addrStr = s.Addr.String()
		networkStr = s.Addr.Network()
	}

	return fmt.Sprintf("%s (Addr: %s/%s) (DC: %s)", s.Name, networkStr, addrStr, s.Datacenter)
}

var versionFormat = regexp.MustCompile(`\d+\.\d+\.\d+`)

// IsConsulServer returns true if a serf member is a consul server
// agent. Returns a bool and a pointer to the Server.
func IsConsulServer(m serf.Member) (bool, *Server) {
	if m.Tags["role"] != "consul" {
		return false, nil
	}

	datacenter := m.Tags["dc"]
	segment := m.Tags["segment"]
	_, bootstrap := m.Tags["bootstrap"]
	_, useTLS := m.Tags["use_tls"]

	expect := 0
	expectStr, ok := m.Tags["expect"]
	var err error
	if ok {
		expect, err = strconv.Atoi(expectStr)
		if err != nil {
			return false, nil
		}
	}

	portStr := m.Tags["port"]
	port, err := strconv.Atoi(portStr)
	if err != nil {
		return false, nil
	}

	segmentAddrs := make(map[string]string)
	segmentPorts := make(map[string]int)
	for name, value := range m.Tags {
		if strings.HasPrefix(name, "sl_") {
			addr, port, err := net.SplitHostPort(value)
			if err != nil {
				return false, nil
			}
			segmentPort, err := strconv.Atoi(port)
			if err != nil {
				return false, nil
			}

			segmentName := strings.TrimPrefix(name, "sl_")
			segmentAddrs[segmentName] = addr
			segmentPorts[segmentName] = segmentPort
		}
	}

	buildVersion, err := Build(&m)
	if err != nil {
		return false, nil
	}

	wanJoinPort := 0
	wanJoinPortStr, ok := m.Tags["wan_join_port"]
	if ok {
		wanJoinPort, err = strconv.Atoi(wanJoinPortStr)
		if err != nil {
			return false, nil
		}
	}

	vsnStr := m.Tags["vsn"]
	vsn, err := strconv.Atoi(vsnStr)
	if err != nil {
		return false, nil
	}

	raftVsn := 0
	raftVsnStr, ok := m.Tags["raft_vsn"]
	if ok {
		raftVsn, err = strconv.Atoi(raftVsnStr)
		if err != nil {
			return false, nil
		}
	}

	addr := &net.TCPAddr{IP: m.Addr, Port: port}

	parts := &Server{
		Name:         m.Name,
		ID:           m.Tags["id"],
		Datacenter:   datacenter,
		Segment:      segment,
		Port:         port,
		SegmentAddrs: segmentAddrs,
		SegmentPorts: segmentPorts,
		WanJoinPort:  wanJoinPort,
		Bootstrap:    bootstrap,
		Expect:       expect,
		Addr:         addr,
		Build:        *buildVersion,
		Version:      vsn,
		RaftVersion:  raftVsn,
		Status:       m.Status,
		UseTLS:       useTLS,
	}
	return true, parts
}


text:
package com.serenegiant.bluetooth;

import android.Manifest;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;

/**
 * Created by saki on 16/08/31.
 * ペアリング済みまたは検出したBluetooth機器情報保持のためのクラス
 */
public class BluetoothDeviceInfo implements Parcelable {
	public static final Creator<BluetoothDeviceInfo> CREATOR = new Creator<BluetoothDeviceInfo>() {
		@Override
		public BluetoothDeviceInfo createFromParcel(Parcel in) {
			return new BluetoothDeviceInfo(in);
		}

		@Override
		public BluetoothDeviceInfo[] newArray(int size) {
			return new BluetoothDeviceInfo[size];
		}
	};

	public final String name;
	public final String address;
	public final int type;
	public final int deviceClass;
	/**
	 * ペアリングの状態
	 * BluetoothDevice.BOND_NONE, BluetoothDevice.BOND_BONDING, BluetoothDevice.BOND_BONDEDのどれか
	 */
	public final int bondState;

	@RequiresPermission(Manifest.permission.BLUETOOTH)
	/*package*/BluetoothDeviceInfo(final BluetoothDevice device) {
		name = device.getName();
		address =  device.getAddress();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
			type = device.getType();
		} else {
			type = 0;
		}
		final BluetoothClass clazz = device.getBluetoothClass();
		deviceClass = clazz != null ? clazz.getDeviceClass() : 0;
		bondState = device.getBondState();
	}

	protected BluetoothDeviceInfo(Parcel in) {
		name = in.readString();
		address = in.readString();
		type = in.readInt();
		deviceClass = in.readInt();
		bondState = in.readInt();
	}

	/**
	 * ペアリングされているかどうか
	 * @return
	 */
	public boolean isPaired() {
		return bondState == BluetoothDevice.BOND_BONDED;
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(final Parcel parcel, final int flags) {

		parcel.writeString(name);
		parcel.writeString(address);
		parcel.writeInt(type);
		parcel.writeInt(deviceClass);
		parcel.writeInt(bondState);
	}

	@NonNull
	@Override
	public String toString() {
		return String.format("BluetoothDeviceInfo(%s/%s)", name, address);
	}
}


text:
%%  screenUpdate.m
%
% screenUpdate.m is the script to check for new EDF files in the working
% directory and, if present, to build acreening analysis figures for them.
% It will SKIP any files for which the "screening" directories already
% exist, and it will warn when data files exist for an EDF (without a
% screening directory).
%
% For a completely new directory, screenLoop.m can be used as well, but
% this one should be safer!
%
% MDT
% 2016.01.11
% Alpha

% Initialize eeglab for use by ge_screeningAnalysis2 function

eeglab;
close all;
clc;

% Make list of EDF files

fileList           = ls('*.edf');
[numFiles, useless] = size(fileList);

disp('screenUpdate.m Running');
disp(['Current directory:  ' pwd]);
disp(['Number of EDF files:  ' int2str(numFiles)]);

for ii = 1:numFiles
    curFile = fileList(ii,:);
    ge_screeningAnalysis2(curFile);
end


text:
<?php

namespace Magento\Cron\Model\Config\Converter;

/**
 * Convert data incoming from data base storage
 */
class Db implements \Magento\Framework\Config\ConverterInterface
{
    /**
     * Convert data
     *
     * @param array $source
     * @return array
     */
    public function convert($source)
    {
        $cronTab = isset($source['crontab']) ? $source['crontab'] : [];

        if (empty($cronTab)) {
            return $cronTab;
        }
        return $this->_extractParams($cronTab);
    }

    /**
     * Extract and prepare cron job data
     *
     * @param array $jobs
     * @return array
     */
    protected function _extractParams(array $cronTab)
    {
        $result = [];
        foreach ($cronTab as $groupName => $groupConfig) {
            $jobs = $groupConfig['jobs'];
            foreach ($jobs as $jobName => $value) {
                $result[$groupName][$jobName] = $value;

                if (isset($value['schedule']) && is_array($value['schedule'])) {
                    $this->_processConfigParam($value, $jobName, $result[$groupName]);
                    $this->_processScheduleParam($value, $jobName, $result[$groupName]);
                }

                $this->_processRunModel($value, $jobName, $result[$groupName]);
            }
        }
        return $result;
    }

    /**
     * Fetch parameter 'config_path' from 'schedule' container
     *
     * @param array  $jobConfig
     * @param string $jobName
     * @param array  $result
     * @return void
     */
    protected function _processConfigParam(array $jobConfig, $jobName, array &$result)
    {
        if (array_key_exists('config_path', $jobConfig['schedule'])) {
            $result[$jobName]['config_path'] = $jobConfig['schedule']['config_path'];
        }
    }

    /**
     * Fetch parameter 'cron_expr' from 'schedule' container, reassign it
     *
     * @param array  $jobConfig
     * @param string $jobName
     * @param array  $result
     * @return void
     */
    protected function _processScheduleParam(array $jobConfig, $jobName, array &$result)
    {
        if (array_key_exists('cron_expr', $jobConfig['schedule'])) {
            $result[$jobName]['schedule'] = $jobConfig['schedule']['cron_expr'];
        }
    }

    /**
     * Fetch parameters from 'run' container and save it by reference
     *
     * @param array  $jobConfig
     * @param string $jobName
     * @param array  $result
     * @return void
     */
    protected function _processRunModel(array $jobConfig, $jobName, array &$result)
    {
        if (isset($jobConfig['run']) && is_array($jobConfig['run']) && array_key_exists('model', $jobConfig['run'])) {
            $callPath = explode('::', $jobConfig['run']['model']);

            if (empty($callPath) || empty($callPath[0]) || empty($callPath[1])) {
                unset($result[$jobName]['run']);
                return;
            }

            $result[$jobName]['instance'] = $callPath[0];
            $result[$jobName]['method'] = $callPath[1];
            unset($result[$jobName]['run']);
        }
    }
}


text:
import {Map, List} from 'immutable';

export default () => {
    return Map({
            vote: Map({
                seats: List(),
                tally: Map()
            }),
            round: Map({
                quarterFinals: List(),
                simiFinals: List(),
                finals: List(),
                winner: List()
            }),
            videoSource: '',
            vidSourceSwap: false,
            timer: '',
            timerLen: '',
            votingDisabled: false,
            currentRound: 'quarterFinals'
        });
};


text:
package org.keycloak.authorization.model;

import org.keycloak.storage.SearchableModelField;

/**
 * Represents a scope, which is usually associated with one or more resources in order to define the actions that can be performed
 * or a specific access context.
 *
 * @author Pedro Igor
 */
public interface Scope {

    public static class SearchableFields {
        public static final SearchableModelField<Scope> ID = new SearchableModelField<>("id", String.class);
        public static final SearchableModelField<Scope> NAME = new SearchableModelField<>("name", String.class);
        public static final SearchableModelField<Scope> RESOURCE_SERVER_ID = new SearchableModelField<>("resourceServerId", String.class);
    }

    public static enum FilterOption {
        ID("id", SearchableFields.ID),
        NAME("name", SearchableFields.NAME);

        private final String name;
        private final SearchableModelField<Scope> searchableModelField;

        FilterOption(String name, SearchableModelField<Scope> searchableModelField) {
            this.name = name;
            this.searchableModelField = searchableModelField;
        }

        public String getName() {
            return name;
        }

        public SearchableModelField<Scope> getSearchableModelField() {
            return searchableModelField;
        }
    }

    /**
     * Returns the unique identifier for this instance.
     *
     * @return the unique identifier for this instance
     */
    String getId();

    /**
     * Returns the name of this scope.
     *
     * @return the name of this scope
     */
    String getName();

    /**
     * Sets a name for this scope. The name must be unique.
     *
     * @param name the name of this scope
     */
    void setName(String name);

    /**
     * Returns the end user friendly name for this scope. If not defined, value for {@link #getName()} is returned.
     *
     * @return the friendly name for this scope
     */
    String getDisplayName();

    /**
     * Sets an end user friendly name for this scope.
     *
     * @param name the name of this scope
     */
    void setDisplayName(String name);

    /**
     * Returns an icon {@link java.net.URI} for this scope.
     *
     * @return a uri for an icon
     */
    String getIconUri();

    /**
     * Sets an icon {@link java.net.URI} for this scope.
     *
     * @return a uri for an icon
     */
    void setIconUri(String iconUri);

    /**
     * Returns the {@link ResourceServer} instance to where this scope belongs to.
     *
     * @return
     */
    ResourceServer getResourceServer();
}


text:
#import "WXDisplayQueue.h"

#define MAX_CONCURRENT_COUNT 8

static dispatch_semaphore_t WXDisplayConcurrentSemaphore;

@implementation WXDisplayQueue

+ (dispatch_queue_t)displayQueue
{
    static dispatch_queue_t displayQueue = NULL;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        displayQueue = dispatch_queue_create("com.taobao.weex.displayQueue", DISPATCH_QUEUE_CONCURRENT);
        dispatch_set_target_queue(displayQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
    });

    return displayQueue;
}

+ (void)addBlock:(void(^)(void))block
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSUInteger processorCount = [NSProcessInfo processInfo].activeProcessorCount;
        NSUInteger maxConcurrentCount = processorCount <= MAX_CONCURRENT_COUNT ? processorCount : MAX_CONCURRENT_COUNT;
        WXDisplayConcurrentSemaphore = dispatch_semaphore_create(maxConcurrentCount);
    });

    dispatch_async([self displayQueue], ^{
        dispatch_semaphore_wait(WXDisplayConcurrentSemaphore, DISPATCH_TIME_FOREVER);
        block();
        dispatch_semaphore_signal(WXDisplayConcurrentSemaphore);
    });
}

@end


text:
package org.apache.cassandra.transport;

import java.util.ArrayList;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.MessageToMessageEncoder;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.service.ClientWarn;
import org.apache.cassandra.transport.messages.*;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.utils.JVMStabilityInspector;

/**
 * A message from the CQL binary protocol.
 */
public abstract class Message
{
    protected static final Logger logger = LoggerFactory.getLogger(Message.class);

    /**
     * When we encounter an unexpected IOException we look for these {@link Throwable#getMessage() messages}
     * (because we have no better way to distinguish) and log them at DEBUG rather than INFO, since they
     * are generally caused by unclean client disconnects rather than an actual problem.
     */
    private static final Set<String> ioExceptionsAtDebugLevel = ImmutableSet.<String>builder().
            add("Connection reset by peer").
            add("Broken pipe").
            add("Connection timed out").
            build();

    public interface Codec<M extends Message> extends CBCodec<M> {}

    public enum Direction
    {
        REQUEST, RESPONSE;

        public static Direction extractFromVersion(int versionWithDirection)
        {
            return (versionWithDirection & 0x80) == 0 ? REQUEST : RESPONSE;
        }

        public int addToVersion(int rawVersion)
        {
            return this == REQUEST ? (rawVersion & 0x7F) : (rawVersion | 0x80);
        }
    }

    public enum Type
    {
        ERROR          (0,  Direction.RESPONSE, ErrorMessage.codec),
        STARTUP        (1,  Direction.REQUEST,  StartupMessage.codec),
        READY          (2,  Direction.RESPONSE, ReadyMessage.codec),
        AUTHENTICATE   (3,  Direction.RESPONSE, AuthenticateMessage.codec),
        CREDENTIALS    (4,  Direction.REQUEST,  CredentialsMessage.codec),
        OPTIONS        (5,  Direction.REQUEST,  OptionsMessage.codec),
        SUPPORTED      (6,  Direction.RESPONSE, SupportedMessage.codec),
        QUERY          (7,  Direction.REQUEST,  QueryMessage.codec),
        RESULT         (8,  Direction.RESPONSE, ResultMessage.codec),
        PREPARE        (9,  Direction.REQUEST,  PrepareMessage.codec),
        EXECUTE        (10, Direction.REQUEST,  ExecuteMessage.codec),
        REGISTER       (11, Direction.REQUEST,  RegisterMessage.codec),
        EVENT          (12, Direction.RESPONSE, EventMessage.codec),
        BATCH          (13, Direction.REQUEST,  BatchMessage.codec),
        AUTH_CHALLENGE (14, Direction.RESPONSE, AuthChallenge.codec),
        AUTH_RESPONSE  (15, Direction.REQUEST,  AuthResponse.codec),
        AUTH_SUCCESS   (16, Direction.RESPONSE, AuthSuccess.codec);

        public final int opcode;
        public final Direction direction;
        public final Codec<?> codec;

        private static final Type[] opcodeIdx;
        static
        {
            int maxOpcode = -1;
            for (Type type : Type.values())
                maxOpcode = Math.max(maxOpcode, type.opcode);
            opcodeIdx = new Type[maxOpcode + 1];
            for (Type type : Type.values())
            {
                if (opcodeIdx[type.opcode] != null)
                    throw new IllegalStateException("Duplicate opcode");
                opcodeIdx[type.opcode] = type;
            }
        }

        private Type(int opcode, Direction direction, Codec<?> codec)
        {
            this.opcode = opcode;
            this.direction = direction;
            this.codec = codec;
        }

        public static Type fromOpcode(int opcode, Direction direction)
        {
            if (opcode >= opcodeIdx.length)
                throw new ProtocolException(String.format("Unknown opcode %d", opcode));
            Type t = opcodeIdx[opcode];
            if (t == null)
                throw new ProtocolException(String.format("Unknown opcode %d", opcode));
            if (t.direction != direction)
                throw new ProtocolException(String.format("Wrong protocol direction (expected %s, got %s) for opcode %d (%s)",
                                                          t.direction,
                                                          direction,
                                                          opcode,
                                                          t));
            return t;
        }
    }

    public final Type type;
    protected Connection connection;
    private int streamId;
    private Frame sourceFrame;
    private Map<String, ByteBuffer> customPayload;

    protected Message(Type type)
    {
        this.type = type;
    }

    public void attach(Connection connection)
    {
        this.connection = connection;
    }

    public Connection connection()
    {
        return connection;
    }

    public Message setStreamId(int streamId)
    {
        this.streamId = streamId;
        return this;
    }

    public int getStreamId()
    {
        return streamId;
    }

    public void setSourceFrame(Frame sourceFrame)
    {
        this.sourceFrame = sourceFrame;
    }

    public Frame getSourceFrame()
    {
        return sourceFrame;
    }

    public Map<String, ByteBuffer> getCustomPayload()
    {
        return customPayload;
    }

    public void setCustomPayload(Map<String, ByteBuffer> customPayload)
    {
        this.customPayload = customPayload;
    }

    public static abstract class Request extends Message
    {
        protected boolean tracingRequested;

        protected Request(Type type)
        {
            super(type);

            if (type.direction != Direction.REQUEST)
                throw new IllegalArgumentException();
        }

        public abstract Response execute(QueryState queryState);

        public void setTracingRequested()
        {
            this.tracingRequested = true;
        }

        public boolean isTracingRequested()
        {
            return tracingRequested;
        }
    }

    public static abstract class Response extends Message
    {
        protected UUID tracingId;
        protected List<String> warnings;

        protected Response(Type type)
        {
            super(type);

            if (type.direction != Direction.RESPONSE)
                throw new IllegalArgumentException();
        }

        public Message setTracingId(UUID tracingId)
        {
            this.tracingId = tracingId;
            return this;
        }

        public UUID getTracingId()
        {
            return tracingId;
        }

        public Message setWarnings(List<String> warnings)
        {
            this.warnings = warnings;
            return this;
        }

        public List<String> getWarnings()
        {
            return warnings;
        }
    }

    @ChannelHandler.Sharable
    public static class ProtocolDecoder extends MessageToMessageDecoder<Frame>
    {
        public void decode(ChannelHandlerContext ctx, Frame frame, List results)
        {
            boolean isRequest = frame.header.type.direction == Direction.REQUEST;
            boolean isTracing = frame.header.flags.contains(Frame.Header.Flag.TRACING);
            boolean isCustomPayload = frame.header.flags.contains(Frame.Header.Flag.CUSTOM_PAYLOAD);
            boolean hasWarning = frame.header.flags.contains(Frame.Header.Flag.WARNING);

            UUID tracingId = isRequest || !isTracing ? null : CBUtil.readUUID(frame.body);
            List<String> warnings = isRequest || !hasWarning ? null : CBUtil.readStringList(frame.body);
            Map<String, ByteBuffer> customPayload = !isCustomPayload ? null : CBUtil.readBytesMap(frame.body);

            try
            {
                if (isCustomPayload && frame.header.version < Server.VERSION_4)
                    throw new ProtocolException("Received frame with CUSTOM_PAYLOAD flag for native protocol version < 4");

                Message message = frame.header.type.codec.decode(frame.body, frame.header.version);
                message.setStreamId(frame.header.streamId);
                message.setSourceFrame(frame);
                message.setCustomPayload(customPayload);

                if (isRequest)
                {
                    assert message instanceof Request;
                    Request req = (Request)message;
                    Connection connection = ctx.channel().attr(Connection.attributeKey).get();
                    req.attach(connection);
                    if (isTracing)
                        req.setTracingRequested();
                }
                else
                {
                    assert message instanceof Response;
                    if (isTracing)
                        ((Response)message).setTracingId(tracingId);
                    if (hasWarning)
                        ((Response)message).setWarnings(warnings);
                }

                results.add(message);
            }
            catch (Throwable ex)
            {
                frame.release();
                // Remember the streamId
                throw ErrorMessage.wrap(ex, frame.header.streamId);
            }
        }
    }

    @ChannelHandler.Sharable
    public static class ProtocolEncoder extends MessageToMessageEncoder<Message>
    {
        public void encode(ChannelHandlerContext ctx, Message message, List results)
        {
            Connection connection = ctx.channel().attr(Connection.attributeKey).get();
            // The only case the connection can be null is when we send the initial STARTUP message (client side thus)
            int version = connection == null ? Server.CURRENT_VERSION : connection.getVersion();

            EnumSet<Frame.Header.Flag> flags = EnumSet.noneOf(Frame.Header.Flag.class);

            Codec<Message> codec = (Codec<Message>)message.type.codec;
            try
            {
                int messageSize = codec.encodedSize(message, version);
                ByteBuf body;
                if (message instanceof Response)
                {
                    UUID tracingId = ((Response)message).getTracingId();
                    Map<String, ByteBuffer> customPayload = message.getCustomPayload();
                    if (tracingId != null)
                        messageSize += CBUtil.sizeOfUUID(tracingId);
                    List<String> warnings = ((Response)message).getWarnings();
                    if (warnings != null)
                    {
                        if (version < Server.VERSION_4)
                            throw new ProtocolException("Must not send frame with WARNING flag for native protocol version < 4");
                        messageSize += CBUtil.sizeOfStringList(warnings);
                    }
                    if (customPayload != null)
                    {
                        if (version < Server.VERSION_4)
                            throw new ProtocolException("Must not send frame with CUSTOM_PAYLOAD flag for native protocol version < 4");
                        messageSize += CBUtil.sizeOfBytesMap(customPayload);
                    }
                    body = CBUtil.allocator.buffer(messageSize);
                    if (tracingId != null)
                    {
                        CBUtil.writeUUID(tracingId, body);
                        flags.add(Frame.Header.Flag.TRACING);
                    }
                    if (warnings != null)
                    {
                        CBUtil.writeStringList(warnings, body);
                        flags.add(Frame.Header.Flag.WARNING);
                    }
                    if (customPayload != null)
                    {
                        CBUtil.writeBytesMap(customPayload, body);
                        flags.add(Frame.Header.Flag.CUSTOM_PAYLOAD);
                    }
                }
                else
                {
                    assert message instanceof Request;
                    if (((Request)message).isTracingRequested())
                        flags.add(Frame.Header.Flag.TRACING);
                    Map<String, ByteBuffer> payload = message.getCustomPayload();
                    if (payload != null)
                        messageSize += CBUtil.sizeOfBytesMap(payload);
                    body = CBUtil.allocator.buffer(messageSize);
                    if (payload != null)
                    {
                        CBUtil.writeBytesMap(payload, body);
                        flags.add(Frame.Header.Flag.CUSTOM_PAYLOAD);
                    }
                }

                try
                {
                    codec.encode(message, body, version);
                }
                catch (Throwable e)
                {
                    body.release();
                    throw e;
                }

                results.add(Frame.create(message.type, message.getStreamId(), version, flags, body));
            }
            catch (Throwable e)
            {
                throw ErrorMessage.wrap(e, message.getStreamId());
            }
        }
    }

    @ChannelHandler.Sharable
    public static class Dispatcher extends SimpleChannelInboundHandler<Request>
    {
        private static class FlushItem
        {
            final ChannelHandlerContext ctx;
            final Object response;
            final Frame sourceFrame;
            private FlushItem(ChannelHandlerContext ctx, Object response, Frame sourceFrame)
            {
                this.ctx = ctx;
                this.sourceFrame = sourceFrame;
                this.response = response;
            }
        }

        private static final class Flusher implements Runnable
        {
            final EventLoop eventLoop;
            final ConcurrentLinkedQueue<FlushItem> queued = new ConcurrentLinkedQueue<>();
            final AtomicBoolean running = new AtomicBoolean(false);
            final HashSet<ChannelHandlerContext> channels = new HashSet<>();
            final List<FlushItem> flushed = new ArrayList<>();
            int runsSinceFlush = 0;
            int runsWithNoWork = 0;
            private Flusher(EventLoop eventLoop)
            {
                this.eventLoop = eventLoop;
            }
            void start()
            {
                if (!running.get() && running.compareAndSet(false, true))
                {
                    this.eventLoop.execute(this);
                }
            }
            public void run()
            {

                boolean doneWork = false;
                FlushItem flush;
                while ( null != (flush = queued.poll()) )
                {
                    channels.add(flush.ctx);
                    flush.ctx.write(flush.response, flush.ctx.voidPromise());
                    flushed.add(flush);
                    doneWork = true;
                }

                runsSinceFlush++;

                if (!doneWork || runsSinceFlush > 2 || flushed.size() > 50)
                {
                    for (ChannelHandlerContext channel : channels)
                        channel.flush();
                    for (FlushItem item : flushed)
                        item.sourceFrame.release();

                    channels.clear();
                    flushed.clear();
                    runsSinceFlush = 0;
                }

                if (doneWork)
                {
                    runsWithNoWork = 0;
                }
                else
                {
                    // either reschedule or cancel
                    if (++runsWithNoWork > 5)
                    {
                        running.set(false);
                        if (queued.isEmpty() || !running.compareAndSet(false, true))
                            return;
                    }
                }

                eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS);
            }
        }

        private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new ConcurrentHashMap<>();

        public Dispatcher()
        {
            super(false);
        }

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Request request)
        {

            final Response response;
            final ServerConnection connection;

            try
            {
                assert request.connection() instanceof ServerConnection;
                connection = (ServerConnection)request.connection();
                if (connection.getVersion() >= Server.VERSION_4)
                    ClientWarn.captureWarnings();

                QueryState qstate = connection.validateNewMessage(request.type, connection.getVersion(), request.getStreamId());

                logger.trace("Received: {}, v={}", request, connection.getVersion());
                response = request.execute(qstate);
                response.setStreamId(request.getStreamId());
                response.setWarnings(ClientWarn.getWarnings());
                response.attach(connection);
                connection.applyStateTransition(request.type, response.type);
            }
            catch (Throwable t)
            {
                JVMStabilityInspector.inspectThrowable(t);
                UnexpectedChannelExceptionHandler handler = new UnexpectedChannelExceptionHandler(ctx.channel(), true);
                flush(new FlushItem(ctx, ErrorMessage.fromException(t, handler).setStreamId(request.getStreamId()), request.getSourceFrame()));
                return;
            }
            finally
            {
                ClientWarn.resetWarnings();
            }

            logger.trace("Responding: {}, v={}", response, connection.getVersion());
            flush(new FlushItem(ctx, response, request.getSourceFrame()));
        }

        private void flush(FlushItem item)
        {
            EventLoop loop = item.ctx.channel().eventLoop();
            Flusher flusher = flusherLookup.get(loop);
            if (flusher == null)
            {
                Flusher alt = flusherLookup.putIfAbsent(loop, flusher = new Flusher(loop));
                if (alt != null)
                    flusher = alt;
            }

            flusher.queued.add(item);
            flusher.start();
        }

        @Override
        public void exceptionCaught(final ChannelHandlerContext ctx, Throwable cause)
        throws Exception
        {
            if (ctx.channel().isOpen())
            {
                UnexpectedChannelExceptionHandler handler = new UnexpectedChannelExceptionHandler(ctx.channel(), false);
                ChannelFuture future = ctx.writeAndFlush(ErrorMessage.fromException(cause, handler));
                // On protocol exception, close the channel as soon as the message have been sent
                if (cause instanceof ProtocolException)
                {
                    future.addListener(new ChannelFutureListener() {
                        public void operationComplete(ChannelFuture future) {
                            ctx.close();
                        }
                    });
                }
            }
        }
    }

    /**
     * Include the channel info in the logged information for unexpected errors, and (if {@link #alwaysLogAtError} is
     * false then choose the log level based on the type of exception (some are clearly client issues and shouldn't be
     * logged at server ERROR level)
     */
    static final class UnexpectedChannelExceptionHandler implements Predicate<Throwable>
    {
        private final Channel channel;
        private final boolean alwaysLogAtError;

        UnexpectedChannelExceptionHandler(Channel channel, boolean alwaysLogAtError)
        {
            this.channel = channel;
            this.alwaysLogAtError = alwaysLogAtError;
        }

        @Override
        public boolean apply(Throwable exception)
        {
            String message;
            try
            {
                message = "Unexpected exception during request; channel = " + channel;
            }
            catch (Exception ignore)
            {
                // We don't want to make things worse if String.valueOf() throws an exception
                message = "Unexpected exception during request; channel = <unprintable>";
            }

            if (!alwaysLogAtError && exception instanceof IOException)
            {
                if (ioExceptionsAtDebugLevel.contains(exception.getMessage()))
                {
                    // Likely unclean client disconnects
                    logger.trace(message, exception);
                }
                else
                {
                    // Generally unhandled IO exceptions are network issues, not actual ERRORS
                    logger.info(message, exception);
                }
            }
            else
            {
                // Anything else is probably a bug in server of client binary protocol handling
                logger.error(message, exception);
            }

            // We handled the exception.
            return true;
        }
    }
}


text:
class ImageSpec::Parser::GIF
  CONTENT_TYPE = 'image/gif'

  def self.attributes(stream)
    width, height = dimensions(stream)
    {:width => width, :height => height, :content_type => CONTENT_TYPE, :dimensions => [width, height], :file_size => size(stream)}
  end

  def self.detected?(stream)
    stream.rewind
    stream.read(4) == 'GIF8'
  end

  def self.dimensions(stream)
    stream.seek(6)
    stream.read(4).unpack('SS')
  end

  def self.size(stream)
    stream.size
  end

end


text:
package org.apache.shardingsphere.shardingproxy.backend.text.sctl.hint.internal.executor;

import com.google.common.base.Joiner;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.api.hint.HintManager;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.sharding.merge.dal.common.MultipleLocalDataMergedResult;
import org.apache.shardingsphere.shardingproxy.backend.communication.jdbc.connection.BackendConnection;
import org.apache.shardingsphere.shardingproxy.backend.response.query.QueryHeader;
import org.apache.shardingsphere.shardingproxy.backend.text.sctl.hint.internal.command.HintShowTableStatusCommand;
import org.apache.shardingsphere.shardingproxy.backend.text.sctl.hint.internal.result.HintShowTableStatusResult;
import org.apache.shardingsphere.underlying.merge.result.MergedResult;

import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Hint show table status command executor.
 */
@RequiredArgsConstructor
public final class HintShowTableStatusExecutor extends AbstractHintQueryExecutor<HintShowTableStatusCommand> {

    private final BackendConnection backendConnection;

    @Override
    protected List<QueryHeader> createQueryHeaders() {
        List<QueryHeader> queryHeaders = new ArrayList<>(3);
        queryHeaders.add(new QueryHeader("", "", "table_name", "", 255, Types.CHAR, 0, false, false, false, false));
        queryHeaders.add(new QueryHeader("", "", "database_sharding_values", "", 255, Types.CHAR, 0, false, false, false, false));
        queryHeaders.add(new QueryHeader("", "", "table_sharding_values", "", 255, Types.CHAR, 0, false, false, false, false));
        return queryHeaders;
    }

    @Override
    protected MergedResult createMergedResult() {
        Map<String, HintShowTableStatusResult> results = new HashMap<>();
        for (String each : getLogicTableNames()) {
            if (HintManager.isDatabaseShardingOnly()) {
                fillShardingValues(results, each, HintManager.getDatabaseShardingValues(), Collections.emptyList());
            } else {
                fillShardingValues(results, each, HintManager.getDatabaseShardingValues(each), HintManager.getTableShardingValues(each));
            }
        }
        return convert2MergedResult(results.values());
    }

    private void fillShardingValues(final Map<String, HintShowTableStatusResult> results, final String logicTable,
                                    final Collection<Comparable<?>> databaseShardingValues, final Collection<Comparable<?>> tableShardingValues) {
        if (!results.containsKey(logicTable)) {
            results.put(logicTable, new HintShowTableStatusResult(logicTable));
        }
        for (Comparable<?> each : databaseShardingValues) {
            results.get(logicTable).getDatabaseShardingValues().add(each.toString());
        }
        for (Comparable<?> each : tableShardingValues) {
            results.get(logicTable).getTableShardingValues().add(each.toString());
        }
    }

    private Collection<String> getLogicTableNames() {
        Collection<String> result = new LinkedList<>();
        Collection<TableRule> tableRules = backendConnection.getLogicSchema().getShardingRule().getTableRules();
        for (TableRule each : tableRules) {
            result.add(each.getLogicTable());
        }
        return result;
    }

    private MergedResult convert2MergedResult(final Collection<HintShowTableStatusResult> hintShowTableStatusResults) {
        Collection<List<Object>> values = new ArrayList<>(hintShowTableStatusResults.size());
        for (HintShowTableStatusResult each : hintShowTableStatusResults) {
            values.add(createRow(each));
        }
        return new MultipleLocalDataMergedResult(values);
    }

    private List<Object> createRow(final HintShowTableStatusResult hintShowTableStatusResult) {
        List<Object> row = new ArrayList<>(3);
        row.add(hintShowTableStatusResult.getLogicTable());
        row.add(Joiner.on(",").join(hintShowTableStatusResult.getDatabaseShardingValues()));
        row.add(Joiner.on(",").join(hintShowTableStatusResult.getTableShardingValues()));
        return row;
    }
}


text:
using System;
using System.Web.UI.WebControls;
using Sitecore.Extranet.Core.Utility;
using Sitecore.Extranet.Core.Extensions;
using Sitecore.Extranet.Core.Utility.FormText;
using System.Web.Security;

namespace Sitecore.Extranet.Core.Sublayouts.Extranet {
	public abstract class BaseLogin : BaseSublayout {

		protected abstract Panel LoginPanel { get; }
		protected abstract Panel LoggedInPanel { get; }
		protected abstract HyperLink RegisterLink { get; }
		protected abstract Literal MessageText { get; }
		protected abstract TextBox Username { get; }
		protected abstract TextBox Password { get; }
		protected abstract Button SubmitButton { get; }

		private string _returnURL;
		protected string returnURL {
			get {
				if (string.IsNullOrEmpty(_returnURL)) {
					if (Request.QueryString.HasKey("returnUrl") && !Request.QueryString.HasKey("returnUrl").Equals(""))
						_returnURL = Request.QueryString["returnUrl"];
					else
						_returnURL = string.Empty;
				}
				return _returnURL;
			}
		}

		private string _RegisterURL;
		public virtual string RegisterURL {
			get {
				if (string.IsNullOrEmpty(_RegisterURL))
					_RegisterURL = ExtranetSecurity.RegisterURL;
				return _RegisterURL;
			}
		}
		private string _ForgotPasswordURL;
		public virtual string ForgotPasswordURL {
			get {
				if (string.IsNullOrEmpty(_ForgotPasswordURL))
					_ForgotPasswordURL = ExtranetSecurity.ForgotPasswordURL;
				return _ForgotPasswordURL;
			}
		}

		protected virtual void Page_Load(object sender, EventArgs e) {

			SubmitButton.Text = FormTextUtility.Provider.GetTextByKey("/Login/Login");

			//if you're logged in and you've got permissions to this site then redirect to home
			if (ExtranetSecurity.IsLoggedIn()) {
				if (!string.IsNullOrEmpty(returnURL)) {
					Sitecore.Web.WebUtil.Redirect(returnURL);
				}

				//hide login if you didn't redirect
				LoginPanel.Visible = false;
				LoggedInPanel.Visible = true;
			} else {
				//show login and hide logged in content
				LoginPanel.Visible = true;
				LoggedInPanel.Visible = false;
			}

			//add the return url to the form button
			RegisterLink.NavigateUrl = (!string.IsNullOrEmpty(returnURL)) ? RegisterURL + "?returnUrl=" + returnURL : RegisterURL;

			//if you've been redirected from an activation then show messaging
			if (Request.QueryString.HasKey("activated") && !Request.QueryString.HasKey("activated").Equals("true")) {
				//show a message explaining the user what happened.
				MessageText.Text = FormTextUtility.Provider.GetTextByKey("/Login/AccountActivated");
			}
		}

		protected virtual void ProcessLogin(object sender, EventArgs e) {

			if (Page.IsValid) {
				string message = "";
				if (Login(Username.Text, Password.Text, ref message)) {
					if (!string.IsNullOrEmpty(returnURL)) {
						Sitecore.Web.WebUtil.Redirect(returnURL);
					} else {
						Sitecore.Web.WebUtil.Redirect(Sitecore.Context.Site.LoginPage);
					}
				} else {
					MessageText.Text = message;
				}
			}
		}

		protected virtual bool Login(string username, string password, ref string message) {

			//if the session is old reset it
			if (ExtranetSession.ExpiryDate().CompareTo(DateTime.Now) < 1) {
				ExtranetSession.Reset();
			}
			//increase the counter
			ExtranetSession.IncreaseCounter();
			//only try to login a limited amount of times
			if (ExtranetSession.Count() < ExtranetSecurity.LoginCount()) {
				if (ExtranetSecurity.HasExtranetUserPrefix()) {
					try {
						Sitecore.Security.Domains.Domain domain = Sitecore.Context.Domain;
						string domainUser = domain.Name + @"\" + ExtranetSecurity.ExtranetUserPrefix() + username;
						if (Sitecore.Security.Authentication.AuthenticationManager.Login(domainUser, password, false)) {
							//if you pass the login attempt but you're not logged in, that means there's no security attached to your user.
							if (ExtranetSecurity.IsLoggedIn()) {
								ExtranetSession.Reset();
								return true;
							} else {
								//users with no roles never activated their accounts
								message = FormTextUtility.Provider.GetTextByKey("/Login/UserRegisteredNotActivated");
							}
						} else {
							//throw new System.Security.Authentication.AuthenticationException("Invalid username or password.");
							message = FormTextUtility.Provider.GetTextByKey("/Login/InvalidUsernameOrPassword");
						}
					} catch (System.Security.Authentication.AuthenticationException) {
						//generic error
						message = FormTextUtility.Provider.GetTextByKey("/Login/AuthenticationError");
					}
				} else {
					//actually an error because the extranet user prefix wasn't setup properly
					message = ": " + FormTextUtility.Provider.GetTextByKey("/Login/AuthenticationError");
				}
			} else {
				//too many attempts to login.
				message = FormTextUtility.Provider.GetTextByKey("/Login/TooManyAttempts");
			}
			return false;
		}

	}
}


text:
#ifndef QDIALOG_H
#define QDIALOG_H

#include <QtWidgets/qtwidgetsglobal.h>
#include <QtWidgets/qwidget.h>

QT_REQUIRE_CONFIG(dialog);

QT_BEGIN_NAMESPACE

class QPushButton;
class QDialogPrivate;

class Q_WIDGETS_EXPORT QDialog : public QWidget
{
    Q_OBJECT
    friend class QPushButton;

    Q_PROPERTY(bool sizeGripEnabled READ isSizeGripEnabled WRITE setSizeGripEnabled)
    Q_PROPERTY(bool modal READ isModal WRITE setModal)

public:
    explicit QDialog(QWidget *parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags());
    ~QDialog();

    enum DialogCode { Rejected, Accepted };

    int result() const;

    void setVisible(bool visible) override;

    void setOrientation(Qt::Orientation orientation);
    Qt::Orientation orientation() const;

    void setExtension(QWidget* extension);
    QWidget* extension() const;

    QSize sizeHint() const override;
    QSize minimumSizeHint() const override;

    void setSizeGripEnabled(bool);
    bool isSizeGripEnabled() const;

    void setModal(bool modal);
    void setResult(int r);

Q_SIGNALS:
    void finished(int result);
    void accepted();
    void rejected();

public Q_SLOTS:
    virtual void open();
    virtual int exec();
    virtual void done(int);
    virtual void accept();
    virtual void reject();

    void showExtension(bool);

protected:
    QDialog(QDialogPrivate &, QWidget *parent, Qt::WindowFlags f = Qt::WindowFlags());

    void keyPressEvent(QKeyEvent *) override;
    void closeEvent(QCloseEvent *) override;
    void showEvent(QShowEvent *) override;
    void resizeEvent(QResizeEvent *) override;
#ifndef QT_NO_CONTEXTMENU
    void contextMenuEvent(QContextMenuEvent *) override;
#endif
    bool eventFilter(QObject *, QEvent *) override;
    void adjustPosition(QWidget*);
private:
    Q_DECLARE_PRIVATE(QDialog)
    Q_DISABLE_COPY(QDialog)
};

QT_END_NAMESPACE

#endif // QDIALOG_H