Пример #1
0
        public Heap(Pair[] _points)
        {
            this.points = _points;
            int pointsCount = _points.Length;

            int leafsCount = pointsCount;
            leafsCount = leafsCount - 1;
            leafsCount = leafsCount | (leafsCount >> 1);
            leafsCount = leafsCount | (leafsCount >> 2);
            leafsCount = leafsCount | (leafsCount >> 4);
            leafsCount = leafsCount | (leafsCount >> 8);
            leafsCount = leafsCount | (leafsCount >> 16);
            leafsCount = leafsCount | (leafsCount >> 32);
            leafsCount = leafsCount + 1;

            this.count = 2 * leafsCount - 1;
            this.heap = new int[this.count];

            for (int i = 0; i < pointsCount; i++) {
                this.heap[this.count - 1 - i] = i;
            }
            for (int i = count - 1 - pointsCount; i >= 0; i--) {
                this.heap[i] = int.MinValue;
            }
            BuildHeap();
        }
Пример #2
0
        void Proxy(object user)
        {
            Pair p = new Pair();
            p.inst = Interlocked.Increment(ref inst);
            p.sl = (Socket)user;
            p.sr = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            lock (lck) Console.WriteLine("{0} Connect now", p.Id);

            p.sr.Connect(e2);

            lock (lck) Console.WriteLine("{0} Connected", p.Id);

            Thread tlr = new Thread(Dolr);
            tlr.Start(p);
            Thread trl = new Thread(Dorl);
            trl.Start(p);

            tlr.Join();
            trl.Join();

            lock (lck) Console.WriteLine("{0} Shutdown now", p.Id);

            p.sr.Shutdown(SocketShutdown.Both);
            p.sl.Shutdown(SocketShutdown.Both);

            lock (lck) Console.WriteLine("{0} Close now", p.Id);

            p.sr.Close();
            p.sl.Close();

            lock (lck) Console.WriteLine("{0} Finished", p.Id);
        }
Пример #3
0
        /// <summary>
        /// Bootstraps to the given peer addresses. I.e., looking for near nodes.
        /// </summary>
        /// <param name="peerAddresses">The node to which bootstrap should be performed to.</param>
        /// <param name="routingBuilder">All relevant information for the routing process.</param>
        /// <param name="cc">The channel creator.</param>
        /// <returns>A task object that is set to complete if the route has been found.</returns>
        public Task<Pair<TcsRouting, TcsRouting>> Bootstrap(ICollection<PeerAddress> peerAddresses,
            RoutingBuilder routingBuilder, ChannelCreator cc)
        {
            // search close peers
            Logger.Debug("Bootstrap to {0}.", Convenient.ToString(peerAddresses));
            var tcsDone = new TaskCompletionSource<Pair<TcsRouting, TcsRouting>>();

            // first, we find close peers to us
            routingBuilder.IsBootstrap = true;

            var tcsRouting0 = Routing(peerAddresses, routingBuilder, Message.Message.MessageType.Request1, cc);
            // we need to know other peers as well
            // this is important if this peer is passive and only replies on requests from other peers
            tcsRouting0.Task.ContinueWith(taskRouting0 =>
            {
                if (!taskRouting0.IsFaulted)
                {
                    // setting this to null causes to search for a random number
                    routingBuilder.LocationKey = null;
                    var tcsRouting1 = Routing(peerAddresses, routingBuilder, Message.Message.MessageType.Request1, cc);
                    tcsRouting1.Task.ContinueWith(taskRouting1 =>
                    {
                        var pair = new Pair<TcsRouting, TcsRouting>(tcsRouting0, tcsRouting1);
                        tcsDone.SetResult(pair);
                    });
                }
                else
                {
                    tcsDone.SetException(taskRouting0.TryGetException());
                }
            });

            return tcsDone.Task;
        }
Пример #4
0
 void RoundWin(Pair<int, float> winInfo)
 {
     // init values
     targetCol = gameMan.pColor[winInfo.First];
     winDuration = winInfo.Second / winSpeedFactor;
     winTimer = 0;
 }
Пример #5
0
 /// <summary>
 /// Initializes a new instance of the Team8x4ViewModel class.
 /// </summary>
 public Team8x4ViewModel()
 {
     Pair1 = new Pair();
     Pair2 = new Pair();
     Pair3 = new Pair();
     Pair4 = new Pair();
 }
Пример #6
0
  public void process(Message message, SessionID sessionID)
  {
    Message echo = (Message)message;
    PossResend possResend = new PossResend(false);
    if (message.getHeader().isSetField(possResend))
      message.getHeader().getField(possResend);

    ClOrdID clOrdID = new ClOrdID();
    message.getField(clOrdID);

    Pair pair = new Pair(clOrdID, sessionID);

    if (possResend.getValue() == true)
    {
      if (orderIDs.Contains(pair))
        return;
    }
    if(!orderIDs.Contains(pair))
      orderIDs.Add(pair, pair);
    try
    {
      Session.sendToTarget(echo, sessionID);
    }
    catch (SessionNotFound) { }
  }
Пример #7
0
        public static string NormalizeSequence(Animation anim, DamageState state, string sequence)
        {
            var states = new Pair<DamageState, string>[]
            {
                Pair.New(DamageState.Critical, "critical-"),
                Pair.New(DamageState.Heavy, "damaged-"),
                Pair.New(DamageState.Medium, "scratched-"),
                Pair.New(DamageState.Light, "scuffed-")
            };

            // Remove existing damage prefix
            foreach (var s in states)
            {
                if (sequence.StartsWith(s.Second))
                {
                    sequence = sequence.Substring(s.Second.Length);
                    break;
                }
            }

            foreach (var s in states)
                if (state >= s.First && anim.HasSequence(s.Second + sequence))
                    return s.Second + sequence;

            return sequence;
        }
Пример #8
0
        public Pair<List<Double>, List<Double>> numerize(Example e)
        {
            List<Double> input = new List<Double>();
            List<Double> desiredOutput = new List<Double>();

            double sepal_length = e.getAttributeValueAsDouble("sepal_length");
            double sepal_width = e.getAttributeValueAsDouble("sepal_width");
            double petal_length = e.getAttributeValueAsDouble("petal_length");
            double petal_width = e.getAttributeValueAsDouble("petal_width");

            input.Add(sepal_length);
            input.Add(sepal_width);
            input.Add(petal_length);
            input.Add(petal_width);

            String plant_category_string = e
                    .getAttributeValueAsString("plant_category");

            desiredOutput = convertCategoryToListOfDoubles(plant_category_string);

            Pair<List<Double>, List<Double>> io = new Pair<List<Double>, List<Double>>(
                    input, desiredOutput);

            return io;
        }
Пример #9
0
		public static LNode replace(LNode node, IMacroContext context)
		{
			var args_body = context.GetArgsAndBody(true);
			var args = args_body.A;
			var body = args_body.B;
			if (args.Count >= 1)
			{
				var patterns = new Pair<LNode, LNode>[args.Count];
				for (int i = 0; i < patterns.Length; i++)
				{
					var pair = args[i];
					if (pair.Calls(S.Lambda, 2)) {
						LNode pattern = pair[0], repl = pair[1];
						if (pattern.Calls(S.Braces, 1) && repl.Calls(S.Braces)) {
							pattern = pattern.Args[0];
							repl = repl.WithTarget(S.Splice);
						}
						patterns[i] = Pair.Create(pattern, repl);
					} else {
						string msg = "Expected 'pattern => replacement'.";
						if (pair.Descendants().Any(n => n.Calls(S.Lambda, 2)))
							msg += " " + "(Using '=>' already? Put the pattern on the left-hand side in parentheses.)";
						return Reject(context, pair, msg);
					}
				}

				int replacementCount;
				var output = Replace(body, patterns, out replacementCount);
				if (replacementCount == 0)
					context.Write(Severity.Warning, node, "No patterns recognized; no replacements were made.");
				return output.AsLNode(S.Splice);
			}
			return null;
		}
