示例#1
0
        public void Ask_Adds1Order_OnExistingLimit_With1Order()
        {
            // Arrange.
            var existingOrder = new Order {
                Shares = 100, Subscription = new Subscription {
                    Owned = 100, UserId = _userId2
                }
            };

            var existingLimit = Limits.First();

            existingLimit.AskHead     = existingOrder;
            existingOrder.ParentLimit = existingLimit;

            Limits.Add(existingLimit);
            Orders.Add(existingOrder.Id, existingOrder);
            Subscriptions.Add(existingOrder.Subscription.UserId, existingOrder.Subscription);
            Subscriptions.Add(_userId1, new Subscription {
                Owned = 5, UserId = _userId1
            });

            // Act.
            Ask(_userId1, 1, 5);

            // Assert.
            var existingOrder2 = new Order {
                Shares = 100, Subscription = new Subscription {
                    Owned = 100, UserId = _userId2
                }
            };

            var existingLimit2 = new Limit {
                Price = 1 * ScaleFactor
            };

            existingOrder2.ParentLimit = existingLimit2;

            var order = new Order
            {
                Id           = 1,
                Next         = existingOrder2,
                Shares       = 5,
                Subscription = new Subscription
                {
                    Owned  = 5,
                    UserId = _userId1
                }
            };

            existingLimit2.AskHead = order;
            existingOrder2.Prev    = order;
            order.ParentLimit      = existingLimit2;

            Assert.AreEqual(1, Limits.Count);
            Assert.AreEqual(2, Orders.Count);
            Assert.AreEqual(2, Subscriptions.Count);
            CollectionAssert.AreEqual(new Limit[] { existingLimit2 }, Limits, _limitTestComparer);
            CollectionAssert.AreEqual(new Order[] { existingOrder2, order }, (ICollection)Orders.Values, _orderTestComparer);
            CollectionAssert.AreEqual(new Subscription[] { existingOrder2.Subscription, order.Subscription }, (ICollection)Subscriptions.Values, _subscriptionTestComparer);
        }
示例#2
0
        //新增或修改角色
        public string EditOrUpdateRole(Role role)
        {
            var loginInfo = LoginFac.Admin.GetLoginInfo();

            role.AddTime = DateTime.Now;
            role.AdminId = loginInfo.UserId;
            if (role.RoleId != 0)
            {
                if (Limits.Contains(2) && ((role.OrganId == 0 && loginInfo.RoleId == CustomConfig.SuperRoleId) || role.OrganId.ToString().StartsWith(loginInfo.OrganId.ToString())))
                {
                    DbOp.Update(role);
                    return("True");
                }
                else
                {
                    return("你没有权限进行修改");
                }
            }
            else
            {
                if (Limits.Contains(3) && ((role.OrganId == 0 && loginInfo.RoleId == CustomConfig.SuperRoleId) || role.OrganId.ToString().StartsWith(loginInfo.OrganId.ToString())))
                {
                    DbOp.Add(role);
                    return("True");
                }
                else
                {
                    return("你没有权限新增数据");
                }
            }
        }
示例#3
0
        /// <summary>
        /// Moves robot to specified position (sets target position).
        /// </summary>
        /// <param name="targetPosition">target position</param>
        /// <param name="targetVelocity">target velocity (velocity after targetDuration)</param>
        /// <param name="targetDuration">desired movement duration in seconds</param>
        public void MoveTo(RobotVector targetPosition, RobotVector targetVelocity, double targetDuration)
        {
            if (!isInitialized)
            {
                throw new InvalidOperationException("Robot is not initialized");
            }

            if (!Limits.CheckPosition(targetPosition))
            {
                throw new ArgumentException("Target position is outside the available workspace:" +
                                            $"{Environment.NewLine}{targetPosition}");
            }

            if (!Limits.CheckVelocity(targetVelocity))
            {
                throw new ArgumentException("target velocity exceeding max value " +
                                            $"({Limits.MaxVelocity.XYZ} [mm/s], {Limits.MaxVelocity.ABC} [deg/s]):" +
                                            $"{Environment.NewLine}{targetVelocity}");
            }

            lock (forceMoveSyncLock) {
                if (forceMoveMode)
                {
                    return;
                }
            }

            generator.SetTargetPosition(targetPosition, targetVelocity, targetDuration);
        }
示例#4
0
 //新增或修改权限
 public JsonResult EditOrUpdateLimit(Limit limitInfo)
 {
     if (DbOp.KeyExits(limitInfo.Code, limitInfo.ModuleId, limitInfo.LimitId))
     {
         return(Json("权限编码已经存在,请重新设置"));
     }
     if (limitInfo.LimitId != 0)
     {
         if (Limits.Contains(2))
         {
             DbOp.Update(limitInfo);
         }
         else
         {
             return(Json("你没有权限进行修改"));
         }
     }
     else
     {
         if (Limits.Contains(1))
         {
             DbOp.Add(limitInfo);
         }
         else
         {
             return(Json("你没有权限新增数据"));
         }
     }
     return(Json(true));
 }
