public void TestFindActiveIdentifiers() { // Build up a tree with OR node as root, child a (OR node) for value 0, child b (value node) for value 1. // Create the nodes. IParameterTreeNode a = new OrNode <int>("a", new CategoricalDomain <int>(new List <int> { 2, 5 })); IParameterTreeNode b = new ValueNode <int>("b", new IntegerDomain()); var rootDecision = new OrNode <int>("or", new CategoricalDomain <int>(new List <int> { 0, 1 })); // Create connections. rootDecision.AddChild(0, a); rootDecision.AddChild(1, b); var parameterTree = new ParameterTree(rootDecision); // Set value for roort node s.t. only node a should be active. var values = new Dictionary <string, IAllele>(3) { { "a", new Allele <int>(2) }, { "b", new Allele <int>(7) }, { "or", new Allele <int>(0) }, }; var activeIdentifiers = parameterTree.FindActiveIdentifiers(values.ToImmutableDictionary()).ToList(); var expectedActiveIdentifiers = new List <string> { "or", "a" }; Assert.True( TestUtils.SetsAreEquivalent(activeIdentifiers, expectedActiveIdentifiers), $"Active identifiers should be {TestUtils.PrintList(expectedActiveIdentifiers)}, but are {TestUtils.PrintList(activeIdentifiers)}."); }
public void ResetSimulationTest() { var inputNode1 = new InputNode("in1", new State(false)); var inputNode2 = new InputNode("in2", new State(true)); var orNode = new OrNode("or"); var outputNode = new OutputNode("out"); var nodeConnections = new List <NodeConnection> { new NodeConnection( new List <NodeBase> { inputNode1, inputNode2 }, orNode), new NodeConnection(orNode, outputNode) }; var inputNodes = new List <InputNode> { inputNode1, inputNode2 }; var simulation = new NodeSimulation(nodeConnections); simulation.RunSimulation(); simulation.ResetSimulation(); var output = simulation.GetOutputState(); Assert.Null(output["out"]); }
public void SetInvalidAmountInputsTest() { var inputNode1 = new InputNode("in1"); var inputNode2 = new InputNode("in2"); var orNode = new OrNode("or"); var outputNode = new OutputNode("out"); var nodeConnections = new List <NodeConnection> { new NodeConnection( new List <NodeBase> { inputNode1, inputNode2 }, orNode), new NodeConnection(orNode, outputNode) }; var inputNodes = new List <InputNode> { inputNode1, inputNode2 }; var simulation = new NodeSimulation(nodeConnections); var inputValues = new Dictionary <string, State> { { inputNode1.NodeId, new State(true) }, { inputNode2.NodeId, new State(false) }, { orNode.NodeId, new State(false) } }; Assert.Throws <ArgumentException>(() => simulation.SetInputs(inputValues)); }
public void CreateSimulationTest() { var inputNode1 = new InputNode("in1", new State(false)); var inputNode2 = new InputNode("in2", new State(true)); var orNode = new OrNode("or"); var outputNode = new OutputNode("out"); var nodeConnections = new List <NodeConnection> { new NodeConnection( new List <NodeBase> { inputNode1, inputNode2 }, orNode), new NodeConnection(orNode, outputNode) }; var inputNodes = new List <InputNode> { inputNode1, inputNode2 }; var simulation = new NodeSimulation(nodeConnections); // TODO: Is this the same as CollectionAssert? Assert.Equal(nodeConnections, simulation.NodeConnections); }
public override BaseNode VisitFilterExpression(QueryFilteringParser.FilterExpressionContext context) { BaseNode resultNode = context.children[0].Accept(this); for (int i = 1; i < context.children.Count; i += 2) { var left = resultNode; var right = context.children[i + 1].Accept(this); var aggregateNode = (ITerminalNode)context.children[i]; switch (aggregateNode.Symbol.Type) { case QueryFilteringLexer.AND: resultNode = new AndNode(left, right); continue; case QueryFilteringLexer.OR: resultNode = new OrNode(left, right); continue; default: throw new ParseRuleException( nameof(FilterExpressionVisitor), $"неизвестный тип предиката '{aggregateNode.Symbol.Type}'"); } } return(resultNode); }
/// <summary> /// Takes a list of tokenized input and create the corresponding expression tree. /// </summary> /// <param name="tokenList"> /// Tokenized list of the input string. /// </param> private Node ConstructExpressionTree(List <Token> tokenList) { bool notFlag = false; Queue <Node> andQueue = new Queue <Node>(); Queue <Node> orQueue = new Queue <Node>(); for (int i = 0; i < tokenList.Count; i++) { Token token = tokenList[i]; TokenKind kind = token.Kind; if (kind == TokenKind.Identifier) { Node idNode = new OperandNode(token.Text); if (notFlag) // identifier preceded by NOT { Node notNode = new NotNode(); notNode.Operand1 = idNode; notFlag = false; andQueue.Enqueue(notNode); } else { andQueue.Enqueue(idNode); } } else if (kind == TokenKind.Not) { notFlag = true; } else if (kind == TokenKind.And) { // do nothing } else if (kind == TokenKind.Or) { // Dequeue all nodes from AND queue, // create the AND tree, then add to the OR queue. Node andCurrent = andQueue.Dequeue(); while (andQueue.Count > 0) { Node andNode = new AndNode(andCurrent); andNode.Operand1 = andQueue.Dequeue(); andCurrent = andNode; } orQueue.Enqueue(andCurrent); } } // Dequeue all nodes from OR queue, // create the OR tree (final expression tree) Node orCurrent = orQueue.Dequeue(); while (orQueue.Count > 0) { Node orNode = new OrNode(orCurrent); orNode.Operand1 = orQueue.Dequeue(); orCurrent = orNode; } return(orCurrent); }
public void Should_parse_or_expression() { OrNode or = (OrNode)Parse("1~or~2"); Assert.Equal(1, Convert.ToInt32(((NumberNode)or.First).Value)); Assert.Equal(2, Convert.ToInt32(((NumberNode)or.Second).Value)); }
public Func <IQuery <T>, ValueTask <IQuery <T> > > Visit(OrNode node, QueryExecutionContext <T> argument) { return(result => argument.Item.AnyAsync( (q) => node.Left.Accept(this, argument)(q), (q) => node.Right.Accept(this, argument)(q) )); }
protected virtual QueryNode VisitOr(OrNode node, AzureQueryOptimizerState state) { QueryNode queryNode1 = this.Visit(node.LeftNode, state); QueryNode queryNode2 = this.Visit(node.RightNode, state); bool? booleanValue1 = this.GetBooleanValue(queryNode1); bool? booleanValue2 = this.GetBooleanValue(queryNode2); if (!booleanValue1.HasValue && !booleanValue2.HasValue) { return((QueryNode) new OrNode(queryNode1, queryNode2)); } if (booleanValue1.HasValue && booleanValue2.HasValue) { if (!booleanValue1.Value && !booleanValue2.Value) { return((QueryNode) new MatchNoneNode()); } return((QueryNode) new MatchAllNode()); } if (booleanValue1.HasValue) { return(queryNode2); } return(queryNode1); }
private Value Or(OrNode exp) { try { Constant left = Eval(exp.Left).GetRValue(); Constant right = Eval(exp.Right).GetRValue(); BoolValue l = (BoolValue)Convert(left, Constant.Type.Bool); BoolValue r = (BoolValue)Convert(right, Constant.Type.Bool); return(BoolValue.OpOr(l, r)); } catch (TypeConversionError exc) { throw new ModelInterpreterException($"Операция \"ИЛИ\" не определена для типов \"{exc.Src}\" и \"{exc.Dst}\"") { Line = exp.Line, Position = exp.Position }; } catch (Exception exc) { throw new ModelInterpreterException(exc.Message) { Line = exp.Line, Position = exp.Position }; } }
public void GetFilteredGenesHandlesOrNodesCorrectly() { // Build up a tree with OR node as root, child a (OR node) for value 0, child b (value node) for value 1. // Create the nodes. IParameterTreeNode a = new OrNode <int>("a", new CategoricalDomain <int>(new List <int> { 2, 5 })); IParameterTreeNode b = new ValueNode <int>("b", new IntegerDomain()); OrNode <int> rootDecision = new OrNode <int>("or", new CategoricalDomain <int>(new List <int> { 0, 1 })); // Create connections. rootDecision.AddChild(0, a); rootDecision.AddChild(1, b); var parameterTree = new ParameterTree(rootDecision); this._genome.SetGene("a", new Allele <int>(2)); this._genome.SetGene("b", new Allele <int>(7)); this._genome.SetGene("or", new Allele <int>(0)); var filteredGenes = this._genome.GetFilteredGenes(parameterTree); var expectedFilteredGenes = new List <string> { "or", "a" }; Assert.True( TestUtils.SetsAreEquivalent(filteredGenes.Keys, expectedFilteredGenes), $"Filtered genes should be {TestUtils.PrintList(expectedFilteredGenes)}, but are {TestUtils.PrintList(filteredGenes.Keys)}."); }
public OrNode Or() { OrNode orNode = new OrNode(); Match(TokenType.OR); return(orNode); }
public void Visit(OrNode node) { var right = Nodes.Pop(); var left = Nodes.Pop(); Nodes.Push(new OrNode(left, right)); }
protected virtual BaseQuery HandleOr(OrNode node, ElasticSearchQueryMapperState state) { //TODO: the code below specifically handles IsNullOrEmpty method, seems like a lot to handle one case... is there a better place for it? //Lucene provider doesn't have this code, but Solr provider does if (node.LeftNode.NodeType == QueryNodeType.Equal && node.RightNode.NodeType == QueryNodeType.Equal) { var leftNode = (EqualNode)node.LeftNode; var rightNode = (EqualNode)node.RightNode; if (leftNode.RightNode.NodeType == QueryNodeType.Constant && rightNode.RightNode.NodeType == QueryNodeType.Constant) { var leftNodeValue = ((ConstantNode)leftNode.RightNode).Value; var rightNodeValue = ((ConstantNode)rightNode.RightNode).Value; if ((string)leftNodeValue == string.Empty && rightNodeValue == null) { var fieldName = ((FieldNode)leftNode.LeftNode).FieldKey; //TODO: this query works for 99% of items, however if a field contains a stopword and only a stopword, then it's treated as "missing" by ES //For example, say you have an item whose "Title" field contains just the word "To" (which is a stopword), if you try to search for all items //without a value in the "Title" field (i.e. the field is missing), ES will still return the item whose "Title" field contains just the word "To". //There's likely a better query to use... or maybe not, maybe it can only be done with analyzers. who could say? return(Query.Filtered(fq => fq.Filter(f => f.Missing(fieldName)))); } } } var query1 = Handle(node.LeftNode, state); var query2 = Handle(node.RightNode, state); if (query1) { return(query1); } return(query1 | query2); }
/// <summary> /// Builds the following parameter tree: /// - AND node as root /// - 1st child of AND node: OR node with string either a or b (default: "a") /// - 2nd child of AND node: value node with integer between 1 and 5 (default: 1) /// - OR node, a branch: value node with integer (default: 42). /// - OR node, b branch: value node with double between 0.1 and 0.8 (default: 0.2). /// </summary> /// <param name="includeDefaultValues">Indicates whether to add default values to the domains.</param> /// <returns>The build parameter tree.</returns> private static ParameterTree BuildParameterTree(bool includeDefaultValues = false) { // Create all parameter tree nodes. var rootNode = new AndNode(); OrNode <string> decideAOrBNode = new OrNode <string>( DecisionParameter, new CategoricalDomain <string>(new List <string> { "a", "b" }, includeDefaultValues ? new Allele <string>("a") : (Allele <string>?)null)); IParameterNode integerParamNode = new ValueNode <int>( GenomeBuilderTest.DiscreteParameter, new IntegerDomain(defaultValue: includeDefaultValues ? new Allele <int>(42) : (Allele <int>?)null)); IParameterNode continuousParamNode = new ValueNode <double>( GenomeBuilderTest.ContinuousParameter, new ContinuousDomain(0.1, 0.8, includeDefaultValues ? new Allele <double>(0.2) : (Allele <double>?)null)); IParameterNode smallIntegerParamNode = new ValueNode <int>( GenomeBuilderTest.SmallValueParameter, new IntegerDomain(1, 5, includeDefaultValues ? new Allele <int>(1) : (Allele <int>?)null)); // Connect them. decideAOrBNode.AddChild("a", integerParamNode); decideAOrBNode.AddChild("b", continuousParamNode); rootNode.AddChild(decideAOrBNode); rootNode.AddChild(smallIntegerParamNode); // Return tree. return(new ParameterTree(rootNode)); }
/// <summary> /// Converts this node to an <see cref="OrNode{T}"/>. /// </summary> /// <typeparam name="T">The type of values the represented parameter can take.</typeparam> /// <returns>The converted <see cref="OrNode{T}"/>.</returns> /// <exception cref="XmlException">Thrown if the object was read from XML in such a way that it /// does not represent a valid <see cref="IParameterTreeNode"/> object.</exception> protected override IParameterTreeNode ConvertToParameterTreeNode<T>() { // Cast domain to correct type. CategoricalDomain<T> categoricalDomain = this.domain.ConvertToParameterTreeDomain() as CategoricalDomain<T>; if (categoricalDomain == null) { throw new XmlException( $"Domain of OR node '{this.id}' was not of type {typeof(CategoricalDomain<T>)} as expected."); } // Create OR node. var node = new OrNode<T>(this.id, categoricalDomain); // Add children: foreach (var choice in this.choice) { // Check activator is of correct type. if (!(choice.Item is T)) { throw new XmlException( $"OR node '{this.id}' had a choice of type {choice.Item.GetType()} instead of {typeof(T)}."); } // Add child. node.AddChild((T)choice.Item, choice.child.ConvertToParameterTreeNode()); } return node; }
public void GenerateCode(OrNode node, ICIL_CodeGenerator codeGenerator) { node.Holder = codeGenerator.DefineVariable(); codeGenerator.AddLocalVariable( new CIL_LocalVariable((Variable)node.Holder)); GenerateCode(node.OpNode1, codeGenerator); codeGenerator.AddInstruction( new Assign((Variable)node.Holder, node.OpNode1.Holder)); var label = codeGenerator.DefineLabel(); codeGenerator.AddInstruction( new ConditionalJump((Variable)node.Holder, true, label)); GenerateCode(node.OpNode2, codeGenerator); codeGenerator.AddInstruction( new Assign((Variable)node.Holder, node.OpNode2.Holder)); codeGenerator.AddInstruction( new Label(label)); }
private string BuildFilter(OrNode orNode) { string tempFilter = ""; foreach (var Node in orNode.Nodes) { if (tempFilter.Trim().Length > 0) { tempFilter += " OR "; } ; if (Node.GetType() == typeof(ParameterNode)) { tempFilter += BuildFilter((ParameterNode)Node); } ; if (Node.GetType() == typeof(AndNode)) { tempFilter += BuildFilter((AndNode)Node); } ; if (Node.GetType() == typeof(OrNode)) { tempFilter += BuildFilter((OrNode)Node); } ; } return($"({tempFilter})"); }
public void OrNode_should_accept_visitor() { visitor.Setup(v => v.StartVisit(It.IsAny <ILogicalNode>())).Verifiable(); visitor.Setup(v => v.EndVisit()).Verifiable(); Mock <IFilterNode> first = new Mock <IFilterNode>(); first.Setup(f => f.Accept(It.IsAny <IFilterNodeVisitor>())).Verifiable(); Mock <IFilterNode> second = new Mock <IFilterNode>(); second.Setup(f => f.Accept(It.IsAny <IFilterNodeVisitor>())).Verifiable(); OrNode orNode = new OrNode { First = first.Object, Second = second.Object }; orNode.Accept(visitor.Object); visitor.VerifyAll(); first.Verify(); second.Verify(); }
public void Should_parse_complex_nested_expression() { OrNode or = (OrNode)Parse("(age~lt~20~and~startswith(name,'j'))~or~(endswith(name,'s')~and~number~gt~20)"); Assert.IsType(typeof(AndNode), or.First); Assert.IsType(typeof(AndNode), or.Second); }
public object Visit(OrNode node, object value) { foreach (var child in node.Children) { child.Accept(this, null); } return(this); }
void PropagateNotToLeaves(ref IQueryNode rootNode) { if (rootNode.leaf || !(rootNode is CombinedNode cn)) { return; } if (rootNode.type != QueryNodeType.Not) { return; } var parent = rootNode.parent; var oldNode = rootNode.children[0]; if (!(oldNode is CombinedNode oldCombinedNode) || (oldCombinedNode.type != QueryNodeType.And && oldCombinedNode.type != QueryNodeType.Or)) { return; } CombinedNode newCombinedNode; if (oldNode.type == QueryNodeType.And) { newCombinedNode = new OrNode(); } else { newCombinedNode = new AndNode(); } cn.RemoveNode(oldNode); foreach (var child in oldNode.children) { var propagatedNotNode = new NotNode(); propagatedNotNode.AddNode(child); newCombinedNode.AddNode(propagatedNotNode); } oldCombinedNode.Clear(); // If the old not is the root of the evaluationGraph, then the new combined node // becomes the new root. if (parent == null) { this.root = newCombinedNode; } else { // In order to not change the parent's enumeration, swap directly the old // children with the new one SwapChild(parent, rootNode, newCombinedNode); } // Set the current tree root to the new combined node. rootNode = newCombinedNode; }
private Node Expression() { var node = Xor(); while (_lexer.TryReadChar('|')) { node = new OrNode(node, Xor()); } return(node); }
protected QueryBase VisitOr(OrNode node, ElasticQueryMapperState state) { // TODO: NullOrEmpty check and maybe more var query1 = Visit(node.LeftNode, state); var query2 = Visit(node.RightNode, state); // TODO: This is the same as Union - not sure if that is correct // TODO: Need to check if this is correct, but it should be: https://www.elastic.co/guide/en/elasticsearch/guide/current/bool-query.html return(query1 || query2); }
// Token: 0x060000C9 RID: 201 RVA: 0x000053E4 File Offset: 0x000035E4 public TreeNode CreateSubtree() { OrNode orNode = new OrNode(); foreach (ClassificationDecoding classificationDecoding in this.decodings) { orNode.AddNode(classificationDecoding.CreateSubtree()); } return(orNode); }
/// <summary> /// Creates a parameter tree which root is an OR node "decision". If that is true, a value node "a" is /// evaluated, otherwise a value node "b". /// </summary> /// <returns>The created parameter tree.</returns> private static ParameterTree CreateParameterTree() { var decisionNode = new OrNode <bool>("decision", new CategoricalDomain <bool>(new List <bool> { true, false })); decisionNode.AddChild(true, new ValueNode <double>("a", new ContinuousDomain())); decisionNode.AddChild(false, new ValueNode <double>("b", new ContinuousDomain())); return(new ParameterTree(decisionNode)); }
private ExpressionNode ParseExpression() { var lhs = ParseJoin(); while (_reader.Peek() is Or) { lhs = new OrNode(lhs, ParseJoin()); } return(lhs); }
private Node ConstructExpressionTree(List <Token> tokenList) { bool flag = false; Queue <Node> queue = new Queue <Node>(); Queue <Node> queue2 = new Queue <Node>(); for (int i = 0; i < tokenList.Count; i++) { Token token = tokenList[i]; TokenKind kind = token.Kind; if (kind == TokenKind.Identifier) { Node item = new OperandNode(token.Text); if (flag) { Node node2 = new NotNode { Operand1 = item }; flag = false; queue.Enqueue(node2); } else { queue.Enqueue(item); } } else if (kind == TokenKind.Not) { flag = true; } else if ((kind != TokenKind.And) && (kind == TokenKind.Or)) { Node node3 = queue.Dequeue(); while (queue.Count > 0) { node3 = new AndNode(node3) { Operand1 = queue.Dequeue() }; } queue2.Enqueue(node3); } } Node n = queue2.Dequeue(); while (queue2.Count > 0) { n = new OrNode(n) { Operand1 = queue2.Dequeue() }; } return(n); }
public void Or_VariousPairs_MatchesString(string in0, string in1, string shouldMatch) { var node = new OrNode(); node.Inputs.Inputs.ElementAt(0).ConnectedNode = new FakeNodeOutput(in0); node.Inputs.Inputs.ElementAt(1).ConnectedNode = new FakeNodeOutput(in1); string nodeVal = node.CachedOutput.Expression; Assert.That(nodeVal, Is.Not.Null); Assert.That(shouldMatch, Does.Match(nodeVal)); }
private void Initialize() { _prototypes["AND"] = new AndNode(); _prototypes["NOT"] = new NotNode(); _prototypes["NAND"] = new NotAndNode(); _prototypes["NOR"] = new NotOrNode(); _prototypes["OR"] = new OrNode(); _prototypes["PROBE"] = new OutputNode(); _prototypes["INPUT"] = new InputNode(); _prototypes["XOR"] = new XorNode(); _prototypes["NODE"] = new Node(); }
public void Should_return_composite_descriptor_for_or_node() { OrNode orNode = new OrNode() { First = DateTimeComparison(), Second = StringFunction() }; orNode.Accept(visitor); CompositeFilterDescriptor descriptor = (CompositeFilterDescriptor)visitor.Result; Assert.Equal(FilterCompositionLogicalOperator.Or, descriptor.LogicalOperator); Assert.Equal(FilterOperator.IsEqualTo, ((FilterDescriptor)descriptor.FilterDescriptors[0]).Operator); Assert.Equal(FilterOperator.StartsWith, ((FilterDescriptor)descriptor.FilterDescriptors[1]).Operator); }
// throws RecognitionException [1] // $ANTLR end "language" // $ANTLR start "expr_or" // C:\\Users\\Danaice\\Desktop\\lastversion\\Dany_gramatica tiger ANTLR oficial\\tiger_grammar.g:93:1: expr_or returns [TigerNode or] : exp1= expr_and ( OR exp2= expr_and )* ; public TigerNode expr_or() { TigerNode or = null; IToken OR2 = null; TigerNode exp1 = null; TigerNode exp2 = null; try { // C:\\Users\\Danaice\\Desktop\\lastversion\\Dany_gramatica tiger ANTLR oficial\\tiger_grammar.g:93:31: (exp1= expr_and ( OR exp2= expr_and )* ) // C:\\Users\\Danaice\\Desktop\\lastversion\\Dany_gramatica tiger ANTLR oficial\\tiger_grammar.g:93:33: exp1= expr_and ( OR exp2= expr_and )* { PushFollow(FOLLOW_expr_and_in_expr_or542); exp1 = expr_and(); state.followingStackPointer--; if (state.failed) return or; if ( (state.backtracking==0) ) { or = exp1; } // C:\\Users\\Danaice\\Desktop\\lastversion\\Dany_gramatica tiger ANTLR oficial\\tiger_grammar.g:94:25: ( OR exp2= expr_and )* do { int alt2 = 2; int LA2_0 = input.LA(1); if ( (LA2_0 == OR) ) { alt2 = 1; } switch (alt2) { case 1 : // C:\\Users\\Danaice\\Desktop\\lastversion\\Dany_gramatica tiger ANTLR oficial\\tiger_grammar.g:94:26: OR exp2= expr_and { OR2=(IToken)Match(input,OR,FOLLOW_OR_in_expr_or571); if (state.failed) return or; PushFollow(FOLLOW_expr_and_in_expr_or576); exp2 = expr_and(); state.followingStackPointer--; if (state.failed) return or; if ( (state.backtracking==0) ) { or = new OrNode(or, exp2); or.Col= OR2.CharPositionInLine; or.Row = OR2.Line; } } break; default: goto loop2; } } while (true); loop2: ; // Stops C# compiler whining that label 'loop2' has no statements } } catch (RecognitionException re) { ReportError(re); Recover(input,re); } finally { } return or; }
private Node ParseExpression() { Node n = ParseSequence(); Token t = PeekToken(); for (;;) { switch (t) { case Token.End: case Token.RParen: case Token.Cut: return n; default: Expect(Token.Or); n = new OrNode(n, ParseSequence()); break; } t = PeekToken(); } }