Пример #10
0
 static Enemy()
 {
     _mdl = OBJModelParser.GetInstance().Parse("res/mdl/enemy");
     _garbage = new Bitmap(1, 1);
     _garbageg = Graphics.FromImage(_garbage);
     List<Pair<string, Rect2D>> quotes = new List<Pair<string, Rect2D>>();
     using (StreamReader s = new StreamReader("res/screams.txt")) {
         while (!s.EndOfStream) {
             string q = s.ReadLine();
             while (q.EndsWith(@"\")) {
                 q = q.Substring(0, q.Length - 1);
                 q += "\n";
                 q += s.ReadLine();
             }
             SizeF size = _garbageg.MeasureString(q, SystemFonts.DefaultFont);
             Bitmap img = new Bitmap((int)size.Width + 6, (int)size.Height + 6);
             Graphics g = Graphics.FromImage(img);
             g.FillRectangle(Brushes.White, 0, 0, img.Width, img.Height);
             g.DrawString(q, SystemFonts.DefaultFont, Brushes.Black, 3, 3);
             g.Dispose();
             Pair<string, Rect2D> ins = new Pair<string, Rect2D>();
             ins.First = q;
             const int SCALE = 30;
             const int SCALE2 = 2 * SCALE;
             ins.Second = new Rect2D(img,
                     -(size.Width / SCALE2), -(size.Height / SCALE2),
                     (size.Width / SCALE), (size.Height / SCALE));
             quotes.Add(ins);
         }
     }
     _garbageg.Dispose();
     _garbageg = null; //Prevent accidental use.
     _quotes = quotes.ToArray();
     _r = new Random();
 }
Пример #11
0
        public ObjectCreator(Manifest manifest, FileSystem.FileSystem modFiles)
        {
            typeCache = new Cache<string, Type>(FindType);
            ctorCache = new Cache<Type, ConstructorInfo>(GetCtor);

            // Allow mods to load types from the core Game assembly, and any additional assemblies they specify.
            var assemblyList = new List<Assembly>() { typeof(Game).Assembly };
            foreach (var path in manifest.Assemblies)
            {
                var data = modFiles.Open(path).ReadAllBytes();

                // .NET doesn't provide any way of querying the metadata of an assembly without either:
                //   (a) loading duplicate data into the application domain, breaking the world.
                //   (b) crashing if the assembly has already been loaded.
                // We can't check the internal name of the assembly, so we'll work off the data instead
                var hash = CryptoUtil.SHA1Hash(data);

                Assembly assembly;
                if (!ResolvedAssemblies.TryGetValue(hash, out assembly))
                {
                    assembly = Assembly.Load(data);
                    ResolvedAssemblies.Add(hash, assembly);
                }

                assemblyList.Add(assembly);
            }

            AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
            assemblies = assemblyList.SelectMany(asm => asm.GetNamespaces().Select(ns => Pair.New(asm, ns))).ToArray();
            AppDomain.CurrentDomain.AssemblyResolve -= ResolveAssembly;
        }
        protected void parseLevelFile()
        {
            Stack<String> parseStack = new Stack<String>();
            Pair<int, int> pair;

            using (var stream = System.IO.File.OpenText(fname))
            using (var reader = XmlReader.Create(stream))
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        parseStack.Push(reader.Name);

                        switch (reader.Name)
                        {
                            case "level":
                                name = reader.GetAttribute("name");
                                layers = int.Parse(reader.GetAttribute("layers"));
                                break;
                            case "layers":
                            case "entries":
                                break;
                            case "layer":
                                layerFiles.Add(int.Parse(reader.GetAttribute("id")), reader.GetAttribute("file"));
                                break;
                            case "entry":
                                pair = new Pair<int, int>(int.Parse(reader.GetAttribute("layer")), int.Parse(reader.GetAttribute("eid")));
                                entries.Add(reader.GetAttribute("id"), pair);
                                break;
                        }
                    }
                }
            }
        }
Пример #13
0
        static void Main(string[] args)
        {
            Console.WriteLine("We will now do some Pair Arithmetic!");

            PairArithmeticClient pairClient = new PairArithmeticClient();
            Pair p1 = new Pair { First = 15, Second = 22 };
            Pair p2 = new Pair { First = 7, Second = 13 };
            Console.WriteLine(string.Format("\r\nPair 1 is {{{0}, {1}}}", p1.First, p1.Second));
            Console.WriteLine(string.Format("Pair 2 is {{{0}, {1}}}", p2.First, p2.Second));
            Pair result = pairClient.Add(p1, p2);
            Console.WriteLine(string.Format("\r\nP1 + P2 is {{{0}, {1}}}", result.First, result.Second));

            result = pairClient.Subtract(p1, p2);
            Console.WriteLine(string.Format("\r\nP1 - P2 is {{{0}, {1}}}", result.First, result.Second));

            result = pairClient.ScalarMultiply(p1, 3);
            Console.WriteLine(string.Format("\r\nP1 * 3 is {{{0}, {1}}}", result.First, result.Second));

            PoliteClient politeClient = new PoliteClient();
            Console.WriteLine("");
            Console.WriteLine(politeClient.SayHello("Rob"));

            Console.WriteLine("\r\nDone\r\nPress any key to exit...");
            Console.ReadKey();
        }
Пример #14
0
 /// <summary>
 /// Check if a point is within a given rectangle.
 /// Use an option offset term to convert between world and screen coordinates
 /// </summary>
 /// <param name="pos">Position (in either world or screen coordinates)</param>
 /// <param name="offset">Offset used to convert between coordinates</param>
 /// <param name="rect">Rectangle</param>
 /// <returns>True if the point is in the given rectangle</returns>
 public static bool IsInRectangle(Pair<int> pos, Pair<int> offset, Rectangle rect)
 {
     return (pos.x >= offset.x + rect.X &&
             pos.x <= offset.x + rect.X + rect.Width &&
             pos.y >= offset.y + rect.Y &&
             pos.y <= offset.y + rect.Y + rect.Height);
 }
Пример #15
0
 /// <summary>
 /// Check if a point is within a given rectangle.
 /// </summary>
 /// <param name="pos">Position (in either world or screen coordinates)</param>
 /// <param name="x">Rectangle X position</param>
 /// <param name="y">Rectangle Y position</param>
 /// <param name="width">Rectangle width</param>
 /// <param name="height">Rectangle height</param>
 /// <returns>True if the point is in the given rectangle</returns>
 public static bool IsInRectangle(Pair<int> pos, int x, int y, int width, int height)
 {
     return (pos.x >= x &&
             pos.x <= x + width &&
             pos.y >= y &&
             pos.y <= y + height);
 }
Пример #16
0
        static void Main(string[] args)
        {
            BrokerClient prx = new BrokerClient();
            Pair p = new Pair();

            IContextManager ctxManager = prx.InnerChannel.GetProperty<IContextManager>();
            IDictionary<string, string> context = ctxManager.GetContext();

            context["clientName"] = "Client1";
            ctxManager.SetContext(context);

            for (int i = 0; i < 50; ++i)
            {
                p.Key = "" + i;
                p.Value = "My val " + i;

                try
                {
                    prx.StorePair(p);
                }
                catch (FaultException e)
                {
                    Console.WriteLine(e.Reason);
                }
            }

            Console.WriteLine("Keys Added. Press any key to exit.");
            Console.ReadLine();
        }
Пример #17
0
 internal AcceptorBase(FuncDecl symbol, Expr guard, ExprSet[] lookahead)
 {
     this.symbol = symbol;
     this.guard = guard;
     this.lookahead = lookahead;
     this.lhs = new Pair<FuncDecl, Sequence<ExprSet>>(symbol, new Sequence<ExprSet>(lookahead));
 }
Пример #18
0
 public void GetAlbumArtAsync(MediaControl.Client.Console.MediaLibrary.Track track,
     Action<byte[], object> callback, object state)
 {
     Pair<Action<byte[], object>, object> pair =
         new Pair<Action<byte[], object>, object>(callback, state);
     LibraryServiceClient.GetAlbumArtAsync(new GetAlbumArtRequest(track), pair);
 }
            public Item(int value)
            {
                Value = value;
                NonSerializedValue = value;
                TransientValue = value;
				Pair = new Pair("p1", value);
            }
Пример #20
0
        /// <summary>
        /// 基本代换班
        /// </summary>
        public void SwapingForTerm(Pair<Guid> agentPair, Pair<long?> assignmentPair, bool isLaborRule)
        {
            ReSet();
            _attendanceRepository.Clear();
            GetSwapingDate(assignmentPair);
            Initialize(agentPair,isLaborRule);

            Applier.InitializeSwapingForTerm(assignmentPair.Applier);
            Replier.InitializeSwapingForTerm(assignmentPair.Replier);
            if (Applier.Term != null)
            {
                Replier.TimeOff = Replier.TimeBox.SpecificTerm<TimeOff>().CollideTerms(Applier.Term).FirstOrDefault();
            }
            if (Replier.Term != null)
            {
                Applier.TimeOff = Applier.TimeBox.SpecificTerm<TimeOff>().CollideTerms(Replier.Term).FirstOrDefault();
            }
            //删除班
            DeleteTerm();
            //设置TimeOff
            SetTimeOff();
            //交换班表
            SwapSpecificTerm();
            SwapSpecificSubEvents();
            //验证交换信息
            VaildateSwapMessage();
        }
Пример #21
0
 // Take a bag of LET components and write the equivalent LAMBDA
 // expression.  Handles named LET.
 private static Datum ConstructLambdaFromLet(LetComps comps)
 {
     // Unzip!
     List<Datum> names = new List<Datum>();
     List<Datum> vals = new List<Datum>();
     foreach (Pair p in comps.bindings)
     {
         names.Add(p.First);
         vals.Add(p.Second);
     }
     Datum formals = Primitives.List(names);
     Datum bodyFunc = new Pair(new Symbol("lambda"),
                               new Pair(formals, comps.body));
     Datum transform;
     if (comps.self == null)
     {
         // Unnamed LET.
         transform = new Pair(bodyFunc, Primitives.List(vals));
     }
     else
     {
         // Named LET.
         transform =
             new Pair(Datum.List(new Symbol("let"),
                                 Datum.List(Datum.List(comps.self,
                                                       null)),
                                 Datum.List(new Symbol("set!"),
                                            comps.self,
                                            bodyFunc),
                                 comps.self),
                      Primitives.List(vals));
     }
     Shell.Trace("LET transform produced ", transform);
     return transform;
 }
Пример #22
0
        /// <summary>
        /// Removes the specified constraint from the collision filter.
        /// </summary>
        /// <param name="constraint">The constraint to be removed.</param>
        internal void UnregisterFromCollisionFilter(Constraint constraint)
        {
            Debug.Assert(constraint != null, "constraint is null.");
              Debug.Assert(constraint.BodyA != null, "constraint.BodyA is null.");
              Debug.Assert(constraint.BodyB != null, "constraint.BodyB is null.");

              var pair = new Pair<CollisionObject>(constraint.BodyA.CollisionObject, constraint.BodyB.CollisionObject);
              Debug.Assert(_constraints.ContainsKey(pair), "No constraint is stored in the collision filter for the given pair of collision objects.");
              List<Constraint> constraints = _constraints[pair];
              Debug.Assert(constraints.Contains(constraint));
              if (constraints.Count == 1)
              {
            // The constraint is the only constraint of this pair.
            // --> Remove the entry for this pair.
            Debug.Assert(constraints[0] == constraint, "Constraint is not registered in collision filter.");
            ResourcePools<Constraint>.Lists.Recycle(constraints);
            _constraints.Remove(pair);

            // Re-enable collisions.
            var filter = CollisionDomain.CollisionDetection.CollisionFilter as ICollisionFilter;
            if (filter != null)
              filter.Set(pair.First, pair.Second, true);
              }
              else
              {
            // Remove the constraint from the list.
            constraints.Remove(constraint);
              }
        }
