public GameBoard(MinMax node_type, GameBoard parent) { //parents and children this.parent = parent; this.children = new List<GameBoard>(); this.board = parent.CopyBoard(); if (node_type == MinMax.Max) { this.node_type = MinMax.Max; this.alpha = 0; } else { this.node_type = MinMax.Min; this.beta = 0; } }
// default constructor public GameBoard() { //parents and children this.parent = null; this.children = new List<GameBoard>(); this.board = new GamePiece[4,4]; //the game board - 4x4 array for (int i = 0; i <= 3; i++) { for (int j = 0; j <= 3; j++) { this.board[i, j] = new GamePiece(Colour.NONE, 0); } } this.board[0, 3].stones = 10; //player 1 - BLACK stones (them) this.board[0, 3].colour = Colour.BLACK; //MIN this.board[3, 0].stones = 10; //player2 - WHITE stones (us) this.board[3, 0].colour = Colour.WHITE; //MAX this.node_type = MinMax.Null; }
void RefreshPageSelector() { var paginate = (Pagination.Paginate)Pagination; var totalPages = TotalPages.Value; btPrevious.IsEnabled = 1 < paginate.CurrentPage; btNext.IsEnabled = paginate.CurrentPage < totalPages; spPages.Children.Clear(); MinMax<int> interval = new MinMax<int>( Math.Max(1, paginate.CurrentPage - 2), Math.Min(paginate.CurrentPage + 2, totalPages)); if (interval.Min != 1) { spPages.Children.Add(CreateButton(1)); if (interval.Min - 1 != 1) spPages.Children.Add(CreateLabel("...")); } for (int i = interval.Min; i < paginate.CurrentPage; i++) spPages.Children.Add(CreateButton(i)); spPages.Children.Add(CreateLabel(paginate.CurrentPage.ToString())); for (int i = paginate.CurrentPage + 1; i <= interval.Max; i++) spPages.Children.Add(CreateButton(i)); if (interval.Max != totalPages) { if (interval.Max + 1 != totalPages) spPages.Children.Add(CreateLabel("...")); spPages.Children.Add(CreateButton(totalPages)); } }
public void SetPulseFunctionTrailingEdge(int channel, MinMax transition) { if (transition == MinMax.Max) { WaveGen.SendCommand("SOUR" + channel.ToString() + ":PULSe:TRANsition:TRAILing MAX"); } else { WaveGen.SendCommand("SOUR" + channel.ToString() + ":PULSe:TRANsition:TRAILing MIN"); } }
public bool SetNodeType(MinMax type) { this.node_type = type; return true; }
public async Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> events) { try { var now = DateTime.UtcNow; foreach (var eventData in events) { // We don't care about messages that are older than bufferTimeInterval if ((eventData.EnqueuedTimeUtc + bufferTimeInterval) >= now) { // Get message from the eventData body and convert JSON string into message object string eventBodyAsString = Encoding.UTF8.GetString(eventData.GetBytes()); // There can be several messages in one IList <IDictionary <string, object> > messagePayloads; try { // Attempt to deserialze event body as single JSON message messagePayloads = new List <IDictionary <string, object> > { JsonConvert.DeserializeObject <IDictionary <string, object> >(eventBodyAsString) }; } catch { // Not a single JSON message: attempt to deserialize as array of messages // Azure Stream Analytics Preview generates invalid JSON for some multi-values queries // Workaround: turn concatenated json objects (ivalid JSON) into array of json objects (valid JSON) if (eventBodyAsString.IndexOf("}{") >= 0) { eventBodyAsString = eventBodyAsString.Replace("}{", "},{"); } if (eventBodyAsString.IndexOf("}\r\n{") >= 0) { eventBodyAsString = eventBodyAsString.Replace("}\r\n{", "},{"); } if (!eventBodyAsString.EndsWith("]")) { eventBodyAsString = eventBodyAsString + "]"; } if (!eventBodyAsString.StartsWith("[")) { eventBodyAsString = "[" + eventBodyAsString.Substring(eventBodyAsString.IndexOf("{")); } messagePayloads = JsonConvert.DeserializeObject <IList <IDictionary <string, object> > >(eventBodyAsString); } var rnd = new Random(); foreach (var messagePayload in messagePayloads) { // Read time value if (messagePayload.ContainsKey("timecreated")) { messagePayload["time"] = messagePayload["timecreated"]; } if (messagePayload.ContainsKey("timearrived")) { messagePayload["time"] = messagePayload["timearrived"]; } // Device Id for IoT Hub messages if (eventData.SystemProperties.ContainsKey("iothub-connection-device-id")) { messagePayload["displayname"] = eventData.SystemProperties["iothub-connection-device-id"]; } // process an alert if (messagePayload.ContainsKey("alerttype") && messagePayload.ContainsKey("timecreated")) { Debug.Print("Alert message received!"); DateTime time = DateTime.Parse(messagePayload["timecreated"].ToString()); // find the nearest point lock (sortedDataBuffer) { int idx = SearchHelper.FindFirstIndexGreaterThanOrEqualTo(sortedDataBuffer, time); bool found = false; string alertType = messagePayload["alerttype"] as string; if (idx >= sortedDataBuffer.Values.Count) { idx = sortedDataBuffer.Values.Count - 1; } while (idx >= 0) { List <IDictionary <string, object> > dictList = sortedDataBuffer.Values[idx]; foreach (IDictionary <string, object> dict in dictList) { if ( (dict.ContainsKey("guid") && messagePayload.ContainsKey("guid") && messagePayload["guid"].ToString() == dict["guid"].ToString()) && (dict.ContainsKey("measurename") && messagePayload.ContainsKey("measurename") && messagePayload["measurename"].ToString() == dict["measurename"].ToString()) && (!messagePayload.ContainsKey("displayname") || dict.ContainsKey("displayname") && messagePayload["measurename"].ToString() == dict["measurename"].ToString()) ) { // fill anomaly message if (!messagePayload.ContainsKey("value")) { messagePayload["value"] = dict["value"]; } if (!messagePayload.ContainsKey("displayname") && dict.ContainsKey("displayname")) { messagePayload["displayname"] = dict["displayname"]; } if (!messagePayload.ContainsKey("time")) { messagePayload["time"] = messagePayload["timecreated"]; } found = true; break; } } if (found) { break; } idx--; } } } if (messagePayload.ContainsKey("guid")) { var guid = messagePayload["guid"].ToString(); double val = Convert.ToDouble(messagePayload["value"]); if (!MinMaxValue.ContainsKey(guid)) { MinMaxValue.Add(guid, new MinMax { min = val, max = val }); } MinMax tmp = MinMaxValue[messagePayload["guid"].ToString()]; if (tmp.min > val) { tmp.min = val; } if (tmp.max < val) { tmp.max = val; } } // We want to read the time value from the message itself. // If none is found we will use the enqueued time DateTime messageTimeStamp = new DateTime(); if (messagePayload.ContainsKey("time")) { messageTimeStamp = DateTime.Parse(messagePayload["time"].ToString()); //if (GenerateAnomalies && rnd.Next(100) >= 95) //{ // messagePayload.Add("alerttype", "testType"); // messagePayload.Add("dsplalert", "testAlert"); // messagePayload.Add("message", "Anomaly detected by Azure ML model."); // messagePayload.Add("timestart", messagePayload["time"]); // // correct value // if (rnd.Next(2) == 1) // messagePayload["value"] = MinMaxValue[messagePayload["guid"].ToString()].max * (1.01 + 0.05 * rnd.Next(100) / 100); // else // messagePayload["value"] = MinMaxValue[messagePayload["guid"].ToString()].min * (0.99 - 0.05 * rnd.Next(100) / 100); //} } else if (messagePayload.ContainsKey("timestart")) { messageTimeStamp = DateTime.Parse(messagePayload["timestart"].ToString()); } else { messageTimeStamp = eventData.EnqueuedTimeUtc; } // Build up the list of devices seen so far (in lieu of a formal device repository) // Also keep the last message received per device (not currently used in the sample) if (messagePayload.ContainsKey("guid") && !messagePayload.ContainsKey("valueAvg")) { string guid = messagePayload["guid"].ToString(); if (guid != null) { WebSocketEventProcessor.g_devices.TryAdd(guid, messagePayload); } } // Notify clients MyWebSocketHandler.SendToClients(messagePayload); // Buffer messages so we can resend them to clients that connect later // or when a client requests data for a different device // Lock to guard against concurrent reads from client resend lock (sortedDataBuffer) { if (!sortedDataBuffer.ContainsKey(messageTimeStamp)) { sortedDataBuffer.Add(messageTimeStamp, new List <IDictionary <string, object> >()); } sortedDataBuffer[messageTimeStamp].Add(messagePayload); } } } else { Debug.Print("Received old message timestamped:" + eventData.EnqueuedTimeUtc.ToString()); } } //Call checkpoint every minute if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(1)) { await context.CheckpointAsync(); lock (this) { this.checkpointStopWatch.Restart(); } // trim data buffer to keep only last 10 minutes of data lock (sortedDataBuffer) { DateTime oldDataPoint = now - bufferTimeInterval; // find the closest point int idx = SearchHelper.FindFirstIndexGreaterThanOrEqualTo(sortedDataBuffer, oldDataPoint); // trim while (idx > 0 && sortedDataBuffer.Count > 0 && sortedDataBuffer.Keys[0] <= oldDataPoint) { sortedDataBuffer.RemoveAt(0); } } } } catch (Exception e) { Trace.TraceError("Error processing events in EH {0}, partition {1}: {0}", context.EventHubPath, context.Lease.PartitionId, e.Message); } }
static MinMax MultipleReturns(int[] myArray) { MinMax values = new MinMax(); values.min = myArray.Min(); values.max = myArray.Max(); return values; }
/// <summary> /// Override for <seealso cref="UIElement.ArrangeCore" />. /// </summary> protected sealed override void ArrangeCore(Rect finalRect) { // If using layout rounding, check whether rounding needs to compensate for high DPI bool useLayoutRounding = this.UseLayoutRounding; LayoutTransformData ltd = LayoutTransformDataField.GetValue(this); Size transformedUnroundedDS = Size.Empty; if (useLayoutRounding) { if (!CheckFlagsAnd(VisualFlags.UseLayoutRounding)) { SetFlags(true, VisualFlags.UseLayoutRounding); } } if (BypassLayoutPolicies) { Size oldRenderSize = RenderSize; Size inkSize = ArrangeOverride(finalRect.Size); RenderSize = inkSize; SetLayoutOffset(new Vector(finalRect.X, finalRect.Y), oldRenderSize); } else { // If LayoutConstrained==true (parent wins in layout), // we might get finalRect.Size smaller then UnclippedDesiredSize. // Stricltly speaking, this may be the case even if LayoutConstrained==false (child wins), // since who knows what a particualr parent panel will try to do in error. // In this case we will not actually arrange a child at a smaller size, // since the logic of the child does not expect to receive smaller size // (if it coudl deal with smaller size, it probably would accept it in MeasureOverride) // so lets replace the smaller arreange size with UnclippedDesiredSize // and then clip the guy later. // We will use at least UnclippedDesiredSize to compute arrangeSize of the child, and // we will use layoutSlotSize to compute alignments - so the bigger child can be aligned within // smaller slot. // This is computed on every ArrangeCore. Depending on LayoutConstrained, actual clip may apply or not NeedsClipBounds = false; // Start to compute arrange size for the child. // It starts from layout slot or deisred size if layout slot is smaller then desired, // and then we reduce it by margins, apply Width/Height etc, to arrive at the size // that child will get in its ArrangeOverride. Size arrangeSize = finalRect.Size; Thickness margin = Margin; double marginWidth = margin.Left + margin.Right; double marginHeight = margin.Top + margin.Bottom; arrangeSize.Width = Math.Max(0, arrangeSize.Width - marginWidth); arrangeSize.Height = Math.Max(0, arrangeSize.Height - marginHeight); // First, get clipped, transformed, unrounded size. if (useLayoutRounding) { if (ltd != null && ltd.TransformedUnroundedDS != null) { transformedUnroundedDS = ltd.TransformedUnroundedDS; transformedUnroundedDS.Width = Math.Max(0, transformedUnroundedDS.Width - marginWidth); transformedUnroundedDS.Height = Math.Max(0, transformedUnroundedDS.Height- marginHeight); } } // Next, compare against unclipped, transformed size. SizeBox sb = UnclippedDesiredSizeField.GetValue(this); Size unclippedDesiredSize; if (sb == null) { unclippedDesiredSize = new Size(Math.Max(0, this.DesiredSize.Width - marginWidth), Math.Max(0, this.DesiredSize.Height - marginHeight)); // There is no unclipped desired size, so check against clipped, but unrounded DS. if (transformedUnroundedDS != Size.Empty) { unclippedDesiredSize.Width = Math.Max(transformedUnroundedDS.Width, unclippedDesiredSize.Width); unclippedDesiredSize.Height = Math.Max(transformedUnroundedDS.Height, unclippedDesiredSize.Height); } } else { unclippedDesiredSize = new Size(sb.Width, sb.Height); } if (DoubleUtil.LessThan(arrangeSize.Width, unclippedDesiredSize.Width)) { NeedsClipBounds = true; arrangeSize.Width = unclippedDesiredSize.Width; } if (DoubleUtil.LessThan(arrangeSize.Height, unclippedDesiredSize.Height)) { NeedsClipBounds = true; arrangeSize.Height = unclippedDesiredSize.Height; } // Alignment==Stretch --> arrange at the slot size minus margins // Alignment!=Stretch --> arrange at the unclippedDesiredSize if (HorizontalAlignment != HorizontalAlignment.Stretch) { arrangeSize.Width = unclippedDesiredSize.Width; } if (VerticalAlignment != VerticalAlignment.Stretch) { arrangeSize.Height = unclippedDesiredSize.Height; } //if LayoutTransform is set, arrange at untransformed DS always //alignments apply to the BoundingBox after transform if (ltd != null) { // Repeat the measure-time algorithm for finding a best fit local rect. // This essentially implements Stretch in case of LayoutTransform Size potentialArrangeSize = FindMaximalAreaLocalSpaceRect(ltd.Transform, arrangeSize); arrangeSize = potentialArrangeSize; // If using layout rounding, round untransformed desired size - in MeasureCore, this value is first transformed and clipped // before rounding, and hence saved unrounded. unclippedDesiredSize = ltd.UntransformedDS; //only use max area rect if both dimensions of it are larger then //desired size - replace with desired size otherwise if (!DoubleUtil.IsZero(potentialArrangeSize.Width) && !DoubleUtil.IsZero(potentialArrangeSize.Height)) { //Use less precise comparision - otherwise FP jitter may cause drastic jumps here if (LayoutDoubleUtil.LessThan(potentialArrangeSize.Width, unclippedDesiredSize.Width) || LayoutDoubleUtil.LessThan(potentialArrangeSize.Height, unclippedDesiredSize.Height)) { arrangeSize = unclippedDesiredSize; } } //if pre-transformed into local space arrangeSize is smaller in any dimension then //unclipped local DesiredSize of the element, extend the arrangeSize but //remember that we potentially need to clip the result of such arrange. if (DoubleUtil.LessThan(arrangeSize.Width, unclippedDesiredSize.Width)) { NeedsClipBounds = true; arrangeSize.Width = unclippedDesiredSize.Width; } if (DoubleUtil.LessThan(arrangeSize.Height, unclippedDesiredSize.Height)) { NeedsClipBounds = true; arrangeSize.Height = unclippedDesiredSize.Height; } } MinMax mm = new MinMax(this); //we have to choose max between UnclippedDesiredSize and Max here, because //otherwise setting of max property could cause arrange at less then unclippedDS. //Clipping by Max is needed to limit stretch here double effectiveMaxWidth = Math.Max(unclippedDesiredSize.Width, mm.maxWidth); if (DoubleUtil.LessThan(effectiveMaxWidth, arrangeSize.Width)) { NeedsClipBounds = true; arrangeSize.Width = effectiveMaxWidth; } double effectiveMaxHeight = Math.Max(unclippedDesiredSize.Height, mm.maxHeight); if (DoubleUtil.LessThan(effectiveMaxHeight, arrangeSize.Height)) { NeedsClipBounds = true; arrangeSize.Height = effectiveMaxHeight; } // If using layout rounding, round size passed to children. if (useLayoutRounding) { arrangeSize = UIElement.RoundLayoutSize(arrangeSize, DpiScaleX, DpiScaleY); } Size oldRenderSize = RenderSize; Size innerInkSize = ArrangeOverride(arrangeSize); //Here we use un-clipped InkSize because element does not know that it is //clipped by layout system and it shoudl have as much space to render as //it returned from its own ArrangeOverride RenderSize = innerInkSize; if (useLayoutRounding) { RenderSize = UIElement.RoundLayoutSize(RenderSize, DpiScaleX, DpiScaleY); } //clippedInkSize differs from InkSize only what MaxWidth/Height explicitly clip the //otherwise good arrangement. For ex, DS<clientSize but DS>MaxWidth - in this //case we should initiate clip at MaxWidth and only show Top-Left portion //of the element limited by Max properties. It is Top-left because in case when we //are clipped by container we also degrade to Top-Left, so we are consistent. Size clippedInkSize = new Size(Math.Min(innerInkSize.Width, mm.maxWidth), Math.Min(innerInkSize.Height, mm.maxHeight)); if (useLayoutRounding) { clippedInkSize = UIElement.RoundLayoutSize(clippedInkSize, DpiScaleX, DpiScaleY); } //remember we have to clip if Max properties limit the inkSize NeedsClipBounds |= DoubleUtil.LessThan(clippedInkSize.Width, innerInkSize.Width) || DoubleUtil.LessThan(clippedInkSize.Height, innerInkSize.Height); //if LayoutTransform is set, get the "outer bounds" - the alignments etc work on them if (ltd != null) { Rect inkRectTransformed = Rect.Transform(new Rect(0, 0, clippedInkSize.Width, clippedInkSize.Height), ltd.Transform.Value); clippedInkSize.Width = inkRectTransformed.Width; clippedInkSize.Height = inkRectTransformed.Height; if (useLayoutRounding) { clippedInkSize = UIElement.RoundLayoutSize(clippedInkSize, DpiScaleX, DpiScaleY); } } //Note that inkSize now can be bigger then layoutSlotSize-margin (because of layout //squeeze by the parent or LayoutConstrained=true, which clips desired size in Measure). // The client size is the size of layout slot decreased by margins. // This is the "window" through which we see the content of the child. // Alignments position ink of the child in this "window". // Max with 0 is neccessary because layout slot may be smaller then unclipped desired size. Size clientSize = new Size(Math.Max(0, finalRect.Width - marginWidth), Math.Max(0, finalRect.Height - marginHeight)); if (useLayoutRounding) { clientSize = UIElement.RoundLayoutSize(clientSize, DpiScaleX, DpiScaleY); } //remember we have to clip if clientSize limits the inkSize NeedsClipBounds |= DoubleUtil.LessThan(clientSize.Width, clippedInkSize.Width) || DoubleUtil.LessThan(clientSize.Height, clippedInkSize.Height); Vector offset = ComputeAlignmentOffset(clientSize, clippedInkSize); offset.X += finalRect.X + margin.Left; offset.Y += finalRect.Y + margin.Top; // If using layout rounding, round offset. if (useLayoutRounding) { offset.X = UIElement.RoundLayoutValue(offset.X, DpiScaleX); offset.Y = UIElement.RoundLayoutValue(offset.Y, DpiScaleY); } SetLayoutOffset(offset, oldRenderSize); } }
public List <string> DanhSachHangMinMaxThuocTinh <T>(DanhSachMayTinh danhSachMayTinh, MayTinh.Tinh tinh, MinMax minMax) { List <string> result = new List <string>(); foreach (var item in danhSachMayTinh.listMayTinh) { if (item.TruyXuatThuocTinhThietBi(tinh) == MinMaxThuocTinhThietBi <T>(danhSachMayTinh, tinh, minMax)) { if (!result.Contains(item.TruyXuatHangCuaThietBi <T>())) { result.Add(item.TruyXuatHangCuaThietBi <T>()); } } } return(result); }
public float MinMaxThuocTinhThietBi <T>(DanhSachMayTinh danhSachMayTinh, MayTinh.Tinh tinh, MinMax minMax) { switch (minMax) { case MinMax.Min: return(danhSachMayTinh.listMayTinh.Min(x => x.TruyXuatThuocTinhThietBi(tinh))); case MinMax.Max: return(danhSachMayTinh.listMayTinh.Max(x => x.TruyXuatThuocTinhThietBi(tinh))); } return(0); }
public override void Execute() { #line 6 "..\..\Signum\Views\PaginationSelector.cshtml" Pagination pagination = (Pagination)ViewData[ViewDataKeys.Pagination]; QueryDescription queryDescription = (QueryDescription)ViewData[ViewDataKeys.QueryDescription]; pagination = FindOptions.ReplacePagination(queryDescription.QueryName, pagination); var paginate = pagination as Pagination.Paginate; ResultTable resultTable = (ResultTable)ViewData[ViewDataKeys.Results]; Func <PaginationMode, int?, int?, Pagination> getPagination = (mode, elementsPerPage, pageNumber) => { switch (mode) { case PaginationMode.All: return(new Pagination.All()); case PaginationMode.Firsts: return(new Pagination.Firsts(elementsPerPage ?? 1)); case PaginationMode.Paginate: return(new Pagination.Paginate(elementsPerPage ?? 1)); default: throw new InvalidOperationException(); } }; Func <Pagination, bool> isAllowed = pag => pag == FindOptions.ReplacePagination(queryDescription.QueryName, pag); #line default #line hidden WriteLiteral("\r\n\r\n<div"); WriteLiteral(" class=\"sf-search-footer\""); WriteAttribute("style", Tuple.Create(" style=\"", 1201), Tuple.Create("\"", 1278) , Tuple.Create(Tuple.Create("", 1209), Tuple.Create("display:", 1209), true) #line 32 "..\..\Signum\Views\PaginationSelector.cshtml" , Tuple.Create(Tuple.Create("", 1217), Tuple.Create <System.Object, System.Int32>(((bool)ViewData[ViewDataKeys.ShowFooter])? "block": "none" #line default #line hidden , 1217), false) ); WriteLiteral(">\r\n <div"); WriteLiteral(" class=\"sf-pagination-left\""); WriteLiteral(">\r\n"); #line 34 "..\..\Signum\Views\PaginationSelector.cshtml" #line default #line hidden #line 34 "..\..\Signum\Views\PaginationSelector.cshtml" if (resultTable != null) { if (pagination is Pagination.All) { #line default #line hidden WriteLiteral(" <span>"); #line 38 "..\..\Signum\Views\PaginationSelector.cshtml" Write(SearchMessage._0Results_N.NiceToString().ForGenderAndNumber(number: resultTable.TotalElements).FormatHtml( new HtmlTag("span").Class("sf-pagination-strong").SetInnerText(resultTable.TotalElements.ToString()))); #line default #line hidden WriteLiteral("\r\n </span>\r\n"); #line 41 "..\..\Signum\Views\PaginationSelector.cshtml" } else if (pagination is Pagination.Firsts) { var first = (Pagination.Firsts)pagination; #line default #line hidden WriteLiteral(" <span>"); #line 47 "..\..\Signum\Views\PaginationSelector.cshtml" Write(SearchMessage.First0Results_N.NiceToString().ForGenderAndNumber(number: resultTable.Rows.Length).FormatHtml( new HtmlTag("span").Class("sf-pagination-strong").Class(resultTable.Rows.Length == first.TopElements ? "sf-pagination-overflow" : null).SetInnerText(resultTable.Rows.Length.ToString()))); #line default #line hidden WriteLiteral("\r\n </span>\r\n"); #line 50 "..\..\Signum\Views\PaginationSelector.cshtml" } else if (pagination is Pagination.Paginate) { #line default #line hidden WriteLiteral(" <span>\r\n"); WriteLiteral(" "); #line 54 "..\..\Signum\Views\PaginationSelector.cshtml" Write(SearchMessage._01of2Results_N.NiceToString().ForGenderAndNumber(number: resultTable.TotalElements).FormatHtml( new HtmlTag("span").Class("sf-pagination-strong").SetInnerText(resultTable.StartElementIndex.ToString()), new HtmlTag("span").Class("sf-pagination-strong").SetInnerText(resultTable.EndElementIndex.ToString()), new HtmlTag("span").Class("sf-pagination-strong").SetInnerText(resultTable.TotalElements.ToString()) )); #line default #line hidden WriteLiteral("\r\n </span>\r\n"); #line 60 "..\..\Signum\Views\PaginationSelector.cshtml" } } #line default #line hidden WriteLiteral(" </div>\r\n\r\n <div"); WriteLiteral(" class=\"sf-pagination-center form-inline form-xs\""); WriteLiteral(">\r\n"); #line 65 "..\..\Signum\Views\PaginationSelector.cshtml" #line default #line hidden #line 65 "..\..\Signum\Views\PaginationSelector.cshtml" var currentMode = pagination.GetMode(); var modes = EnumExtensions.GetValues <PaginationMode>().Where(a => isAllowed(getPagination(a, null, null))).Select(pm => new SelectListItem { Text = pm.NiceToString(), Value = pm.ToString(), Selected = currentMode == pm }).ToList(); #line default #line hidden WriteLiteral("\r\n"); WriteLiteral(" "); #line 74 "..\..\Signum\Views\PaginationSelector.cshtml" Write(Html.SafeDropDownList(Model.Compose("sfPaginationMode"), modes, new { @class = "sf-pagination-size form-control" })); #line default #line hidden WriteLiteral("\r\n\r\n"); #line 76 "..\..\Signum\Views\PaginationSelector.cshtml" #line default #line hidden #line 76 "..\..\Signum\Views\PaginationSelector.cshtml" if (!(pagination is Pagination.All)) { var currentElements = pagination.GetElementsPerPage(); var elements = new List <int> { 5, 10, 20, 50, 100, 200 }.Where(a => isAllowed(getPagination(pagination.GetMode(), a, null))).Select(i => new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = i == currentElements }).ToList(); #line default #line hidden #line 81 "..\..\Signum\Views\PaginationSelector.cshtml" Write(Html.SafeDropDownList(Model.Compose("sfElems"), elements, new { @class = "sf-pagination-size form-control" })); #line default #line hidden #line 81 "..\..\Signum\Views\PaginationSelector.cshtml" } #line default #line hidden WriteLiteral(" </div>\r\n\r\n <div"); WriteLiteral(" class=\"sf-pagination-right\""); WriteLiteral(">\r\n\r\n"); #line 87 "..\..\Signum\Views\PaginationSelector.cshtml" #line default #line hidden #line 87 "..\..\Signum\Views\PaginationSelector.cshtml" if (resultTable != null && paginate != null) { MinMax <int> interval = new MinMax <int>( Math.Max(1, paginate.CurrentPage - 2), Math.Min(paginate.CurrentPage + 2, resultTable.TotalPages.Value)); #line default #line hidden WriteLiteral(" <input"); WriteLiteral(" type=\"hidden\""); WriteAttribute("id", Tuple.Create(" id=\"", 4424), Tuple.Create("\"", 4455) #line 93 "..\..\Signum\Views\PaginationSelector.cshtml" , Tuple.Create(Tuple.Create("", 4429), Tuple.Create <System.Object, System.Int32>(Model.Compose("sfPage") #line default #line hidden , 4429), false) ); WriteAttribute("value", Tuple.Create(" value=\"", 4456), Tuple.Create("\"", 4485) #line 93 "..\..\Signum\Views\PaginationSelector.cshtml" , Tuple.Create(Tuple.Create("", 4464), Tuple.Create <System.Object, System.Int32>(paginate.CurrentPage #line default #line hidden , 4464), false) ); WriteLiteral(" />\r\n"); WriteLiteral(" <ul"); WriteLiteral(" class=\"pagination\""); WriteLiteral(">\r\n <li"); WriteAttribute("class", Tuple.Create(" class=\"", 4547), Tuple.Create("\"", 4605) #line 95 "..\..\Signum\Views\PaginationSelector.cshtml" , Tuple.Create(Tuple.Create("", 4555), Tuple.Create <System.Object, System.Int32>((paginate.CurrentPage <= 1) ? "disabled" : null #line default #line hidden , 4555), false) ); WriteLiteral(" ><a"); WriteLiteral(" data-page=\""); #line 95 "..\..\Signum\Views\PaginationSelector.cshtml" Write(paginate.CurrentPage - 1); #line default #line hidden WriteLiteral("\""); WriteLiteral(" href=\"#\""); WriteLiteral(">«</a></li>\r\n\r\n\r\n\r\n"); #line 99 "..\..\Signum\Views\PaginationSelector.cshtml" #line default #line hidden #line 99 "..\..\Signum\Views\PaginationSelector.cshtml" if (interval.Min != 1) { #line default #line hidden WriteLiteral(" <li><a"); WriteLiteral(" data-page=\"1\""); WriteLiteral(" href=\"#\""); WriteLiteral(">1</a></li>\r\n"); #line 102 "..\..\Signum\Views\PaginationSelector.cshtml" if (interval.Min - 1 != 1) { #line default #line hidden WriteLiteral(" <li"); WriteLiteral(" class=\"disabled\""); WriteLiteral("><span>...</span></li>\r\n"); #line 105 "..\..\Signum\Views\PaginationSelector.cshtml" } } #line default #line hidden WriteLiteral("\r\n"); #line 108 "..\..\Signum\Views\PaginationSelector.cshtml" #line default #line hidden #line 108 "..\..\Signum\Views\PaginationSelector.cshtml" for (int i = interval.Min; i < paginate.CurrentPage; i++) { #line default #line hidden WriteLiteral(" <li><a"); WriteLiteral(" data-page=\""); #line 110 "..\..\Signum\Views\PaginationSelector.cshtml" Write(i); #line default #line hidden WriteLiteral("\""); WriteLiteral(" href=\"#\""); WriteLiteral(">"); #line 110 "..\..\Signum\Views\PaginationSelector.cshtml" Write(i); #line default #line hidden WriteLiteral("</a></li> \r\n"); #line 111 "..\..\Signum\Views\PaginationSelector.cshtml" } #line default #line hidden WriteLiteral("\r\n <li"); WriteLiteral(" class=\"active\""); WriteLiteral("><span>"); #line 113 "..\..\Signum\Views\PaginationSelector.cshtml" Write(paginate.CurrentPage.ToString()); #line default #line hidden WriteLiteral("</span></li>\r\n\r\n"); #line 115 "..\..\Signum\Views\PaginationSelector.cshtml" #line default #line hidden #line 115 "..\..\Signum\Views\PaginationSelector.cshtml" for (int i = paginate.CurrentPage + 1; i <= interval.Max; i++) { #line default #line hidden WriteLiteral(" <li><a"); WriteLiteral(" data-page=\""); #line 117 "..\..\Signum\Views\PaginationSelector.cshtml" Write(i); #line default #line hidden WriteLiteral("\""); WriteLiteral(" href=\"#\""); WriteLiteral(">"); #line 117 "..\..\Signum\Views\PaginationSelector.cshtml" Write(i); #line default #line hidden WriteLiteral("</a></li> \r\n"); #line 118 "..\..\Signum\Views\PaginationSelector.cshtml" } #line default #line hidden WriteLiteral("\r\n"); #line 120 "..\..\Signum\Views\PaginationSelector.cshtml" #line default #line hidden #line 120 "..\..\Signum\Views\PaginationSelector.cshtml" if (interval.Max != resultTable.TotalPages) { if (interval.Max + 1 != resultTable.TotalPages) { #line default #line hidden WriteLiteral(" <li"); WriteLiteral(" class=\"disabled\""); WriteLiteral("><span>...</span></li> \r\n"); #line 125 "..\..\Signum\Views\PaginationSelector.cshtml" } #line default #line hidden WriteLiteral(" <li><a"); WriteLiteral(" data-page=\""); #line 126 "..\..\Signum\Views\PaginationSelector.cshtml" Write(resultTable.TotalPages); #line default #line hidden WriteLiteral("\""); WriteLiteral(" href=\"#\""); WriteLiteral(">"); #line 126 "..\..\Signum\Views\PaginationSelector.cshtml" Write(resultTable.TotalPages); #line default #line hidden WriteLiteral("</a></li> \r\n"); #line 127 "..\..\Signum\Views\PaginationSelector.cshtml" } #line default #line hidden WriteLiteral("\r\n <li"); WriteAttribute("class", Tuple.Create(" class=\"", 5850), Tuple.Create("\"", 5927) #line 129 "..\..\Signum\Views\PaginationSelector.cshtml" , Tuple.Create(Tuple.Create("", 5858), Tuple.Create <System.Object, System.Int32>(resultTable.TotalPages <= paginate.CurrentPage ? "disabled" : null #line default #line hidden , 5858), false) ); WriteLiteral("><a"); WriteLiteral(" class=\"sf-pagination-button\""); WriteLiteral(" data-page=\""); #line 129 "..\..\Signum\Views\PaginationSelector.cshtml" Write(paginate.CurrentPage + 1); #line default #line hidden WriteLiteral("\""); WriteLiteral(" href=\"#\""); WriteLiteral(">»</a></li>\r\n </ul>\r\n"); #line 131 "..\..\Signum\Views\PaginationSelector.cshtml" } #line default #line hidden WriteLiteral(" </div>\r\n</div>\r\n"); }
public void UpdateElevation(MinMax elevationMinMax) { // Send information to the shader, under name "_elevationMinMax" settings.planetMaterial.SetVector("_elevationMinMax", new Vector4(elevationMinMax.Min, elevationMinMax.Max)); }
public static AudioSource PlayOneShot(AudioClip audioClip, Vector3 position, float volume, MinMax pitchvariationInterval, float spatialBlend = 0f) { Vector3 spawnPosition = Instance.is2DAudio ? ListenerRelativePosition(position) : position; AudioSource audioSource = SpawnAudioSource(spawnPosition, GetClipLength(audioClip)); audioSource.gameObject.name = "AudioSource(" + audioClip.name + ")"; audioSource.volume = volume * Instance.volumeMultiplier; audioSource.spatialBlend = spatialBlend; float pitchVariation = Random.Range(pitchvariationInterval.min, pitchvariationInterval.max); audioSource.pitch = pitchVariation; audioSource.PlayOneShot(audioClip); return(audioSource); }
/// <summary> /// Resets min max values from some other instance. /// </summary> /// <param name="other">Instance from which to reset.</param> public void Reset(MinMax other) { _min = other.Min; _max = other.Max; }
/// <summary> /// Reads the event data from the underlying stream. /// </summary> /// <param name="reader">The reader.</param> public override void Read(BinaryReader reader) { base.Read(reader); Scale = new MinMax<Vector2>(reader.ReadVector2(), reader.ReadVector2()); }
ChangedTile Change(int x, int y) { ChangedTile tile; if (! changedTiles.TryGetValue ((x << 16) | y, out tile)) { tile = new ChangedTile (x, y); changedTiles[(x << 16) | y] = tile; } if (x < left) left = x; if (x > right) right = x; if (y < top) top = y; if (y > bottom) bottom = y; MinMax row; if (! changedRows.TryGetValue (y, out row)) { changedRows[y] = new MinMax { Min = x, Max = x }; } else { changedRows[y] = new MinMax { Min = Math.Min(x, row.Min), Max = Math.Max (x, row.Max) }; } if (lastX != x || lastY != y) { Logging.ProgramLog.Debug.Log ("changed"); lastX = x; lastY = y; } return tile; }
private float MinMaxTongThuocTinhThietBi <T>(DanhSachMayTinh danhSachMayTinh, MayTinh.Tinh tinh, MinMax minMax) { switch (minMax) { case MinMax.Min: return(danhSachMayTinh.listMayTinh.Min(x => x.TinhTongThuocTinh <T>(tinh))); case MinMax.Max: return(danhSachMayTinh.listMayTinh.Max(x => x.TinhTongThuocTinh <T>(tinh))); } return(0); }
/// <summary> /// This is the method layout parent uses to set a location of the child /// relative to parent's visual as a result of layout. Typically, this is called /// by the parent inside of its ArrangeOverride implementation after calling Arrange on a child. /// Note that this method resets layout tarnsform set by <see cref="InternalSetLayoutTransform"/> method, /// so only one of these two should be used by the parent. /// </summary> private void SetLayoutOffset(Vector offset, Size oldRenderSize) { // // Attempt to avoid changing the transform more often than needed, // such as when a parent is arrange dirty but its children aren't. // // The dependencies for VisualTransform are as follows: // Mirror // RenderSize.Width // FlowDirection // parent.FlowDirection // RenderTransform // RenderTransformOrigin // LayoutTransform // RenderSize // Width, MinWidth, MaxWidth // Height, MinHeight, MaxHeight // // The AreTransformsClean flag will be false (dirty) when FlowDirection, // RenderTransform, LayoutTransform, Min/Max/Width/Height, or // RenderTransformOrigin changes. // // RenderSize is compared here with the previous size to see if it changed. // if (!AreTransformsClean || !DoubleUtil.AreClose(RenderSize, oldRenderSize)) { Transform additionalTransform = GetFlowDirectionTransform(); //rtl Transform renderTransform = this.RenderTransform; if(renderTransform == Transform.Identity) renderTransform = null; LayoutTransformData ltd = LayoutTransformDataField.GetValue(this); TransformGroup t = null; //arbitrary transform, create a collection if (additionalTransform != null || renderTransform != null || ltd != null) { // Create a TransformGroup and make sure it does not participate // in the InheritanceContext treeness because it is internal operation only. t = new TransformGroup(); t.CanBeInheritanceContext = false; t.Children.CanBeInheritanceContext = false; if (additionalTransform != null) t.Children.Add(additionalTransform); if(ltd != null) { t.Children.Add(ltd.Transform); // see if MaxWidth/MaxHeight limit the element MinMax mm = new MinMax(this); //this is in element's local rendering coord system Size inkSize = this.RenderSize; double maxWidthClip = (Double.IsPositiveInfinity(mm.maxWidth) ? inkSize.Width : mm.maxWidth); double maxHeightClip = (Double.IsPositiveInfinity(mm.maxHeight) ? inkSize.Height : mm.maxHeight); //get the size clipped by the MaxWidth/MaxHeight/Width/Height inkSize.Width = Math.Min(inkSize.Width, mm.maxWidth); inkSize.Height = Math.Min(inkSize.Height, mm.maxHeight); Rect inkRectTransformed = Rect.Transform(new Rect(inkSize), ltd.Transform.Value); t.Children.Add(new TranslateTransform(-inkRectTransformed.X, -inkRectTransformed.Y)); } if (renderTransform != null) { Point origin = GetRenderTransformOrigin(); bool hasOrigin = (origin.X != 0d || origin.Y != 0d); if (hasOrigin) { TranslateTransform backOrigin = new TranslateTransform(-origin.X, -origin.Y); backOrigin.Freeze(); t.Children.Add(backOrigin); } //can not freeze render transform - it can be animated t.Children.Add(renderTransform); if (hasOrigin) { TranslateTransform forwardOrigin = new TranslateTransform(origin.X, origin.Y); forwardOrigin.Freeze(); t.Children.Add(forwardOrigin); } } } this.VisualTransform = t; AreTransformsClean = true; } Vector oldOffset = this.VisualOffset; if(!DoubleUtil.AreClose(oldOffset.X, offset.X) || !DoubleUtil.AreClose(oldOffset.Y, offset.Y)) { this.VisualOffset = offset; } }
public List <MayTinh> DanhSachMayTinhMinMaxTheoThuocTinh <T>(DanhSachMayTinh danhSachMayTinh, MayTinh.Tinh tinh, MinMax minMax) => danhSachMayTinh.listMayTinh.Where(x => x.TinhTongThuocTinh <T>(tinh) == MinMaxTongThuocTinhThietBi <T>(danhSachMayTinh, tinh, minMax)).ToList();
public void GenerateNewMesh() { if (Density == 0.0f) { throw new System.Exception("Density is " + Density + " cannot create mesh"); } // create mesh PointMesh = new Mesh(); PointMesh.name = this.name; Debug.Log("parsing " + Filename); var Lines = System.IO.File.ReadAllLines(Filename); var Positions = new List <Vector3> (); var Normals = new List <Vector3> (); var Colours = new List <Color> (); bool BoundsInitialised = false; Bounds MinMax = new Bounds(); // generate indicies int VertexesPerTriangle = (GenerateAsPoints ? 1 : 3); // decode points { var Pos3 = new Vector3(); var Colour3 = new Color(); var Space = new char[] { ' ' }; foreach (string Line in Lines) { try { var Floats = Line.Split(Space); Pos3.x = FastParse.Float(Floats [0]); Pos3.y = FastParse.Float(Floats [1]); Pos3.z = FastParse.Float(Floats [2]); Colour3.r = FastParse.Float(Floats [3]) / 256.0f; Colour3.g = FastParse.Float(Floats [4]) / 256.0f; Colour3.b = FastParse.Float(Floats [5]) / 256.0f; if (!BoundsInitialised) { MinMax = new Bounds(Pos3, Vector3.zero); BoundsInitialised = true; } MinMax.Encapsulate(Pos3); if (GenerateAsPoints) { Positions.Add(Pos3); Colours.Add(Colour3); Normals.Add(new Vector3(1, 0, 0)); } else { Positions.Add(Pos3); Colours.Add(Colour3); Normals.Add(new Vector3(1, 0, 0)); Positions.Add(Pos3); Colours.Add(Colour3); Normals.Add(new Vector3(0, 1, 0)); Positions.Add(Pos3); Colours.Add(Colour3); Normals.Add(new Vector3(0, 0, 1)); } } catch (System.Exception e) { Debug.LogWarning("Exception with line: " + Line + ": " + e.Message); } } } // never added any verts if (!BoundsInitialised) { throw new System.Exception("Failed to parse any points"); } // center verts if (CenterMesh) { var BoundsCenter = MinMax.center; for (int i = 0; i < Positions.Count; i++) { Positions [i] -= BoundsCenter; } MinMax.min -= BoundsCenter; MinMax.max -= BoundsCenter; if (MoveSelf) { this.transform.localPosition = BoundsCenter; } } // crop for density if (Density < 1) { var OldCount = Positions.Count; var Step = 1.0f / (1.0f - Density); if (Step <= 1.0f) { throw new System.Exception("Step is too low " + Step); } if (GenerateAsPoints) { for (float i = Positions.Count - 1; i >= 0; i -= Step) { Positions.RemoveAt((int)i); Normals.RemoveAt((int)i); Colours.RemoveAt((int)i); } } else { int TriangleCount = Positions.Count / 3; for (float i = TriangleCount - 1; i >= 0; i -= Step) { var ti = (int)i * 3; Positions.RemoveRange(ti, 3); Normals.RemoveRange(ti, 3); Colours.RemoveRange(ti, 3); } } var NewDensity = Positions.Count / (float)OldCount; Debug.Log("Reduced points from " + OldCount + " to " + Positions.Count + "(" + (Density * 100) + "% requested, produced " + (NewDensity * 100) + "%)"); } // cap to the unity limit var VertexLimit = 65535 - (GenerateAsPoints ? 1 : 3); if (Positions.Count >= VertexLimit) { var Dropped = Positions.Count - VertexLimit; Debug.LogWarning("capped point cloud to vertex limit of " + VertexLimit + " from " + Positions.Count + ". " + Dropped + " dropped"); Positions.RemoveRange(VertexLimit, Dropped); Normals.RemoveRange(VertexLimit, Dropped); Colours.RemoveRange(VertexLimit, Dropped); } // generate indicies var Indexes = new int[Positions.Count]; for (int i = 0; i < Indexes.Length; i++) { Indexes [i] = i; } PointMesh.SetVertices(Positions); PointMesh.SetNormals(Normals); PointMesh.SetColors(Colours); PointMesh.SetIndices(Indexes, GenerateAsPoints ? MeshTopology.Points : MeshTopology.Triangles, 0); PointMesh.bounds = MinMax; var mf = this.GetComponent <MeshFilter> (); mf.mesh = PointMesh; var mr = this.GetComponent <MeshRenderer> (); var mat = ModifySharedMaterial ? mr.sharedMaterial : mr.material; if (GenerateAsPoints) { mat.EnableKeyword(PointGeometryShaderFeature); } else { mat.DisableKeyword(PointGeometryShaderFeature); } if (UseVertexTriangulation) { mat.EnableKeyword(VertexTriangulationShaderFeature); } else { mat.DisableKeyword(VertexTriangulationShaderFeature); } var bc = this.GetComponent <BoxCollider> (); if (bc != null) { bc.enabled = false; bc.enabled = true; } }
public void FitBoundsToView(ref double MinX, ref double MinY, ref double MaxX, ref double MaxY) { double Aspect = (double)BitmapCanvas.Height / (double)BitmapCanvas.Width; MinMax.SetMinMax(ref MinX, ref MaxX); MinMax.SetMinMax(ref MinY, ref MaxY); // We restrict the maximum zoom extent (ie width/height across view) to +-20,000,000 Meters if ((MaxX - MinX) > MaxViewDimensionMeters) { MinX = ((MaxX + MinX) / 2) - (MaxViewDimensionMeters / 2); MaxX = MinX + MaxViewDimensionMeters; } if ((MaxY - MinY) > MaxViewDimensionMeters) { MinY = ((MaxY + MinY) / 2) - (MaxViewDimensionMeters / 2); MaxY = MinY + MaxViewDimensionMeters; } // We restrict the minimum zoom extent (ie width/height across view) to +0.001 Meters if ((MaxX - MinX) < MinViewDimensionMeters) { MinX = ((MaxX + MinX) / 2) - (MinViewDimensionMeters / 2); MaxX = MinX + MinViewDimensionMeters; } if ((MaxY - MinY) < MinViewDimensionMeters) { MinY = ((MaxY + MinY) / 2) - (MinViewDimensionMeters / 2); MaxY = MinY + MinViewDimensionMeters; } if (!SquareAspect) // Do nothing, we will stretch it to the view... { return; } double wX = (MaxX - MinX); double wY = (MaxY - MinY); double cX = (MaxX + MinX) / 2; double cY = (MaxY + MinY) / 2; try { if (wY / wX > Aspect) // its skinner & taller..., ie: height is OK, width needs to change { MinX = cX - (wY / Aspect) / 2; MaxX = cX + (wY / Aspect) / 2; } else // its fatter & shorter..., ie: width is OK, height needs to change { MinY = cY - (wX * Aspect) / 2; MaxY = cY + (wX * Aspect) / 2; } } catch { // Ooops, we were fed some bad numbers, possibly resulting in a div by zero. // Leave the extents alone... } }
/// <summary> /// Reads the event data from the underlying stream. /// </summary> /// <param name="reader">The reader.</param> public virtual void Read(BinaryReader reader) { TimeRange = new MinMax<float>(reader.ReadSingle(), reader.ReadSingle()); Fade = reader.ReadBoolean(); }
/// <summary> /// Initializes a new instance of the <see cref="TimePeriod"/> struct. /// </summary> /// <param name="start">The start.</param> /// <param name="end">The end.</param> public TimePeriod(TimeSpan start, TimeSpan end) { _period = new MinMax<TimeSpan>(start, end); }
public WanderAIComponentData(bool inAlignWithForwardDirection, float inRotationSpeed, MinMax corners, AttackMovingType battleMovingType, bool useHitProbForAgro = false) : base(inAlignWithForwardDirection, inRotationSpeed, useHitProbForAgro) { this.corners = corners; this.battleMovingType = battleMovingType; }
/// <summary> /// Reads the event data from the underlying stream. /// </summary> /// <param name="reader">The reader.</param> public override void Read(BinaryReader reader) { base.Read(reader); Velocity = new MinMax <Vector3>(reader.ReadVector3(), reader.ReadVector3()); }
private static Centroid GenerateRandomCentroidWithinRange(MinMax[] ranges) { Centroid centroid = new Centroid(); Random rand = new Random(DateTime.Now.Millisecond); for (int i = 0; i < ImageInfo.PropertiesCount; ++i) { MinMax minMax = ranges[i]; centroid.PropertyValues[i] = rand.NextDouble() * (minMax.Max - minMax.Min) + minMax.Min; } return centroid; }
public async Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> events) { try { var now = DateTime.UtcNow; foreach (var eventData in events) { // We don't care about messages that are older than bufferTimeInterval if ((eventData.EnqueuedTimeUtc + bufferTimeInterval) >= now) { // Get message from the eventData body and convert JSON string into message object string eventBodyAsString = Encoding.UTF8.GetString(eventData.GetBytes()); // There can be several messages in one IList <IDictionary <string, object> > messagePayloads; try { // Attempt to deserialze event body as single JSON message messagePayloads = new List <IDictionary <string, object> > { JsonConvert.DeserializeObject <IDictionary <string, object> >(eventBodyAsString) }; } catch { // Not a single JSON message: attempt to deserialize as array of messages // Azure Stream Analytics Preview generates invalid JSON for some multi-values queries // Workaround: turn concatenated json objects (ivalid JSON) into array of json objects (valid JSON) if (eventBodyAsString.IndexOf("}{") >= 0) { eventBodyAsString = eventBodyAsString.Replace("}{", "},{"); } if (!eventBodyAsString.EndsWith("]")) { eventBodyAsString = eventBodyAsString + "]"; } if (!eventBodyAsString.StartsWith("[")) { eventBodyAsString = "[" + eventBodyAsString.Substring(eventBodyAsString.IndexOf("{")); } messagePayloads = JsonConvert.DeserializeObject <IList <IDictionary <string, object> > >(eventBodyAsString); } var rnd = new Random(); foreach (var messagePayload in messagePayloads) { // Read time value if (messagePayload.ContainsKey("timecreated")) { messagePayload["time"] = messagePayload["timecreated"]; } if (messagePayload.ContainsKey("timearrived")) { messagePayload["time"] = messagePayload["timearrived"]; } // process an alert if (messagePayload.ContainsKey("alerttype") && messagePayload.ContainsKey("timecreated")) { Debug.Print("Alert message received!"); DateTime time = DateTime.Parse(messagePayload["timecreated"].ToString()); // find the nearest point lock (sortedDataBuffer) { int idx = SearchHelper.FindFirstIndexGreaterThanOrEqualTo(sortedDataBuffer, time); bool found = false; string alertType = messagePayload["alerttype"] as string; if (idx >= sortedDataBuffer.Values.Count) { idx = sortedDataBuffer.Values.Count - 1; } while (idx >= 0) { List <IDictionary <string, object> > dictList = sortedDataBuffer.Values[idx]; foreach (IDictionary <string, object> dict in dictList) { if ( (dict.ContainsKey("guid") && messagePayload.ContainsKey("guid") && messagePayload["guid"].ToString() == dict["guid"].ToString()) && (dict.ContainsKey("measurename") && messagePayload.ContainsKey("measurename") && messagePayload["measurename"].ToString() == dict["measurename"].ToString()) && (!messagePayload.ContainsKey("displayname") || dict.ContainsKey("displayname") && messagePayload["measurename"].ToString() == dict["measurename"].ToString()) ) { // fill anomaly message if (!messagePayload.ContainsKey("value")) { messagePayload["value"] = dict["value"]; } if (!messagePayload.ContainsKey("displayname") && dict.ContainsKey("displayname")) { messagePayload["displayname"] = dict["displayname"]; } if (!messagePayload.ContainsKey("time")) { messagePayload["time"] = messagePayload["timecreated"]; } found = true; break; } } if (found) { break; } idx--; } } } if (messagePayload.ContainsKey("guid")) { var guid = messagePayload["guid"].ToString(); double val = Convert.ToDouble(messagePayload["value"]); if (!MinMaxValue.ContainsKey(guid)) { MinMaxValue.Add(guid, new MinMax { min = val, max = val }); } MinMax tmp = MinMaxValue[messagePayload["guid"].ToString()]; if (tmp.min > val) { tmp.min = val; } if (tmp.max < val) { tmp.max = val; } } // We want to read the time value from the message itself. // If none is found we will use the enqueued time DateTime messageTimeStamp = new DateTime(); if (messagePayload.ContainsKey("time")) { messageTimeStamp = DateTime.Parse(messagePayload["time"].ToString()); //data.Timestamp = messagePayload["time"].ToString(); //if (GenerateAnomalies && rnd.Next(100) >= 95) //{ // messagePayload.Add("alerttype", "testType"); // messagePayload.Add("dsplalert", "testAlert"); // messagePayload.Add("message", "Anomaly detected by Azure ML model."); // messagePayload.Add("timestart", messagePayload["time"]); // // correct value // if (rnd.Next(2) == 1) // messagePayload["value"] = MinMaxValue[messagePayload["guid"].ToString()].max * (1.01 + 0.05 * rnd.Next(100) / 100); // else // messagePayload["value"] = MinMaxValue[messagePayload["guid"].ToString()].min * (0.99 - 0.05 * rnd.Next(100) / 100); //} } else if (messagePayload.ContainsKey("timestart")) { messageTimeStamp = DateTime.Parse(messagePayload["timestart"].ToString()); } else { messageTimeStamp = eventData.EnqueuedTimeUtc; } // Build up the list of devices seen so far (in lieu of a formal device repository) // Also keep the last message received per device (not currently used in the sample) if (messagePayload.ContainsKey("guid") && !messagePayload.ContainsKey("valueAvg")) { string guid = messagePayload["guid"].ToString(); if (guid != null) { WebSocketEventProcessor.g_devices.TryAdd(guid, messagePayload); } } if (messagePayload["measurename"].ToString().ToLower().Equals("temperature")) { if (!String.IsNullOrEmpty(messagePayload["value"].ToString())) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse("Storage Connection String"); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table = tableClient.GetTableReference("Table Storage Name"); // Create a new customer entity. DeloreanData data = new DeloreanData("Table Storage Primary Key", ""); if (messagePayload.ContainsKey("measurename")) { data.measurename = messagePayload["measurename"].ToString(); } if (messagePayload.ContainsKey("value")) { data.value = messagePayload["value"].ToString(); } if (messagePayload.ContainsKey("unitofmeasure")) { data.unitofmeasure = messagePayload["unitofmeasure"].ToString(); } if (messagePayload.ContainsKey("displayname")) { data.displayname = messagePayload["displayname"].ToString(); } if (messagePayload.ContainsKey("organization")) { data.organization = messagePayload["organization"].ToString(); } if (messagePayload.ContainsKey("location")) { data.location = messagePayload["location"].ToString(); } data.RowKey = DateTime.Parse(messagePayload["timecreated"].ToString()).Ticks.ToString() + "-" + data.measurename; TableOperation insertOperation = TableOperation.Insert(data); //var temperature = double.Parse(data.value); //if (temperature > 75) // { //NotificationHubClient hub = NotificationHubClient // .CreateClientFromConnectionString("Endpoint=sb://deloreantesthub-ns.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=wSpPlbYOksiifQGSa7qT1lXeWzxOKatCbHoGSqZOKfY=", "deloreantesthub"); //var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">Hello from a .NET App!</text></binding></visual></toast>"; //await hub.SendWindowsNativeNotificationAsync(toast); table.Execute(insertOperation); //} } } // Create the TableOperation that inserts the customer entity. //table.Execute(insertOperation); // Notify clients MyWebSocketHandler.SendToClients(messagePayload); // Buffer messages so we can resend them to clients that connect later // or when a client requests data for a different device // Lock to guard against concurrent reads from client resend lock (sortedDataBuffer) { if (!sortedDataBuffer.ContainsKey(messageTimeStamp)) { sortedDataBuffer.Add(messageTimeStamp, new List <IDictionary <string, object> >()); } sortedDataBuffer[messageTimeStamp].Add(messagePayload); } } } else { Debug.Print("Received old message timestamped:" + eventData.EnqueuedTimeUtc.ToString()); } } //Call checkpoint every minute if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(1)) { await context.CheckpointAsync(); lock (this) { this.checkpointStopWatch.Restart(); } // trim data buffer to keep only last 10 minutes of data lock (sortedDataBuffer) { DateTime oldDataPoint = now - bufferTimeInterval; // find the closest point int idx = SearchHelper.FindFirstIndexGreaterThanOrEqualTo(sortedDataBuffer, oldDataPoint); // trim while (idx > 0 && sortedDataBuffer.Count > 0 && sortedDataBuffer.Keys[0] <= oldDataPoint) { sortedDataBuffer.RemoveAt(0); } } } } catch (Exception e) { Trace.TraceError("Error processing events in EH {0}, partition {1}: {0}", context.EventHubPath, context.Lease.PartitionId, e.Message); } }
void initBounds() { enterPointZ[0] = new MinMax<float>(19.0F, 22.6F); // bottom enterPointZ[1] = new MinMax<float>(0.6F, 10.1F); // top side enterPointZ[2] = new MinMax<float>(0.3F, 1.1F); // top back enterPointX[0] = new MinMax<float>(-4.3F, -5.1F); // left side enterPointX[1] = new MinMax<float>(34.5F, 35.1F); // right side enterPointX[2] = new MinMax<float>(0.9F, 14.3F); // left back enterPointX[3] = new MinMax<float>(15.8F, 24.5F); // right back }
/// <summary> /// Calculate the BB based on Investopedia's formula. /// </summary> /// <remarks> /// @see [Bollinger Band Definition](https://www.investopedia.com/terms/b/bollingerbands.asp) /// </remarks> /// <param name="data">Specifies the BB data from the previous cycle.</param> /// <param name="i">Specifies the current data index.</param> /// <param name="minmax">Currently, not used here.</param> /// <param name="nLookahead">Specifies the look ahead value if any.</param> /// <param name="bAddToParams">Optionally, specifies whether or not to add the BB to the parameters of the original data.</param> /// <returns>The new BB values are returned.</returns> public Tuple <long, double, double, double, double, double> Process(BbData data, int i, MinMax minmax = null, int nLookahead = 0, bool bAddToParams = false) { bool bActive = data.SrcData[i].Active; Plot plot = new Plot(data.SrcData[i].X, new float[] { 0, 0, 0 }, null, false, data.SrcData[i].Index, data.SrcData[i].Action1Active, data.SrcData[i].Action2Active); data.DstData.Add(plot, false); float fTypicalValue = (data.SrcData[i].Y_values.Length == 4) ? (data.SrcData[i].Y_values[1] + data.SrcData[i].Y_values[2] + data.SrcData[i].Y_values[3]) / 3 : data.SrcData[i].Y; if (data.SrcData[i].Y_values.Length == 4 && m_target != TARGET.DEFAULT) { if (m_target == TARGET.BAR) { float fVal = (data.SrcData[i].Y_values[0] - data.SrcData[i].Y); m_caValExt.Add(fVal, null, true); } else if (m_target == TARGET.RANGE) { float fVal = (data.SrcData[i].Y_values[1] - data.SrcData[i].Y_values[2]); m_caValExt.Add(fVal, null, true); } } if (m_caVal.Add(fTypicalValue, null, false)) { data.Ave = (float)m_caVal.Average; float fStdevTp = (float)m_caVal.StdDev; if (m_target != TARGET.DEFAULT) { fStdevTp = (float)m_caValExt.StdDev; } double dfStdDvTp = (m_dfStdDev * fStdevTp); data.BbAbove = data.Ave + dfStdDvTp; data.BbBelow = data.Ave - dfStdDvTp; plot.SetYValues(new float[] { (float)data.BbBelow, (float)data.Ave, (float)data.BbAbove }, true); double dfAboveBelow = data.BbAbove - data.BbBelow; data.BbPctb = 0; if (dfAboveBelow != 0) { data.BbPctb = (data.SrcData[i].Y - data.BbBelow) / dfAboveBelow; } data.BbWid = 0; if (data.Ave != 0) { data.BbWid = dfAboveBelow / data.Ave; } if (bAddToParams && bActive) { data.SrcData[i].SetParameter(data.DstData.Name + " Below", data.BbBelow); data.SrcData[i].SetParameter(data.DstData.Name + " Ave", data.Ave); data.SrcData[i].SetParameter(data.DstData.Name + " Above", data.BbAbove); data.SrcData[i].SetParameter(data.DstData.Name + " %b", data.BbPctb); data.SrcData[i].SetParameter(data.DstData.Name + " BandWidth", data.BbWid); } if (minmax != null) { minmax.Add(data.BbBelow); minmax.Add(data.Ave); minmax.Add(data.BbAbove); } } data.Count++; return(new Tuple <long, double, double, double, double, double>((long)data.SrcData[i].X, data.BbBelow, data.Ave, data.BbAbove, data.BbPctb, data.BbWid)); }
/// <summary> /// Reads the event data from the underlying stream. /// </summary> /// <param name="reader">The reader.</param> public override void Read(BinaryReader reader) { base.Read(reader); Velocity = new MinMax<Vector3>(reader.ReadVector3(), reader.ReadVector3()); }
public void UpdateElevation(MinMax elevationMinMax) { // send minMax values to the shader colorSettings.planetMaterial.SetVector("_elevationMinMax", new Vector4(elevationMinMax.Min, elevationMinMax.Max)); }
/// <summary> /// Reads the event data from the underlying stream. /// </summary> /// <param name="reader">The reader.</param> public override void Read(BinaryReader reader) { base.Read(reader); Angle = new MinMax<float>(reader.ReadSingle(), reader.ReadSingle()); }
protected sealed override void ArrangeCore(Rect finalRect) { var arrangeSize = finalRect.Size; var margin = this.Margin; var marginWidth = margin.Left + margin.Right; var marginHeight = margin.Top + margin.Bottom; arrangeSize.Width = Math.Max(0, arrangeSize.Width - marginWidth); arrangeSize.Height = Math.Max(0, arrangeSize.Height - marginHeight); if (this._unclippedDesiredSize.IsEmpty) { return; } if (DoubleUtil.AreClose(arrangeSize.Width, this._unclippedDesiredSize.Width) || arrangeSize.Width < this._unclippedDesiredSize.Width) { //this.needClipBounds = true; arrangeSize.Width = this._unclippedDesiredSize.Width; } if (DoubleUtil.AreClose(arrangeSize.Height, this._unclippedDesiredSize.Height) || arrangeSize.Height < this._unclippedDesiredSize.Height) { //this.needClipBounds = true; arrangeSize.Height = this._unclippedDesiredSize.Height; } if (this.HorizontalAlignment != HorizontalAlignment.Stretch) { arrangeSize.Width = this._unclippedDesiredSize.Width; } if (this.VerticalAlignment != VerticalAlignment.Stretch) { arrangeSize.Height = this._unclippedDesiredSize.Height; } var mm = new MinMax(this); var effectiveMaxWidth = Math.Max(this._unclippedDesiredSize.Width, mm.maxWidth); if (DoubleUtil.AreClose(effectiveMaxWidth, arrangeSize.Width) || effectiveMaxWidth < arrangeSize.Width) { //this.needClipBounds = true; arrangeSize.Width = effectiveMaxWidth; } var effectiveMaxHeight = Math.Max(this._unclippedDesiredSize.Height, mm.maxHeight); if (DoubleUtil.AreClose(effectiveMaxHeight, arrangeSize.Height) || effectiveMaxHeight < arrangeSize.Height) { //this.needClipBounds = true; arrangeSize.Height = effectiveMaxHeight; } var oldRenderSize = this.RenderSize; var innerInkSize = this.ArrangeOverride(arrangeSize); if (innerInkSize.IsEmpty) { throw new InvalidOperationException("arrangeOverride() can't return null"); } this.RenderSize = innerInkSize; var clippedInkSize = new Size(Math.Min(innerInkSize.Width, mm.maxWidth), Math.Min(innerInkSize.Height, mm.maxHeight)); var clientSize = new Size(Math.Max(0, finalRect.Width - marginWidth), Math.Max(0, finalRect.Height - marginHeight)); var offset = this.ComputeAlignmentOffset(clientSize, clippedInkSize); offset.X += finalRect.X + margin.Left; offset.Y += finalRect.Y + margin.Top; var oldOffset = this._visualOffset; if (oldOffset.Equals(default(Vector)) || (!DoubleUtil.AreClose(oldOffset.X, offset.X) || !DoubleUtil.AreClose(oldOffset.Y, offset.Y)) ) { this._visualOffset = offset; } }
/// <summary> /// Override for <seealso cref="UIElement.MeasureCore" />. /// </summary> protected sealed override Size MeasureCore(Size availableSize) { Debug.Assert(MeasureData == null || availableSize == MeasureData.AvailableSize, "MeasureData needs to be passed down in [....] with size"); // If using layout rounding, check whether rounding needs to compensate for high DPI bool useLayoutRounding = this.UseLayoutRounding; if (useLayoutRounding) { if (!CheckFlagsAnd(VisualFlags.UseLayoutRounding)) { this.SetFlags(true, VisualFlags.UseLayoutRounding); } } //build the visual tree from styles first ApplyTemplate(); if (BypassLayoutPolicies) { return MeasureOverride(availableSize); } else { Thickness margin = Margin; double marginWidth = margin.Left + margin.Right; double marginHeight = margin.Top + margin.Bottom; MeasureData measureData = MeasureData; // parent size is what parent want us to be Size frameworkAvailableSize = new Size( Math.Max(availableSize.Width - marginWidth, 0), Math.Max(availableSize.Height - marginHeight, 0)); MinMax mm = new MinMax(this); LayoutTransformData ltd = LayoutTransformDataField.GetValue(this); { Transform layoutTransform = this.LayoutTransform; // check that LayoutTransform is non-trivial if (layoutTransform != null && !layoutTransform.IsIdentity) { if (ltd == null) { // allocate and store ltd if needed ltd = new LayoutTransformData(); LayoutTransformDataField.SetValue(this, ltd); } ltd.CreateTransformSnapshot(layoutTransform); ltd.UntransformedDS = new Size(); if (useLayoutRounding) { ltd.TransformedUnroundedDS = new Size(); } } else if (ltd != null) { // clear ltd storage ltd = null; LayoutTransformDataField.ClearValue(this); } } if (ltd != null) { // Find the maximal area rectangle in local (child) space that we can fit, post-transform // in the decorator's measure constraint. frameworkAvailableSize = FindMaximalAreaLocalSpaceRect(ltd.Transform, frameworkAvailableSize); } frameworkAvailableSize.Width = Math.Max(mm.minWidth, Math.Min(frameworkAvailableSize.Width, mm.maxWidth)); frameworkAvailableSize.Height = Math.Max(mm.minHeight, Math.Min(frameworkAvailableSize.Height, mm.maxHeight)); // If layout rounding is enabled, round available size passed to MeasureOverride. if (useLayoutRounding) { frameworkAvailableSize = UIElement.RoundLayoutSize(frameworkAvailableSize, FrameworkElement.DpiScaleX, FrameworkElement.DpiScaleY); } // call to specific layout to measure if (measureData != null) { measureData.AvailableSize = frameworkAvailableSize; } Size desiredSize = MeasureOverride(frameworkAvailableSize); if (measureData != null) { // MeasureData should be treated like a parameter to Measure and thus not modified when returning from this call. measureData.AvailableSize = availableSize; } // maximize desiredSize with user provided min size desiredSize = new Size( Math.Max(desiredSize.Width, mm.minWidth), Math.Max(desiredSize.Height, mm.minHeight)); //here is the "true minimum" desired size - the one that is //for sure enough for the control to render its content. Size unclippedDesiredSize = desiredSize; if (ltd != null) { //need to store unclipped, untransformed desired size to be able to arrange later ltd.UntransformedDS = unclippedDesiredSize; //transform unclipped desired size Rect unclippedBoundsTransformed = Rect.Transform(new Rect(0, 0, unclippedDesiredSize.Width, unclippedDesiredSize.Height), ltd.Transform.Value); unclippedDesiredSize.Width = unclippedBoundsTransformed.Width; unclippedDesiredSize.Height = unclippedBoundsTransformed.Height; } bool clipped = false; // User-specified max size starts to "clip" the control here. //Starting from this point desiredSize could be smaller then actually //needed to render the whole control if (desiredSize.Width > mm.maxWidth) { desiredSize.Width = mm.maxWidth; clipped = true; } if (desiredSize.Height > mm.maxHeight) { desiredSize.Height = mm.maxHeight; clipped = true; } //transform desired size to layout slot space if (ltd != null) { Rect childBoundsTransformed = Rect.Transform(new Rect(0, 0, desiredSize.Width, desiredSize.Height), ltd.Transform.Value); desiredSize.Width = childBoundsTransformed.Width; desiredSize.Height = childBoundsTransformed.Height; } // because of negative margins, clipped desired size may be negative. // need to keep it as doubles for that reason and maximize with 0 at the // very last point - before returning desired size to the parent. double clippedDesiredWidth = desiredSize.Width + marginWidth; double clippedDesiredHeight = desiredSize.Height + marginHeight; // In overconstrained scenario, parent wins and measured size of the child, // including any sizes set or computed, can not be larger then // available size. We will clip the guy later. if (clippedDesiredWidth > availableSize.Width) { clippedDesiredWidth = availableSize.Width; clipped = true; } if (clippedDesiredHeight > availableSize.Height) { clippedDesiredHeight = availableSize.Height; clipped = true; } // Set transformed, unrounded size on layout transform, if any. if (ltd != null) { ltd.TransformedUnroundedDS = new Size(Math.Max(0, clippedDesiredWidth), Math.Max(0, clippedDesiredHeight)); } // If using layout rounding, round desired size. if (useLayoutRounding) { clippedDesiredWidth = UIElement.RoundLayoutValue(clippedDesiredWidth, DpiScaleX); clippedDesiredHeight = UIElement.RoundLayoutValue(clippedDesiredHeight, DpiScaleY); } // Note: unclippedDesiredSize is needed in ArrangeCore, // because due to the layout protocol, arrange should be called // with constraints greater or equal to child's desired size // returned from MeasureOverride. But in most circumstances // it is possible to reconstruct original unclipped desired size. // In such cases we want to optimize space and save 16 bytes by // not storing it on each FrameworkElement. // // The if statement conditions below lists the cases when // it is NOT possible to recalculate unclipped desired size later // in ArrangeCore, thus we save it into Uncommon Fields... // // Note 2: use SizeBox to avoid CLR boxing of Size. // measurements show it is better to allocate an object once than // have spurious boxing allocations on every resize SizeBox sb = UnclippedDesiredSizeField.GetValue(this); if (clipped || clippedDesiredWidth < 0 || clippedDesiredHeight < 0) { if (sb == null) //not yet allocated, allocate the box { sb = new SizeBox(unclippedDesiredSize); UnclippedDesiredSizeField.SetValue(this, sb); } else //we already have allocated size box, simply change it { sb.Width = unclippedDesiredSize.Width; sb.Height = unclippedDesiredSize.Height; } } else { if (sb != null) UnclippedDesiredSizeField.ClearValue(this); } return new Size(Math.Max(0, clippedDesiredWidth), Math.Max(0, clippedDesiredHeight)); } }
/// <summary> /// This functiuon positions the base at the location 'intersect' /// The idir is the direction that was used to intersect /// </summary> /// <param name="intersect"></param> /// <param name="idir"></param> /// <param name="inorm"></param> public void PositionBottom(ISectData dat) { // the bottom could be a tip or base // need to orient the bottom and position it. Point3d center; // for a base support, just slide it around if (m_subtype == eSubType.eBase) { center = Centroid(); // get the centroid of the selected portion of the object MinMax mm = CalcMinMaxRange(s1i, s4i); float dist = (float)((mm.m_max - mm.m_min) / 2); Translate( (float)(dat.intersect.x - center.x), (float)(dat.intersect.y - center.y), (float)(dat.intersect.z - center.z + dist)); } else if (m_subtype == eSubType.eIntra) // bottom tip { // for a base tip, find the angle and angle it in Vector3d isectnorm = new Vector3d(); //save the polygon intersection normal isectnorm.x = dat.poly.m_normal.x; isectnorm.y = dat.poly.m_normal.y; isectnorm.z = dat.poly.m_normal.z; isectnorm.Normalize(); if (isectnorm.z < 0) { isectnorm.z *= -1.0f; } // limit the z down to 45 degrees if (isectnorm.z < .75) { isectnorm.z = .75f; } // re-genrate the points on the bottom of the foot ReGenSegmentPoints(mSC.htrad, mSC.cdivs, s1i, 0, true); // bottom of foot is the tip radius Matrix3D tMat = new Matrix3D(); Vector3d vup = new Vector3d(0, 1, 0); Vector3d dir = new Vector3d(isectnorm.x, isectnorm.y, isectnorm.z); dir.Normalize(); //direction should be upward at this point. //create a matrix transform tMat.LookAt(dir, vup); //transform the si1-s2i points to look at the vector TransformRange(tMat, s1i, s2i); //move the range of points to be touching the intersection point STranslateRange(dat.intersect.x, dat.intersect.y, dat.intersect.z, s1i, s2i); //now, get the center of s4i to s5i Point3d cnt = CalcCentroid(s2i, s4i); //translate to 0,0,0 STranslateRange(-cnt.x, -cnt.y, -cnt.z, s2i, s4i); //reset the points, ReGenSegmentPoints(mSC.hbrad, mSC.cdivs, s2i, 0, false); // top of foot ReGenSegmentPoints(mSC.hbrad, mSC.cdivs, s3i, 0, false); // top of foot Point3d newp = new Point3d(); newp.x = dat.intersect.x + (isectnorm.x * 2); newp.y = dat.intersect.y + (isectnorm.y * 2); newp.z = dat.intersect.z + (isectnorm.z * 2); STranslateRange(newp.x, newp.y, newp.z, s2i, s4i); Update(); } //Update(); }
/// <summary> /// Override of <seealso cref="UIElement.GetLayoutClip"/>. /// </summary> /// <returns>Geometry to use as additional clip in case when element is larger then available space</returns> protected override Geometry GetLayoutClip(Size layoutSlotSize) { bool useLayoutRounding = this.UseLayoutRounding; if (useLayoutRounding) { if (!CheckFlagsAnd(VisualFlags.UseLayoutRounding)) { SetFlags(true, VisualFlags.UseLayoutRounding); } } if (NeedsClipBounds || ClipToBounds) { // see if MaxWidth/MaxHeight limit the element MinMax mm = new MinMax(this); //this is in element's local rendering coord system Size inkSize = this.RenderSize; double maxWidthClip = (Double.IsPositiveInfinity(mm.maxWidth) ? inkSize.Width : mm.maxWidth); double maxHeightClip = (Double.IsPositiveInfinity(mm.maxHeight) ? inkSize.Height : mm.maxHeight); //need to clip because the computed sizes exceed MaxWidth/MaxHeight/Width/Height bool needToClipLocally = ClipToBounds //need to clip at bounds even if inkSize is less then maxSize || (DoubleUtil.LessThan(maxWidthClip, inkSize.Width) || DoubleUtil.LessThan(maxHeightClip, inkSize.Height)); //now lets say we already clipped by MaxWidth/MaxHeight, lets see if further clipping is needed inkSize.Width = Math.Min(inkSize.Width, mm.maxWidth); inkSize.Height = Math.Min(inkSize.Height, mm.maxHeight); //if LayoutTransform is set, convert RenderSize to "outer bounds" LayoutTransformData ltd = LayoutTransformDataField.GetValue(this); Rect inkRectTransformed = new Rect(); if (ltd != null) { inkRectTransformed = Rect.Transform(new Rect(0, 0, inkSize.Width, inkSize.Height), ltd.Transform.Value); inkSize.Width = inkRectTransformed.Width; inkSize.Height = inkRectTransformed.Height; } //now see if layout slot should clip the element Thickness margin = Margin; double marginWidth = margin.Left + margin.Right; double marginHeight = margin.Top + margin.Bottom; Size clippingSize = new Size(Math.Max(0, layoutSlotSize.Width - marginWidth), Math.Max(0, layoutSlotSize.Height - marginHeight)); bool needToClipSlot = ( ClipToBounds //forces clip at layout slot bounds even if reported sizes are ok || DoubleUtil.LessThan(clippingSize.Width, inkSize.Width) || DoubleUtil.LessThan(clippingSize.Height, inkSize.Height)); Transform rtlMirror = GetFlowDirectionTransform(); if (needToClipLocally && !needToClipSlot) { Rect clipRect = new Rect(0, 0, maxWidthClip, maxHeightClip); if (useLayoutRounding) { clipRect = UIElement.RoundLayoutRect(clipRect, DpiScaleX, DpiScaleY); } RectangleGeometry localClip = new RectangleGeometry(clipRect); if (rtlMirror != null) localClip.Transform = rtlMirror; return localClip; } if (needToClipSlot) { Vector offset = ComputeAlignmentOffset(clippingSize, inkSize); if (ltd != null) { Rect slotClipRect = new Rect(-offset.X + inkRectTransformed.X, -offset.Y + inkRectTransformed.Y, clippingSize.Width, clippingSize.Height); if (useLayoutRounding) { slotClipRect = UIElement.RoundLayoutRect(slotClipRect, DpiScaleX, DpiScaleY); } RectangleGeometry slotClip = new RectangleGeometry(slotClipRect); Matrix m = ltd.Transform.Value; if (m.HasInverse) { m.Invert(); slotClip.Transform = new MatrixTransform(m); } if (needToClipLocally) { Rect localClipRect = new Rect(0, 0, maxWidthClip, maxHeightClip); if (useLayoutRounding) { localClipRect = UIElement.RoundLayoutRect(localClipRect, DpiScaleX, DpiScaleY); } RectangleGeometry localClip = new RectangleGeometry(localClipRect); PathGeometry combinedClip = Geometry.Combine(localClip, slotClip, GeometryCombineMode.Intersect, null); if (rtlMirror != null) combinedClip.Transform = rtlMirror; return combinedClip; } else { if (rtlMirror != null) { if (slotClip.Transform != null) slotClip.Transform = new MatrixTransform(slotClip.Transform.Value * rtlMirror.Value); else slotClip.Transform = rtlMirror; } return slotClip; } } else //no layout transform, intersect axis-aligned rects { Rect slotRect = new Rect(-offset.X + inkRectTransformed.X, -offset.Y + inkRectTransformed.Y, clippingSize.Width, clippingSize.Height); if (useLayoutRounding) { slotRect = UIElement.RoundLayoutRect(slotRect, DpiScaleX, DpiScaleY); } if (needToClipLocally) //intersect 2 rects { Rect localRect = new Rect(0, 0, maxWidthClip, maxHeightClip); if (useLayoutRounding) { localRect = UIElement.RoundLayoutRect(localRect, DpiScaleX, DpiScaleY); } slotRect.Intersect(localRect); } RectangleGeometry combinedClip = new RectangleGeometry(slotRect); if (rtlMirror != null) combinedClip.Transform = rtlMirror; return combinedClip; } } return null; } return base.GetLayoutClip(layoutSlotSize); }
public void UpdateElevation(MinMax elevationMinMax) { _renderer.material.SetVector("_elevationMinMax", new Vector4(elevationMinMax.Min, elevationMinMax.Max)); }
private void initLaneBounds() { laneBounds[0] = new MinMax<float>(-7.5F, 11.3F); laneBounds[1] = new MinMax<float>(-9.0F, 13.0F); laneBounds[2] = new MinMax<float>(-10.6F, 14.6F); laneBounds[3] = new MinMax<float>(-12.1F, 16.3F); laneBounds[4] = new MinMax<float>(-13.7F, 17.9F); }
public void UpdateElevation(MinMax elevationMinMax) { settings.planetMaterial.SetVector("_elevationMinMax", new Vector4(elevationMinMax.Min, elevationMinMax.Max)); }
/// <summary> /// Reads the event data from the underlying stream. /// </summary> /// <param name="reader">The reader.</param> public override void Read(BinaryReader reader) { base.Read(reader); Colour = new MinMax<Color>(reader.ReadColour4(), reader.ReadColour4()); }
/// <summary> /// Defines the template for core-level arrange layout definition. /// </summary> /// <remarks> /// In WPF this method is defined on UIElement as protected virtual and has a base implementation. /// FrameworkElement (which derrives from UIElement) creates a sealed implemention, similar to the below, /// which discards UIElement's base implementation. /// </remarks> /// <param name = "finalRect">The final area within the parent that element should use to arrange itself and its child elements.</param> private void ArrangeCore(BoundingRectangle finalRect) { Thickness margin = this.Margin; Vector2 unclippedDesiredSize = isClippingRequired ? unclippedSize : DesiredSize.Deflate(margin); Vector2 finalSize = new Vector2(finalRect.Width, finalRect.Height); finalSize = finalSize.Deflate(margin); isClippingRequired = false; if (finalSize.X < unclippedDesiredSize.X) { isClippingRequired = true; finalSize.X = unclippedDesiredSize.X; } if (finalSize.Y < unclippedDesiredSize.Y) { isClippingRequired = true; finalSize.Y = unclippedDesiredSize.Y; } if (HorizontalAlignment != HorizontalAlignment.Stretch) { finalSize.X = unclippedDesiredSize.X; } if (VerticalAlignment != VerticalAlignment.Stretch) { finalSize.Y = unclippedDesiredSize.Y; } var minMax = new MinMax(this); float largestWidth = Math.Max(unclippedDesiredSize.X, minMax.MaxWidth); if (largestWidth < finalSize.X) { finalSize.X = largestWidth; } float largestHeight = Math.Max(unclippedDesiredSize.Y, minMax.MaxHeight); if (largestHeight < finalSize.Y) { finalSize.Y = largestHeight; } Vector2 renderSize = this.ArrangeOverride(finalSize); this.RenderSize = renderSize; Vector2 inkSize = new Vector2( Math.Min(renderSize.X, minMax.MaxWidth), Math.Min(renderSize.Y, minMax.MaxHeight)); isClippingRequired |= inkSize.X < renderSize.X || inkSize.Y < renderSize.Y; Vector2 clientSize = finalRect.Size.Deflate(margin); isClippingRequired |= clientSize.X < inkSize.X || clientSize.Y < inkSize.Y; Vector2 offset = this.ComputeAlignmentOffset(clientSize, inkSize); offset.X += finalRect.X + margin.Left; offset.Y += finalRect.Y + margin.Top; this.visualOffset = offset; }