예제 #1
0
 public Metis(Set set, Proximity diss)
     : base(set, diss)
 {
     Name = "Metis";
     //ProximityType = ProximityType.Both;
     ProximityType = ProximityType.Similarity;
 }
예제 #2
0
        /*************************/
        // Selecting initial vertices
        /*************************/
        // Returns a vertex on the last level of a Breadth-first search (BFS)
        public static int BFS(Graph graph, int init)
        {
            // BFS working queue
            Queue<int> queue = new Queue<int>();
            // Vertices that have already been visited
            Set<int> visited = new Set<int>();

            // Initial vertex is given as input
            visited.Add(init);
            queue.Enqueue(init);
            int current = init;

            // While there is still a vertex in the queue...
            while (queue.Count > 0)
            {
                //... select the first vertex and process it
                current = queue.Dequeue();
                foreach (int w in graph.OpenNeighborhood(current))
                {
                    // Enqueue all neighbors that have not been processed yet
                    if (!visited.Contains(w))
                    {
                        visited.Add(w);
                        queue.Enqueue(w);
                    }
                }
            }
            // This is the last vertex that has been processed, thus a vertex that is on the last level of the BFS search
            return current;
        }
예제 #3
0
        // Uses depth-first search to check if the graph induced by the subgraph given as a parameter is connected
        // In other words, we retreive all edges from the original graph and check the subgraph for connectedness
        public static bool Connected(Datastructures.Graph graph, BitSet subgraph)
        {
            // Vertices that are visited
            Set<int> visited = new Set<int>();

            // Stack of vertices yet to visit
            Stack<int> stack = new Stack<int>();

            // Initial vertex
            int s = subgraph.First();
            stack.Push(s);

            // Continue while there are vertices on the stack
            while (stack.Count > 0)
            {
                int v = stack.Pop();

                // If we have not encountered this vertex before, then we check for all neighbors if they are part of the subgraph
                // If a neighbor is part of the subgraph it means that we have to push it on the stack to explore it at a later stage
                if (!visited.Contains(v))
                {
                    visited.Add(v);

                    foreach (int w in graph.OpenNeighborhood(v))
                        if (subgraph.Contains(w))
                            stack.Push(w);
                }
            }

            // If we visited an equal number of vertices as there are vertices in the subgraph then the subgraph is connected
            return visited.Count == subgraph.Count;
        }
예제 #4
0
 public void Graph_with_one_edge_has_size_1()
 {
     var vertices = 1.Upto(2).ToSet();
     var edges = new Set<IDirectedEdge<int>> { new DirectedEdge<int>(1, 2) };
     var graph = new DirectedGraph<int>(vertices, edges);
     graph.Size().ShouldEqual(1);
 }
예제 #5
0
 // <summary>
 // Fixes the range of the restriction in accordance with <paramref name="range" />.
 // Member restriction must be complete for this operation.
 // </summary>
 internal override DomainBoolExpr FixRange(Set<Constant> range, MemberDomainMap memberDomainMap)
 {
     Debug.Assert(IsComplete, "Ranges are fixed only for complete scalar restrictions.");
     var newPossibleValues = memberDomainMap.GetDomain(RestrictedMemberSlot.MemberPath);
     BoolLiteral newLiteral = new ScalarRestriction(RestrictedMemberSlot, new Domain(range, newPossibleValues));
     return newLiteral.GetDomainBoolExpression(memberDomainMap);
 }
예제 #6
0
 public static List<CFGEdge> IsolateNodes(Set<CFGNode> nodes)
 {
     if (nodes.Count == 0)
     {
         return new List<CFGEdge>();
     }
     CFG graph = nodes[0].Graph;
     List<CFGEdge> removedEdges = new List<CFGEdge>();
     foreach (CFGNode node in nodes)
     {
         foreach (CFGEdge edge in graph.OutEdges(node))
         {
             if (!nodes.Contains(edge.Target))
             {
                 removedEdges.Add(edge);
             }
         }
         foreach (CFGEdge edge in graph.InEdges(node))
         {
             if (!nodes.Contains(edge.Source))
             {
                 removedEdges.Add(edge);
             }
         }
     }
     foreach (CFGEdge edge in removedEdges)
     {
         graph.RemoveEdge(edge);
     }
     return removedEdges;
 }
        public void When_Key_Exists_Append_Succeeds()
        {
            const string key = "Hello";
            const string expected = "Hello!";

            //clean up old keys
            var deleteOperation = new Delete(key, GetVBucket(), Converter, Serializer);
            IOStrategy.Execute(deleteOperation);

            deleteOperation = new Delete(key + "!", GetVBucket(),  Converter, Serializer);
            IOStrategy.Execute(deleteOperation);

            //create the key
            var set = new Set<string>(key, "Hello", GetVBucket(), Converter);
            var addResult = IOStrategy.Execute(set);
            Assert.IsTrue(addResult.Success);

            var append = new Append<string>(key, "!", Serializer, GetVBucket(), Converter);
            var result = IOStrategy.Execute(append);

            
            Assert.IsTrue(result.Success);
            Assert.AreEqual(string.Empty, result.Value);

            var get = new Get<string>(key, GetVBucket(),  Converter, Serializer);
            var getResult = IOStrategy.Execute(get);
            Assert.AreEqual(expected, getResult.Value);
        }
        private static void BFS(ref string[,] arr, AllowedCoords start)
        {

            var set = new Set<int>();
            var queue = new Queue<AllowedCoords>();
            var set = new HashSet<AllowedCoords>();
            int depth = 1;
            queue.Enqueue(start);
            set.Add(start);
            while (queue.Count > 0)
            {
                var coords = queue.Dequeue();
                if (arr[coords.Row, coords.Col] == "0")
                {
                    arr[coords.Row, coords.Col] = depth.ToString();
                }

                var neighbors = coords.GetAdjacent();
                for (int i = 0; i < neighbors.Count; i++)
                {
                    var coordinates = neighbors[i];
                    if (!set.Contains(coordinates))
                    {
                        depth++;
                        set.Add(coordinates);
                        queue.Enqueue(coordinates);
                    }
                }
                
            }
        }
예제 #9
0
 public GameDB(params Type[] types)
 {
     if (types == null || types.Length == 0)
     throw new Exception("Need at least one type");
       foreach (Type type in types)
     entities[type] = new Set<object>();
 }
예제 #10
0
		/// <summary>
		/// This is the main entry point.
		/// </summary>
		public XmlNode Merge(XmlNode newMaster, XmlNode oldConfigured, XmlDocument dest, string oldLayoutSuffix)
		{
			// As a result of LT-14650, certain bits of logic regarding copied views and duplicated nodes
			// were brought inside of the Merge.
			m_newMaster = newMaster;
			m_oldConfigured = oldConfigured;
			m_dest = dest;
			m_insertedMissing = new Set<XmlNode>();
			m_output = m_dest.CreateElement(newMaster.Name);
			m_layoutParamAttrSuffix = oldLayoutSuffix;
			CopyAttributes(m_newMaster, m_output);
			int startIndex = 0;
			BuildOldConfiguredPartsDicts();
			while (startIndex < m_newMaster.ChildNodes.Count)
			{
				XmlNode currentChild = m_newMaster.ChildNodes[startIndex];
				if (IsMergeableNode(currentChild))
				{
					int limIndex = startIndex + 1;
					while (limIndex < m_newMaster.ChildNodes.Count && m_newMaster.ChildNodes[limIndex].Name == currentChild.Name)
						limIndex++;
					CopyParts(startIndex, limIndex);
					startIndex = limIndex;
				}
				else
				{
					CopyToOutput(currentChild);
					startIndex++;
				}
			}
			return m_output;
		}
        public void Test_Timed_Execution()
        {
            var converter = new DefaultConverter();
            var transcoder = new DefaultTranscoder(converter);
            var vbucket = GetVBucket();
            int n = 1000; //set to a higher # if needed

            using (new OperationTimer())
            {
                var key = string.Format("key{0}", 111);

                for (var i = 0; i < n; i++)
                {
                    var set = new Set<int?>(key, 111, vbucket, transcoder, OperationLifespanTimeout);
                    var get = new Get<int?>(key, vbucket, transcoder, OperationLifespanTimeout);

                    var result = IOService.Execute(set);
                    Assert.IsTrue(result.Success);

                    var result1 = IOService.Execute(get);
                    Assert.IsTrue(result1.Success);
                    Assert.AreEqual(111, result1.Value);
                }
            }
        }
예제 #12
0
    public static Dictionary<CFGBlock, List<CFGBlock>> ComputeContainingLoopMap(ICFG cfg)
    {
      Contract.Requires(cfg != null);
      Contract.Ensures(Contract.Result<Dictionary<CFGBlock, List<CFGBlock>>>() != null);

      var result = new Dictionary<CFGBlock, List<CFGBlock>>();
      var visitedSubroutines = new Set<int>();
      var pendingSubroutines = new Stack<Subroutine>();
      var pendingAPCs = new Stack<APC>();

      var graph = cfg.AsBackwardGraph(includeExceptionEdges:false, skipContracts:true);
      foreach (var loophead in cfg.LoopHeads)
      {
        // push back-edge sources
        var loopPC = new APC(loophead, 0, null);
        foreach (var pred in cfg.Predecessors(loopPC))
        {
          if (cfg.IsForwardBackEdge(pred, loopPC))
          {
            var normalizedPred = new APC(pred.Block, 0, null);
            pendingAPCs.Push(normalizedPred);
          }
        }
        var visit = new DepthFirst.Visitor<APC, Unit>(graph,
          (APC pc) =>
          {
            if (pc.SubroutineContext != null)
            {
              // push continuation PC
              pendingAPCs.Push(new APC(pc.SubroutineContext.Head.One, 0, null));
              if (visitedSubroutines.AddQ(pc.Block.Subroutine.Id))
              {
                pendingSubroutines.Push(pc.Block.Subroutine);
              }
              return false; // stop exploration
            }
            return !pc.Equals(loopPC);
          });

        while (pendingAPCs.Count > 0)
        {
          var root = pendingAPCs.Pop();
          visit.VisitSubGraphNonRecursive(root);

          while (pendingSubroutines.Count > 0)
          {
            var sub = pendingSubroutines.Pop();
            pendingAPCs.Push(new APC(sub.Exit, 0, null));
          }
        }

        foreach (var visited in visit.Visited)
        {
          if (visited.SubroutineContext != null) continue; // ignore non-primary pcs
          MaterializeContainingLoop(result, visited.Block).AssumeNotNull().Add(loophead);
        }
      }

      return result;
    }
