text:
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using ws.winx.input;
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Linq;
using Mono.TextTemplating;
using ws.winx.devices;

namespace ws.winx.editor
{
		public class InputMapper : EditorWindow
		{

				protected static Dictionary<int,InputState> _stateInputCombinations;// = InputManager.Settings.stateInputs; //new Dictionary<int,InputState> ();
				protected static InputManager.InputSettings settings = InputManager.Settings;
				protected static bool _settingsLoaded = false;
				protected UnityEngine.Object _lastController;
				protected UnityEngine.Object _lastSettingsFile;
				protected static int _selectedStateHash = 0;
				protected static int _deleteStateWithHash = 0;
				protected bool _isDeviceAxisPositionFull;
				protected bool _isComplexActionTypesAllowed;
				protected string _warrningAddStateLabel;
				protected int _isPrimary = 0;
				protected string _currentInputString;
				protected bool _isBinary = true;

				//Players
				protected int _playerNumber = 1;
				protected int[] _playersIndices;
				protected int _playerIndexSelected = 0;
				protected string[] _playerDisplayOptions;

				//Profiles

				int _profileSelectedIndex;
				string[] _profilesDevicesDisplayOptions;

				//Device
				IDevice _deviceByProfile;

				//new state
				protected string _newCustomStateName;
				protected string _prevNewCustomStateName;

				//protected string _className="MyEnumClass";
				protected string _namespace = "ws.winx.input.states";
				protected string _enumName = "States";
				protected string _enumFileName = "States.cs";
				protected bool _enumSettingsFoldout;

				//styles
				protected GUILayoutOption[] _inputLabelStyle = new GUILayoutOption[]{ GUILayout.Width (200)};
				protected GUILayoutOption[] _stateNameLabelStyle = new GUILayoutOption[]{ GUILayout.Width (100)};
				protected GUILayoutOption[]  _settingsStyle = new GUILayoutOption[]{GUILayout.Width (200)};
				protected GUILayoutOption[]  _addRemoveButtonStyle = new GUILayoutOption[]{GUILayout.Width (40)};
				protected Rect _buttonRect = new Rect (0, 0, 100, 15);
				protected Rect _layerLabelRect = new Rect (0, 0, 100, 15);

				// protected GUILayoutOption[] _warrningAddStateLabelStryle=new GUILayoutOption[]{GUILayout.
				protected InputAction _action;
				protected InputCombination _previousStateInput = null;

				//settings
				protected float _singleClickSensitivity = InputManager.Settings.singleClickSensitivity;
				protected float _doubleClickSensitivity = InputManager.Settings.doubleClickSensitivity;
				protected float _longClickSensitivity = InputManager.Settings.longClickSensitivity;
				protected float _combosClickSensitivity = InputManager.Settings.combinationsClickSensitivity;
				protected string _longClickDesignator = InputManager.Settings.longDesignator;
				protected string _doubleClickDesignator = InputManager.Settings.doubleDesignator;
				protected string _spaceDesignator = InputManager.Settings.spaceDesignator;
				protected char _prevSpaceDesinator = InputManager.Settings.spaceDesignator [0];
				protected string _prevlongClickDesignator = InputManager.Settings.longDesignator;
				protected string _prevdoubleClickDesignator = InputManager.Settings.doubleDesignator;
				protected bool[] _showLayer;
				private bool __wereDevicesEnumerated = false;

				//PUBLIC
				public Vector2 scrollPosition = Vector2.zero;
				public Vector2 scrollPosition2 = Vector2.zero;
				public int maxCombosNum = 3;
				public UnityEngine.Object settingsFile;
				public UnityEditor.Animations.AnimatorController controller;
				public bool saveBinary = false;
				public static EditorWindow _instance;

				void Start ()
				{

						Debug.Log ("Start");

//			#if (UNITY_STANDALONE_WIN)
//			InputManager.AddDriver(new ThrustMasterDriver());
//			InputManager.AddDriver(new WiiDriver());
//			InputManager.AddDriver(new XInputDriver());
//
//			#endif
//
//			#if (UNITY_STANDALONE_OSX)
//			InputManager.AddDriver(new ThrustMasterDriver());
//			//InputManager.AddDriver(new XInputDriver());
//			#endif
//
//			#if (UNITY_STANDALONE_ANDROID)
//			InputManager.AddDriver(new ThrustMasterDriver());
//			#endif

						//if (!Application.isPlaying) {
						//        InputManager.hidInterface.Enumerate ();
						//        __wereDevicesEnumerated = true;
						//}

				}

				void Enable ()
				{

						Debug.Log ("Enable");

				}

				// Add menu named "Input Mapper" to the Window menu
				[MenuItem ("Window/Input Mapper/Input Mapper")]
				static void ShowEditor ()
				{
						//if (_stateInputCombinations != null && _stateInputCombinations.Count > 0)
						//		_stateInputCombinations = new Dictionary<int, InputState> ();

						//deselect if some state is selected for editing
						_selectedStateHash = 0;

						_instance = EditorWindow.GetWindow (typeof(InputMapper));

				}

				static void generateCSharpStatesEnum (string namespaceName, string enumName, string fileName, StringBuilder statesStringBuilder)
				{

						//Create template generator
						TemplateGenerator generator = new TemplateGenerator ();
						generator.Session.Add ("Namespace", namespaceName);
						//generator.Session.Add ("ClassName", controller.name.Replace (" ", "") + "Class");
						generator.Session.Add ("EnumName", enumName);
						generator.Session.Add ("Values", statesStringBuilder.ToString ());

						string generated;

						generated = Path.Combine (Application.dataPath, "Scripts");

						//if Scripts doesn't exist
						if (!Directory.Exists (generated))
								Directory.CreateDirectory (generated);

						//string[] filesFound=Directory.GetFiles (Path.Combine (generated, fileName));

						//if (filesFound.Length == 0) {
						generated = namespaceToDirectory (generated, namespaceName);
						generated = Path.GetFullPath (Path.Combine (generated, fileName));
						//} else {
						//		generated=filesFound[0];
						//}

						try {

								///!!! OSX : error !Error running gmcs : Cannot find the specified file.! happen here cos of unity bug
								/// Download and install MRE(Mono Runtime Envi)
								/// http://www.mono-project.com/download/
								/// saving doesn't work still cos of unknown
								fileName = Path.Combine (Path.Combine (Application.dataPath, "Editor"), "StatesEnumTemplate.tpl");
								UnityEngine.Debug.Log ("Generating " + generated + " from template:" + fileName);
								generator.ProcessTemplate (fileName, generated);

						} catch (Exception e) {
								UnityEngine.Debug.LogError (e.Message);
						}

						AssetDatabase.Refresh ();

				}

				/// <summary>
				/// Generates Directory Structure based on namespace string ex. ws.winx.input
				/// in specified "rootDir"
				/// </summary>
				/// <returns>The to directory.</returns>
				/// <param name="root">Root.</param>
				/// <param name="namespaceName">Namespace name.</param>
				static string namespaceToDirectory (string root, string namespaceName)
				{

						//split ws.winx.input.states
						string[] namespacePath = namespaceName.Split ('.');
						int i = 0;

						//generate subdirs
						for (; i<namespacePath.Length; i++) {
								root = Path.Combine (root, namespacePath [i]);

								if (!Directory.Exists (root))
										Directory.CreateDirectory (root);
						}

						return root;

				}

				void loadAsset (string path)
				{
						Uri fullPath = new Uri (path, UriKind.Absolute);
						Uri relRoot = new Uri (Application.dataPath, UriKind.Absolute);

						AssetDatabase.ImportAsset (relRoot.MakeRelativeUri (fullPath).ToString (), ImportAssetOptions.ForceUpdate);

						_lastSettingsFile = settingsFile = AssetDatabase.LoadAssetAtPath (relRoot.MakeRelativeUri (fullPath).ToString (), typeof(UnityEngine.Object));

						if (_lastSettingsFile != null)
								_settingsLoaded= loadInputSettings (_lastSettingsFile);

						//_lastSettingsXML = settingsXML = AssetDatabase.LoadAssetAtPath (relRoot.MakeRelativeUri(fullPath).ToString(), typeof(TextAsset)) as TextAsset;
						//Debug.Log ("Loading Text asset"+settingsXML.name+" from "+path+" full path:"+ fullPath+" rell:"+relRoot+"relativePath:"+relRoot.MakeRelativeUri(fullPath).ToString());

				}

				///////////////////////////////        LOAD INPUT SETTINGS          //////////////////////
				/// <summary>
				/// Loads the input settings
				/// </summary>
				bool loadInputSettings (UnityEngine.Object asset)
				{

						if (asset is TextAsset) {

								string text = ((TextAsset)asset).text;

								if (text != null && text.Length > 1) {

										Debug.Log ("Loading..." + _stateInputCombinations);

										//clone
										//_stateInputCombinations = new Dictionary<int,InputState> (_stateInputCombinations);
										//Debug.Log ("Clone..." + _stateInputCombinations.Count);

										//load
										#if (UNITY_STANDALONE || UNITY_EDITOR || UNITY_ANDROID) && !UNITY_WEBPLAYER
											settings=InputManager.loadSettings (new StringReader (text));
										#else
										settings = InputManager.loadSettingsFromText (text, false);
										#endif

								}

						} else {

								String path = AssetDatabase.GetAssetPath (settingsFile);
								if (!String.IsNullOrEmpty (path)) {
										_isBinary = Path.GetExtension (path) == ".bin";

										if (_isBinary)
												settings = InputManager.loadSettingsFromBin (path);
										else
												settings = InputManager.loadSettingsFromXMLText (path);
								}
						}

						if (settings != null) {

								//assign settings
								_doubleClickDesignator = settings.doubleDesignator;
								_doubleClickSensitivity = settings.doubleClickSensitivity;
								_combosClickSensitivity = settings.combinationsClickSensitivity;
								_singleClickSensitivity = settings.singleClickSensitivity;
								_longClickDesignator = settings.longDesignator;
								_longClickSensitivity = settings.longClickSensitivity;
								_spaceDesignator = settings.spaceDesignator;

								_playerNumber = settings.Players.Length;
								_playerIndexSelected = 0;

								return true;

						}

						return false;
				}