Пример #23
0
        static void Main(string[] args)
        {
            // Question 1
            foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (asm.GetName().Name == "tp3")
                {
                    foreach (Type ty in asm.GetTypes())
                    {
                        Console.WriteLine(" Classe : " + ty);
                        foreach (MethodInfo mi in ty.GetMethods())
                        {
                            Console.WriteLine(" Methode : " + mi);
                            foreach (ParameterInfo pi in mi.GetParameters())
                                Console.WriteLine("Parametre : " + pi.GetType());
                        }
                    }
                }
            }

            // Question 2
            Console.WriteLine();
            Pair<int, char> p = new Pair<int, char>(5, 'c');
            Console.WriteLine("Paire:" + p.El1 + " " + p.El2);

            // Question 3

            HashTableReflection tab = new HashTableReflection();

            Console.ReadLine();
        }
Пример #24
0
 internal static void RemoveAspect(BoundSetAspect boundSetAspect)
 {
     Pair<BoundSetAspect>[] pairs = new Pair<BoundSetAspect>[collisions.Keys.Count];
     collisions.Keys.CopyTo(pairs, 0);
     foreach (Pair<BoundSetAspect> pair in pairs)
     {
         if (pair.First == boundSetAspect)
         {
             Pair<BoundSetAspect> newPair = new Pair<BoundSetAspect>(null, pair.Second);
             collisions.Remove(pair);
             if (pair.Second != null)
                 collisions.Add(pair, 0);
             SendNotCollision(boundSetAspect, pair.Second);
         }
         else
             if (pair.Second == boundSetAspect)
             {
                 Pair<BoundSetAspect> newPair = new Pair<BoundSetAspect>(pair.First, null);
                 collisions.Remove(pair);
                 if (pair.First != null)
                     collisions.Add(pair, 0);
                 SendNotCollision(boundSetAspect, pair.First);
             }
     }
 }
Пример #25
0
        /// <summary>
        /// Adds the specified constraint to the collision filter.
        /// </summary>
        /// <param name="constraint">The constraint to be registered.</param>
        internal void RegisterInCollisionFilter(Constraint constraint)
        {
            Debug.Assert(constraint != null, "constraint is null.");
              Debug.Assert(constraint.BodyA != null, "constraint.BodyA is null.");
              Debug.Assert(constraint.BodyB != null, "constraint.BodyB is null.");
              Debug.Assert(constraint.Enabled && !constraint.CollisionEnabled, "Constraints should only be registered if it disabled collisions.");

              var pair = new Pair<CollisionObject>(constraint.BodyA.CollisionObject, constraint.BodyB.CollisionObject);
              List<Constraint> constraints;
              if (!_constraints.TryGetValue(pair, out constraints))
              {
            // Create new list of constraints for the current pair.
            constraints = ResourcePools<Constraint>.Lists.Obtain();
            _constraints[pair] = constraints;
              }

              if (!constraints.Contains(constraint))
              {
            if (constraints.Count == 0)
            {
              var filter = CollisionDomain.CollisionDetection.CollisionFilter as ICollisionFilter;
              if (filter != null)
            filter.Set(pair.First, pair.Second, false);
            }

            constraints.Add(constraint);
              }
        }
Пример #26
0
         public CodeBrowser()
            : base(Constants.WINDOW_ID_CODEBROWSER, "Ribbon Codes")
         {
            STYLE_CODE.stretchWidth = false;
            STYLE_CODE.fixedWidth = 100;
            STYLE_CODE.alignment = TextAnchor.MiddleLeft;
            STYLE_NAME.stretchWidth = true;
            STYLE_NAME.alignment = TextAnchor.MiddleLeft;
            //
            // copy activitiesfor sorting into code list
            Log.Detail("adding action codes to code browser " + ActionPool.Instance());
            foreach (Activity activity in ActivityPool.Instance())
            {
               Pair<String, String> code = new Pair<String, String>(activity.GetCode(), activity.GetName());
               codes.Add(code);
            }

            // sort by code
            Log.Detail("sorting codes in code browser");
            codes.Sort(
               delegate(Pair<String,String> left, Pair<String,String> right)
               {
                  return left.first.CompareTo(right.first);
               });
         }
Пример #27
0
        void PasswordCommand(ISender sender, ArgumentList args)
        {
            Player player = sender as Player;
                Protection temp = new Protection ();
                Pair<Action, Protection> pair = new Pair<Action, Protection> (Action.NOTHING, null);

                if (args.Count != 1) {
                    player.SendMessage ("Usage: /cpassword <password>", 255, 255, 0, 0);
                    return;
                }

                string Extra = args[0];

                temp = new Protection ();
                temp.Owner = player.Name;
                temp.Type = Protection.PASSWORD_PROTECTION;
                temp.Data = SHA1.Hash (Extra);

                char[] pass = Extra.ToCharArray ();
                for (int index = 0; index < pass.Length; index++) {
                    pass [index] = '*';
                }

                pair.First = Action.CREATE;
                pair.Second = temp;

                player.SendMessage ("Password: "******"Open the chest to protect it!", 255, 0, 255, 0);

            // cache the action if it's not null!
            if (pair.First != Action.NOTHING) {
                ResetActions (player);
                Cache.Actions.Add (player.Name, pair);
            }
        }
Пример #28
0
 public static Vector2 GetActualPos(Pair coord)
 {
     Vector2 result;
     result.x = - coord.x * 0.5f + coord.y * 0.5f;
     result.y = coord.x * 0.25f + coord.y * 0.25f;
     return result;
 }
Пример #29
0
 internal static void CheckIntersection(BoundSetAspect boundSet1, BoundSetAspect boundSet2)
 {
     Pair<BoundSetAspect> pair = new Pair<BoundSetAspect>(boundSet1, boundSet2);
     // если объекты пересекаются, то ищем их в словаре.
     // если нашли, то НЕ генерируем событие Collision
     // если не нашли, то генерируем событие Collision и заносим их в словарь
     if (boundSet1.IntersectsWith(boundSet2))
     {
         if (!collisions.ContainsKey(pair))
         {
             collisions.Add(pair, 0);
             SendCollision(boundSet1, boundSet2);
         }
     }
     // объекты не пересекаются.
     // нужно удалить их из словарей, если они там есть,
     // и сгенерировать событие NotCollision, если они там были
     else
     {
         if (collisions.ContainsKey(pair))
         {
             collisions.Remove(pair);
             SendNotCollision(boundSet1, boundSet2);
         }
     }
 }
Пример #30
0
 public void Pair1_Unit_Constructor1_Optimal()
 {
     String expected = default(String);
     Pair<String> target = new Pair<String>();
     Assert.AreEqual(expected, target.First);
     Assert.AreEqual(expected, target.Second);
 }
Пример #31
0
        void SetupFilters()
        {
            // Game type
            {
                var ddb = panel.GetOrNull <DropDownButtonWidget>("FLT_GAMETYPE_DROPDOWNBUTTON");
                if (ddb != null)
                {
                    // Using list to maintain the order
                    var options = new List <Pair <GameType, string> >
                    {
                        Pair.New(GameType.Any, ddb.GetText()),
                        Pair.New(GameType.Singleplayer, "Singleplayer"),
                        Pair.New(GameType.Multiplayer, "Multiplayer")
                    };

                    var lookup = options.ToDictionary(kvp => kvp.First, kvp => kvp.Second);

                    ddb.GetText     = () => lookup[filter.Type];
                    ddb.OnMouseDown = _ =>
                    {
                        Func <Pair <GameType, string>, ScrollItemWidget, ScrollItemWidget> setupItem = (option, tpl) =>
                        {
                            var item = ScrollItemWidget.Setup(
                                tpl,
                                () => filter.Type == option.First,
                                () => { filter.Type = option.First; ApplyFilter(); });
                            item.Get <LabelWidget>("LABEL").GetText = () => option.Second;
                            return(item);
                        };

                        ddb.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 330, options, setupItem);
                    };
                }
            }

            // Date type
            {
                var ddb = panel.GetOrNull <DropDownButtonWidget>("FLT_DATE_DROPDOWNBUTTON");
                if (ddb != null)
                {
                    // Using list to maintain the order
                    var options = new List <Pair <DateType, string> >
                    {
                        Pair.New(DateType.Any, ddb.GetText()),
                        Pair.New(DateType.Today, "Today"),
                        Pair.New(DateType.LastWeek, "Last 7 days"),
                        Pair.New(DateType.LastFortnight, "Last 14 days"),
                        Pair.New(DateType.LastMonth, "Last 30 days")
                    };

                    var lookup = options.ToDictionary(kvp => kvp.First, kvp => kvp.Second);

                    ddb.GetText     = () => lookup[filter.Date];
                    ddb.OnMouseDown = _ =>
                    {
                        Func <Pair <DateType, string>, ScrollItemWidget, ScrollItemWidget> setupItem = (option, tpl) =>
                        {
                            var item = ScrollItemWidget.Setup(
                                tpl,
                                () => filter.Date == option.First,
                                () => { filter.Date = option.First; ApplyFilter(); });

                            item.Get <LabelWidget>("LABEL").GetText = () => option.Second;
                            return(item);
                        };

                        ddb.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 330, options, setupItem);
                    };
                }
            }

            // Duration
            {
                var ddb = panel.GetOrNull <DropDownButtonWidget>("FLT_DURATION_DROPDOWNBUTTON");
                if (ddb != null)
                {
                    // Using list to maintain the order
                    var options = new List <Pair <DurationType, string> >
                    {
                        Pair.New(DurationType.Any, ddb.GetText()),
                        Pair.New(DurationType.VeryShort, "Under 5 min"),
                        Pair.New(DurationType.Short, "Short (10 min)"),
                        Pair.New(DurationType.Medium, "Medium (30 min)"),
                        Pair.New(DurationType.Long, "Long (60+ min)")
                    };

                    var lookup = options.ToDictionary(kvp => kvp.First, kvp => kvp.Second);

                    ddb.GetText     = () => lookup[filter.Duration];
                    ddb.OnMouseDown = _ =>
                    {
                        Func <Pair <DurationType, string>, ScrollItemWidget, ScrollItemWidget> setupItem = (option, tpl) =>
                        {
                            var item = ScrollItemWidget.Setup(
                                tpl,
                                () => filter.Duration == option.First,
                                () => { filter.Duration = option.First; ApplyFilter(); });
                            item.Get <LabelWidget>("LABEL").GetText = () => option.Second;
                            return(item);
                        };

                        ddb.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 330, options, setupItem);
                    };
                }
            }

            // Outcome (depends on Player)
            {
                var ddb = panel.GetOrNull <DropDownButtonWidget>("FLT_OUTCOME_DROPDOWNBUTTON");
                if (ddb != null)
                {
                    ddb.IsDisabled = () => string.IsNullOrEmpty(filter.PlayerName);

                    // Using list to maintain the order
                    var options = new List <Pair <WinState, string> >
                    {
                        Pair.New(WinState.Undefined, ddb.GetText()),
                        Pair.New(WinState.Lost, "Defeat"),
                        Pair.New(WinState.Won, "Victory")
                    };

                    var lookup = options.ToDictionary(kvp => kvp.First, kvp => kvp.Second);

                    ddb.GetText     = () => lookup[filter.Outcome];
                    ddb.OnMouseDown = _ =>
                    {
                        Func <Pair <WinState, string>, ScrollItemWidget, ScrollItemWidget> setupItem = (option, tpl) =>
                        {
                            var item = ScrollItemWidget.Setup(
                                tpl,
                                () => filter.Outcome == option.First,
                                () => { filter.Outcome = option.First; ApplyFilter(); });
                            item.Get <LabelWidget>("LABEL").GetText = () => option.Second;
                            return(item);
                        };

                        ddb.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 330, options, setupItem);
                    };
                }
            }

            // Reset button
            {
                var button = panel.Get <ButtonWidget>("FLT_RESET_BUTTON");
                button.IsDisabled = () => filter.IsEmpty;
                button.OnClick    = () => { filter = new Filter(); ApplyFilter(); };
            }
        }
