Exemple #1
0
        // Creates the SQL command to add a resource to the _values table.
        private void AddValue(Resource resource, StringBuilder buffer, bool insertCombined, ref bool firstInsert)
        {
            StringBuilder b = buffer;

            if (!insertCombined)
            {
                b.Append("INSERT ");
                b.Append(connection.ValueInsertKeywords);
                b.Append(" INTO ");
                b.Append(prefix);
                b.Append("_values ");
            }
            else
            {
                if (!firstInsert)
                {
                    b.Append(',');
                }
                firstInsert = false;
            }
            b.Append('(');
            b.Append('\'');
            b.Append(GetHash(resource));
            b.Append('\'');
            b.Append(',');

            if ((object)resource == (object)Statement.DefaultMeta)
            {
                b.Append('2');
                b.Append(',');
                EscapedAppend(b, DEFAULT_META_KEY);
            }
            else if (resource is BNode)
            {
                BNode bnode = (BNode)resource;
                b.Append('2');
                b.Append(',');
                EscapedAppend(b, bnode.GetGUID().ToString("N"));
            }
            else if (resource is Entity)
            {
                b.Append('1');
                b.Append(',');
                EscapedAppend(b, resource.Uri);
            }
            else if (resource is Literal)
            {
                Literal literal = (Literal)resource;
                b.Append('3');
                b.Append(',');
                EscapedAppend(b, literal.Value);
                b.Append(',');
                if (literal.Language != null)
                {
                    EscapedAppend(b, literal.Language);
                }
                else
                {
                    b.Append("NULL");
                }
                b.Append(',');
                if (literal.DataType != null)
                {
                    EscapedAppend(b, literal.DataType);
                }
                else
                {
                    b.Append("NULL");
                }
            }

            b.Append(')');
            if (!insertCombined)
            {
                b.Append(';');
            }
        }
 public FactorizationTree()
 {
     _root = null;
     Count = 0;
 }
Exemple #3
0
    private void NodeAdderPanel()
    {
        nAdder = o(main, 0, w.height - 30, main.width, 30);
        GUI.Box(nAdder, "");
        Rect bNode = o(nAdder, 20, 5, 100, 20);

        if (GUI.Button(bNode, "Begin/Gate"))
        {
            if (c != null)
            {
                BNode n = new BNode();
                c.nodes.Add((CNode)n);
                CNode newN = c.nodes.nodes [c.nodes.nodes.Count - 1];
                //c.nodes.nodes [c.nodes.nodes.Count - 1].chat = c;
                c.nodes.nodes [c.nodes.nodes.Count - 1].name = "Gate";
                for (int i = 0; i < c.dict.keys.Count; i++)
                {
                    CChecker checkNew = new CChecker();
                    checkNew.checkType    = CChecker.propertyCheck.NA;
                    checkNew.propertyName = c.dict.keys [i];
                    checkNew.value        = c.dict.value(c.dict.keys [i]);
                    newN.checkers.Add(checkNew);
                }
            }
        }
        Rect playerNode = o(nAdder, 140, 5, 100, 20);
        Rect npcNode    = duplicate(playerNode, 120, 0);

        if (GUI.Button(playerNode, "Player Response"))
        {
            if (c != null)
            {
//				ScriptableObject n = ScriptableObject.CreateInstance<CPlayerWindow> ();
                c.nodes.Add((CNode) new CPlayerWindow());
                CNode newN = c.nodes.nodes [c.nodes.nodes.Count - 1];
                //c.nodes.nodes [c.nodes.nodes.Count - 1].chat = c;
                c.nodes.nodes [c.nodes.nodes.Count - 1].name = "Player Node";

                for (int i = 0; i < c.dict.keys.Count; i++)
                {
                    CEffector ef = new CEffector();
                    ef.s    = c.dict.keys [i];
                    ef.f    = c.dict.value(c.dict.keys [i]);
                    ef.type = CEffector.operationType.NA;
                    newN.effectors.Add(ef);
                }
            }
        }
        if (GUI.Button(npcNode, "NPC Response"))
        {
            if (c != null)
            {
                c.nodes.Add((CNode) new CNPCWindow());
                CNode newN = c.nodes.nodes [c.nodes.nodes.Count - 1];
                //c.nodes.nodes [c.nodes.nodes.Count - 1].chat = c;
                c.nodes.nodes [c.nodes.nodes.Count - 1].name = "NPC";

                for (int i = 0; i < c.dict.keys.Count; i++)
                {
                    CEffector ef = new CEffector();
                    ef.s    = c.dict.keys [i];
                    ef.f    = c.dict.value(c.dict.keys [i]);
                    ef.type = CEffector.operationType.NA;
                    newN.effectors.Add(ef);
                }
            }
        }
        //	Rect sel = duplicate (npcNode, 120, 0);
        //	c = (NPC_Chat)EditorGUI.ObjectField (sel, c, typeof(NPC_Chat));
        Rect clear = duplicate(npcNode, 120, 0);

        if (GUI.Button(clear, "Clear"))
        {
            if (c != null)
            {
                c.nodes.nodes.Clear();
            }
            deleted.Clear();
        }
        Rect showAll = duplicate(clear, 120, 0);

        if (GUI.Button(showAll, "Show All"))
        {
            if (c != null)
            {
                for (int i = 0; i < c.nodes.nodes.Count; i++)
                {
                    c.nodes.nodes [i].hidden = false;
                }
            }
        }
    }
Exemple #4
0
 public static bool IsInternal(this BNode node)
 {
     // если у узла есть потомок то это внутренний узел
     return(node.LeftNode != null || node.RightNode != null);
 }
        /// <summary>
        /// Add Data To Cache
        /// </summary>
        private List <EnergyInfo> AddDataToCache()
        {
            try {
                var userData = UserData;
                var cacheKey = WebUtility.GetCacheKeyName(userData, "energy-records");
                HttpRuntime.Cache.Remove(cacheKey);

                if (LscsComboBox.SelectedItem == null)
                {
                    return(null);
                }
                if (String.IsNullOrEmpty(CountItemField.Text.Trim()))
                {
                    return(null);
                }
                var ids = WebUtility.ItemSplit(LscsComboBox.SelectedItem.Value);
                if (ids.Length != 2)
                {
                    return(null);
                }
                var lscId   = Int32.Parse(ids[0]);
                var groupId = Int32.Parse(ids[1]);
                var lscUser = userData.LscUsers.Find(lu => { return(lu.LscID == lscId); });
                if (lscUser == null)
                {
                    return(null);
                }

                var nodeEntity = new BNode();
                var fromTime   = DateTime.Parse(FromDate.Text);
                var toTime     = DateTime.Parse(ToDate.Text);
                var countItem  = CountItemField.Text.Trim();
                var area2Name  = WebUtility.DefaultString;
                var area3Name  = WebUtility.DefaultString;
                if (Area2ComboBox.SelectedIndex > 0)
                {
                    area2Name = Area2ComboBox.SelectedItem.Text;
                }
                if (Area3ComboBox.SelectedIndex > 0)
                {
                    area3Name = Area3ComboBox.SelectedItem.Text;
                }
                var nodes  = nodeEntity.GetNodes(lscId, EnmNodeType.Aic, WebUtility.DefaultString, area2Name, area3Name, WebUtility.DefaultString, WebUtility.DefaultString, WebUtility.DefaultString, WebUtility.DefaultString, countItem);
                var gNodes = from node in nodes
                             join gnode in lscUser.Group.GroupNodes on node.DevID equals gnode.NodeID
                             select node;

                var AINodes1    = nodeEntity.GetAIStatic(lscId, WebUtility.DefaultInt32, fromTime, toTime);
                var nodesCount1 = from node in gNodes
                                  join ai in AINodes1 on node.NodeID equals ai.NodeID into nodesGroup
                                  select new {
                    LscID       = node.LscID,
                    LscName     = node.LscName,
                    Area1ID     = node.Area1ID,
                    Area1Name   = node.Area1Name,
                    Area2ID     = node.Area2ID,
                    Area2Name   = node.Area2Name,
                    Area3ID     = node.Area3ID,
                    Area3Name   = node.Area3Name,
                    StaID       = node.StaID,
                    StaName     = node.StaName,
                    StaTypeName = node.StaTypeName,
                    SumValue    = nodesGroup.Any() ? nodesGroup.Max(v => v.MaxValue) - nodesGroup.Min(v => v.MaxValue) : 0
                };
                var staCount1 = from node in nodesCount1
                                group node by new { LscID = node.LscID, StaID = node.StaID } into staGroup
                    select new {
                    LscID       = staGroup.Key.LscID,
                    LscName     = staGroup.Max(v => v.LscName),
                    Area1ID     = staGroup.Max(v => v.Area1ID),
                    Area1Name   = staGroup.Max(v => v.Area1Name),
                    Area2ID     = staGroup.Max(v => v.Area2ID),
                    Area2Name   = staGroup.Max(v => v.Area2Name),
                    Area3ID     = staGroup.Max(v => v.Area3ID),
                    Area3Name   = staGroup.Max(v => v.Area3Name),
                    StaID       = staGroup.Key.StaID,
                    StaName     = staGroup.Max(v => v.StaName),
                    StaTypeName = staGroup.Max(v => v.StaTypeName),
                    SumValue    = staGroup.Sum(v => v.SumValue)
                };

                var AINodes2    = nodeEntity.GetAIStatic(lscId, WebUtility.DefaultInt32, fromTime.AddYears(-1), toTime.AddYears(-1));
                var nodesCount2 = from node in gNodes
                                  join ai in AINodes2 on new { LscID = node.LscID, NodeID = node.NodeID } equals new { LscID = ai.LscID, NodeID = ai.NodeID } into nodesGroup
                    select new {
                    LscID       = node.LscID,
                    LscName     = node.LscName,
                    Area1ID     = node.Area1ID,
                    Area1Name   = node.Area1Name,
                    Area2ID     = node.Area2ID,
                    Area2Name   = node.Area2Name,
                    Area3ID     = node.Area3ID,
                    Area3Name   = node.Area3Name,
                    StaID       = node.StaID,
                    StaName     = node.StaName,
                    StaTypeName = node.StaTypeName,
                    SumValue    = nodesGroup.Any() ? nodesGroup.Max(v => v.MaxValue) - nodesGroup.Min(v => v.MaxValue) : 0
                };
                var staCount2 = from node in nodesCount2
                                group node by new { LscID = node.LscID, StaID = node.StaID } into staGroup
                    select new {
                    LscID       = staGroup.Key.LscID,
                    LscName     = staGroup.Max(v => v.LscName),
                    Area1ID     = staGroup.Max(v => v.Area1ID),
                    Area1Name   = staGroup.Max(v => v.Area1Name),
                    Area2ID     = staGroup.Max(v => v.Area2ID),
                    Area2Name   = staGroup.Max(v => v.Area2Name),
                    Area3ID     = staGroup.Max(v => v.Area3ID),
                    Area3Name   = staGroup.Max(v => v.Area3Name),
                    StaID       = staGroup.Key.StaID,
                    StaName     = staGroup.Max(v => v.StaName),
                    StaTypeName = staGroup.Max(v => v.StaTypeName),
                    SumValue    = staGroup.Sum(v => v.SumValue)
                };

                var AINodes3    = nodeEntity.GetAIStatic(lscId, WebUtility.DefaultInt32, fromTime.AddMonths(-1), toTime.AddMonths(-1));
                var nodesCount3 = from node in gNodes
                                  join ai in AINodes3 on new { LscID = node.LscID, NodeID = node.NodeID } equals new { LscID = ai.LscID, NodeID = ai.NodeID } into nodesGroup
                    select new {
                    LscID       = node.LscID,
                    LscName     = node.LscName,
                    Area1ID     = node.Area1ID,
                    Area1Name   = node.Area1Name,
                    Area2ID     = node.Area2ID,
                    Area2Name   = node.Area2Name,
                    Area3ID     = node.Area3ID,
                    Area3Name   = node.Area3Name,
                    StaID       = node.StaID,
                    StaName     = node.StaName,
                    StaTypeName = node.StaTypeName,
                    SumValue    = nodesGroup.Any() ? nodesGroup.Max(v => v.MaxValue) - nodesGroup.Min(v => v.MaxValue) : 0
                };
                var staCount3 = from node in nodesCount3
                                group node by new { LscID = node.LscID, StaID = node.StaID } into staGroup
                    select new {
                    LscID       = staGroup.Key.LscID,
                    LscName     = staGroup.Max(v => v.LscName),
                    Area1ID     = staGroup.Max(v => v.Area1ID),
                    Area1Name   = staGroup.Max(v => v.Area1Name),
                    Area2ID     = staGroup.Max(v => v.Area2ID),
                    Area2Name   = staGroup.Max(v => v.Area2Name),
                    Area3ID     = staGroup.Max(v => v.Area3ID),
                    Area3Name   = staGroup.Max(v => v.Area3Name),
                    StaID       = staGroup.Key.StaID,
                    StaName     = staGroup.Max(v => v.StaName),
                    StaTypeName = staGroup.Max(v => v.StaTypeName),
                    SumValue    = staGroup.Sum(v => v.SumValue)
                };

                var records = (from rec1 in staCount1
                               join rec2 in staCount2 on new { LscID = rec1.LscID, StaID = rec1.StaID } equals new { LscID = rec2.LscID, StaID = rec2.StaID } into defaultRecords2
                               from defaultRec2 in defaultRecords2.DefaultIfEmpty()
                               join rec3 in staCount3 on new { LscID = rec1.LscID, StaID = rec1.StaID } equals new { LscID = rec3.LscID, StaID = rec3.StaID } into defaultRecords3
                               from defaultRec3 in defaultRecords3.DefaultIfEmpty()
                               select new EnergyInfo {
                    LscID = rec1.LscID,
                    LscName = rec1.LscName,
                    Area1Name = rec1.Area1Name,
                    Area2Name = rec1.Area2Name,
                    Area3Name = rec1.Area3Name,
                    StaName = rec1.StaName,
                    StaTypeName = rec1.StaTypeName,
                    SumValue = rec1.SumValue,
                    YoYValue = (defaultRec2 == null ? 0 : defaultRec2.SumValue),
                    QoQValue = (defaultRec3 == null ? 0 : defaultRec3.SumValue)
                }).ToList();

                var cacheDuration = Int32.Parse(WebConfigurationManager.AppSettings["DefaultCacheDuration"]);
                HttpRuntime.Cache.Insert(cacheKey, records, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(cacheDuration), CacheItemPriority.Default, null);
                return(records);
            } catch { throw; }
        }
    void OnGUI()
    {
        //////////////////// draw the tree /////////////////////
        this.m_cScrollPos = GUI.BeginScrollView(new Rect(0, 0, position.width - 240, position.height), this.m_cScrollPos, new Rect(0, 0, this.maxSize.x, this.maxSize.y));

        Texture2D tex1 = new Texture2D(1, 1);

        tex1.SetPixel(0, 0, Color.black);
        tex1.Apply();
        Texture2D tex2 = new Texture2D(1, 1);

        tex2.SetPixel(0, 0, Color.gray);
        tex2.Apply();
        for (int i = 0; i < 1000; i++)
        {
            if (i % 2 == 0)
            {
                GUI.DrawTexture(new Rect(0, i * NODE_HEIGHT, BTreeWin.sInstance.position.width, NODE_HEIGHT), tex1);
            }
            else
            {
                GUI.DrawTexture(new Rect(0, i * NODE_HEIGHT, BTreeWin.sInstance.position.width, NODE_HEIGHT), tex2);
            }
        }

        if (cur_tree != null && cur_tree.m_cRoot != null)
        {
            int xx = 0;
            int yy = 0;
            cur_tree.m_cRoot.Render(xx, ref yy);
        }

        GUI.EndScrollView();
        //////////////////// draw the tree /////////////////////

        //////////////////// draw editor gui /////////////////////
        GUI.BeginGroup(new Rect(position.width - GUI_WIDTH, 0, 300, 1000));
        int          x   = 0;
        int          y   = 0;
        List <BTree> lst = BTreeMgr.sInstance.GetTrees();

        if (GUI.Button(new Rect(x, y, 200, 40), "Load"))
        {
            cur_tree              = null;
            cur_node              = null;
            cur_tree_index        = -1;
            last_tree_index       = -1;
            select_create_node_id = -1;
            select = null;

            BTreeMgr.sInstance.EditorLoad();
        }
        y += 40;
        if (GUI.Button(new Rect(x, y, 200, 40), "Save Editor BTree"))
        {
            BTreeMgr.sInstance.EditorSave();
            AssetDatabase.Refresh();
        }
        y += 40;
        if (GUI.Button(new Rect(x, y, 200, 40), "Save BTree"))
        {
//			BTreeMgr.sInstance.SaveEx();
            AssetDatabase.Refresh();
        }
        y += 40;
        GUI.Label(new Rect(x, y, 200, 20), "=======================");
        y += 20;

        this.m_strInputName = GUI.TextField(new Rect(x, y + 10, 100, 20), this.m_strInputName);
        if (GUI.Button(new Rect(x + 100, y, 100, 40), "create tree"))
        {
            if (this.m_strInputName != "")
            {
                cur_node = null;
                BTree tree = new BTree();
                tree.m_strName = this.m_strInputName;
                BTreeMgr.sInstance.Add(tree);
                lst      = BTreeMgr.sInstance.GetTrees();
                cur_tree = tree;
                for (int i = 0; i < lst.Count; i++)
                {
                    if (lst[i].m_strName == tree.m_strName)
                    {
                        cur_tree_index = i;
                        break;
                    }
                }
                last_tree_index = cur_tree_index;
                Repaint();
            }
        }
        y += 40;
        if (GUI.Button(new Rect(x, y, 200, 40), "remove tree"))
        {
            cur_node = null;
            BTreeMgr.sInstance.Remove(cur_tree);
            lst             = BTreeMgr.sInstance.GetTrees();
            cur_tree        = null;
            cur_tree_index  = -1;
            last_tree_index = -1;
            Repaint();
        }
        y += 40;
        GUI.Label(new Rect(x, y, 200, 20), "=======================");
        y += 20;

        string[] treeNames = new string[lst.Count];
        for (int i = 0; i < lst.Count; i++)
        {
            treeNames[i] = lst[i].m_strName;
        }
        cur_tree_index = EditorGUI.Popup(new Rect(x, y, 200, 45), cur_tree_index, treeNames);
        if (cur_tree_index != last_tree_index)
        {
            last_tree_index = cur_tree_index;
            cur_tree        = lst[cur_tree_index];
            cur_node        = null;
        }
        y += 40;
        GUI.Label(new Rect(x, y, 200, 20), "=======================");
        y += 20;

        if (cur_tree != null)
        {
            GUI.Label(new Rect(x, y, 200, 20), "TreeName: " + cur_tree.m_strName);
            y += 20;
            cur_tree.m_strName = GUI.TextField(new Rect(x, y, 100, 20), cur_tree.m_strName);
            y += 20;
        }
        select_create_node_id = EditorGUI.Popup(new Rect(x, y, 100, 40), select_create_node_id, BNodeFactory.sInstance.GetNodeLst());
        if (GUI.Button(new Rect(x + 100, y, 100, 40), "create root"))
        {
            if (select_create_node_id >= 0)
            {
                BNode node = BNodeFactory.sInstance.Create(select_create_node_id);
                if (cur_tree != null)
                {
                    cur_tree.m_cRoot = node;
                }
            }
        }
        y += 40;
        if (GUI.Button(new Rect(x, y, 200, 40), "clear"))
        {
            if (cur_tree != null)
            {
                cur_tree.Clear();
            }
        }
        y += 40;
        GUI.Label(new Rect(x, y, 200, 20), "=======================");
        y += 20;
        if (cur_node != null)
        {
            GUI.Label(new Rect(x, y, 300, 20), "Node Type: " + cur_node.GetType().FullName);
            y += 20;
            GUI.Label(new Rect(x, y, 200, 20), "Node Name: " + cur_node.GetName());
            y += 20;
            GUI.Label(new Rect(x, y, 200, 15), "=======================");
            y += 15;
            cur_node.RenderEditor(x, y);
        }
        //
        GUI.EndGroup();
        //////////////////// draw editor gui /////////////////////
    }