示例#5
0
        public static async Task <List <Movie> > GetMovies(Limits limits = null, Filter filter = null, Sort sort = null)
        {
            JObject parameters = new JObject(
                new JProperty("properties",
                              new JArray("title", "genre", "year", "rating", "director", "trailer", "tagline", "plot", "plotoutline", "originaltitle", "lastplayed", "playcount", "writer", "studio", "mpaa", "cast", "country", "imdbnumber", "runtime", "set", "showlink", "streamdetails", "top250", "votes", "fanart", "thumbnail", "file", "sorttitle", "resume", "setid", "dateadded", "tag", "art")
                              ));

            if (limits != null)
            {
                parameters["limits"] = JObject.FromObject(limits);
            }

            if (filter != null)
            {
                parameters["filter"] = JObject.FromObject(filter);
            }

            if (sort != null)
            {
                parameters["sort"] = JObject.FromObject(sort);
            }


            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("VideoLibrary.GetMovies", parameters);

            JArray movieListObject = (JArray)responseObject["result"]["movies"];

            List <Movie> listToReturn = movieListObject != null?movieListObject.ToObject <List <Movie> >() : new List <Movie>();

            return(listToReturn);
        }
示例#6
0
        /// <summary>
        /// Receives data (IPOC, cartesian and axis position) from the robot asynchronously,
        /// raises <see cref="KUKARobot.FrameRecived">FrameReceived</see> event
        /// </summary>
        private async Task ReceiveDataAsync()
        {
            InputFrame receivedFrame = await rsiAdapter.ReceiveDataAsync();

            RobotVector correction = receivedFrame.Position - position;

            if (!Limits.CheckCorrection(correction))
            {
                Uninitialize();
                throw new InvalidOperationException("Correction limit has been exceeded:" +
                                                    $"{Environment.NewLine}{correction}");
            }

            if (!Limits.CheckAxisPosition(receivedFrame.AxisPosition))
            {
                Uninitialize();
                throw new InvalidOperationException("Axis position limit has been exceeded:" +
                                                    $"{Environment.NewLine}{receivedFrame.AxisPosition}");
            }

            if (!Limits.CheckPosition(receivedFrame.Position))
            {
                Uninitialize();
                throw new InvalidOperationException("Available workspace limit has been exceeded:" +
                                                    $"{Environment.NewLine}{receivedFrame.Position}");
            }

            lock (receivedDataSyncLock) {
                IPOC         = receivedFrame.IPOC;
                position     = receivedFrame.Position;
                axisPosition = receivedFrame.AxisPosition;
            }

            FrameReceived?.Invoke(receivedFrame);
        }
示例#7
0
        private void UpdateInfo()
        {
            Dictionary <string, int> counts = new Dictionary <string, int>();

            foreach (TreeNode fileNode in this.AssetTree.Nodes)
            {
                foreach (TreeNode typeNode in fileNode.Nodes)
                {
                    AddCount(counts, typeNode.Name, typeNode.Nodes.Count);
                }
            }

            counts.Sort();

            StringBuilder text = new StringBuilder("Total stats" + Environment.NewLine);

            string curLine;

            foreach (string key in counts.Keys)
            {
                curLine = key + ": " + counts[key];
                if (Enum.IsDefined(typeof(Limits), key))
                {
                    Limits limit = (Limits)Enum.Parse(typeof(Limits), key);
                    curLine += "/" + (int)limit;
                }
                text.Append(curLine + Environment.NewLine);
            }

            text.Append(Environment.NewLine);
            text.Append("Overwrites: " + this.totalOverwrites);

            this.TotalInfoTextBox.Text = text.ToString();
        }
示例#8
0
        public static async Task <List <Episode> > GetRecentlyAddedEpisodes(Limits limits = null, JObject sort = null)
        {
            JObject parameters = new JObject(
                new JProperty("properties",
                              new JArray("title", "plot", "votes", "rating", "writer", "firstaired", "playcount", "runtime", "director", "productioncode", "season", "episode", "originaltitle", "showtitle", "streamdetails", "lastplayed", "fanart", "thumbnail", "file", "resume", "tvshowid", "dateadded", "uniqueid", "art")
                              ));

            if (limits != null)
            {
                parameters["limits"] = new JObject(
                    new JProperty("start", limits.Start),
                    new JProperty("end", limits.End));
            }

            if (sort != null)
            {
                parameters["sort"] = sort;
            }

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("VideoLibrary.GetRecentlyAddedEpisodes", parameters);

            JArray         episodeListObject = (JArray)responseObject["result"]["episodes"];
            List <Episode> listToReturn      = episodeListObject != null?episodeListObject.ToObject <List <Episode> >() : new List <Episode>();

            return(listToReturn);
        }