Пример #32
0
 internal void AddMessage(string message)
 {
     LevelIndex.Add(Pair.Create(LevelKind.Message, Messages.Count));
     Messages.Add(message);
 }
Пример #33
0
 internal void AddLevel(Level level)
 {
     LevelIndex.Add(Pair.Create(LevelKind.Level, Levels.Count));
     Levels.Add(level);
 }
Пример #34
0
 public void SetSetting(OptionSetting name, Pair <int, int> value)
 {
     PairSettings[name] = value;
 }
Пример #35
0
 public Pair <int, int> GetSetting(OptionSetting name, Pair <int, int> other)
 {
     return(PairSettings.SafeLookup(name, other));
 }
Пример #36
0
        public void UpdateFromMap(IReadOnlyPackage p, IReadOnlyPackage parent, MapClassification classification, string[] mapCompatibility, MapGridType gridType)
        {
            Dictionary <string, MiniYaml> yaml;

            using (var yamlStream = p.GetStream("map.yaml"))
            {
                if (yamlStream == null)
                {
                    throw new FileNotFoundException("Required file map.yaml not present in this map");
                }

                yaml = new MiniYaml(null, MiniYaml.FromStream(yamlStream, "map.yaml")).ToDictionary();
            }

            Package       = p;
            parentPackage = parent;

            var newData = innerData.Clone();

            newData.GridType = gridType;
            newData.Class    = classification;

            MiniYaml temp;

            if (yaml.TryGetValue("MapFormat", out temp))
            {
                var format = FieldLoader.GetValue <int>("MapFormat", temp.Value);
                if (format != Map.SupportedMapFormat)
                {
                    throw new InvalidDataException("Map format {0} is not supported.".F(format));
                }
            }

            if (yaml.TryGetValue("Title", out temp))
            {
                newData.Title = temp.Value;
            }

            if (yaml.TryGetValue("Categories", out temp))
            {
                newData.Categories = FieldLoader.GetValue <string[]>("Categories", temp.Value);
            }

            if (yaml.TryGetValue("Tileset", out temp))
            {
                newData.TileSet = temp.Value;
            }

            if (yaml.TryGetValue("Author", out temp))
            {
                newData.Author = temp.Value;
            }

            if (yaml.TryGetValue("Bounds", out temp))
            {
                newData.Bounds = FieldLoader.GetValue <Rectangle>("Bounds", temp.Value);
            }

            if (yaml.TryGetValue("Visibility", out temp))
            {
                newData.Visibility = FieldLoader.GetValue <MapVisibility>("Visibility", temp.Value);
            }

            string requiresMod = string.Empty;

            if (yaml.TryGetValue("RequiresMod", out temp))
            {
                requiresMod = temp.Value;
            }

            newData.Status = mapCompatibility == null || mapCompatibility.Contains(requiresMod) ?
                             MapStatus.Available : MapStatus.Unavailable;

            try
            {
                // Actor definitions may change if the map format changes
                MiniYaml actorDefinitions;
                if (yaml.TryGetValue("Actors", out actorDefinitions))
                {
                    var spawns = new List <CPos>();
                    foreach (var kv in actorDefinitions.Nodes.Where(d => d.Value.Value == "mpspawn"))
                    {
                        var s = new ActorReference(kv.Value.Value, kv.Value.ToDictionary());
                        spawns.Add(s.InitDict.Get <LocationInit>().Value(null));
                    }

                    newData.SpawnPoints = spawns.ToArray();
                }
                else
                {
                    newData.SpawnPoints = new CPos[0];
                }
            }
            catch (Exception)
            {
                newData.SpawnPoints = new CPos[0];
                newData.Status      = MapStatus.Unavailable;
            }

            try
            {
                // Player definitions may change if the map format changes
                MiniYaml playerDefinitions;
                if (yaml.TryGetValue("Players", out playerDefinitions))
                {
                    newData.Players     = new MapPlayers(playerDefinitions.Nodes);
                    newData.PlayerCount = newData.Players.Players.Count(x => x.Value.Playable);
                }
            }
            catch (Exception)
            {
                newData.Status = MapStatus.Unavailable;
            }

            newData.SetRulesetGenerator(modData, () =>
            {
                var ruleDefinitions         = LoadRuleSection(yaml, "Rules");
                var weaponDefinitions       = LoadRuleSection(yaml, "Weapons");
                var voiceDefinitions        = LoadRuleSection(yaml, "Voices");
                var musicDefinitions        = LoadRuleSection(yaml, "Music");
                var notificationDefinitions = LoadRuleSection(yaml, "Notifications");
                var sequenceDefinitions     = LoadRuleSection(yaml, "Sequences");
                var rules = Ruleset.Load(modData, this, TileSet, ruleDefinitions, weaponDefinitions,
                                         voiceDefinitions, notificationDefinitions, musicDefinitions, sequenceDefinitions);
                var flagged = Ruleset.DefinesUnsafeCustomRules(modData, this, ruleDefinitions,
                                                               weaponDefinitions, voiceDefinitions, notificationDefinitions, sequenceDefinitions);
                return(Pair.New(rules, flagged));
            });

            if (p.Contains("map.png"))
            {
                using (var dataStream = p.GetStream("map.png"))
                    newData.Preview = new Bitmap(dataStream);
            }

            // Assign the new data atomically
            innerData = newData;
        }
 public int GetHashCode(Pair <int> obj)
 {
     return(obj.First + (obj.Second << 16));
 }
 public bool Equals(Pair <int> x, Pair <int> y)
 {
     return((x.First == y.First) && (x.Second == y.Second));
 }
Пример #39
0
 public int CompareTo(Pair <T, U> a) => f.CompareTo(a.f) != 0 ? f.CompareTo(a.f) : s.CompareTo(a.s);
Пример #40
0
 public static Vector2 ToVector2(this Pair <float, float> pair)
 {
     return(new Vector2(pair.X, pair.Y));
 }