Exemple #7
0
    private const int _defaultCapacity = 4; //默认大小
    //private const int _maxCapacity = 1000;

    public NodeList(BNode node)
    {
        _items = new BNode[_defaultCapacity];
        Insert(node);
    }
		public string GetPersistentBNodeId(BNode node) {
			ResourceKey rk = (ResourceKey)GetResourceKey(node);
			if (rk == null) return null;
			return GetStoreGuid() + ":" + rk.ResId.ToString();
		}
Exemple #9
0
        private List <EnergyInfo03> AddDataToCache()
        {
            var userData = UserData;
            var cacheKey = WebUtility.GetCacheKeyName(userData, "energy-003-report");

            HttpRuntime.Cache.Remove(cacheKey);

            if (String.IsNullOrEmpty(RangeField.RawValue.ToString()))
            {
                return(new List <EnergyInfo03>());
            }
            var period     = (EnmPeriod)int.Parse(PeriodField.SelectedItem.Value);
            var startDate  = DateTime.Parse(StartDate.RawText);
            var endDate    = DateTime.Parse(EndDate.RawText).AddSeconds(86399);
            var tstartDate = startDate.AddYears(-1);
            var tendDate   = endDate.AddYears(-1);
            var ranges     = RangeField.RawValue.ToString();
            var auxSet     = new string[] { "NHPAT", "NHPBT", "NHPCT", "NHPDT", "NHPET", "NHPFT" };

            var result = new List <EnergyInfo03>();

            if (ranges == "root")
            {
                #region root
                var nodeEntity = new BNode();
                foreach (var lsc in userData.LscUsers)
                {
                    var def   = this.GetEntities(lsc.LscID.ToString(), lsc.LscName, period, startDate, endDate);
                    var nodes = nodeEntity.GetNodes(lsc.LscID, EnmNodeType.Aic, null, auxSet, null);
                    if (nodes.Count > 0)
                    {
                        var values    = nodeEntity.GetElecValues(lsc.LscID, startDate, endDate, period);
                        var valWnodes = from node in nodes
                                        join value in values on node.NodeID equals value.NodeId
                                        select new { Start = value.Start, End = value.End, Value = value.Value };

                        def.Value = valWnodes.Sum(v => v.Value);

                        var tvalues    = nodeEntity.GetElecValues(lsc.LscID, tstartDate, tendDate, period);
                        var tvalWnodes = from node in nodes
                                         join value in tvalues on node.NodeID equals value.NodeId
                                         select new { Start = value.Start, End = value.End, Value = value.Value };

                        def.TValue = tvalWnodes.Sum(v => v.Value);
                    }

                    result.Add(def);
                }
                #endregion
            }
            else
            {
                var keys = WebUtility.ItemSplit(ranges);
                if (keys.Length != 5)
                {
                    return(result);
                }

                var lscId       = int.Parse(keys[0]);
                var groupId     = int.Parse(keys[1]);
                var nodeId      = int.Parse(keys[2]);
                var nodeType    = int.Parse(keys[3]);
                var remark      = keys[4];
                var enmNodeType = Enum.IsDefined(typeof(EnmNodeType), nodeType) ? (EnmNodeType)nodeType : EnmNodeType.Null;
                if (enmNodeType == EnmNodeType.LSC)
                {
                    #region lsc
                    var lscUser = userData.LscUsers.Find(l => l.LscID == lscId);
                    if (lscUser != null)
                    {
                        var nodeEntity = new BNode();
                        var values     = new List <ElecValueInfo>();
                        var tvalues    = new List <ElecValueInfo>();
                        var nodes      = nodeEntity.GetNodes(lscUser.LscID, EnmNodeType.Aic, null, auxSet, null);
                        if (nodes.Count > 0)
                        {
                            values  = nodeEntity.GetElecValues(lscUser.LscID, startDate, endDate, period);
                            tvalues = nodeEntity.GetElecValues(lscUser.LscID, tstartDate, tendDate, period);
                        }

                        var valWnodes = from node in nodes
                                        join value in values on node.NodeID equals value.NodeId
                                        select new {
                            Area  = node.Area2ID,
                            Start = value.Start,
                            End   = value.End,
                            Value = value.Value
                        };

                        var valWgrp = from vn in valWnodes
                                      group vn by new { vn.Area } into g
                            select new {
                            Area  = g.Key.Area,
                            Value = g.Sum(v => v.Value)
                        };

                        var tvalWnodes = from node in nodes
                                         join value in tvalues on node.NodeID equals value.NodeId
                                         select new {
                            Area  = node.Area2ID,
                            Start = value.Start,
                            End   = value.End,
                            Value = value.Value
                        };

                        var tvalWgrp = from vn in tvalWnodes
                                       group vn by new { vn.Area } into g
                            select new {
                            Area  = g.Key.Area,
                            Value = g.Sum(v => v.Value)
                        };

                        var gnodes = lscUser.Group.GroupNodes.FindAll(gti => gti.NodeType == EnmNodeType.Area && gti.Remark.Equals("2"));
                        foreach (var gn in gnodes)
                        {
                            var def = this.GetEntities(string.Format("{0}-{1}", gn.LscID, gn.NodeID), gn.NodeName, period, startDate, endDate);
                            if (nodes.Count > 0 && values.Count > 0)
                            {
                                var details = valWgrp.Where(m => m.Area == gn.NodeID);
                                def.Value = details.Sum(v => v.Value);

                                var tdetails = tvalWgrp.Where(m => m.Area == gn.NodeID);
                                def.TValue = tdetails.Sum(v => v.Value);
                            }
                            result.Add(def);
                        }
                    }
                    #endregion
                }
                else if (enmNodeType == EnmNodeType.Area && remark.Equals("2"))
                {
                    #region area2
                    var lscUser = userData.LscUsers.Find(l => l.LscID == lscId);
                    if (lscUser != null)
                    {
                        var nodeEntity = new BNode();
                        var values     = new List <ElecValueInfo>();
                        var tvalues    = new List <ElecValueInfo>();
                        var nodes      = nodeEntity.GetNodes(lscUser.LscID, EnmNodeType.Aic, null, auxSet, null);
                        if (nodes.Count > 0)
                        {
                            values  = nodeEntity.GetElecValues(lscUser.LscID, startDate, endDate, period);
                            tvalues = nodeEntity.GetElecValues(lscUser.LscID, tstartDate, tendDate, period);
                        }

                        var valWnodes = from node in nodes
                                        join value in values on node.NodeID equals value.NodeId
                                        select new {
                            Area  = node.Area3ID,
                            Start = value.Start,
                            End   = value.End,
                            Value = value.Value
                        };

                        var valWgrp = from vn in valWnodes
                                      group vn by new { vn.Area } into g
                            select new {
                            Area  = g.Key.Area,
                            Value = g.Sum(v => v.Value)
                        };

                        var tvalWnodes = from node in nodes
                                         join value in tvalues on node.NodeID equals value.NodeId
                                         select new {
                            Area  = node.Area3ID,
                            Start = value.Start,
                            End   = value.End,
                            Value = value.Value
                        };

                        var tvalWgrp = from vn in tvalWnodes
                                       group vn by new { vn.Area } into g
                            select new {
                            Area  = g.Key.Area,
                            Value = g.Sum(v => v.Value)
                        };

                        var gnodes = lscUser.Group.GroupNodes.FindAll(gti => gti.NodeType == EnmNodeType.Area && gti.LastNodeID == nodeId);
                        foreach (var gn in gnodes)
                        {
                            var def = this.GetEntities(string.Format("{0}-{1}", gn.LscID, gn.NodeID), gn.NodeName, period, startDate, endDate);
                            if (nodes.Count > 0 && values.Count > 0)
                            {
                                var details = valWgrp.Where(m => m.Area == gn.NodeID);
                                def.Value = details.Sum(v => v.Value);

                                var tdetails = tvalWgrp.Where(m => m.Area == gn.NodeID);
                                def.TValue = tdetails.Sum(v => v.Value);
                            }
                            result.Add(def);
                        }
                    }
                    #endregion
                }
                else if (enmNodeType == EnmNodeType.Area && remark.Equals("3"))
                {
                    #region area3
                    var lscUser = userData.LscUsers.Find(l => l.LscID == lscId);
                    if (lscUser != null)
                    {
                        var nodeEntity = new BNode();
                        var values     = new List <ElecValueInfo>();
                        var tvalues    = new List <ElecValueInfo>();
                        var nodes      = nodeEntity.GetNodes(lscUser.LscID, EnmNodeType.Aic, null, auxSet, null);
                        if (nodes.Count > 0)
                        {
                            values  = nodeEntity.GetElecValues(lscUser.LscID, startDate, endDate, period);
                            tvalues = nodeEntity.GetElecValues(lscUser.LscID, tstartDate, tendDate, period);
                        }

                        var valWnodes = from node in nodes
                                        join value in values on node.NodeID equals value.NodeId
                                        select new {
                            Station = node.StaID,
                            Start   = value.Start,
                            End     = value.End,
                            Value   = value.Value
                        };

                        var valWgrp = from vn in valWnodes
                                      group vn by new { vn.Station } into g
                            select new {
                            Station = g.Key.Station,
                            Value   = g.Sum(v => v.Value)
                        };

                        var tvalWnodes = from node in nodes
                                         join value in tvalues on node.NodeID equals value.NodeId
                                         select new {
                            Station = node.StaID,
                            Start   = value.Start,
                            End     = value.End,
                            Value   = value.Value
                        };

                        var tvalWgrp = from vn in tvalWnodes
                                       group vn by new { vn.Station } into g
                            select new {
                            Station = g.Key.Station,
                            Value   = g.Sum(v => v.Value)
                        };

                        var gnodes = lscUser.Group.GroupNodes.FindAll(gti => gti.NodeType == EnmNodeType.Sta && gti.LastNodeID == nodeId);
                        foreach (var gn in gnodes)
                        {
                            var def = this.GetEntities(string.Format("{0}-{1}", gn.LscID, gn.NodeID), gn.NodeName, period, startDate, endDate);
                            if (nodes.Count > 0 && values.Count > 0)
                            {
                                var details = valWgrp.Where(m => m.Station == gn.NodeID);
                                def.Value = details.Sum(v => v.Value);

                                var tdetails = tvalWgrp.Where(m => m.Station == gn.NodeID);
                                def.TValue = tdetails.Sum(v => v.Value);
                            }
                            result.Add(def);
                        }
                    }
                    #endregion
                }
            }

            #region total
            if (result.Count > 0)
            {
                var def = this.GetEntities("TOTAL", "总计", period, startDate, endDate);
                def.Value  = result.Sum(v => v.Value);
                def.TValue = result.Sum(v => v.TValue);
                result.Add(def);
            }
            #endregion

            var cacheDuration = Int32.Parse(WebConfigurationManager.AppSettings["DefaultCacheDuration"]);
            HttpRuntime.Cache.Insert(cacheKey, result, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(cacheDuration), CacheItemPriority.Default, null);
            return(result);
        }
Exemple #10
0
        /// <summary>
        /// Add Data To Cache
        /// </summary>
        private List <AIStaticGridInfo> AddDataToCache()
        {
            var userData = UserData;
            var cacheKey = WebUtility.GetCacheKeyName(userData, "his-ai-static-values");

            HttpRuntime.Cache.Remove(cacheKey);

            var lscIds = new List <Int32>();
            var texts  = new List <String>();
            var gnodes = new List <GroupTreeInfo>();

            if (LscsComboBox.SelectedIndex > 0)
            {
                var ids = WebUtility.ItemSplit(LscsComboBox.SelectedItem.Value);
                if (ids.Length != 2)
                {
                    return(null);
                }
                var lscId   = Int32.Parse(ids[0]);
                var groupId = Int32.Parse(ids[1]);
                var lscUser = userData.LscUsers.Find(lu => { return(lu.LscID == lscId); });
                if (lscUser == null)
                {
                    return(null);
                }

                lscIds.Add(lscId);
                gnodes.AddRange(lscUser.Group.GroupNodes);
            }
            else
            {
                lscIds.AddRange(userData.LscUsers.Select(lu => lu.LscID));
                gnodes.AddRange(userData.LscUsers.SelectMany(lu => lu.Group.GroupNodes));
            }

            var area2Id    = WebUtility.DefaultInt32;
            var area3Id    = WebUtility.DefaultInt32;
            var devTypeId  = WebUtility.DefaultInt32;
            var fromTime   = DateTime.Parse(BeginFromDate.Text);
            var toTime     = DateTime.Parse(BeginToDate.Text);
            var filterText = WebUtility.StringSplit(FilterText.Text.Trim());
            var filterType = Int32.Parse(FilterList.SelectedItem.Value);

            if (Area2ComboBox.SelectedIndex > 0)
            {
                area2Id = Int32.Parse(Area2ComboBox.SelectedItem.Value);
            }
            if (Area3ComboBox.SelectedIndex > 0)
            {
                area3Id = Int32.Parse(Area3ComboBox.SelectedItem.Value);
            }
            if (DevTypeComboBox.SelectedIndex > 0)
            {
                devTypeId = Int32.Parse(DevTypeComboBox.SelectedItem.Value);
            }

            foreach (var ft in filterText)
            {
                if (String.IsNullOrEmpty(ft.Trim()))
                {
                    continue;
                }
                texts.Add(ft.Trim());
            }

            if (area3Id == WebUtility.DefaultInt32 && devTypeId == WebUtility.DefaultInt32 && texts.Count == 0)
            {
                WebUtility.ShowMessage(EnmErrType.Warning, "数据量过多,请更换查询条件后重试!");
                return(null);
            }

            if (toTime.Subtract(fromTime).TotalDays > 30)
            {
                WebUtility.ShowMessage(EnmErrType.Warning, "查询时间必须在30天内!");
                return(null);
            }

            var nodeEntity       = new BNode();
            var staticGridValues = new List <AIStaticGridInfo>();
            var staticValues     = nodeEntity.GetAIStatic(lscIds.ToArray(), fromTime, toTime);

            if (staticValues.Count > 0)
            {
                var nodes = new BNode().GetAINodeValues(lscIds.ToArray(), area2Id, area3Id, devTypeId, filterType, texts.ToArray(), MatchMenuItem.Checked);
                nodes = (from n in nodes
                         join gn in gnodes on new { n.LscID, n.DevID, NodeType = EnmNodeType.Dev } equals new { gn.LscID, DevID = gn.NodeID, gn.NodeType }
                         select n).ToList();

                staticGridValues = (from ai in staticValues
                                    join node in nodes on ai.NodeID equals node.NodeID
                                    orderby ai.BeginTime descending
                                    select new AIStaticGridInfo {
                    LscID = node.LscID,
                    LscName = node.LscName,
                    Area1Name = node.Area1Name,
                    Area2Name = node.Area2Name,
                    Area3Name = node.Area3Name,
                    StaName = node.StaName,
                    DevName = node.DevName,
                    NodeID = node.NodeID,
                    NodeType = node.NodeType,
                    NodeName = node.NodeName,
                    TypeName = node.DevTypeName,
                    ProdName = node.ProdName,
                    Remark = node.Remark,
                    BeginTime = ai.BeginTime,
                    EndTime = ai.EndTime,
                    OclValue = ai.OclValue,
                    AvgValue = ai.AvgValue,
                    MaxValue = ai.MaxValue,
                    MinValue = ai.MinValue,
                    MaxTime = ai.MaxTime,
                    MinTime = ai.MinTime
                }).ToList();
            }

            int cacheDuration = Int32.Parse(WebConfigurationManager.AppSettings["DefaultCacheDuration"]);

            HttpRuntime.Cache.Insert(cacheKey, staticValues, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(cacheDuration), CacheItemPriority.Default, null);
            return(staticGridValues);
        }