				///////////////////////////////////////  SAVE INPUT SETTINGS /////////////////////////////////////
				/// <summary>
				/// Saves the input settings.
				/// </summary>
				void saveInputSettings (string path)
				{

						if (path != null && path.Length > 1) {
								//Debug.Log ("Before..." + _stateInputCombinations.Count+" inputmngr "+InputManager.Settings.stateInputs.Count);
								generateCSharpStatesEnum (_namespace, _enumName, _enumFileName, HashStateInputsToStringBuilder ());

								InputManager.saveSettings (path);

								//Debug.Log ("AfterSave..." + _stateInputCombinations.Count+" inputmngr "+InputManager.Settings.stateInputs.Count+"to path:"+path);

								loadAsset (path);

								AssetDatabase.Refresh ();

						}
				}

				/// <summary>
				/// Fill StringBuilde with StateName=Hash,...values
				/// </summary>
				/// <returns></returns>
				StringBuilder HashStateInputsToStringBuilder ()
				{
						Dictionary<int,InputState> stateInputsCurrent;
						List<int> inputStatesToBeRemoved;
						List<string> profilesToBeRemoved;
						StringBuilder statesStringBuilder;

						statesStringBuilder = new StringBuilder ();

						Dictionary<int,bool> stateInputsCombined = new Dictionary<int, bool> ();
						int numPlayers = settings.Players.Length;

						for (int i=0; i<numPlayers; i++) {

								profilesToBeRemoved = new List<string> ();

								foreach (var DeviceProfileHashStateInput in settings.Players[i].DeviceProfileStateInputs) {

										stateInputsCurrent = DeviceProfileHashStateInput.Value;

										if (stateInputsCurrent.Count == 0) {
												profilesToBeRemoved.Add (DeviceProfileHashStateInput.Key);
												continue;
										}

										inputStatesToBeRemoved = new List<int> ();

										//Filter
										foreach (var HashStateInput in stateInputsCurrent) {

												//fill String Builder with unique StateInputs
												if (!stateInputsCombined.ContainsKey (HashStateInput.Key)) {

														stateInputsCombined [HashStateInput.Key] = true;

														statesStringBuilder.Append ("\t" + HashStateInput.Value.name.Replace (" ", "_") + "=" + HashStateInput.Key + ",\n\r");

												}

												InputCombination combos = HashStateInput.Value.combinations [0];

												if (combos != null && combos.GetActionAt (0).codeString == "None") {
														combos.Clear ();

														inputStatesToBeRemoved.Add (HashStateInput.Key);
												}

												combos = HashStateInput.Value.combinations [1];

												if (combos != null && combos.GetActionAt (0).codeString == "None") {
														combos.Clear ();
														HashStateInput.Value.combinations [1] = null;

												}

										}

										//remove those with "None" as Primary combination
										foreach (var key in inputStatesToBeRemoved) {
												stateInputsCurrent.Remove (key);
										}

								}

								//remove empty profiles
								foreach (var key in profilesToBeRemoved) {
										settings.Players [i].DeviceProfileStateInputs.Remove (key);
								}

						}//end for Players

						return statesStringBuilder;

				}

				/// <summary>
				/// Replaces the designator.
				/// </summary>
				/// <param name="oldValue">Old value.</param>
				/// <param name="newValue">New value.</param>
				void replaceDesignator (string oldValue, string newValue)
				{
						foreach (var KeyCombinationStringPair in InputMapper._stateInputCombinations) {
								InputCombination combos = KeyCombinationStringPair.Value.combinations [0];

								if (combos != null)
										combos.combinationString = combos.combinationString.Replace (oldValue, newValue);

								combos = KeyCombinationStringPair.Value.combinations [1];

								if (combos != null)
										combos.combinationString = combos.combinationString.Replace (oldValue, newValue);

						}
				}

				/// <summary>
				/// Exists the in controller.
				/// </summary>
				/// <returns><c>true</c>, if in controller was existed, <c>false</c> otherwise.</returns>
				/// <param name="key">Key.</param>
				bool existInController (int key)
				{

						if (controller != null) {

								int numLayers, numStates, i = 0, j = 0;

								UnityEditor.Animations.AnimatorControllerLayer layer;
								UnityEditor.Animations.AnimatorStateMachine stateMachine;

								UnityEditor.Animations.AnimatorController ac = controller as UnityEditor.Animations.AnimatorController;
								numLayers = ac.layers.Length;

								for (; i<numLayers; i++) {
										layer = ac.layers [i];

										stateMachine = layer.stateMachine;

										numStates = stateMachine.states.Length;

										for (j=0; j<numStates; j++) {
												if (Animator.StringToHash (stateMachine.states [j].state.name) == key)
												//if (stateMachine.GetState (j).uniqueNameHash == key)
														return true;

										}

								}

								return false;
						}

						return false;
				}

				/// <summary>
				/// Resolves empty or None input or restricts input to max num of combinaition(maxCombosNum)
				/// </summary>
				/// <param name="combos">Combos. ex. w+Mouse1(x2)+Joystick1Button3(-)</param>
				/// <param name="input">Input.</param>
				void toInputCombination (InputCombination combos, InputAction input)
				{

						if (combos.numActions + 1 > maxCombosNum || (combos.numActions == 1 && combos.GetActionAt (0).getCode (_deviceByProfile) == 0))
								combos.Clear ();

						combos.Add (input);

						//Debug.Log(input);

				}

				/////////////////////////                  UPDATE              /////////////////////////
				/// <summary>
				/// Update this instance.
				/// </summary>
				void Update ()
				{
						InputState state;

						if (!Application.isPlaying && !__wereDevicesEnumerated) {
								__wereDevicesEnumerated = true;
								InputManager.hidInterface.SetProfiles (AssetDatabase.LoadAssetAtPath ("Assets/Resources/DeviceProfiles.asset", typeof(DeviceProfiles)) as DeviceProfiles);

								InputManager.hidInterface.Enumerate ();

						}

						if (!Application.isPlaying && _selectedStateHash != 0) {

								_action = InputManager.GetAction (_deviceByProfile);

								if (_action != null && (_action.getCode (_deviceByProfile) ^ (int)KeyCode.Escape) != 0 && (_action.getCode (_deviceByProfile) ^ (int)KeyCode.Return) != 0) {

										if ((_action.getCode (_deviceByProfile) ^ (int)KeyCode.Backspace) == 0) {
												state = _stateInputCombinations [_selectedStateHash];
												state.combinations [_isPrimary].Clear ();
												state.combinations [_isPrimary].Add (new InputAction (KeyCode.None));

										} else {

												if (!_isComplexActionTypesAllowed)
														_action.type = InputActionType.SINGLE;

												_action.setCode (InputCode.toCodeAnyDevice (_action.getCode (_deviceByProfile)), _deviceByProfile);

												if (_isDeviceAxisPositionFull) {
														_action.setCode (InputCode.toCodeAxisFull (_action.getCode (_deviceByProfile)), _deviceByProfile);

												}

												toInputCombination (_stateInputCombinations [_selectedStateHash].combinations [_isPrimary], _action);
										}

										//Debug.Log ("Action:" + _action + " " + _action.getCode(_deviceByProfile)+" type:"+_action.type);
								}

								//Debug.Log ("Action:"+action);
						}

				}