Пример #41
0
        /// <summary>
        /// Simplify the graph by removing the cycles and smoothing techniques. On the way of removing the cycle, if any nodes
        /// disappear from the graph, the edge color mapping should be return back
        /// </summary>
        /// <param name="cycleLenghtThreshold">The maximum cycle length that can be re-route</param>
        /// <param name="smoothingThreshold">the maximum length of the simple path that can be splitted</param>
        /// <param name="shouldSmooth">If we should smooth the graph</param>
        /// <param name="splitNodes">Split nodes Set</param>
        /// <returns>Color edge Set</returns>
        public HashSet <KeyValuePair <int, int> > Simplify(int cycleLenghtThreshold, int smoothingThreshold, bool shouldSmooth, out HashSet <int> splitNodes)
        {
            splitNodes = new HashSet <int>();
            HashSet <KeyValuePair <int, int> > colorEdges         = new HashSet <KeyValuePair <int, int> >();
            IDictionary <Pair <int>, int>      multiplicityByEdge = GenerateMultiplicityByEdge(_workingSequence.GetMembersValue()); //用字典记录有多少边,key是边,value是个数

            Console.Out.WriteLine("Number of edges: " + multiplicityByEdge.Count);
            IList <Pair <int> > weakEdges = _graphTool.GetWeakEdges(multiplicityByEdge);       //找到循环

            while (weakEdges.Count != 0)
            {
                Pair <int> currentWeakEdge = weakEdges[0];
                weakEdges.RemoveAt(0);
                HashSet <KeyValuePair <int, int> > suspectedWeakEdges = _graphTool.ReSolveCycle(currentWeakEdge, cycleLenghtThreshold, ref _graph);        //去除循环,返回颜色边界
                if (suspectedWeakEdges != null)
                {
                    foreach (KeyValuePair <int, int> edge in suspectedWeakEdges)         //标记所有颜色边界
                    {
                        if (!colorEdges.Contains(edge))
                        {
                            colorEdges.Add(edge);
                        }
                    }
                }

                /*
                 * foreach (pair<int> edge in suspectedweakedges)
                 *  weakedges.insert(0, edge);
                 */
            }
            Console.Out.WriteLine("Nodes:" + _graph.Keys.Count);
            //平滑需要
            if (shouldSmooth)
            {
                //PRocess tandem Repeat A-A
                _graphTool.ProcessTandem(ref _workingSequence, ref _graph);
                //smoothing step
                IDictionary <Pair <int>, int> newMultiplicityByEdge =
                    GenerateMultiplicityByEdge(_workingSequence.GetMembersValue());                                                                      //返回一个字典,key是一个边的pair,value是边的个数
                IDictionary <int, IList <int> > graphLinkStructure =
                    GenerateGraphLinkStructure(_workingSequence.GetMembersValue());                                                                      //返回一个字典,key是基因,value是这个基因所有邻居的列表
                IDictionary <int, int> multiplicityByNodeID = GetMultiplicityByNodeID();                                                                 //返回一个字典,key是基因,value是基因的个数
                IList <IList <int> >   simplePaths          = _graphTool.GetSimplePath(graphLinkStructure, newMultiplicityByEdge, multiplicityByNodeID); //获得多条简单路径
                foreach (IList <int> path in simplePaths)
                {
                    if (path.Count < smoothingThreshold && _graph[path[0]].Count > 1)    //只有小于2个点的基因才可以平滑
                    {
                        IList <int> smooth = _graphTool.Smooth(path, ref _graph);        //path可分才返回path,不然返回null
                        foreach (int i in smooth)
                        {
                            if (!splitNodes.Contains(i))
                            {
                                splitNodes.Add(i);
                            }
                        }
                    }
                }
                //ProcessPalindrome(_workingSequence);
                _graphTool.ProcessPalindrome(ref _workingSequence, ref _graph);
            }
            return(colorEdges);
        }
Пример #42
0
        public void UpdateRemoteSearch(MapStatus status, MiniYaml yaml, Action <MapPreview> parseMetadata = null)
        {
            var newData = innerData.Clone();

            newData.Status = status;
            newData.Class  = MapClassification.Remote;

            if (status == MapStatus.DownloadAvailable)
            {
                try
                {
                    var r = FieldLoader.Load <RemoteMapData>(yaml);

                    // Map download has been disabled server side
                    if (!r.downloading)
                    {
                        newData.Status = MapStatus.Unavailable;
                        return;
                    }

                    newData.Title       = r.title;
                    newData.Categories  = r.categories;
                    newData.Author      = r.author;
                    newData.PlayerCount = r.players;
                    newData.Bounds      = r.bounds;
                    newData.TileSet     = r.tileset;

                    var spawns = new CPos[r.spawnpoints.Length / 2];
                    for (var j = 0; j < r.spawnpoints.Length; j += 2)
                    {
                        spawns[j / 2] = new CPos(r.spawnpoints[j], r.spawnpoints[j + 1]);
                    }
                    newData.SpawnPoints = spawns;
                    newData.GridType    = r.map_grid_type;
                    try
                    {
                        newData.Preview = new Bitmap(new MemoryStream(Convert.FromBase64String(r.minimap)));
                    }
                    catch (Exception e)
                    {
                        Log.Write("debug", "Failed parsing mapserver minimap response: {0}", e);
                        newData.Preview = null;
                    }

                    var playersString = Encoding.UTF8.GetString(Convert.FromBase64String(r.players_block));
                    newData.Players = new MapPlayers(MiniYaml.FromString(playersString));

                    newData.SetRulesetGenerator(modData, () =>
                    {
                        var rulesString             = Encoding.UTF8.GetString(Convert.FromBase64String(r.rules));
                        var rulesYaml               = new MiniYaml("", MiniYaml.FromString(rulesString)).ToDictionary();
                        var ruleDefinitions         = LoadRuleSection(rulesYaml, "Rules");
                        var weaponDefinitions       = LoadRuleSection(rulesYaml, "Weapons");
                        var voiceDefinitions        = LoadRuleSection(rulesYaml, "Voices");
                        var musicDefinitions        = LoadRuleSection(rulesYaml, "Music");
                        var notificationDefinitions = LoadRuleSection(rulesYaml, "Notifications");
                        var sequenceDefinitions     = LoadRuleSection(rulesYaml, "Sequences");
                        var rules = Ruleset.Load(modData, this, TileSet, ruleDefinitions, weaponDefinitions,
                                                 voiceDefinitions, notificationDefinitions, musicDefinitions, sequenceDefinitions);
                        var flagged = Ruleset.DefinesUnsafeCustomRules(modData, this, ruleDefinitions,
                                                                       weaponDefinitions, voiceDefinitions, notificationDefinitions, sequenceDefinitions);
                        return(Pair.New(rules, flagged));
                    });
                }
                catch (Exception e)
                {
                    Log.Write("debug", "Failed parsing mapserver response: {0}", e);
                }

                // Commit updated data before running the callbacks
                innerData = newData;

                if (innerData.Preview != null)
                {
                    cache.CacheMinimap(this);
                }

                if (parseMetadata != null)
                {
                    parseMetadata(this);
                }
            }

            // Update the status and class unconditionally
            innerData = newData;
        }
Пример #43
0
 public PairChanged(OperationId operationId, Pair pair)
 {
     OperationId = operationId;
     Pair        = pair;
 }
Пример #44
0
        public string recognizeNumber()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            try
            {
                string number = String.Empty;

                List <Limits> numbers = new List <Limits>();

                Pair boundariesX = new Pair(0, 0);
                Pair boundariesY = new Pair(0, 0);

                int i = 0;
                while (true)
                {
                    if (sw.ElapsedMilliseconds > 1000 * 60 * 10)
                    {
                        goto Exit;
                    }
                    try
                    {
                        if (numbers.Count > 0)
                        {
                            boundariesX = getBoundariesX(numbers[i - 1].x2);
                        }
                        else
                        {
                            boundariesX = getBoundariesX();
                        }

                        boundariesY = getBoundariesY(boundariesX);

                        numbers.Add(new Limits()
                        {
                            x1 = boundariesX.v1, x2 = boundariesX.v2, y1 = boundariesY.v1, y2 = boundariesY.v2
                        });

                        i++;
                        if (i > 6)
                        {
                            goto Exit;
                        }
                    }
                    //If there is no more data to look up, it breaks the while
                    catch
                    {
                        break;
                    }
                }

                #region Check Numbers
                sw = new Stopwatch();
                foreach (Limits val in numbers)
                {
                    if (sw.ElapsedMilliseconds > 1000 * 60 * 10)
                    {
                        goto Exit;
                    }

                    //A digit that has a width of less than one quarter of it's height is recognized as a one.
                    if ((val.x2 - val.x1) <= (int)(val.y2 - val.y1) / 4)
                    {
                        number += "1";
                    }
                    //To recognize a minus sign a method similar to recognizing the digit one is used. If a digit is less high than 1/3 of its width, it is considered a minus sign.
                    else if ((val.y2 - val.y1) <= (int)(val.x2 - val.x1) / 3)
                    {
                        number += "-";
                    }
                    //To recognize a decimal point, e.g. of a digital scale, the size of each digit (that was not recognized as a one already) is compared with the maximum digit width and height. If a digit is significantly smaller than that, it is assumed to be a decimal point. The decimal point or thousands separators count towards the number of digits to recognize.
                    else if ((val.y2 - val.y1) <= (val.x2 - val.x1))
                    {
                        number += ".";
                    }

                    /*
                     * Every digit found by the segmentation is classified as follows: A vertical scan is started in the center top pixel of the digit to find the three horizontal segments. Any foreground pixel in the upper third is counted as part of the top segment, those in the second third as part of the middle and those in the last third as part of the bottom segment.
                     * To examine the vertical segments two horizontal scanlines starting on the left margin of the digit are used. The first starts a quarter of the digit height from the top, the other from a quarter of the digit height from the bottom. Foreground pixels in the left resp. right half represent left resp. right segments.
                     * The recognized segments are then used to identify the displayed digit using a table lookup (implemented as a switch statement).
                     */
                    else
                    {
                        number += detectNumber(val);
                    }
                }
                #endregion

                sw.Stop();
                return(number);
            }
            catch
            {
                sw.Stop();
                return("unknown");
            }
Exit:
            sw.Stop();
            return("unknown");
        }
Пример #45
0
		/// <summary>Forgets previously encountered operators to save memory.</summary>
		public virtual void Reset() {
			this[OperatorShape.Suffix] = Pair.Create(PredefinedSuffixPrecedence.AsMutable(), P.Primary);
			this[OperatorShape.Prefix] = Pair.Create(PredefinedPrefixPrecedence.AsMutable(), P.Other);
			this[OperatorShape.Infix]  = Pair.Create(PredefinedInfixPrecedence .AsMutable(), P.Other);
			_suffixOpNames = null;
		}
Пример #46
0
 public override EnumDefined <BoxedVariable <Variable>, Type, BoxedExpression> HelperForAssignInParallel(
     EnumDefined <BoxedVariable <Variable>, Type, BoxedExpression> state, Pair <APC, APC> edge,
     Dictionary <BoxedVariable <Variable>, FList <BoxedVariable <Variable> > > refinedMap, Converter <BoxedVariable <Variable>, BoxedExpression> convert)
 {
     return(Rename(state, refinedMap));
 }
Пример #47
0
 public int CompareTo(Pair <T, U> a) => v1.CompareTo(a.v1) != 0 ? v1.CompareTo(a.v1) : v2.CompareTo(a.v2);