Exemple #11
0
        /// <summary>
        /// Given a shape, fill the session with its closed islands.
        /// </summary>
        /// <param name="shape">The shape to analyze.</param>
        /// <returns>The number of islands extracted.</returns>
        public int ExtractFillLoops(BShape shape)
        {
            int ret = 0;

            List <BNode> islandNodes = new List <BNode>();

            // For all loops in the shape, extract a single peice of each
            // unique circular island.
            foreach (BLoop loop in shape.loops)
            {
                HashSet <BNode> toScan = new HashSet <BNode>(loop.nodes);

                while (toScan.Count > 0)
                {
                    BNode bn = Utils.GetFirstInHash(toScan);

                    BNode.EndpointQuery eq = bn.GetPathLeftmost();

                    // If cyclical, save a single node to scan the island later
                    if (eq.result == BNode.EndpointResult.Cyclical)
                    {
                        islandNodes.Add(bn);
                    }

                    // And remove every part of it from what we're going to
                    //scan in the future.
                    BNode it = bn;
                    while (true)
                    {
                        toScan.Remove(it);

                        it = it.next;
                        if (it == null || it == eq.node)
                        {
                            break;
                        }
                    }
                }
            }

            // Extra islands from the looped nodes we've collected.
            foreach (BNode bisln in islandNodes)
            {
                BSample bstart = bisln.sample;
                BSample bit    = bstart;

                FillIsland island = new FillIsland();
                this.islands.Add(island);
                ++ret;

                FillSegment firstSeg = null;
                FillSegment lastSeg  = null;

                // For now we're going to assume the samples are well formed.
                while (true)
                {
                    FillSegment fs = new FillSegment();

                    // Transfer positions. We keep a local copy of positions, but by convention,
                    // the prevPos will match the prev's nextPos, and the nextPos will match
                    // the next's prevPos.
                    fs.pos = bit.pos;

                    island.segments.Add(fs);

                    if (firstSeg == null)
                    {
                        firstSeg = fs;
                    }
                    else
                    {
                        lastSeg.next = fs;
                        fs.prev      = lastSeg;
                    }

                    lastSeg = fs;

                    bit = bit.next;
                    if (bit == bstart)
                    {
                        break;
                    }
                }
                lastSeg.next  = firstSeg;
                firstSeg.prev = lastSeg;

                // Delme
                if (island.TestValidity() == false)
                {
                    throw new System.Exception("FillSession.ExtractFillLoops produced invalid island.");
                }
            }


            return(ret);
        }
Exemple #12
0
        /// <summary>
        /// Given a font glyph, generate a formal path for it.
        /// </summary>
        /// <param name="glyph">The glyph to turn into a path.</param>
        /// <param name="l">The layer to create the shape in.</param>
        /// <param name="offset">The offset to translate the glyph.</param>
        /// <param name="scale">The scale of the glyph, with 1.0 being the
        /// default size.</param>
        /// <returns>The created path. If the glyph has multiple
        /// contours, they will be created as individual loops.</returns>
        public static BShape GenerateGlyph(
            Font.Glyph glyph,
            Layer l,
            Vector2 offset,
            float scale)
        {
            BShape shapeLetter = new BShape(Vector2.zero, 0.0f);

            shapeLetter.layer = l;

            if (l != null)
            {
                l.shapes.Add(shapeLetter);
            }

            // Generate each contour in the glyph. When we're iterating through the glyph points,
            // we need to remember we're dealing with two possible conventions at once - TTF/OTF and
            // CFF.
            //
            // Remember TTF/OTF uses quadratic Beziers and the control flags.
            //
            // While CCF uses cubic Beziers and the point tangents and tangent flags.
            for (int j = 0; j < glyph.contours.Count; ++j)
            {
                BLoop loopCont = new BLoop(shapeLetter);

                //https://stackoverflow.com/questions/20733790/truetype-fonts-glyph-are-made-of-quadratic-bezier-why-do-more-than-one-consecu
                Font.Contour cont = glyph.contours[j];

                for (int k = 0; k < cont.points.Count; ++k)
                {
                    int nextId = (k + 1) % cont.points.Count;
                    // If two control points are next to each other, there's an implied
                    // point in between them at their average. The easiest way to handle
                    // that is to make a representation where we manually inserted them
                    // to define them explicitly.
                    //
                    // NOTE: We should probably just directly "sanitize" this information
                    // when it's first loaded.
                    if (cont.points[k].isControl == true && cont.points[nextId].isControl == true)
                    {
                        Font.Point pt = new Font.Point();
                        pt.isControl = false;
                        pt.position  = (cont.points[k].position + cont.points[nextId].position) * 0.5f;

                        // Things that process this data may want to know it's implied, especially
                        // diagnostic tools.
                        pt.implied = true;

                        cont.points.Insert(nextId, pt);
                        ++k;
                    }
                }

                BNode   firstNode = null;   // Used to know what to link the last node to when we're done looping.
                BNode   prevNode  = null;   // Used to have a record of the last node when we're done looping.
                Vector2?lastTan   = null;   // The last used tangent when dealing with control points.

                // Point are now either points, or curve controls surrounded by points -
                // or it's a CFF and we don't actually care about control points since we have
                // explicitly defined tangents.
                //
                // The code is written to handle both without explicitly knowing which system is being used.
                for (int k = 0; k < cont.points.Count; ++k)
                {
                    Vector2 ptpos = cont.points[k].position * scale + offset;

                    if (cont.points[k].isControl == false)
                    {
                        BNode node = new BNode(loopCont, ptpos);
                        loopCont.nodes.Add(node);

                        if (lastTan.HasValue == true)
                        {
                            node.UseTanIn = true;
                            node.TanIn    = (lastTan.Value - ptpos) * (2.0f / 3.0f) * scale;
                        }

                        lastTan = null;
                        if (prevNode != null)
                        {
                            node.prev     = prevNode;
                            prevNode.next = node;
                        }

                        if (firstNode == null)
                        {
                            firstNode = node;
                        }

                        int kPrev = (k - 1 + cont.points.Count) % cont.points.Count;

                        if (k != 0 && cont.points[kPrev].isControl == false && cont.points[kPrev].useTangentOut == false)
                        {
                            prevNode.UseTanOut = false;
                            node.UseTanIn      = false;
                        }

                        if (cont.points[k].useTangentIn == true)
                        {
                            node.UseTanIn = true;
                            node.TanIn    = cont.points[k].tangentIn;
                        }

                        if (cont.points[k].useTangentOut == true)
                        {
                            node.UseTanOut = true;
                            node.TanOut    = cont.points[k].tangentOut;
                        }

                        node.FlagDirty();
                        prevNode = node;
                    }
                    else // if (cont.points[k].control == true)
                    {
                        lastTan = ptpos;

                        if (prevNode != null)
                        {
                            prevNode.UseTanOut = true;
                            prevNode.TanOut    = (ptpos - prevNode.Pos) * (2.0f / 3.0f) * scale;
                        }
                    }
                }

                if (firstNode != null)
                {
                    prevNode.next  = firstNode;
                    firstNode.prev = prevNode;

                    if (
                        cont.points[0].isControl == false &&
                        cont.points[0].useTangentIn == false &&
                        cont.points[cont.points.Count - 1].isControl == false &&
                        cont.points[cont.points.Count - 1].useTangentOut == false)
                    {
                        firstNode.UseTanIn = false;
                        prevNode.UseTanOut = false;
                    }

                    if (lastTan.HasValue == true)
                    {
                        firstNode.UseTanIn = true;
                        firstNode.TanIn    = (lastTan.Value - firstNode.Pos) * (2.0f / 3.0f) * scale;
                    }
                }
            }

            return(shapeLetter);
        }
Exemple #13
0
        /// <summary>
        /// Given a BShape that was created from a font glyph, modify as needed so that
        /// it can be immediately filled properly.
        /// </summary>
        /// <param name="shape"></param>
        public static void BridgeGlyph(BShape shape)
        {
            // Find the outer-most point
            BNode   maxXNode;
            float   maxXT;
            Vector2 maxV;

            BNode.GetMaxPoint(shape.EnumerateNodes(), out maxXNode, out maxV, out maxXT, 0);

            if (maxXNode == null)
            {
                return;
            }

            float wind = BNode.CalculateWinding(maxXNode.Travel());

            // Separate positive from negative islands.
            List <BNode> positiveIslands = new List <BNode>();
            List <BNode> negativeIslands = new List <BNode>();

            foreach (BLoop bl in shape.loops)
            {
                List <BNode> islands = bl.GetIslands(IslandTypeRequest.Closed);
                for (int i = 0; i < islands.Count; ++i)
                {
                    float islW = BNode.CalculateWinding(islands[i].Travel());
                    if (Mathf.Sign(islW) == Mathf.Sign(wind))
                    {
                        positiveIslands.Add(islands[i]);
                    }
                    else
                    {
                        negativeIslands.Add(islands[i]);
                    }
                }
            }

            // We're going to do a non-generic kludge that should handle how most fonts are
            // created. For every negative shape, we're going to use it to hollow the next
            // largest positive shape. And then just leave positive (bridged) shapes left.

            foreach (BNode negIsl in negativeIslands)
            {
                List <BNode> positiveIslandOrder = new List <BNode>();

                List <BNode> negIslSegs = new List <BNode>(negIsl.Travel());
                BNode        negMaxX;
                Vector2      pos;
                float        t;
                BNode.GetMaxPoint(negIslSegs, out negMaxX, out pos, out t, 0);
                Vector2 control = pos + new Vector2(1.0f, 0.0f);

                // Add all nodes in all positive islands
                int   closest    = -1;
                float closestDst = 0.0f;
                Dictionary <BNode, int> indexFrom  = new Dictionary <BNode, int>();
                List <float>            interCurve = new List <float>();
                List <float>            interLine  = new List <float>();
                List <BNode>            interNode  = new List <BNode>();

                for (int i = 0; i < positiveIslands.Count; ++i)
                {
                    foreach (BNode bn in positiveIslands[i].Travel())
                    {
                        indexFrom.Add(bn, i);
                        int inters = bn.ProjectSegment(pos, control, interCurve, interLine, true);

                        for (int j = 0; j < inters; ++j)
                        {
                            interNode.Add(bn);
                        }
                    }
                }

                const float eps = 0.000001f;
                for (int i = 0; i < interCurve.Count;)
                {
                    if (interCurve[i] < -eps || interCurve[i] >= 1.0f + eps || interLine[i] < 0.0f)
                    {
                        interCurve.RemoveAt(i);
                        interLine.RemoveAt(i);
                        interNode.RemoveAt(i);
                    }
                    else
                    {
                        ++i;
                    }
                }

                // We now have all the value intersections going to the right,
                // and we have their distances (interLine). Time to go through
                // the entries from the nearest to the farthest islands, making
                // sure every island is only visited once.
                HashSet <BNode> usedNodes = new HashSet <BNode>();
                do
                {
                    if (interLine.Count == 0)
                    {
                        break;
                    }

                    int   idx = 0;
                    float dst = interLine[0];

                    for (int i = 0; i < interCurve.Count; ++i)
                    {
                        if (interLine[i] < dst)
                        {
                            idx = i;
                            dst = interLine[i];
                        }
                    }

                    List <BNode>         posIslandSegs = new List <BNode>(interNode[idx].Travel());
                    BNode                posRepl;
                    Boolean.BoundingMode bm = Boolean.Difference(posIslandSegs[0].parent, posIslandSegs, negIslSegs, out posRepl, false);
                    if (bm == Boolean.BoundingMode.Collision)
                    {
                        break;
                    }

                    if (bm == Boolean.BoundingMode.Degenerate)
                    {
                        bm = Boolean.GetLoopBoundingMode(posIslandSegs, negIslSegs);
                    }

                    if (bm == Boolean.BoundingMode.LeftSurroundsRight)
                    {
                        foreach (BNode bn in negMaxX.Travel())
                        {
                            bn.SetParent(interNode[idx].parent);
                        }


                        BNode.MakeBridge(negMaxX, t, interNode[idx], interCurve[idx]);
                    }
                    else if (bm == Boolean.BoundingMode.RightSurroundsLeft)
                    {
                        for (int i = 0; i < interCurve.Count;)
                        {
                            if (usedNodes.Contains(interNode[i]) == true)
                            {
                                interCurve.RemoveAt(i);
                                interLine.RemoveAt(i);
                                interNode.RemoveAt(i);
                            }
                            else
                            {
                                ++i;
                            }
                        }
                        continue;
                    }

                    //positiveIslands.RemoveAt(indexFrom[posIslandSegs[0]]);
                }while (false);
            }

            // The old implementation.
            // It was an attempt to make it generic without any
            // assumptions - but the current version takes advantage
            // of a property of how fonts are authored to be well-formed
            // and shows less edge cases.
            //
            //for(int p = 0; p < posIslands.Count; ++p)
            //{
            //    for(int n = 0; n < negIslands.Count; ++n)
            //    {
            //        List<BNode> posIslSegs = new List<BNode>(posIslands[p].Travel());
            //        List<BNode> negIslSegs = new List<BNode>(negIslands[n].Travel());
            //
            //        Boolean.BoundingMode bm = Boolean.Difference(posIslSegs[0].parent, posIslSegs, negIslSegs, false);
            //        if( bm == Boolean.BoundingMode.Collision)
            //        {
            //            // If there's a collision, the positive loops is modified and items will be clipped.
            //            //
            //            // This solution isn't completely robust because it's possible every node
            //            // of the original island is clipped.
            //            for(int i = 0; i < posIslSegs.Count; ++i)
            //            {
            //                if(posIslSegs[i].next != null && posIslSegs[i].prev != null)
            //                {
            //                    posIslands[p] = posIslSegs[i];
            //                    break;
            //                }
            //            }
            //        }
            //        else if( bm == Boolean.BoundingMode.LeftSurroundsRight)
            //        {
            //            // If the positive fully wraps the negative, bridge it.
            //            Dictionary<BNode, BNode> dmap = BNode.CloneNodes(negIslSegs, false);
            //            List<BNode> negClone = new List<BNode>();
            //            foreach(BNode b in negIslSegs)
            //            {
            //                BNode cl = dmap[b];
            //                cl.SetParent(posIslSegs[0].parent);
            //                negClone.Add(cl);
            //            }
            //
            //            BNode outer;
            //            BNode inner;
            //            float outT;
            //            float inT;
            //            BNode.FindBridge(posIslSegs, negClone, out inner, out outer, out inT, out outT);
            //            if(outer != null)
            //                BNode.MakeBridge(inner, inT, outer, outT);
            //        }
            //    }
            //}
            //
            //// Subtract negative nodes from any positive nodes it affects.
            //
            //// Get rid of negative nodes, we made sure their "cavity-ness"
            //// was applied in a way it will show when we tessellate the
            //// shape.
            //foreach(BNode bn in negIslands)
            //    bn.RemoveIsland(false);

            shape.CleanEmptyLoops();
        }
Exemple #14
0
        public BNode <T> CastNode(int position)
        {
            var buffer = new byte[LineLength];

            using (var fs = new FileStream(Path, FileMode.OpenOrCreate))
            {
                fs.Seek((position - 1) * LineLength + MetaDataLength, SeekOrigin.Begin);
                fs.Read(buffer, 0, LineLength);
            }

            string node_text = Encoding.UTF8.GetString(buffer);

            //REMIENDO
            node_text = node_text.Substring(1, node_text.Length - 1);
            node_text = node_text.Replace("\0", " ");
            node_text = node_text.Substring(0, (LineLength - 2));

            if (node_text.Substring(0, 20).Trim() == "")
            {
                return(null);
            }

            int id     = Convert.ToInt32(node_text.Substring(0, 20).Trim());
            int father = Convert.ToInt32(node_text.Substring(21, 25).Trim());

            string[] references = node_text.Substring(47, 25).Trim().Split(",");

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

            for (int i = 0; i < references.Length; i++)
            {
                references_list.Add(Convert.ToInt32(references[i]));
            }

            //////////////////////////////////////////////////////////////////
            string values = node_text.Substring(73, ((Grade) * FieldLength));
            ////////////////////////////////////////////////////////////////////

            ///////////////////////////////////////////////////////////////////
            List <string> values_list = new List <string>();

            for (int i = 0; i < ((Grade) * FieldLength); i += FieldLength)
            {
                string current_value = values.Substring(i, FieldLength);
                if (current_value.Trim() != "")
                {
                    values_list.Add(current_value);
                }
            }
            //////////////////////////////////////////////////////////////////////

            List <T> valuesT = (List <T>)ValueConverter.DynamicInvoke(values_list);

            BNode <T> node = new BNode <T>(Grade - 1);

            node.Childs = references_list;
            node.Id     = id;
            node.Father = father;
            node.Values = valuesT;

            return(node);
        }
 public RandSelectorNode(BNode p) : base(p)
 {
     child = null;
 }
		public string GetNodeId(BNode node) {
			ResourceKey rk = (ResourceKey)GetResourceKey(node);
			if (rk == null) return null;
			return rk.ResId.ToString();
		}
Exemple #17
0
 public Inverter(BNode t_node)
 {
     this.node = t_node;
 }
		Resource GetBinding(XmlElement binding, string v, Resource[] values, Hashtable bnodes) {
			if (values != null && values.Length == 1) return values[0];
			
			XmlElement b = (XmlElement)binding.FirstChild;
			while (b != null && b.GetAttribute("name") != v)
				b = (XmlElement)b.NextSibling;
			if (b == null)
				throw new ApplicationException("Invalid server response: Not all bindings present (" + v + "): " + binding.OuterXml);
			
			b = (XmlElement)b.FirstChild;
			if (b.Name == "uri")
				return new Entity(b.InnerText);
			else if (b.Name == "literal")
				return new Literal(b.InnerText); // datatype/lang
			else if (b.Name == "bnode") {
				string id = b.InnerText;
				if (bnodes.ContainsKey(id)) return (Entity)bnodes[id];
				Entity ret = new BNode();
				bnodes[id] = ret;
				return ret;
			}
			throw new ApplicationException("Invalid server response: " + b.OuterXml);
		}