				///////////////////////////             OnGUI                ////////////////////////
				/// <summary>
				/// Raises the GU event.
				/// </summary>
				void OnGUI ()
				{

						int numLayers;
						int numStates;
						int i = 0;
						int j = 0;
						UnityEditor.Animations.AnimatorStateMachine stateMachine;
						UnityEditor.Animations.AnimatorState state;
						UnityEditor.Animations.AnimatorControllerLayer layer;
						UnityEditor.Animations.AnimatorController ac;

						if (_deleteStateWithHash != 0) {
								_stateInputCombinations.Remove (_deleteStateWithHash);
								_deleteStateWithHash = 0;
						}

						if (_spaceDesignator != null) {

								EditorGUILayout.LabelField ("Settings");
								EditorGUILayout.Separator ();

								////// MAX NUM COMBOS  /////
								maxCombosNum = EditorGUILayout.IntField ("Combos per input:", maxCombosNum, _settingsStyle);

								EditorGUILayout.Separator ();

								////// DESIGNATORS /////
								EditorGUILayout.LabelField ("Click Designators");

								///////// DOUBLE ////////////
								_doubleClickDesignator = EditorGUILayout.TextField ("Double click designator", _doubleClickDesignator, _settingsStyle);
								InputManager.Settings.doubleDesignator = _doubleClickDesignator.Length > 0 ? _doubleClickDesignator : _prevlongClickDesignator;

								if (_prevdoubleClickDesignator != null && _doubleClickDesignator.Length > 0 && _prevdoubleClickDesignator != _doubleClickDesignator) {
										replaceDesignator (_prevdoubleClickDesignator, _doubleClickDesignator);
								}
								_prevdoubleClickDesignator = _doubleClickDesignator;

								//////////////  LONG //////////
								_longClickDesignator = EditorGUILayout.TextField ("Long click designator", _longClickDesignator, _settingsStyle);

								InputManager.Settings.longDesignator = _longClickDesignator.Length > 0 ? _longClickDesignator : _prevlongClickDesignator;

								if (_prevlongClickDesignator != null && _longClickDesignator.Length > 0 && _prevlongClickDesignator != _longClickDesignator) {
										replaceDesignator (_prevlongClickDesignator, _longClickDesignator);
								}
								_prevlongClickDesignator = _longClickDesignator;

								///////////// SPACE /////////////
								_spaceDesignator = EditorGUILayout.TextField ("Combination separator", _spaceDesignator, _settingsStyle);
								if (_spaceDesignator.Length > 1)
										_spaceDesignator = _spaceDesignator [0].ToString ();//restrict to 1 char

								InputManager.Settings.spaceDesignator = _spaceDesignator.Length > 0 ? _spaceDesignator : _prevSpaceDesinator.ToString ();

								if (_spaceDesignator.Length > 0 && _prevSpaceDesinator != _spaceDesignator [0]) {
										replaceDesignator (_prevSpaceDesinator.ToString (), _spaceDesignator [0].ToString ());
								}

								_prevSpaceDesinator = _spaceDesignator [0];

								EditorGUILayout.Separator ();

								/////  SENSITIVITY  ////
								EditorGUILayout.LabelField ("Sensitivity");
								InputManager.Settings.singleClickSensitivity = _singleClickSensitivity = EditorGUILayout.FloatField ("Single click sensitivity", _singleClickSensitivity, _settingsStyle);
								InputManager.Settings.doubleClickSensitivity = _doubleClickSensitivity = EditorGUILayout.FloatField ("Double click sensitivity", _doubleClickSensitivity, _settingsStyle);
								InputManager.Settings.longClickSensitivity = _longClickSensitivity = EditorGUILayout.FloatField ("Long click sensitivity", _longClickSensitivity, _settingsStyle);
								InputManager.Settings.combinationsClickSensitivity = _combosClickSensitivity = EditorGUILayout.FloatField ("Combos click sensitivity", _combosClickSensitivity, _settingsStyle);
								EditorGUILayout.Separator ();

								//////////// PLAYERS //////////////
								EditorGUILayout.BeginHorizontal ();

								InputPlayer player = null;
								_playerNumber = EditorGUILayout.IntField ("Number of Players", _playerNumber);

								if (_playerNumber < 1)
										_playerNumber = 1;

								//create Players
								if (settings.Players == null || _playerNumber != settings.Players.Length) {

										InputPlayer[] players = new InputPlayer[_playerNumber];

										for (i=0; i<_playerNumber; i++) {

												//don't delete previous players just add new
												if (settings.Players != null && settings.Players.Length > i)
														players [i] = settings.Players [i];
												else
														players [i] = new InputPlayer ();
										}

										settings.Players = players;

										//set last player as current
										_playerIndexSelected = _playerNumber - 1;

										//reset profile to default
										_profileSelectedIndex = 0;

								}

								//create player display options
								if (_playerDisplayOptions == null || _playerNumber != _playerDisplayOptions.Length) {
										_playerDisplayOptions = new string [_playerNumber];
										for (i=0; i<_playerNumber; i++) {
												_playerDisplayOptions [i] = "Player" + i;
										}

								}

								_playerIndexSelected = EditorGUILayout.Popup (_playerIndexSelected, _playerDisplayOptions);

								if (_playerNumber > 1 && GUILayout.Button ("Clone To All")) {

										if (EditorUtility.DisplayDialog ("Clone to All!",
                                                "Are you sure to clone selected player overwriting other player's settings?", "Yes", "Cancel")) {
												InputPlayer sample = settings.Players [_playerIndexSelected];

												for (i = 0; i < _playerNumber; i++) {
														if (i != _playerIndexSelected)
																settings.Players [i] = sample.Clone ();
												}
										}
								}

								EditorGUILayout.EndHorizontal ();

								//////////// Profiles /////////////

								EditorGUILayout.BeginHorizontal ();

								EditorGUILayout.LabelField ("Profiles");

								List<IDevice> devices = InputManager.GetDevices<IDevice> ();

								if (devices.Count > 0) {

										List<string> pList = devices.Where (item => item.profile != null).Select (item => item.profile.Name).Distinct ().ToList ();
										pList.Insert (0, "default");

										_profilesDevicesDisplayOptions = pList.ToArray ();

								} else {
										_profileSelectedIndex = 0;
										_profilesDevicesDisplayOptions = new string[] { "default" };
								}

								_profileSelectedIndex = EditorGUILayout.Popup (_profileSelectedIndex, _profilesDevicesDisplayOptions);

								//by selecting profile we are setting Device type expectation
								_deviceByProfile = devices.Where (item => item.profile != null).FirstOrDefault (item => item.profile.Name == _profilesDevicesDisplayOptions [_profileSelectedIndex]);

								player = settings.Players [_playerIndexSelected];

								Dictionary<int,InputState> stateInputsCurrent = null;

								//init stateInput Dictionary if player numbers is increased
								if (_profilesDevicesDisplayOptions.Length > _profileSelectedIndex) {
										if (!player.DeviceProfileStateInputs.ContainsKey (_profilesDevicesDisplayOptions [_profileSelectedIndex])) {
												player.DeviceProfileStateInputs [_profilesDevicesDisplayOptions [_profileSelectedIndex]] = new Dictionary<int, InputState> ();
										}

										stateInputsCurrent = player.DeviceProfileStateInputs [_profilesDevicesDisplayOptions [_profileSelectedIndex]];
								} else {
										_profileSelectedIndex = 0;
										stateInputsCurrent = player.DeviceProfileStateInputs ["default"];

								}

								if (_profileSelectedIndex > 0) {
										if (GUILayout.Button ("Clone default")
												&& EditorUtility.DisplayDialog ("Clone Default!",
                                                "Are you sure to clone Default input settings to " + _profilesDevicesDisplayOptions [_profileSelectedIndex] + " device specific settings?", "Yes", "Cancel")

                                            ) {

												Dictionary<int,InputState> stateInputsDefault = player.DeviceProfileStateInputs ["default"];
												foreach (var HashInputStatePair in stateInputsDefault) {
														if (!stateInputsCurrent.ContainsKey (HashInputStatePair.Key))
																stateInputsCurrent.Add (HashInputStatePair.Key, HashInputStatePair.Value.Clone ());

												}

										}

								}

								_stateInputCombinations = stateInputsCurrent;

								EditorGUILayout.EndHorizontal ();
								EditorGUILayout.Separator ();

								//////////  ANY/Complex Action Types(doubles,long...)  /FULL AXIS Checkers ///////
								EditorGUILayout.BeginHorizontal ();
								//	_isDeviceAny = GUILayout.Toggle (_isDeviceAny, "Any(Uncheck 4Testing Only");
								_isComplexActionTypesAllowed = GUILayout.Toggle (_isComplexActionTypesAllowed, "Allow DOUBLE/LONG(HOLD)");
								_isDeviceAxisPositionFull = GUILayout.Toggle (_isDeviceAxisPositionFull, "Full Axis");
								EditorGUILayout.EndHorizontal ();

								EditorGUILayout.Separator ();

						}

						/////////////// GENERATING ENUM SETTINGS  ///////////
						_enumSettingsFoldout = EditorGUILayout.Foldout (_enumSettingsFoldout, "States Enum Properties");

						if (_enumSettingsFoldout) {
								EditorGUILayout.BeginVertical ();

								//settingsXML = EditorGUILayout.ObjectField (settingsXML, typeof(TextAsset), true) as TextAsset;
								_namespace = EditorGUILayout.TextField ("Namespace:", _namespace);
								_enumName = EditorGUILayout.TextField ("Enum:", _enumName);
								_enumFileName = EditorGUILayout.TextField ("File name:", _enumFileName);
								EditorGUILayout.EndVertical ();
						}

						EditorGUILayout.Separator ();

						/////////////////   XML  ////////////////////
						EditorGUILayout.LabelField ("Input XML/BIN");
						EditorGUILayout.BeginHorizontal ();
						settingsFile = EditorGUILayout.ObjectField (settingsFile, typeof(UnityEngine.Object), true);

						//reload if xml changed
						if (_lastSettingsFile != settingsFile) {
								_settingsLoaded = false;

						}

						_lastSettingsFile = settingsFile;

						if (_selectedStateHash == 0 && GUILayout.Button ("Open")) {
								string path;

								if (_isBinary)
										path = EditorUtility.OpenFilePanel ("Open XML Input Settings file", "", "bin");
								else
										path = EditorUtility.OpenFilePanel ("Open XML Input Settings file", "", "xml");

								if (path.Length > 0) {

										loadAsset (path);

								}

								return;
						}

						///////////////   SAVE ////////////////////

						if (_selectedStateHash == 0 && GUILayout.Button ("Save")) {

								EditorGUIUtility.keyboardControl = 0;
								_selectedStateHash = 0;

								if (!Directory.Exists (Application.streamingAssetsPath)) {
										Directory.CreateDirectory (Application.streamingAssetsPath);
								}

								if (settingsFile != null) {
										string path = AssetDatabase.GetAssetPath (settingsFile);

										if (Path.GetExtension (path) == ".xml") {
												saveInputSettings (Path.Combine (Application.streamingAssetsPath, settingsFile.name + ".xml"));
										} else {
												saveInputSettings (Path.Combine (Application.streamingAssetsPath, settingsFile.name + ".bin"));
										}
								} else {

										if (_isBinary)
												saveInputSettings (EditorUtility.SaveFilePanel ("Save Input Settings", Application.streamingAssetsPath, "InputSettings", "bin"));
										else
												saveInputSettings (EditorUtility.SaveFilePanel ("Save Input Settings", Application.streamingAssetsPath, "InputSettings", "xml"));
										return;
								}
						}

						if (settingsFile == null)
								_isBinary = GUILayout.Toggle (_isBinary, "Binary");

						/////////// RELOAD ////////////////
						if (GUILayout.Button ("Reload")) {
								_settingsLoaded = false;
						}
						EditorGUILayout.EndHorizontal ();

						EditorGUILayout.Separator ();

						//loadingSettings selected thru ObjectField browser or drag and drop
						if ((!_settingsLoaded && settingsFile != null)) {

							_settingsLoaded=loadInputSettings (settingsFile);

						}

						/////////  ANIMATOR CONTROLER //////////
						_lastController = controller;

						EditorGUILayout.LabelField ("Animator Controller States");

						EditorGUILayout.BeginHorizontal ();
						controller = EditorGUILayout.ObjectField (controller, typeof(UnityEditor.Animations.AnimatorController), true) as UnityEditor.Animations.AnimatorController;

						EditorGUILayout.EndHorizontal ();

						EditorGUILayout.Separator ();

						/////////  Create AnimaitonController states GUI //////////
						if (controller != null) {

								ac = controller as UnityEditor.Animations.AnimatorController;

								numLayers = ac.layers.Length;

								if (_showLayer == null || _showLayer.Length != numLayers)
										_showLayer = new bool[controller.layers.Length];

								for (i=0; i<numLayers; i++) {
										layer = ac.layers [i];

										_showLayer [i] = EditorGUILayout.Foldout (_showLayer [i], layer.name);

										if (_showLayer [i]) {
												stateMachine = layer.stateMachine;

												numStates = stateMachine.states.Length;

												scrollPosition = GUILayout.BeginScrollView (scrollPosition, false, false);

												for (j=0; j<numStates; j++) {
														state = stateMachine.states [j].state;
														createInputStateGUI (state.name, Animator.StringToHash (state.name));
														//createInputStateGUI (state.name, state.uniqueNameHash);

												}

												GUILayout.EndScrollView ();
										}

								}

								EditorGUILayout.Separator ();

						}

						///////////////////// NEW CUSTOM STATE STATE //////////////////////
						EditorGUILayout.LabelField ("Custom States");

						EditorGUILayout.BeginHorizontal ();
						EditorGUILayout.LabelField ("New state name:", _stateNameLabelStyle);
						_newCustomStateName = EditorGUILayout.TextField (_newCustomStateName, _stateNameLabelStyle);

						if (_newCustomStateName != _prevNewCustomStateName)
								_warrningAddStateLabel = "";

						_prevNewCustomStateName = _newCustomStateName;

						if (GUILayout.Button ("+", _addRemoveButtonStyle)) {

								EditorGUIUtility.keyboardControl = 0;
								_selectedStateHash = 0;

								if (_newCustomStateName != null && _newCustomStateName.Length > 0) {
										int hash = Animator.StringToHash (_newCustomStateName);
										if (!_stateInputCombinations.ContainsKey (hash)) {//not already there
												_stateInputCombinations [hash] = new InputState (_newCustomStateName, hash);// string[]{"None","None"};
												_stateInputCombinations [hash].Add (new InputCombination ("None"));
												_stateInputCombinations [hash].Add (new InputCombination ("None"));

												_newCustomStateName = "";//reset
										} else
												_warrningAddStateLabel = "Already exist!";
								} else {

										_warrningAddStateLabel = "Empty state name!";

								}
						}

						GUI.color = Color.red;
						EditorGUILayout.LabelField (_warrningAddStateLabel);
						EditorGUILayout.EndHorizontal ();
						GUI.color = Color.white;

						EditorGUILayout.BeginHorizontal ();
						scrollPosition2 = EditorGUILayout.BeginScrollView (scrollPosition2, false, false);
						//Debug.Log ("Loop..." + _stateInputCombinations.Count+" inputmngr "+InputManager.Settings.stateInputs.Count);
						if (_stateInputCombinations != null)
								foreach (var KeyValuePair in _stateInputCombinations) {
										if (!existInController (KeyValuePair.Key)) {
												createInputStateGUI (KeyValuePair.Value.name, KeyValuePair.Key);
										}

								}
						GUILayout.EndScrollView ();
						EditorGUILayout.EndHorizontal ();

						//}

						//if event is of key or mouse
						if (Event.current.isKey) {

								if (Event.current.keyCode == KeyCode.Return) {
										_selectedStateHash = 0;
										_previousStateInput = null;
										this.Repaint ();
								} else if (Event.current.keyCode == KeyCode.Escape) {
										if (_selectedStateHash != 0) {
												_stateInputCombinations [_selectedStateHash].combinations [_isPrimary] = _previousStateInput;
												_previousStateInput = null;
												_selectedStateHash = 0;
										}
								}
						}

						if (_selectedStateHash != 0)
								InputManager.processGUIEvent (Event.current);//process input from keyboard & mouses

				}