Пример #48
0
 string ActiveSettingsPath()
 {
     return(Path.Combine(Lib.CurrentDirectory, "Settings\\{0}({1})_Last.txt".Formater(Pair.Replace("/", ""), PairIndex)));
 }
Пример #49
0
 public Triple(A a, B b, C c)
 {
     fst = a; snd = new Pair <B, C>(b, c);
 }
Пример #50
0
 static Tuple <Group, Group> FindContainingGroups(Pair pair, List <Group> groups) => new Tuple <Group, Group>(FindContainingGroup(pair.First, groups), FindContainingGroup(pair.Second, groups));
        private static void createKey(CurveName curveName, CurveGroupName curveGroup, string curveTypeStr, string referenceStr, string currencyStr, IDictionary <CurveGroupName, IDictionary <Pair <RepoGroup, Currency>, CurveName> > repoGroups, IDictionary <CurveGroupName, IDictionary <Pair <LegalEntityGroup, Currency>, CurveName> > legalEntityGroups)
        {
            Currency currency = Currency.of(currencyStr);

            if (REPO.Equals(curveTypeStr.ToLower(Locale.ENGLISH), StringComparison.OrdinalIgnoreCase))
            {
                RepoGroup repoGroup = RepoGroup.of(referenceStr);
                repoGroups.computeIfAbsent(curveGroup, k => new LinkedHashMap <>()).put(Pair.of(repoGroup, currency), curveName);
            }
            else if (ISSUER.Equals(curveTypeStr.ToLower(Locale.ENGLISH), StringComparison.OrdinalIgnoreCase))
            {
                LegalEntityGroup legalEntiryGroup = LegalEntityGroup.of(referenceStr);
                legalEntityGroups.computeIfAbsent(curveGroup, k => new LinkedHashMap <>()).put(Pair.of(legalEntiryGroup, currency), curveName);
            }
            else
            {
                throw new System.ArgumentException(Messages.format("Unsupported curve type: {}", curveTypeStr));
            }
        }
Пример #52
0
        public void TestRootKeyDerivationV2()
        {
            byte[] rootKeySeed =
            {
                0x7b, 0xa6, 0xde, 0xbc, 0x2b,
                0xc1, 0xbb, 0xf9, 0x1a, 0xbb,
                0xc1, 0x36, 0x74, 0x04, 0x17,
                0x6c, 0xa6, 0x23, 0x09, 0x5b,
                0x7e, 0xc6, 0x6b, 0x45, 0xf6,
                0x02, 0xd9, 0x35, 0x38, 0x94,
                0x2d, 0xcc
            };

            byte[] alicePublic =
            {
                0x05, 0xee, 0x4f, 0xa6, 0xcd,
                0xc0, 0x30, 0xdf, 0x49, 0xec,
                0xd0, 0xba, 0x6c, 0xfc, 0xff,
                0xb2, 0x33, 0xd3, 0x65, 0xa2,
                0x7f, 0xad, 0xbe, 0xff, 0x77,
                0xe9, 0x63, 0xfc, 0xb1, 0x62,
                0x22, 0xe1, 0x3a
            };

            byte[] alicePrivate =
            {
                0x21, 0x68, 0x22, 0xec, 0x67,
                0xeb, 0x38, 0x04, 0x9e, 0xba,
                0xe7, 0xb9, 0x39, 0xba, 0xea,
                0xeb, 0xb1, 0x51, 0xbb, 0xb3,
                0x2d, 0xb8, 0x0f, 0xd3, 0x89,
                0x24, 0x5a, 0xc3, 0x7a, 0x94,
                0x8e, 0x50
            };

            byte[] bobPublic =
            {
                0x05, 0xab, 0xb8, 0xeb, 0x29,
                0xcc, 0x80, 0xb4, 0x71, 0x09,
                0xa2, 0x26, 0x5a, 0xbe, 0x97,
                0x98, 0x48, 0x54, 0x06, 0xe3,
                0x2d, 0xa2, 0x68, 0x93, 0x4a,
                0x95, 0x55, 0xe8, 0x47, 0x57,
                0x70, 0x8a, 0x30
            };

            byte[] nextRoot =
            {
                0xb1, 0x14, 0xf5, 0xde, 0x28,
                0x01, 0x19, 0x85, 0xe6, 0xeb,
                0xa2, 0x5d, 0x50, 0xe7, 0xec,
                0x41, 0xa9, 0xb0, 0x2f, 0x56,
                0x93, 0xc5, 0xc7, 0x88, 0xa6,
                0x3a, 0x06, 0xd2, 0x12, 0xa2,
                0xf7, 0x31
            };

            byte[] nextChain =
            {
                0x9d, 0x7d, 0x24, 0x69, 0xbc,
                0x9a, 0xe5, 0x3e, 0xe9, 0x80,
                0x5a, 0xa3, 0x26, 0x4d, 0x24,
                0x99, 0xa3, 0xac, 0xe8, 0x0f,
                0x4c, 0xca, 0xe2, 0xda, 0x13,
                0x43, 0x0c, 0x5c, 0x55, 0xb5,
                0xca, 0x5f
            };

            IEcPublicKey  alicePublicKey  = Curve.DecodePoint(alicePublic, 0);
            IEcPrivateKey alicePrivateKey = Curve.DecodePrivatePoint(alicePrivate);
            EcKeyPair     aliceKeyPair    = new EcKeyPair(alicePublicKey, alicePrivateKey);

            IEcPublicKey bobPublicKey = Curve.DecodePoint(bobPublic, 0);
            RootKey      rootKey      = new RootKey(Hkdf.CreateFor(2), rootKeySeed);

            Pair <RootKey, ChainKey> rootKeyChainKeyPair = rootKey.CreateChain(bobPublicKey, aliceKeyPair);
            RootKey  nextRootKey  = rootKeyChainKeyPair.First();
            ChainKey nextChainKey = rootKeyChainKeyPair.Second();

            CollectionAssert.AreEqual(rootKey.GetKeyBytes(), rootKeySeed);
            CollectionAssert.AreEqual(nextRootKey.GetKeyBytes(), nextRoot);
            CollectionAssert.AreEqual(nextChainKey.GetKey(), nextChain);
        }
Пример #53
0
        List <Pair> paired_children_; //!< All Children of this dockpanel paired up with a splitter.

        /**
         * @brief Runs after WPF initialization of the control is complete. This functions puts all childs in their respective tab controls and dockpanels.
         */
        public override void EndInit()
        {
            base.EndInit();
            for (int i = 0; i < Children.Count; ++i)
            {
                UIElement child = Children[i];
                uint      group = GetGroup(child);

                DynamicDockTab item = new DynamicDockTab();
                item.Header  = ((FrameworkElement)child).Name;
                item.Content = new DynamicDock();
                item.Content = child;

                if (group != uint.MaxValue)
                {
                    bool group_found = false;
                    foreach (Pair entry in paired_children_)
                    {
                        if (group == GetGroup(entry.element))
                        {
                            entry.element.Items.Add(item);
                            group_found = true;
                            break;
                        }
                    }

                    if (group_found == true)
                    {
                        continue;
                    }
                }

                Dock dockmode = GetDock(child);
                DynamicDockTabControl tabs = new DynamicDockTabControl(true);
                tabs.items_changed += TabItemsChanged;
                tabs.Items.Add(item);
                SetGroup(tabs, group);

                Pair pair = new Pair();
                pair.splitter = null;
                pair.element  = tabs;
                pair.dockmode = dockmode;
                pair.adorner  = new DynamicDockAdorner(pair.element);
                SetDock(pair.element, pair.dockmode);
                if (paired_children_.Count != 0)
                {
                    Pair back = paired_children_[paired_children_.Count - 1];
                    back.CreateSplitter();

                    back.splitter.resizing_started += (object sender, EventArgs args) =>
                                                      notify_subscribers_?.Invoke(
                        sender,
                        new NotificationEventArgs(
                            null,
                            (uint)Notifications.kLayoutChangeStarted,
                            id <DynamicDock> .type_id_)
                        );

                    back.splitter.resizing_stopped += (object sender, EventArgs args) =>
                                                      notify_subscribers_?.Invoke(
                        sender,
                        new NotificationEventArgs(
                            null,
                            (uint)Notifications.kLayoutChangeEnded,
                            id <DynamicDock> .type_id_)
                        );
                }
                paired_children_.Add(pair);
            }

            Children.Clear();
            foreach (Pair pair in paired_children_)
            {
                Children.Add(pair.element);

                if (pair.splitter != null)
                {
                    Children.Add(pair.splitter);
                }
            }
        }
Пример #54
0
 public static void Generate()
 {
     if (working)
     {
         Log.Error("Cannot call Generate() while already generating. Nested calls are not allowed.");
     }
     else
     {
         working = true;
         try
         {
             if (symbolStack.Empty)
             {
                 Log.Warning("Symbol stack is empty.");
             }
             else if (globalSettings.map == null)
             {
                 Log.Error("Called BaseGen.Resolve() with null map.");
             }
             else
             {
                 int num  = symbolStack.Count - 1;
                 int num2 = 0;
                 while (true)
                 {
                     if (symbolStack.Empty)
                     {
                         return;
                     }
                     num2++;
                     if (num2 > 100000)
                     {
                         break;
                     }
                     Pair <string, ResolveParams> toResolve = symbolStack.Pop();
                     if (symbolStack.Count == num)
                     {
                         GlobalSettings obj    = globalSettings;
                         ResolveParams  second = toResolve.Second;
                         obj.mainRect = second.rect;
                         num--;
                     }
                     try
                     {
                         Resolve(toResolve);
                     }
                     catch (Exception ex)
                     {
                         Log.Error("Error while resolving symbol \"" + toResolve.First + "\" with params=" + toResolve.Second + "\n\nException: " + ex);
                     }
                 }
                 Log.Error("Error in BaseGen: Too many iterations. Infinite loop?");
             }
         }
         catch (Exception arg)
         {
             Log.Error("Error in BaseGen: " + arg);
         }
         finally
         {
             working = false;
             symbolStack.Clear();
             globalSettings.Clear();
         }
     }
 }