Exemple #19
0
        /// <summary>
        /// Add data to cache.
        /// </summary>
        private List <Report013Entity> AddDataToCache()
        {
            var userData = UserData;
            var cacheKey = WebUtility.GetCacheKeyName(userData, "kpi-report-013");

            HttpRuntime.Cache.Remove(cacheKey);

            var lscs = new List <LscUserInfo>();

            if (LscsComboBox.SelectedIndex > 0)
            {
                var ids = WebUtility.ItemSplit(LscsComboBox.SelectedItem.Value);
                if (ids.Length == 2)
                {
                    var lscId   = Int32.Parse(ids[0]);
                    var groupId = Int32.Parse(ids[1]);
                    var lscUser = userData.LscUsers.Find(lu => { return(lu.LscID == lscId); });
                    if (lscUser != null)
                    {
                        lscs.Add(lscUser);
                    }
                }
            }
            else
            {
                lscs.AddRange(userData.LscUsers);
            }
            if (lscs.Count == 0)
            {
                return(null);
            }

            var staTypes = new Dictionary <Int32, String>();

            foreach (var dt in StaTypeMultiCombo.SelectedItems)
            {
                staTypes[Int32.Parse(dt.Value)] = dt.Text;
            }
            if (staTypes.Count == 0)
            {
                return(null);
            }

            var fromTime = DateTime.Parse(BeginDate.Text);
            var toTime   = DateTime.Parse(EndDate.Text);

            var texts      = new List <String>();
            var auxSets    = new List <String>();
            var filterText = WebUtility.StringSplit(NodeText.Text.Trim());

            foreach (var ft in filterText)
            {
                if (String.IsNullOrEmpty(ft.Trim()))
                {
                    continue;
                }
                if (FilterTypeList.SelectedItem.Value.Equals("1"))
                {
                    auxSets.Add(ft.Trim());
                }
                else
                {
                    texts.Add(ft.Trim());
                }
            }

            var nodeEntity  = new BNode();
            var otherEntity = new BOther();
            var source1     = new List <Report013Entity>();

            foreach (var lsc in lscs)
            {
                var bats = otherEntity.GetBatStatic(lsc.LscID, lsc.LscName, null, null, fromTime, null, null, toTime, 0, Int32.MaxValue);
                var fdev = from bat in bats
                           group bat by bat.DevID into g
                           select new {
                    DevID    = g.Key,
                    Interval = g.Max(t => t.LastTime) * 24 * 60
                };

                var rdev = from fv in fdev
                           where fv.Interval >= 15
                           select fv.DevID;

                if (rdev.Any())
                {
                    var nodes  = nodeEntity.GetNodes(lsc.LscID, EnmNodeType.Aic, texts.ToArray(), auxSets.ToArray(), null);
                    var values = nodeEntity.GetMaxHisAIV(lsc.LscID, fromTime, toTime);
                    var ndWavl = from node in nodes
                                 join val in values on node.NodeID equals val.NodeID into tp
                                 from nv in tp.DefaultIfEmpty()
                                 select new {
                        Node  = node,
                        Value = nv != null ? nv.Value : 0
                    };

                    var ndWre = from na in ndWavl
                                join id in rdev on na.Node.DevID equals id
                                select na;

                    var staWall = from nr in ndWre
                                  group nr by nr.Node.StaID into g
                                  select new {
                        StaID = g.Key,
                        Value = g.Min(v => v.Value)
                    };

                    var staWhg = from sw in staWall
                                 where sw.Value >= 47
                                 select sw;

                    source1.Add(new Report013Entity {
                        LscID        = lsc.LscID,
                        LscName      = lsc.LscName,
                        CorrectCount = staWhg.Count(),
                        AllCount     = staWall.Count()
                    });
                }
                else
                {
                    source1.Add(new Report013Entity {
                        LscID        = lsc.LscID,
                        LscName      = lsc.LscName,
                        CorrectCount = 0,
                        AllCount     = 0
                    });
                }
            }

            if (source1.Count > 0)
            {
                source1.Add(new Report013Entity {
                    LscID        = -100,
                    LscName      = "汇总(平均值)",
                    CorrectCount = (Int32)source1.Average(r => r.CorrectCount),
                    AllCount     = (Int32)source1.Average(r => r.AllCount)
                });
            }

            int cacheDuration = Int32.Parse(WebConfigurationManager.AppSettings["DefaultCacheDuration"]);

            HttpRuntime.Cache.Insert(cacheKey, source1, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(cacheDuration), CacheItemPriority.Default, null);
            return(source1);
        }
 public BNode(T value)
 {
     Value = value;
     Left  = null;
     Right = null;
 }
Exemple #21
0
        /// <summary>
        /// Add data to cache.
        /// </summary>
        private List <Report110Entity> AddDataToCache()
        {
            var userData  = UserData;
            var cacheKey1 = WebUtility.GetCacheKeyName(userData, "kpi-report-110");
            var cacheKey2 = WebUtility.GetCacheKeyName(userData, "kpi-report-110-02");

            HttpRuntime.Cache.Remove(cacheKey1);
            HttpRuntime.Cache.Remove(cacheKey2);

            var lscIds = new List <int>();

            if (LscsComboBox.SelectedIndex > 0)
            {
                var ids = WebUtility.ItemSplit(LscsComboBox.SelectedItem.Value);
                if (ids.Length == 2)
                {
                    var lscId   = Int32.Parse(ids[0]);
                    var groupId = Int32.Parse(ids[1]);
                    lscIds.Add(lscId);
                }
            }
            else
            {
                lscIds.AddRange(userData.LscUsers.Select(l => l.LscID));
            }
            if (lscIds.Count == 0)
            {
                return(null);
            }

            var staTypes = new Dictionary <Int32, String>();

            foreach (var dt in StaTypeMultiCombo.SelectedItems)
            {
                staTypes[Int32.Parse(dt.Value)] = dt.Text;
            }
            if (staTypes.Count == 0)
            {
                return(null);
            }

            var fromTime = DateTime.Parse(BeginDate.Text);
            var toTime   = DateTime.Parse(EndDate.Text);

            var texts      = new List <String>();
            var auxSets    = new List <String>();
            var filterText = WebUtility.StringSplit(NodeText.Text.Trim());

            foreach (var ft in filterText)
            {
                if (String.IsNullOrEmpty(ft.Trim()))
                {
                    continue;
                }
                if (FilterTypeList.SelectedItem.Value.Equals("1"))
                {
                    auxSets.Add(ft.Trim());
                }
                else
                {
                    texts.Add(ft.Trim());
                }
            }

            var lscEntity  = new BLsc();
            var nodeEntity = new BNode();
            var source1    = new List <Report110Entity>();
            var source2    = new Dictionary <String, List <StationInfo> >();

            foreach (var id in lscIds)
            {
                var lsc = lscEntity.GetLsc(id);
                if (lsc == null)
                {
                    continue;
                }

                //var instance = new Dictionary<string, NodeInfo>();
                //var nodes = nodeEntity.GetNodes(lsc.LscID, EnmNodeType.Aic, texts.ToArray(), auxSets.ToArray(), null);
                //foreach (var node in nodes) {
                //    instance[String.Format("{0}-{1}", node.LscID, node.StaID)] = node;
                //}

                var stations = new BOther().GetStations(lsc.LscID).FindAll(s => staTypes.ContainsKey(s.StaTypeID));
                var values   = nodeEntity.GetMaxHisAIV(lsc.LscID, fromTime, toTime);
                //var temp = from n in instance.Values
                //           join s in stations on new { n.LscID, n.StaID } equals new { s.LscID,s.StaID}
                //           join v in values on new { n.LscID, n.NodeID } equals new { v.LscID, v.NodeID }
                //           select new {
                //               Station = s,
                //               Node = n,
                //               Value = v.Value
                //           };

                var temp = from s in stations
                           join v in values on new { s.LscID, s.StaID } equals new { v.LscID, StaID = v.NodeID }
                select new {
                    Station = s,
                    Value   = v.Value
                };

                var correct = temp.Where(n => n.Value >= 1);
                source2[String.Format("{0}-CorrectCount", source1.Count)] = correct.Any() ? correct.Select(n => n.Station).ToList() : new List <StationInfo>();
                source2[String.Format("{0}-AllCount", source1.Count)]     = temp.Any() ? temp.Select(n => n.Station).ToList() : new List <StationInfo>();

                source1.Add(new Report110Entity {
                    LscID        = lsc.LscID,
                    LscName      = lsc.LscName,
                    CorrectCount = correct.Count(),
                    AllCount     = temp.Count()
                });
            }

            int cacheDuration = Int32.Parse(WebConfigurationManager.AppSettings["DefaultCacheDuration"]);

            HttpRuntime.Cache.Insert(cacheKey1, source1, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(cacheDuration), CacheItemPriority.Default, null);
            HttpRuntime.Cache.Insert(cacheKey2, source2, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(cacheDuration), CacheItemPriority.Default, null);
            return(source1);
        }
Exemple #22
0
    private void Enumming()
    {
        Event e = Event.current;

        if (e != null && e.keyCode != KeyCode.None && e.type == EventType.KeyUp && e.alt == true)
        {
            if (e.keyCode == KeyCode.A)
            {
                if (c != null)
                {
                    BNode n = new BNode();
                    c.nodes.Add((CNode)n);
                    CNode newN = c.nodes.nodes [c.nodes.nodes.Count - 1];
                    //c.nodes.nodes [c.nodes.nodes.Count - 1].chat = c;
                    c.nodes.nodes [c.nodes.nodes.Count - 1].name = "Gate";
                    newN.pos.position = e.mousePosition;
                    for (int i = 0; i < c.dict.keys.Count; i++)
                    {
                        CChecker checkNew = new CChecker();
                        checkNew.checkType    = CChecker.propertyCheck.NA;
                        checkNew.propertyName = c.dict.keys [i];
                        checkNew.value        = c.dict.value(c.dict.keys [i]);
                        newN.checkers.Add(checkNew);
                    }
                }
            }

            if (e.keyCode == KeyCode.S)
            {
                if (c != null)
                {
                    //				ScriptableObject n = ScriptableObject.CreateInstance<CPlayerWindow> ();
                    c.nodes.Add((CNode) new CPlayerWindow());
                    CNode newN = c.nodes.nodes [c.nodes.nodes.Count - 1];
                    //c.nodes.nodes [c.nodes.nodes.Count - 1].chat = c;
                    c.nodes.nodes [c.nodes.nodes.Count - 1].name = "Player Node";
                    newN.pos.position = e.mousePosition;
                    for (int i = 0; i < c.dict.keys.Count; i++)
                    {
                        CEffector ef = new CEffector();
                        ef.s    = c.dict.keys [i];
                        ef.f    = c.dict.value(c.dict.keys [i]);
                        ef.type = CEffector.operationType.NA;
                        newN.effectors.Add(ef);
                    }
                }
            }

            if (e.keyCode == KeyCode.D)
            {
                if (c != null)
                {
                    c.nodes.Add((CNode) new CNPCWindow());
                    CNode newN = c.nodes.nodes [c.nodes.nodes.Count - 1];
                    //c.nodes.nodes [c.nodes.nodes.Count - 1].chat = c;
                    c.nodes.nodes [c.nodes.nodes.Count - 1].name = "NPC";
                    newN.pos.position = e.mousePosition;
                    for (int i = 0; i < c.dict.keys.Count; i++)
                    {
                        CEffector ef = new CEffector();
                        ef.s    = c.dict.keys [i];
                        ef.f    = c.dict.value(c.dict.keys [i]);
                        ef.type = CEffector.operationType.NA;
                        newN.effectors.Add(ef);
                    }
                }
            }
        }
    }
