protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Settings); ActionBar.SetDisplayHomeAsUpEnabled(true); counter = 0; var prefs = AndroidAppPreferences.Create(Application.Context.GetSharedPreferences(KeySndrApplication.AppPreferencesId, FileCreationMode.Private)); editIpView = FindViewById<EditText>(Resource.Id.ipEditText); editPortView = FindViewById<EditText>(Resource.Id.portEditText); useCacheView = FindViewById<CheckBox>(Resource.Id.enableCache); if (!string.IsNullOrEmpty(prefs.Ip)) editIpView.Text = prefs.Ip; if (prefs.Port > 0) editPortView.Text = prefs.Port.ToString(); useCacheView.Checked = prefs.UseCache; probe = new Probe("KeySndrServer"); probe.BeaconsUpdated += Probe_BeaconsUpdated; t = new Timer(1000); t.Elapsed += TimerOnElapsed; if (Intent.Extras == null || !Intent.Extras.ContainsKey("search")) return; }
public Trigger(Probe probe, PropertyInfo datumProperty, TriggerValueCondition condition, object conditionValue, bool change, bool fireRepeatedly, bool useRegularExpressions, bool ignoreFirstDatum, TimeSpan startTime, TimeSpan endTime) : this() { if (probe == null) throw new Exception("Trigger is missing Probe selection."); else if (datumProperty == null) throw new Exception("Trigger is missing Property selection."); else if (conditionValue == null) throw new Exception("Trigger is missing Value selection."); else if (endTime <= startTime) throw new Exception("Trigger Start Time must precede End Time."); _probe = probe; _datumPropertyName = datumProperty.Name; _condition = condition; _conditionValue = conditionValue; _change = change; _fireRepeatedly = fireRepeatedly; _ignoreFirstDatum = ignoreFirstDatum; _startTime = startTime; _endTime = endTime; if (useRegularExpressions) _regularExpression = new Regex(_conditionValue.ToString()); }
private Boolean check_and_match_probes(Probe[] probes) { foreach (var probe in probes) { if (!probe.probeAndMatch()) return false; } return true; }
Probe crossover(Probe probeA, Probe probeB) { float[] childEngineTimes = new float[4]; for (int i = 0; i < childEngineTimes.Length; i++) { float r = Random.value; if (r < .5) { childEngineTimes [i] = probeA.engineTimes [i]; } else { childEngineTimes [i] = probeB.engineTimes [i]; } } Probe childProbe = new Probe (); childProbe.engineTimes = childEngineTimes; return childProbe; // GameObject childProbe = Instantiate (probePrefab, transform.position + new Vector3 (0f, 7f), Quaternion.identity) as GameObject; // childProbe.name = "ChildProbe"; // childProbe.GetComponent<Probe> ().engineTimes = childEngineTimes; }
private IList<Tuple<IValueProvider, IProbe>> Probe(IDictionary<string, string> context) { IList<Tuple<IValueProvider, IProbe>> queryResults = new List<Tuple<IValueProvider, IProbe>>(); foreach (var item in this._index) { var probe = new Probe(); foreach (var contributor in item.Item2) { contributor.Handle(context, probe); if (probe.Exclude) { break; } } if (!probe.Exclude) { queryResults.Add(new Tuple<IValueProvider, IProbe>(item.Item1, probe)); } } return queryResults; }
private void CubeMapSamplerSetIndex( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { Probe.Set S = _Pixel.ParentSet; byte C = 0; if ( S != null && S.SetIndex != -1 && (!m_IsolateSet || S.SetIndex == m_IsolatedSetIndex) ) { C = m_IsolateSet ? (byte) 255 : (byte) (255 * (1 + S.SetIndex) / m_Probe.m_Sets.Length); } _R = _G = _B = C; }
private void CubeMapSamplerEmissiveMatID( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { byte C = (byte) Math.Min( 255, 255 * ((1+_Pixel.EmissiveMatID) % 4) / 4 ); _R = _G = _B = C; }
private void CubeMapSamplerStaticLit( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { _R = (byte) Math.Min( 255, 255 * _Pixel.StaticLitColor.x ); _G = (byte) Math.Min( 255, 255 * _Pixel.StaticLitColor.y ); _B = (byte) Math.Min( 255, 255 * _Pixel.StaticLitColor.z ); }
private void CubeMapSamplerDistance( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { byte C = (byte) Math.Min( 255, 255 * 0.1f * _Pixel.Distance ); _R = _G = _B = C; }
/// <summary> /// Initializes a new instance of the <see cref="ProbePage"/> class. /// </summary> /// <param name="probe">Probe to display.</param> public ProbePage(Probe probe) { Title = "Probe"; StackLayout contentLayout = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.FillAndExpand }; string type = ""; if (probe is ListeningProbe) { type = "Listening"; } else if (probe is PollingProbe) { type = "Polling"; } contentLayout.Children.Add(new ContentView { Content = new Label { Text = probe.DisplayName + (type == "" ? "" : " (" + type + ")"), FontSize = 20, FontAttributes = FontAttributes.Italic, TextColor = Color.Accent, HorizontalOptions = LayoutOptions.Center }, Padding = new Thickness(0, 10, 0, 10) }); foreach (StackLayout stack in UiProperty.GetPropertyStacks(probe)) { contentLayout.Children.Add(stack); } #region script probes if (probe is ScriptProbe) { ScriptProbe scriptProbe = probe as ScriptProbe; Button editScriptsButton = new Button { Text = "Edit Scripts", FontSize = 20 }; contentLayout.Children.Add(editScriptsButton); editScriptsButton.Clicked += async(o, e) => { await Navigation.PushAsync(new ScriptRunnersPage(scriptProbe)); }; Button shareScriptButton = new Button { Text = "Share Definition", FontSize = 20 }; contentLayout.Children.Add(shareScriptButton); shareScriptButton.Clicked += async(o, e) => { string sharePath = SensusServiceHelper.Get().GetSharePath(".json"); using (StreamWriter shareFile = new StreamWriter(sharePath)) { shareFile.WriteLine(JsonConvert.SerializeObject(probe, SensusServiceHelper.JSON_SERIALIZER_SETTINGS)); } await SensusServiceHelper.Get().ShareFileAsync(sharePath, "Probe Definition", "application/json"); }; Button setAgentButton = new Button { Text = "Set Agent" + (scriptProbe.Agent == null ? "" : ": " + scriptProbe.Agent.Id), FontSize = 20, HorizontalOptions = LayoutOptions.FillAndExpand }; setAgentButton.Clicked += async(sender, e) => { await SetAgentButton_Clicked(setAgentButton, scriptProbe); }; contentLayout.Children.Add(setAgentButton); Button clearAgentButton = new Button { Text = "Clear Agent", FontSize = 20, HorizontalOptions = LayoutOptions.FillAndExpand }; clearAgentButton.Clicked += async(sender, e) => { if (scriptProbe.Agent != null) { if (await DisplayAlert("Confirm", "Are you sure you wish to clear the survey agent?", "Yes", "No")) { scriptProbe.Agent = null; setAgentButton.Text = "Set Agent"; } } await SensusServiceHelper.Get().FlashNotificationAsync("Survey agent cleared."); }; contentLayout.Children.Add(clearAgentButton); } #endregion #region proximity probe if (probe is IPointsOfInterestProximityProbe) { Button editTriggersButton = new Button { Text = "Edit Triggers", FontSize = 20, HorizontalOptions = LayoutOptions.FillAndExpand }; contentLayout.Children.Add(editTriggersButton); editTriggersButton.Clicked += async(o, e) => { await Navigation.PushAsync(new ProximityTriggersPage(probe as IPointsOfInterestProximityProbe)); }; } #endregion #region estimote probe if (probe is EstimoteBeaconProbe) { EstimoteBeaconProbe estimoteBeaconProbe = probe as EstimoteBeaconProbe; Button editBeaconsButton = new Button { Text = "Edit Beacons", FontSize = 20, HorizontalOptions = LayoutOptions.FillAndExpand }; contentLayout.Children.Add(editBeaconsButton); editBeaconsButton.Clicked += async(sender, e) => { await Navigation.PushAsync(new EstimoteBeaconProbeBeaconsPage(estimoteBeaconProbe)); }; Button setLocationButton = new Button { Text = estimoteBeaconProbe.Location == null ? "Set Location" : "Location: " + estimoteBeaconProbe.Location, FontSize = 20, HorizontalOptions = LayoutOptions.FillAndExpand }; contentLayout.Children.Add(setLocationButton); setLocationButton.Clicked += async(sender, e) => { List <EstimoteLocation> locations; try { locations = await estimoteBeaconProbe.GetLocationsFromCloudAsync(TimeSpan.FromSeconds(10)); if (locations.Count == 0) { throw new Exception("No locations present within Estimote Cloud."); } } catch (Exception ex) { await SensusServiceHelper.Get().FlashNotificationAsync("Failed to set location: " + ex.Message); return; } List <Input> inputs = await SensusServiceHelper.Get().PromptForInputsAsync("Set Location", new Input[] { new ItemPickerDialogInput("Location:", null, locations.Select(location => location.Name + " (" + location.Identifier + ")").ToList()) { AllowClearSelection = true } }, null, true, null, null, null, null, false); if (inputs == null || inputs[0]?.Value == null) { estimoteBeaconProbe.Location = null; await SensusServiceHelper.Get().FlashNotificationAsync("Location cleared."); setLocationButton.Text = "Set Location"; } else { try { string locationIdentifier = inputs[0].Value.ToString().Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)[1]; estimoteBeaconProbe.Location = locations.Single(location => location.Identifier == locationIdentifier); setLocationButton.Text = "Location: " + estimoteBeaconProbe.Location; } catch (Exception) { await SensusServiceHelper.Get().FlashNotificationAsync("Failed to set location."); } } }; } #endregion #region anonymization List <PropertyInfo> anonymizableProperties = probe.DatumType.GetProperties().Where(property => property.GetCustomAttribute <Anonymizable>() != null).ToList(); if (anonymizableProperties.Count > 0) { contentLayout.Children.Add(new Label { Text = "Anonymization", FontSize = 20, FontAttributes = FontAttributes.Italic, TextColor = Color.Accent, HorizontalOptions = LayoutOptions.Center }); List <StackLayout> anonymizablePropertyStacks = new List <StackLayout>(); foreach (PropertyInfo anonymizableProperty in anonymizableProperties) { Anonymizable anonymizableAttribute = anonymizableProperty.GetCustomAttribute <Anonymizable>(true); Label propertyLabel = new Label { Text = anonymizableAttribute.PropertyDisplayName ?? anonymizableProperty.Name + ":", FontSize = 20, HorizontalOptions = LayoutOptions.Start, VerticalTextAlignment = TextAlignment.Center }; // populate a picker of anonymizers for the current property Picker anonymizerPicker = new Picker { Title = "Select Anonymizer", HorizontalOptions = LayoutOptions.FillAndExpand }; anonymizerPicker.Items.Add("Do Not Anonymize"); foreach (Anonymizer anonymizer in anonymizableAttribute.AvailableAnonymizers) { anonymizerPicker.Items.Add(anonymizer.DisplayText); } anonymizerPicker.SelectedIndexChanged += (o, e) => { Anonymizer selectedAnonymizer = null; if (anonymizerPicker.SelectedIndex > 0) { selectedAnonymizer = anonymizableAttribute.AvailableAnonymizers[anonymizerPicker.SelectedIndex - 1]; // subtract one from the selected index since the JsonAnonymizer's collection of anonymizers start after the "None" option within the picker. } probe.Protocol.JsonAnonymizer.SetAnonymizer(anonymizableProperty, selectedAnonymizer); }; // set the picker's index to the current anonymizer (or "Do Not Anonymize" if there is no current) Anonymizer currentAnonymizer = probe.Protocol.JsonAnonymizer.GetAnonymizer(anonymizableProperty); int currentIndex = 0; if (currentAnonymizer != null) { currentIndex = anonymizableAttribute.AvailableAnonymizers.IndexOf(currentAnonymizer) + 1; } anonymizerPicker.SelectedIndex = currentIndex; StackLayout anonymizablePropertyStack = new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { propertyLabel, anonymizerPicker } }; anonymizablePropertyStacks.Add(anonymizablePropertyStack); } foreach (StackLayout anonymizablePropertyStack in anonymizablePropertyStacks.OrderBy(s => (s.Children[0] as Label).Text)) { contentLayout.Children.Add(anonymizablePropertyStack); } } #endregion Content = new ScrollView { Content = contentLayout }; }
private void EndProbeSerialize( StreamWriter streamWriter, SerializationContext serializationContext, object value, PropertyMetaData propertyMetaData, Probe probe) { probe.DiagnosticInfo.Length = streamWriter.Position - probe.DiagnosticInfo.Offset; serializationContext.EndProbe(probe); }
private void Restart(string processMessage, string continueMessage, string progressMessage, Probe probe) { if (ShouldProcess(processMessage)) { if (Force || yesToAll || ShouldContinue(continueMessage, "WARNING", true, ref yesToAll, ref noToAll)) { restartTime = DateTime.Now; if (probe != null) { probesRestarted.Add(probe); } ExecuteOperation(() => client.RestartProbe(probe == null ? null : new[] { probe.Id }), progressMessage, !Wait); } } }
public void Init() { testNetworkObject = GameObject.Instantiate(AssetDatabase.LoadAssetAtPath ("Assets/Prefabs/Network.prefab", typeof(GameObject)), Vector3.zero, Quaternion.identity) as GameObject; testNetwork = testNetworkObject.GetComponent<Network> (); testNetworkProbe = new Probe<Network> (testNetwork); }
public ServerListLogic(Widget widget, ModData modData, Action <GameServer> onJoin) { this.modData = modData; this.onJoin = onJoin; services = modData.Manifest.Get <WebServices>(); incompatibleVersionColor = ChromeMetrics.Get <Color>("IncompatibleVersionColor"); incompatibleGameColor = ChromeMetrics.Get <Color>("IncompatibleGameColor"); incompatibleProtectedGameColor = ChromeMetrics.Get <Color>("IncompatibleProtectedGameColor"); protectedGameColor = ChromeMetrics.Get <Color>("ProtectedGameColor"); waitingGameColor = ChromeMetrics.Get <Color>("WaitingGameColor"); incompatibleWaitingGameColor = ChromeMetrics.Get <Color>("IncompatibleWaitingGameColor"); gameStartedColor = ChromeMetrics.Get <Color>("GameStartedColor"); incompatibleGameStartedColor = ChromeMetrics.Get <Color>("IncompatibleGameStartedColor"); serverList = widget.Get <ScrollPanelWidget>("SERVER_LIST"); headerTemplate = serverList.Get <ScrollItemWidget>("HEADER_TEMPLATE"); serverTemplate = serverList.Get <ScrollItemWidget>("SERVER_TEMPLATE"); noticeContainer = widget.GetOrNull("NOTICE_CONTAINER"); if (noticeContainer != null) { noticeContainer.IsVisible = () => showNotices; noticeContainer.Get("OUTDATED_VERSION_LABEL").IsVisible = () => services.ModVersionStatus == ModVersionStatus.Outdated; noticeContainer.Get("UNKNOWN_VERSION_LABEL").IsVisible = () => services.ModVersionStatus == ModVersionStatus.Unknown; noticeContainer.Get("PLAYTEST_AVAILABLE_LABEL").IsVisible = () => services.ModVersionStatus == ModVersionStatus.PlaytestAvailable; } var noticeWatcher = widget.Get <LogicTickerWidget>("NOTICE_WATCHER"); if (noticeWatcher != null && noticeContainer != null) { var containerHeight = noticeContainer.Bounds.Height; noticeWatcher.OnTick = () => { var show = services.ModVersionStatus != ModVersionStatus.NotChecked && services.ModVersionStatus != ModVersionStatus.Latest; if (show != showNotices) { var dir = show ? 1 : -1; serverList.Bounds.Y += dir * containerHeight; serverList.Bounds.Height -= dir * containerHeight; showNotices = show; } }; } joinButton = widget.GetOrNull <ButtonWidget>("JOIN_BUTTON"); if (joinButton != null) { joinButton.IsVisible = () => currentServer != null; joinButton.IsDisabled = () => !currentServer.IsJoinable; joinButton.OnClick = () => onJoin(currentServer); joinButtonY = joinButton.Bounds.Y; } // Display the progress label over the server list // The text is only visible when the list is empty var progressText = widget.Get <LabelWidget>("PROGRESS_LABEL"); progressText.IsVisible = () => searchStatus != SearchStatus.Hidden; progressText.GetText = ProgressLabelText; var gs = Game.Settings.Game; Action <MPGameFilters> toggleFilterFlag = f => { gs.MPGameFilters ^= f; Game.Settings.Save(); RefreshServerList(); }; var filtersButton = widget.GetOrNull <DropDownButtonWidget>("FILTERS_DROPDOWNBUTTON"); if (filtersButton != null) { // HACK: MULTIPLAYER_FILTER_PANEL doesn't follow our normal procedure for dropdown creation // but we still need to be able to set the dropdown width based on the parent // The yaml should use PARENT_RIGHT instead of DROPDOWN_WIDTH var filtersPanel = Ui.LoadWidget("MULTIPLAYER_FILTER_PANEL", filtersButton, new WidgetArgs()); filtersButton.Children.Remove(filtersPanel); var showWaitingCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("WAITING_FOR_PLAYERS"); if (showWaitingCheckbox != null) { showWaitingCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Waiting); showWaitingCheckbox.OnClick = () => toggleFilterFlag(MPGameFilters.Waiting); } var showEmptyCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("EMPTY"); if (showEmptyCheckbox != null) { showEmptyCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Empty); showEmptyCheckbox.OnClick = () => toggleFilterFlag(MPGameFilters.Empty); } var showAlreadyStartedCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("ALREADY_STARTED"); if (showAlreadyStartedCheckbox != null) { showAlreadyStartedCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Started); showAlreadyStartedCheckbox.OnClick = () => toggleFilterFlag(MPGameFilters.Started); } var showProtectedCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("PASSWORD_PROTECTED"); if (showProtectedCheckbox != null) { showProtectedCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Protected); showProtectedCheckbox.OnClick = () => toggleFilterFlag(MPGameFilters.Protected); } var showIncompatibleCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("INCOMPATIBLE_VERSION"); if (showIncompatibleCheckbox != null) { showIncompatibleCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Incompatible); showIncompatibleCheckbox.OnClick = () => toggleFilterFlag(MPGameFilters.Incompatible); } filtersButton.IsDisabled = () => searchStatus == SearchStatus.Fetching; filtersButton.OnMouseDown = _ => { filtersButton.RemovePanel(); filtersButton.AttachPanel(filtersPanel); }; } var reloadButton = widget.GetOrNull <ButtonWidget>("RELOAD_BUTTON"); if (reloadButton != null) { reloadButton.IsDisabled = () => searchStatus == SearchStatus.Fetching; reloadButton.OnClick = RefreshServerList; var reloadIcon = reloadButton.GetOrNull <ImageWidget>("IMAGE_RELOAD"); if (reloadIcon != null) { var disabledFrame = 0; var disabledImage = "disabled-" + disabledFrame.ToString(); reloadIcon.GetImageName = () => searchStatus == SearchStatus.Fetching ? disabledImage : reloadIcon.ImageName; var reloadTicker = reloadIcon.Get <LogicTickerWidget>("ANIMATION"); if (reloadTicker != null) { reloadTicker.OnTick = () => { disabledFrame = searchStatus == SearchStatus.Fetching ? (disabledFrame + 1) % 12 : 0; disabledImage = "disabled-" + disabledFrame.ToString(); }; } } } var playersLabel = widget.GetOrNull <LabelWidget>("PLAYER_COUNT"); if (playersLabel != null) { var playersText = new CachedTransform <int, string>(c => c == 1 ? "1 Player Online" : c.ToString() + " Players Online"); playersLabel.IsVisible = () => playerCount != 0; playersLabel.GetText = () => playersText.Update(playerCount); } mapPreview = widget.GetOrNull <MapPreviewWidget>("SELECTED_MAP_PREVIEW"); if (mapPreview != null) { mapPreview.Preview = () => currentMap; } var mapTitle = widget.GetOrNull <LabelWidget>("SELECTED_MAP"); if (mapTitle != null) { var font = Game.Renderer.Fonts[mapTitle.Font]; var title = new CachedTransform <MapPreview, string>(m => WidgetUtils.TruncateText(m.Title, mapTitle.Bounds.Width, font)); mapTitle.GetText = () => { if (currentMap == null) { return("No Server Selected"); } if (currentMap.Status == MapStatus.Searching) { return("Searching..."); } if (currentMap.Class == MapClassification.Unknown) { return("Unknown Map"); } return(title.Update(currentMap)); }; } var ip = widget.GetOrNull <LabelWidget>("SELECTED_IP"); if (ip != null) { ip.IsVisible = () => currentServer != null; ip.GetText = () => currentServer.Address; } var status = widget.GetOrNull <LabelWidget>("SELECTED_STATUS"); if (status != null) { status.IsVisible = () => currentServer != null; status.GetText = () => GetStateLabel(currentServer); status.GetColor = () => GetStateColor(currentServer, status); } var modVersion = widget.GetOrNull <LabelWidget>("SELECTED_MOD_VERSION"); if (modVersion != null) { modVersion.IsVisible = () => currentServer != null; modVersion.GetColor = () => currentServer.IsCompatible ? modVersion.TextColor : incompatibleVersionColor; var font = Game.Renderer.Fonts[modVersion.Font]; var version = new CachedTransform <GameServer, string>(s => WidgetUtils.TruncateText(s.ModLabel, modVersion.Bounds.Width, font)); modVersion.GetText = () => version.Update(currentServer); } var players = widget.GetOrNull <LabelWidget>("SELECTED_PLAYERS"); if (players != null) { players.IsVisible = () => currentServer != null && (clientContainer == null || !currentServer.Clients.Any()); players.GetText = () => PlayersLabel(currentServer); } clientContainer = widget.GetOrNull("CLIENT_LIST_CONTAINER"); if (clientContainer != null) { clientList = Ui.LoadWidget("MULTIPLAYER_CLIENT_LIST", clientContainer, new WidgetArgs()) as ScrollPanelWidget; clientList.IsVisible = () => currentServer != null && currentServer.Clients.Any(); clientHeader = clientList.Get <ScrollItemWidget>("HEADER"); clientTemplate = clientList.Get <ScrollItemWidget>("TEMPLATE"); clientList.RemoveChildren(); } lanGameLocations = new List <BeaconLocation>(); try { lanGameProbe = new Probe("OpenRALANGame"); lanGameProbe.BeaconsUpdated += locations => lanGameLocations = locations; lanGameProbe.Start(); } catch (Exception ex) { Log.Write("debug", "BeaconLib.Probe: " + ex.Message); } RefreshServerList(); }
public void Init() { testNetworkObject = GameObject.Instantiate(AssetDatabase.LoadAssetAtPath ("Assets/Prefabs/Network.prefab", typeof(GameObject)), Vector3.zero, Quaternion.identity) as GameObject; testNetwork = testNetworkObject.GetComponent<Network> (); testNetworkProbe = new Probe<Network> (testNetwork); testNetwork.initialize (3, 3); map = testNetworkProbe.getField ("networkMap") as NodeController[,]; }
public void addNeighbourTest() { INode testNode = map [1, 1]; Vector2 testNeighbourLocalCoordinates = new Vector2 (1, 0); INode testNeighbour = map [2, 1]; testNode.addNeighbour (testNeighbour); Probe<NodeController> testNodeProbe = new Probe<NodeController> (map[1,1]); NodeModel testNodeModel = testNodeProbe.getField ("nodeModel") as NodeModel; Assert.NotNull (testNodeModel); Assert.IsTrue (testNodeModel.neighbours.ContainsKey (testNeighbourLocalCoordinates)); Assert.IsTrue (testNodeModel.neighbours.ContainsValue (testNeighbour)); Vector2 incorrectNeighbourLocation = new Vector2 (0, 1); Assert.IsFalse (testNodeModel.neighbours.ContainsKey (incorrectNeighbourLocation)); }
public int visit(Probe ProbeItem) { return((ProbeItem.PropogationDelay) + 2); }
private void CubeMapSamplerSetDistance( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { Probe.Set S = _Pixel.ParentSet; if ( S == null || S.SetIndex == -1 || (m_IsolateSet && S.SetIndex != m_IsolatedSetIndex) ) { _R = 63; _G = 0; _B = 63; return; } float Distance2SetCenter = 0.2f * (_Pixel.Position - S.Position).Length; byte C = (byte) Math.Min( 255, 255 * Distance2SetCenter ); _R = _G = _B = C; }
public void Start() { m_Probe = new Probe(BeaconModel.Types.Service, "MultiPlug", "1"); m_Probe.BeaconsUpdated += OnNewDiscovery; m_Probe.Start(); }
private void CubeMapSamplerSH( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { WMath.Vector Dir = _Pixel.View; // Dot the SH together WMath.Vector Color = WMath.Vector.Zero; if ( m_IsolateSet ) { float Factor = 1.0f; if ( m_bShowSHDynamic ) { for ( int i=0; i < 9; i++ ) Color += (float) _Pixel.SHCoeffs[i] * m_Probe.m_Sets[m_IsolatedSetIndex].SH[i]; Factor = m_bNormalizeSH ? 2.0f * m_Probe.m_Sets[m_IsolatedSetIndex].SH[0].Max() : 1.0f; } if ( m_bShowSHEmissive ) { int EmissiveSetIndex = Math.Min( m_IsolatedSetIndex, m_Probe.m_EmissiveSets.Length-1 ); if ( EmissiveSetIndex >= 0 ) for ( int i=0; i < 9; i++ ) Color += (float) _Pixel.SHCoeffs[i] * m_Probe.m_EmissiveSets[EmissiveSetIndex].SH[i]; Factor = m_bNormalizeSH ? 2.0f * m_Probe.m_EmissiveSets[EmissiveSetIndex].SH[0].Max() : 1.0f; } // Color *= 100.0f; Color *= 1.0f / Factor; } else { float Factor = 0.0f; if ( m_bShowSHStatic ) { for ( int i=0; i < 9; i++ ) Color += (float) _Pixel.SHCoeffs[i] * m_SHStatic[i]; Factor = Math.Max( Factor, m_SHStatic[0].Max() ); } if ( m_bShowSHDynamic ) { for ( int i=0; i < 9; i++ ) Color += (float) _Pixel.SHCoeffs[i] * m_SHDynamic[i]; Factor = Math.Max( Factor, m_SHDynamic[0].Max() ); } if ( m_bShowSHEmissive ) { for ( int i=0; i < 9; i++ ) Color += (float) _Pixel.SHCoeffs[i] * m_SHEmissive[i]; Factor = Math.Max( Factor, m_SHEmissive[0].Max() ); } if ( m_bShowSHOcclusion ) { for ( int i=0; i < 9; i++ ) Color += (float) _Pixel.SHCoeffs[i] * m_SHOcclusion[i] * WMath.Vector.One; Factor = Math.Max( Factor, m_SHOcclusion[0] ); } // Color *= 50.0f; Color *= m_bNormalizeSH ? 1.0f / Factor : 1.0f; } if ( Color.x < 0.0f || Color.y < 0.0f || Color.z < 0.0f ) Color.Set( 1, 0, 1 ); _R = (byte) Math.Min( 255, 255 * Color.x ); _G = (byte) Math.Min( 255, 255 * Color.y ); _B = (byte) Math.Min( 255, 255 * Color.z ); }
private void LoadCubeMap( FileInfo _POMCubeMap ) { try { Probe NewProbe = new Probe(); NewProbe.LoadCubeMap( _POMCubeMap ); SelectedProbe = NewProbe; } catch ( Exception _e ) { throw new Exception( "Error while loading cube map \"" + _POMCubeMap.Name + "\": " + _e.Message ); } finally { buttonComputeFilling.Focus(); } }
public void Test_Z3_GoalsAndProbes() { using (Context ctx = new Context()) { Solver solver = ctx.MkSolver(); #region Print all Probes if (false) { for (int i = 0; i < ctx.ProbeNames.Length; ++i) { Console.WriteLine(i + ": probe " + ctx.ProbeNames[i] + "; " + ctx.ProbeDescription(ctx.ProbeNames[i])); } /* * 0: probe is-quasi-pb; true if the goal is quasi-pb. * 1: probe is-unbounded; true if the goal contains integer/real constants that do not have lower/upper bounds. * 2: probe is-pb; true if the goal is a pseudo-boolean problem. * 3: probe arith-max-deg; max polynomial total degree of an arithmetic atom. * 4: probe arith-avg-deg; avg polynomial total degree of an arithmetic atom. * 5: probe arith-max-bw; max coefficient bit width. * 6: probe arith-avg-bw; avg coefficient bit width. * 7: probe is-qflia; true if the goal is in QF_LIA. * 8: probe is-qfauflia; true if the goal is in QF_AUFLIA. * 9: probe is-qflra; true if the goal is in QF_LRA. * 10: probe is-qflira; true if the goal is in QF_LIRA. * 11: probe is-ilp; true if the goal is ILP. * 12: probe is-qfnia; true if the goal is in QF_NIA (quantifier-free nonlinear integer arithmetic). * 13: probe is-qfnra; true if the goal is in QF_NRA (quantifier-free nonlinear real arithmetic). * 14: probe is-nia; true if the goal is in NIA (nonlinear integer arithmetic, formula may have quantifiers). * 15: probe is-nra; true if the goal is in NRA (nonlinear real arithmetic, formula may have quantifiers). * 16: probe is-nira; true if the goal is in NIRA (nonlinear integer and real arithmetic, formula may have quantifiers). * 17: probe is-lia; true if the goal is in LIA (linear integer arithmetic, formula may have quantifiers). * 18: probe is-lra; true if the goal is in LRA (linear real arithmetic, formula may have quantifiers). * 19: probe is-lira; true if the goal is in LIRA (linear integer and real arithmetic, formula may have quantifiers). * 20: probe is-qfufnra; true if the goal is QF_UFNRA (quantifier-free nonlinear real arithmetic with other theories). * 21: probe memory; ammount of used memory in megabytes. * 22: probe depth; depth of the input goal. * 23: probe size; number of assertions in the given goal. * 24: probe num-exprs; number of expressions/terms in the given goal. * 25: probe num-consts; number of non Boolean constants in the given goal. * 26: probe num-bool-consts; number of Boolean constants in the given goal. * 27: probe num-arith-consts; number of arithmetic constants in the given goal. * 28: probe num-bv-consts; number of bit-vector constants in the given goal. * 29: probe produce-proofs; true if proof generation is enabled for the given goal. * 30: probe produce-model; true if model generation is enabled for the given goal. * 31: probe produce-unsat-cores; true if unsat-core generation is enabled for the given goal. * 32: probe has-patterns; true if the goal contains quantifiers with patterns. * 33: probe is-propositional; true if the goal is in propositional logic. * 34: probe is-qfbv; true if the goal is in QF_BV. * 35: probe is-qfaufbv; true if the goal is in QF_AUFBV. * 36: probe is-qfbv-eq; true if the goal is in a fragment of QF_BV which uses only =, extract, concat. * 37: probe is-qffp; true if the goal is in QF_FP (floats). * 38: probe is-qffpbv; true if the goal is in QF_FPBV (floats+bit-vectors). */ } #endregion Print all Probes #region Print all Tactics if (false) { for (int i = 0; i < ctx.TacticNames.Length; ++i) { Console.WriteLine(i + ": tactic " + ctx.TacticNames[i] + "; " + ctx.TacticDescription(ctx.TacticNames[i])); } /* * 0: tactic qfbv; builtin strategy for solving QF_BV problems. * 1: tactic qflia; builtin strategy for solving QF_LIA problems. * 2: tactic qflra; builtin strategy for solving QF_LRA problems. * 3: tactic qfnia; builtin strategy for solving QF_NIA problems. * 4: tactic qfnra; builtin strategy for solving QF_NRA problems. * 5: tactic qfufnra; builtin strategy for solving QF_UNFRA problems. * 6: tactic add-bounds; add bounds to unbounded variables(under approximation). * 7: tactic card2bv; convert pseudo-boolean constraints to bit - vectors. * 8: tactic degree-shift; try to reduce degree of polynomials(remark: :mul2power simplification is automatically applied). * 9: tactic diff-neq; specialized solver for integer arithmetic problems that contain only atoms of the form(<= k x)(<= x k) and(not(= (-x y) k)), where x and y are constants and k is a numberal, and all constants are bounded. * 10: tactic elim01; eliminate 0 - 1 integer variables, replace them by Booleans. * 11: tactic eq2bv; convert integer variables used as finite domain elements to bit-vectors. * 12: tactic factor; polynomial factorization. * 13: tactic fix-dl - var; if goal is in the difference logic fragment, then fix the variable with the most number of occurrences at 0. * 14: tactic fm; eliminate variables using fourier - motzkin elimination. * 15: tactic lia2card; introduce cardinality constraints from 0 - 1 integer. * 16: tactic lia2pb; convert bounded integer variables into a sequence of 0 - 1 variables. * 17: tactic nla2bv; convert a nonlinear arithmetic problem into a bit-vector problem, in most cases the resultant goal is an under approximation and is useul for finding models. * 18: tactic normalize - bounds; replace a variable x with lower bound k <= x with x' = x - k. * 19: tactic pb2bv; convert pseudo-boolean constraints to bit - vectors. * 20: tactic propagate-ineqs; propagate ineqs/ bounds, remove subsumed inequalities. * 21: tactic purify-arith; eliminate unnecessary operators: -, /, div, mod, rem, is- int, to - int, ^, root - objects. * 22: tactic recover-01; recover 0 - 1 variables hidden as Boolean variables. * 23: tactic blast-term-ite; blast term if-then -else by hoisting them. * 24: tactic cofactor-term-ite; eliminate term if-the -else using cofactors. * 25: tactic ctx-simplify; apply contextual simplification rules. * 26: tactic der; destructive equality resolution. * 27: tactic distribute-forall; distribute forall over conjunctions. * 28: tactic elim-term-ite; eliminate term if-then -else by adding fresh auxiliary declarations. * 29: tactic elim-uncnstr; eliminate application containing unconstrained variables. * 30: tactic snf; put goal in skolem normal form. * 31: tactic nnf; put goal in negation normal form. * 32: tactic occf; put goal in one constraint per clause normal form (notes: fails if proof generation is enabled; only clauses are considered). * 33: tactic pb-preprocess; pre - process pseudo - Boolean constraints a la Davis Putnam. * 34: tactic propagate-values; propagate constants. * 35: tactic reduce-args; reduce the number of arguments of function applications, when for all occurrences of a function f the i - th is a value. * 36: tactic simplify; apply simplification rules. * 37: tactic elim-and; convert(and a b) into(not(or(not a)(not b))). * 38: tactic solve-eqs; eliminate variables by solving equations. * 39: tactic split-clause; split a clause in many subgoals. * 40: tactic symmetry-reduce; apply symmetry reduction. * 41: tactic tseitin-cnf; convert goal into CNF using tseitin - like encoding(note: quantifiers are ignored). * 42: tactic tseitin-cnf-core; convert goal into CNF using tseitin - like encoding(note: quantifiers are ignored).This tactic does not apply required simplifications to the input goal like the tseitin - cnf tactic. * 43: tactic skip; do nothing tactic. * 44: tactic fail; always fail tactic. * 45: tactic fail-if-undecided; fail if goal is undecided. * 46: tactic bit-blast; reduce bit-vector expressions into SAT. * 47: tactic bv1-blast; reduce bit-vector expressions into bit - vectors of size 1(notes: only equality, extract and concat are supported). * 48: tactic reduce-bv-size; try to reduce bit - vector sizes using inequalities. * 49: tactic max-bv-sharing; use heuristics to maximize the sharing of bit-vector expressions such as adders and multipliers. * 50: tactic nlsat; (try to) solve goal using a nonlinear arithmetic solver. * 51: tactic qfnra-nlsat; builtin strategy for solving QF_NRA problems using only nlsat. * 52: tactic sat; (try to) solve goal using a SAT solver. * 53: tactic sat-preprocess; Apply SAT solver preprocessing procedures(bounded resolution, Boolean constant propagation, 2 - SAT, subsumption, subsumption resolution). * 54: tactic ctx-solver-simplify; apply solver-based contextual simplification rules. * 55: tactic smt; apply a SAT based SMT solver. * 56: tactic unit-subsume-simplify; unit subsumption simplification. * 57: tactic aig; simplify Boolean structure using AIGs. * 58: tactic horn; apply tactic for horn clauses. * 59: tactic horn-simplify; simplify horn clauses. * 60: tactic qe-light; apply light-weight quantifier elimination. * 61: tactic qe-sat; check satisfiability of quantified formulas using quantifier elimination. * 62: tactic qe; apply quantifier elimination. * 63: tactic vsubst; checks satsifiability of quantifier-free non - linear constraints using virtual substitution. * 64: tactic nl-purify; Decompose goal into pure NL-sat formula and formula over other theories. * 65: tactic macro-finder; Identifies and applies macros. * 66: tactic quasi-macros; Identifies and applies quasi-macros. * 67: tactic bv; builtin strategy for solving BV problems(with quantifiers). * 68: tactic ufbv; builtin strategy for solving UFBV problems(with quantifiers). * 69: tactic fpa2bv; convert floating point numbers to bit-vectors. * 70: tactic qffp; (try to) solve goal using the tactic for QF_FP. * 71: tactic qffpbv; (try to) solve goal using the tactic for QF_FPBV(floats+bit-vectors). * 72: tactic qfbv-sls; (try to) solve using stochastic local search for QF_BV. * 73: tactic subpaving; tactic for testing subpaving module. */ } #endregion Print all Tactics BitVecExpr rax = ctx.MkBVConst("rax", 64); BitVecExpr rbx = ctx.MkBVConst("rbx", 64); BoolExpr a1 = ctx.MkEq(rax, ctx.MkBV(0, 64)); BoolExpr a2 = ctx.MkEq(rbx, rax); Goal goal1 = ctx.MkGoal(true, false, false); goal1.Assert(a1, a2); Console.WriteLine("goal1=" + goal1 + "; inconsistent=" + goal1.Inconsistent); Tactic tactic1 = ctx.MkTactic("simplify"); // Console.WriteLine("tactic1=" + tactic1.ToString()); ApplyResult applyResult = tactic1.Apply(goal1); Console.WriteLine("applyResult=" + applyResult.ToString() + "; nSubGoals=" + applyResult.NumSubgoals); // Console.WriteLine("AsBoolExpr=" + goal1.AsBoolExpr()); #region Probe Tests if (false) { Probe probe1 = ctx.MkProbe("is-qfbv"); double d = probe1.Apply(goal1); Console.WriteLine("d=" + d); } #endregion Probe Tests } }
partial void OnProbeChanging(Probe value);
public Func <RegionalContext, IRegionalEndpoint> BuildVMScaleSetApp(GlobalContext context) { var options = CustomResourceOptions.Merge(context.Options, new CustomResourceOptions { DeleteBeforeReplace = true }); var file = File.ReadAllText("./vm/vmCustomData.yaml"); return((RegionalContext region) => { var location = region.Location; var domainName = $"rnddnplm{location}"; //TODO: random var publicIp = new PublicIp($"pip-{location}", new PublicIpArgs { ResourceGroupName = resourceGroup.Name, Location = location, AllocationMethod = "Static", DomainNameLabel = domainName, }, options); var loadBalancer = new LoadBalancer($"lb-{location}", new LoadBalancerArgs { ResourceGroupName = resourceGroup.Name, Location = location, FrontendIpConfigurations = { new LoadBalancerFrontendIpConfigurationsArgs { Name = "PublicIPAddress", PublicIpAddressId = publicIp.Id, } } }, options); var bpepool = new BackendAddressPool($"bap-{location}", new BackendAddressPoolArgs { ResourceGroupName = resourceGroup.Name, LoadbalancerId = loadBalancer.Id, }, options); var probe = new Probe($"ssh-probe-{location}".Truncate(16), new ProbeArgs { ResourceGroupName = resourceGroup.Name, LoadbalancerId = loadBalancer.Id, Port = 80, }, options); var rule = new Rule($"rule-{location}", new RuleArgs { ResourceGroupName = resourceGroup.Name, BackendAddressPoolId = bpepool.Id, BackendPort = 80, FrontendIpConfigurationName = "PublicIPAddress", FrontendPort = 80, LoadbalancerId = loadBalancer.Id, ProbeId = probe.Id, Protocol = "Tcp", }, options); var vnet = new VirtualNetwork($"vnet-{location}", new VirtualNetworkArgs { ResourceGroupName = resourceGroup.Name, Location = location, AddressSpaces = { "10.0.0.0/16" }, }, options); var subnet = new Subnet($"subnet-{location}", new SubnetArgs { ResourceGroupName = resourceGroup.Name, AddressPrefix = "10.0.2.0/24", VirtualNetworkName = vnet.Name, }, options); var customData = Output.All <string>(context.CosmosAccount.Endpoint, context.CosmosAccount.PrimaryMasterKey, context.Database.Name, context.Container.Name) .Apply(values => { return file.Replace("${ENDPOINT}", values[0]) .Replace("${MASTER_KEY}", values[1]) .Replace("${DATABASE}", values[2]) .Replace("${COLLECTION}", values[3]) .Replace("${LOCATION}", location); }); var scaleSet = new ScaleSet($"vmss-{location}", new ScaleSetArgs { ResourceGroupName = resourceGroup.Name, Location = location, NetworkProfiles = { new ScaleSetNetworkProfilesArgs { IpConfigurations = { new ScaleSetNetworkProfilesIpConfigurationsArgs { LoadBalancerBackendAddressPoolIds ={ bpepool.Id }, Name = "IPConfiguration", Primary = true, SubnetId = subnet.Id, } }, Name = "networkprofile", Primary = true, } }, OsProfile = new ScaleSetOsProfileArgs { AdminUsername = "******", AdminPassword = "******", ComputerNamePrefix = "lab", CustomData = customData, }, OsProfileLinuxConfig = new ScaleSetOsProfileLinuxConfigArgs { DisablePasswordAuthentication = false }, Sku = new ScaleSetSkuArgs { Capacity = 1, Name = "Standard_DS1_v2", Tier = "Standard", }, StorageProfileDataDisks = { new ScaleSetStorageProfileDataDisksArgs { Caching = "ReadWrite", CreateOption = "Empty", DiskSizeGb = 10, Lun = 0, } }, StorageProfileImageReference = new ScaleSetStorageProfileImageReferenceArgs { Offer = "UbuntuServer", Publisher = "Canonical", Sku = "18.04-LTS", Version = "latest", }, StorageProfileOsDisk = new ScaleSetStorageProfileOsDiskArgs { Caching = "ReadWrite", CreateOption = "FromImage", ManagedDiskType = "Standard_LRS", Name = "", }, UpgradePolicyMode = "Automatic", }, CustomResourceOptions.Merge(options, new CustomResourceOptions { DependsOn = { bpepool, rule } })); var autoscale = new AutoscaleSetting($"as-{location}", new AutoscaleSettingArgs { ResourceGroupName = resourceGroup.Name, Location = location, Notification = new AutoscaleSettingNotificationArgs { Email = new AutoscaleSettingNotificationEmailArgs { CustomEmails = { "*****@*****.**" }, SendToSubscriptionAdministrator = true, SendToSubscriptionCoAdministrator = true, }, }, Profiles = { new AutoscaleSettingProfilesArgs { Capacity = new AutoscaleSettingProfilesCapacityArgs { Default = 1, Maximum = 10, Minimum = 1, }, Name = "defaultProfile", Rules = { new AutoscaleSettingProfilesRulesArgs { MetricTrigger = new AutoscaleSettingProfilesRulesMetricTriggerArgs { MetricName = "Percentage CPU", MetricResourceId = scaleSet.Id, Operator = "GreaterThan", Statistic = "Average", Threshold = 75, TimeAggregation = "Average", TimeGrain = "PT1M", TimeWindow = "PT5M", }, ScaleAction = new AutoscaleSettingProfilesRulesScaleActionArgs { Cooldown = "PT1M", Direction = "Increase", Type = "ChangeCount", Value = 1, }, }, new AutoscaleSettingProfilesRulesArgs { MetricTrigger = new AutoscaleSettingProfilesRulesMetricTriggerArgs { MetricName = "Percentage CPU", MetricResourceId = scaleSet.Id, Operator = "LessThan", Statistic = "Average", Threshold = 25, TimeAggregation = "Average", TimeGrain = "PT1M", TimeWindow = "PT5M", }, ScaleAction = new AutoscaleSettingProfilesRulesScaleActionArgs { Cooldown = "PT1M", Direction = "Decrease", Type = "ChangeCount", Value = 1, }, }, } } }, TargetResourceId = scaleSet.Id, }, options); return new AzureEndpoint(publicIp.Id); }); }
private void ElecCompList_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (elecCompList.SelectedItems.Count == 1) { //MessageBox.Show("Select: " + elecCompList.SelectedIndex); switch (elecCompList.SelectedIndex) { case 0: Resistance r = new Resistance(); elecCompSet.AddCompAndShow(r, Mycanvas); r.Move(100, 100); break; case 1: Capacity c = new Capacity(); elecCompSet.AddCompAndShow(c, Mycanvas); c.Move(100, 100); break; case 2: Wire w = new Wire(); elecCompSet.AddCompAndShow(w, Mycanvas); w.Move(100, 100); break; case 3: Inductance i = new Inductance(); elecCompSet.AddCompAndShow(i, Mycanvas); i.Move(100, 100); break; case 4: OhmMeter o = new OhmMeter(); elecCompSet.AddCompAndShow(o, Mycanvas); o.Move(100, 100); break; case 5: VoltMeter ee = new VoltMeter(); elecCompSet.AddCompAndShow(ee, Mycanvas); ee.Move(100, 100); break; case 6: ElecGround eg = new ElecGround(); elecCompSet.AddCompAndShow(eg, Mycanvas); eg.Move(100, 100); break; case 7: oscilloscopeData myOscilloscopeData = new oscilloscopeData(Brushes.Red, oscilloscopeData.Volt_Index, myOscilloscope.m_SyncContext); Probe pb = new Probe(Brushes.Red, myOscilloscopeData); if (!myOscilloscope.IsVisible) { myOscilloscope.Show(); } myOscilloscope.AddData(myOscilloscopeData); myOscilloscope.SyncSettings(); elecCompSet.AddCompAndShow(pb, Mycanvas); pb.Move(100, 100); break; case 8: myOscilloscopeData = new oscilloscopeData(Brushes.Blue, oscilloscopeData.Volt_Index, myOscilloscope.m_SyncContext); pb = new Probe(Brushes.Blue, myOscilloscopeData); if (!myOscilloscope.IsVisible) { myOscilloscope.Show(); } myOscilloscope.AddData(myOscilloscopeData); myOscilloscope.SyncSettings(); elecCompSet.AddCompAndShow(pb, Mycanvas); pb.Move(100, 100); break; } } }
public Probe(Probe parent = null) { this.parent = parent; this.diagnosticInfo = new DiagnosticInfo(); }
protected override void PreStart() { base.PreStart(); Probe.Tell(new ProcessActorEvent(Id, "Started")); }
private void CubeMapSamplerAlbedo( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { _R = (byte) Math.Min( 255, 255 * _Pixel.Albedo.x ); _G = (byte) Math.Min( 255, 255 * _Pixel.Albedo.y ); _B = (byte) Math.Min( 255, 255 * _Pixel.Albedo.z ); }
/// <summary> /// Initializes a new instance of the <see cref="AddScriptTriggerPage"/> class. /// </summary> /// <param name="scriptRunner">Script runner to add trigger to.</param> public AddScriptTriggerPage(ScriptRunner scriptRunner) { _scriptRunner = scriptRunner; Title = "Add Trigger"; Probe[] enabledProbes = _scriptRunner.Probe.Protocol.Probes.Where(p => p != _scriptRunner.Probe && p.Enabled).ToArray(); if (!enabledProbes.Any()) { Content = new Label { Text = "No enabled probes. Please enable them before creating triggers.", FontSize = 20 }; return; } StackLayout contentLayout = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.FillAndExpand }; Label probeLabel = new Label { Text = "Probe:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; Picker probePicker = new Picker { Title = "Select Probe", HorizontalOptions = LayoutOptions.FillAndExpand }; foreach (Probe enabledProbe in enabledProbes) { probePicker.Items.Add(enabledProbe.DisplayName); } contentLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { probeLabel, probePicker } }); StackLayout triggerDefinitionLayout = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.Start }; contentLayout.Children.Add(triggerDefinitionLayout); bool allowChangeCalculation = false; Switch changeSwitch = new Switch(); bool allowRegularExpression = false; Switch regexSwitch = new Switch(); Switch fireRepeatedlySwitch = new Switch(); TimePicker startTimePicker = new TimePicker { HorizontalOptions = LayoutOptions.FillAndExpand }; TimePicker endTimePicker = new TimePicker { HorizontalOptions = LayoutOptions.FillAndExpand }; probePicker.SelectedIndexChanged += (o, e) => { _selectedProbe = null; _selectedDatumProperty = null; _conditionValue = null; triggerDefinitionLayout.Children.Clear(); if (probePicker.SelectedIndex < 0) { return; } _selectedProbe = enabledProbes[probePicker.SelectedIndex]; PropertyInfo[] datumProperties = _selectedProbe.DatumType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttributes <ProbeTriggerProperty>().Any()).ToArray(); if (datumProperties.Length == 0) { return; } #region datum property picker Label datumPropertyLabel = new Label { Text = "Property:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; Picker datumPropertyPicker = new Picker { Title = "Select Datum Property", HorizontalOptions = LayoutOptions.FillAndExpand }; foreach (PropertyInfo datumProperty in datumProperties) { ProbeTriggerProperty triggerProperty = datumProperty.GetCustomAttributes <ProbeTriggerProperty>().First(); datumPropertyPicker.Items.Add(triggerProperty.Name ?? datumProperty.Name); } triggerDefinitionLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { datumPropertyLabel, datumPropertyPicker } }); #endregion #region condition picker (same for all datum types) Label conditionLabel = new Label { Text = "Condition:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; Picker conditionPicker = new Picker { Title = "Select Condition", HorizontalOptions = LayoutOptions.FillAndExpand }; TriggerValueCondition[] conditions = Enum.GetValues(typeof(TriggerValueCondition)) as TriggerValueCondition[]; foreach (TriggerValueCondition condition in conditions) { conditionPicker.Items.Add(condition.ToString()); } conditionPicker.SelectedIndexChanged += (oo, ee) => { if (conditionPicker.SelectedIndex < 0) { return; } _selectedCondition = conditions[conditionPicker.SelectedIndex]; }; triggerDefinitionLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { conditionLabel, conditionPicker } }); #endregion #region condition value for comparison, based on selected datum property -- includes change calculation (for double datum) and regex (for string datum) StackLayout conditionValueStack = new StackLayout { Orientation = StackOrientation.Vertical, HorizontalOptions = LayoutOptions.FillAndExpand }; triggerDefinitionLayout.Children.Add(conditionValueStack); datumPropertyPicker.SelectedIndexChanged += (oo, ee) => { _selectedDatumProperty = null; _conditionValue = null; conditionValueStack.Children.Clear(); if (datumPropertyPicker.SelectedIndex < 0) { return; } _selectedDatumProperty = datumProperties[datumPropertyPicker.SelectedIndex]; ProbeTriggerProperty datumTriggerAttribute = _selectedDatumProperty.GetCustomAttribute <ProbeTriggerProperty>(); View conditionValueStackView = null; if (datumTriggerAttribute is ListProbeTriggerProperty) { Picker conditionValuePicker = new Picker { Title = "Select Condition Value", HorizontalOptions = LayoutOptions.FillAndExpand }; object[] items = (datumTriggerAttribute as ListProbeTriggerProperty).Items; foreach (object item in items) { conditionValuePicker.Items.Add(item.ToString()); } conditionValuePicker.SelectedIndexChanged += (ooo, eee) => { if (conditionValuePicker.SelectedIndex < 0) { return; } _conditionValue = items[conditionValuePicker.SelectedIndex]; }; conditionValueStackView = conditionValuePicker; } else if (datumTriggerAttribute is DoubleProbeTriggerProperty) { Entry entry = new Entry { Keyboard = Keyboard.Numeric, HorizontalOptions = LayoutOptions.FillAndExpand }; entry.TextChanged += (ooo, eee) => { double value; if (double.TryParse(eee.NewTextValue, out value)) { _conditionValue = value; } }; conditionValueStackView = entry; allowChangeCalculation = true; } else if (datumTriggerAttribute is StringProbeTriggerProperty) { Entry entry = new Entry { Keyboard = Keyboard.Default, HorizontalOptions = LayoutOptions.FillAndExpand }; entry.TextChanged += (ooo, eee) => _conditionValue = eee.NewTextValue; conditionValueStackView = entry; allowRegularExpression = true; } else if (datumTriggerAttribute is BooleanProbeTriggerProperty) { Switch booleanSwitch = new Switch(); booleanSwitch.Toggled += (ooo, eee) => _conditionValue = eee.Value; conditionValueStackView = booleanSwitch; } Label conditionValueStackLabel = new Label { Text = "Value:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; conditionValueStack.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { conditionValueStackLabel, conditionValueStackView } }); #region change calculation if (allowChangeCalculation) { Label changeLabel = new Label { Text = "Change:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; changeSwitch.IsToggled = false; conditionValueStack.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { changeLabel, changeSwitch } }); } #endregion #region regular expression if (allowRegularExpression) { Label regexLabel = new Label { Text = "Regular Expression:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; regexSwitch.IsToggled = false; conditionValueStack.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { regexLabel, regexSwitch } }); } #endregion }; datumPropertyPicker.SelectedIndex = 0; #endregion #region fire repeatedly Label fireRepeatedlyLabel = new Label { Text = "Fire Repeatedly:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; fireRepeatedlySwitch.IsToggled = true; triggerDefinitionLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { fireRepeatedlyLabel, fireRepeatedlySwitch } }); #endregion #region start/end times Label startTimeLabel = new Label { Text = "Start Time:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; startTimePicker.Time = new TimeSpan(0, 0, 0); triggerDefinitionLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { startTimeLabel, startTimePicker } }); Label endTimeLabel = new Label { Text = "End Time:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; endTimePicker.Time = new TimeSpan(23, 59, 59); triggerDefinitionLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { endTimeLabel, endTimePicker } }); #endregion }; probePicker.SelectedIndex = 0; Button okButton = new Button { Text = "OK", FontSize = 20, VerticalOptions = LayoutOptions.Start }; okButton.Clicked += async(o, e) => { try { _scriptRunner.Triggers.Add(new Probes.User.Scripts.Trigger(_selectedProbe, _selectedDatumProperty, _selectedCondition, _conditionValue, allowChangeCalculation && changeSwitch.IsToggled, fireRepeatedlySwitch.IsToggled, allowRegularExpression && regexSwitch.IsToggled, startTimePicker.Time, endTimePicker.Time)); await Navigation.PopAsync(); } catch (Exception ex) { await SensusServiceHelper.Get().FlashNotificationAsync($"Failed to add trigger: {ex.Message}"); SensusServiceHelper.Get().Logger.Log($"Failed to add trigger: {ex.Message}", LoggingLevel.Normal, GetType()); } }; contentLayout.Children.Add(okButton); Content = new ScrollView { Content = contentLayout }; }
private void CubeMapSamplerNormal( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { #if ABS_NORMAL _R = (byte) Math.Min( 255, 255 * Math.Abs( _Pixel.Normal.x) ); _G = (byte) Math.Min( 255, 255 * Math.Abs( _Pixel.Normal.y) ); _B = (byte) Math.Min( 255, 255 * Math.Abs( _Pixel.Normal.z) ); #else _R = (byte) Math.Min( 255, 127 * (1.0f + _Pixel.Normal.x) ); _G = (byte) Math.Min( 255, 127 * (1.0f + _Pixel.Normal.y) ); _B = (byte) Math.Min( 255, 127 * (1.0f + _Pixel.Normal.z) ); #endif }
/// <summary> /// Converts JSON to a Protocol object. Private because Protocols should always be serialized as encrypted binary codes, and this function works with unencrypted strings (it's called in service of the former). /// </summary> /// <param name="json">JSON to deserialize.</param> private static void DisplayFromJsonAsync(string json) { new Thread(() => { try { #region allow protocols to be opened across platforms by manually editing the namespaces in the JSON string newJSON; switch (SensusServiceHelper.Get().GetType().Name) { case "AndroidSensusServiceHelper": newJSON = json.Replace(".iOS", ".Android").Replace(".WinPhone", ".Android"); break; case "iOSSensusServiceHelper": newJSON = json.Replace(".Android", ".iOS").Replace(".WinPhone", ".iOS"); break; case "WinPhone": newJSON = json.Replace(".Android", ".WinPhone").Replace(".iOS", ".WinPhone"); break; default: throw new SensusException("Attempted to deserialize JSON into unknown service helper type: " + SensusServiceHelper.Get().GetType().FullName); } if (newJSON == json) { SensusServiceHelper.Get().Logger.Log("No cross-platform conversion required for service helper JSON.", LoggingLevel.Normal, typeof(Protocol)); } else { SensusServiceHelper.Get().Logger.Log("Performed cross-platform conversion of service helper JSON.", LoggingLevel.Normal, typeof(Protocol)); json = newJSON; } #endregion Protocol protocol = null; ManualResetEvent protocolWait = new ManualResetEvent(false); // always deserialize protocols on the main thread (e.g., since a looper might be required for android) Device.BeginInvokeOnMainThread(() => { try { protocol = JsonConvert.DeserializeObject <Protocol>(json, SensusServiceHelper.JSON_SERIALIZER_SETTINGS); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Error while deserializing protocol: " + ex.Message, LoggingLevel.Normal, typeof(Protocol)); } finally { protocolWait.Set(); } }); protocolWait.WaitOne(); if (protocol == null) { SensusServiceHelper.Get().Logger.Log("Failed to deserialize protocol.", LoggingLevel.Normal, typeof(Protocol)); SensusServiceHelper.Get().FlashNotificationAsync("Failed to deserialize protocol."); return; } else { Action <Protocol> StartProtocol = p => { Device.BeginInvokeOnMainThread(async() => { if (!(App.Current.MainPage.Navigation.NavigationStack.Last() is ProtocolsPage)) { await App.Current.MainPage.Navigation.PushAsync(new ProtocolsPage()); } p.StartWithUserAgreement("You just opened a protocol named \"" + p.Name + "\" within Sensus." + (string.IsNullOrWhiteSpace(p.StartupAgreement) ? "" : " Please read the following terms and conditions.")); }); }; Protocol existingProtocol = SensusServiceHelper.Get().RegisteredProtocols.FirstOrDefault(p => p.Id == protocol.Id); if (existingProtocol == null) { Probe.GetAllAsync(probes => { // add any probes for the current platform that didn't come through when deserializing. for example, android has a listening WLAN probe, but iOS has a polling WLAN probe. neither will come through on the other platform when deserializing, since the types are not defined. List <Type> deserializedProbeTypes = protocol.Probes.Select(p => p.GetType()).ToList(); foreach (Probe probe in probes) { if (!deserializedProbeTypes.Contains(probe.GetType())) { SensusServiceHelper.Get().Logger.Log("Adding missing probe to protocol: " + probe.GetType().FullName, LoggingLevel.Normal, typeof(Protocol)); protocol.AddProbe(probe); } } // reset the random time anchor -- we shouldn't use the same one that someone else used protocol.ResetRandomTimeAnchor(); // reset the storage directory protocol.StorageDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), protocol.Id); if (!Directory.Exists(protocol.StorageDirectory)) { Directory.CreateDirectory(protocol.StorageDirectory); } SensusServiceHelper.Get().RegisterProtocol(protocol); StartProtocol(protocol); }); } else if (existingProtocol.Running) { SensusServiceHelper.Get().FlashNotificationAsync("Protocol \"" + existingProtocol.Name + "\" is already running."); } else { StartProtocol(existingProtocol); } } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to deserialize/display protocol from JSON: " + ex.Message, LoggingLevel.Normal, typeof(Protocol)); SensusServiceHelper.Get().FlashNotificationAsync("Failed to deserialize and/or display protocol."); } }).Start(); }
private void CubeMapSamplerFaceIndex( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { byte C = (byte) (_Pixel.FaceIndex & 0xFF); _R = _G = _B = C; }
protected override void PostStop() { Probe.Tell("postStop"); }
private void CubeMapSamplerNeighborProbeID( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { byte C = (byte) Math.Min( 255, 255 * ((1+_Pixel.NeighborProbeID) % 4) / 4 ); _R = _G = _B = C; }
/// <summary> /// Initializes a new instance of the <see cref="ProbePage"/> class. /// </summary> /// <param name="probe">Probe to display.</param> public ProbePage(Probe probe) { Title = "Probe"; StackLayout contentLayout = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.FillAndExpand }; string type = ""; if (probe is ListeningProbe) { type = "Listening"; } else if (probe is PollingProbe) { type = "Polling"; } contentLayout.Children.Add(new ContentView { Content = new Label { Text = probe.DisplayName + (type == "" ? "" : " (" + type + ")"), FontSize = 20, FontAttributes = FontAttributes.Italic, TextColor = Color.Accent, HorizontalOptions = LayoutOptions.Center }, Padding = new Thickness(0, 10, 0, 10) }); foreach (StackLayout stack in UiProperty.GetPropertyStacks(probe)) { contentLayout.Children.Add(stack); } #region script probes if (probe is ScriptProbe) { ScriptProbe scriptProbe = probe as ScriptProbe; Button editScriptsButton = new Button { Text = "Edit Scripts", FontSize = 20 }; contentLayout.Children.Add(editScriptsButton); editScriptsButton.Clicked += async(o, e) => { await Navigation.PushAsync(new ScriptRunnersPage(scriptProbe)); }; Button shareScriptButton = new Button { Text = "Share Definition", FontSize = 20 }; contentLayout.Children.Add(shareScriptButton); shareScriptButton.Clicked += async(o, e) => { string sharePath = SensusServiceHelper.Get().GetSharePath(".json"); using (StreamWriter shareFile = new StreamWriter(sharePath)) { shareFile.WriteLine(JsonConvert.SerializeObject(probe, SensusServiceHelper.JSON_SERIALIZER_SETTINGS)); } await SensusServiceHelper.Get().ShareFileAsync(sharePath, "Probe Definition", "application/json"); }; } #endregion #region proximity probe if (probe is IPointsOfInterestProximityProbe) { Button editTriggersButton = new Button { Text = "Edit Triggers", FontSize = 20, HorizontalOptions = LayoutOptions.FillAndExpand }; contentLayout.Children.Add(editTriggersButton); editTriggersButton.Clicked += async(o, e) => { await Navigation.PushAsync(new ProximityTriggersPage(probe as IPointsOfInterestProximityProbe)); }; } #endregion #region estimote probe if (probe is EstimoteBeaconProbe) { Button editBeaconsButton = new Button { Text = "Edit Beacons", FontSize = 20, HorizontalOptions = LayoutOptions.FillAndExpand }; contentLayout.Children.Add(editBeaconsButton); editBeaconsButton.Clicked += async(sender, e) => { await Navigation.PushAsync(new EstimoteBeaconProbeBeaconsPage(probe as EstimoteBeaconProbe)); }; } #endregion #region anonymization List <PropertyInfo> anonymizableProperties = probe.DatumType.GetProperties().Where(property => property.GetCustomAttribute <Anonymizable>() != null).ToList(); if (anonymizableProperties.Count > 0) { contentLayout.Children.Add(new Label { Text = "Anonymization", FontSize = 20, FontAttributes = FontAttributes.Italic, TextColor = Color.Accent, HorizontalOptions = LayoutOptions.Center }); List <StackLayout> anonymizablePropertyStacks = new List <StackLayout>(); foreach (PropertyInfo anonymizableProperty in anonymizableProperties) { Anonymizable anonymizableAttribute = anonymizableProperty.GetCustomAttribute <Anonymizable>(true); Label propertyLabel = new Label { Text = anonymizableAttribute.PropertyDisplayName ?? anonymizableProperty.Name + ":", FontSize = 20, HorizontalOptions = LayoutOptions.Start }; // populate a picker of anonymizers for the current property Picker anonymizerPicker = new Picker { Title = "Select Anonymizer", HorizontalOptions = LayoutOptions.FillAndExpand }; anonymizerPicker.Items.Add("Do Not Anonymize"); foreach (Anonymizer anonymizer in anonymizableAttribute.AvailableAnonymizers) { anonymizerPicker.Items.Add(anonymizer.DisplayText); } anonymizerPicker.SelectedIndexChanged += (o, e) => { Anonymizer selectedAnonymizer = null; if (anonymizerPicker.SelectedIndex > 0) { selectedAnonymizer = anonymizableAttribute.AvailableAnonymizers[anonymizerPicker.SelectedIndex - 1]; // subtract one from the selected index since the JsonAnonymizer's collection of anonymizers start after the "None" option within the picker. } probe.Protocol.JsonAnonymizer.SetAnonymizer(anonymizableProperty, selectedAnonymizer); }; // set the picker's index to the current anonymizer (or "Do Not Anonymize" if there is no current) Anonymizer currentAnonymizer = probe.Protocol.JsonAnonymizer.GetAnonymizer(anonymizableProperty); int currentIndex = 0; if (currentAnonymizer != null) { currentIndex = anonymizableAttribute.AvailableAnonymizers.IndexOf(currentAnonymizer) + 1; } anonymizerPicker.SelectedIndex = currentIndex; StackLayout anonymizablePropertyStack = new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { propertyLabel, anonymizerPicker } }; anonymizablePropertyStacks.Add(anonymizablePropertyStack); } foreach (StackLayout anonymizablePropertyStack in anonymizablePropertyStacks.OrderBy(s => (s.Children[0] as Label).Text)) { contentLayout.Children.Add(anonymizablePropertyStack); } } #endregion Content = new ScrollView { Content = contentLayout }; }
private void CubeMapSamplerSetAlbedo( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { Probe.Set S = _Pixel.ParentSet; if ( S == null || S.SetIndex == -1 || (m_IsolateSet && S.SetIndex != m_IsolatedSetIndex) ) { _R = _G = _B = 0; return; } _R = (byte) Math.Min( 255, 255 * S.Albedo.x ); _G = (byte) Math.Min( 255, 255 * S.Albedo.y ); _B = (byte) Math.Min( 255, 255 * S.Albedo.z ); }
private void FlashChartDataCountAsync(Probe probe) { SensusServiceHelper.Get().FlashNotificationAsync("Displaying " + probe.MaxChartDataCount + " point" + (probe.MaxChartDataCount == 1 ? "" : "s") + ".", false, TimeSpan.FromSeconds(2)); }
private void CubeMapSamplerSetNormal( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { Probe.Set S = _Pixel.ParentSet; if ( S == null || S.SetIndex == -1 || (m_IsolateSet && S.SetIndex != m_IsolatedSetIndex) ) { _R = _G = _B = 0; return; } #if ABS_NORMAL _R = (byte) Math.Min( 255, 255 * Math.Abs( S.Normal.x) ); _G = (byte) Math.Min( 255, 255 * Math.Abs( S.Normal.y) ); _B = (byte) Math.Min( 255, 255 * Math.Abs( S.Normal.z) ); #else _R = (byte) Math.Min( 255, 127 * (1.0f + S.Normal.x) ); _G = (byte) Math.Min( 255, 127 * (1.0f + S.Normal.y) ); _B = (byte) Math.Min( 255, 127 * (1.0f + S.Normal.z) ); #endif }
public void ProcessRequest(HttpContext context) { Menu menu = new Menu(); context.Response.Clear(); context.Response.ContentType = "text/plain"; //StringBuilder response = this.GetResponse(); try { // Create and register new channel this.channel_ = new IiopClientChannel(); ChannelServices.RegisterChannel(this.channel_, false); //Accessing the target object provided by TEM service this.tem_ = (TestExecutionManager)RemotingServices.Connect(typeof(TestExecutionManager), context.Request.QueryString["temLocation"]); DataAcquisitionController[] dacs = this.tem_.get_DACs(); if (0 < dacs.Length) { menu.Dacs = new List<DAC>(); foreach (DataAcquisitionController dac in dacs) { DAC dac_element = new DAC(); dac_element.Name = dac.name; dac_element.Probes = new List<Probe>(); this.probes_ = dac.get_probe_instances(); if (0 < this.probes_.Length) { foreach (ProbeInstance probe in this.probes_) { Probe probe_element = new Probe(); probe_element.Name = probe.inst_name; probe_element.Einode_Name = probe.einode_name; probe_element.Uuid = probe.inst_uuid; probe_element.Type_Name = probe.inst_type_name; dac_element.Probes.Add(probe_element); } } menu.Dacs.Add(dac_element); } } } finally { ChannelServices.UnregisterChannel(this.channel_); } StringBuilder response = new StringBuilder(); JavaScriptSerializer ser = new JavaScriptSerializer(); ser.Serialize(menu,response); context.Response.Write(response.ToString()); context.Response.End(); }
private void CubeMapSamplerSetSamples( Probe.Pixel _Pixel, out byte _R, out byte _G, out byte _B ) { Probe.Set S = _Pixel.ParentSet; if ( S == null || S.SetIndex == -1 || S.EmissiveMatID != -1 || (m_IsolateSet && S.SetIndex != m_IsolatedSetIndex) ) { _R = 0; _G = 0; _B = 0; return; } // float Distance2SetCenter = 0.2f * (_Pixel.Position - S.Position).Length; // byte C = (byte) Math.Min( 255, 255 * Distance2SetCenter ); byte C = (byte) (255 * (1+_Pixel.ParentSetSampleIndex) / S.Samples.Length); _R = _G = _B = C; }
public IsolatedPingWindow(Probe pingItem) { InitializeComponent(); pingItem.IsolatedWindow = this; DataContext = pingItem; }
private void EndProbeDeserialize( StreamReader streamReader, SerializationContext serializationContext, PropertyMetaData propertyMetaData, object deserializedObject, Probe probe) { probe.DiagnosticInfo.Length = streamReader.Position - probe.DiagnosticInfo.Offset; probe.DiagnosticInfo.Value = deserializedObject; serializationContext.EndProbe(probe); }
public void Clone() { MachineModel original = new MachineModel(); Endstop endstop = new Endstop { Triggered = true, Type = EndstopType.MotorStallAny, Probe = 0 }; original.Sensors.Endstops.Add(endstop); Probe probe = new Probe { DisablesBed = true, DiveHeight = 45.6F, Inverted = true, MaxProbeCount = 4, RecoveryTime = 0.65F, Speed = 456, Threshold = 678, Tolerance = 0.42F, TravelSpeed = 500, TriggerHeight = 1.23F, Type = ProbeType.Switch, Value = 45 }; probe.SecondaryValues.Add(12); probe.SecondaryValues.Add(34); original.Sensors.Probes.Add(probe); MachineModel clone = (MachineModel)original.Clone(); Assert.AreEqual(1, original.Sensors.Endstops.Count); Assert.AreEqual(original.Sensors.Endstops[0].Triggered, clone.Sensors.Endstops[0].Triggered); Assert.AreEqual(original.Sensors.Endstops[0].Type, clone.Sensors.Endstops[0].Type); Assert.AreEqual(original.Sensors.Endstops[0].Probe, clone.Sensors.Endstops[0].Probe); Assert.AreEqual(1, original.Sensors.Probes.Count); Assert.AreEqual(original.Sensors.Probes[0].DisablesBed, clone.Sensors.Probes[0].DisablesBed); Assert.AreEqual(original.Sensors.Probes[0].DiveHeight, clone.Sensors.Probes[0].DiveHeight); Assert.AreEqual(original.Sensors.Probes[0].Inverted, clone.Sensors.Probes[0].Inverted); Assert.AreEqual(original.Sensors.Probes[0].MaxProbeCount, clone.Sensors.Probes[0].MaxProbeCount); Assert.AreEqual(original.Sensors.Probes[0].RecoveryTime, clone.Sensors.Probes[0].RecoveryTime); Assert.AreEqual(original.Sensors.Probes[0].SecondaryValues, clone.Sensors.Probes[0].SecondaryValues); Assert.AreEqual(original.Sensors.Probes[0].Speed, clone.Sensors.Probes[0].Speed); Assert.AreEqual(original.Sensors.Probes[0].Threshold, clone.Sensors.Probes[0].Threshold); Assert.AreEqual(original.Sensors.Probes[0].Tolerance, clone.Sensors.Probes[0].Tolerance); Assert.AreEqual(original.Sensors.Probes[0].TravelSpeed, clone.Sensors.Probes[0].TravelSpeed); Assert.AreEqual(original.Sensors.Probes[0].TriggerHeight, clone.Sensors.Probes[0].TriggerHeight); Assert.AreEqual(original.Sensors.Probes[0].Type, clone.Sensors.Probes[0].Type); Assert.AreEqual(original.Sensors.Probes[0].Value, clone.Sensors.Probes[0].Value); Assert.AreNotSame(original.Sensors.Endstops[0].Triggered, clone.Sensors.Endstops[0].Triggered); Assert.AreNotSame(original.Sensors.Endstops[0].Type, clone.Sensors.Endstops[0].Type); Assert.AreNotSame(original.Sensors.Endstops[0].Probe, clone.Sensors.Endstops[0].Probe); Assert.AreNotSame(original.Sensors.Probes[0].DisablesBed, clone.Sensors.Probes[0].DisablesBed); Assert.AreNotSame(original.Sensors.Probes[0].DiveHeight, clone.Sensors.Probes[0].DiveHeight); Assert.AreNotSame(original.Sensors.Probes[0].Inverted, clone.Sensors.Probes[0].Inverted); Assert.AreNotSame(original.Sensors.Probes[0].MaxProbeCount, clone.Sensors.Probes[0].MaxProbeCount); Assert.AreNotSame(original.Sensors.Probes[0].RecoveryTime, clone.Sensors.Probes[0].RecoveryTime); Assert.AreNotSame(original.Sensors.Probes[0].SecondaryValues, clone.Sensors.Probes[0].SecondaryValues); Assert.AreNotSame(original.Sensors.Probes[0].Speed, clone.Sensors.Probes[0].Speed); Assert.AreNotSame(original.Sensors.Probes[0].Threshold, clone.Sensors.Probes[0].Threshold); Assert.AreNotSame(original.Sensors.Probes[0].Tolerance, clone.Sensors.Probes[0].Tolerance); Assert.AreNotSame(original.Sensors.Probes[0].TravelSpeed, clone.Sensors.Probes[0].TravelSpeed); Assert.AreNotSame(original.Sensors.Probes[0].TriggerHeight, clone.Sensors.Probes[0].TriggerHeight); Assert.AreNotSame(original.Sensors.Probes[0].Type, clone.Sensors.Probes[0].Type); Assert.AreNotSame(original.Sensors.Probes[0].Value, clone.Sensors.Probes[0].Value); }