				//////////////////////               CREATE STATE GUI             ///////////////////////

				/// <summary>
				/// Creates the state GUI.
				/// </summary>
				/// <param name="name">State Name.</param>
				/// <param name="hash">State Hash.</param>
				void createInputStateGUI (string name, int hash)
				{
						InputCombination[] combinations;
						string currentCombinationString;

						GUILayout.BeginHorizontal ();

						GUILayout.Label (name, _stateNameLabelStyle);

						if (_selectedStateHash != hash) {

								if (InputMapper._stateInputCombinations.ContainsKey (hash)) {

										combinations = InputMapper._stateInputCombinations [hash].combinations;

										if (combinations [0] == null)
												combinations [0] = new InputCombination ("None");

										if (GUILayout.Button (combinations [0].combinationString)) {
												_selectedStateHash = hash;
												_previousStateInput = null;
												_isPrimary = 0;
												EditorGUIUtility.keyboardControl = 0;
										}

										if (combinations [1] == null)
												combinations [1] = new InputCombination ("None");

										if (GUILayout.Button (combinations [1].combinationString)) {
												_selectedStateHash = hash;
												_previousStateInput = null;
												_isPrimary = 1;
												EditorGUIUtility.keyboardControl = 0;
										}

										//DELETE
										if (GUILayout.Button ("-", _addRemoveButtonStyle)) {
												//delete
												_deleteStateWithHash = hash;
												//this.Repaint();
										}
								} else {
										if (GUILayout.Button ("None")) {

												InputState state = _stateInputCombinations [hash] = new InputState (name, hash);
												state.Add (new InputCombination ((int)KeyCode.None), 0);

												_selectedStateHash = hash;
												_previousStateInput = null;
												_isPrimary = 0;
												EditorGUIUtility.keyboardControl = 0;
										}

										if (GUILayout.Button ("None")) {

												InputState state = _stateInputCombinations [hash] = new InputState (name, hash);
												state.Add (new InputCombination ((int)KeyCode.None), 1);

												_selectedStateHash = hash;
												_previousStateInput = null;
												_isPrimary = 1;
												EditorGUIUtility.keyboardControl = 0;
										}

								}

						} else {

								if (InputMapper._stateInputCombinations.ContainsKey (hash)) {
										combinations = InputMapper._stateInputCombinations [hash].combinations;

										currentCombinationString = combinations [_isPrimary].combinationString;

										if (_previousStateInput == null) {
												_previousStateInput = combinations [_isPrimary].Clone ();
										}

								} else {
										currentCombinationString = "None";
								}

								GUILayout.Label (currentCombinationString);//, _inputLabelStyle);

								this.Repaint ();
						}

						//

						GUILayout.EndHorizontal ();

						EditorGUILayout.Separator ();
				}

				///////////////////     ON DESTROY     ////////////////
				void OnDestroy ()
				{

						_selectedStateHash = 0;
						_deleteStateWithHash = 0;
						__wereDevicesEnumerated = false;

						if (!Application.isPlaying) {

								InputManager.Dispose ();

						}
				}
		}
}


text:
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using Microsoft.Win32;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Internal;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// This enum is used to distinguish two sets of parameters on some of the remoting cmdlets.
    /// </summary>
    internal enum RunspaceParameterSet
    {
        /// <summary>
        /// Use ComputerName parameter set
        /// </summary>
        ComputerName,
        /// <summary>
        /// Use Runspace Parameter set
        /// </summary>
        Runspace
    }

    /// <summary>
    /// This is a static utility class that performs some of the common chore work for the
    /// the remoting cmdlets.
    /// </summary>
    internal static class RemotingCommandUtil
    {
        /// <summary>
        /// The existence of the following registry confirms that the host machine is a WinPE
        /// HKLM\System\CurrentControlSet\Control\MiniNT
        /// </summary>
        internal static string WinPEIdentificationRegKey = @"System\CurrentControlSet\Control\MiniNT";

        internal static bool HasRepeatingRunspaces(PSSession[] runspaceInfos)
        {
            if (runspaceInfos == null)
            {
                throw PSTraceSource.NewArgumentNullException("runspaceInfos");
            }

            if (runspaceInfos.GetLength(0) == 0)
            {
                throw PSTraceSource.NewArgumentException("runspaceInfos");
            }

            for (int i = 0; i < runspaceInfos.GetLength(0); i++)
            {
                for (int k = 0; k < runspaceInfos.GetLength(0); k++)
                {
                    if (i != k)
                    {
                        if (runspaceInfos[i].Runspace.InstanceId == runspaceInfos[k].Runspace.InstanceId)
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        internal static bool ExceedMaximumAllowableRunspaces(PSSession[] runspaceInfos)
        {
            if (runspaceInfos == null)
            {
                throw PSTraceSource.NewArgumentNullException("runspaceInfos");
            }

            if (runspaceInfos.GetLength(0) == 0)
            {
                throw PSTraceSource.NewArgumentException("runspaceInfos");
            }

            return false;
        }

        /// <summary>
        /// Checks the prerequisites for a cmdlet and terminates if the cmdlet
        /// is not valid
        /// </summary>
        internal static void CheckRemotingCmdletPrerequisites()
        {
#if UNIX
            // TODO: check that PSRP requirements are installed
            return;
#else
            bool notSupported = true;
            String WSManKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WSMAN\\";

            CheckHostRemotingPrerequisites();

            try
            {
                // the following registry key defines WSMan compatability
                // HKLM\Software\Microsoft\Windows\CurrentVersion\WSMAN\ServiceStackVersion
                string wsManStackValue = null;
                RegistryKey wsManKey = Registry.LocalMachine.OpenSubKey(WSManKeyPath);
                if (wsManKey != null)
                {
                    wsManStackValue = (string)wsManKey.GetValue("ServiceStackVersion");
                }

                Version wsManStackVersion = !string.IsNullOrEmpty(wsManStackValue) ?
                    new Version(wsManStackValue.Trim()) :
                    System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STACK_VERSION;

                // WSMan stack version must be 2.0 or later.
                if (wsManStackVersion >= new Version(2, 0))
                {
                    notSupported = false;
                }
            }
            catch (FormatException)
            {
                notSupported = true;
            }
            catch (OverflowException)
            {
                notSupported = true;
            }
            catch (ArgumentException)
            {
                notSupported = true;
            }
            catch (System.Security.SecurityException)
            {
                notSupported = true;
            }
            catch (ObjectDisposedException)
            {
                notSupported = true;
            }

            if (notSupported)
            {
                // WSMan is not supported on this platform
                throw new InvalidOperationException(
                     "Windows PowerShell remoting features are not enabled or not supported on this machine.\nThis may be because you do not have the correct version of WS-Management installed or this version of Windows does not support remoting currently.\n For more information, type 'get-help about_remote_requirements'.");
            }
#endif
        }

        /// <summary>
        /// Facilitates to check if remoting is supported on the host machine.
        /// PowerShell remoting is supported on all Windows SQU's except WinPE.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// When PowerShell is hosted on a WinPE machine, the execution
        /// of this API would result in an InvalidOperationException being
        /// thrown, indicating that remoting is not supported on a WinPE machine.
        /// </exception>
        internal static void CheckHostRemotingPrerequisites()
        {
            // A registry key indicates if the SKU is WINPE. If this turns out to be true,
            // then an InValidOperation exception is thrown.
            bool isWinPEHost = Utils.IsWinPEHost();
            if (isWinPEHost)
            {
                // WSMan is not supported on this platform
                //throw new InvalidOperationException(
                //     "WinPE does not support Windows PowerShell remoting");
                ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.WinPERemotingNotSupported)), null, ErrorCategory.InvalidOperation, null);
                throw new InvalidOperationException(errorRecord.ToString());
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Component, ViewEncapsulation } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { MatIconRegistry } from '@angular/material';

@Component({
  moduleId: module.id,
  selector: 'md-icon-demo',
  templateUrl: 'icon-demo.html',
  styleUrls: ['icon-demo.css'],
  viewProviders: [MatIconRegistry],
  encapsulation: ViewEncapsulation.None,
})
export class IconDemoComponent {
  constructor(mdIconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
    mdIconRegistry
        .addSvgIcon('thumb-up',
          sanitizer.bypassSecurityTrustResourceUrl('/assets/svg/thumbup-icon.svg'))
        .addSvgIconSetInNamespace('core',
          sanitizer.bypassSecurityTrustResourceUrl('/assets/svg/core-icon-set.svg'))
        .registerFontClassAlias('fontawesome', 'fa');
  }
}


text:
package kubecli

import (
	"crypto/sha256"
	"fmt"
	"hash"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/gorilla/websocket"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"k8s.io/apimachinery/pkg/util/rand"
)

var _ = Describe("Websocket", func() {

	Context("data proxied through our websocket proxy", func() {
		var proxy *httptest.Server
		var target *httptest.Server
		var receivedDataHash hash.Hash
		var done chan error
		BeforeEach(func() {
			done = make(chan error)
			receivedDataHash = sha256.New()
			target = newTargetServer(receivedDataHash, done)
			proxy = newProxyServer(target)
		})
		AfterEach(func() {
			proxy.Close()
			target.Close()
		})
		It("should transfer arbitrary sized packets which are bigger and smaller than the websocket buffer", func() {
			proxyCon := dial(proxy)
			defer proxyCon.Close()
			messages := [][]byte{
				[]byte(rand.String(WebsocketMessageBufferSize - 10)),
				[]byte(rand.String(WebsocketMessageBufferSize + 10)),
				[]byte(rand.String(10)),
				[]byte(rand.String(WebsocketMessageBufferSize*3 + 10)),
			}

			expectedDataHash := sha256.New()
			writer := binaryWriter{conn: proxyCon}
			for _, msg := range messages {
				expectedDataHash.Write(msg)
				_, err := writer.Write(msg)
				Expect(err).ToNot(HaveOccurred())
			}
			err := proxyCon.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
			Expect(err).ToNot(HaveOccurred(), "failed to write close message")
			err = <-done
			Expect(err).ToNot(HaveOccurred(), "target server did not receive a propler close message")
			Expect(fmt.Sprintf("%x", expectedDataHash.Sum(nil))).To(Equal(fmt.Sprintf("%x", receivedDataHash.Sum(nil))))
		})
	})

})

func newTargetServer(writer io.Writer, done chan error) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer GinkgoRecover()
		upgrader := NewUpgrader()
		targetCon, err := upgrader.Upgrade(w, r, nil)
		Expect(err).ToNot(HaveOccurred())
		_, err = CopyFrom(writer, targetCon)
		done <- err
	}))
}

