public void ExplicitCastSuccessTest() { SumType <int, string> sum = "foo"; Assert.Equal("foo", (string)sum); sum = 1; Assert.Equal(1, (int)sum); }
public void SumTryGetFailsTest() { bool boolValue; string stringValue; int intValue; SumType <int, string, bool> sum = 1; Assert.False(sum.TryGet <string>(out stringValue)); Assert.Equal(default, stringValue);
public void SumTryGetSucceedsTest() { SumType <int, string> sum = "foo"; Assert.True(sum.TryGet <string>(out var stringValue)); Assert.Equal("foo", stringValue); sum = 1; Assert.True(sum.TryGet <int>(out var intValue)); Assert.Equal(1, intValue); }
public void ExplicitCastDowncastSucceeds() { SumType <int, string, bool, double> sum = 1; SumType <int, string, bool> tripleSum = sum; SumType <int, string> doubleSum = sum; SumType <int> singleSum = sum; Assert.Equal(1, (int)sum); Assert.Equal(1, (int)tripleSum); Assert.Equal(1, (int)doubleSum); Assert.Equal(1, (int)singleSum); }
public void SumIsTrueTest() { SumType <int, string, bool> sum = 1; Assert.True(sum.Is <int>()); sum = "foo"; Assert.True(sum.Is <string>()); sum = true; Assert.True(sum.Is <bool>()); }
async Task <object> RequestCompletionsInternal(CompletionParams completionParams, CancellationToken token) { SumType <CompletionItem[], CompletionList>?result = await jsonRpc.InvokeWithParameterObjectAsync(Methods.TextDocumentCompletion, completionParams, token); if (result == null) { return(null); } return(result.Value.Match <object> ( completionItems => completionItems, completionList => completionList)); }
private ISum GetInstanceOfTypeISum(SumType sumType) { switch (sumType) { case SumType.SumAfterMultiplyByTwo: return(new SumAfterMultipyByTwo()); case SumType.SumAfterMultiplyByThree: return(new SumAfterMultiplyByThree()); default: throw new NotSupportedException("sumType not supported"); } }
public List <List <Node> > GetPaths(SumType sumType) { List <List <Node> > ret = new List <List <Node> >(); //второой список сделать списком строк foreach (var path in getPathList(Root, new List <Node>(), new List <List <Node> >(), sumType)) { if (Sum(path) == 0) { ret.Add(path); } } return(ret); }
public void ExplicitCastFailsTest() { SumType <int, string, bool> sum = 1; Assert.Throws <InvalidCastException>(() => (string)sum); Assert.Throws <InvalidCastException>(() => (bool)sum); sum = "foo"; Assert.Throws <InvalidCastException>(() => (int)sum); Assert.Throws <InvalidCastException>(() => (bool)sum); sum = true; Assert.Throws <InvalidCastException>(() => (int)sum); Assert.Throws <InvalidCastException>(() => (string)sum); }
public void ExplicitCastSuccessTest() { SumType <int, string, bool, double> sum = 1; Assert.Equal(1, (int)sum); sum = "foo"; Assert.Equal("foo", (string)sum); sum = true; Assert.True((bool)sum); sum = 4.5; Assert.Equal(4.5, (double)sum); }
public void ExplicitCastDowncastUpcastSucceedsTest() { SumType <int, string, bool> sum = "foo"; SumType <int> lowerSum = sum; SumType <int, string, bool> upperSum = lowerSum; Assert.Equal("foo", (string)upperSum); sum = true; SumType <int, string> middleSum = sum; upperSum = middleSum; Assert.True((bool)upperSum); }
public void SumIsTrueDowncastUpcastTest() { SumType <int, string, bool> sum = "foo"; SumType <int> lowerSum = sum; SumType <int, string, bool> upperSum = lowerSum; Assert.True(upperSum.Is <string>()); sum = true; SumType <int, string> middleSum = sum; upperSum = middleSum; Assert.True(upperSum.Is <bool>()); }
public void ExplicitCastDowncastUpcastFailsTest() { SumType <int, string, bool> sum = "foo"; SumType <int> lowerSum = sum; SumType <int, bool, string> upperSum = lowerSum; Assert.Throws <InvalidCastException>(() => (bool)upperSum); Assert.Throws <InvalidCastException>(() => (string)upperSum); sum = true; SumType <int, string> middleSum = sum; SumType <int, string, float> upperSum2 = middleSum; Assert.Throws <InvalidCastException>(() => (bool)upperSum); Assert.Throws <InvalidCastException>(() => (float)upperSum); }
public void SumIsFalseDowncastUpcastTest() { SumType <int, string, bool> sum = "foo"; SumType <int> lowerSum = sum; SumType <int, bool, string> upperSum = lowerSum; Assert.False(upperSum.Is <string>()); Assert.False(upperSum.Is <bool>()); sum = true; SumType <int, string> middleSum = sum; SumType <int, string, float> upperSum2 = middleSum; Assert.False(upperSum.Is <string>()); Assert.False(upperSum.Is <float>()); }
public void ExplicitCastDowncastUpcastSucceeds() { SumType <int, string, bool, double> sum = 4.5; SumType <int, string, bool> tripleSum = sum; SumType <int, string> doubleSum = sum; SumType <int> singleSum = sum; sum = tripleSum; Assert.Equal(4.5, (double)sum); sum = doubleSum; Assert.Equal(4.5, (double)sum); sum = singleSum; Assert.Equal(4.5, (double)sum); }
public AnalysisKey([CanBeNull] string trafokreis, [CanBeNull] string providerType, SumType sumType, GenerationOrLoad generationOrLoad, [CanBeNull] string houseName, [CanBeNull] string profileSource, [CanBeNull] string houseComponentType) { Trafokreis = trafokreis; ProviderType = providerType; SumType = sumType; GenerationOrLoad = generationOrLoad; HouseName = houseName; ProfileSource = profileSource; HouseComponentType = houseComponentType; }
// Internal for testing internal SumType <CompletionItem[], CompletionList>?SetResolveData(SumType <CompletionItem[], CompletionList> completionResult, LanguageServerKind kind) { var result = completionResult.Match <SumType <CompletionItem[], CompletionList>?>( items => { var newItems = items.Select(item => SetData(item)).ToArray(); return(newItems); }, list => { var newItems = list.Items.Select(item => SetData(item)).ToArray(); if (list is VSCompletionList vsList) { return(new VSCompletionList() { Items = newItems, IsIncomplete = vsList.IsIncomplete, SuggesstionMode = vsList.SuggesstionMode, ContinueCharacters = vsList.ContinueCharacters }); } return(new CompletionList() { Items = newItems, IsIncomplete = list.IsIncomplete, }); }, () => null); return(result); CompletionItem SetData(CompletionItem item) { var data = new CompletionResolveData() { LanguageServerKind = kind, OriginalData = item.Data }; item.Data = data; return(item); } }
private SumType <CompletionItem[], CompletionList>?MassageCSharpCompletions( CompletionParams request, LSPDocumentSnapshot documentSnapshot, SumType <CompletionItem[], CompletionList> result) { var updatedResult = result; var wordExtent = documentSnapshot.Snapshot.GetWordExtent(request.Position.Line, request.Position.Character, _textStructureNavigator); if (IsSimpleImplicitExpression(request, documentSnapshot, wordExtent)) { updatedResult = DoNotPreselect(updatedResult); updatedResult = IncludeCSharpKeywords(updatedResult); } updatedResult = RemoveDesignTimeItems(documentSnapshot, wordExtent, updatedResult); return(updatedResult); }
// We should remove Razor design time helpers from C#'s completion list. If the current identifier being targeted does not start with a double // underscore, we trim out all items starting with "__" from the completion list. If the current identifier does start with a double underscore // (e.g. "__ab[||]"), we only trim out common design time helpers from the completion list. private SumType <CompletionItem[], CompletionList> RemoveDesignTimeItems( LSPDocumentSnapshot documentSnapshot, TextExtent?wordExtent, SumType <CompletionItem[], CompletionList> completionResult) { var result = completionResult.Match <SumType <CompletionItem[], CompletionList> >( items => { items = RemoveDesignTimeItems(documentSnapshot, wordExtent, items); return(items); }, list => { list.Items = RemoveDesignTimeItems(documentSnapshot, wordExtent, list.Items); return(list); }); return(result);
// C# keywords were previously provided by snippets, but as of now C# LSP doesn't provide snippets. // We're providing these for now to improve the user experience (not having to ESC out of completions to finish), // but once C# starts providing them their completion will be offered instead, at which point we should be able to remove this step. private SumType <CompletionItem[], CompletionList>?IncludeCSharpKeywords(SumType <CompletionItem[], CompletionList> completionResult, LanguageServerKind kind) { var result = completionResult.Match <SumType <CompletionItem[], CompletionList>?>( items => { var newList = items.Union(KeywordCompletionItems, CompletionItemComparer.Instance); return(newList.ToArray()); }, list => { var newList = list.Items.Union(KeywordCompletionItems, CompletionItemComparer.Instance); list.Items = newList.ToArray(); return(list); }); return(result); }
private static int GetSum(SumType type) { int length = type == SumType.Demand ? consumers.Count : producers.Count; int sum = 0; for (int i = 0; i < length; i++) { if (type == SumType.Demand) { sum += consumers[i].Demand; } else { sum += producers[i].Stock; } } return(sum); }
public async Task <IEnumerable <DocumentsSummery> > SumAsync(SumType type, DateTime fromDate, DateTime toDate, int?salesmanCode = null, bool?isClosed = null) { if (type != SumType.Monthly) { throw new InvalidStateException($"Unsupported type {type} Not Implemented"); } using var transaction = DalService.CreateUnitOfWork(); Expression <Func <TDocumentHeader, bool> > datePredicate = x => x.Date >= fromDate && x.Date <= toDate && x.IsCanceled != true; Expression <Func <TDocumentHeader, bool> > salesmanPredicate = x => x.SalesmanSn == salesmanCode && x.Date >= fromDate && x.Date <= toDate && x.IsCanceled != true; Expression <Func <TDocumentHeader, bool> > isClosedPredicate = x => x.IsClosed == isClosed && x.Date >= fromDate && x.Date <= toDate && x.IsCanceled != true; Expression <Func <TDocumentHeader, bool> > isClosedSalesmanPredicate = x => x.IsClosed == isClosed && x.SalesmanSn == salesmanCode && x.Date >= fromDate && x.Date <= toDate && x.IsCanceled != true; Expression <Func <TDocumentHeader, bool> > predicate; if (salesmanCode.HasValue && isClosed.HasValue) { predicate = isClosedSalesmanPredicate; } else if (salesmanCode.HasValue) { predicate = salesmanPredicate; } else if (isClosed.HasValue) { predicate = isClosedPredicate; } else { predicate = datePredicate; } return(await GetRepository(transaction).SumMonthlyAsync(predicate)); }
// In cases like "@{" preselection can lead to unexpected behavior, so let's exclude it. private SumType <CompletionItem[], CompletionList>?DoNotPreselect(SumType <CompletionItem[], CompletionList> completionResult) { var result = completionResult.Match <SumType <CompletionItem[], CompletionList>?>( items => { foreach (var i in items) { i.Preselect = false; } return(items); }, list => { foreach (var i in list.Items) { i.Preselect = false; } return(list); }); return(result); }
static bool TryConvertToCompletionList(SumType <CompletionItem[], CompletionList>?original, out CompletionList completionList) { if (!original.HasValue) { completionList = null; return(false); } if (original.Value.TryGetFirst(out var completionItems)) { completionList = new CompletionList() { Items = completionItems, IsIncomplete = false }; } else if (!original.Value.TryGetSecond(out completionList)) { throw new InvalidOperationException("Could not convert Razor completion set to a completion list. This should be impossible, the completion result should be either a completion list, a set of completion items or `null`."); } return(true); }
public void IsFalseTest() { SumType <int, string, bool, double> sum = 1; Assert.False(sum.Is <string>()); Assert.False(sum.Is <bool>()); Assert.False(sum.Is <double>()); sum = "foo"; Assert.False(sum.Is <int>()); Assert.False(sum.Is <bool>()); Assert.False(sum.Is <double>()); sum = true; Assert.False(sum.Is <int>()); Assert.False(sum.Is <string>()); Assert.False(sum.Is <double>()); sum = 4.5; Assert.False(sum.Is <int>()); Assert.False(sum.Is <string>()); Assert.False(sum.Is <bool>()); }
public async Task HandleRequestAsync_CSharpProjection_InvokesCSharpLanguageServer() { // Arrange var called = false; var expectedContents = new SumType <SumType <string, MarkedString>, SumType <string, MarkedString>[], MarkupContent>( new MarkedString() { Language = "markdown", Value = "Hover Details" } ); var lspResponse = new Hover() { Range = new Range() { Start = new Position(10, 0), End = new Position(10, 1) }, Contents = expectedContents }; var expectedItem = new Hover() { Range = new Range() { Start = new Position(0, 0), End = new Position(0, 1) }, Contents = expectedContents }; var hoverRequest = new TextDocumentPositionParams() { TextDocument = new TextDocumentIdentifier() { Uri = Uri }, Position = new Position(0, 1) }; var documentManager = new TestDocumentManager(); documentManager.AddDocument(Uri, Mock.Of <LSPDocumentSnapshot>()); var requestInvoker = new Mock <LSPRequestInvoker>(); requestInvoker .Setup(r => r.ReinvokeRequestOnServerAsync <TextDocumentPositionParams, Hover>(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <TextDocumentPositionParams>(), It.IsAny <CancellationToken>())) .Callback <string, string, TextDocumentPositionParams, CancellationToken>((method, serverContentType, hoverParams, ct) => { Assert.Equal(Methods.TextDocumentHoverName, method); Assert.Equal(RazorLSPConstants.CSharpContentTypeName, serverContentType); called = true; }) .Returns(Task.FromResult(lspResponse)); var projectionResult = new ProjectionResult() { LanguageKind = RazorLanguageKind.CSharp }; var projectionProvider = new Mock <LSPProjectionProvider>(); projectionProvider.Setup(p => p.GetProjectionAsync(It.IsAny <LSPDocumentSnapshot>(), It.IsAny <Position>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(projectionResult)); var remappingResult = new RazorMapToDocumentRangesResponse() { Ranges = new[] { new Range() { Start = new Position(0, 0), End = new Position(0, 1) } }, HostDocumentVersion = 0 }; var documentMappingProvider = new Mock <LSPDocumentMappingProvider>(); documentMappingProvider.Setup(d => d.MapToDocumentRangesAsync(RazorLanguageKind.CSharp, It.IsAny <Uri>(), It.IsAny <Range[]>(), It.IsAny <CancellationToken>())). Returns(Task.FromResult(remappingResult)); var hoverHandler = new HoverHandler(requestInvoker.Object, documentManager, projectionProvider.Object, documentMappingProvider.Object); // Act var result = await hoverHandler.HandleRequestAsync(hoverRequest, new ClientCapabilities(), CancellationToken.None).ConfigureAwait(false); // Assert Assert.True(called); Assert.Equal(expectedItem.Contents, result.Contents); Assert.Equal(expectedItem.Range, result.Range); }
/// <summary> /// Don't use this class /// </summary> /// <param name="_entityID"></param> /// <param name="_sumType"></param> /// <returns></returns> public EntityCollection QuerySumTypeEntity(int _entityID, SumType _sumType) { return null; }
public EntityCollection QuerySumTypeEntity(SumType _sumType) { EntityCollection collection = new EntityCollection(); using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "SP_SEL_Table"; SqlParameter _param = command.Parameters.Add("@value1", System.Data.SqlDbType.VarChar); _param.Value = "Entity"; SqlParameter _param2 = command.Parameters.Add("@value2", System.Data.SqlDbType.VarChar); _param2.Value = "5"; SqlParameter _param3 = command.Parameters.Add("@value3", System.Data.SqlDbType.VarChar); _param3.Value = (int)_sumType; SqlParameter _param4 = command.Parameters.Add("@order_by1", System.Data.SqlDbType.VarChar); _param4.Value = "1"; SqlParameter _param5 = command.Parameters.Add("@order_by2", System.Data.SqlDbType.TinyInt); _param5.Value = 0; command.CommandType = System.Data.CommandType.StoredProcedure; connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Entity _entity = new Entity(); _entity.EntityID = Convert.ToInt32(reader["ID"]); _entity.ParentID = Convert.ToInt32(reader["ParentID"]); _entity.EntityName = reader["Entity_Name"].ToString(); _entity.EntityType = (EntityType)Convert.ToInt32(reader["Entity_Type"]); _entity.SumType = (SumType)Convert.ToInt32(reader["SumType"]); _entity.Currency.CurrencyID = reader["Currency"].ToString(); _entity.ExchangeRate = Convert.ToDecimal(reader["Exchange_Rate"]); _entity.IsAccount = Convert.ToInt32(reader["IsAccount"]); _entity.Enable = Convert.ToInt32(reader["Enable"]); _entity.IsLastLevel = Convert.ToInt32(reader["IsLastLevel"]); if (_entity.Enable == 1) { collection.Add(_entity); } } } reader.Close(); return collection; } }
public static Command GetCommand(this SumType <Command, CodeAction> commandOrCodeAction) { return(commandOrCodeAction.Match( command => command, codeAction => codeAction.Command)); }
public void SumTryGetFailsTest() { SumType <int> sum = 1; Assert.False(sum.TryGet <string>(out var value)); Assert.Equal(default, value);
public void SumIsFalseTest() { SumType <int> sum = 1; Assert.False(sum.Is <string>()); }
public void SumIsTrueTest() { SumType <int> sum = 1; Assert.True(sum.Is <int>()); }
public void VisitSum(SumType t) { t.Left.AcceptVisitor(this); t.Right.AcceptVisitor(this); }
private void fillDataPeriod(Worksheet ws, List<FactData> sqlData, int columnIndex, int minRowIndex, int maxRowIndex, SumType sumType) { for (int rowIndex = minRowIndex; rowIndex <= maxRowIndex; rowIndex++) { var row = (Range)ws.Rows[rowIndex]; var codes = row.GetCellValue<string>(1, 1); int currentColIndex = columnIndex; // флаг стоматологии (или неотложки) var isStomaOrEmegency = (rowIndex >= stomaRowRowIndex && rowIndex <= emergencyRowIndex); if (!string.IsNullOrEmpty(codes) || isStomaOrEmegency) { if (codes == null) codes = ""; // выделяем услуги для текущих специализаций (для стоматологии и неотложки // услуги выделяются в SQL запросе) string[] specCodes = codes.Split(','); List<FactData> rowData = (from c in sqlData where isStomaOrEmegency || specCodes.Contains(c.SpecCode) select c).ToList(); double fact = 0; // лямбда для определения фактического показателя для суммирования Func<FactData, double> sumFunc = y => { double result = 0; switch (sumType) { case SumType.Event: result = y.EventCount; break; case SumType.Kol: result = y.Kol; break; case SumType.Uet: result = y.Uet; break; } return result; }; // есть ли для текущей специальности годовой план по детям var useChildCodes = row.GetCellValue<int>(1, childPlanProfilacticColumn) > 0 || row.GetCellValue<int>(1, childPlanVisitColumn) > 0 || row.GetCellValue<int>(1, childPlanTreatmentColumn) > 0; // лямбда для отнесения фактических данных к колонке отчета Func<FactData, bool, ActionKind, bool> selectorFunc = (factData, isChild, actionKind) => { var result = factData.ActionKind == (int)actionKind; if (useChildCodes) result = result && (factData.IsChild == (isChild ? 1 : 0)); else result = result && !isChild; return result; }; fact = rowData.Where(x => selectorFunc(x, false, ActionKind.Profilactic)).Sum(sumFunc); row.SetCellValue(1, currentColIndex++, fact); fact = rowData.Where(x => selectorFunc(x, true, ActionKind.Profilactic)).Sum(sumFunc); row.SetCellValue(1, currentColIndex++, fact); fact = rowData.Where(x => selectorFunc(x, false, ActionKind.Visit)).Sum(sumFunc); row.SetCellValue(1, currentColIndex++, fact); fact = rowData.Where(x => selectorFunc(x, true, ActionKind.Visit)).Sum(sumFunc); row.SetCellValue(1, currentColIndex++, fact); fact = rowData.Where(x => selectorFunc(x, false, ActionKind.Treatment)).Sum(sumFunc); row.SetCellValue(1, currentColIndex++, fact); fact = rowData.Where(x => selectorFunc(x, true, ActionKind.Treatment)).Sum(sumFunc); row.SetCellValue(1, currentColIndex++, fact); #region Сбор использованных кодов услуг currentColIndex = serviceCodeColumn; string services = ""; services = string.Join(",", rowData.Where(x => selectorFunc(x, false, ActionKind.Profilactic)) .Select(x => x.ServiceCode).Distinct()); row.SetCellValue(1, currentColIndex++, services); services = string.Join(",", rowData.Where(x => selectorFunc(x, true, ActionKind.Profilactic)) .Select(x => x.ServiceCode).Distinct()); row.SetCellValue(1, currentColIndex++, services); services = string.Join(",", rowData.Where(x => selectorFunc(x, false, ActionKind.Visit)) .Select(x => x.ServiceCode).Distinct()); row.SetCellValue(1, currentColIndex++, services); services = string.Join(",", rowData.Where(x => selectorFunc(x, true, ActionKind.Visit)) .Select(x => x.ServiceCode).Distinct()); row.SetCellValue(1, currentColIndex++, services); services = string.Join(",", rowData.Where(x => selectorFunc(x, false, ActionKind.Treatment)) .Select(x => x.ServiceCode).Distinct()); row.SetCellValue(1, currentColIndex++, services); services = string.Join(",", rowData.Where(x => selectorFunc(x, true, ActionKind.Treatment)) .Select(x => x.ServiceCode).Distinct()); row.SetCellValue(1, currentColIndex++, services); #endregion } } }
private void fillDataCell(Worksheet ws, List<FactData> factDatas, int columnIndex, int rowIndex, SumType sumType) { Func<FactData, double> sumFunc = y => { double result = 0; switch (sumType) { case SumType.Event: result = y.EventCount; break; case SumType.Client: result = y.ClientCount; break; } return result; }; var fact = factDatas.Sum(sumFunc); Utils.SetExcelValue(ws.Cells, rowIndex, columnIndex, fact); }
private static double getRiemannSum(int rects, double start, double end, double deltaX, string func, SumType sumSide) { var watch = new System.Diagnostics.Stopwatch(); watch.Start(); ScalarValue x = new ScalarValue(0); Parser.AddVariable("x", x); var c = Parser.Parse(func); double sum = 0.0; double middleOffset = 0; int first = 0; int limit = rects; double trapezoidalMultiple = 1.0; //sumSide == SumType.Left is the default case, in which none of these if statements will fire. if (sumSide == SumType.Middle) { middleOffset = deltaX / 2; } if (sumSide == SumType.Right) { first++; limit++; } if (sumSide == SumType.Trapezoidal) { trapezoidalMultiple = 2.0; //Shrink the sum calculated by removing a term on the right side/ first++; } try { for (int i = first; i < limit; i++) { x.Value = trapezoidalMultiple * (start + (i * deltaX) + middleOffset); ScalarValue s = (ScalarValue)c.Execute(); sum += s.Value; } if (sumSide == SumType.Trapezoidal) { x.Value = start; ScalarValue s = (ScalarValue)c.Execute(); sum += s.Value; x.Value = end; s = (ScalarValue)c.Execute(); sum += s.Value; sum *= 0.5; } } catch (YAMP.YAMPException ex) { Console.WriteLine(ex.Message); throw ex; } finally { Parser.RemoveVariable("x"); } Console.WriteLine(watch.Elapsed); //Console.WriteLine(sum * deltaX); return sum * deltaX; }