Exemple #23
0
        /// <summary>
        /// Union boolean operation using a tracing strategy.
        /// </summary>
        /// <param name="islA">A node, on an island, to be unioned.</param>
        /// <param name="islB">A node, on another island, that is to be unioned.</param>
        /// <param name="loopInto">The destination loop, where the newly traced contents
        /// will be parented to.</param>
        /// <param name="onIsle">Output parameter, returns a node on the traced island.</param>
        /// <param name="removeInputs">If true, remove the island nodes of islA and islB from
        /// their parents after the operation is finished. This only happens if there is a
        /// collision to process.</param>
        /// <returns>True if the parameter islands touch and a traced result was created. Else, false.</returns>
        public static bool TraceUnion(
            BNode islA,
            BNode islB,
            BLoop loopInto,
            out BNode onIsle,
            bool removeInputs = true)
        {
            // Every node for both islands
            List <BNode> allNodes = new List <BNode>();
            List <Utils.BezierSubdivSample> outList = new List <Utils.BezierSubdivSample>();
            Dictionary <BNode, List <Utils.BezierSubdivSample> > dictCol = new Dictionary <BNode, List <Utils.BezierSubdivSample> >();

            GatherTraceData(islA, islB, allNodes, outList, dictCol);

            if (outList.Count == 0)
            {
                onIsle = null;
                return(false);
            }

            //
            //  FIND THE MOST EXTREME POINT
            //
            //////////////////////////////////////////////////
            // Rightmost node. We need to find a point on every segment that's on the most
            // extreme somewhere (i.e., leftmost, topmost, rightmost, bottom-most). That way
            // we know it's not inside the shape union.
            BNode   rtmst = islA;
            Vector2 rt    = rtmst.Pos;  // Point of rightmost
            float   lam   = 0.0f;       // Lambda of rightmost

            foreach (BNode bn in allNodes)
            {
                if (bn.GetMaxPoint(ref rt, ref lam, 0) == true)
                {
                    rtmst = bn;
                }
            }

            //  FIND THE ACTUAL STARTING POSITIONS
            //
            //////////////////////////////////////////////////
            // Given the rightmost postion we found earlier, we can't use that directly
            // because that's not a good endpoint for how we trace. A valid starting
            // point needs to also be a good end point for us to know when to stop without
            // creating awkward edge cases in the tracing code.
            //
            // Valid positions at the endpoints of a node, or the closest previous collision
            // point on the segment.
            List <Utils.BezierSubdivSample> lstBss;

            if (dictCol.TryGetValue(rtmst, out lstBss) == false)
            {
                lam = 0.0f;
            }
            else if (lam > lstBss[0].a.lEst)
            {
                lam = 0.0f;
            }
            else
            {
                for (int i = lstBss.Count - 1; i >= 0; --i)
                {
                    if (lam <= lstBss[i].a.lEst)
                    {
                        lam = lstBss[i].a.lEst;
                        break;
                    }
                }
            }

            //  PERFORM THE TRACING
            //
            //////////////////////////////////////////////////
            List <BNode> newPath = new List <BNode>();

            BNode.SubdivideInfo sdiFirst = rtmst.GetSubdivideInfo(lam);
            BNode bnPrevNew = new BNode(null, sdiFirst.subPos);

            bnPrevNew.TanIn     = sdiFirst.subIn;
            bnPrevNew.UseTanIn  = sdiFirst.subIn != Vector2.zero;
            bnPrevNew.TanOut    = sdiFirst.subOut;
            bnPrevNew.UseTanOut = sdiFirst.subOut != Vector2.zero;
            newPath.Add(bnPrevNew);

            BNode bnIt  = rtmst;
            float itLam = lam;

            BNode.SubdivideInfo sdiL;
            BNode.SubdivideInfo sdiR;

            while (true)
            {
                BNode bnPrev = bnIt;
                if (dictCol.TryGetValue(bnIt, out lstBss) == false)
                {
                    // If there are no collisions in the segment, just
                    // add the whole segment
                    itLam = 0.0f;
                    bnIt  = bnIt.next;

                    if (bnIt == rtmst && itLam == lam) // Are we back where we started?
                    {
                        // close the shape and we're done
                        bnPrevNew.TanIn    = bnIt.TanIn;
                        bnPrevNew.UseTanIn = true;

                        BNode prevToFirst = newPath[newPath.Count - 1];
                        prevToFirst.TanOut    = bnPrev.TanOut;
                        prevToFirst.UseTanOut = true;
                        break;
                    }
                    else
                    {
                        // Full copy. TanOut can be modified later.
                        BNode bnDirAdd = new BNode(null, bnIt.Pos);
                        bnDirAdd.TanOut    = bnIt.TanOut;
                        bnDirAdd.TanIn     = bnIt.TanIn;
                        bnDirAdd.UseTanIn  = bnIt.UseTanIn;
                        bnDirAdd.UseTanOut = bnIt.UseTanOut;
                        newPath.Add(bnDirAdd);

                        BNode prevToFirst = newPath[newPath.Count - 2];
                        prevToFirst.TanOut    = bnPrev.TanOut;
                        prevToFirst.UseTanOut = true;
                    }
                    continue;
                }

                // If there are collision points, trace only the segment
                // and swap the segment chain we're tracing with the one
                // we collided with.
                //
                // Where we've moved, in relationship to bnPrev.
                float itStart = itLam;
                float itEnd   = 1.0f;

                bool nextProc = false;
                for (int i = 0; i < lstBss.Count - 1; ++i)
                {
                    if (lstBss[i].a.lEst == itLam && i != lstBss.Count - 1)
                    {
                        itEnd = lstBss[i + 1].a.lEst;

                        // Figure out where we continue after jumping to the next item
                        bnIt     = lstBss[i + 1].b.node;
                        itLam    = lstBss[i + 1].b.lEst;
                        nextProc = true;
                        break;
                    }
                }

                if (nextProc == false)
                {
                    if (itLam == 0.0f)
                    {
                        // The first collision in the segment
                        itStart = 0.0f;
                        itEnd   = lstBss[0].a.lEst;

                        // Swap as we were in the loop directly above
                        bnIt  = lstBss[0].b.node;
                        itLam = lstBss[0].b.lEst;
                    }
                    else
                    {
                        // The last collision to the end
                        itStart = lstBss[lstBss.Count - 1].a.lEst;
                        itEnd   = 1.0f;

                        // Move on to the next node in the chain.
                        bnIt  = bnIt.next;
                        itLam = 0.0f;
                    }
                }

                bnPrev.GetSubdivideInfo(itStart, out sdiL, itEnd, out sdiR);

                if (bnIt == rtmst && itLam == lam) // Are we back where we started?
                {
                    // close the shape and we're done
                    bnPrevNew.TanIn    = sdiR.subIn;
                    bnPrevNew.UseTanIn = true;

                    newPath[newPath.Count - 1].TanOut    = sdiL.subOut;
                    newPath[newPath.Count - 1].UseTanOut = true;
                    break;
                }
                else
                {
                    // Add additional traced point.
                    BNode bnNew = new BNode(null, sdiR.subPos);
                    bnNew.TanIn    = sdiR.subIn;
                    bnNew.UseTanIn = true;

                    newPath[newPath.Count - 1].TanOut    = sdiL.subOut;
                    newPath[newPath.Count - 1].UseTanOut = true;

                    newPath.Add(bnNew);
                }
            }


            for (int i = 0; i < newPath.Count; ++i)
            {
                newPath[i].parent = loopInto;

                if (loopInto != null)
                {
                    loopInto.nodes.Add(newPath[i]);
                }

                newPath[i].next = newPath[(i + 1) % newPath.Count];
                newPath[i].prev = newPath[((i - 1) + newPath.Count) % newPath.Count];
            }

            if (newPath.Count > 0)
            {
                onIsle = newPath[0];
            }
            else
            {
                onIsle = null;
            }

            if (removeInputs == true)
            {
                foreach (BNode bn in allNodes)
                {
                    if (bn.parent != null)
                    {
                        bn.parent.RemoveNode(bn);
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Add data to cache.
        /// </summary>
        private List <OilEngineEntity> AddDataToCache()
        {
            var userData = UserData;
            var cacheKey = WebUtility.GetCacheKeyName(userData, "kpi-oil-engine-report");

            HttpRuntime.Cache.Remove(cacheKey);

            var lscs = new List <LscUserInfo>();

            if (LscsComboBox.SelectedIndex > 0)
            {
                var ids = WebUtility.ItemSplit(LscsComboBox.SelectedItem.Value);
                if (ids.Length != 2)
                {
                    return(null);
                }
                var lscId   = Int32.Parse(ids[0]);
                var groupId = Int32.Parse(ids[1]);
                var lscUser = userData.LscUsers.Find(lu => { return(lu.LscID == lscId); });
                if (lscUser == null)
                {
                    return(null);
                }
                lscs.Add(lscUser);
            }
            else
            {
                lscs.AddRange(userData.LscUsers);
            }

            var fromTime = DateTime.Parse(BeginFromDate.Text);
            var toTime   = DateTime.Parse(BeginToDate.Text);

            var stexts      = new List <String>();
            var sauxSets    = new List <String>();
            var sfilterText = WebUtility.StringSplit(SNodeText.Text.Trim());

            foreach (var ft in sfilterText)
            {
                if (String.IsNullOrEmpty(ft.Trim()))
                {
                    continue;
                }
                if (SFilterList.SelectedItem.Value.Equals("1"))
                {
                    sauxSets.Add(ft.Trim());
                }
                else
                {
                    stexts.Add(ft.Trim());
                }
            }

            var ytexts      = new List <String>();
            var yauxSets    = new List <String>();
            var yfilterText = WebUtility.StringSplit(YNodeText.Text.Trim());

            foreach (var ft in yfilterText)
            {
                if (String.IsNullOrEmpty(ft.Trim()))
                {
                    continue;
                }
                if (YFilterList.SelectedItem.Value.Equals("1"))
                {
                    yauxSets.Add(ft.Trim());
                }
                else
                {
                    ytexts.Add(ft.Trim());
                }
            }

            var devTypes = new Dictionary <Int32, String>();

            foreach (var dt in DevTypeMultiCombo.SelectedItems)
            {
                devTypes[Int32.Parse(dt.Value)] = dt.Text;
            }
            if (devTypes.Count == 0)
            {
                return(null);
            }

            var otherEntity = new BOther();
            var nodeEntity  = new BNode();
            var result      = new List <OilEngineEntity>();

            foreach (var lsc in lscs)
            {
                var stations = otherEntity.GetStations(lsc.LscID, lsc.Group.GroupID);

                var snodes = new List <NodeInfo>();
                var ynodes = new List <NodeInfo>();
                if (stexts.Count > 0 || sauxSets.Count > 0)
                {
                    snodes.AddRange(nodeEntity.GetNodes(lsc.LscID, EnmNodeType.Dic, stexts.ToArray(), sauxSets.ToArray(), devTypes.Keys.ToArray()));
                }
                if (ytexts.Count > 0 || yauxSets.Count > 0)
                {
                    ynodes.AddRange(nodeEntity.GetNodes(lsc.LscID, EnmNodeType.Dic, ytexts.ToArray(), yauxSets.ToArray(), devTypes.Keys.ToArray()));
                }

                if (Area2ComboBox.SelectedIndex > 0)
                {
                    var area2Id = Int32.Parse(Area2ComboBox.SelectedItem.Value);
                    stations = stations.FindAll(s => s.Area2ID == area2Id);
                    snodes   = snodes.FindAll(n => n.Area2ID == area2Id);
                    ynodes   = ynodes.FindAll(n => n.Area2ID == area2Id);
                }
                if (Area3ComboBox.SelectedIndex > 0)
                {
                    var area3Id = Int32.Parse(Area3ComboBox.SelectedItem.Value);
                    stations = stations.FindAll(s => s.Area3ID == area3Id);
                    snodes   = snodes.FindAll(n => n.Area3ID == area3Id);
                    ynodes   = ynodes.FindAll(n => n.Area3ID == area3Id);
                }

                var spairs = new List <OilEnginePair>();
                var sdiv   = nodeEntity.GetHisDIV(lsc.LscID, snodes.Select(n => n.NodeID).ToArray(), fromTime, toTime);
                foreach (var node in snodes)
                {
                    var curNodes = sdiv.FindAll(d => d.NodeID == node.NodeID).OrderBy(d => d.UpdateTime).ToList();

                    var interval  = 0d;
                    var startTime = DateTime.MinValue;
                    foreach (var cn in curNodes)
                    {
                        if (cn.Value == GJ && startTime == DateTime.MinValue)
                        {
                            startTime = cn.UpdateTime;
                        }
                        else if (cn.Value == ZC && startTime != DateTime.MinValue)
                        {
                            interval += cn.UpdateTime.Subtract(startTime).TotalMinutes;
                            startTime = DateTime.MinValue;
                        }
                    }

                    if (startTime != DateTime.MinValue)
                    {
                        interval += toTime.Subtract(startTime).TotalMinutes;
                        startTime = DateTime.MinValue;
                    }

                    spairs.Add(new OilEnginePair {
                        Node     = node,
                        Divs     = curNodes,
                        Interval = interval
                    });
                }

                var ypairs = new List <OilEnginePair>();
                var ydiv   = nodeEntity.GetHisDIV(lsc.LscID, ynodes.Select(n => n.NodeID).ToArray(), fromTime, toTime);
                foreach (var node in ynodes)
                {
                    var curNodes = ydiv.FindAll(d => d.NodeID == node.NodeID).OrderBy(d => d.UpdateTime).ToList();

                    var interval  = 0d;
                    var startTime = DateTime.MinValue;
                    foreach (var cn in curNodes)
                    {
                        if (cn.Value == GJ && startTime == DateTime.MinValue)
                        {
                            startTime = cn.UpdateTime;
                        }
                        else if (cn.Value == ZC && startTime != DateTime.MinValue)
                        {
                            interval += cn.UpdateTime.Subtract(startTime).TotalMinutes;
                            startTime = DateTime.MinValue;
                        }
                    }

                    if (startTime != DateTime.MinValue)
                    {
                        interval += toTime.Subtract(startTime).TotalMinutes;
                        startTime = DateTime.MinValue;
                    }

                    ypairs.Add(new OilEnginePair {
                        Node     = node,
                        Divs     = curNodes,
                        Interval = interval
                    });
                }

                var sresult = from s in spairs
                              group s by new { s.Node.LscID, s.Node.StaID } into g
                    select new {
                    LscID = g.Key.LscID,
                    StaID = g.Key.StaID,
                    Nodes = g
                };

                var yresult = from y in ypairs
                              group y by new { y.Node.LscID, y.Node.StaID } into g
                    select new {
                    LscID = g.Key.LscID,
                    StaID = g.Key.StaID,
                    Nodes = g
                };

                result.AddRange(from sta in stations
                                join sr in sresult on new { sta.LscID, sta.StaID } equals new { sr.LscID, sr.StaID } into lt1
                                from ss in lt1.DefaultIfEmpty()
                                join yr in yresult on new { sta.LscID, sta.StaID } equals new { yr.LscID, yr.StaID } into lt2
                                from ys in lt2.DefaultIfEmpty()
                                select new OilEngineEntity {
                    Station = sta,
                    SNodes  = ss != null ? ss.Nodes.ToList() : new List <OilEnginePair>(),
                    YNodes  = ys != null ? ys.Nodes.ToList() : new List <OilEnginePair>()
                });
            }

            int cacheDuration = Int32.Parse(WebConfigurationManager.AppSettings["DefaultCacheDuration"]);

            HttpRuntime.Cache.Insert(cacheKey, result, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(cacheDuration), CacheItemPriority.Default, null);
            return(result);
        }
Exemple #25
0
        /// <summary>
        /// Gather intersection data commonly used in boolean trace operations.
        /// </summary>
        /// <param name="islA">A node on a closed island used as the left path parameter.</param>
        /// <param name="islB">A node on a closed island used as the right path parameter.</param>
        /// <param name="allNodes">All the nodes found in the loop for islA and islB.</param>
        /// <param name="outList">
        /// A collection of all the collisions found between islA and islB. This also includes self
        /// intersections (such as collisions between islA and other parts of islA).</param>
        /// <param name="dictCol">A collection of collisions sorted per-node, and ordered by the
        /// point on the beziers they occured.</param>
        /// <remarks>The significance of the left and right paths depends on the operation this
        /// function is being used for.</remarks>
        public static void GatherTraceData(
            BNode islA,
            BNode islB,
            List <BNode> allNodes,
            List <Utils.BezierSubdivSample> outList,
            Dictionary <BNode, List <Utils.BezierSubdivSample> > dictCol)
        {
            foreach (BNode bnit in islA.Travel())
            {
                allNodes.Add(bnit); // Also collect for allNodes
            }
            foreach (BNode bnit in islB.Travel())
            {
                allNodes.Add(bnit); // Also collect for allNodes
            }
            //  SCAN AND LOG ALL COLLISIONS
            //
            //////////////////////////////////////////////////

            for (int i = 0; i < allNodes.Count - 1; ++i)
            {
                BNode bni = allNodes[i];
                // This check isn't as robust as it could be. While rare, a segment can create
                // a loop that causes an intersection with itself. But, these loops are set up
                // assuming loops can never do that.
                for (int j = i + 1; j < allNodes.Count; ++j)
                {
                    BNode bnj = allNodes[j];

                    // Make an output list that checks and cleans for each individual
                    // collision.
                    List <Utils.BezierSubdivSample> ol = new List <Utils.BezierSubdivSample>();
                    Utils.NodeIntersections(bni, bnj, 20, 0.00001f, ol);
                    Utils.BezierSubdivSample.CleanIntersectionList(ol);

                    foreach (Utils.BezierSubdivSample bss in ol)
                    {
                        // This part is trick and isn't as robust as it could be. Neighboring nodes
                        // are prone to creating false positives for collising at the ends where
                        // they are attached. We can't be too aggressive on culling these detections
                        // out though because it is possible that there could be tiny loops that
                        // back-track and legitimately collide with their segment neighbors
                        // *near* the ends. To do this properly we need to bounds check at the
                        // (cubic) curve roots instead of at extreemly low (0.001) and high (0.99)
                        // interpolation points.
                        if (
                            (bss.a.lEst < 0.001f && bss.a.node.prev == bss.b.node) ||
                            (bss.a.lEst > 0.99f && bss.a.node.next == bss.b.node))
                        {
                            continue;
                        }

                        outList.Add(bss);
                    }
                }
            }

            //  ORGANIZE COLLISIONS TO BE USABLE
            //
            //////////////////////////////////////////////////

            // Each node that has a collision has a ordered list of where collisions
            // happened. This makes the collision data FAR less unwieldy and more
            // usable. Note that because a collision involves two segments colliding
            // (ignoring self collisions) each collision will be added to two nodes;
            // where the list it's added to will be the "a" segment. If it's originally
            // labeled the "b" segment in the collision data, a and b are swapped.

            foreach (Utils.BezierSubdivSample bss in outList)
            {
                List <Utils.BezierSubdivSample> lstA;
                List <Utils.BezierSubdivSample> lstB;

                // Add a directly.
                if (dictCol.TryGetValue(bss.a.node, out lstA) == false)
                {
                    lstA = new List <Utils.BezierSubdivSample>();
                    dictCol.Add(bss.a.node, lstA);
                }
                lstA.Add(bss);

                // For b, swap b and a before adding so that it's also
                // a. This makes it so we don't need to branch to figure
                // out which NodeSubRgn (a or b) to reference for a given
                // key.
                Utils.BezierSubdivSample bssRec = bss.Reciprocal();
                if (dictCol.TryGetValue(bss.b.node, out lstB) == false)
                {
                    lstB = new List <Utils.BezierSubdivSample>();
                    dictCol.Add(bss.b.node, lstB);
                }
                lstB.Add(bssRec);
            }

            foreach (List <Utils.BezierSubdivSample> lst in dictCol.Values)
            {
                lst.Sort(_LexicalSubdivSort);
            }
        }
Exemple #26
0
        private static void ProcessResponse(string mimetype, Stream stream, object outputObj)
        {
            // If the user wants the output sent to a TextWriter, copy the response from
            // the response stream to the TextWriter. TODO: Get encoding from HTTP header.
            if (outputObj is TextWriter)
            {
                TextWriter tw = (TextWriter)outputObj;
                using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8)) {
                    char[] buffer = new char[512];
                    while (true)
                    {
                        int len = reader.Read(buffer, 0, buffer.Length);
                        if (len <= 0)
                        {
                            break;
                        }
                        tw.Write(buffer, 0, len);

                        if (Debug)
                        {
                            Console.Error.WriteLine(">> " + new String(buffer, 0, len));
                        }
                    }
                }
                tw.Flush();
                return;
            }

            // If the user wants a boolean out of this, then we're expecting a
            // SPARQL XML Results document with a boolean response element.
            if (outputObj is BooleanWrap)
            {
                BooleanWrap bw = (BooleanWrap)outputObj;

                if (mimetype != null && mimetype != "application/sparql-results+xml" && mimetype != "text/xml" && mimetype != "application/xml")
                {
                    throw new ApplicationException("The result of the query was not a SPARQL Results document.");
                }

                XmlReader xmldoc = new XmlTextReader(stream);
                {
                    // Move to the document element
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element)
                        {
                            break;
                        }
                    }

                    // Just check that it has the right local name.
                    if (xmldoc.LocalName != "sparql" || xmldoc.IsEmptyElement)
                    {
                        throw new ApplicationException("Invalid server response: Not a SPARQL results document.");
                    }

                    // Move to the next node.
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element)
                        {
                            break;
                        }
                    }

                    // If it's a head node, skip it.
                    if (xmldoc.LocalName == "head")
                    {
                        xmldoc.Skip();
                        // Move to the 'boolean' element, it better be next
                        while (xmldoc.Read())
                        {
                            if (xmldoc.NodeType == XmlNodeType.Element)
                            {
                                break;
                            }
                        }
                    }

                    if (xmldoc.LocalName != "boolean")
                    {
                        throw new ApplicationException("Invalid server response: Missing 'boolean' element.");
                    }

                    string value = xmldoc.ReadElementString();
                    bw.value = (value == "true");
                }

                if (Debug)
                {
                    Console.Error.WriteLine(">> " + bw.value);
                }

                return;
            }

            // If the user wants statements out of the response, read it with an RDFReader.
            if (outputObj is StatementSink)
            {
                // If the mime type is application/sparql-results+xml, just try to
                // read it as if it were an RDF/XML MIME type.
                if (mimetype != null && mimetype == "application/sparql-results+xml")
                {
                    mimetype = "text/xml";
                }
                using (RdfReader reader = RdfReader.Create(mimetype, stream))
                    reader.Select((StatementSink)outputObj);
                if (Debug)
                {
                    Console.Error.WriteLine(">> (read as statements)");
                }
                return;
            }

            // If the user wants query result bindings, read the response XML.
            if (outputObj is QueryResultSink)
            {
                QueryResultSink sink = (QueryResultSink)outputObj;

                if (mimetype != null && mimetype != "application/sparql-results+xml" && mimetype != "text/xml")
                {
                    throw new ApplicationException("The result of the query was not a SPARQL Results document.");
                }

                ArrayList  variableNames  = new ArrayList();
                ArrayList  variables      = new ArrayList();
                Variable[] variablesArray = null;
                Hashtable  bnodes         = new Hashtable();

                XmlReader xmldoc = new XmlTextReader(stream);
                {
                    // Move to the document element
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element)
                        {
                            break;
                        }
                    }

                    // Just check that it has the right local name.
                    if (xmldoc.LocalName != "sparql" || xmldoc.IsEmptyElement)
                    {
                        throw new ApplicationException("Invalid server response: Not a SPARQL results document.");
                    }

                    // Move to the 'head' node, it better be the first element
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element)
                        {
                            break;
                        }
                    }

                    if (xmldoc.LocalName != "head" || xmldoc.IsEmptyElement)
                    {
                        throw new ApplicationException("Invalid server response: Missing head full element.");
                    }

                    // Read the head element
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "variable")
                        {
                            if (xmldoc.GetAttribute("name") == null)
                            {
                                throw new ApplicationException("Invalid server response: Head/variable node missing name attribute.");
                            }
                            variableNames.Add(xmldoc.GetAttribute("name"));
                            variables.Add(new Variable(xmldoc.GetAttribute("name")));
                            if (!xmldoc.IsEmptyElement)
                            {
                                xmldoc.Skip();
                            }
                        }
                        else if (xmldoc.NodeType == XmlNodeType.EndElement)
                        {
                            break;
                        }
                    }

                    // Move to the 'results' element, it better be next
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element)
                        {
                            break;
                        }
                    }

                    if (xmldoc.LocalName != "results")
                    {
                        throw new ApplicationException("Invalid server response: Missing results element.");
                    }

                    variablesArray = (Variable[])variables.ToArray(typeof(Variable));
                    sink.Init(variablesArray);

                    // Read the results

                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "result")
                        {
                            // Read the bindings in this result
                            Resource[] valuesArray = new Resource[variablesArray.Length];
                            while (xmldoc.Read())
                            {
                                if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "binding")
                                {
                                    if (xmldoc.IsEmptyElement)
                                    {
                                        throw new ApplicationException("Invalid server response: Binding element empty.");
                                    }
                                    if (xmldoc.GetAttribute("name") == null)
                                    {
                                        throw new ApplicationException("Invalid server response: Result binding node missing name attribute.");
                                    }
                                    int vIndex = variableNames.IndexOf(xmldoc.GetAttribute("name"));
                                    if (vIndex == -1)
                                    {
                                        throw new ApplicationException("Invalid server response: Result binding name does not match a variable in the head.");
                                    }

                                    Resource value = null;

                                    while (xmldoc.Read())
                                    {
                                        if (xmldoc.NodeType == XmlNodeType.Whitespace || xmldoc.NodeType == XmlNodeType.SignificantWhitespace)
                                        {
                                            continue;
                                        }
                                        if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "uri")
                                        {
                                            value = new Entity(xmldoc.ReadElementString());
                                            if (!xmldoc.IsEmptyElement)
                                            {
                                                xmldoc.Skip();
                                            }
                                        }
                                        else if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "literal")
                                        {
                                            string lang = xmldoc.XmlLang;
                                            if (lang == "")
                                            {
                                                lang = null;
                                            }
                                            string dt = xmldoc.GetAttribute("datatype");
                                            value = new Literal(xmldoc.ReadElementString(), lang, dt);
                                            if (!xmldoc.IsEmptyElement)
                                            {
                                                xmldoc.Skip();
                                            }
                                        }
                                        else if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "bnode")
                                        {
                                            string id = xmldoc.ReadElementString();
                                            if (bnodes.ContainsKey(id))
                                            {
                                                value = (BNode)bnodes[id];
                                            }
                                            else
                                            {
                                                value      = new BNode(id);
                                                bnodes[id] = value;
                                            }
                                            if (!xmldoc.IsEmptyElement)
                                            {
                                                xmldoc.Skip();
                                            }
                                        }
                                        else
                                        {
                                            throw new ApplicationException("Invalid server response: Invalid content in binding node.");
                                        }
                                        break;
                                    }
                                    if (value == null)
                                    {
                                        throw new ApplicationException("Invalid server response: Result binding value is invalid.");
                                    }

                                    valuesArray[vIndex] = value;
                                }
                                else if (xmldoc.NodeType == XmlNodeType.EndElement)
                                {
                                    break;
                                }
                            }

                            sink.Add(new VariableBindings(variablesArray, valuesArray));
                            if (Debug)
                            {
                                Console.Error.WriteLine(">> " + new VariableBindings(variablesArray, valuesArray));
                            }
                        }
                        else if (xmldoc.NodeType == XmlNodeType.EndElement)
                        {
                            break;
                        }
                    }

                    sink.Finished();
                }
            }
        }