示例#9
0
        protected override YAMLMappingNode ExportYAMLRoot(IExportContainer container)
        {
            YAMLMappingNode node = base.ExportYAMLRoot(container);

            node.Add(ConnectedBodyName, ConnectedBody.ExportYAML(container));
            node.Add(AnchorName, Anchor.ExportYAML(container));
            node.Add(AxisName, Axis.ExportYAML(container));
            node.Add(AutoConfigureConnectedAnchorName, AutoConfigureConnectedAnchor);
            node.Add(ConnectedAnchorName, ConnectedAnchor.ExportYAML(container));

            node.Add(UseSpringName, UseSpring);
            node.Add(SpringName, Spring.ExportYAML(container));
            node.Add(UseMotorName, UseMotor);
            node.Add(MotorName, Motor.ExportYAML(container));
            node.Add(UseLimitsName, UseLimits);
            node.Add(LimitsName, Limits.ExportYAML(container));

            node.Add(BreakForceName, BreakForce);
            node.Add(BreakTorqueName, BreakTorque);
            node.Add(EnableCollisionName, EnableCollision);
            node.Add(EnablePreprocessingName, EnablePreprocessing);
            node.Add(MassScaleName, MassScale);
            node.Add(ConnectedMassScaleName, ConnectedMassScale);
            return(node);
        }
示例#10
0
 ////新增或修改数据
 public string EditOrUpdateOption(ConfigOption option)
 {
     if (option.OptionId != 0)
     {
         if (Limits.Contains(2))
         {
             DbOp.Update(option);
         }
         else
         {
             return("你没有权限进行修改");
         }
     }
     else
     {
         if (Limits.Contains(3))
         {
             DbOp.Add(option);
         }
         else
         {
             return("你没有权限新增数据");
         }
     }
     return("True");
 }
示例#11
0
 //新增或修改数据
 public string EditOrUpdateConf(ConfigInfo conf)
 {
     if (conf.ConfigId != 0)
     {
         if (Limits.Contains(2))
         {
             DbOp.Update(conf);
         }
         else
         {
             return("你没有权限进行修改");
         }
     }
     else
     {
         if (Limits.Contains(3))
         {
             DbOp.Add(conf);
         }
         else
         {
             return("你没有权限新增数据");
         }
     }
     return("True");
 }
示例#12
0
        public static async Task<List<TVShow>> GetTVShows(Limits limits = null, Filter filter = null, Sort sort = null)
        {
            JObject parameters = new JObject(
                                new JProperty("properties",
                                    new JArray("title", "genre", "year", "rating", "plot", "studio", "mpaa", "cast", "playcount", "episode", "imdbnumber", "premiered", "votes", "lastplayed", "fanart", "thumbnail", "file", "originaltitle", "sorttitle", "episodeguide", "season", "watchedepisodes", "dateadded", "tag", "art")
                                    ));

            if (limits != null)
            {
                parameters["limits"] = JObject.FromObject(limits);
            }

            if (filter != null)
            {
                parameters["filter"] = JObject.FromObject(filter);
            }

            if (sort != null)
            {
                parameters["sort"] = JObject.FromObject(sort);
            }

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("VideoLibrary.GetTVShows", parameters);
            JArray tvShowsListObject = (JArray)responseObject["result"]["tvshows"];
            
            List<TVShow> listToReturn = tvShowsListObject != null ? tvShowsListObject.ToObject<List<TVShow>>() : new List<TVShow>();
            return listToReturn;
        }
示例#13
0
        public static async Task<List<Song>> GetSongs(Filter filter = null, Limits limits = null, Sort sort = null)
        {
            JObject parameters = new JObject(
                                     new JProperty("properties",
                                         new JArray("album", "albumartist", "albumartistid", "albumid", "comment", "disc", "duration", "file", "lastplayed", "lyrics", "musicbrainzartistid", "musicbrainztrackid", "playcount", "track"))
                                             );

            if (limits != null)
            {
                parameters["limits"] = JObject.FromObject(limits);
            }

            if (filter != null)
            {
                parameters["filter"] = JObject.FromObject(filter);
            }

            if (sort != null)
            {
                parameters["sort"] = JObject.FromObject(sort);
            }

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("AudioLibrary.GetSongs", parameters);

            JArray songListObject = (JArray)responseObject["result"]["songs"];
            List<Song> listToReturn = songListObject != null ? songListObject.ToObject<List<Song>>() : new List<Song>();
            return listToReturn;
        }
示例#14
0
        /// <summary>
        /// Limits the bandwith used globally by the subsequent stages in the owin pipeline.
        /// </summary>
        /// <param name="app">The IAppBuilder instance.</param>
        /// <param name="getMaxBytesPerSecond">A delegate to retrieve the maximum number of bytes per second to be transferred.
        /// Allows you to supply different values at runtime. Use 0 or a negative number to specify infinite bandwidth.</param>
        /// <returns>The app instance.</returns>
        public static IAppBuilder MaxBandwidthGlobal(this IAppBuilder app, Func <int> getMaxBytesPerSecond)
        {
            app.MustNotNull("app");

            app.Use(Limits.MaxBandwidthGlobal(getMaxBytesPerSecond));
            return(app);
        }