func newProxyServer(target *httptest.Server) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer GinkgoRecover()
		upgrader := NewUpgrader()
		src, err := upgrader.Upgrade(w, r, nil)
		Expect(err).ToNot(HaveOccurred())
		targetURL := "ws" + strings.TrimPrefix(target.URL, "http")
		dst, _, err := Dial(targetURL, nil)
		Expect(err).ToNot(HaveOccurred())
		defer dst.Close()
		_, _ = Copy(dst, src)
	}))
}

func dial(proxy *httptest.Server) *websocket.Conn {
	u := "ws" + strings.TrimPrefix(proxy.URL, "http")
	proxyCon, _, err := Dial(u, nil)
	Expect(err).ToNot(HaveOccurred())
	return proxyCon
}


text:
#include "DetectorConstruction.hh"
#include "DetectorMessenger.hh"

#include "globals.hh"
#include "G4Material.hh"
#include "G4NistManager.hh"
#include "Materials.hh"
#include "G4UnitsTable.hh"

#include "G4Box.hh"
#include "G4Tubs.hh"
#include "G4LogicalVolume.hh"
#include "G4PVReplica.hh"
#include "G4PVPlacement.hh"

#include "G4GeometryManager.hh"
#include "G4PhysicalVolumeStore.hh"
#include "G4LogicalVolumeStore.hh"
#include "G4SolidStore.hh"

#include "CaloSensitiveDetector.hh"
#include "G4SDManager.hh"

#include "G4VisAttributes.hh"
#include "G4Colour.hh"

#include "G4FieldManager.hh"
#include "G4TransportationManager.hh"
#include "G4UserLimits.hh"

#include <iostream>
#include <string>
#include <sstream>
#include "Analysis.hh"

/**
 * DetectorConstruction
 *
 * Setting the default detector construciton.
 */
DetectorConstruction::DetectorConstruction() : G4VUserDetectorConstruction(),
  fCheckOverlaps(true){

    worldSizeZ  = 25*cm;      // Fixed World Size;

    // Geometry parameters
    absThickness = 2*cm;	        // Thickness of Absorber
    gapThickness = 1*cm;            // Thickness of Gap
    oRadius  = 2.54*cm;		        // Outer Radius of Detector
    iRadius = 0.*cm;				// Inner radious of  Detector
    startAngle = 0.*deg;
    spanAngle = 360.*deg;

    // Compute parameters
    ComputeParameters();

    // Define materials
    materials = Materials::GetInstance();
    SetAbsorberMaterial("PSLiF");
    SetGapMaterial("G4_PLEXIGLASS");
    defaultMaterial = materials->GetMaterial("G4_Galactic");

    // Create commands for interactive defiantions of the calorimeter
    detectorMessenger = new DetectorMessenger(this);
}

DetectorConstruction::~DetectorConstruction(){
  delete detectorMessenger;
}

/**
 * Construct
 *
 * Creating the detector's world volume
 */
G4VPhysicalVolume* DetectorConstruction::Construct(){

  // Return Physical World
  G4VPhysicalVolume* calo = ConstructCalorimeter();

  // Set Visulation Attributes
  SetVisAttributes();

  // Assign Sensitve Detectors
  SetSensitiveDetectors();
  return calo;
}

/**
 * ComputeParameters
 *
 */
void DetectorConstruction::ComputeParameters(){

  caloThickness = absThickness+2*gapThickness;
  worldSizeXY = 1.2 * oRadius;
}

/**
 * PrintCaloParameters
 *
 * Prints the parameters of the geometry
 */
void DetectorConstruction::PrintCaloParameters(){

  // print parameters
  G4cout << "\n------------ Calorimeter Parameters ---------------------"
    <<"\n--> The detector is a single layer of: \n\t[ "
    << G4BestUnit(absThickness,"Length")<< " of " << absMaterial->GetName()
    << " + "
    << G4BestUnit(gapThickness,"Length") << " of " << gapMaterial->GetName() << " ]"
    << "\n--> The calormeter is " <<G4BestUnit(caloThickness,"Length") << " thick"
    << " with a radius of "<<G4BestUnit(oRadius,"Length")<<""
    << "\n------------------------------------------------------------\n"
    <<" The world is "<<worldSizeXY/cm<<" cm by "<<worldSizeXY/cm
    <<" cm by "<<worldSizeZ/cm<<" cm."
    <<G4endl;
}

/**
 * ConstructCalorimeter()
 *
 * Calorimeter is constructed as a solid cylinder of the gap (non-scintillating)
 * material with layers of the absorber (scintillating) material.
 */
G4VPhysicalVolume* DetectorConstruction::ConstructCalorimeter(){

  // Clean old geometry, if any
  G4GeometryManager::GetInstance()->OpenGeometry();
  G4PhysicalVolumeStore::GetInstance()->Clean();
  G4LogicalVolumeStore::GetInstance()->Clean();
  G4SolidStore::GetInstance()->Clean();

  // complete the Calor parameters definition
  ComputeParameters();

  // World
  worldS = new G4Box("World",worldSizeXY, worldSizeXY, worldSizeZ);
  worldLV = new G4LogicalVolume(worldS,defaultMaterial,"World");
  worldPV = new G4PVPlacement(0,G4ThreeVector(),worldLV,"World",
      0,false,0,fCheckOverlaps);

  //
  // Setting up the Calorimeter
  //
  // The beam is shotting along the z, comming from +z

  // Absorber
  absS = new G4Tubs("Abs",iRadius,oRadius,absThickness/2,0,360*deg);
  absLV = new G4LogicalVolume(absS,absMaterial,"Absorber",0);
  absPV = new G4PVPlacement(0,G4ThreeVector(0,0,(gapThickness+absThickness)/2),
      absLV,"Absorber",worldLV,false,0,fCheckOverlaps);

  // Spacer / gap
  gapS = new G4Tubs("Gap",iRadius,oRadius,gapThickness/2,0,360*deg);
  gapLV = new G4LogicalVolume(gapS,gapMaterial,"Gap",0);
  gapPV = new G4PVPlacement(0,G4ThreeVector(),
      gapLV,"Gap",worldLV,false,0,fCheckOverlaps);

  PrintCaloParameters();

  // Return the worlds physical volume
  return worldPV;
}
/**
 * SetSensitiveDetectors
 *
 * Setting the Sensitive Detectors of the Detector
 */
void DetectorConstruction::SetSensitiveDetectors(){
  G4SDManager* SDman = G4SDManager::GetSDMpointer();
  caloSD = new CaloSensitiveDetector("SD/CaloSD","CaloHitCollection");
  SDman->AddNewDetector(caloSD);
  absLV->SetSensitiveDetector(caloSD);

  // Setting the Maximum Step Size
  G4double maxStep = 0.01*absThickness;
  absLV->SetUserLimits(new G4UserLimits(maxStep));
}
/**
 * SetVisAttributes()
 *
 * Sets the visualtion attributes
 */
#include "G4Colour.hh"
void DetectorConstruction::SetVisAttributes(){

  // Setting the Visualization attributes for the Abs
  {G4VisAttributes* atb= new G4VisAttributes(G4Colour::Cyan());
    //atb->SetForceWireframe(true);
    atb->SetForceSolid(true);
    absLV->SetVisAttributes(atb);}

    // Setting the Visualization attributes for the Calorimeter
    {G4VisAttributes* atb= new G4VisAttributes(G4Colour::Gray());
      //atb->SetForceWireframe(true);
      atb->SetForceSolid(true);
      gapLV->SetVisAttributes(atb);}

      // Setting the Layers to be white and invisiable
      {G4VisAttributes* atb = new G4VisAttributes(G4Colour::White());
        atb->SetForceWireframe(true);
        atb->SetVisibility(false);
        worldLV->SetVisAttributes(atb);}

        // Setting the World to be white and invisiable
        {G4VisAttributes* atb = new G4VisAttributes(G4Colour::White());
          atb->SetForceWireframe(true);
          atb->SetVisibility(false);
          worldPV->GetLogicalVolume()->SetVisAttributes(atb);}

}