예제 #13
0
        public TemplateOptions()
        {
            Usings = new Set<string>(new[] { "System", "System.IO", "System.Web", "NHaml", "NHaml.Utils", "System.Collections.Generic" });
            References = new Set<string>(new[]
            {
                typeof(TemplateEngine).Assembly.Location, // NHaml
                typeof(INotifyPropertyChanged).Assembly.Location, // System
                typeof(HttpUtility).Assembly.Location // System.Web
            });
            AutoClosingTags = new Set<string>(new[] { "META", "IMG", "LINK", "BR", "HR", "INPUT" });
            ReferencedTypeHandles = new List<RuntimeTypeHandle>();
            MarkupRules = new List<MarkupRule>();
            _indentSize = 2;
            _templateBaseType = typeof(Template);
            _templateCompiler = new CSharp3TemplateCompiler();
            TemplateContentProvider = new FileTemplateContentProvider();

            AddRule(new EofMarkupRule());
            AddRule(new MetaMarkupRule());
            AddRule(new DocTypeMarkupRule());
            AddRule(new TagMarkupRule());
            AddRule(new ClassMarkupRule());
            AddRule(new IdMarkupRule());
            AddRule(new EvalMarkupRule());
            AddRule(new EncodedEvalMarkupRule());
            AddRule(new SilentEvalMarkupRule());
            AddRule(new PreambleMarkupRule());
            AddRule(new CommentMarkupRule());
            AddRule(new EscapeMarkupRule());
            AddRule(new PartialMarkupRule());
            AddRule(new NotEncodedEvalMarkupRule());
        }
 public ClusterAlgorithm(Set set, Proximity diss)
 {
     if (set == null || diss == null)
         throw new ArgumentNullException("Parametro Incorrecto en el constructor de la clase ClusterAlgorithm");
     this.Set = set;
     this.Proximity = diss;
 }
예제 #15
0
        /// <summary>
        ///  This function takes a set of peaks, a lookup mass, and 
        ///  finds the closest peak with in a certain tolerance. If 
        ///  multiple peaks exists with in the window, most closest peak
        ///  is selected
        /// </summary>
        /// <param name="peaks">A spectrum</param>
        /// <param name="mz">Look up m/z</param>
        /// <param name="tolerance">Mass tolerance for look-up</param>
        /// <returns>Peak if found</returns>
        public static Peak findClose(Set<Peak> peaks, double mz, double tolerance)
        {
            Set<Peak>.Enumerator cur, min, max;

            min = peaks.LowerBound(new Peak(mz - tolerance));
            max = peaks.LowerBound(new Peak(mz + tolerance));
            if (!min.IsValid && !max.IsValid)
                return null;
            if (!min.IsValid && max.IsValid)
                return max.Current;
            if (min.IsValid && !max.IsValid)
                return min.Current;
            if (min.Current == max.Current)
                return null;

            // If we found multiple matching peaks,
            // return the closest peak.
            Peak best = min.Current;

            //find the peak closest to the desired mz
            double minDiff = Math.Abs(mz - best.mz);
            for (cur = min; cur.Current != max.Current; cur.MoveNext())
            {
                double curDiff = Math.Abs(mz - cur.Current.mz);
                if (curDiff < minDiff)
                {
                    minDiff = curDiff;
                    best = cur.Current;
                }
            }
            return best;
        }
예제 #16
0
		public void OnExclude ()
		{
			//if all of the selection is already checked, then toggle checks them off
			//else it turns them on. hence we need to find if they're all checked,
			bool allChecked = true;
			foreach (ITreeNavigator node in CurrentNodes) {
				ProjectFile file = (ProjectFile) node.DataItem;
				if (file.Project != null) {
					MakefileData data = file.Project.ExtendedProperties [infoProperty] as MakefileData;
					if (data != null && data.IsFileIntegrationEnabled (file.BuildAction)) {
						if (data.IsFileExcluded (file.FilePath)) {
							allChecked = false;
							break;
						}
					}
				}
			}
			
			Set<SolutionEntityItem> projects = new Set<SolutionEntityItem> ();
			
			foreach (ITreeNavigator node in CurrentNodes) {
				ProjectFile file = (ProjectFile) node.DataItem;
				if (file.Project != null) {
					projects.Add (file.Project);
					MakefileData data = file.Project.ExtendedProperties [infoProperty] as MakefileData;
					if (data != null && data.IntegrationEnabled) {
						data.SetFileExcluded (file.FilePath, allChecked);
					}
				}
			}
				
			IdeApp.ProjectOperations.Save (projects);
		}
예제 #17
0
        public void AddColumns()
        {
            Column[] columns = new Column[] {
                new Column("Name", ColumnType.String),
                new Column("Age", ColumnType.Integer)
            };

            Set set = new Set(columns);

            NameValues values = new NameValues();
            values.Add("Name", "Adam");
            values.Add("Age", 800);

            set = set.AddTuple(values);

            Column[] newcolumns = new Column[] {
                new Column("Height", ColumnType.Integer),
                new Column("Weight", ColumnType.Integer)
            };

            var result = set.AddColumns(newcolumns);

            Assert.AreNotEqual(result, set);
            Assert.IsNotNull(result.Tuples);
            Assert.AreEqual(1, result.Tuples.Count());
            Assert.AreEqual(4, result.Columns.Count());

            Tuple tuple = result.Tuples.First();
            Assert.AreEqual("Adam", tuple[0]);
            Assert.AreEqual(800, tuple[1]);
            Assert.IsNull(tuple[2]);
            Assert.IsNull(tuple[3]);
        }
예제 #18
0
파일: Set.cs 프로젝트: mstaessen/fluorinefx
 /// <summary>
 /// Returns difference of two sets.
 /// </summary>
 /// <remarks>
 /// Difference contains elements present in first set, but not in the second.<br/>
 /// Difference is not symmetric. Difference(a,b) is not equal to Difference(b,a)
 /// </remarks>
 public static Set Difference(Set a, Set b)
 {
     a.CheckComparer(b);
     var result = new Set(a.Comparer);
     SetOp.Difference(a, b, a.Comparer, new Inserter(result));
     return result;
 }
예제 #19
0
 public bool Remove(string url, ArrayList<ulong> hashCodes, bool fullPath, bool unique, bool decDocCount)
 {
     Set<ulong> hashCodesUnique = new Set<ulong>(hashCodes);
     int numDomainParts, numTldParts;
     ArrayList<string> path = GetPath(url, out numDomainParts, out numTldParts, fullPath);
     if (path == null) { return false; }
     Node node = mRoot;
     if (decDocCount) { node.mCount--; }
     if (unique) { node.mHashCodes.RemoveRange(hashCodesUnique); }
     else { node.mHashCodes.RemoveRange(hashCodes); }
     if (node.mCount == 0) // cut the branch?
     {
         node.mChildren.Clear();
         return true;
     }
     for (int i = 0; i < path.Count; i++)
     {
         Node child = node.GetChildNode(path[i]);
         if (child == null) { return false; }
         if (decDocCount) { child.mCount--; }
         if (unique) { child.mHashCodes.RemoveRange(hashCodesUnique); }
         else { child.mHashCodes.RemoveRange(hashCodes); }
         if (child.mCount == 0) // cut the branch?
         {
             child.mChildren.Clear();
             return true;
         }
         node = child;
     }
     return true;
 }
        /// <summary>
        /// some other jumpers may stop being ones if the jump 
        /// was just in to their destination layer, so before the actual 
        /// jump we have to recheck if the jump makes sense
        /// 
        /// </summary>
        /// <param name="jumperLayer">old layer of jumper</param>
        /// <param name="jumper"></param>
        void UpdateRegionsForPossibleJumpersAndInsertJumpers(int jumperLayer, int jumper) {
            Set<int> neighborPossibleJumpers = new Set<int>();
            //update possible jumpers neighbors
            foreach (int v in new Pred(dag, jumper))
                if (IsJumper(v)) {
                    this.CalculateRegionAndInsertJumper(v);
                    neighborPossibleJumpers.Insert(v);
                }

            foreach (int v in new Succ(dag, jumper))
                if (IsJumper(v)) {
                    this.CalculateRegionAndInsertJumper(v);
                    neighborPossibleJumpers.Insert(v);
                }

            List<int> possibleJumpersToUpdate = new List<int>();

            foreach (KeyValuePair<int, IntPair> kv in this.possibleJumperFeasibleIntervals) {
                if (!neighborPossibleJumpers.Contains(kv.Key))
                    if (kv.Value.x > jumperLayer && kv.Value.y < jumperLayer)
                        possibleJumpersToUpdate.Add(kv.Key);
            }

            foreach (int v in possibleJumpersToUpdate)
                this.CalculateRegionAndInsertJumper(v);
        }
 internal PreGraph(EdgeGeometry[] egs, Set<ICurve> nodeBoundaries) {
     edgeGeometries = new List<EdgeGeometry>(egs);
     this.nodeBoundaries = new Set<ICurve>(nodeBoundaries);
     boundingBox = Rectangle.CreateAnEmptyBox();
     foreach (var curve in nodeBoundaries)
         boundingBox.Add(curve.BoundingBox);
 }
예제 #22
0
 public NameSupply(IImSet<string> globals, NameSupply parent)
 {
     this.globals = globals ?? Constants.EmptyStringSet;
     boundInThisScope = new Set<string>();
     boundInChildScope = new Set<string>();
     this.parent = parent;
 }
예제 #23
0
        public void SymmetricTest()
        {
            var a = new Set<int>(1, 2, 3);
            var b = new Set<int>(2, 3, 4);

            Console.WriteLine(a.Symmetric(b));
        }
예제 #24
0
        public void AddSets()
        {
            var a = new Set<int>(1, 2, 3, 4, 5);
            var b = new Set<int>(6, 7, 8, 9, 10);

            Console.WriteLine(a.Add(b).ToString());
        }
예제 #25
0
        public void IntersectionTest()
        {
            var a = new Set<int>(1, 2, 3);
            var b = new Set<int>(2, 3, 4);

            Console.WriteLine(a.Intersection(b));
        }