Exemple #27
0
        /// <summary>
        /// Difference boolean operation using a tracing strategy.
        /// </summary>
        /// <param name="islA">A node, on an island, to be differenced (as the left side).</param>
        /// <param name="islB">A node, on another island, that is to be intersectioned.</param>
        /// <param name="loopInto">The destination loop, where newly traced contents
        /// will be parented to.</param>
        /// <param name="onIsle">Output parameter. If the return value is true, it returns a node on
        /// the newly created traced island.</param>
        /// <param name="removeInputs">If true, the contents in the islands of islA and islB will be
        /// removed from their parents if a traced path is created.</param>
        /// <returns>True if the parameter islands touch and a traced result was created. Else, false.</returns>
        public static bool TraceDifference(
            BNode islA,
            BNode islB,
            BLoop loopInto,
            List <BNode> generated,
            bool removeInputs = true)
        {
            List <BNode> allNodes = new List <BNode>();
            List <Utils.BezierSubdivSample> outList = new List <Utils.BezierSubdivSample>();
            Dictionary <BNode, List <Utils.BezierSubdivSample> > dictCol = new Dictionary <BNode, List <Utils.BezierSubdivSample> >();

            HashSet <BNode> islANodes = new HashSet <BNode>(islA.Travel());

            GatherTraceData(islA, islB, allNodes, outList, dictCol);

            if (outList.Count == 0)
            {
                return(false);
            }

            while (outList.Count > 0)
            {
                BNode   startnode = null;
                Vector2 rt        = Vector2.zero; // Point of rightmost
                float   lam       = 0.0f;         // Lambda of rightmost

                BNode.SubdivideInfo sdiStartA = outList[0].a.node.GetSubdivideInfo(outList[0].a.lEst);
                BNode.SubdivideInfo sdiStartB = outList[0].b.node.GetSubdivideInfo(outList[0].b.lEst);
                float wind;
                if (islANodes.Contains(outList[0].a.node) == true)
                {
                    wind = Utils.Vector2Cross(sdiStartA.windTangent, sdiStartB.windTangent);
                }
                else
                {
                    wind = Utils.Vector2Cross(sdiStartB.windTangent, sdiStartA.windTangent);
                }

                List <BNode> newPath  = new List <BNode>();
                BNode        firstNew = null;

                if (wind > 0.0f)
                {
                    startnode = outList[0].a.node;
                    lam       = outList[0].a.lEst;

                    firstNew           = new BNode(null, sdiStartA.subPos);
                    firstNew.TanIn     = sdiStartA.subIn;
                    firstNew.UseTanIn  = sdiStartA.subIn != Vector2.zero;
                    firstNew.TanOut    = sdiStartA.subOut;
                    firstNew.UseTanOut = sdiStartA.subOut != Vector2.zero;
                }
                else
                {
                    startnode = outList[0].b.node;
                    lam       = outList[0].b.lEst;

                    firstNew           = new BNode(null, sdiStartB.subPos);
                    firstNew.TanIn     = sdiStartB.subIn;
                    firstNew.UseTanIn  = sdiStartB.subIn != Vector2.zero;
                    firstNew.TanOut    = sdiStartB.subOut;
                    firstNew.UseTanOut = sdiStartB.subOut != Vector2.zero;
                }
                outList.RemoveAt(0);
                newPath.Add(firstNew);


                BNode bnIt  = startnode;
                float itLam = lam;

                BNode.SubdivideInfo sdiL;
                BNode.SubdivideInfo sdiR;

                while (true)
                {
                    BNode bnPrev = bnIt;
                    List <Utils.BezierSubdivSample> lstBss;
                    if (dictCol.TryGetValue(bnIt, out lstBss) == false)
                    {
                        // If there are no collisions in the segment, just
                        // add the whole segment
                        itLam = 0.0f;
                        bnIt  = bnIt.next;

                        if (bnIt == startnode && itLam == lam) // Are we back where we started?
                        {
                            // close the shape and we're done
                            firstNew.TanIn    = bnIt.TanIn;
                            firstNew.UseTanIn = true;

                            BNode prevToFirst = newPath[newPath.Count - 1];
                            prevToFirst.TanOut    = bnPrev.TanOut;
                            prevToFirst.UseTanOut = true;
                            break;
                        }
                        else
                        {
                            // Full copy. TanOut can be modified later.
                            BNode bnDirAdd = new BNode(null, bnIt.Pos);
                            bnDirAdd.TanOut    = bnIt.TanOut;
                            bnDirAdd.TanIn     = bnIt.TanIn;
                            bnDirAdd.UseTanIn  = bnIt.UseTanIn;
                            bnDirAdd.UseTanOut = bnIt.UseTanOut;
                            newPath.Add(bnDirAdd);

                            BNode prevToFirst = newPath[newPath.Count - 2];
                            prevToFirst.TanOut    = bnPrev.TanOut;
                            prevToFirst.UseTanOut = true;
                        }
                        continue;
                    }

                    // If there are collision points, trace only the segment
                    // and swap the segment chain we're tracing with the one
                    // we collided with.
                    //
                    // Where we've moved, in relationship to bnPrev.
                    float itStart = itLam;
                    float itEnd   = 1.0f;

                    bool nextProc = false;
                    for (int i = 0; i < lstBss.Count - 1; ++i)
                    {
                        if (lstBss[i].a.lEst == itLam && i != lstBss.Count - 1)
                        {
                            itEnd = lstBss[i + 1].a.lEst;

                            // Figure out where we continue after jumping to the next item
                            bnIt     = lstBss[i + 1].b.node;
                            itLam    = lstBss[i + 1].b.lEst;
                            nextProc = true;

                            if (outList.Remove(lstBss[i]) == false)
                            {
                                outList.Remove(lstBss[i].Reciprocal());
                            }

                            break;
                        }
                    }

                    if (nextProc == false)
                    {
                        if (itLam == 0.0f)
                        {
                            // The first collision in the segment
                            itStart = 0.0f;
                            itEnd   = lstBss[0].a.lEst;

                            // Swap as we were in the loop directly above
                            bnIt  = lstBss[0].b.node;
                            itLam = lstBss[0].b.lEst;
                        }
                        else
                        {
                            // The last collision to the end
                            itStart = lstBss[lstBss.Count - 1].a.lEst;
                            itEnd   = 1.0f;

                            if (outList.Remove(lstBss[lstBss.Count - 1]) == false)
                            {
                                outList.Remove(lstBss[lstBss.Count - 1].Reciprocal());
                            }

                            // Move on to the next node in the chain.
                            bnIt  = bnIt.next;
                            itLam = 0.0f;
                        }
                    }

                    bnPrev.GetSubdivideInfo(itStart, out sdiL, itEnd, out sdiR);

                    if (bnIt == startnode && itLam == lam) // Are we back where we started?
                    {
                        // close the shape and we're done
                        firstNew.TanIn    = sdiR.subIn;
                        firstNew.UseTanIn = true;

                        newPath[newPath.Count - 1].TanOut    = sdiL.subOut;
                        newPath[newPath.Count - 1].UseTanOut = true;
                        break;
                    }
                    else
                    {
                        // Add additional traced point.
                        BNode bnNew = new BNode(null, sdiR.subPos);
                        bnNew.TanIn    = sdiR.subIn;
                        bnNew.UseTanIn = true;

                        newPath[newPath.Count - 1].TanOut    = sdiL.subOut;
                        newPath[newPath.Count - 1].UseTanOut = true;

                        newPath.Add(bnNew);
                    }
                }

                for (int i = 0; i < newPath.Count; ++i)
                {
                    newPath[i].parent = loopInto;

                    if (loopInto != null)
                    {
                        loopInto.nodes.Add(newPath[i]);
                    }

                    newPath[i].next = newPath[(i + 1) % newPath.Count];
                    newPath[i].prev = newPath[((i - 1) + newPath.Count) % newPath.Count];
                }

                if (generated != null && newPath.Count > 0)
                {
                    generated.Add(newPath[0]);
                }
            }

            if (removeInputs == true)
            {
                foreach (BNode bn in allNodes)
                {
                    if (bn.parent != null)
                    {
                        bn.parent.RemoveNode(bn);
                    }
                }
            }

            return(true);
        }
Exemple #28
0
        /// <summary>
        /// Add data to cache.
        /// </summary>
        private List <Report106Entity> AddDataToCache()
        {
            var userData = UserData;
            var cacheKey = WebUtility.GetCacheKeyName(userData, "kpi-report-106");

            HttpRuntime.Cache.Remove(cacheKey);

            var lscs = new List <LscUserInfo>();

            if (LscsComboBox.SelectedIndex > 0)
            {
                var ids = WebUtility.ItemSplit(LscsComboBox.SelectedItem.Value);
                if (ids.Length != 2)
                {
                    return(null);
                }
                var lscId   = Int32.Parse(ids[0]);
                var groupId = Int32.Parse(ids[1]);
                var lscUser = userData.LscUsers.Find(lu => { return(lu.LscID == lscId); });
                if (lscUser == null)
                {
                    return(null);
                }
                lscs.Add(lscUser);
            }
            else
            {
                lscs.AddRange(userData.LscUsers);
            }

            var fromTime = DateTime.Parse(BeginFromDate.Text);
            var toTime   = DateTime.Parse(BeginToDate.Text);

            var texts      = new List <String>();
            var auxSets    = new List <String>();
            var filterText = WebUtility.StringSplit(NodeText.Text.Trim());

            foreach (var ft in filterText)
            {
                if (String.IsNullOrEmpty(ft.Trim()))
                {
                    continue;
                }
                if (FilterTypeList.SelectedItem.Value.Equals("1"))
                {
                    auxSets.Add(ft.Trim());
                }
                else
                {
                    texts.Add(ft.Trim());
                }
            }

            var devTypes = new Dictionary <Int32, String>();

            foreach (var dt in DevTypeMultiCombo.SelectedItems)
            {
                devTypes[Int32.Parse(dt.Value)] = dt.Text;
            }
            if (devTypes.Count == 0)
            {
                return(null);
            }

            var almNames = new List <String>();
            var almIds   = new Dictionary <String, String>();
            var almText  = WebUtility.StringSplit(AlarmNameText.Text.Trim());

            foreach (var at in almText)
            {
                if (String.IsNullOrEmpty(at.Trim()))
                {
                    continue;
                }
                if (AlmNameList.SelectedItem.Value.Equals("1"))
                {
                    almIds[at.Trim()] = null;
                }
                else
                {
                    almNames.Add(at.Trim());
                }
            }

            var otherEntity = new BOther();
            var nodeEntity  = new BNode();
            var stations    = new List <StationInfo>();
            var nodes       = new List <NodeInfo>();

            foreach (var lsc in lscs)
            {
                stations.AddRange(otherEntity.GetStations(lsc.LscID, lsc.Group.GroupID).FindAll(s => s.BuildingID != WebUtility.DefaultInt32));
                nodes.AddRange(nodeEntity.GetNodes(lsc.LscID, EnmNodeType.Aic, texts.ToArray(), auxSets.ToArray(), devTypes.Keys.ToArray()));
            }

            if (Area2ComboBox.SelectedIndex > 0)
            {
                var area2Id = Int32.Parse(Area2ComboBox.SelectedItem.Value);
                stations = stations.FindAll(s => s.Area2ID == area2Id);
            }
            if (Area3ComboBox.SelectedIndex > 0)
            {
                var area3Id = Int32.Parse(Area3ComboBox.SelectedItem.Value);
                stations = stations.FindAll(s => s.Area3ID == area3Id);
            }
            if (stations.Count == 0)
            {
                return(null);
            }

            var ndGroup = from node in nodes
                          group node by new { node.LscID, node.StaID } into g
                select new {
                LscID = g.Key.LscID,
                StaID = g.Key.StaID,
                Nodes = g.ToList()
            };

            var staWnd = from sta in stations
                         join ng in ndGroup on new { sta.LscID, sta.StaID } equals new { ng.LscID, ng.StaID } into lt
            from ns in lt.DefaultIfEmpty()
            select new {
                Station = sta,
                Nodes   = ns == null ? new List <NodeInfo>() : ns.Nodes
            };

            var alarmEntity = new BAlarm();
            var alarms      = WebUtility.GetUserAlarms(userData).FindAll(alarm => lscs.Any(l => l.LscID == alarm.LscID) && alarm.StartTime >= fromTime && alarm.StartTime <= toTime);

            foreach (var lsc in lscs)
            {
                alarms.AddRange(alarmEntity.GetHisAlarms(lsc.LscID, lsc.LscName, userData.StandardProtocol, lsc.Group.GroupNodes, fromTime, toTime));
            }

            var ndWam = from alarm in alarms
                        join node in nodes on new { alarm.LscID, alarm.NodeID, alarm.NodeType } equals new { node.LscID, node.NodeID, node.NodeType }
            where (almNames.Count == 0 || almNames.Any(name => alarm.AlarmName.Contains(name))) && (almIds.Count == 0 || almIds.ContainsKey(alarm.AlarmID.ToString()))
            select new {
                Node  = node,
                Alarm = alarm
            };

            var almGroup = from alarm in ndWam
                           group alarm by new { alarm.Node.LscID, alarm.Node.StaID } into g
                select new {
                LscID  = g.Key.LscID,
                StaID  = g.Key.StaID,
                Alarms = g.Select(a => a.Alarm)
            };

            var staWam = from sn in staWnd
                         join ga in almGroup on new { sn.Station.LscID, sn.Station.StaID } equals new { ga.LscID, ga.StaID } into lt
            from gs in lt.DefaultIfEmpty()
            select new {
                Station = sn.Station,
                Nodes   = sn.Nodes,
                Alarms  = gs == null ? new List <AlarmInfo>() : gs.Alarms
            };

            var result = (from sa in staWam
                          group sa by new { sa.Station.LscID, sa.Station.Area3ID, sa.Station.BuildingID } into g
                          orderby g.Key.LscID, g.Key.Area3ID, g.Key.BuildingID
                          select new Report106Entity {
                Station = g.First().Station,
                BeginTime = fromTime,
                EndTime = toTime,
                Nodes = g.SelectMany(s => s.Nodes).ToList(),
                Alarms = g.SelectMany(a => a.Alarms).ToList(),
            }).ToList();

            int cacheDuration = Int32.Parse(WebConfigurationManager.AppSettings["DefaultCacheDuration"]);

            HttpRuntime.Cache.Insert(cacheKey, result, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(cacheDuration), CacheItemPriority.Default, null);
            return(result);
        }