/**
 * SetAbsorberMaterial
 *
 * Set's the absorber material, which contains the neutron absorber
 */
void DetectorConstruction::SetAbsorberMaterial(G4String materialChoice){
  // search the material by its name
  G4Material* pttoMaterial = materials->GetMaterial(materialChoice);
  if (pttoMaterial) absMaterial = pttoMaterial;
}
/**
 * SetGapMaterial
 *
 * Set's the gap material.
 */
void DetectorConstruction::SetGapMaterial(G4String materialChoice){
  // search the material by its name
  G4Material* pttoMaterial = materials->GetMaterial(materialChoice);
  if (pttoMaterial) gapMaterial = pttoMaterial;
}

/**
 * SetAbsorberThickness
 *
 * Sets the absorber thickness
 */
void DetectorConstruction::SetAbsorberThickness(G4double val){
  absThickness = val;
}

/**
 * SetGapThickness
 *
 * Sets the thickness of the gap
 */
void DetectorConstruction::SetGapThickness(G4double val){
  gapThickness = val;
}

/**
 * SetCaloRadius
 *
 * Sets the calorimter radius
 */
void DetectorConstruction::SetCaloRadius(G4double val){
  oRadius = val;
}

#include "G4RunManager.hh"

void DetectorConstruction::UpdateGeometry(){
  G4RunManager::GetRunManager()->DefineWorldVolume(ConstructCalorimeter());
  SetVisAttributes();
  absLV->SetSensitiveDetector(caloSD);

  // Setting the Maximum Step Size
  G4double maxStep = 0.01*absThickness;
  absLV->SetUserLimits(new G4UserLimits(maxStep));

  G4RunManager::GetRunManager()->GeometryHasBeenModified();
}


text:
/**
 * DO NOT EDIT
 *
 * This file was automatically generated by
 *   https://github.com/Polymer/tools/tree/master/packages/gen-typescript-declarations
 *
 * To modify these typings, edit the source file(s):
 *   lib/utils/settings.js
 */

// tslint:disable:variable-name Describing an API that's defined elsewhere.
// tslint:disable:no-any describes the API as best we are able today

import {pathFromUrl} from './resolve-url.js';

export {setRootPath};

/**
 * Sets the global rootPath property used by `ElementMixin` and
 * available via `rootPath`.
 */
declare function setRootPath(path: string): void;

export {setSanitizeDOMValue};

/**
 * Sets the global sanitizeDOMValue available via this module's exported
 * `sanitizeDOMValue` variable.
 */
declare function setSanitizeDOMValue(newSanitizeDOMValue: ((p0: any, p1: string, p2: string, p3: Node|null) => any)|undefined): void;

export {setPassiveTouchGestures};

/**
 * Sets `passiveTouchGestures` globally for all elements using Polymer Gestures.
 */
declare function setPassiveTouchGestures(usePassive: boolean): void;

export {setStrictTemplatePolicy};

/**
 * Sets `strictTemplatePolicy` globally for all elements
 */
declare function setStrictTemplatePolicy(useStrictPolicy: boolean): void;

export {setAllowTemplateFromDomModule};

/**
 * Sets `lookupTemplateFromDomModule` globally for all elements
 */
declare function setAllowTemplateFromDomModule(allowDomModule: boolean): void;

export {setLegacyOptimizations};

/**
 * Sets `legacyOptimizations` globally for all elements to enable optimizations
 * when only legacy based elements are used.
 */
declare function setLegacyOptimizations(useLegacyOptimizations: boolean): void;

export {setSyncInitialRender};

/**
 * Sets `syncInitialRender` globally for all elements to enable synchronous
 * initial rendering.
 */
declare function setSyncInitialRender(useSyncInitialRender: boolean): void;


text:
using System;

namespace Messages.Demo04
{
    public class OrderPreparedEvent : BaseMessage
    {
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<TITLE>Man page of LP</TITLE>

LP

Section: Linux Programmer's Manual (4)
Updated: 1995-01-15
Index
Return to Main Contents

NAME

lp - line printer devices

SYNOPSIS

#include <linux/lp.h>

CONFIGURATION

lp[0-2] are character devices for the parallel line printers;
they have major number 6 and minor number 0-2.
The minor numbers
correspond to the printer port base addresses 0x03bc, 0x0378 and 0x0278.
Usually they have mode 220 and are owned by root and group lp.
You can use printer ports either with polling or with interrupts.
Interrupts are recommended when high traffic is expected, for example,
for laser printers.
For usual dot matrix printers polling will usually be enough.
The default is polling.

DESCRIPTION

The following
ioctl(2)

calls are supported:

int ioctl(int fd, LPTIME, int arg)

Sets the amount of time that the driver sleeps before rechecking the printer
when the printer's buffer appears to be filled to
arg.

If you have a fast printer, decrease this number;
if you have a slow printer, then increase it.
This is in hundredths of a second, the default 2
being 0.02 seconds.
It only influences the polling driver.

int ioctl(int fd, LPCHAR, int arg)

Sets the maximum number of busy-wait iterations which the polling driver does
while waiting for the printer to get ready for receiving a character to
arg.

If printing is too slow, increase this number; if the
system gets too slow, decrease this number.
The default is 1000.
It only influences the polling driver.

int ioctl(int fd, LPABORT, int arg)

If
arg

is 0, the printer driver will retry on errors, otherwise
it will abort.
The default is 0.

int ioctl(int fd, LPABORTOPEN, int arg)

If
arg

is 0,
open(2)

will be aborted on error, otherwise error will be ignored.
The default is to ignore it.

int ioctl(int fd, LPCAREFUL, int arg)

If
arg

is 0, then the out-of-paper, offline and error signals are
required to be false on all writes, otherwise they are ignored.
The default is to ignore them.

int ioctl(int fd, LPWAIT, int arg)

Sets the number of busy waiting iterations to wait before strobing the
printer to accept a just-written character, and the number of iterations to
wait before turning the strobe off again,
to
arg.

The specification says this time should be 0.5
microseconds, but experience has shown the delay caused by the code is
already enough.
For that reason, the default value is 0.
This is used for both the polling and the interrupt driver.

int ioctl(int fd, LPSETIRQ, int arg)

This
ioctl(2)

requires superuser privileges.
It takes an
int

containing the new IRQ as argument.
As a side effect, the printer will be reset.
When
arg

is 0, the polling driver will be used, which is also default.

int ioctl(int fd, LPGETIRQ, int *arg)

Stores the currently used IRQ in
arg.

int ioctl(int fd, LPGETSTATUS, int *arg)

Stores the value of the status port in
arg.

The bits have the following meaning:

LP_PBUSY	inverted busy input, active high

LP_PACK	unchanged acknowledge input, active low

LP_POUTPA	unchanged out-of-paper input, active high

LP_PSELECD	unchanged selected input, active high

LP_PERRORP	unchanged error input, active low

Refer to your printer manual for the meaning of the signals.
Note that undocumented bits may also be set, depending on your printer.

int ioctl(int fd, LPRESET)

Resets the printer.
No argument is used.

FILES

/dev/lp*

SEE ALSO

chmod(1),

chown(1),

mknod(1),

lpcntl(8),

tunelp(8)

Index

NAME

SYNOPSIS

CONFIGURATION

DESCRIPTION

FILES

SEE ALSO

This document was created by
man2html,
using the manual pages.

Time: 02:55:19 GMT, September 18, 2014


text:
package com.home.jsquad.knowhunt.android.maps;

import org.osmdroid.bonuspack.overlays.MapEventsReceiver;
import org.osmdroid.util.GeoPoint;

import java.util.concurrent.Callable;

public class MapOnClickListener implements MapEventsReceiver
{

    Callable<Void> _callback;

    public MapOnClickListener(Callable<Void> callback)
    {
        _callback = callback;
    }