예제 #26
0
 public void TestDirectedGraphEmptyHasEdgeTrue()
 {
     var vertices = 1.Upto(3).ToSet();
     var edges = new Set<IDirectedEdge<int>> { new DirectedEdge<int>(1, 2) };
     var graph = new DirectedGraph<int>(vertices, edges);
     graph.HasEdge(1, 2).ShouldBeTrue();
 }
예제 #27
0
        /// <summary>
        /// Given a Set, produces a CSS property. 
        /// Implementers can override this method to customize support for CSS properties given a Set.
        /// For example if you want a Setter of "Foo" to produce a CSS property "Bar", you can filter it here.
        /// You must call this methods for Setter properties you don't wish to filter, so that the default implementation
        /// can generate CSS.
        /// </summary>
        /// <param name="set">The target Set.</param>
        /// <returns>The CSS property, in string form.</returns>
        public virtual string TransformSet(Set set)
        {
            // TODO: Some more type checking. I really don't like this entire method.
            switch (set.Property.ToLower())
            {
                case "width":
                    int widthResult;

                    if (int.TryParse(set.To, out widthResult))
                        return string.Format("width: {0}px;", widthResult);

                    break;
                case "height":
                    int heightResult;

                    if (int.TryParse(set.To, out heightResult))
                        return string.Format("height: {0}px;", heightResult);

                    break;
                case "background":
                    return string.Format("background-color: {0};", set.To);

                case "foreground":
                    return string.Format("color: {0};", set.To);

                case "padding":
                    return string.Format("padding: {0}px;", set.To);

                case "margin":
                    return string.Format("margin: {0}px;", set.To);

            }

            return string.Empty;
        }
예제 #28
0
파일: Credits.cs 프로젝트: juhan/NModel
 public static void Res(int m, int c)
 {
     for (int i = 1; i <= c; i++)
     window = window.Add(maxId + i);
       requests = requests.RemoveKey(m);
       maxId = maxId + c;
 }
예제 #29
0
 public void Graph_with_one_vertex_has_order_1()
 {
     var vertices = 1.WrapInList().ToSet();
     var edges = new Set<IDirectedEdge<int>>();
     var graph = new DirectedGraph<int>(vertices, edges);
     graph.Order().ShouldEqual(1);
 }
예제 #30
0
        public static ChartSet PopulateChartSet(Set set, IEnumerable<int> monthsInSetsData, IEnumerable<int> weeksInSetsData, DateTime startDate, DateTime endDate)
        {
            ChartSet chartSet = new ChartSet();

            chartSet.Name = set.Name;
            chartSet.Id = set.Id;
            //#######################################################################
            // Start Building the set month statistics (NOTICE: that the calculation is intended to calculate by aggregating all activities by month regardless of the year the month belongs to)
            //#######################################################################
            chartSet.ChartSetMonthsData = new List<ChartSetMonthData>();
            foreach (var month in monthsInSetsData)
            {
                chartSet.ChartSetMonthsData.Add(new ChartSetMonthData
                {
                    ActivityCount = set.Exercises.Where(o => o.ExerciseRecords.Any(m => m.Date.Month == month)).Count(),
                    StartDate = DateTime.Now.StartOfMonth(month),
                    EndDate = DateTime.Now.EndOfMonth(month),
                    MonthNumber = month
                });
            }
            //chartSet.ChartSetMonthsData.OrderBy(o => o.MonthNumber);
            //#######################################################################

            //#######################################################################
            // Start Building the set weeks statistics (NOTICE: that the calculation is intended to calculate by aggregating all activities by week regardless of the year the week belongs to)
            //#######################################################################
            chartSet.ChartSetWeeksData = new List<ChartSetWeekData>();
            foreach (var week in weeksInSetsData)
            {
                //var er = set.Exercises.Select(o => o.ExerciseRecords.Where(m => m.Date.WeekOfDate() == week && m.Date >= startDate && m.Date <= endDate)).ElementAtOrDefault(0);
                var er = set.Exercises.Select(o => o.ExerciseRecords.FirstOrDefault( m => m.Date.WeekOfDate() == week)).ElementAtOrDefault(0);

                chartSet.ChartSetWeeksData.Add(new ChartSetWeekData
                {
                    ActivityCount = set.Exercises.Where(o => o.ExerciseRecords.Any(m => m.Date.WeekOfDate() == week)).Count(),
                    StartDate = DateTimeExtensions.StartOfWeekNumber(er != null ? er.Date.Year : DateTime.Now.Year, week),
                    EndDate = DateTimeExtensions.EndOfWeekNumber(er != null ? er.Date.Year : DateTime.Now.Year, week),
                    WeekNumber = week
                });
            }
            //chartSet.ChartSetWeeksData.OrderBy(o => o.WeekNumber);
            chartSet.TotalActivityCount = chartSet.ChartSetMonthsData.Sum(ac => ac.ActivityCount);
            //#######################################################################

            //#######################################################################
            // Start creating chart data for excercises
            //#######################################################################
            chartSet.ChartSetExercises = new List<ChartExercise>();

            foreach (var exercise in set.Exercises)
            {
                ChartExercise chartExercise = ChartsHelper.PopulateChartExercise(exercise, monthsInSetsData, weeksInSetsData, startDate, endDate);
                // Final step is to add the loaded exercise data into the corresponding set that is to be returned to the client
                chartSet.ChartSetExercises.Add(chartExercise);
            }
            //#######################################################################

            // Final step is to add the loaded set data that is to be returned to the client
            return (chartSet);
        }
예제 #31
0
 public Task <User> FindByUserNameAsync(string username)
 {
     return(Set.FirstOrDefaultAsync(x => x.UserName == username));
 }