Exemple #29
0
        public static void TraceDifference(
            List <BNode> islsA,
            List <BNode> islsB,
            BLoop loopInto,
            bool removeInputs = true)
        {
            // If there's nothing we're subtracting, just abort.
            if (islsB.Count == 0)
            {
                return;
            }

            // If we're not subtracing away from anything but still go through
            // with the subtraction, the end result would be that the right
            // side goes away.
            if (islsA.Count == 0)
            {
                if (removeInputs == true)
                {
                    foreach (BNode bn in islsB)
                    {
                        bn.RemoveIsland(false);
                    }
                }
                return;
            }

            // Make sure the islands are the appropriate winding order. We're
            // assuming the positive shape is counter-clockwise, and the
            // negative shape is counter clockwise.

            foreach (BNode bnislA in islsA)
            {
                if (BNode.CalculateWinding(bnislA.Travel()) > 0)
                {
                    bnislA.ReverseChainOrder();
                }
            }

            foreach (BNode bnislB in islsB)
            {
                if (BNode.CalculateWinding(bnislB.Travel()) < 0)
                {
                    bnislB.ReverseChainOrder();
                }
            }

            // Were any paths created from intersections?
            bool anyClipped = false;

            // Negative islands (from islsB) that should be kept
            // because they create hollow holes that are surrounded
            // by positive regions.
            HashSet <BNode> negativeHoles = new HashSet <BNode>();

            // Compare each element of islaA with islsB. If there's a collision,
            // islaA is replaced with the created geometry. Note that the number of
            // generated islands is variable.
            for (int i = 0; i < islsA.Count;)
            {
                bool incr = true;
                for (int j = 0; j < islsB.Count; ++j)
                {
                    List <BNode> newTracedIslands = new List <BNode>();

                    // Note how the removeInputs parameter for TraceDifference is false.
                    // That's something we're managing at this current level when operating
                    // in batch.
                    if (TraceDifference(islsA[i], islsB[j], loopInto, newTracedIslands, false) == true)
                    {
                        if (removeInputs == true)
                        {
                            islsA[i].RemoveIsland(false);
                        }

                        // Replace
                        islsA.RemoveAt(i);
                        islsA.InsertRange(i, newTracedIslands);

                        anyClipped = true;
                    }
                    else
                    {
                        BoundingMode bm = GetLoopBoundingMode(islsA[i], islsB[j], false);
                        if (bm == BoundingMode.LeftSurroundsRight)
                        {
                            // Do nothing, leave the inside with a reverse hole in it.
                            negativeHoles.Add(islsB[j]);
                        }
                        else if (bm == Boolean.BoundingMode.RightSurroundsLeft)
                        {
                            if (removeInputs == true)
                            {
                                islsA[i].RemoveIsland(false);
                            }

                            islsA.RemoveAt(i);
                            incr = false;
                        }
                    }
                }

                if (incr == true)
                {
                    ++i;
                }
            }

            if (removeInputs == true)
            {
                foreach (BNode bn in islsB)
                {
                    if (negativeHoles.Contains(bn) == false)
                    {
                        bn.RemoveIsland(false);
                    }
                }
            }

            if (anyClipped == true && negativeHoles.Count > 0)
            {
                // If we have any negative holes and clipping happened, combine the
                // negative regions and see if that punches a hole past the positive
                // region through recurion.
                //
                // In theory, this should only happen at most once.

                List <BNode> negs = new List <BNode>(negativeHoles);
                TraceUnion(negs, loopInto, true);

                TraceDifference(islsA, negs, loopInto, removeInputs);
            }
        }
        public static void Print(this BNode root, string textFormat = "0", int spacing = 1, int topMargin = 2, int leftMargin = 2)
        {
            if (root == null)
            {
                return;
            }
            int rootTop = Console.CursorTop + topMargin;
            var last    = new List <NodeInfo>();
            var next    = root;

            for (int level = 0; next != null; level++)
            {
                var item = new NodeInfo {
                    Node = next, Text = next.item.ToString(textFormat)
                };
                if (level < last.Count)
                {
                    item.StartPos = last[level].EndPos + spacing;
                    last[level]   = item;
                }
                else
                {
                    item.StartPos = leftMargin;
                    last.Add(item);
                }
                if (level > 0)
                {
                    item.Parent = last[level - 1];
                    if (next == item.Parent.Node.left)
                    {
                        item.Parent.Left = item;
                        item.EndPos      = Math.Max(item.EndPos, item.Parent.StartPos - 1);
                    }
                    else
                    {
                        item.Parent.Right = item;
                        item.StartPos     = Math.Max(item.StartPos, item.Parent.EndPos + 1);
                    }
                }
                next = next.left ?? next.right;
                for (; next == null; item = item.Parent)
                {
                    int top = rootTop + 2 * level;
                    Print(item.Text, top, item.StartPos);
                    if (item.Left != null)
                    {
                        Print("/", top + 1, item.Left.EndPos);
                        Print("_", top, item.Left.EndPos + 1, item.StartPos);
                    }
                    if (item.Right != null)
                    {
                        Print("_", top, item.EndPos, item.Right.StartPos - 1);
                        Print("\\", top + 1, item.Right.StartPos - 1);
                    }
                    if (--level < 0)
                    {
                        break;
                    }
                    if (item == item.Parent.Left)
                    {
                        item.Parent.StartPos = item.EndPos + 1;
                        next = item.Parent.Node.right;
                    }
                    else
                    {
                        if (item.Parent.Left == null)
                        {
                            item.Parent.EndPos = item.StartPos - 1;
                        }
                        else
                        {
                            item.Parent.StartPos += (item.StartPos - 1 - item.Parent.EndPos) / 2;
                        }
                    }
                }
            }
            Console.SetCursorPosition(0, rootTop + 2 * last.Count - 1);
        }
Exemple #31
0
        private static void MakeLeanMSG2(Store msg, ResSet predicates, StatementSink removed,
                                         ResSet nodesremoved, BNode startingnode)
        {
            // Find every pair of two distinct outgoing edges from startingnode
            // with the same predicate, targeting entities only.

            MultiMap edges = new MultiMap();

            foreach (Statement s in msg.Select(new Statement(startingnode, null, null)))
            {
                if (s.Object is Entity)
                {
                    edges.Put(new Edge(true, startingnode, s.Predicate, null), s.Object);
                }
            }
            foreach (Statement s in msg.Select(new Statement(null, null, startingnode)))
            {
                edges.Put(new Edge(false, startingnode, s.Predicate, null), s.Subject);
            }

            foreach (Edge e in edges.Keys)
            {
                // Make sure we have a distinct set of targets.
                ResSet targets_set = new ResSet();
                foreach (Entity r in edges.Get(e))
                {
                    targets_set.Add(r);
                }
                if (targets_set.Count == 1)
                {
                    continue;
                }

                IList targets = targets_set.ToEntityArray();

                // Take every pair of targets, provided
                // one is a bnode that can be a variable.
                for (int i = 0; i < targets.Count; i++)
                {
                    if (!(targets[i] is BNode) || predicates.Contains((BNode)targets[i]))
                    {
                        continue;
                    }
                    if (nodesremoved.Contains((BNode)targets[i]))
                    {
                        continue;
                    }
                    for (int j = 0; j < targets.Count; j++)
                    {
                        if (i == j)
                        {
                            continue;
                        }
                        // Create a new synchronous-path object.
                        SyncPath p = new SyncPath();
                        p.FixedNodes.Add((Resource)targets[j]);
                        p.FrontierVariables.Add((Resource)targets[i]);
                        p.Mapping[targets[i]] = targets[j];
                        p.Path[new Edge(e.Direction, e.Start, e.Predicate, (BNode)targets[i])] = p.Path;
                        if (MakeLeanMSG3(msg, predicates, removed, nodesremoved, p))
                        {
                            break;                             // the target was removed
                        }
                    }
                }
            }
        }
 public BTree()
 {
     _root  = null;
     _count = 0;
 }
Exemple #33
0
        Resource GetRes(uint key, Hashtable createdResources)
        {
            if (key == 1) return Statement.DefaultMeta;
            if (createdResources.ContainsKey(key)) return (Resource)createdResources[key];

            Resource ret;

            string stringval = (string)db_id_to_value.Get(key);
            if (stringval == null) // must be a bnode
                ret = new BNode();
            else if (stringval[0] == 'L')
                ret = Literal.Parse(stringval.Substring(1), null);
            else if (stringval[0] == 'U')
                ret = new Entity(stringval.Substring(1));
            else
                throw new InvalidOperationException();

            SetResourceKey(ret, key);
            createdResources[key] = ret;

            return ret;
        }