    @Override
    public boolean singleTapConfirmedHelper(GeoPoint p) {
        boolean shouldCallCallback = false;

        if (shouldCallCallback) {
            try {
                _callback.call();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return false;
    }

    @Override
    public boolean longPressHelper(GeoPoint p) {
        return false;
    }
}


text:
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.messages.util;

import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.*;

/**
 * This class holds attributes which identifies Template Artifact uniquely and
 * defined in ESB Mediation Debugger communication channel
 *

 * Attribute values this class holding are : <u1>
 *
Template Key

 *
Mediator Position
<u1>
 */
public class ESBTemplateBean {

    private String templateKey;
    private ESBMediatorPosition mediatorPosition;

    public ESBTemplateBean(String sequenceKey, ESBMediatorPosition mediatorPosition) {
        this.templateKey = sequenceKey;
        this.mediatorPosition = mediatorPosition;
    }

    @Override
    public boolean equals(Object templateBean) {
        if (templateBean instanceof ESBTemplateBean) {
            ESBTemplateBean templateBeanTemp = (ESBTemplateBean) templateBean;
            if (!(getTemplateKey().equals((templateBeanTemp).getTemplateKey()) && getMediatorPosition().equals(
                    templateBeanTemp.getMediatorPosition()))) {
                return false;
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        int result = INITIAL_HASH_CODE_RESULT_VALUE;
        result = HASHCODE_MULTIPLIER_VALUE * result + getTemplateKey().hashCode() + TEMPLATE_KEY_LABEL.hashCode();
        result = HASHCODE_MULTIPLIER_VALUE * result + getMediatorPosition().hashCode()
                + MEDIATOR_POSITION_LABEL.hashCode();
        return result;
    }

    public String getTemplateKey() {
        return templateKey;
    }

    public void setTemplateKey(String sequenceKey) {
        this.templateKey = sequenceKey;
    }

    public ESBMediatorPosition getMediatorPosition() {
        return mediatorPosition;
    }

    public void setMediatorPosition(ESBMediatorPosition mediatorPosition) {
        this.mediatorPosition = mediatorPosition;
    }

}


text:
#include <gasnet_coll_pami.h>

#if GASNET_PAMI_NATIVE_COLL

static void
gasnete_coll_pami_bcast(const gasnet_team_handle_t team, void *dst,
                        gasnet_image_t srcimage, const void *src,
                        size_t nbytes, int flags GASNETE_THREAD_FARG)
{
    const int i_am_root = gasnete_coll_image_is_local(team, srcimage);

  #if GASNET_PAR
    int i_am_leader = gasnete_coll_pami_images_barrier(team); /* XXX: over-synced for IN_NO and IN_MY */

    if ((flags & GASNET_COLL_LOCAL) && i_am_root) {
        /* root thread must be leader for its node */
        const gasnete_coll_threaddata_t * const td = GASNETE_COLL_MYTHREAD_NOALLOC;
        i_am_leader = (srcimage == td->my_image);
    }
  #else
    const int i_am_leader = 1;
  #endif

    if (i_am_leader) {
        volatile unsigned int done = 0;
        pami_result_t rc;
        pami_xfer_t op;

        if (flags & GASNET_COLL_IN_ALLSYNC) gasnetc_fast_barrier();

        op = gasnete_op_template_bcast;
        op.cookie = (void *)&done;
        op.algorithm = team->pami.bcast_alg;
        op.cmd.xfer_broadcast.root = gasnetc_endpoint(GASNETE_COLL_REL2ACT(team,gasnete_coll_image_node(team, srcimage)));
        op.cmd.xfer_broadcast.buf  = i_am_root ? (/*not-const*/ void *)src : dst;
        op.cmd.xfer_broadcast.typecount = nbytes;

        GASNETC_PAMI_LOCK(gasnetc_context);
        rc = PAMI_Collective(gasnetc_context, &op);
        GASNETC_PAMI_UNLOCK(gasnetc_context);
        GASNETC_PAMI_CHECK(rc, "initiating blocking broadcast");

        if (i_am_root) {
          if (dst != src) GASNETE_FAST_UNALIGNED_MEMCPY(dst, src, nbytes);
        }

        gasneti_polluntil(done);
    }

  #if GASNET_PAR
    if (i_am_leader) {
        gasneti_assert(NULL == team->pami.tmp_addr);
        gasneti_sync_writes();
        team->pami.tmp_addr = dst; /* wakes pollers, below */
        (void) gasnete_coll_pami_images_barrier(team); /* matches instance below vvvv */
        team->pami.tmp_addr = NULL;
    } else {
        gasneti_waitwhile(NULL == team->pami.tmp_addr);
        GASNETE_FAST_UNALIGNED_MEMCPY(dst, team->pami.tmp_addr, nbytes);
        (void) gasnete_coll_pami_images_barrier(team); /* matches instance above ^^^^ */
    }

    if (flags & GASNET_COLL_OUT_ALLSYNC) {
        if (i_am_leader) gasnetc_fast_barrier();
        (void) gasnete_coll_pami_images_barrier(team);
    }
  #else
    if (flags & GASNET_COLL_OUT_ALLSYNC) gasnetc_fast_barrier();
  #endif
}

extern void
gasnete_coll_broadcast_pami(gasnet_team_handle_t team, void *dst,
                            gasnet_image_t srcimage, void *src,
                            size_t nbytes, int flags GASNETE_THREAD_FARG)
{
  if ((team->pami.geom == PAMI_GEOMETRY_NULL) || !gasnete_use_pami_bcast) {
    /* Use generic implementation for cases we don't (yet) handle, or when disabled */
    gasnet_coll_handle_t handle;
    handle = gasnete_coll_broadcast_nb_default(team,dst,srcimage,src,nbytes,flags,0 GASNETE_THREAD_PASS);
    gasnete_coll_wait_sync(handle GASNETE_THREAD_PASS);
  } else {
    /* Use PAMI-specific implementation */
    gasnete_coll_pami_bcast(team,dst,srcimage,src,nbytes,flags GASNETE_THREAD_PASS);
  }
}

extern void
gasnete_coll_broadcastM_pami(gasnet_team_handle_t team,
                             void * const dstlist[],
                             gasnet_image_t srcimage, void *src,
                             size_t nbytes, int flags GASNETE_THREAD_FARG)
{
  if ((team->pami.geom == PAMI_GEOMETRY_NULL) || !gasnete_use_pami_bcast) {
    /* Use generic implementation for cases we don't (yet) handle, or when disabled */
    gasnet_coll_handle_t handle;
    handle = gasnete_coll_broadcastM_nb_default(team,dstlist,srcimage,src,nbytes,flags,0 GASNETE_THREAD_PASS);
    gasnete_coll_wait_sync(handle GASNETE_THREAD_PASS);
  } else {
    /* Use PAMI-specific implementation */
  #if GASNET_PAR
    const gasnete_coll_threaddata_t * const td = GASNETE_COLL_MYTHREAD_NOALLOC;
    void * const dst = dstlist[((flags & GASNET_COLL_LOCAL) ? td->my_local_image : td->my_image)];
  #else
    void * const dst = GASNETE_COLL_MY_1ST_IMAGE(team, dstlist, flags);
  #endif

    gasnete_coll_pami_bcast(team,dst,srcimage,src,nbytes,flags GASNETE_THREAD_PASS);
  }
}

#endif /* GASNET_PAMI_NATIVE_COLL */


text:
import ObjectCreate from "../../helper/ObjectCreate";

function Blank() {}
Blank.prototype = ObjectCreate( null );

export default Blank;


text:
Sample of name server using rails with bind-sdb.

# Set up docker containers and rails server
* PostgreSQL
    * docker build -t pg94 docker/postgres
    * docker run -itd --name postgres-server -p 5432:5432 -e POSTGRES_PASSWORD=hogehoge pg94
    * See Details (https://hub.docker.com/_/postgres/)

* Rails
    * rake db:create db:migrate
    * rake db:seed
        * insert SOA and NS
        * insert sample IP information (aaa.hoge.com, 10.100.200.1)
    * rails server
        * Please Add your IP Information

* Bind SDB
    * modify IP in docker/bind-sdb/named.conf
        * Please set your postgres-server IP or docker host IP
    * $ docker build -t bind_sdb_with_rails/bind-sdb docker/bind-sdb
    * $ docker run -itd --name name-server -p 53:53 -p 53:53/udp bind_sdb_with_rails/bind-sdb

# Look up name
* dig @<your-container-ip> aaa.hoge.com
    * => 10.100.200.1
* dig @<your-container-ip> -x 10.100.200.1
    * => aaa.hoge.com


text:
package org.wildfly.camel.test.google.bigquery;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.model.TableDataInsertAllRequest;
import com.google.api.services.bigquery.model.TableDataInsertAllResponse;

import net.bytebuddy.ByteBuddy;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.component.google.bigquery.GoogleBigQueryConfiguration;
import org.apache.camel.component.google.bigquery.GoogleBigQueryConstants;
import org.apache.camel.component.google.bigquery.GoogleBigQueryEndpoint;
import org.apache.camel.component.google.bigquery.GoogleBigQueryProducer;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultExchange;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.objenesis.Objenesis;
import org.wildfly.extension.camel.CamelAware;

@CamelAware
@RunWith(Arquillian.class)
public class GoogleBigQueryIntegrationTest {

    private static final String TEST_PROJECT_ID = "testProjectId";
    private static final String TEST_TABLE_ID = "testTableId";
    private static final String TEST_DATASET_ID = "testDatasetId";
    private GoogleBigQueryConfiguration configuration;
    private Bigquery bigquery;
    private GoogleBigQueryEndpoint endpoint;
    private Bigquery.Tabledata tabledata;
    private Bigquery.Tabledata.InsertAll mockInsertall;

    @Deployment
    public static JavaArchive createDeployment() {
        return ShrinkWrap.create(JavaArchive.class, "camel-google-bigquery-tests.jar")
            .addPackages(true, Mockito.class.getPackage(), Objenesis.class.getPackage(), ByteBuddy.class.getPackage());
    }

    @Before
    public void setUp() throws Exception {
        configuration = new GoogleBigQueryConfiguration();

        bigquery = Mockito.mock(Bigquery.class);
        endpoint = Mockito.mock(GoogleBigQueryEndpoint.class);
        tabledata = Mockito.mock(Bigquery.Tabledata.class);
        mockInsertall = Mockito.mock(Bigquery.Tabledata.InsertAll.class);

        Mockito.when(bigquery.tabledata()).thenReturn(tabledata);
        Mockito.when(tabledata.insertAll(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any())).thenReturn(mockInsertall);

        TableDataInsertAllResponse mockResponse = new TableDataInsertAllResponse();
        Mockito.when(mockInsertall.execute()).thenReturn(mockResponse);
    }

    @Test
    public void sendMessage() throws Exception {
        createProducer().process(createExchangeWithBody(new DefaultCamelContext(), new HashMap<>()));
        ArgumentCaptor<TableDataInsertAllRequest> dataCaptor = ArgumentCaptor.forClass(TableDataInsertAllRequest.class);
        Mockito.verify(tabledata).insertAll(Mockito.eq(TEST_PROJECT_ID), Mockito.eq(TEST_DATASET_ID), Mockito.eq(TEST_TABLE_ID), dataCaptor.capture());
        List<TableDataInsertAllRequest> requests = dataCaptor.getAllValues();
        Assert.assertEquals(1, requests.size());
        Assert.assertEquals(1, requests.get(0).getRows().size());
        Assert.assertNull(requests.get(0).getRows().get(0).getInsertId());
    }

    @Test
    public void sendMessageWithTableId() throws Exception {
        Exchange exchange = createExchangeWithBody(new DefaultCamelContext(), new HashMap<>());
        exchange.getIn().setHeader(GoogleBigQueryConstants.TABLE_ID, "exchange_table_id");
        createProducer().process(exchange);
        ArgumentCaptor<TableDataInsertAllRequest> dataCaptor = ArgumentCaptor.forClass(TableDataInsertAllRequest.class);
        Mockito.verify(tabledata).insertAll(Mockito.eq(TEST_PROJECT_ID), Mockito.eq(TEST_DATASET_ID), Mockito.eq("exchange_table_id"), dataCaptor.capture());
        List<TableDataInsertAllRequest> requests = dataCaptor.getAllValues();
        Assert.assertEquals(1, requests.size());
        Assert.assertEquals(1, requests.get(0).getRows().size());
        Assert.assertNull(requests.get(0).getRows().get(0).getInsertId());
    }

    @Test
    public void useAsInsertIdConfig() throws Exception {
        configuration.setUseAsInsertId("row1");
        Map<String, String> map = new HashMap<>();
        map.put("row1", "value1");
        createProducer().process(createExchangeWithBody(new DefaultCamelContext(), map));
        ArgumentCaptor<TableDataInsertAllRequest> dataCaptor = ArgumentCaptor.forClass(TableDataInsertAllRequest.class);
        Mockito.verify(tabledata).insertAll(Mockito.eq(TEST_PROJECT_ID), Mockito.eq(TEST_DATASET_ID), Mockito.eq(TEST_TABLE_ID), dataCaptor.capture());
        List<TableDataInsertAllRequest> requests = dataCaptor.getAllValues();
        Assert.assertEquals(1, requests.size());
        Assert.assertEquals(1, requests.get(0).getRows().size());
        Assert.assertEquals("value1", requests.get(0).getRows().get(0).getInsertId());
    }

    @Test
    public void listOfMessages() throws Exception {
        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(new HashMap<>());
        messages.add(new HashMap<>());
        createProducer().process(createExchangeWithBody(new DefaultCamelContext(), messages));
        ArgumentCaptor<TableDataInsertAllRequest> dataCaptor = ArgumentCaptor.forClass(TableDataInsertAllRequest.class);
        Mockito.verify(tabledata).insertAll(Mockito.eq(TEST_PROJECT_ID), Mockito.eq(TEST_DATASET_ID), Mockito.eq(TEST_TABLE_ID), dataCaptor.capture());
        List<TableDataInsertAllRequest> requests = dataCaptor.getAllValues();
        Assert.assertEquals(1, requests.size());
        Assert.assertEquals(2, requests.get(0).getRows().size());
    }

    private GoogleBigQueryProducer createProducer() throws Exception {
        configuration.setProjectId(TEST_PROJECT_ID);
        configuration.setTableId(TEST_TABLE_ID);
        configuration.setDatasetId(TEST_DATASET_ID);
        return new GoogleBigQueryProducer(bigquery, endpoint, configuration);
    }

    private Exchange createExchangeWithBody(CamelContext camelContext, Object body) {
        Exchange exchange = new DefaultExchange(camelContext);
        Message message = exchange.getIn();
        message.setBody(body);
        return exchange;
    }
}


text:
#pragma once

#include <cuda.h>
#include <mutex>  // NOLINT
#include "paddle/fluid/platform/dynload/dynamic_loader.h"
#include "paddle/fluid/platform/port.h"

namespace paddle {
namespace platform {
namespace dynload {

extern std::once_flag cuda_dso_flag;
extern void* cuda_dso_handle;

#ifdef PADDLE_USE_DSO

#define DECLARE_DYNAMIC_LOAD_CUDA_WRAP(__name)                           \
  struct DynLoad__##__name {                                             \
    template <typename... Args>                                          \
    auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) {     \
      using cuda_func = decltype(&::__name);                             \
      std::call_once(cuda_dso_flag, []() {                               \
        cuda_dso_handle = paddle::platform::dynload::GetCUDADsoHandle(); \
      });                                                                \
      static void* p_##__name = dlsym(cuda_dso_handle, #__name);         \
      return reinterpret_cast<cuda_func>(p_##__name)(args...);           \
    }                                                                    \
  };                                                                     \
  extern struct DynLoad__##__name __name

#else

#define DECLARE_DYNAMIC_LOAD_CUDA_WRAP(__name) \
  struct DynLoad__##__name {                   \
    template <typename... Args>                \
    inline auto operator()(Args... args) {     \
      return ::__name(args...);                \
    }                                          \
  };                                           \
  extern DynLoad__##__name __name

#endif

/**
 * include all needed cuda driver functions
 **/
#define CUDA_ROUTINE_EACH(__macro)                      \
  __macro(cuGetErrorString);                            \
  __macro(cuModuleLoadData);                            \
  __macro(cuModuleGetFunction);                         \
  __macro(cuModuleUnload);                              \
  __macro(cuOccupancyMaxActiveBlocksPerMultiprocessor); \
  __macro(cuLaunchKernel);                              \
  __macro(cuCtxCreate);                                 \
  __macro(cuCtxGetCurrent);                             \
  __macro(cuDeviceGet);                                 \
  __macro(cuDevicePrimaryCtxGetState)

CUDA_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CUDA_WRAP);

#undef DECLARE_DYNAMIC_LOAD_CUDA_WRAP

}  // namespace dynload
}  // namespace platform
}  // namespace paddle


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2012 Eric Niebler

  Distributed under the Boost
  Software License, Version 1.0. (See accompanying
  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  -->
<header name="boost/proto/transform/lazy.hpp">
  <para>
    Contains definition of the
    <computeroutput>
      <classname alt="boost::proto::lazy">proto::lazy<></classname>
    </computeroutput> transform.
  </para>
  <namespace name="boost">
    <namespace name="proto">
      <struct name="lazy">
        <template>
          <template-type-parameter name="T"/>
        </template>
        <inherit><classname>proto::transform</classname>< lazy<T> ></inherit>
        <purpose>A <conceptname>PrimitiveTransform</conceptname> that uses
          <computeroutput><classname>proto::make<></classname></computeroutput> to build a
          <conceptname>CallableTransform</conceptname>, and then uses
          <computeroutput><classname>proto::call<></classname></computeroutput> to apply it.
        </purpose>
        <description>
          <para>
            <computeroutput>proto::lazy<></computeroutput> is useful as a higher-order transform,
            when the transform to be applied depends on the current state of the transformation. The
            invocation of the <computeroutput>
              <classname>proto::make<></classname>
            </computeroutput> transform evaluates any nested transforms, and the resulting type is treated
            as a <conceptname>CallableTransform</conceptname>, which is evaluated with
            <computeroutput><classname>proto::call<></classname></computeroutput>.
          </para>
          <para>
            For the full description of the behavior of the
            <computeroutput>
              <classname>proto::lazy<></classname>
            </computeroutput>
            transform, see the documentation for the nested
            <computeroutput>
              <classname>proto::lazy::impl<></classname>
            </computeroutput>
            class template.
          </para>
        </description>
        <struct name="impl">
          <template>
            <template-type-parameter name="Expr"/>
            <template-type-parameter name="State"/>
            <template-type-parameter name="Data"/>
          </template>
          <inherit><type><classname>proto::transform_impl</classname><Expr, State, Data></type></inherit>
          <typedef name="result_type">
            <type><replaceable>see-below</replaceable></type>
            <description>
              <para>
                <computeroutput><classname>proto::lazy</classname><T>::impl<Expr,State,Data>::result_type</computeroutput>
                is calculated as follows:
                <itemizedlist>
                  <listitem>
                    <para>
                      If <computeroutput>T</computeroutput> if of the form
                      <computeroutput>O(A<subscript>0</subscript>,…A<subscript>n</subscript>)</computeroutput>, then let <computeroutput>O'</computeroutput>
                      be <computeroutput>boost::result_of<<classname>proto::make</classname><O>(Expr, State, Data)>::type</computeroutput>
                      and let <computeroutput>T'</computeroutput> be <computeroutput>O'(A<subscript>0</subscript>,…A<subscript>n</subscript>)</computeroutput>.
                    </para>
                  </listitem>
                  <listitem>
                    <para>
                      If <computeroutput>T</computeroutput> if of the form
                      <computeroutput>O(A<subscript>0</subscript>,…A<subscript>n</subscript> ...)</computeroutput>, then let <computeroutput>O'</computeroutput>
                      be <computeroutput>boost::result_of<<classname>proto::make</classname><O>(Expr, State, Data)>::type</computeroutput>
                      and let <computeroutput>T'</computeroutput> be <computeroutput>O'(A<subscript>0</subscript>,…A<subscript>n</subscript> ...)</computeroutput>.
                    </para>
                  </listitem>
                  <listitem>
                    <para>
                      Otherwise, let <computeroutput>T'</computeroutput>
                      be <computeroutput>boost::result_of<<classname>proto::make</classname><T>(Expr, State, Data)>::type</computeroutput>.
                    </para>
                  </listitem>
                </itemizedlist>
                <para>
                  The result type is
                  <computeroutput>
                    boost::result_of<<classname>proto::call</classname><T'>(Expr, State, Data)>::type
                  </computeroutput>.
                </para>
              </para>
            </description>
          </typedef>
          <method-group name="public member functions">
            <method name="operator()" cv="const">
              <type>result_type</type>
              <parameter name="expr">
                <paramtype>typename impl::expr_param</paramtype>
              </parameter>
              <parameter name="state">
                <paramtype>typename impl::state_param</paramtype>
              </parameter>
              <parameter name="data">
                <paramtype>typename impl::data_param</paramtype>
              </parameter>
              <description>
                <para>
                  <computeroutput><classname>proto::lazy</classname><T>::impl<Expr,State,Data>::operator()</computeroutput> behaves as follows:
                  <itemizedlist>
                    <listitem>
                      <para>
                        If <computeroutput>T</computeroutput> if of the form
                        <computeroutput>O(A<subscript>0</subscript>,…A<subscript>n</subscript>)</computeroutput>, then let <computeroutput>O'</computeroutput>
                        be <computeroutput>boost::result_of<<classname>proto::make</classname><O>(Expr, State, Data)>::type</computeroutput>
                        and let <computeroutput>T'</computeroutput> be <computeroutput>O'(A<subscript>0</subscript>,…A<subscript>n</subscript>)</computeroutput>.
                      </para>
                    </listitem>
                    <listitem>
                      <para>
                        If <computeroutput>T</computeroutput> if of the form
                        <computeroutput>O(A<subscript>0</subscript>,…A<subscript>n</subscript> ...)</computeroutput>, then let <computeroutput>O'</computeroutput>
                        be <computeroutput>boost::result_of<<classname>proto::make</classname><O>(Expr, State, Data)>::type</computeroutput>
                        and let <computeroutput>T'</computeroutput> be <computeroutput>O'(A<subscript>0</subscript>,…A<subscript>n</subscript> ...)</computeroutput>.
                      </para>
                    </listitem>
                    <listitem>
                      <para>
                        Otherwise, let <computeroutput>T'</computeroutput>
                        be <computeroutput>boost::result_of<<classname>proto::make</classname><T>(Expr, State, Data)>::type</computeroutput>.
                      </para>
                    </listitem>
                  </itemizedlist>
                </para>
              </description>
              <returns>
                <para>
                  <computeroutput>
                    <classname>proto::call</classname><T'>()(expr, state, data)
                  </computeroutput>
                </para>
              </returns>
            </method>
          </method-group>
        </struct>
      </struct>
    </namespace>
  </namespace>
</header>