示例#15
0
        public static void Start()
        {
            // Location of your APEX and C# Files that we will be converting
            DirectoryInfo apexLocation   = new DirectoryInfo(@"/ApexSharp/SalesForce/src/classes/");
            DirectoryInfo cSharpLocation = new DirectoryInfo(@"/ApexSharp/Demo/CSharpClasses/");

            // Start Logging
            Setup.StartLogging();

            // Always Initialize your settings when ever you are connecting to SF
            Setup.Init();

            // Keep Track of the API Limits
            Console.WriteLine($"Api Request Remaining {Limits.GetApiLimits().DailyApiRequests.Remaining}");

            // Create Offline classes for SObjects
            CreateOffLineClasses();


            CodeConverter.ConvertToCSharp(apexLocation, cSharpLocation, "Demo.CSharpClasses");

            //DmlTest.UpsertTest();


            CodeConverter.ConvertToApex(cSharpLocation, apexLocation, 40);

            // Keep Track of the API Limits
            Console.WriteLine($"Api Request Remaining {Limits.GetApiLimits().DailyApiRequests.Remaining}");

            // Flush and Close
            Setup.StopLogging();

            Console.WriteLine("Done, Press Any Key To Exit");
            Console.ReadKey();
        }
        private async void SaveButtonClicked(object sender, EventArgs e)
        {
            List <Limits> list = new List <Limits>();

            foreach (LimitsItem item in viewModel.DataSource)
            {
                Limits limit = new Limits();
                {
                    if (item.LimitsName != null && item.CurrentFuelType != null && item.CurrentlimitType != null)
                    {
                        limit.FuelType   = item.LimitsName;
                        limit.FuelAmount = item.FuelAmount;
                        limit.FuelUnits  = item.CurrentFuelType;
                        limit.LimitType  = item.CurrentlimitType;
                        list.Add(limit);
                    }
                };
            }
            var checkLimitsPopup = new CardLimitsPopup(list, false, false)
            {
                OkClicked = () => {
                    //TODO проверить лимиты на валидность и отправить запрос на сервер с лимитами
                    SendCardLimits cardLimits = new SendCardLimits();
                    Dictionary <string, List <Limits> > limitsDic = new Dictionary <string, List <Limits> >();
                    limitsDic.Add(Number, list);
                    cardLimits.Limits            = limitsDic;
                    cardLimits.Date              = DateTime.Now.ToString("yyyy-MM-dd");
                    cardLimits.Country           = _Country;
                    cardLimits.RefuelingStations = Stations;
                    viewModel.SendCardLimits(cardLimits);
                }
            };
            await PopupNavigation.Instance.PushAsync(checkLimitsPopup);
        }
示例#17
0
        public override string ToString()
        {
            if (!IsDirty && _toString != null)
            {
                return(_toString);
            }

            var descriptors = new HashSet <string>
            {
                Limits.ToString(),
                GetRangesDescriptor(),
                GetSinglesDescriptor(),
                BuildTypeDescriptor(Variables[VariableClauseTypes.Is].ToList(), "Is"),
                GetPredicatesDescriptor()
            };

            descriptors.Remove(string.Empty);

            var descriptor = new StringBuilder();

            for (var idx = 0; idx < descriptors.Count; idx++)
            {
                descriptor.Append(descriptors.ElementAt(idx));
            }

            _toString = descriptor.ToString();
            IsDirty   = false;
            return(_toString);
        }
示例#18
0
        public void Ask_PartialExecutes_AginstUser1Bid_ButAskSharesIsGreaterThanBidShares()
        {
            // Arrange.
            var existingBidOrder = new Order {
                Id = 100, Shares = 100, Subscription = new Subscription {
                    Owned = 0, UserId = _userId1
                }
            };

            var existingLimit = Limits.First();

            existingLimit.BidHead        = existingBidOrder;
            existingBidOrder.ParentLimit = existingLimit;

            Limits.Add(existingLimit);
            Orders.Add(existingBidOrder.Id, existingBidOrder);

            Subscriptions.Add(existingBidOrder.Subscription.UserId, existingBidOrder.Subscription);
            var existingSellerSubscription = new Subscription {
                Owned = 500, UserId = _userId2
            };

            Subscriptions.Add(existingSellerSubscription.UserId, existingSellerSubscription);

            // Act.
            Ask(_userId2, 1, 200);

            // Assert.
            var existingBidOrder2 = new Order {
                Id = 100, Shares = 0, Subscription = new Subscription {
                    Owned = 100, UserId = _userId1
                }
            };

            var existingLimit2 = new Limit {
                Price = 1 * ScaleFactor, BidHead = existingBidOrder2
            };

            existingBidOrder2.ParentLimit = existingLimit2;

            var existingSellerSubscription2 = new Subscription {
                Owned = 400, UserId = _userId2
            };
            var remainingSellersOrder = new Order
            {
                Id           = 1,
                ParentLimit  = existingLimit2,
                Shares       = 100,
                Subscription = existingSellerSubscription2
            };

            existingLimit2.AskHead = remainingSellersOrder;

            Assert.AreEqual(1, Limits.Count);
            Assert.AreEqual(2, Orders.Count);
            Assert.AreEqual(2, Subscriptions.Count);
            CollectionAssert.AreEqual(new Limit[] { existingLimit2 }, Limits, _limitTestComparer);
            CollectionAssert.AreEqual(new Order[] { existingBidOrder2, remainingSellersOrder }, (ICollection)Orders.Values, _orderTestComparer);
            CollectionAssert.AreEqual(new Subscription[] { existingBidOrder2.Subscription, existingSellerSubscription2 }, (ICollection)Subscriptions.Values, _subscriptionTestComparer);
        }
        public async Task Query_Rate_Limit_Max_Commands_WaitUntilReady()
        {
            await EnforceRateLimits();

            var username = "******";
            var limits   = new Limits();

            limits.QueryLimits = new QueryLimits(10, 1, 10, 10);
            await CreateRateLimitedUser(username, limits);

            try
            {
                var cluster = await Cluster.ConnectAsync(_connectionString, new ClusterOptions()
                {
                    UserName = username,
                    Password = RlPassword,
                    EnableDnsSrvResolution = false
                });

                var ex = await Assert.ThrowsAsync <RateLimitedException>(async() => await cluster.WaitUntilReadyAsync(TimeSpan.FromSeconds(30)));

                Assert.True(ex.Context?.Message.Contains("User has exceeded request rate limit"));
                await cluster.DisposeAsync();
            }
            finally
            {
                await _fixture.Cluster.Users.DropUserAsync(username);
            }
        }