예제 #32
0
        private void Compile(
            out List <ProviderCommandInfo> providerCommands,
            out ColumnMap resultColumnMap,
            out int columnCount,
            out Set <EntitySet> entitySets)
        {
            this.Initialize();
            string empty1  = string.Empty;
            string empty2  = string.Empty;
            string empty3  = string.Empty;
            string empty4  = string.Empty;
            string empty5  = string.Empty;
            string empty6  = string.Empty;
            string empty7  = string.Empty;
            string empty8  = string.Empty;
            string empty9  = string.Empty;
            string empty10 = string.Empty;
            string empty11 = string.Empty;
            string empty12 = string.Empty;
            string empty13 = string.Empty;
            string empty14 = string.Empty;
            string empty15 = string.Empty;

            this.m_neededPhases = 593;
            this.SwitchToPhase(PlanCompilerPhase.PreProcessor);
            StructuredTypeInfo typeInfo;
            Dictionary <EdmFunction, EdmProperty[]> tvfResultKeys;

            PreProcessor.Process(this, out typeInfo, out tvfResultKeys);
            entitySets = typeInfo.GetEntitySets();
            if (this.IsPhaseNeeded(PlanCompilerPhase.AggregatePushdown))
            {
                this.SwitchToPhase(PlanCompilerPhase.AggregatePushdown);
                AggregatePushdown.Process(this);
            }
            if (this.IsPhaseNeeded(PlanCompilerPhase.Normalization))
            {
                this.SwitchToPhase(PlanCompilerPhase.Normalization);
                Normalizer.Process(this);
            }
            if (this.IsPhaseNeeded(PlanCompilerPhase.NTE))
            {
                this.SwitchToPhase(PlanCompilerPhase.NTE);
                NominalTypeEliminator.Process(this, typeInfo, tvfResultKeys);
            }
            if (this.IsPhaseNeeded(PlanCompilerPhase.ProjectionPruning))
            {
                this.SwitchToPhase(PlanCompilerPhase.ProjectionPruning);
                ProjectionPruner.Process(this);
            }
            if (this.IsPhaseNeeded(PlanCompilerPhase.NestPullup))
            {
                this.SwitchToPhase(PlanCompilerPhase.NestPullup);
                NestPullup.Process(this);
                this.SwitchToPhase(PlanCompilerPhase.ProjectionPruning);
                ProjectionPruner.Process(this);
            }
            if (this.IsPhaseNeeded(PlanCompilerPhase.Transformations) && this.ApplyTransformations(ref empty8, TransformationRulesGroup.All))
            {
                this.SwitchToPhase(PlanCompilerPhase.ProjectionPruning);
                ProjectionPruner.Process(this);
                this.ApplyTransformations(ref empty10, TransformationRulesGroup.Project);
            }
            if (this.IsPhaseNeeded(PlanCompilerPhase.NullSemantics))
            {
                this.SwitchToPhase(PlanCompilerPhase.NullSemantics);
                if (!this.m_ctree.UseDatabaseNullSemantics && NullSemantics.Process(this.Command))
                {
                    this.ApplyTransformations(ref empty12, TransformationRulesGroup.NullSemantics);
                }
            }
            if (this.IsPhaseNeeded(PlanCompilerPhase.JoinElimination))
            {
                for (int index = 0; index < 10; ++index)
                {
                    this.SwitchToPhase(PlanCompilerPhase.JoinElimination);
                    if (JoinElimination.Process(this) || this.TransformationsDeferred)
                    {
                        this.TransformationsDeferred = false;
                        this.ApplyTransformations(ref empty14, TransformationRulesGroup.PostJoinElimination);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            this.SwitchToPhase(PlanCompilerPhase.CodeGen);
            CodeGen.Process(this, out providerCommands, out resultColumnMap, out columnCount);
        }
예제 #33
0
 public Spot FindClosestSpot(Location l_d, Set <Spot> Not)
 {
     return(FindClosestSpot(l_d, 30.0f, Not));
 }
예제 #34
0
        public void SymbolResolutionTest()
        {
            ExpressionScope ast;

            //
            // Test schema. "Set A" -> b/c -> "Set B" -> d/i -> "Double"/"Integer"
            //
            SetTop top        = new SetTop("Top");
            Set    setInteger = top.GetPrimitive("Integer");
            Set    setDouble  = top.GetPrimitive("Double");

            Set setA = new Set("Set A");

            top.Root.AddSubset(setA);

            Set setB = new Set("Set B");

            top.Root.AddSubset(setB);

            Dim dimB = top.CreateColumn("b", setA, setB, true);

            dimB.Add();

            Dim dimC = top.CreateColumn("Function c", setA, setB, true);

            dimC.Add();

            Dim dimD = top.CreateColumn("d", setB, setDouble, true);

            dimD.Add();

            Dim dimI = top.CreateColumn("i", setB, setInteger, true);

            dimI.Add();

            //
            // Test symbol resolution, type resolution and validation
            //
            string functionStr = "[Set B] [Function c]([Set A] this, [Integer] [param 2], [Set B] [param 3]) { return b().d() * this.b().d() + [param 2] / [param 3] <- b(); } ";

            ast = (ExpressionScope)BuildFunction(functionStr);

            // Bind ast to the real schema
            ast.ResolveFunction(top);

            Assert.AreEqual(ast.Input.OutputSet, setA);
            Assert.AreEqual(ast.Operands[0].OutputSet, setInteger);
            Assert.AreEqual(ast.Operands[1].OutputSet, setB);

            Assert.AreEqual(ast.OutputSet, setB);
            Assert.AreEqual(ast.Dimension, dimC);

            // Resolve all symboles used in the function definition
            ast.Resolve();

            Assert.AreEqual(ast.Statements[0].Input.Operands[0].Operands[0].OutputSet, setDouble);
            Assert.AreEqual(ast.Statements[0].Input.Operands[0].Operands[0].Input.OutputSet, setB);
            Assert.AreEqual(ast.Statements[0].Input.Operands[0].Operands[0].Input.Input.OutputSet, setA);

            Assert.AreEqual(ast.Statements[0].Input.Operands[0].Operands[1].Input.Input.OutputSet, setA);

            Assert.AreEqual(ast.Statements[0].Input.Operands[1].Operands[0].OutputSet, setInteger);

            Assert.AreEqual(ast.Statements[0].Input.Operands[1].Operands[1].OutputSet, setA);
            Assert.AreEqual(ast.Statements[0].Input.Operands[1].Operands[1].Input.OutputSet, setB);
        }
 /// <summary>
 /// Tworzy enumerator nad wêz³em w ramach kompozytu.
 /// </summary>
 /// <param name="node">wêze³ do przechodzenia</param>
 /// <param name="visited">zbiór do zapisywania odwiedzonych wêz³ów</param>
 public ComponentEnumerator(Object head, Set visited)
 {
     _head    = head;
     _visited = visited;
 }
예제 #36
0
 public SetViewModel()
 {
     this.set = new Set();
     this.CollectionChanged     += ViewModelCollectionChanged;
     this.set.CollectionChanged += ModelCollectionChanged;
 }
예제 #37
0
 public Task <User> FindByUserNameAsync(System.Threading.CancellationToken cancellationToken, string username)
 {
     return(Set.FirstOrDefaultAsync(x => x.UserName == username, cancellationToken));
 }
예제 #38
0
파일: Mul.cs 프로젝트: genveir/Advent
 public Mul(Set left, Set right) : base(left, right)
 {
 }
예제 #39
0
        internal static void AddTransitions(FSM fsm, int state, CodeStatementCollection stmts, Set <int> visited)
        {
            if (visited.Contains(state))
            {
                return;
            }
            else
            {
                visited.Add(state);
            }

            Transitions currTrans = null;

            fsm.Trans.TryGetValue(state, out currTrans);
            if (currTrans == null || currTrans.Count == 0)
            {
                return;
            }

            CreateAddTransitionStmts(fsm, stmts, state, currTrans, visited);
        }
예제 #40
0
 public User FindByUserName(string username)
 {
     return(Set.FirstOrDefault(x => x.UserName == username));
 }
        private bool CheckIfConstraintMappedToForeignKeyAssociation(
            QueryRewriter childRewriter, Set <Cell> cells)
        {
            var childContext = childRewriter.ViewgenContext;

            //First collect the sets of properties that the principal and dependant ends of this FK
            //are mapped to in the Edm side.
            var childPropertiesSet  = new List <Set <EdmProperty> >();
            var parentPropertiesSet = new List <Set <EdmProperty> >();

            foreach (var cell in cells)
            {
                if (cell.CQuery.Extent.BuiltInTypeKind
                    != BuiltInTypeKind.AssociationSet)
                {
                    var childProperties = cell.GetCSlotsForTableColumns(ChildColumns);
                    if ((childProperties != null) &&
                        (childProperties.Count != 0))
                    {
                        childPropertiesSet.Add(childProperties);
                    }
                    var parentProperties = cell.GetCSlotsForTableColumns(ParentColumns);
                    if ((parentProperties != null) &&
                        (parentProperties.Count != 0))
                    {
                        parentPropertiesSet.Add(parentProperties);
                    }
                }
            }

            //Now Check if the properties on the Edm side are connected via an FK relationship.
            if ((childPropertiesSet.Count != 0) &&
                (parentPropertiesSet.Count != 0))
            {
                var foreignKeyAssociations =
                    childContext.EntityContainerMapping.EdmEntityContainer.BaseEntitySets.OfType <AssociationSet>().Where(
                        it => it.ElementType.IsForeignKey).Select(it => it.ElementType);
                foreach (var association in foreignKeyAssociations)
                {
                    var refConstraint = association.ReferentialConstraints.FirstOrDefault();
                    //We need to check to see if the dependent properties that were mapped from S side are present as
                    //dependant properties of this ref constraint on the Edm side. We need to do the same for principal side but
                    //we can not enforce equality since the order of the properties participating in the constraint on the S side and
                    //C side could be different. This is OK as long as they are mapped appropriately. We also can not use Existance as a sufficient
                    //condition since it will allow invalid mapping where FK columns could have been flipped when mapping to the Edm side. So
                    //we make sure that the index of the properties in the principal and dependant are same on the Edm side even if they are in
                    //different order for ref constraints for Edm and store side.
                    var childRefPropertiesCollection =
                        childPropertiesSet.Where(it => it.SetEquals(new Set <EdmProperty>(refConstraint.ToProperties)));
                    var parentRefPropertiesCollection =
                        parentPropertiesSet.Where(it => it.SetEquals(new Set <EdmProperty>(refConstraint.FromProperties)));
                    if ((childRefPropertiesCollection.Count() != 0 && parentRefPropertiesCollection.Count() != 0))
                    {
                        foreach (var parentRefProperties in parentRefPropertiesCollection)
                        {
                            var parentIndexes = GetPropertyIndexes(parentRefProperties, refConstraint.FromProperties);
                            foreach (var childRefProperties in childRefPropertiesCollection)
                            {
                                var childIndexes = GetPropertyIndexes(childRefProperties, refConstraint.ToProperties);

                                if (childIndexes.SequenceEqual(parentIndexes))
                                {
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }
            return(false);
        }
예제 #42
0
        private void Compile(
            out List <ProviderCommandInfo> providerCommands, out ColumnMap resultColumnMap, out int columnCount,
            out Set <md.EntitySet> entitySets)
        {
            Initialize(); // initialize the ITree

            var beforePreProcessor      = String.Empty;
            var beforeAggregatePushdown = String.Empty;
            var beforeNormalization     = String.Empty;
            var beforeNTE = String.Empty;
            var beforeProjectionPruning1   = String.Empty;
            var beforeNestPullup           = String.Empty;
            var beforeProjectionPruning2   = String.Empty;
            var beforeTransformationRules1 = String.Empty;
            var beforeProjectionPruning3   = String.Empty;
            var beforeTransformationRules2 = String.Empty;
            var beforeNullSemantics        = String.Empty;
            var beforeTransformationRules3 = String.Empty;
            var beforeJoinElimination      = String.Empty;
            var beforeTransformationRules4 = String.Empty;
            var beforeCodeGen = String.Empty;

            //
            // We always need the pre-processor and the codegen phases.
            // It is generally a good thing to run through the transformation rules, and
            // the projection pruning phases.
            // The "optional" phases are AggregatePushdown, Normalization, NTE, NestPullup and JoinElimination
            //
            m_neededPhases = (1 << (int)PlanCompilerPhase.PreProcessor) |
                             // (1 << (int)PlanCompilerPhase.AggregatePushdown) |
                             // (1 << (int)PlanCompilerPhase.Normalization) |
                             // (1 << (int)PlanCompilerPhase.NTE) |
                             (1 << (int)PlanCompilerPhase.ProjectionPruning) |
                             // (1 << (int)PlanCompilerPhase.NestPullup) |
                             (1 << (int)PlanCompilerPhase.Transformations) |
                             // (1 << (int)PlanCompilerPhase.JoinElimination) |
                             // (1 << (int)PlanCompilerPhase.NullSemantics) |
                             (1 << (int)PlanCompilerPhase.CodeGen);

            // Perform any necessary preprocessing
            StructuredTypeInfo typeInfo;
            Dictionary <md.EdmFunction, md.EdmProperty[]> tvfResultKeys;

            beforePreProcessor = SwitchToPhase(PlanCompilerPhase.PreProcessor);
            PreProcessor.Process(this, out typeInfo, out tvfResultKeys);
            entitySets = typeInfo.GetEntitySets();

            if (IsPhaseNeeded(PlanCompilerPhase.AggregatePushdown))
            {
                beforeAggregatePushdown = SwitchToPhase(PlanCompilerPhase.AggregatePushdown);
                AggregatePushdown.Process(this);
            }

            if (IsPhaseNeeded(PlanCompilerPhase.Normalization))
            {
                beforeNormalization = SwitchToPhase(PlanCompilerPhase.Normalization);
                Normalizer.Process(this);
            }

            // Eliminate "structured" types.
            if (IsPhaseNeeded(PlanCompilerPhase.NTE))
            {
                beforeNTE = SwitchToPhase(PlanCompilerPhase.NTE);
                NominalTypeEliminator.Process(this, typeInfo, tvfResultKeys);
            }

            // Projection pruning - eliminate unreferenced expressions
            if (IsPhaseNeeded(PlanCompilerPhase.ProjectionPruning))
            {
                beforeProjectionPruning1 = SwitchToPhase(PlanCompilerPhase.ProjectionPruning);
                ProjectionPruner.Process(this);
            }

            // Nest Pull-up on the ITree
            if (IsPhaseNeeded(PlanCompilerPhase.NestPullup))
            {
                beforeNestPullup = SwitchToPhase(PlanCompilerPhase.NestPullup);

                NestPullup.Process(this);

                //If we do Nest Pull-up, we should again do projection pruning
                beforeProjectionPruning2 = SwitchToPhase(PlanCompilerPhase.ProjectionPruning);
                ProjectionPruner.Process(this);
            }

            // Run transformations on the tree
            if (IsPhaseNeeded(PlanCompilerPhase.Transformations))
            {
                var projectionPrunningNeeded = ApplyTransformations(ref beforeTransformationRules1, TransformationRulesGroup.All);

                if (projectionPrunningNeeded)
                {
                    beforeProjectionPruning3 = SwitchToPhase(PlanCompilerPhase.ProjectionPruning);
                    ProjectionPruner.Process(this);
                    ApplyTransformations(ref beforeTransformationRules2, TransformationRulesGroup.Project);
                }
            }

            if (IsPhaseNeeded(PlanCompilerPhase.NullSemantics))
            {
                beforeNullSemantics = SwitchToPhase(PlanCompilerPhase.NullSemantics);

                if (!m_ctree.UseDatabaseNullSemantics && NullSemantics.Process(Command))
                {
                    ApplyTransformations(ref beforeTransformationRules3, TransformationRulesGroup.NullSemantics);
                }
            }

            // Join elimination
            if (IsPhaseNeeded(PlanCompilerPhase.JoinElimination))
            {
                const int maxIterations = 10;

                for (var i = 0; i < maxIterations; i++)
                {
                    beforeJoinElimination = SwitchToPhase(PlanCompilerPhase.JoinElimination);

                    var modified = JoinElimination.Process(this);

                    if (modified || TransformationsDeferred)
                    {
                        TransformationsDeferred = false;

                        ApplyTransformations(ref beforeTransformationRules4, TransformationRulesGroup.PostJoinElimination);
                    }
                    else
                    {
                        break;
                    }
                }
            }

            // Code generation
            beforeCodeGen = SwitchToPhase(PlanCompilerPhase.CodeGen);
            CodeGen.Process(this, out providerCommands, out resultColumnMap, out columnCount);

#if DEBUG
            // GC.KeepAlive makes FxCop Grumpy.
            var size = beforePreProcessor.Length;
            size = beforeAggregatePushdown.Length;
            size = beforeNormalization.Length;
            size = beforeNTE.Length;
            size = beforeProjectionPruning1.Length;
            size = beforeNestPullup.Length;
            size = beforeProjectionPruning2.Length;
            size = beforeTransformationRules1.Length;
            size = beforeProjectionPruning3.Length;
            size = beforeTransformationRules2.Length;
            size = beforeNullSemantics.Length;
            size = beforeTransformationRules3.Length;
            size = beforeJoinElimination.Length;
            size = beforeTransformationRules4.Length;
            size = beforeCodeGen.Length;
#endif
        }
        // effects: Checks that this foreign key constraints for all the
        // tables are being ensured on the C-side as well. If not, adds
        // errors to the errorLog
        internal void CheckConstraint(
            Set <Cell> cells, QueryRewriter childRewriter, QueryRewriter parentRewriter,
            ErrorLog errorLog, ConfigViewGenerator config)
        {
            if (IsConstraintRelevantForCells(cells) == false)
            {
                // if the constraint does not deal with any cell in this group, ignore it
                return;
            }

            if (config.IsNormalTracing)
            {
                Trace.WriteLine(String.Empty);
                Trace.WriteLine(String.Empty);
                Trace.Write("Checking: ");
                Trace.WriteLine(this);
            }

            if (childRewriter == null &&
                parentRewriter == null)
            {
                // Neither table is mapped - so we are fine
                return;
            }

            // If the child table has not been mapped, we used to say that we
            // are fine. However, if we have SPerson(pid) and SAddress(aid,
            // pid), where pid is an FK into SPerson, we are in trouble if
            // SAddress is not mapped - SPerson could get deleted. So we
            // check for it as well
            // if the parent table is not mapped, we also have a problem

            if (childRewriter == null)
            {
                var message = Strings.ViewGen_Foreign_Key_Missing_Table_Mapping(
                    ToUserString(), ChildTable.Name);
                // Get the cells from the parent table
                var record = new ErrorLog.Record(
                    ViewGenErrorCode.ForeignKeyMissingTableMapping, message, parentRewriter.UsedCells, String.Empty);
                errorLog.AddEntry(record);
                return;
            }

            if (parentRewriter == null)
            {
                var message = Strings.ViewGen_Foreign_Key_Missing_Table_Mapping(
                    ToUserString(), ParentTable.Name);
                // Get the cells from the child table
                var record = new ErrorLog.Record(
                    ViewGenErrorCode.ForeignKeyMissingTableMapping, message, childRewriter.UsedCells, String.Empty);
                errorLog.AddEntry(record);
                return;
            }

            // Note: we do not check if the parent columns correspond to the
            // table's keys - metadata checks for that

            //First check if the FK is covered by Foreign Key Association
            //If we find this, we don't need to check for independent associations. If user maps the Fk to both FK and independent associations,
            //the regular round tripping validation will catch the error.
            if (CheckIfConstraintMappedToForeignKeyAssociation(childRewriter, cells))
            {
                return;
            }

            // Check if the foreign key in the child table corresponds to the primary key, i.e., if
            // the foreign key (e.g., pid, pid2) is a superset of the actual key members (e.g., pid), it means
            // that the foreign key is also the primary key for this table -- so we can propagate the queries upto C-Space
            // rather than doing the cell check

            var initialErrorLogSize = errorLog.Count;

            if (IsForeignKeySuperSetOfPrimaryKeyInChildTable())
            {
                GuaranteeForeignKeyConstraintInCSpace(childRewriter, parentRewriter, errorLog);
            }
            else
            {
                GuaranteeMappedRelationshipForForeignKey(childRewriter, parentRewriter, cells, errorLog, config);
            }

            if (initialErrorLogSize == errorLog.Count)
            {
                // Check if the order of columns in foreign key correponds to the
                // mappings in m_cellGroup, e.g., if <pid1, pid2> in SAddress is
                // a foreign key into <pid1, pid2> of the SPerson table, make
                // sure that this order is preserved through the mappings in m_cellGroup
                CheckForeignKeyColumnOrder(cells, errorLog);
            }
        }
        // requires: all columns in constraint.ParentColumns and
        // constraint.ChildColumns must have been mapped in some cell in m_cellGroup
        // effects: Given the foreign key constraint, checks if the
        // constraint.ChildColumns are mapped to the constraint.ParentColumns
        // in m_cellGroup in the right oder. If not, adds an error to m_errorLog and returns
        // false. Else returns true
        private bool CheckForeignKeyColumnOrder(Set <Cell> cells, ErrorLog errorLog)
        {
            // Go through every cell and find the cells that are relevant to
            // parent and those that are relevant to child
            // Then for each cell pair (parent, child) make sure that the
            // projected foreign keys columns in C-space are aligned

            var parentCells = new List <Cell>();
            var childCells  = new List <Cell>();

            foreach (var cell in cells)
            {
                if (cell.SQuery.Extent.Equals(ChildTable))
                {
                    childCells.Add(cell);
                }

                if (cell.SQuery.Extent.Equals(ParentTable))
                {
                    parentCells.Add(cell);
                }
            }

            // Make sure that all child cells and parent cells align on
            // the columns, i.e., for each DISTINCT pair C and P, get the columns
            // on the S-side. Then get the corresponding fields on the
            // C-side. The fields on the C-side should match

            var foundParentCell = false;
            var foundChildCell  = false;

            foreach (var childCell in childCells)
            {
                var allChildSlotNums = GetSlotNumsForColumns(childCell, ChildColumns);

                if (allChildSlotNums.Count == 0)
                {
                    // slots in present in S-side, ignore
                    continue;
                }

                List <MemberPath> childPaths  = null;
                List <MemberPath> parentPaths = null;
                Cell errorParentCell          = null;

                foreach (var childSlotNums in allChildSlotNums)
                {
                    foundChildCell = true;

                    // Get the fields on the C-side
                    childPaths = new List <MemberPath>(childSlotNums.Count);
                    foreach (var childSlotNum in childSlotNums)
                    {
                        // Initial slots only have JoinTreeSlots
                        var childSlot = (MemberProjectedSlot)childCell.CQuery.ProjectedSlotAt(childSlotNum);
                        Debug.Assert(childSlot != null);
                        childPaths.Add(childSlot.MemberPath);
                    }

                    foreach (var parentCell in parentCells)
                    {
                        var allParentSlotNums = GetSlotNumsForColumns(parentCell, ParentColumns);
                        if (allParentSlotNums.Count == 0)
                        {
                            // * Parent and child cell are the same - we do not
                            // need to check since we want to check the foreign
                            // key constraint mapping across cells
                            // * Some slots not in present in S-side, ignore
                            continue;
                        }
                        foreach (var parentSlotNums in allParentSlotNums)
                        {
                            foundParentCell = true;

                            parentPaths = new List <MemberPath>(parentSlotNums.Count);
                            foreach (var parentSlotNum in parentSlotNums)
                            {
                                var parentSlot = (MemberProjectedSlot)parentCell.CQuery.ProjectedSlotAt(parentSlotNum);
                                Debug.Assert(parentSlot != null);
                                parentPaths.Add(parentSlot.MemberPath);
                            }

                            // Make sure that the last member of each of these is the same
                            // or the paths are essentially equivalent via referential constraints
                            // We need to check that the last member is essentially the same because it could
                            // be a regular scenario where aid is mapped to PersonAddress and Address - there
                            // is no ref constraint. So when projected into C-Space, we will get Address.aid
                            // and PersonAddress.Address.aid
                            if (childPaths.Count
                                == parentPaths.Count)
                            {
                                var notAllPathsMatched = false;
                                for (var i = 0; i < childPaths.Count && !notAllPathsMatched; i++)
                                {
                                    var parentPath = parentPaths[i];
                                    var childPath  = childPaths[i];

                                    if (!parentPath.LeafEdmMember.Equals(childPath.LeafEdmMember)) //Child path did not match
                                    {
                                        if (parentPath.IsEquivalentViaRefConstraint(childPath))
                                        {
                                            //Specifying the referential constraint once in the C space should be enough.
                                            //This is the only way possible today.
                                            //We might be able to derive more knowledge by using boolean logic
                                            return(true);
                                        }
                                        else
                                        {
                                            notAllPathsMatched = true;
                                        }
                                    }
                                }

                                if (!notAllPathsMatched)
                                {
                                    return(true); //all childPaths matched parentPaths
                                }
                                else
                                {
                                    //If not this one, some other Parent Cell may match.
                                    errorParentCell = parentCell;
                                }
                            }
                        }
                    } //foreach parentCell
                }

                //If execution is at this point, no parent cell's end has matched (otherwise it would have returned true)

                Debug.Assert(childPaths != null, "child paths should be set");
                Debug.Assert(parentPaths != null, "parent paths should be set");
                Debug.Assert(errorParentCell != null, "errorParentCell should be set");

                var message = Strings.ViewGen_Foreign_Key_ColumnOrder_Incorrect(
                    ToUserString(),
                    MemberPath.PropertiesToUserString(ChildColumns, false),
                    ChildTable.Name,
                    MemberPath.PropertiesToUserString(childPaths, false),
                    childCell.CQuery.Extent.Name,
                    MemberPath.PropertiesToUserString(ParentColumns, false),
                    ParentTable.Name,
                    MemberPath.PropertiesToUserString(parentPaths, false),
                    errorParentCell.CQuery.Extent.Name);
                var record = new ErrorLog.Record(
                    ViewGenErrorCode.ForeignKeyColumnOrderIncorrect, message, new[] { errorParentCell, childCell }, String.Empty);
                errorLog.AddEntry(record);
                return(false);
            }
            Debug.Assert(foundParentCell, "Some cell that mapped the parent's key must be present!");
            Debug.Assert(
                foundChildCell == true, "Some cell that mapped the child's foreign key must be present according to the requires clause!");
            return(true);
        }
예제 #45
0
 public override Task <Aid> GetByIDAsync(Guid key)
 {
     return(Set.Include(c => c.Case.City.Region.Country)
            .Include(c => c.Case.District).FirstOrDefaultAsync(c => c.Id == key));
 }
        // effects: Ensures that there is a relationship mapped into the C-space for some cell in m_cellGroup. Else
        // adds an error to errorLog
        private void GuaranteeMappedRelationshipForForeignKey(
            QueryRewriter childRewriter, QueryRewriter parentRewriter,
            IEnumerable <Cell> cells,
            ErrorLog errorLog, ConfigViewGenerator config)
        {
            var childContext  = childRewriter.ViewgenContext;
            var parentContext = parentRewriter.ViewgenContext;

            // Find a cell where this foreign key is mapped as a relationship
            var prefix           = new MemberPath(ChildTable);
            var primaryKey       = ExtentKey.GetPrimaryKeyForEntityType(prefix, ChildTable.ElementType);
            var primaryKeyFields = primaryKey.KeyFields;
            var foundCell        = false;

            var foundValidParentColumnsForForeignKey = false; //we need to find only one, dont error on any one check being false
            List <ErrorLog.Record> errorListForInvalidParentColumnsForForeignKey = null;

            foreach (var cell in cells)
            {
                if (cell.SQuery.Extent.Equals(ChildTable) == false)
                {
                    continue;
                }

                // The childtable is mapped to a relationship in the C-space in cell
                // Check that all the columns of the foreign key and the primary key in the child table are mapped to some
                // property in the C-space

                var parentEnd = GetRelationEndForColumns(cell, ChildColumns);
                if (parentEnd != null &&
                    CheckParentColumnsForForeignKey(cell, cells, parentEnd, ref errorListForInvalidParentColumnsForForeignKey) == false)
                {
                    // Not an error unless we find no valid case
                    continue;
                }
                else
                {
                    foundValidParentColumnsForForeignKey = true;
                }

                var childEnd = GetRelationEndForColumns(cell, primaryKeyFields);
                Debug.Assert(
                    childEnd == null || parentEnd != childEnd,
                    "Ends are same => PKey and child columns are same - code should gone to other method");
                // Note: If both of them are not-null, they are mapped to the
                // same association set -- since we checked that particular cell

                if (childEnd != null &&
                    parentEnd != null &&
                    FindEntitySetForColumnsMappedToEntityKeys(cells, primaryKeyFields).Count > 0)
                {
                    foundCell = true;
                    CheckConstraintWhenParentChildMapped(cell, errorLog, parentEnd, config);
                    break; // Done processing for the foreign key - either it was mapped correctly or it was not
                }
                else if (parentEnd != null)
                {
                    // At this point, we know cell corresponds to an association set
                    var assocSet = (AssociationSet)cell.CQuery.Extent;
                    foundCell = CheckConstraintWhenOnlyParentMapped(assocSet, parentEnd, childRewriter, parentRewriter);
                    if (foundCell)
                    {
                        break;
                    }
                }
            }

            //CheckParentColumnsForForeignKey has returned no matches, Error.
            if (!foundValidParentColumnsForForeignKey)
            {
                Debug.Assert(
                    errorListForInvalidParentColumnsForForeignKey != null && errorListForInvalidParentColumnsForForeignKey.Count > 0);
                foreach (var errorRecord in errorListForInvalidParentColumnsForForeignKey)
                {
                    errorLog.AddEntry(errorRecord);
                }
                return;
            }

            if (foundCell == false)
            {
                // No cell found -- Declare error
                var message = Strings.ViewGen_Foreign_Key_Missing_Relationship_Mapping(ToUserString());

                IEnumerable <LeftCellWrapper> parentWrappers = GetWrappersFromContext(parentContext, ParentTable);
                IEnumerable <LeftCellWrapper> childWrappers  = GetWrappersFromContext(childContext, ChildTable);
                var bothExtentWrappers =
                    new Set <LeftCellWrapper>(parentWrappers);
                bothExtentWrappers.AddRange(childWrappers);
                var record = new ErrorLog.Record(
                    ViewGenErrorCode.ForeignKeyMissingRelationshipMapping, message, bothExtentWrappers, String.Empty);
                errorLog.AddEntry(record);
            }
        }
예제 #47
0
        public Cache Get()
        {
            var cache = Set.FirstOrDefault();

            return(cache == null || cache.HasExpired() ? Refresh() : cache);
        }
예제 #48
0
 internal DomainVariable(T_Variable identifier, Set <T_Element> domain) : this(identifier, domain, null)
 {
 }
예제 #49
0
        private void AsCql(
            Action <NegatedConstant, IEnumerable <Constant> > negatedConstantAsCql,
            Action <Set <Constant> > varInDomain,
            Action varIsNotNull,
            Action varIsNull,
            bool skipIsNotNull)
        {
            Debug.Assert(this.RestrictedMemberSlot.MemberPath.IsScalarType(), "Expected scalar.");

            // If domain values contain a negated constant, delegate Cql generation into that constant.
            Debug.Assert(this.Domain.Values.Count(c => c is NegatedConstant) <= 1, "Multiple negated constants?");
            NegatedConstant negated = (NegatedConstant)this.Domain.Values.FirstOrDefault(c => c is NegatedConstant);

            if (negated != null)
            {
                negatedConstantAsCql(negated, this.Domain.Values);
            }
            else // We have only positive constants.
            {
                // 1. Generate "var in domain"
                // 2. If var is not nullable, append "... and var is not null".
                //    This is needed for boolean _from variables that must never evaluate to null because view generation assumes 2-valued boolean logic.
                // 3. If domain contains null, prepend "var is null or ...".
                //
                // A complete generation pattern:
                //     (var is null or    ( var in domain    and var is not null))
                //      ^^^^^^^^^^^^^^      ^^^^^^^^^^^^^    ^^^^^^^^^^^^^^^^^^^
                //      generated by #3    generated by #1     generated by #2

                // Copy the domain values for simplification changes.
                Set <Constant> domainValues = new Set <Constant>(this.Domain.Values, Constant.EqualityComparer);

                bool includeNull = false;
                if (domainValues.Contains(Constant.Null))
                {
                    includeNull = true;
                    domainValues.Remove(Constant.Null);
                }

                // Constraint counter-example could contain undefined cellconstant. E.g for booleans (for int its optimized out due to negated constants)
                // we want to treat undefined as nulls.
                if (domainValues.Contains(Constant.Undefined))
                {
                    includeNull = true;
                    domainValues.Remove(Constant.Undefined);
                }

                bool excludeNull = !skipIsNotNull && this.RestrictedMemberSlot.MemberPath.IsNullable;

                Debug.Assert(!includeNull || !excludeNull, "includeNull and excludeNull can't be true at the same time.");

                // #1: Generate "var in domain"
                if (domainValues.Count > 0)
                {
                    varInDomain(domainValues);
                }

                // #2: Append "... and var is not null".
                if (excludeNull)
                {
                    varIsNotNull();
                }

                // #3: Prepend "var is null or ...".
                if (includeNull)
                {
                    varIsNull();
                }
            }
        }
예제 #50
0
        private ITag LoadTag(XmlNode xmlNode, IList <Include> includes)
        {
            ITag tag          = null;
            var  prepend      = xmlNode.Attributes?["Prepend"]?.Value.Trim();
            var  property     = xmlNode.Attributes?["Property"]?.Value.Trim();
            var  compareValue = xmlNode.Attributes?["CompareValue"]?.Value.Trim();

            #region Init Tag
            switch (xmlNode.Name)
            {
            case "#text":
            case "#cdata-section":
            {
                var bodyText = " " + xmlNode.InnerText.Replace("\n", "").Trim();
                return(new SqlText
                    {
                        BodyText = bodyText
                    });
            }

            case "Include":
            {
                var refId       = xmlNode.Attributes?["RefId"]?.Value;
                var include_tag = new Include
                {
                    RefId   = refId,
                    Prepend = prepend
                };
                includes.Add(include_tag);
                tag = include_tag;
                break;
            }

            case "IsEmpty":
            {
                tag = new IsEmpty
                {
                    Prepend   = prepend,
                    Property  = property,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "IsEqual":
            {
                tag = new IsEqual
                {
                    Prepend      = prepend,
                    Property     = property,
                    CompareValue = compareValue,
                    ChildTags    = new List <ITag>()
                };
                break;
            }

            case "IsGreaterEqual":
            {
                tag = new IsGreaterEqual
                {
                    Prepend      = prepend,
                    Property     = property,
                    CompareValue = compareValue,
                    ChildTags    = new List <ITag>()
                };
                break;
            }

            case "IsGreaterThan":
            {
                tag = new IsGreaterThan
                {
                    Prepend      = prepend,
                    Property     = property,
                    CompareValue = compareValue,
                    ChildTags    = new List <ITag>()
                };
                break;
            }

            case "IsLessEqual":
            {
                tag = new IsLessEqual
                {
                    Prepend      = prepend,
                    Property     = property,
                    CompareValue = compareValue,
                    ChildTags    = new List <ITag>()
                };
                break;
            }

            case "IsLessThan":
            {
                tag = new IsLessThan
                {
                    Prepend      = prepend,
                    Property     = property,
                    CompareValue = compareValue,
                    ChildTags    = new List <ITag>()
                };
                break;
            }

            case "IsNotEmpty":
            {
                tag = new IsNotEmpty
                {
                    Prepend   = prepend,
                    Property  = property,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "IsNotEqual":
            {
                tag = new IsNotEqual
                {
                    Prepend      = prepend,
                    Property     = property,
                    CompareValue = compareValue,
                    ChildTags    = new List <ITag>()
                };
                break;
            }

            case "IsNotNull":
            {
                tag = new IsNotNull
                {
                    Prepend   = prepend,
                    Property  = property,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "IsNull":
            {
                tag = new IsNull
                {
                    Prepend   = prepend,
                    Property  = property,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "IsTrue":
            {
                tag = new IsTrue
                {
                    Prepend   = prepend,
                    Property  = property,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "IsFalse":
            {
                tag = new IsFalse
                {
                    Prepend   = prepend,
                    Property  = property,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "IsProperty":
            {
                tag = new IsProperty
                {
                    Prepend   = prepend,
                    Property  = property,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "Placeholder":
            {
                tag = new Placeholder
                {
                    Prepend   = prepend,
                    Property  = property,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "Switch":
            {
                tag = new Switch
                {
                    Property = property,
                    //Prepend = prepend,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "Case":
            {
                var switchNode     = xmlNode.ParentNode;
                var switchProperty = switchNode.Attributes?["Property"]?.Value.Trim();
                var switchPrepend  = switchNode.Attributes?["Prepend"]?.Value.Trim();
                tag = new Switch.Case
                {
                    CompareValue = compareValue,
                    Property     = switchProperty,
                    Prepend      = switchPrepend,
                    ChildTags    = new List <ITag>()
                };
                break;
            }

            case "Default":
            {
                var switchNode     = xmlNode.ParentNode;
                var switchProperty = switchNode.Attributes?["Property"]?.Value.Trim();
                var switchPrepend  = switchNode.Attributes?["Prepend"]?.Value.Trim();
                tag = new Switch.Defalut
                {
                    Property  = switchProperty,
                    Prepend   = switchPrepend,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "Dynamic":
            {
                tag = new Dynamic
                {
                    Prepend   = prepend,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "Where":
            {
                tag = new Where
                {
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "Set":
            {
                tag = new Set
                {
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "For":
            {
                var open      = xmlNode.Attributes?["Open"]?.Value.Trim();
                var separator = xmlNode.Attributes?["Separator"]?.Value.Trim();
                var close     = xmlNode.Attributes?["Close"]?.Value.Trim();
                var key       = xmlNode.Attributes?["Key"]?.Value.Trim();
                tag = new For
                {
                    Prepend   = prepend,
                    Property  = property,
                    Open      = open,
                    Close     = close,
                    Separator = separator,
                    Key       = key,
                    ChildTags = new List <ITag>()
                };
                break;
            }

            case "Env":
            {
                var dbProvider = xmlNode.Attributes?["DbProvider"]?.Value.Trim();
                tag = new Env
                {
                    Prepend    = prepend,
                    DbProvider = dbProvider,
                    ChildTags  = new List <ITag>()
                };
                break;
            }

            case "#comment": { break; }

            default:
            {
                throw new SmartSqlException($"Statement.LoadTag unkonw tagName:{xmlNode.Name}.");
            };
            }
            #endregion
            foreach (XmlNode childNode in xmlNode)
            {
                ITag childTag = LoadTag(childNode, includes);
                if (childTag != null && tag != null)
                {
                    (tag as Tag).ChildTags.Add(childTag);
                }
            }
            return(tag);
        }
예제 #51
0
        public IEnumerator <TableExporter.ITableRow> GetEnumerator()
        {
            IEnumerable exportedRows;
            IList <int> exportedColumns;

            if (exportSelectedCellsOnly &&
                treeDataGridView.SelectedCells.Count > 0 &&
                !treeDataGridView.AreAllCellsSelected(false))
            {
                var selectedRows    = new Set <DataGridViewRow>();
                var selectedColumns = new Map <int, int>(); // ordered by DisplayIndex

                foreach (DataGridViewCell cell in treeDataGridView.SelectedCells)
                {
                    selectedRows.Add(cell.OwningRow);
                    selectedColumns[cell.OwningColumn.DisplayIndex] = cell.ColumnIndex;
                }

                exportedRows    = selectedRows;
                exportedColumns = selectedColumns.Values;
            }
            else
            {
                exportedRows    = treeDataGridView.Rows;
                exportedColumns = treeDataGridView.GetVisibleColumnsInDisplayOrder().Select(o => o.Index).ToList();
            }

            // add column headers
            var Headers = new List <string>();

            foreach (var columnIndex in exportedColumns)
            {
                Headers.Add(treeDataGridView.Columns[columnIndex].HeaderText);
            }

            foreach (DataGridViewRow row in exportedRows)
            {
                var exportedRow = new ExportedTableRow();
                exportedRow.Headers = Headers;

                /* TODO: how to handle non-root rows?
                 * var row = rows[rowIndex];
                 *
                 * // skip non-root rows or filtered rows
                 * if (rowIndexHierarchy.Count > 1 || getRowFilterState(row) == RowFilterState.Out)
                 *  continue;*/

                if (rows.Count > row.Index)
                {
                    Row row2 = rows[row.Index];
                    if (getRowFilterState(row2) == RowFilterState.Out)
                    {
                        continue;
                    }
                }

                var rowIndexHierarchy = treeDataGridView.GetRowHierarchyForRowIndex(row.Index);

                exportedRow.Cells = new List <string>();
                foreach (var columnIndex in exportedColumns)
                {
                    // empty cells are exported as blank except for pivot columns which are exported as zeros
                    object value = row.Cells[columnIndex].Value ?? (treeDataGridView.Columns[columnIndex].Name.StartsWith("pivot") ? "0" : String.Empty);
                    var    sb    = new StringBuilder(value.ToString());

                    if (columnIndex == 0 && rowIndexHierarchy.Count > 1)
                    {
                        int indent = (rowIndexHierarchy.Count - 1) * 2;
                        sb.Insert(0, new string(' ', indent));
                    }
                    exportedRow.Cells.Add(sb.ToString());
                }

                yield return(exportedRow);
            }
        }
예제 #52
0
        public void RoutingWithThreeGroups()
        {
            var graph = LoadGraph("abstract.msagl.geom");
            var root  = graph.RootCluster;
            var a     = new Cluster {
                UserData = "a"
            };

            foreach (string id in new[] { "17", "39", "13", "19", "28", "12" })
            {
                a.AddChild(graph.FindNodeByUserData(id));
            }

            var b = new Cluster {
                UserData = "b"
            };

            b.AddChild(a);
            b.AddChild(graph.FindNodeByUserData("18"));
            root.AddChild(b);

            var c = new Cluster {
                UserData = "c"
            };

            foreach (string id in new[] { "30", "5", "6", "7", "8" })
            {
                c.AddChild(graph.FindNodeByUserData(id));
            }
            root.AddChild(c);

            var clusterNodes = new Set <Node>(root.AllClustersDepthFirst().SelectMany(cl => cl.Nodes));

            foreach (var node in graph.Nodes.Where(n => clusterNodes.Contains(n) == false))
            {
                root.AddChild(node);
            }

            FixClusterBoundariesWithNoRectBoundaries(root, 5);
            var defaultSettings = new FastIncrementalLayoutSettings();
            var rootSettings    = new FastIncrementalLayoutSettings()
            {
                AvoidOverlaps = true
            };

            var initialLayout = new InitialLayoutByCluster(graph, new[] { graph.RootCluster }, cl => cl == root ? rootSettings : defaultSettings);

            initialLayout.Run();

            const double Padding = 5;

            SplineRouter splineRouter = new SplineRouter(graph, Padding / 3, Padding, Math.PI / 6);

            splineRouter.Run();
#if TEST_MSAGL
            if (!DontShowTheDebugViewer())
            {
                graph.UpdateBoundingBox();
                DisplayGeometryGraph.ShowGraph(graph);
            }
#endif
        }
예제 #53
0
 /// <summary>
 /// Initialize a sentence given the appropriate sentence clauses. Produces
 /// an equivalent expression by composing the clause expressions using
 /// the given tree type.
 /// </summary>
 /// <param name="clauses">Sentence clauses</param>
 /// <param name="treeType">Tree type for sentence (and generated expression)</param>
 protected Sentence(Set <T_Clause> clauses, ExprType treeType)
     : base(ConvertClausesToExpr(clauses, treeType))
 {
     _clauses = clauses.AsReadOnly();
 }
예제 #54
0
        public virtual List <List <string> > GetFormTable(bool selected)
        {
            var         exportTable = new List <List <string> >();
            IList <int> exportedRows, exportedColumns;

            if (selected && treeDataGridView.SelectedCells.Count > 0 && !treeDataGridView.AreAllCellsSelected(false))
            {
                var selectedRows    = new Set <int>();
                var selectedColumns = new Map <int, int>(); // ordered by DisplayIndex

                foreach (DataGridViewCell cell in treeDataGridView.SelectedCells)
                {
                    selectedRows.Add(cell.RowIndex);
                    selectedColumns[cell.OwningColumn.DisplayIndex] = cell.ColumnIndex;
                }

                exportedRows    = selectedRows.ToList();
                exportedColumns = selectedColumns.Values;
            }
            else
            {
                exportedRows    = treeDataGridView.Rows.Cast <DataGridViewRow>().Select(o => o.Index).ToList();
                exportedColumns = treeDataGridView.GetVisibleColumnsInDisplayOrder().Select(o => o.Index).ToList();
            }

            // add column headers
            exportTable.Add(new List <string>());
            foreach (var columnIndex in exportedColumns)
            {
                exportTable.Last().Add(treeDataGridView.Columns[columnIndex].HeaderText);
            }

            foreach (int rowIndex in exportedRows)
            {
                /* TODO: how to handle non-root rows?
                 * var row = rows[rowIndex];
                 *
                 * // skip non-root rows or filtered rows
                 * if (rowIndexHierarchy.Count > 1 || getRowFilterState(row) == RowFilterState.Out)
                 *  continue;*/

                var rowIndexHierarchy = treeDataGridView.GetRowHierarchyForRowIndex(rowIndex);

                var rowText = new List <string>();
                foreach (var columnIndex in exportedColumns)
                {
                    object value = treeDataGridView[columnIndex, rowIndex].Value ?? String.Empty;
                    rowText.Add(value.ToString());

                    if (columnIndex == 0 && rowIndexHierarchy.Count > 1)
                    {
                        int indent = (rowIndexHierarchy.Count - 1) * 2;
                        rowText[rowText.Count - 1] = new string(' ', indent) + rowText[rowText.Count - 1];
                    }
                }

                exportTable.Add(rowText);
            }

            return(exportTable);
        }
예제 #55
0
 // Initializes a new DNF sentence given its clauses.
 internal DnfSentence(Set <DnfClause <T_Identifier> > clauses)
     : base(clauses, ExprType.Or)
 {
 }
예제 #56
0
        /// <summary>
        /// don't let this be constructed publicly;
        /// </summary>
        /// <exception cref="EntityCommandCompilationException">Cannot prepare the command definition for execution; consult the InnerException for more information.</exception>
        /// <exception cref="NotSupportedException">The ADO.NET Data Provider you are using does not support CommandTrees.</exception>
        internal EntityCommandDefinition(DbProviderFactory storeProviderFactory, DbCommandTree commandTree)
        {
            EntityUtil.CheckArgumentNull(storeProviderFactory, "storeProviderFactory");
            EntityUtil.CheckArgumentNull(commandTree, "commandTree");

            DbProviderServices storeProviderServices = DbProviderServices.GetProviderServices(storeProviderFactory);

            try {
                if (DbCommandTreeKind.Query == commandTree.CommandTreeKind)
                {
                    // Next compile the plan for the command tree
                    List <ProviderCommandInfo> mappedCommandList = new List <ProviderCommandInfo>();
                    ColumnMap columnMap;
                    int       columnCount;
                    PlanCompiler.Compile(commandTree, out mappedCommandList, out columnMap, out columnCount, out _entitySets);
                    _columnMapGenerators = new IColumnMapGenerator[] { new ConstantColumnMapGenerator(columnMap, columnCount) };
                    // Note: we presume that the first item in the ProviderCommandInfo is the root node;
                    Debug.Assert(mappedCommandList.Count > 0, "empty providerCommandInfo collection and no exception?"); // this shouldn't ever happen.

                    // Then, generate the store commands from the resulting command tree(s)
                    _mappedCommandDefinitions = new List <DbCommandDefinition>(mappedCommandList.Count);

                    foreach (ProviderCommandInfo providerCommandInfo in mappedCommandList)
                    {
                        DbCommandDefinition providerCommandDefinition = storeProviderServices.CreateCommandDefinition(providerCommandInfo.CommandTree);

                        if (null == providerCommandDefinition)
                        {
                            throw EntityUtil.ProviderIncompatible(System.Data.Entity.Strings.ProviderReturnedNullForCreateCommandDefinition);
                        }
                        _mappedCommandDefinitions.Add(providerCommandDefinition);
                    }
                }
                else
                {
                    Debug.Assert(DbCommandTreeKind.Function == commandTree.CommandTreeKind, "only query and function command trees are supported");
                    DbFunctionCommandTree entityCommandTree = (DbFunctionCommandTree)commandTree;

                    // Retrieve mapping and metadata information for the function import.
                    FunctionImportMappingNonComposable mapping          = GetTargetFunctionMapping(entityCommandTree);
                    IList <FunctionParameter>          returnParameters = entityCommandTree.EdmFunction.ReturnParameters;
                    int resultSetCount = returnParameters.Count > 1 ? returnParameters.Count : 1;
                    _columnMapGenerators = new IColumnMapGenerator[resultSetCount];
                    TypeUsage storeResultType = DetermineStoreResultType(entityCommandTree.MetadataWorkspace, mapping, 0, out _columnMapGenerators[0]);
                    for (int i = 1; i < resultSetCount; i++)
                    {
                        DetermineStoreResultType(entityCommandTree.MetadataWorkspace, mapping, i, out _columnMapGenerators[i]);
                    }
                    // Copy over parameters (this happens through a more indirect route in the plan compiler, but
                    // it happens nonetheless)
                    List <KeyValuePair <string, TypeUsage> > providerParameters = new List <KeyValuePair <string, TypeUsage> >();
                    foreach (KeyValuePair <string, TypeUsage> parameter in entityCommandTree.Parameters)
                    {
                        providerParameters.Add(parameter);
                    }

                    // Construct store command tree usage.
                    DbFunctionCommandTree providerCommandTree = new DbFunctionCommandTree(entityCommandTree.MetadataWorkspace, DataSpace.SSpace,
                                                                                          mapping.TargetFunction, storeResultType, providerParameters);

                    DbCommandDefinition storeCommandDefinition = storeProviderServices.CreateCommandDefinition(providerCommandTree);
                    _mappedCommandDefinitions = new List <DbCommandDefinition>(1)
                    {
                        storeCommandDefinition
                    };

                    EntitySet firstResultEntitySet = mapping.FunctionImport.EntitySets.FirstOrDefault();
                    if (firstResultEntitySet != null)
                    {
                        _entitySets = new Set <EntitySet>();
                        _entitySets.Add(mapping.FunctionImport.EntitySets.FirstOrDefault());
                        _entitySets.MakeReadOnly();
                    }
                }

                // Finally, build a list of the parameters that the resulting command should have;
                List <EntityParameter> parameterList = new List <EntityParameter>();

                foreach (KeyValuePair <string, TypeUsage> queryParameter in commandTree.Parameters)
                {
                    EntityParameter parameter = CreateEntityParameterFromQueryParameter(queryParameter);
                    parameterList.Add(parameter);
                }

                _parameters = new System.Collections.ObjectModel.ReadOnlyCollection <EntityParameter>(parameterList);
            }
            catch (EntityCommandCompilationException) {
                // No need to re-wrap EntityCommandCompilationException
                throw;
            }
            catch (Exception e) {
                // we should not be wrapping all exceptions
                if (EntityUtil.IsCatchableExceptionType(e))
                {
                    // we don't wan't folks to have to know all the various types of exceptions that can
                    // occur, so we just rethrow a CommandDefinitionException and make whatever we caught
                    // the inner exception of it.
                    throw EntityUtil.CommandCompilation(System.Data.Entity.Strings.EntityClient_CommandDefinitionPreparationFailed, e);
                }
                throw;
            }
        }
예제 #57
0
 /// <summary>
 ///
 /// </summary>
 public StringAbstraction(Set <SimpleCharacterAbstraction> /*!*/ characters)
 {
     this.content    = ContentType.SetOfCharacters;
     this.characters = characters;
 }
예제 #58
0
 // Initializes a new CNF sentence given its clauses.
 internal CnfSentence(Set <CnfClause <T_Identifier> > clauses)
     : base(clauses, ExprType.And)
 {
 }
예제 #59
0
        static private IAbstractDomain /*!*/ HelperForSetOfCharactersJoin(Set <SimpleCharacterAbstraction> /*!*/ iSet1, Set <SimpleCharacterAbstraction> /*!*/ iSet2)
        {
            Set <SimpleCharacterAbstraction> union = iSet1.Union(iSet2);

            return(new StringAbstraction(union));
        }
예제 #60
0
        public bool LessEqual(IAbstractDomain /*!*/ a)
        {
            bool tryResult;

            if (AbstractDomainsHelper.TryTrivialLessEqual(this, a, out tryResult))
            {
                return(tryResult);
            }

            StringAbstraction right = a as StringAbstraction;

            //^ assert right != null;
            Debug.Assert(right != null, "I was expecting a " + this.GetType().ToString());

            bool result;

            if (this.content == right.content)
            {
                switch (this.content)
                {
                    #region All the cases
                case ContentType.Prefix:
                    result = this.prefix.StartsWith(right.prefix); // it is larger if it is a substring
                    break;

                case ContentType.SetOfCharacters:
                    result = this.characters.IsSubset(right.characters); // it is larger if it is a subset
                    break;

                case ContentType.String:
                    result = this.fullstring.CompareTo(right.fullstring) == 0; // must be the same string
                    break;

                case ContentType.Bottom:
                case ContentType.Top:
                default:
                    throw new AbstractInterpretationException("Unexpected case : " + this.content);
                    #endregion
                }
            }
            else
            {
                switch (this.content)
                {
                    #region All the cases
                case ContentType.Prefix:
                    if (right.content == ContentType.SetOfCharacters)
                    {
                        result = false;
                    }
                    else if (right.content == ContentType.String)
                    {
                        result = false;
                    }
                    else
                    {
                        goto default;
                    }
                    break;

                case ContentType.SetOfCharacters:
                    if (right.content == ContentType.Prefix)
                    {
                        result = false;
                    }
                    else if (right.content == ContentType.String)
                    {
                        result = false;
                    }
                    else
                    {
                        goto default;
                    }
                    break;

                case ContentType.String:
                    if (right.content == ContentType.Prefix)
                    {
                        result = this.fullstring.StartsWith(right.prefix);
                    }
                    else if (right.content == ContentType.SetOfCharacters)
                    {
                        Set <SimpleCharacterAbstraction> tmp = AlphaToSetOfCharacters(this.fullstring);
                        result = tmp.IsSubset(right.characters);
                    }
                    else
                    {
                        goto default;
                    }
                    break;

                case ContentType.Bottom:
                case ContentType.Top:
                default:
                    throw new AbstractInterpretationException("Unexpected case : " + this.content);
                    #endregion
                }
            }

            return(result);
        }