Пример #55
0
        public static bool Generate(string str1, string str2, out string expression, out List <SequentialIntFunction> functions)
        {
            expression = string.Empty;
            functions  = new List <SequentialIntFunction>();
            List <Pair <Pair <int, string>, Pair <int, string> > > diffs = Diff.DiffString(str1, str2);

            if (diffs.Count > 0 /*&& Diff.IsDiffNumerical(diffs)*/)
            {
                //if (diffs[0].Second.Second == "2")
                //    System.Windows.Forms.MessageBox.Show("woot");
                Regex           regex = new Regex(@"[0-9]+");
                MatchCollection mcol1 = regex.Matches(str1);
                MatchCollection mcol2 = regex.Matches(str2);

                if (mcol1.Count != mcol2.Count || mcol1.Count == 0)
                {
                    return(false);
                }

                expression = str2;
                int    val1, val2, padding, pos1, pos2;
                string f_name = string.Empty, to_replace = string.Empty;

                List <int>               positions_to_replace = new List <int>();
                Dictionary <int, int>    fpositions_to_replace = new Dictionary <int, int>();
                Dictionary <int, string> tokens_to_replace = new Dictionary <int, string>();
                Dictionary <int, SequentialIntFunction> funcs_to_add = new Dictionary <int, SequentialIntFunction>();

                for (int i = 1; i <= diffs.Count; i++)
                {
                    Pair <Pair <int, string>, Pair <int, string> > diff = diffs[i - 1];
                    f_name = "§" + i.ToString();
                    //to_replace = diff.Second.Second;
                    //val1 = Int32.Parse(diff.First.Second);
                    //pos1 = diff.First.First;
                    //val2 = Int32.Parse(diff.Second.Second);
                    //pos2 = diff.Second.First;
                    //padding = 0;
                    val1       = val2 = pos1 = pos2 = padding = 0;
                    to_replace = string.Empty;
                    int offset = 0;
                    for (int n = 0; n < mcol2.Count; n++)
                    {
                        Match match1 = mcol1[n];
                        Match match2 = mcol2[n];
                        padding = match2.Length;
                        if (diff.Second.First >= match2.Index && diff.Second.First <= (match2.Index + match2.Length - 1) && diff.Second.First + diff.Second.Second.Length - 1 <= match2.Index + match2.Length - 1 &&
                            diff.First.First >= match1.Index && diff.First.First <= (match1.Index + match1.Length - 1) && diff.First.First + diff.First.Second.Length - 1 <= match1.Index + match1.Length - 1)
                        {
                            if (match1.Value.Length > 9)
                            {
                                offset = match1.Value.Length - 9;
                            }
                            else
                            {
                                offset = 0;
                            }
                            val1 = Int32.Parse(match1.Value.Substring(offset));
                            pos1 = match1.Index + offset;
                            if (match2.Value.Length > 9)
                            {
                                offset = match2.Value.Length - 9;
                            }
                            else
                            {
                                offset = 0;
                            }
                            val2       = Int32.Parse(match2.Value.Substring(offset));
                            pos2       = match2.Index + offset;
                            to_replace = match2.Value.Substring(offset);
                            break;
                        }
                        else
                        {
                            int result;
                            if (!Int32.TryParse(diff.First.Second, out result) && !Int32.TryParse(diff.Second.Second, out result))
                            {
                                return(false);
                            }
                        }
                    }
                    if (pos1 == pos2 && to_replace != string.Empty)
                    {
                        //expression = expression.Replace(to_replace, f_name);
                        SequentialIntFunction func = new SequentialIntFunction(f_name, val2, val2 - val1, padding, 0, 2);
                        //if (!functions.Contains(func))
                        //    functions.Add(func);
                        if (!positions_to_replace.Contains(pos2))
                        {
                            positions_to_replace.Add(pos2);
                            fpositions_to_replace.Add(pos2, pos2 + to_replace.Length - 1);
                            tokens_to_replace.Add(pos2, f_name);
                            funcs_to_add.Add(pos2, func);
                        }
                    }
                }

                // add functions by its correct order
                positions_to_replace.Sort();
                foreach (int pos in positions_to_replace)
                {
                    functions.Add(funcs_to_add[pos]);
                }
                // replace text beginning from the end of the string
                positions_to_replace.Reverse();
                foreach (int pos in positions_to_replace)
                {
                    expression = SystemCore.SystemAbstraction.StringUtilities.StringUtility.ReplaceBetweenPositions(expression, pos, fpositions_to_replace[pos], tokens_to_replace[pos]);
                }
            }
            if (functions.Count > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #56
0
        /// <summary>
        /// 成比例的缩放目标大小为指定大小
        /// </summary>
        /// <param name="mode"> </param>
        /// <param name="sizeResult"> </param>
        /// <param name="scaleResult"> </param>
        /// <param name="powerOfTwo"> </param>
        /// <param name="srcWidth"> </param>
        /// <param name="srcHeight"> </param>
        /// <param name="tarWidth"> </param>
        /// <param name="tarHeight">
        /// @return </param>
        public virtual Pair <Vector2f, Vector2f> ScaledSize(Mode mode, Vector2f sizeResult, Vector2f scaleResult, bool powerOfTwo, float srcWidth, float srcHeight, float tarWidth, float tarHeight)
        {
            if (mode == default)
            {
                mode = Mode.NONE;
            }

            float targetRatio = this.factor;
            float sourceRatio = this.factor;
            float scaleValue  = this.factor;

            switch (mode)
            {
            case Mode.FILL:
                targetRatio = tarHeight / tarWidth;
                sourceRatio = srcHeight / srcWidth;
                scaleValue  = targetRatio < sourceRatio ? tarWidth / srcWidth : tarHeight / srcHeight;
                if (powerOfTwo)
                {
                    scaleValue = MathUtils.PreviousPowerOfTwo(MathUtils.Ceil(scaleValue));
                }
                sizeResult.Set(srcWidth * scaleValue, srcHeight * scaleValue);
                scaleResult.Set(scaleValue, scaleValue);
                break;

            case Mode.FILL_X:
                scaleValue = tarWidth / srcWidth;
                if (powerOfTwo)
                {
                    scaleValue = MathUtils.PreviousPowerOfTwo(MathUtils.Ceil(scaleValue));
                }
                sizeResult.Set(srcWidth * scaleValue, srcHeight * scaleValue);
                scaleResult.Set(scaleValue, scaleValue);
                break;

            case Mode.FILL_Y:
                scaleValue = tarHeight / srcHeight;
                if (powerOfTwo)
                {
                    scaleValue = MathUtils.PreviousPowerOfTwo(MathUtils.Ceil(scaleValue));
                }
                sizeResult.Set(srcWidth * scaleValue, srcHeight * scaleValue);
                scaleResult.Set(scaleValue, scaleValue);
                break;

            case Mode.FIT:
                targetRatio = tarHeight / tarWidth;
                sourceRatio = srcHeight / srcWidth;
                scaleValue  = targetRatio > sourceRatio ? tarWidth / srcWidth : tarHeight / srcHeight;
                if (powerOfTwo)
                {
                    scaleValue = MathUtils.PreviousPowerOfTwo(MathUtils.Floor(scaleValue));
                }
                sizeResult.Set(srcWidth * scaleValue, srcHeight * scaleValue);
                scaleResult.Set(scaleValue, scaleValue);
                break;

            case Mode.STRETCH:
                float scaleX = tarWidth / srcWidth;
                float scaleY = tarHeight / srcHeight;
                if (powerOfTwo)
                {
                    scaleX = MathUtils.PreviousPowerOfTwo(MathUtils.Ceil(scaleX));
                    scaleY = MathUtils.PreviousPowerOfTwo(MathUtils.Ceil(scaleY));
                }
                sizeResult.Set(tarWidth, tarHeight);
                scaleResult.Set(scaleX, scaleY);
                break;

            case Mode.NONE:
            default:
                sizeResult.Set(srcWidth, srcHeight);
                scaleResult.Set(1f);
                break;
            }
            return(Pair <Vector2f, Vector2f> .Get(sizeResult, scaleResult));
        }
Пример #57
0
        // Since static method calls such as "Class.method('a')" and mapped properties "Stream.property('key')"
        // look the same, however as the validation could not resolve "Stream.property('key')" before calling this method,
        // this method tries to resolve the mapped property as a static method.
        // Assumes that this is an ExprIdentNode.
        private static ExprNode ResolveStaticMethodOrField(
            ExprIdentNode identNode,
            ExprValidationException propertyException,
            ExprValidationContext validationContext)
        {
            // Reconstruct the original string
            StringBuilder mappedProperty = new StringBuilder(identNode.UnresolvedPropertyName);
            if (identNode.StreamOrPropertyName != null) {
                mappedProperty.Insert(0, identNode.StreamOrPropertyName + '.');
            }

            // Parse the mapped property format into a class name, method and single string parameter
            MappedPropertyParseResult parse = ParseMappedProperty(mappedProperty.ToString());
            if (parse == null) {
                ExprConstantNode constNode = ResolveIdentAsEnumConst(
                    mappedProperty.ToString(),
                    validationContext.ImportService);
                if (constNode == null) {
                    throw propertyException;
                }
                else {
                    return constNode;
                }
            }

            // If there is a class name, assume a static method is possible.
            if (parse.ClassName != null) {
                IList<ExprNode> parameters =
                    Collections.SingletonList((ExprNode) new ExprConstantNodeImpl(parse.ArgString));
                IList<ExprChainedSpec> chain = new List<ExprChainedSpec>();
                chain.Add(new ExprChainedSpec(parse.ClassName, Collections.GetEmptyList<ExprNode>(), false));
                chain.Add(new ExprChainedSpec(parse.MethodName, parameters, false));
                ConfigurationCompilerExpression exprConfig =
                    validationContext.StatementCompileTimeService.Configuration.Compiler.Expression;
                ExprNode result = new ExprDotNodeImpl(chain, exprConfig.IsDuckTyping, exprConfig.IsUdfCache);

                // Validate
                try {
                    result.Validate(validationContext);
                }
                catch (ExprValidationException e) {
                    throw new ExprValidationException(
                        $"Failed to resolve enumeration method, date-time method or mapped property '{mappedProperty}': {e.Message}",
                        e);
                }

                return result;
            }

            // There is no class name, try a single-row function
            string functionName = parse.MethodName;
            try {
                Pair<Type, ImportSingleRowDesc> classMethodPair =
                    validationContext.ImportService.ResolveSingleRow(functionName);
                IList<ExprNode> parameters =
                    Collections.SingletonList((ExprNode) new ExprConstantNodeImpl(parse.ArgString));
                IList<ExprChainedSpec> chain = Collections.SingletonList(
                    new ExprChainedSpec(classMethodPair.Second.MethodName, parameters, false));
                ExprNode result = new ExprPlugInSingleRowNode(
                    functionName,
                    classMethodPair.First,
                    chain,
                    classMethodPair.Second);

                // Validate
                try {
                    result.Validate(validationContext);
                }
                catch (EPException) {
                    throw;
                }
                catch (Exception ex) {
                    throw new ExprValidationException(
                        "Plug-in aggregation function '" + parse.MethodName + "' failed validation: " + ex.Message);
                }

                return result;
            }
            catch (ImportUndefinedException) {
                // Not an single-row function
            }
            catch (ImportException e) {
                throw new IllegalStateException("Error resolving single-row function: " + e.Message, e);
            }

            // Try an aggregation function factory
            try {
                AggregationFunctionForge aggregationForge =
                    validationContext.ImportService.ResolveAggregationFunction(parse.MethodName);
                ExprNode result = new ExprPlugInAggNode(false, aggregationForge, parse.MethodName);
                result.AddChildNode(new ExprConstantNodeImpl(parse.ArgString));

                // Validate
                try {
                    result.Validate(validationContext);
                }
                catch (EPException) {
                    throw;
                }
                catch (Exception e) {
                    throw new ExprValidationException(
                        "Plug-in aggregation function '" + parse.MethodName + "' failed validation: " + e.Message);
                }

                return result;
            }
            catch (ImportUndefinedException) {
                // Not an aggregation function
            }
            catch (ImportException e) {
                throw new IllegalStateException("Error resolving aggregation: " + e.Message, e);
            }

            // absolutely cannot be resolved
            throw propertyException;
        }
        private Object CreateFactory(ObjectSpec spec, PluggableObjectType type)
        {
            if (Log.IsDebugEnabled)
            {
                Log.Debug(".create Creating factory, spec=" + spec);
            }

            // Find the factory class for this pattern object
            Type factoryClass = null;

            IDictionary <String, Pair <Type, PluggableObjectEntry> > namespaceMap = _patternObjects.Pluggables.Get(spec.ObjectNamespace);

            if (namespaceMap != null)
            {
                Pair <Type, PluggableObjectEntry> pair = namespaceMap.Get(spec.ObjectName);
                if (pair != null)
                {
                    if (pair.Second.PluggableType == type)
                    {
                        factoryClass = pair.First;
                    }
                    else
                    {
                        // invalid type: expecting observer, got guard
                        if (type == PluggableObjectType.PATTERN_GUARD)
                        {
                            throw new PatternObjectException("Pattern observer function '" + spec.ObjectName + "' cannot be used as a pattern guard");
                        }
                        else
                        {
                            throw new PatternObjectException("Pattern guard function '" + spec.ObjectName + "' cannot be used as a pattern observer");
                        }
                    }
                }
            }

            if (factoryClass == null)
            {
                if (type == PluggableObjectType.PATTERN_GUARD)
                {
                    String message = "Pattern guard name '" + spec.ObjectName + "' is not a known pattern object name";
                    throw new PatternObjectException(message);
                }
                else if (type == PluggableObjectType.PATTERN_OBSERVER)
                {
                    String message = "Pattern observer name '" + spec.ObjectName + "' is not a known pattern object name";
                    throw new PatternObjectException(message);
                }
                else
                {
                    throw new PatternObjectException("Pattern object type '" + type + "' not known");
                }
            }

            Object result;

            try
            {
                result = Activator.CreateInstance(factoryClass);
            }
            catch (TypeInstantiationException ex)
            {
                String message = "Error invoking pattern object factory constructor for object '" + spec.ObjectName;
                message += "' using Activator.CreateInstance";
                throw new PatternObjectException(message, ex);
            }
            catch (TargetInvocationException ex)
            {
                String message = "Error invoking pattern object factory constructor for object '" + spec.ObjectName;
                message += "' using Activator.CreateInstance";
                throw new PatternObjectException(message, ex);
            }
            catch (MethodAccessException ex)
            {
                String message = "Error invoking pattern object factory constructor for object '" + spec.ObjectName;
                message += "', no invocation access for Activator.CreateInstance";
                throw new PatternObjectException(message, ex);
            }
            catch (MemberAccessException ex)
            {
                String message = "Error invoking pattern object factory constructor for object '" + spec.ObjectName;
                message += "', no invocation access for Activator.CreateInstance";
                throw new PatternObjectException(message, ex);
            }

            return(result);
        }
Пример #59
0
        /// <summary>
        /// Tries to resolve a pair as a choice.
        /// </summary>
        /// <param name="pair">Pair being resolved.</param>
        /// <param name="entities">Entities of the pair.</param>
        /// <param name="implementationPair">If pair is an <see cref="Alias"/> then this parameter should get be an <see cref="DOM.AliasDefinition"/>.</param>
        /// <returns>True if pair is choice.</returns>
        protected bool EnterChoiceContainer(Pair pair, PairCollection <Entity> entities, Pair implementationPair = null)
        {
            if (implementationPair == null)
            {
                implementationPair = pair;
            }
            if (implementationPair.Assignment != AssignmentEnum.CC && implementationPair.Assignment != AssignmentEnum.ECC ||
                entities == null || entities.Count == 0)
            {
                return(false);
            }

            var choice     = ChoiceStack.Peek();
            var choiceInfo = JsonGenerator.FindChoiceInfo(choice, pair);

            if (choice.ChoiceNode != pair)
            {
                ChoiceStack.Push(choiceInfo);
            }
            ChoiceStack.Push(choiceInfo.Children[0]);
            if (((Element)choiceInfo.Children[0].ChoiceNode).Entities.Count > 0)
            {
                Visit(((Element)choiceInfo.Children[0].ChoiceNode).Entities);
            }

            ChoiceStack.Pop();
            if (choice.ChoiceNode != pair)
            {
                ChoiceStack.Pop();
            }
            return(true);
        }
Пример #60
0
        public static ICollection<EventBean> Snapshot(
            QueryGraph filterQueryGraph,
            Attribute[] annotations,
            VirtualDWView virtualDataWindow,
            EventTableIndexRepository indexRepository,
            string objectName,
            AgentInstanceContext agentInstanceContext)
        {
            var queryGraphValue = filterQueryGraph == null
                ? null
                : filterQueryGraph.GetGraphValue(QueryGraphForge.SELF_STREAM, 0);
            if (queryGraphValue == null || queryGraphValue.Items.IsEmpty()) {
                if (virtualDataWindow != null) {
                    Pair<IndexMultiKey, EventTable> pair = VirtualDWQueryPlanUtil.GetFireAndForgetDesc(
                        virtualDataWindow.EventType,
                        new EmptySet<string>(),
                        new EmptySet<string>());
                    return virtualDataWindow.GetFireAndForgetData(
                        pair.Second,
                        CollectionUtil.OBJECTARRAY_EMPTY,
                        new RangeIndexLookupValue[0],
                        annotations);
                }

                return null;
            }

            // determine custom index
            var customResult = SnapshotCustomIndex(
                queryGraphValue,
                indexRepository,
                annotations,
                agentInstanceContext,
                objectName);
            if (customResult != null) {
                return customResult.Value;
            }

            // determine lookup based on hash-keys and ranges
            var keysAvailable = queryGraphValue.HashKeyProps;
            ISet<string> keyNamesAvailable = keysAvailable.Indexed.Length == 0
                ? (ISet<string>) new EmptySet<string>()
                : (ISet<string>) new HashSet<string>(keysAvailable.Indexed);
            var rangesAvailable = queryGraphValue.RangeProps;
            ISet<string> rangeNamesAvailable = rangesAvailable.Indexed.Length == 0
                ? (ISet<string>) new EmptySet<string>()
                : (ISet<string>) new HashSet<string>(rangesAvailable.Indexed);
            Pair<IndexMultiKey, EventTableAndNamePair> tablePair;

            // find index that matches the needs
            tablePair = FindIndex(
                keyNamesAvailable,
                rangeNamesAvailable,
                indexRepository,
                virtualDataWindow,
                annotations);

            // regular index lookup
            if (tablePair != null) {
                return SnapshotIndex(
                    keysAvailable,
                    rangesAvailable,
                    tablePair,
                    virtualDataWindow,
                    annotations,
                    agentInstanceContext,
                    objectName);
            }

            // in-keyword lookup
            var inkwResult = SnapshotInKeyword(
                queryGraphValue,
                indexRepository,
                virtualDataWindow,
                annotations,
                agentInstanceContext,
                objectName);
            if (inkwResult != null) {
                return inkwResult.Value;
            }

            QueryPlanReportTableScan(annotations, agentInstanceContext, objectName);
            return null;
        }