示例#20
0
        public static async Task <List <TVShow> > GetTVShows(Limits limits = null, Filter filter = null, Sort sort = null)
        {
            JObject parameters = new JObject(
                new JProperty("properties",
                              new JArray("title", "genre", "year", "rating", "plot", "studio", "mpaa", "cast", "playcount", "episode", "imdbnumber", "premiered", "votes", "lastplayed", "fanart", "thumbnail", "file", "originaltitle", "sorttitle", "episodeguide", "season", "watchedepisodes", "dateadded", "tag", "art")
                              ));

            if (limits != null)
            {
                parameters["limits"] = JObject.FromObject(limits);
            }

            if (filter != null)
            {
                parameters["filter"] = JObject.FromObject(filter);
            }

            if (sort != null)
            {
                parameters["sort"] = JObject.FromObject(sort);
            }

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("VideoLibrary.GetTVShows", parameters);

            JArray tvShowsListObject = (JArray)responseObject["result"]["tvshows"];

            List <TVShow> listToReturn = tvShowsListObject != null?tvShowsListObject.ToObject <List <TVShow> >() : new List <TVShow>();

            return(listToReturn);
        }
示例#21
0
        private void FindPrimes(object limits)
        {
            if (!(limits is Limits))
            {
                return;
            }
            Limits l = (Limits)limits;

            for (int val = l.minimum; val <= l.maximum; ++val)
            {
                if (primep(val))
                //It was prime!
                {
                    if (InvokeRequired)
                    {
                        try
                        {
                            Invoke(new delVoidVoid(IncrementCount));
                            Invoke(new delVoidObject(AddPrime), val);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("We've made a terrible mistake: " + ex.Message, "Invoke Exception",
                                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }
示例#22
0
        /// <summary>
        /// Sends data (IPOC, correction) to the robot, raises <see cref="KUKARobot.FrameSent">FrameSent</see> event
        /// </summary>
        private void SendData()
        {
            RobotVector correction;

            lock (forceMoveSyncLock) {
                correction = generator.GetNextCorrection(position);
            }

            correction = new RobotVector(correction.X, correction.Y, correction.Z, 0, 0, 0);

            // CAŁY IF DO ZAKOMENTOWANIA DLA POZYCJI ABSOLUTNEJ
            if (!Limits.CheckCorrection(correction))
            {
                Uninitialize();
                throw new InvalidOperationException("Correction limit has been exceeded:" +
                                                    $"{Environment.NewLine}{correction}");
            }

            OutputFrame outputFrame = new OutputFrame()
            {
                Correction = correction,
                IPOC       = IPOC
            };

            rsiAdapter.SendData(outputFrame);
            FrameSent?.Invoke(outputFrame);
        }
示例#23
0
        private async Task <long> ReceiveDataAsync()
        {
            InputFrame receivedFrame = await rsiAdapter.ReceiveDataAsync();

            if (!Limits.CheckAxisPosition(receivedFrame.AxisPosition))
            {
                Uninitialize();
                throw new InvalidOperationException("Axis position limit has been exceeded:" +
                                                    $"{Environment.NewLine}{receivedFrame.AxisPosition}");
            }

            if (!Limits.CheckPosition(receivedFrame.Position))
            {
                Uninitialize();
                throw new InvalidOperationException("Available workspace limit has been exceeded:" +
                                                    $"{Environment.NewLine}{receivedFrame.Position}");
            }

            lock (receivedDataSyncLock) {
                position     = receivedFrame.Position;
                axisPosition = receivedFrame.AxisPosition;
            }

            FrameReceived?.Invoke(this, new FrameReceivedEventArgs {
                ReceivedFrame = receivedFrame
            });

            return(receivedFrame.IPOC);
        }
示例#24
0
        public void CanSerializeLimits()
        {
            var limits = new Limits();
            var xml    = _serializer.Serialize(limits);

            Assert.AreEqual("<Limits />", xml);
        }
示例#25
0
            public HotkeyBox()
            {
                key = mod = Keys.None;
                limit = Limits.None;
                Multiline = false;
                ContextMenu = new ContextMenu();
                Text = Enum.GetName(typeof(Keys), key);

                KeyPress += delegate(object sender, KeyPressEventArgs e)
                                {
                                    e.Handled = true;
                                };

                KeyUp += delegate(object sender, KeyEventArgs e)
                             {
                                 if (e.KeyCode == Keys.None && e.Modifiers == Keys.None)
                                     key = Keys.None;
                             };

                KeyDown += delegate(object sender, KeyEventArgs e)
                               {
                                   if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete)
                                       key = mod = Keys.None;
                                   else
                                   {
                                       key = e.KeyCode;
                                       mod = e.Modifiers;
                                       Validate();
                                   }

                                   SetText();
                               };
            }
示例#26
0
        /// <summary>
        ///    This method generates an expression labelling intervals of values with lables.
        /// </summary>
        /// <remarks>
        ///    Intervals are [-Inf;L1[,[L1;L2[,[L2;L3[,..,[Ln-1;Ln[,[Ln;Inf].
        /// </remarks>
        public override string GetExpression()
        {
            if (Limits == null || Items == null)
            {
                return(string.Empty);
            }

            var expression = new StringBuilder();

            var i      = 0;
            var labels = Labels.ToList();

            foreach (var limit in Limits)
            {
                expression.AppendFormat("iif([{0}] < {1}, '{2}', ", FieldName, limit.ConvertedTo <string>(), labels[i++]);
            }

            expression.AppendFormat("'{0}'", labels[i]);
            for (var j = 0; j < Limits.Count(); j++)
            {
                expression.Append(")");
            }

            return(expression.ToString());
        }
示例#27
0
        void fillClasses(List <Room> rooms)
        {
            for (int i = 1; i < 7; i++)
            {
                for (int j = 1; j < 9; j++)
                {
                    for (int r = 0; r < rooms.Count; r++)
                    {
                        Classes.Add(new WhenClass(i, j, false, rooms[r].ID_Room, rooms[r].Roominess));
                    }
                }
            }

            for (int i = 1; i < 7; i++)
            {
                for (int j = 1; j < 9; j++)
                {
                    for (int r = 0; r < rooms.Count; r++)
                    {
                        Classes.Add(new WhenClass(i, j, true, rooms[r].ID_Room, rooms[r].Roominess));
                    }
                }
            }

            for (int i = 0; i < Orders.Count; i++)
            {
                Limits.Add(Orders[i].Number);
            }
        }
示例#28
0
        /// <summary>
        ///     Sets a minimum delay before sending the response.
        /// </summary>
        /// <param name="app">The IAppBuilder instance.</param>
        /// <param name="getMinDelay">
        ///     A delegate to retrieve the minimum delay before calling the next stage in the pipeline. Note:
        ///     the delegate should return quickly.
        /// </param>
        /// <returns>The app instance.</returns>
        public static IAppBuilder MinResponseDelay(this IAppBuilder app, Func <RequestContext, TimeSpan> getMinDelay,
                                                   string loggerName = null)
        {
            app.MustNotNull("app");

            app.Use(Limits.MinResponseDelay(getMinDelay, loggerName));
            return(app);
        }
示例#29
0
 public Term Splice(Term a)
 {
     if (Spliceable(a))
     {
         return(TermHelper.Create(Numerator, Denominator, Limits.Splice(a.Limits)));
     }
     throw new InvalidOperationException($"Cannot Splice {this} and {a}");
 }
示例#30
0
        /// <summary>
        /// Limits the bandwith used by the subsequent stages in the owin pipeline.
        /// </summary>
        /// <param name="getMaxBytesPerSecond">A delegate to retrieve the maximum number of bytes per second to be transferred.
        /// Allows you to supply different values at runtime. Use 0 or a negative number to specify infinite bandwidth.</param>
        /// <returns>An OWIN middleware delegate.</returns>
        /// <param name="app">The IAppBuilder instance.</param>
        /// <exception cref="System.ArgumentNullException">app</exception>
        /// <exception cref="System.ArgumentNullException">getMaxBytesPerSecond</exception>
        public static IAppBuilder MaxBandwidthPerRequest(this IAppBuilder app, Func <RequestContext, int> getMaxBytesPerSecond)
        {
            app.MustNotNull("app");
            getMaxBytesPerSecond.MustNotNull("getMaxBytesPerSecond");

            app.Use(Limits.MaxBandwidthPerRequest(getMaxBytesPerSecond));
            return(app);
        }
示例#31
0
        /// <inheritdoc/>
        public void Normalize()
        {
            Limits       = Limits ?? new ServiceResourceSettings();
            Reservations = Reservations ?? new ServiceResourceSettings();

            Limits?.Normalize();
            Reservations?.Normalize();
        }
示例#32
0
        /// <summary>
        /// Limits the length of the URL.
        /// </summary>
        /// <param name="app">The IAppBuilder instance.</param>
        /// <param name="getMaxUrlLength">A delegate to get the maximum URL length.</param>
        /// <returns>The IAppBuilder instance.</returns>
        public static IAppBuilder MaxUrlLength(this IAppBuilder app, Func <RequestContext, int> getMaxUrlLength)
        {
            app.MustNotNull("app");
            getMaxUrlLength.MustNotNull("getMaxUrlLength");

            app.Use(Limits.MaxUrlLength(getMaxUrlLength));
            return(app);
        }
        /// <summary>
        ///     Timeouts the connection if there hasn't been an read activity on the request body stream or any
        ///     write activity on the response body stream.
        /// </summary>
        /// <param name="app">The IAppBuilder instance.</param>
        /// <param name="timeout">The timeout.</param>
        /// <param name="loggerName">(Optional) The name of the logger log messages are written to.</param>
        /// <returns>The IAppBuilder instance.</returns>
        public static IAppBuilder ConnectionTimeout(this IAppBuilder app, TimeSpan timeout, string loggerName = null)
        {
            app.MustNotNull("app");

            app.Use(Limits.ConnectionTimeout(timeout, loggerName));

            return app;
        }
        public RateLimitFeatureTests()
        {
            redisManager = A.Fake<IRedisClientsManager>();
            limitProvider = A.Fake<ILimitProvider>();
            keyGenerator = A.Fake<ILimitKeyGenerator>();

            var fixture = new Fixture().Customize(new AutoFakeItEasyCustomization());
            limit = fixture.Create<Limits>();
            A.CallTo(() => limitProvider.GetLimits(A<IRequest>.Ignored)).Returns(limit);
        }
示例#35
0
        public static async Task<List<Source>> GetSources(string media = "files", Limits limits = null, Sort sort = null)
        {
            JObject parameters = new JObject();

            parameters["media"] = media;

            if (limits != null)
            {
                parameters["limits"] = JObject.FromObject(limits);
            }

            if (sort != null)
            {
                parameters["sort"] = JObject.FromObject(sort);
            }

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("Files.GetSources", parameters);
            JArray fileListObject = (JArray)responseObject["result"]["sources"];
            List<Source> listToReturn = fileListObject != null ? fileListObject.ToObject<List<Source>>() : new List<Source>();
            return listToReturn;
        }
示例#36
0
        public static async Task<List<Movie>> GetRecentlyAddedMovies(Limits limits = null, Sort sort = null)
        {
            JObject parameters = new JObject(
                                new JProperty("properties",
                                    new JArray("title", "genre", "year", "rating", "director", "trailer", "tagline", "plot", "plotoutline", "originaltitle", "lastplayed", "playcount", "writer", "studio", "mpaa", "cast", "country", "imdbnumber", "runtime", "set", "showlink", "streamdetails", "top250", "votes", "fanart", "thumbnail", "file", "sorttitle", "resume", "setid", "dateadded", "tag", "art")
                                    ));

            if (limits != null)
            {
                parameters["limits"] = JObject.FromObject(limits);
            }

            if (sort != null)
            {
                parameters["sort"] = JObject.FromObject(sort);
            }

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("VideoLibrary.GetRecentlyAddedMovies", parameters);
            JArray movieListObject = (JArray)responseObject["result"]["movies"];
            List<Movie> listToReturn = movieListObject != null ? movieListObject.ToObject<List<Movie>>() : new List<Movie>();
            return listToReturn;
        }
示例#37
0
        public static async Task<List<Episode>> GetRecentlyAddedEpisodes(Limits limits = null, Sort sort = null)
        {
            JObject parameters = new JObject(
                                new JProperty("properties",
                                    new JArray("title", "plot", "votes", "rating", "writer", "firstaired", "playcount", "runtime", "director", "productioncode", "season", "episode", "originaltitle", "showtitle", "streamdetails", "lastplayed", "fanart", "thumbnail", "file", "resume", "tvshowid", "dateadded", "uniqueid", "art")
                                    ));

            if (limits != null)
            {
                parameters["limits"] = JObject.FromObject(limits);
            }

            if (sort != null)
            {
                parameters["sort"] = JObject.FromObject(sort);
            }

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("VideoLibrary.GetRecentlyAddedEpisodes", parameters);
            JArray episodeListObject = (JArray)responseObject["result"]["episodes"];
            List<Episode> listToReturn = episodeListObject != null ? episodeListObject.ToObject<List<Episode>>() : new List<Episode>();
            return listToReturn;
        }
示例#38
0
        public static async Task<List<Album>> GetRecentlyAddedAlbums(Limits limits = null, Sort sort = null)
        {
            JObject parameters = new JObject(
                                new JProperty("properties",
                                    new JArray("title", "description", "artist", "genre", "theme", "mood", "style", "type", "albumlabel", "rating", "year", "musicbrainzalbumid", "musicbrainzalbumartistid", "fanart", "thumbnail", "playcount", "genreid", "artistid", "displayartist")
                                    ));

            if (limits != null)
            {
                parameters["limits"] = JObject.FromObject(limits);
            }

            if (sort != null)
            {
                parameters["sort"] = JObject.FromObject(sort);
            }

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("AudioLibrary.GetRecentlyAddedAlbums", parameters);

            JArray albumListObject = (JArray)responseObject["result"]["albums"];
            List<Album> listToReturn = albumListObject != null ? albumListObject.ToObject<List<Album>>() : new List<Album>();
            return listToReturn;
        }
示例#39
0
        public static async Task<List<Artist>> GetArtists(Filter filter = null, Limits limits = null, Sort sort = null)
        {
            JObject parameters = new JObject(
                                     new JProperty("properties",
                                         new JArray("born", "description", "died", "disbanded", "formed", "instrument", "mood", "musicbrainzartistid", "style", "yearsactive", "thumbnail", "fanart"))
                                             );

            if (limits != null)
            {
                parameters["limits"] = JObject.FromObject(limits);
            }

            if (filter != null)
            {
                parameters["filter"] = JObject.FromObject(filter);
            }

            if (sort != null)
            {
                parameters["sort"] = JObject.FromObject(sort);
            }

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("AudioLibrary.GetArtists", parameters);

            JArray artistListObject = (JArray)responseObject["result"]["artists"];
            List<Artist> listToReturn = artistListObject != null ? artistListObject.ToObject<List<Artist>>() : new List<Artist>();
            return listToReturn;
        }
示例#40
0
        public static async Task<int> GetSongsCount(Filter filter = null)
        {
            JObject parameters = new JObject();
            Limits limits = new Limits { Start = 0, End = 1 };
            if (filter != null)
            {
                parameters["filter"] = JObject.FromObject(filter);
            }
            parameters["limits"] = JObject.FromObject(limits);

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("AudioLibrary.GetSongs", parameters);
            return (int)responseObject["result"]["limits"]["total"];
        }
        private RateLimitResult GetLimitResult(IRequest request, Limits limits)
        {
            string consumerId = KeyGenerator.GetConsumerId(request);
            string requestId = KeyGenerator.GetRequestId(request);

            string args = GetLuaArgs(limits, request);

            using (var client = redisClientsManager.GetClient())
            {
                RedisText result = null;
                try
                {
                    // Call lua script to get current hit-rate and overall access/no-access
                    result = client.ExecLuaSha(GetSha1(), new[] { consumerId, requestId }, new[] { args });

                    var rateLimitResult = result.Text.FromJson<RateLimitResult>();
                    return rateLimitResult;
                }
                catch (RedisResponseException e)
                {
                    log.Error($"Error executing rate-limit Lua script. Called with {args}", e);
                }
                catch (SerializationException e)
                {
                    log.Error(
                        $"Error serialising rate-limit Lua script return to RateLimitResult. Result: {result?.Text}. Called with {args}",
                        e);
                }
                catch (Exception e)
                {
                    log.Error($"Error getting rate-limit result from Redis. Called with {args}", e);
                }
            }

            return new RateLimitResult();
        }
示例#42
0
        protected void OnPositionOpened(PositionOpenedEventArgs args)
        {
            var position = args.Position;

            Limits limits = new Limits(position.TradeType, position.EntryPrice, Symbol.PipSize, TakeProfit, StopLoss);

            //position.LimitsExt().SL_PIPS = StopLoss;
            //position.LimitsExt().TP_PIPS = TakeProfit;

            // double stopLoss = position.TradeType == TradeType.Buy ? position.EntryPrice - Symbol.PipSize * StopLoss : position.EntryPrice + Symbol.PipSize * StopLoss;
            // double takeProfit = position.TradeType == TradeType.Buy ? position.EntryPrice + Symbol.PipSize * TakeProfit : position.EntryPrice - Symbol.PipSize * TakeProfit;

            ModifyPosition(position, limits.StopLoss, limits.TakeProfit);
        }
 private string GetLuaArgs(Limits limits, IRequest request)
 {
     var args = new { Time = limits, Stamp = SecondsFromUnixTime(), RequestId = GetRequestCorrelationId(request) };
     return args.ToJson();
 }
示例#44
0
        public static async Task<int> GetEpisodesCount(Filter filter = null, int? tvShowID = null)
        {
            JObject parameters = new JObject();
            Limits limits = new Limits { Start = 0, End = 1 };
            if (filter != null)
            {
                parameters["filter"] = JObject.FromObject(filter);
            }
            if (tvShowID != null)
            {
                parameters["tvshowid"] = tvShowID;
            }
            parameters["limits"] = JObject.FromObject(limits);

            JObject responseObject = await ConnectionManager.ExecuteRPCRequest("VideoLibrary.GetEpisodes", parameters);
            return (int)responseObject["result"]["limits"]["total"];
        }
示例#45
0
 public static async Task PlayPartyMode()
 {
     List<Players> activePlayers = await Player.GetActivePlayers();
     if (!activePlayers.Contains(Players.Audio))
     {
         Limits limits = new Limits(0, 1);
         List<Song> oneSong = await AudioLibrary.GetSongs(null, limits, null);
         await Player.PlaySong(oneSong[0]);
     }
     await SetPartyMode(Players.Audio, true);
 }
示例#46
0
 void Awake()
 {
     limit = this;
 }
 // Events
 // Constructors
 public ServerInformation( )
 {
     ChannelModes = new ChannelModesInfo( );
     CaseMapping = "rfc1459";
     ChannelTypes = "#&";
     Feature = new Features( );
     Limit = new Limits( );
     UserModes = new UserModesInfo( );
 }
示例#48
0
 public static async Task<List<Song>> GetAllSongs()
 {
     int stepSize = 50;
     List<Song> toReturn = new List<Song>();
     int returnedStep = stepSize;
     Limits limits = new Limits { Start = 0, End = stepSize };
     while (returnedStep == stepSize)
     {
         List<Song> currentList = await GetSongs(limits: limits);
         returnedStep = currentList.Count;
         toReturn.AddRange(currentList);
         limits.Start += stepSize;
         limits.End += stepSize;
     }
     return toReturn;
 }