Exemple #34
0
		public void Query(Statement[] graph, SemWeb.Query.QueryOptions options, SemWeb.Query.QueryResultSink sink) {
			if (graph.Length == 0) throw new ArgumentException("graph array must have at least one element");
			
			// This method translates the graph pattern into a single SQL statement. Each graph statement
			// corresponds to a new use of the _statements table in the FROM clause. For instance:
			//     ?a foaf:knows ?b . ?b foaf:name ?c .
			// translates to
			//     SELECT
			//       g0.subject, v0.value,
			//       g0.object, v1.value,
			//       g1.object, v2.value, v2lit.value, v2lit.language, v2lit.datatype
			//     FROM
			//       db_tables as g0 LEFT JOIN db_entities AS v0 ON g0.subject=v0.id LEFT JOIN db_entities AS v1 ON g0.object=v1.id,
			//       db_tables as g1 LEFT JOIN db_entities AS v2 ON g1.object=v2.id LEFT JOIN db_literals AS v2lit ON g1.object=v2lit.id
			//     WHERE
			//       g0.predicate = <the id of the foaf:knows entity> AND
			//       g1.predicate = <the id of the foaf:name entity> AND
			//       g0.object = g1.subject
			//
			// If any variable column is an *undistinguished* variable --- which is to say that the caller
			// says it is a variable, but is not concerned with its values --- then we want to apply
			// DISTINCT to the SELECT statement. This is because while in the normal case we may get
			// duplicates, we expect that to not occur more than the caller expects, but in the latter
			// case there will often be many duplicates. Consider the SPARQL query:
			//      SELECT DISTINCT ?p WHERE { ?s ?p ?o }
			// to get a list of predicates in the dataset, which corresponds to the graph query
			//      ?s ?p ?o
			// where only ?p is distinguished.
			// This normally translates to:
			//     SELECT
			//       g0.predicate, v0.value,
			//     FROM
			//       db_tables as g0 LEFT JOIN db_entities AS v0 ON g0.predicate=v0.id
			// which of course is going to return a result for every triple in the database.
			// So we add DISTINCT to beginning ("SELECT DISTINCT").
			// Unfortunately, MySQL performs the DISTINCT bit only after the LEFT JOINs (which makes sense normally).
			// That means that MySQL is repeatedly fetching the URI values of the predicates and checking
			// if a new unique row has been created, and this is very slow. What we want is to get the distinct
			// IDs of the predicates first, and then get their URIs.
			// I first tried implementing this with VIEWs, but it didn't always speed things up, and it was
			// difficult to manage the creation and deletion of VIEWs.
			// So instead, in this case, we do the query in two parts. First we get the IDs of the variables,
			// and then we get their URIs.
			
			options = options.Clone(); // because we modify the knownvalues array
			
			// Order the variables mentioned in the graph.
			Variable[] varOrder;
			ResSet distinguishedVars = null;
			bool useDistinct = false;
			{
				if (options.DistinguishedVariables != null)
					distinguishedVars = new ResSet(options.DistinguishedVariables);
				else
					distinguishedVars = new ResSet();
			
				Hashtable seenvars = new Hashtable();
				foreach (Statement filter in graph) {
					for (int i = 0; i < 4; i++) {
						Resource r = filter.GetComponent(i);
						if (r == null)
							throw new ArgumentException("The graph may not have any null components.  Use Variables instead.");

						if (r is Variable) {
							if (options.DistinguishedVariables != null) {
								if (!distinguishedVars.Contains(r)) {
									// If we are omitting a column from the results because it is
									// not distinguished, and it's not a meta column, then we'll
									// use DISTINCT.
									if (i != 3)
										useDistinct = true;
										
									// Don't put this into seenvars.
									continue;
								}
							} else {
								distinguishedVars.Add(r); // all variables are distinguished
							}
							
							seenvars[r] = r;
						}
					}
				}
				
				varOrder = new Variable[seenvars.Count];
				int ctr = 0;
				foreach (Variable v in seenvars.Keys)
					varOrder[ctr++] = v;
			}
			
			// Set the initial bindings to the result sink

			sink.Init(varOrder);
			
			Hashtable varLitFilters = new Hashtable();
			
			// Prefetch the IDs of all resources mentioned in the graph and in variable known values.
			// For Resources in the graph that are not in the store, the query immediately fails.
			{
				ArrayList graphResources = new ArrayList();
				foreach (Statement s in graph) {
					for (int i = 0; i < 4; i++) {
						Resource r = s.GetComponent(i);
						if (!(r is BNode)) // definitely exclude variables, but bnodes are useless too
							graphResources.Add(r);
					}
				}
				if (options.VariableKnownValues != null)
					foreach (ICollection values in options.VariableKnownValues.Values)
						graphResources.AddRange(values);

				PrefetchResourceIds(graphResources);
				
				// Check resources in graph and fail fast if any is not in the store.
				foreach (Statement s in graph) {
					for (int i = 0; i < 4; i++) {
						Resource r = s.GetComponent(i);
						if (r is Variable) continue;
						if ((object)r != (object)Statement.DefaultMeta && GetResourceKey(r) == null) {
							sink.AddComments("Resource " + r + " is not contained in the data model.");
							sink.Finished();
							return;
						}
					}
				}
				
				// Check variable known values and remove any values not in the store.
				// Don't do any fail-fasting here because there might be entries in this
				// dictionary that aren't even used in this query (yes, poor design).
				// We check later anyway.
				if (options.VariableKnownValues != null) {
					#if !DOTNET2
					foreach (Variable v in new ArrayList(options.VariableKnownValues.Keys)) {
					#else
					foreach (Variable v in new System.Collections.Generic.List<Variable>(options.VariableKnownValues.Keys)) {
					#endif
						#if !DOTNET2
						ArrayList newvalues = new ArrayList();
						#else
						System.Collections.Generic.List<Resource> newvalues = new System.Collections.Generic.List<Resource>();
						#endif
						
						foreach (Resource r in (ICollection)options.VariableKnownValues[v]) {
							if ((object)r == (object)Statement.DefaultMeta || GetResourceKey(r) != null)
								newvalues.Add(r);
						}

						options.VariableKnownValues[v] = newvalues;
					}
				}
			}
			
			// Helpers
			
			string[] colnames = { "subject", "predicate", "object", "meta" };
			
			// we initialize these things while locked, but use them after we release the lock
			ArrayList results = new ArrayList();
			Hashtable resourceCache = new Hashtable(); // map resource ID to Resource instances

			// We can either include JOINs to the entities and literals table for every variable
			// in the query, or we can delay fetching that information to separate SELECTs
			// after the main part of the query is done. If we are including DISTINCT, then we
			// don't want to do the JOINs because the JOINs happen before the DISTINCT and will
			// be unnecessarily repeated. Also if the query has many variables, say more than 6,
			// then it may slow down query planning (the MySQL optimizer) to include them all in
			// one query.
			bool joinEntitiesAndLiterals = true;
			if (useDistinct) joinEntitiesAndLiterals = false;
			if (varOrder.Length > 6) joinEntitiesAndLiterals = false;
						
			// Lock the store and make sure we are initialized and any pending add's have been committed.
			
			lock (syncroot) {
			
			Init();
			RunAddBuffer();
			
			// Compile the SQL statement.

			Hashtable varRef = new Hashtable(); // the column name representing the variable, as in "g0.subject"
			Hashtable varRef2 = new Hashtable(); // the index of the variable, for accessing the entities and literals joined tables
			Hashtable varSelectedLiteral = new Hashtable(); // whether the variable is in a literal column and a LEFT JOIN for the literals table was used for it
			Hashtable varCouldBeLiteral = new Hashtable(); // whether the variable is only in literal columns
			Hashtable varSelectedEntity = new Hashtable(); // whether a LEFT JOIN for the entities table was used for a variable
			
			StringBuilder fromClause = new StringBuilder();
			StringBuilder whereClause = new StringBuilder();
			
			for (int f = 0; f < graph.Length; f++) {
				// For each filter, we select FROM the statements table with an
				// alias: q#, where # is the filter's index.
				
				if (f > 0) fromClause.Append(',');
				fromClause.Append(table);
				fromClause.Append("_statements AS g");
				fromClause.Append(f);
				
				// For each component of the filter...
				
				for (int i = 0; i < 4; i++) {
					// This has the name of the column corresponding to this variable (i.e. "g1.predicate").
					string myRef = "g" + f + "." + colnames[i];
					
					Variable v = graph[f].GetComponent(i) as Variable;
					if (v != null) {
						// If the component is a variable, then if this is
						// the first time we're seeing the variable, we don't
						// add any restrictions to the WHERE clause, but we
						// note the variable's "name" in the world of SQL
						// so we can refer back to it later and we add the
						// necessary FROM tables so we can get its URI and
						// literal value if it is a reported variable.
						// If this isn't the first time, then we add a WHERE restriction so
						// that the proper columns here and in a previous
						// filter are forced to have the same value.
					
						if (!varRef.ContainsKey(v)) {
							// This is the first time we are seeing this variable.
									
							// Record the column name for the variable (i.e. g0.subject).
							varRef[v] = myRef;
							
							// Record an index for the variable (i.e. 0, 1, 2, ...)
							int vIndex = varRef.Count;
							varRef2[v] = vIndex;
							
							varCouldBeLiteral[v] = (i == 2);
							
							// LEFT JOIN the entities table for this variable to get its URI
							// only if it is a distinguished variable and we are not using DISTINCT.
							varSelectedEntity[v] = false;
							if (joinEntitiesAndLiterals && distinguishedVars.Contains(v)) {
								varSelectedEntity[v] = true; // Record that we are selecting the entities table for this variable.
								fromClause.Append(" LEFT JOIN ");
								fromClause.Append(table);
								fromClause.Append("_entities AS vent");
								fromClause.Append(vIndex);
								fromClause.Append(" ON ");
								fromClause.Append(myRef);
								fromClause.Append("=");
								fromClause.Append("vent" + vIndex + ".id ");
							}
									
							// LEFT JOIN the literals table for this variable:
							//    if it is in an object position
							//    to get its value, language, and datatype only if it is a distinguished variable and we are not using DISTINCT
							//    to apply a literal value filter (which will be done later)
							#if !DOTNET2
							bool hasLitFilter = (options.VariableLiteralFilters != null && options.VariableLiteralFilters[v] != null);
							#else
							bool hasLitFilter = (options.VariableLiteralFilters != null && options.VariableLiteralFilters.ContainsKey(v));
							#endif
							varSelectedLiteral[v] = false;
							if (i == 2 && ((joinEntitiesAndLiterals && distinguishedVars.Contains(v)) || hasLitFilter)) {
								varSelectedLiteral[v] = true; // Record that we are selecting the literals table for this variable.
								fromClause.Append(" LEFT JOIN ");
								fromClause.Append(table);
								fromClause.Append("_literals AS vlit");
								fromClause.Append(vIndex);
								fromClause.Append(" ON ");
								fromClause.Append(myRef);
								fromClause.Append("=");
								fromClause.Append("vlit" + vIndex + ".id ");
							}
							
							// If this variable has known values, then we must restrict what values can appear using a WHERE clause.
							if (options.VariableKnownValues != null) {
								ICollection values = null;
								#if DOTNET2
								if (options.VariableKnownValues.ContainsKey(v))
								#endif
									values = (ICollection)options.VariableKnownValues[v];
								if (values != null) {
									if (values.Count == 0) {
										sink.Finished();
										return;
									}
									Resource r = ToMultiRes((Resource[])new ArrayList(values).ToArray(typeof(Resource)));
									if (!WhereItem(myRef, r, whereClause, whereClause.Length != 0)) {
										// We know at this point that the query cannot return any results.
										sink.Finished();
										return;
									}
								}
							}
							
						} else {
							// We've seen this variable before, so link up the column in this
							// statement to the corresponding column in a previous (or this) statement.
							if (whereClause.Length != 0) whereClause.Append(" AND ");
							whereClause.Append('(');
							whereClause.Append((string)varRef[v]);
							whereClause.Append('=');
							whereClause.Append(myRef);
							whereClause.Append(')');
							if (i != 2)
								varCouldBeLiteral[v] = false;
						}
					
					} else {
						// If this is not a variable, then it is a resource.
					
						// Append something into the WHERE clause to make sure this component gets
						// the right fixed value. If we cannot add the component to the WHERE clause
						// because the fixed value isn't even known in the data source, we can stop early.
						if (!WhereItem(myRef, graph[f].GetComponent(i), whereClause, whereClause.Length != 0)) {
							// We know at this point that the query cannot return any results.
							sink.Finished();
							return;
						}

					}
				}
			
			} // graph filter 0...n
			
			// Add literal filters to the WHERE clause

			foreach (Variable v in varOrder) {
				// Is there a literal value filter?
				if (options.VariableLiteralFilters == null) continue;
				#if !DOTNET2
				if (options.VariableLiteralFilters[v] == null) continue;
				#else
				if (!options.VariableLiteralFilters.ContainsKey(v)) continue;
				#endif
				
				// If this variable was not used in a literal column, then
				// we cannot filter its value. Really, it will never be a literal.
				if (!(bool)varSelectedLiteral[v]) continue;

				foreach (LiteralFilter filter in (ICollection)options.VariableLiteralFilters[v]) {
					string s = FilterToSQL(filter, "vlit" + (int)varRef2[v] + ".value");
					if (s == null) continue;

					if (whereClause.Length != 0) whereClause.Append(" AND ");
					whereClause.Append(s);
				}
			}

			// Put the parts of the SQL statement together

			StringBuilder cmd = new StringBuilder();
			
			cmd.Append("SELECT ");

			if (useDistinct) cmd.Append("DISTINCT ");
			
			if (!SupportsLimitClause && options.Limit > 0) {
				cmd.Append("TOP ");
				cmd.Append(options.Limit);
				cmd.Append(' ');
			}
			
			// Add all of the distinguished variables to the SELECT clause.
			bool firstvar = true;
			foreach (Variable v in varOrder) {
				if (!firstvar) cmd.Append(','); firstvar = false;
				
				cmd.Append((string)varRef[v]);
				
				if ((bool)varSelectedEntity[v]) {
					cmd.Append(", vent" + (int)varRef2[v] + ".value");
				}
				if ((bool)varSelectedLiteral[v]) {
					cmd.Append(", vlit" + (int)varRef2[v] + ".value");
					cmd.Append(", vlit" + (int)varRef2[v] + ".language");
					cmd.Append(", vlit" + (int)varRef2[v] + ".datatype");
				}
			}
			
			cmd.Append(" FROM ");
			cmd.Append(fromClause.ToString());
			
			if (whereClause.Length > 0)
				cmd.Append(" WHERE ");
			cmd.Append(whereClause.ToString());
			
			if (SupportsLimitClause && options.Limit > 0) {
				cmd.Append(" LIMIT ");
				cmd.Append(options.Limit);
			}
			
			cmd.Append(';');

			if (Debug) {
				string cmd2 = cmd.ToString();
				//if (cmd2.Length > 80) cmd2 = cmd2.Substring(0, 80);
				Console.Error.WriteLine(cmd2);
			}
			
			// Execute the query.
					
			// When we use DISTINCT and don't select URI and literal values at first,
			// we have to select them after. And since we can't maintain two IDataReaders
			// simultaneously, that means we have to pull the first set of results into
			// memory. It would be nice to not have to do that when we don't use DISTINCT,
			// but in practice it doesn't really matter since in SPARQL it's all sucked
			// into memory anyway.
					
			using (IDataReader reader = RunReader(cmd.ToString())) {
				while (reader.Read()) {
					QueryResultRowVariable[] row = new QueryResultRowVariable[varOrder.Length];
					results.Add(row);
					
					int col = 0;
					for (int i = 0; i < varOrder.Length; i++) {
						Variable v = varOrder[i];
						
						row[i].id = reader.GetInt64(col++);
						if ((bool)varSelectedEntity[v]) {
							row[i].uri = AsString(reader[col++]);
						}
						if ((bool)varSelectedLiteral[v]) {
							row[i].litvalue = AsString(reader[col++]);
							row[i].litlanguage = AsString(reader[col++]);
							row[i].litdatatype = AsString(reader[col++]);
						}
					}
				}
			}
		
			// For any distinguished variable that we did not select URIs or literal values for,
			// select that information now.
			
			for (int i = 0; i < varOrder.Length; i++) {
				Variable v = varOrder[i];
			
				if ((bool)varSelectedEntity[v] && (!(bool)varCouldBeLiteral[v] || (bool)varSelectedLiteral[v])) continue;
				
				// Get the list of resource IDs found for this variable.
				ArrayList rids = new ArrayList();
				foreach (QueryResultRowVariable[] row in results) {
					if (row[i].id <= 1) continue; // can't fetch for Statement.DefaultMeta
					if (resourceCache.ContainsKey(row[i].id)) continue; // we've already fetched it
					rids.Add(row[i].id); // probably no need to remove duplicates
				}
				
				if (rids.Count > 0) {
					// Fetch what we can for entities.
					if (!(bool)varSelectedEntity[v]) {
						StringBuilder cmd2 = new StringBuilder();
						cmd2.Append("SELECT id, value FROM ");
						cmd2.Append(table);
						cmd2.Append("_entities WHERE id IN (");
						bool first = true;
						foreach (Int64 id in rids) {
							if (!first) cmd2.Append(','); first = false;
							cmd2.Append(id);
						}
						cmd2.Append(")");
						if (Debug) { Console.Error.WriteLine(cmd2.ToString()); }
						using (IDataReader reader = RunReader(cmd2.ToString())) {
							while (reader.Read()) {
                                Int64 id = reader.GetInt64(0);
								string uri = AsString(reader[1]);
								resourceCache[id] = MakeEntity(id, uri, null);
							}
						}
					}
					
					// Fetch what we can for literals.
					if ((bool)varCouldBeLiteral[v] && !(bool)varSelectedLiteral[v]) {
						StringBuilder cmd2 = new StringBuilder();
						cmd2.Append("SELECT id, value, language, datatype FROM ");
						cmd2.Append(table);
						cmd2.Append("_literals WHERE id IN (");
						bool first = true;
                        foreach (Int64 id in rids)
                        {
							if (!first) cmd2.Append(','); first = false;
							cmd2.Append(id);
						}
						cmd2.Append(")");
						if (Debug) { Console.Error.WriteLine(cmd2.ToString()); }
						using (IDataReader reader = RunReader(cmd2.ToString())) {
							while (reader.Read()) {
                                Int64 id = reader.GetInt64(0);
								string value = AsString(reader[1]);
								string language = AsString(reader[2]);
								string datatype = AsString(reader[3]);
								Literal lit = new Literal(value, language, datatype);
								SetResourceKey(lit, new ResourceKey(id));
								resourceCache[id] = lit;
							}
						}
					}
					
					// Any ids not found so far are bnodes.
                    foreach (Int64 id in rids)
                    {
						if (!resourceCache.ContainsKey(id)) {
							BNode b = new BNode();
							SetResourceKey(b, new ResourceKey(id));
							resourceCache[id] = b;
						}
					}
				}
			}
			
			} // lock
			
			// Now loop through the binding results.
			
			foreach (QueryResultRowVariable[] row in results) {
				bool match = true;
				Resource[] variableBindings = new Resource[varOrder.Length];
				
				for (int i = 0; i < varOrder.Length; i++) {
                    Int64 id = row[i].id;
					if (resourceCache.ContainsKey(id)) {
						variableBindings[i] = (Resource)resourceCache[id];
					} else {
						if (row[i].litvalue == null) {
							variableBindings[i] = MakeEntity(id, row[i].uri, null);
						} else {
							Literal lit = new Literal(row[i].litvalue, row[i].litlanguage, row[i].litdatatype);
							
							ArrayList litFilters = (ArrayList)varLitFilters[varOrder[i]];
							if (litFilters != null && !LiteralFilter.MatchesFilters(lit, (LiteralFilter[])litFilters.ToArray(typeof(LiteralFilter)), this)) {
								match = false;
								break;
							}
								
							SetResourceKey(lit, new ResourceKey(id));
							variableBindings[i] = lit;
						}
						
						// reuse this entity later
						resourceCache[id] = variableBindings[i];
					}
				}
				
				if (!match) continue;
				if (!sink.Add(new SemWeb.Query.VariableBindings(varOrder, variableBindings))) return;
			}
			
			sink.Finished();
		}
Exemple #35
0
        /// <summary>
        /// Add data to cache.
        /// </summary>
        private List <Report002Entity> AddDataToCache()
        {
            var userData = UserData;
            var cacheKey = WebUtility.GetCacheKeyName(userData, "kpi-report-002");

            HttpRuntime.Cache.Remove(cacheKey);

            var lscs = new List <LscUserInfo>();

            if (LscsComboBox.SelectedIndex > 0)
            {
                var ids = WebUtility.ItemSplit(LscsComboBox.SelectedItem.Value);
                if (ids.Length == 2)
                {
                    var lscId   = Int32.Parse(ids[0]);
                    var groupId = Int32.Parse(ids[1]);
                    var lscUser = userData.LscUsers.Find(lu => { return(lu.LscID == lscId); });
                    if (lscUser != null)
                    {
                        lscs.Add(lscUser);
                    }
                }
            }
            else
            {
                lscs.AddRange(userData.LscUsers);
            }
            if (lscs.Count == 0)
            {
                return(null);
            }

            var fromTime = DateTime.Parse(BeginFromDate.Text);
            var toTime   = DateTime.Parse(BeginToDate.Text);

            var auxSets    = new List <String>();
            var texts      = new List <String>();
            var filterText = WebUtility.StringSplit(NodeText.Text.Trim());

            foreach (var ft in filterText)
            {
                if (String.IsNullOrEmpty(ft.Trim()))
                {
                    continue;
                }
                if (FilterList.SelectedItem.Value.Equals("1"))
                {
                    auxSets.Add(ft.Trim());
                }
                else
                {
                    texts.Add(ft.Trim());
                }
            }
            if (texts.Count == 0 && auxSets.Count == 0)
            {
                return(null);
            }

            var pauxSets    = new List <String>();
            var ptexts      = new List <String>();
            var pfilterText = WebUtility.StringSplit(PNodeText.Text.Trim());

            foreach (var ft in pfilterText)
            {
                if (String.IsNullOrEmpty(ft.Trim()))
                {
                    continue;
                }
                if (PFilterList.SelectedItem.Value.Equals("1"))
                {
                    pauxSets.Add(ft.Trim());
                }
                else
                {
                    ptexts.Add(ft.Trim());
                }
            }
            if (ptexts.Count == 0 && pauxSets.Count == 0)
            {
                return(null);
            }

            var devTypes = new Dictionary <Int32, String>();

            foreach (var dt in DevTypeMultiCombo.SelectedItems)
            {
                devTypes[Int32.Parse(dt.Value)] = dt.Text;
            }
            if (devTypes.Count == 0)
            {
                return(null);
            }

            var almNames = new List <String>();
            var almIds   = new Dictionary <String, String>();
            var almText  = WebUtility.StringSplit(AlarmNameText.Text.Trim());

            foreach (var at in almText)
            {
                if (String.IsNullOrEmpty(at.Trim()))
                {
                    continue;
                }
                if (AlmNameList.SelectedItem.Value.Equals("1"))
                {
                    almIds[at.Trim()] = null;
                }
                else
                {
                    almNames.Add(at.Trim());
                }
            }

            var palmNames = new List <String>();
            var palmIds   = new Dictionary <String, String>();
            var palmText  = WebUtility.StringSplit(PAlarmNameText.Text.Trim());

            foreach (var at in palmText)
            {
                if (String.IsNullOrEmpty(at.Trim()))
                {
                    continue;
                }
                if (PAlmNameList.SelectedItem.Value.Equals("1"))
                {
                    palmIds[at.Trim()] = null;
                }
                else
                {
                    palmNames.Add(at.Trim());
                }
            }

            var otherEntity = new BOther();
            var nodeEntity  = new BNode();
            var devices     = new List <DeviceInfo>();
            var nodes       = new List <NodeInfo>();
            var pnodes      = new List <NodeInfo>();

            foreach (var lsc in lscs)
            {
                devices.AddRange(otherEntity.GetDevices(lsc.LscID, lsc.Group.GroupID));
                nodes.AddRange(nodeEntity.GetNodes(lsc.LscID, EnmNodeType.Img, texts.ToArray(), auxSets.ToArray(), null));
                if (ptexts.Count > 0 || pauxSets.Count > 0)
                {
                    pnodes.AddRange(nodeEntity.GetNodes(lsc.LscID, EnmNodeType.Img, ptexts.ToArray(), pauxSets.ToArray(), null));
                }
            }

            devices = devices.FindAll(d => devTypes.ContainsKey(d.AlmDevTypeID));
            var devGroup = from dev in devices
                           group dev by new { dev.LscID } into g
                select new {
                LscID   = g.Key.LscID,
                Devices = g.ToList()
            };

            var lcWdv = from lsc in lscs
                        join dg in devGroup on new { lsc.LscID } equals new { dg.LscID } into lt
            from gs in lt.DefaultIfEmpty()
            select new {
                LscID   = lsc.LscID,
                LscName = lsc.LscName,
                Devices = gs == null ? new List <DeviceInfo>() : gs.Devices
            };

            var alarmEntity = new BAlarm();
            var alarms      = WebUtility.GetUserAlarms(userData).FindAll(alarm => lscs.Any(l => l.LscID == alarm.LscID) && alarm.StartTime >= fromTime && alarm.StartTime <= toTime);

            foreach (var lsc in lscs)
            {
                alarms.AddRange(alarmEntity.GetHisAlarms(lsc.LscID, lsc.LscName, userData.StandardProtocol, lsc.Group.GroupNodes, fromTime, toTime));
            }

            var ndWam = from alarm in alarms
                        join node in nodes on new { alarm.LscID, alarm.NodeID, alarm.NodeType } equals new { node.LscID, node.NodeID, node.NodeType }
            where (almNames.Count == 0 || almNames.Any(name => alarm.AlarmName.Contains(name))) && (almIds.Count == 0 || almIds.ContainsKey(alarm.AlarmID.ToString())) && string.IsNullOrEmpty(alarm.ProjName)
            select new {
                Node  = node,
                Alarm = alarm
            };

            var pdWam = from alarm in alarms
                        join node in pnodes on new { alarm.LscID, alarm.NodeID, alarm.NodeType } equals new { node.LscID, node.NodeID, node.NodeType }
            where (palmNames.Count == 0 || palmNames.Any(name => alarm.AlarmName.Contains(name))) && (palmIds.Count == 0 || palmIds.ContainsKey(alarm.AlarmID.ToString())) && string.IsNullOrEmpty(alarm.ProjName)
            select new {
                Node  = node,
                Alarm = alarm
            };

            var almGroup = from alarm in ndWam
                           group alarm by new { alarm.Node.LscID } into g
                select new {
                LscID  = g.Key.LscID,
                Alarms = g.Select(a => a.Alarm)
            };

            var plmGroup = from alarm in pdWam
                           group alarm by new { alarm.Node.LscID } into g
                select new {
                LscID  = g.Key.LscID,
                Alarms = g.Select(a => a.Alarm)
            };

            var result = (from ld in lcWdv
                          join ag in almGroup on new { ld.LscID } equals new { ag.LscID } into lt1
                          from la in lt1.DefaultIfEmpty()
                          join pg in plmGroup on new { ld.LscID } equals new { pg.LscID } into lt2
                          from lp in lt2.DefaultIfEmpty()
                          orderby ld.LscID
                          select new Report002Entity {
                LscID = ld.LscID,
                LscName = ld.LscName,
                BeginTime = fromTime,
                EndTime = toTime,
                Devices = ld.Devices,
                Alarms = la == null ? new List <AlarmInfo>() : la.Alarms.ToList(),
                PAlarms = lp == null ? new List <AlarmInfo>() : lp.Alarms.ToList()
            }).ToList();

            if (result.Count > 0)
            {
                result.Add(new Report002Entity {
                    LscID     = -100,
                    LscName   = "汇总(平均值)",
                    BeginTime = fromTime,
                    EndTime   = toTime,
                    Devices   = new List <DeviceInfo>(),
                    Alarms    = new List <AlarmInfo>(),
                    PAlarms   = new List <AlarmInfo>()
                });
            }

            int cacheDuration = Int32.Parse(WebConfigurationManager.AppSettings["DefaultCacheDuration"]);

            HttpRuntime.Cache.Insert(cacheKey, result, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(cacheDuration), CacheItemPriority.Default, null);
            return(result);
        }
Exemple #36
0
		// Creates an entity given its ID and its URI, and put it into
		// the cache argument if the argument is not null.
        private Entity MakeEntity(Int64 resourceId, string uri, Hashtable cache)
        {
			if (resourceId == 0)
				return null;
			if (resourceId == 1)
				return Statement.DefaultMeta;
			
			ResourceKey rk = new ResourceKey(resourceId);
			
			if (cache != null && cache.ContainsKey(rk))
				return (Entity)cache[rk];
			
			Entity ent;
			if (uri != null) {
				ent = new Entity(uri);
			} else {
				ent = new BNode();
			}
			
			SetResourceKey(ent, rk);
			
			if (cache != null)
				cache[rk] = ent;
				
			return ent;
		}
Exemple #37
0
 private Entity SelectEntity(int type, string value)
 {
     switch (type) {
     case 1: return new Entity(value);
     case 2:
         if (value == DEFAULT_META_KEY) return Statement.DefaultMeta;
         BNode b = new BNode();
         b.SetGUID(new Guid(value));
         return b;
     }
     throw new Exception(); //unreachable
 }