Exemple #1
0
        public void Can_Generate_Single_Number_Within_One_Number_Range()
        {
            var random = new RandomNumber();

            var res = random.Next(3, 3);

            Assert.Equal(3, res);
        }
Exemple #2
0
        public void Can_Generate_Single_Numbers_Within_Range()
        {
            var random = new RandomNumber();

            var res = random.Next(3, 6);

            Assert.InRange(res, 3, 6);
        }
    public static string CropImage(string ImagePath, int X1, int Y1, int X2, int Y2, int w, int h, int portalID, string userName, int userModuleID, string secureToken)
    {
        string CroppedImag             = "";
        AuthenticateService objService = new AuthenticateService();

        if (objService.IsPostAuthenticatedView(portalID, userModuleID, userName, secureToken))
        {
            string dir       = "";
            string imagename = ImagePath.Substring(ImagePath.LastIndexOf('/') + 1).ToString();
            dir = ImagePath.Replace(imagename, "");
            string imagenamewithoutext = imagename.Substring(imagename.LastIndexOf('.') + 1).ToString();

            int X     = System.Math.Min(X1, X2);
            int Y     = System.Math.Min(Y1, Y2);
            int index = 0;
            index = HttpContext.Current.Request.ApplicationPath == "/" ? 0 : 1;
            string originalFile = string.Concat(HttpContext.Current.Server.MapPath("~/"), ImagePath.Substring(ImagePath.IndexOf('/', index)).Replace("/", "\\"));
            string savePath     = Path.GetDirectoryName(originalFile) + "\\";
            if (File.Exists(originalFile))
            {
                using (System.Drawing.Image img = System.Drawing.Image.FromFile(originalFile))
                {
                    using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(w, h))
                    {
                        _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                        using (Graphics _graphic = Graphics.FromImage(_bitmap))
                        {
                            _graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            _graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            _graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                            _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                            _graphic.DrawImage(img, 0, 0, w, h);
                            _graphic.DrawImage(img, new Rectangle(0, 0, w, h), X, Y, w, h, GraphicsUnit.Pixel);

                            Random rand = new Random((int)DateTime.Now.Ticks);
                            int    RandomNumber;
                            RandomNumber = rand.Next(1, 200);
                            int    CharCode   = rand.Next(Convert.ToInt32('a'), Convert.ToInt32('z'));
                            char   RandomChar = Convert.ToChar(CharCode);
                            string extension  = Path.GetExtension(originalFile);
                            //string croppedFileName = Guid.NewGuid().ToString();
                            string croppedFileName = imagenamewithoutext + "_" + RandomNumber.ToString() + RandomChar.ToString();
                            string path            = savePath;

                            // If the image is a gif file, change it into png
                            if (extension.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
                            {
                                extension = ".png";
                            }

                            string newFullPathName = string.Concat(path, croppedFileName, extension);

                            using (EncoderParameters encoderParameters = new EncoderParameters(1))
                            {
                                encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                                _bitmap.Save(newFullPathName, GetImageCodec(extension), encoderParameters);
                            }

                            //lblCroppedImage.Text = string.Format("<img src='{0}' alt='Cropped image'>", path + extension);

                            CroppedImag = string.Format("<img src='{0}' alt='Cropped image'>", string.Concat(dir, croppedFileName, extension));
                        }
                    }
                }
            }
        }
        return(CroppedImag);
    }
        public bool TryAuthenticate(string AuthTicket)
        {
            try
            {
                UserData userData = UserDataFactory.GetUserData(AuthTicket, out byte errorCode);
                if (errorCode == 1 || errorCode == 2)
                {
                    Disconnect();
                    return(false);
                }

                #region Ban Checking

                //Let's have a quick search for a ban before we successfully authenticate..
                ModerationBan BanRecord;
                if (!string.IsNullOrEmpty(MachineId))
                {
                    if (NeonEnvironment.GetGame().GetModerationManager().IsBanned(MachineId, out BanRecord))
                    {
                        if (NeonEnvironment.GetGame().GetModerationManager().MachineBanCheck(MachineId))
                        {
                            Disconnect();
                            return(false);
                        }
                    }
                }

                if (NeonEnvironment.GetGame().GetModerationManager().IsBanned(userData.user.Username, out BanRecord))
                {
                    if (NeonEnvironment.GetGame().GetModerationManager().UsernameBanCheck(userData.user.Username))
                    {
                        Disconnect();
                        return(false);
                    }
                }

                #endregion

                NeonEnvironment.GetGame().GetClientManager().RegisterClient(this, userData.userID, userData.user.Username);
                _habbo = userData.user;


                if (_habbo != null)
                {
                    ssoTicket = AuthTicket;
                    userData.user.Init(this, userData);


                    SendMessage(new AuthenticationOKComposer());
                    SendMessage(new AvatarEffectsComposer(_habbo.Effects().GetAllEffects));
                    SendMessage(new NavigatorSettingsComposer(_habbo.HomeRoom));
                    SendMessage(new FavouritesComposer(userData.user.FavoriteRooms));
                    SendMessage(new FigureSetIdsComposer(_habbo.GetClothing().GetClothingAllParts));
                    SendMessage(new UserRightsComposer(_habbo));
                    SendMessage(new AvailabilityStatusComposer());
                    SendMessage(new AchievementScoreComposer(_habbo.GetStats().AchievementPoints));


                    //var habboClubSubscription = new ServerPacket(ServerPacketHeader.HabboClubSubscriptionComposer);
                    //habboClubSubscription.WriteString("club_habbo");
                    //habboClubSubscription.WriteInteger(0);
                    //habboClubSubscription.WriteInteger(0);
                    //habboClubSubscription.WriteInteger(0);
                    //habboClubSubscription.WriteInteger(2);
                    //habboClubSubscription.WriteBoolean(false);
                    //habboClubSubscription.WriteBoolean(false);
                    //habboClubSubscription.WriteInteger(0);
                    //habboClubSubscription.WriteInteger(0);
                    //habboClubSubscription.WriteInteger(0);
                    //SendMessage(habboClubSubscription);

                    SendMessage(new BuildersClubMembershipComposer());
                    SendMessage(new CfhTopicsInitComposer());

                    SendMessage(new BadgeDefinitionsComposer(NeonEnvironment.GetGame().GetAchievementManager()._achievements));
                    SendMessage(new SoundSettingsComposer(_habbo.ClientVolume, _habbo.ChatPreference, _habbo.AllowMessengerInvites, _habbo.FocusPreference, FriendBarStateUtility.GetInt(_habbo.FriendbarState)));

                    if (GetHabbo().GetMessenger() != null)
                    {
                        GetHabbo().GetMessenger().OnStatusChanged(true);
                    }

                    if (_habbo.Rank < 2 && !NeonStaticGameSettings.HotelOpenForUsers)
                    {
                        SendMessage(new SendHotelAlertLinkEventComposer("Actualmente solo el Equipo Adminsitrativo puede entrar al hotel para comprobar que todo está bien antes de que los usuarios puedan entrar. Vuelve a intentarlo en unos minutos, podrás encontrar más información en nuestro Facebook.", NeonEnvironment.GetDBConfig().DBData["facebook_url"]));
                        Thread.Sleep(10000);
                        Disconnect();
                        return(false);
                    }

                    if (!string.IsNullOrEmpty(MachineId))
                    {
                        if (_habbo.MachineId != MachineId)
                        {
                            using (IQueryAdapter dbClient = NeonEnvironment.GetDatabaseManager().GetQueryReactor())
                            {
                                dbClient.SetQuery("UPDATE `users` SET `machine_id` = @MachineId WHERE `id` = @id LIMIT 1");
                                dbClient.AddParameter("MachineId", MachineId);
                                dbClient.AddParameter("id", _habbo.Id);
                                dbClient.RunQuery();
                            }
                        }

                        _habbo.MachineId = MachineId;
                    }
                    if (NeonEnvironment.GetGame().GetPermissionManager().TryGetGroup(_habbo.Rank, out PermissionGroup PermissionGroup))
                    {
                        if (!string.IsNullOrEmpty(PermissionGroup.Badge))
                        {
                            if (!_habbo.GetBadgeComponent().HasBadge(PermissionGroup.Badge))
                            {
                                _habbo.GetBadgeComponent().GiveBadge(PermissionGroup.Badge, true, this);
                            }
                        }
                    }

                    if (NeonEnvironment.GetGame().GetSubscriptionManager().TryGetSubscriptionData(_habbo.VIPRank, out SubscriptionData SubData))
                    {
                        if (!string.IsNullOrEmpty(SubData.Badge))
                        {
                            if (!_habbo.GetBadgeComponent().HasBadge(SubData.Badge))
                            {
                                _habbo.GetBadgeComponent().GiveBadge(SubData.Badge, true, this);
                            }
                        }
                    }

                    if (!NeonEnvironment.GetGame().GetCacheManager().ContainsUser(_habbo.Id))
                    {
                        NeonEnvironment.GetGame().GetCacheManager().GenerateUser(_habbo.Id);
                    }

                    _habbo.InitProcess();

                    GetHabbo()._lastitems = new Dictionary <int, CatalogItem>();
                    //ICollection<MessengerBuddy> Friends = new List<MessengerBuddy>();
                    //foreach (MessengerBuddy Buddy in this.GetHabbo().GetMessenger().GetFriends().ToList())
                    //{
                    //    if (Buddy == null)
                    //        continue;

                    //    GameClient Friend = NeonEnvironment.GetGame().GetClientManager().GetClientByUserID(Buddy.Id);
                    //    if (Friend == null)
                    //        continue;
                    //    string figure = this.GetHabbo().Look;


                    //    Friend.SendMessage(RoomNotificationComposer.SendBubble("usr/look/" + this.GetHabbo().Username + "", this.GetHabbo().Username + " se ha conectado a " + NeonEnvironment.GetDBConfig().DBData["hotel.name"] + ".", ""));

                    //}

                    if (GetHabbo()._NUX)
                    {
                        SendMessage(new MassEventComposer("habbopages/bienvenida.txt"));
                    }
                    else
                    {
                        SendMessage(new MassEventComposer("habbopages/welk.txt?249"));
                    }


                    if (NeonEnvironment.GetDBConfig().DBData["pin.system.enable"] == "0")
                    {
                        GetHabbo().StaffOk = true;
                    }

                    if (GetHabbo().StaffOk)
                    {
                        if (GetHabbo().GetPermissions().HasRight("mod_tickets"))
                        {
                            SendMessage(new ModeratorInitComposer(
                                            NeonEnvironment.GetGame().GetModerationManager().UserMessagePresets,
                                            NeonEnvironment.GetGame().GetModerationManager().RoomMessagePresets,
                                            NeonEnvironment.GetGame().GetModerationManager().GetTickets));
                        }
                    }

                    if (GetHabbo().Rank > 5 || GetHabbo()._guidelevel > 0)
                    {
                        HelperToolsManager.AddHelper(_habbo.GetClient(), false, true, true);
                        SendMessage(new HandleHelperToolComposer(true));
                    }

                    //SendMessage(new CampaignCalendarDataComposer(_habbo.calendarGift));
                    //if (int.Parse(NeonEnvironment.GetDBConfig().DBData["advent.calendar.enable"]) == 1) // Tk Custom By Whats
                    //    SendMessage(new MassEventComposer("openView/calendar"));

                    if (NeonEnvironment.GetGame().GetTargetedOffersManager().TargetedOffer != null)
                    {
                        NeonEnvironment.GetGame().GetTargetedOffersManager().Initialize(NeonEnvironment.GetDatabaseManager().GetQueryReactor());
                        TargetedOffers TargetedOffer = NeonEnvironment.GetGame().GetTargetedOffersManager().TargetedOffer;

                        if (TargetedOffer.Expire > NeonEnvironment.GetIUnixTimestamp())
                        {
                            if (TargetedOffer.Limit != GetHabbo()._TargetedBuy)
                            {
                                SendMessage(NeonEnvironment.GetGame().GetTargetedOffersManager().TargetedOffer.Serialize());
                            }
                        }
                        else if (TargetedOffer.Expire == -1)
                        {
                            if (TargetedOffer.Limit != GetHabbo()._TargetedBuy)
                            {
                                SendMessage(NeonEnvironment.GetGame().GetTargetedOffersManager().TargetedOffer.Serialize());
                            }
                        }
                        else
                        {
                            using (IQueryAdapter dbClient = NeonEnvironment.GetDatabaseManager().GetQueryReactor())
                            {
                                dbClient.runFastQuery("UPDATE targeted_offers SET active = 'false'");
                            }

                            using (IQueryAdapter dbClient2 = NeonEnvironment.GetDatabaseManager().GetQueryReactor())
                            {
                                dbClient2.runFastQuery("UPDATE users SET targeted_buy = '0' WHERE targeted_buy > 0");
                            }
                        }
                    }

                    if (_habbo.MysticBoxes.Count == 0 && _habbo.MysticKeys.Count == 0)
                    {
                        int    box      = RandomNumber.GenerateRandom(1, 8);
                        string boxcolor = "";
                        switch (box)
                        {
                        case 1:
                            boxcolor = "purple";
                            break;

                        case 2:
                            boxcolor = "blue";
                            break;

                        case 3:
                            boxcolor = "green";
                            break;

                        case 4:
                            boxcolor = "yellow";
                            break;

                        case 5:
                            boxcolor = "lilac";
                            break;

                        case 6:
                            boxcolor = "orange";
                            break;

                        case 7:
                            boxcolor = "turquoise";
                            break;

                        case 8:
                            boxcolor = "red";
                            break;
                        }

                        int    key      = RandomNumber.GenerateRandom(1, 8);
                        string keycolor = "";
                        switch (key)
                        {
                        case 1:
                            keycolor = "purple";
                            break;

                        case 2:
                            keycolor = "blue";
                            break;

                        case 3:
                            keycolor = "green";
                            break;

                        case 4:
                            keycolor = "yellow";
                            break;

                        case 5:
                            keycolor = "lilac";
                            break;

                        case 6:
                            keycolor = "orange";
                            break;

                        case 7:
                            keycolor = "turquoise";
                            break;

                        case 8:
                            keycolor = "red";
                            break;
                        }

                        _habbo.MysticKeys.Add(keycolor);
                        _habbo.MysticBoxes.Add(boxcolor);

                        using (IQueryAdapter dbClient = NeonEnvironment.GetDatabaseManager().GetQueryReactor())
                        {
                            dbClient.runFastQuery("INSERT INTO user_mystic_data(user_id, mystic_keys, mystic_boxes) VALUES(" + GetHabbo().Id + ", '" + keycolor + "', '" + boxcolor + "');");
                        }
                    }

                    SendMessage(new MysteryBoxDataComposer(_habbo.GetClient()));

                    SendMessage(new HCGiftsAlertComposer());

                    //if(!GetHabbo()._NUX)
                    //{
                    //    DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                    //    dtDateTime = dtDateTime.AddSeconds(GetHabbo().LastOnline);

                    //    if ((DateTime.Now - dtDateTime).TotalDays > 2)
                    //    {
                    //        //NeonEnvironment.GetGame().GetAchievementManager().ProgressAchievement(_habbo.GetClient(), "ACH_Login", 1, true);
                    //        NeonEnvironment.GetGame().GetAchievementManager().ProgressAchievement(_habbo.GetClient(), "ACH_RegistrationDuration", 1);
                    //    }

                    //    else if ((DateTime.Now - dtDateTime).TotalDays > 1 && (DateTime.Now - dtDateTime).TotalDays < 2)
                    //    {
                    //        NeonEnvironment.GetGame().GetAchievementManager().ProgressAchievement(_habbo.GetClient(), "ACH_Login", 1);
                    //        NeonEnvironment.GetGame().GetAchievementManager().ProgressAchievement(_habbo.GetClient(), "ACH_RegistrationDuration", 1);

                    //        if(GetHabbo().Rank > 2 || GetHabbo()._guidelevel > 0)
                    //        {
                    //            NeonEnvironment.GetGame().GetAchievementManager().ProgressAchievement(_habbo.GetClient(), "ACH_GuideEnrollmentLifetime", 1);
                    //        }
                    //    }
                    //}


                    NeonEnvironment.GetGame().GetRewardManager().CheckRewards(this);

                    if (GetHabbo()._NUX)
                    {
                        NeonEnvironment.GetGame().GetClientManager().StaffAlert(new RoomInviteComposer(int.MinValue, GetHabbo().Username + " acaba de registrarse en Keko."));

                        GetHabbo()._NUX = false;
                        using (IQueryAdapter dbClient = NeonEnvironment.GetDatabaseManager().GetQueryReactor())
                        {
                            dbClient.runFastQuery("UPDATE users SET nux_user = '******' WHERE id = " + GetHabbo().Id + ";");
                        }
                    }

                    return(true);
                }
            }
            catch (Exception e)
            {
                Logging.LogCriticalException("Bug during user login: " + e);
            }
            return(false);
        }
Exemple #5
0
 private void btnInitillize_Click(object sender, EventArgs e)
 {
     #region Ürünler
     var products = new List <Product>();
     for (int i = 0; i < 100; i++)
     {
         var name = Lorem.Words(1).ElementAt(0);
         var p    = new Product
         {
             Id         = i + 1,
             Name       = name.Substring(0, 1).ToUpper() + name.Substring(1).ToLower(),
             CategoryId = RandomNumber.Next(1, 10),
             SupplierId = RandomNumber.Next(1, 25),
             Stock      = RandomNumber.Next(0, 800),
             Price      = RandomNumber.Next(1, 5600)
         };
         products.Add(p);
     }
     FileManager.SaveProducts(products);
     #endregion
     #region Kategoriler
     var categories = new List <Category>
     {
         new Category {
             Id = 1, Name = "Giyim"
         },
         new Category {
             Id = 2, Name = "Yiyecek"
         },
         new Category {
             Id = 3, Name = "İçecek"
         },
         new Category {
             Id = 4, Name = "Elektronik"
         },
         new Category {
             Id = 5, Name = "Kırtasiye"
         },
         new Category {
             Id = 6, Name = "Züccaciye"
         },
         new Category {
             Id = 7, Name = "Mobilya"
         },
         new Category {
             Id = 8, Name = "Ayakkabı"
         },
         new Category {
             Id = 9, Name = "Takı"
         },
         new Category {
             Id = 10, Name = "Beyaz Eşya"
         }
     };
     FileManager.SaveCategories(categories);
     #endregion
     #region Sağlayıcılar
     var suppliers = new List <Supplier>();
     for (int i = 0; i < 25; i++)
     {
         var s = new Supplier
         {
             Id    = i + 1,
             Name  = Company.Name(),
             Phone = Phone.Number()
         };
         suppliers.Add(s);
     }
     FileManager.SaveSuppliers(suppliers);
     #endregion
 }
        public override void OnTimerTick()
        {
            RoomUser Pet = GetRoomUser();

            if (Pet == null)
            {
                return;
            }


            #region Speech

            if (SpeechTimer <= 0)
            {
                if (Pet.PetData.DBState != DatabaseUpdateState.NeedsInsert)
                {
                    Pet.PetData.DBState = DatabaseUpdateState.NeedsUpdate;
                }

                if (Pet != null)
                {
                    var RandomSpeech = new Random();
                    RemovePetStatus();

                    string[] Speech  = BiosEmuThiago.GetGame().GetChatManager().GetPetLocale().GetValue("speech.pet" + Pet.PetData.Type);
                    string   rSpeech = Speech[RandomNumber.GenerateRandom(0, Speech.Length - 1)];

                    if (rSpeech.Length != 3)
                    {
                        Pet.Chat(rSpeech, false);
                    }
                    else
                    {
                        Pet.Statusses.Add(rSpeech, TextHandling.GetString(Pet.Z));
                    }
                }
                SpeechTimer = BiosEmuThiago.GetRandomNumber(20, 120);
            }
            else
            {
                SpeechTimer--;
            }

            #endregion

            #region Actions

            if (ActionTimer <= 0)
            {
                try
                {
                    RemovePetStatus();
                    ActionTimer = RandomNumber.GenerateRandom(15, 40 + GetRoomUser().PetData.VirtualId);
                    if (!GetRoomUser().RidingHorse)
                    {
                        // Remove Status
                        RemovePetStatus();

                        Point nextCoord = GetRoom().GetGameMap().GetRandomWalkableSquare();
                        if (GetRoomUser().CanWalk)
                        {
                            GetRoomUser().MoveTo(nextCoord.X, nextCoord.Y);
                        }
                    }
                }
                catch (Exception e)
                {
                    ExceptionLogger.LogException(e);
                }
            }
            else
            {
                ActionTimer--;
            }

            #endregion

            #region Energy

            if (EnergyTimer <= 0)
            {
                RemovePetStatus();                                  // Remove Status

                Pet.PetData.PetEnergy(true);                        // Add Energy

                EnergyTimer = RandomNumber.GenerateRandom(30, 120); // 2 Min Max
            }
            else
            {
                EnergyTimer--;
            }

            #endregion
        }
Exemple #7
0
        public static InstructionCollection Parse(Stream input, long instructionsPosition)
        {
            var instructions = new SortedList <int, InstructionBase>();

            using (var helper = new InstructionParseHelper(input, instructionsPosition))
            {
                var reader = helper.GetReader();
                while (helper.CanParse(instructions))
                {
                    //now reader the instructions
                    var instructionPosition = helper.CurrentPosition;
                    var type             = reader.ReadByteAsEnum <InstructionType>();
                    var requireAlignment = InstructionAlignment.IsAligned(type);

                    if (requireAlignment)
                    {
                        reader.Align(4);
                    }

                    InstructionBase instruction = null;
                    var             parameters  = new List <Value>();

                    switch (type)
                    {
                    case InstructionType.ToNumber:
                        instruction = new ToNumber();
                        break;

                    case InstructionType.NextFrame:
                        instruction = new NextFrame();
                        break;

                    case InstructionType.Play:
                        instruction = new Play();
                        break;

                    case InstructionType.Stop:
                        instruction = new Stop();
                        break;

                    case InstructionType.Add:
                        instruction = new Add();
                        break;

                    case InstructionType.Subtract:
                        instruction = new Subtract();
                        break;

                    case InstructionType.Multiply:
                        instruction = new Multiply();
                        break;

                    case InstructionType.Divide:
                        instruction = new Divide();
                        break;

                    case InstructionType.Not:
                        instruction = new Not();
                        break;

                    case InstructionType.StringEquals:
                        instruction = new StringEquals();
                        break;

                    case InstructionType.Pop:
                        instruction = new Pop();
                        break;

                    case InstructionType.ToInteger:
                        instruction = new ToInteger();
                        break;

                    case InstructionType.GetVariable:
                        instruction = new GetVariable();
                        break;

                    case InstructionType.SetVariable:
                        instruction = new SetVariable();
                        break;

                    case InstructionType.StringConcat:
                        instruction = new StringConcat();
                        break;

                    case InstructionType.GetProperty:
                        instruction = new GetProperty();
                        break;

                    case InstructionType.SetProperty:
                        instruction = new SetProperty();
                        break;

                    case InstructionType.Trace:
                        instruction = new Trace();
                        break;

                    case InstructionType.Random:
                        instruction = new RandomNumber();
                        break;

                    case InstructionType.Delete:
                        instruction = new Delete();
                        break;

                    case InstructionType.Delete2:
                        instruction = new Delete2();
                        break;

                    case InstructionType.DefineLocal:
                        instruction = new DefineLocal();
                        break;

                    case InstructionType.CallFunction:
                        instruction = new CallFunction();
                        break;

                    case InstructionType.Return:
                        instruction = new Return();
                        break;

                    case InstructionType.Modulo:
                        instruction = new Modulo();
                        break;

                    case InstructionType.NewObject:
                        instruction = new NewObject();
                        break;

                    case InstructionType.InitArray:
                        instruction = new InitArray();
                        break;

                    case InstructionType.InitObject:
                        instruction = new InitObject();
                        break;

                    case InstructionType.TypeOf:
                        instruction = new TypeOf();
                        break;

                    case InstructionType.Add2:
                        instruction = new Add2();
                        break;

                    case InstructionType.LessThan2:
                        instruction = new LessThan2();
                        break;

                    case InstructionType.Equals2:
                        instruction = new Equals2();
                        break;

                    case InstructionType.ToString:
                        instruction = new ToString();
                        break;

                    case InstructionType.PushDuplicate:
                        instruction = new PushDuplicate();
                        break;

                    case InstructionType.GetMember:
                        instruction = new GetMember();
                        break;

                    case InstructionType.SetMember:
                        instruction = new SetMember();
                        break;

                    case InstructionType.Increment:
                        instruction = new Increment();
                        break;

                    case InstructionType.Decrement:
                        instruction = new Decrement();
                        break;

                    case InstructionType.CallMethod:
                        instruction = new CallMethod();
                        break;

                    case InstructionType.Enumerate2:
                        instruction = new Enumerate2();
                        break;

                    case InstructionType.EA_PushThis:
                        instruction = new PushThis();
                        break;

                    case InstructionType.EA_PushZero:
                        instruction = new PushZero();
                        break;

                    case InstructionType.EA_PushOne:
                        instruction = new PushOne();
                        break;

                    case InstructionType.EA_CallFunc:
                        instruction = new CallFunc();
                        break;

                    case InstructionType.EA_CallMethodPop:
                        instruction = new CallMethodPop();
                        break;

                    case InstructionType.BitwiseXOr:
                        instruction = new BitwiseXOr();
                        break;

                    case InstructionType.Greater:
                        instruction = new Greater();
                        break;

                    case InstructionType.EA_PushThisVar:
                        instruction = new PushThisVar();
                        break;

                    case InstructionType.EA_PushGlobalVar:
                        instruction = new PushGlobalVar();
                        break;

                    case InstructionType.EA_ZeroVar:
                        instruction = new ZeroVar();
                        break;

                    case InstructionType.EA_PushTrue:
                        instruction = new PushTrue();
                        break;

                    case InstructionType.EA_PushFalse:
                        instruction = new PushFalse();
                        break;

                    case InstructionType.EA_PushNull:
                        instruction = new PushNull();
                        break;

                    case InstructionType.EA_PushUndefined:
                        instruction = new PushUndefined();
                        break;

                    case InstructionType.GotoFrame:
                        instruction = new GotoFrame();
                        parameters.Add(Value.FromInteger(reader.ReadInt32()));
                        break;

                    case InstructionType.GetURL:
                        instruction = new GetUrl();
                        parameters.Add(Value.FromString(reader.ReadStringAtOffset()));
                        parameters.Add(Value.FromString(reader.ReadStringAtOffset()));
                        break;

                    case InstructionType.SetRegister:
                        instruction = new SetRegister();
                        parameters.Add(Value.FromInteger(reader.ReadInt32()));
                        break;

                    case InstructionType.ConstantPool:
                    {
                        instruction = new ConstantPool();
                        var count     = reader.ReadUInt32();
                        var constants = reader.ReadFixedSizeArrayAtOffset <uint>(() => reader.ReadUInt32(), count);

                        foreach (var constant in constants)
                        {
                            parameters.Add(Value.FromConstant(constant));
                        }
                    }
                    break;

                    case InstructionType.GotoLabel:
                        instruction = new GotoLabel();
                        parameters.Add(Value.FromString(reader.ReadStringAtOffset()));
                        break;

                    case InstructionType.DefineFunction2:
                    {
                        instruction = new DefineFunction2();
                        var name       = reader.ReadStringAtOffset();
                        var nParams    = reader.ReadUInt32();
                        var nRegisters = reader.ReadByte();
                        var flags      = reader.ReadUInt24();

                        //list of parameter strings
                        var paramList = reader.ReadFixedSizeListAtOffset <FunctionArgument>(() => new FunctionArgument()
                            {
                                Register  = reader.ReadInt32(),
                                Parameter = reader.ReadStringAtOffset(),
                            }, nParams);

                        parameters.Add(Value.FromString(name));
                        parameters.Add(Value.FromInteger((int)nParams));
                        parameters.Add(Value.FromInteger((int)nRegisters));
                        parameters.Add(Value.FromInteger((int)flags));
                        foreach (var param in paramList)
                        {
                            parameters.Add(Value.FromInteger(param.Register));
                            parameters.Add(Value.FromString(param.Parameter));
                        }
                        //body size of the function
                        parameters.Add(Value.FromInteger(reader.ReadInt32()));
                        //skip 8 bytes
                        reader.ReadUInt64();
                    }
                    break;

                    case InstructionType.PushData:
                    {
                        instruction = new PushData();

                        var count     = reader.ReadUInt32();
                        var constants = reader.ReadFixedSizeArrayAtOffset <uint>(() => reader.ReadUInt32(), count);

                        foreach (var constant in constants)
                        {
                            parameters.Add(Value.FromConstant(constant));
                        }
                    }
                    break;

                    case InstructionType.BranchAlways:
                    {
                        instruction = new BranchAlways();
                        var offset = reader.ReadInt32();
                        parameters.Add(Value.FromInteger(offset));
                        helper.ReportBranchOffset(offset);
                    }
                    break;

                    case InstructionType.GetURL2:
                        instruction = new GetUrl2();
                        break;

                    case InstructionType.DefineFunction:
                    {
                        instruction = new DefineFunction();
                        var name = reader.ReadStringAtOffset();
                        //list of parameter strings
                        var paramList = reader.ReadListAtOffset <string>(() => reader.ReadStringAtOffset());

                        parameters.Add(Value.FromString(name));
                        parameters.Add(Value.FromInteger(paramList.Count));
                        foreach (var param in paramList)
                        {
                            parameters.Add(Value.FromString(param));
                        }
                        //body size of the function
                        parameters.Add(Value.FromInteger(reader.ReadInt32()));
                        //skip 8 bytes
                        reader.ReadUInt64();
                    }
                    break;

                    case InstructionType.BranchIfTrue:
                    {
                        instruction = new BranchIfTrue();
                        var offset = reader.ReadInt32();
                        parameters.Add(Value.FromInteger(offset));
                        helper.ReportBranchOffset(offset);
                    }
                    break;

                    case InstructionType.GotoFrame2:
                        instruction = new GotoFrame2();
                        parameters.Add(Value.FromInteger(reader.ReadInt32()));
                        break;

                    case InstructionType.EA_PushString:
                        instruction = new PushString();
                        //the constant id that should be pushed
                        parameters.Add(Value.FromString(reader.ReadStringAtOffset()));
                        break;

                    case InstructionType.EA_PushConstantByte:
                        instruction = new PushConstantByte();
                        //the constant id that should be pushed
                        parameters.Add(Value.FromConstant(reader.ReadByte()));
                        break;

                    case InstructionType.EA_GetStringVar:
                        instruction = new GetStringVar();
                        parameters.Add(Value.FromString(reader.ReadStringAtOffset()));
                        break;

                    case InstructionType.EA_SetStringVar:
                        instruction = new SetStringVar();
                        parameters.Add(Value.FromString(reader.ReadStringAtOffset()));
                        break;

                    case InstructionType.EA_GetStringMember:
                        instruction = new GetStringMember();
                        parameters.Add(Value.FromString(reader.ReadStringAtOffset()));
                        break;

                    case InstructionType.EA_SetStringMember:
                        instruction = new SetStringMember();
                        parameters.Add(Value.FromString(reader.ReadStringAtOffset()));
                        break;

                    case InstructionType.EA_PushValueOfVar:
                        instruction = new PushValueOfVar();
                        //the constant id that should be pushed
                        parameters.Add(Value.FromConstant(reader.ReadByte()));
                        break;

                    case InstructionType.EA_GetNamedMember:
                        instruction = new GetNamedMember();
                        parameters.Add(Value.FromConstant(reader.ReadByte()));
                        break;

                    case InstructionType.EA_CallNamedFuncPop:
                        instruction = new CallNamedFuncPop();
                        parameters.Add(Value.FromConstant(reader.ReadByte()));
                        break;

                    case InstructionType.EA_CallNamedFunc:
                        instruction = new CallNamedFunc();
                        parameters.Add(Value.FromConstant(reader.ReadByte()));
                        break;

                    case InstructionType.EA_CallNamedMethodPop:
                        instruction = new CallNamedMethodPop();
                        parameters.Add(Value.FromConstant(reader.ReadByte()));
                        break;

                    case InstructionType.EA_PushFloat:
                        instruction = new PushFloat();
                        parameters.Add(Value.FromFloat(reader.ReadSingle()));
                        break;

                    case InstructionType.EA_PushByte:
                        instruction = new PushByte();
                        parameters.Add(Value.FromInteger(reader.ReadByte()));
                        break;

                    case InstructionType.EA_PushShort:
                        instruction = new PushShort();
                        parameters.Add(Value.FromInteger(reader.ReadUInt16()));
                        break;

                    case InstructionType.End:
                        instruction = new End();
                        break;

                    case InstructionType.EA_CallNamedMethod:
                        instruction = new CallNamedMethod();
                        parameters.Add(Value.FromConstant(reader.ReadByte()));
                        break;

                    case InstructionType.Var:
                        instruction = new Var();
                        break;

                    case InstructionType.EA_PushRegister:
                        instruction = new PushRegister();
                        parameters.Add(Value.FromInteger(reader.ReadByte()));
                        break;

                    case InstructionType.EA_PushConstantWord:
                        instruction = new PushConstantWord();
                        parameters.Add(Value.FromConstant(reader.ReadUInt16()));
                        break;

                    case InstructionType.EA_CallFuncPop:
                        instruction = new CallFunctionPop();
                        break;

                    case InstructionType.StrictEqual:
                        instruction = new StrictEquals();
                        break;

                    default:
                        throw new InvalidDataException("Unimplemented bytecode instruction:" + type.ToString());
                    }

                    if (instruction != null)
                    {
                        instruction.Parameters = parameters;
                        instructions.Add(instructionPosition, instruction);
                    }
                }
            }

            return(new InstructionCollection(instructions));
        }
        public BookNewConferenceRequestBuilder WithIndividual(string caseTypeGroup = "Claimant")
        {
            var participant = Builder <ParticipantRequest> .CreateNew()
                              .With(x => x.Name             = $"Automation_{Name.FullName()}")
                              .With(x => x.FirstName        = $"Automation_{Name.First()}")
                              .With(x => x.LastName         = $"Automation_{Name.Last()}")
                              .With(x => x.DisplayName      = $"Automation_{Internet.UserName()}")
                              .With(x => x.UserRole         = UserRole.Individual)
                              .With(x => x.CaseTypeGroup    = caseTypeGroup)
                              .With(x => x.HearingRole      = ParticipantBuilder.DetermineHearingRole(UserRole.Representative, caseTypeGroup))
                              .With(x => x.ParticipantRefId = Guid.NewGuid())
                              .With(x => x.ContactEmail     = $"Automation_Video_APi_{RandomNumber.Next()}@email.com")
                              .With(x => x.Username         = $"Automation_Video_APi_{RandomNumber.Next()}@username.com")
                              .Build();

            _bookNewConferenceRequest.Participants.Add(participant);
            return(this);
        }
 public void GetOperator_ShouldBeNumberInRange1To3()
 {
     RandomNumber random = new RandomNumber();
     Assert.That(random.GetOperator(), Is.InRange(1, 3));
 }
        public void Should_pass_validation_with_good_email()
        {
            var email = $"{RandomNumber.Next()}@hmcts.net";

            email.IsValidEmail().Should().BeTrue();
        }
Exemple #11
0
        private static object GetPropertyValue(PropertyInfo propInfo)
        {
            object[] attrs = propInfo.GetCustomAttributes(true);
            foreach (var attr in attrs)
            {
                if (attr.GetType() == typeof(DataType.IPv4))
                {
                    return(Internet.IPv4Address());
                }

                if (attr.GetType() == typeof(DataType.IPv6))
                {
                    return(Internet.IPv6Address());
                }

                if (attr.GetType() == typeof(DataType.Email))
                {
                    return(Internet.Email());
                }

                if (attr.GetType() == typeof(DataType.PhoneNumber))
                {
                    return(Phone.Number());
                }

                if (attr.GetType() == typeof(DataType.PhoneNumber))
                {
                    return(Phone.Number());
                }

                if (attr.GetType() == typeof(DataType.FullName))
                {
                    return(Name.FullName());
                }

                if (attr.GetType() == typeof(DataType.FirstName))
                {
                    return(Name.First());
                }

                if (attr.GetType() == typeof(DataType.LastName))
                {
                    return(Name.Last());
                }

                if (attr.GetType() == typeof(DataType.Static))
                {
                    var staticAttribute = attr as DataType.Static;
                    return(staticAttribute != null ? staticAttribute.Value : "");
                }
            }

            var pt = propInfo.PropertyType;

            if (pt.Name.ToLower().Contains("string"))
            {
                return(Company.Name());
            }

            if (pt.Name.ToLower().Contains("int"))
            {
                return(RandomNumber.Next());
            }

            return(null);
        }
Exemple #12
0
        public void OnTrigger(GameClient Session, Item Item, int Request, bool HasRights)
        {
            if ((!string.IsNullOrEmpty(Item.FoundBy)))
            {
                if (Session.GetHabbo().Username != Item.FoundBy)
                {
                    Session.SendMessage(RoomNotificationComposer.SendBubble("easteregg", "¡Este huevo ya ha sido encontrado por " + Item.FoundBy + "!", ""));
                    return;
                }
            }
            else

            if (Session == null || Session.GetHabbo() == null || Item == null)
            {
                return;
            }

            Room Room = Session.GetHabbo().CurrentRoom;

            if (Room == null)
            {
                return;
            }

            RoomUser Actor = Room.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);

            if (Actor == null)
            {
                return;
            }

            if (Gamemap.TileDistance(Actor.X, Actor.Y, Item.GetX, Item.GetY) < 2)
            {
                Item.FoundBy = Session.GetHabbo().Username;
            }

            var tick = int.Parse(Item.ExtraData);

            if (tick < 19)
            {
                if (Gamemap.TileDistance(Actor.X, Actor.Y, Item.GetX, Item.GetY) < 2)
                {
                    tick++;
                    Item.ExtraData = tick.ToString();
                    Item.UpdateState(true, true);
                    int    X = Item.GetX, Y = Item.GetY, Rot = Item.Rotation;
                    Double Z = Item.GetZ;
                    if (tick == 19)
                    {
                        using (var dbClient = RavenEnvironment.GetDatabaseManager().GetQueryReactor())
                        {
                            Room.GetRoomItemHandler().RemoveFurniture(Session, Item.Id);
                            dbClient.runFastQuery("DELETE FROM items WHERE id = " + Item.Id);
                        }

                        // Empezamos a generar el tipo de premio según lotería.
                        int RewardType = RandomNumber.GenerateRandom(1, 20);
                        switch (RewardType)
                        {
                        case 1:
                            int RewardDiamonds           = RandomNumber.GenerateRandom(1, 10);
                            Session.GetHabbo().Diamonds += RewardDiamonds;
                            Session.SendMessage(new HabboActivityPointNotificationComposer(Session.GetHabbo().Diamonds, RewardDiamonds, 5));
                            Session.SendWhisper("Acabas de ganar " + RewardDiamonds + " diamantes con este Huevo de Pascua, ¡qué suerte!.", 34);
                            break;

                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 8:
                        case 10:
                        case 11:
                        case 12:
                        case 13:
                        case 14:
                        case 15:
                        case 16:
                        case 17:
                        case 18:
                        case 19:
                        case 20:
                            Session.GetHabbo().GOTWPoints += 1;
                            Session.SendMessage(new HabboActivityPointNotificationComposer(Session.GetHabbo().GOTWPoints, 1, 103));
                            Session.SendMessage(RoomNotificationComposer.SendBubble("easteregg", "Acabas de conseguir un Huevo de Pascua, colecciona varios para canjearlos por premios.", ""));
                            break;

                        case 7:
                            ItemData RewardItemPrize = null;
                            if (!RavenEnvironment.GetGame().GetItemManager().GetItem(9780, out RewardItemPrize))
                            {
                                return;
                            }

                            Item GiveItem = ItemFactory.CreateSingleItemNullable(RewardItemPrize, Session.GetHabbo(), "", "");
                            if (GiveItem != null)
                            {
                                Session.GetHabbo().GetInventoryComponent().TryAddItem(GiveItem);
                                Session.SendMessage(new FurniListNotificationComposer(GiveItem.Id, 1));
                                Session.SendMessage(new FurniListUpdateComposer());
                                Session.SendMessage(RoomNotificationComposer.SendBubble("easteregg", "Acabas de recibir un Huevo de Pascua raro.\n\n¡Corre, " + Session.GetHabbo().Username + ", haz click aquí y revisa tu inventario!", "inventory/open"));
                            }

                            Session.GetHabbo().GetInventoryComponent().UpdateItems(true);
                            break;
                        }

                        RavenEnvironment.GetGame().GetAchievementManager().ProgressAchievement(Actor.GetClient(), "ACH_EggCracker", 1);
                    }
                }
            }
        }
 public void GetPattern_ShouldBeNumberInRange1To2()
 {
     RandomNumber random = new RandomNumber();
     Assert.That(random.GetPattern(), Is.InRange(1, 2));
 }
        // Token: 0x060036CE RID: 14030 RVA: 0x000F37B0 File Offset: 0x000F19B0
        public static int ComputeSkillHpModifyValue(BattleProperty attackerProperty, BattleProperty targetProperty, ArmyRelationData armyRelation, ConfigDataSkillInfo skillInfo, bool isCritical, bool isBuffForceMagicDamage, bool isBanMeleePunish, ConfigDataTerrainInfo targetTerrain, int gridDistance, bool isSameTeam, RandomNumber randomNumber, IConfigDataLoader configDataLoader)
        {
            Fix64 value = Fix64.Zero;
            bool  flag  = false;

            if (skillInfo.SkillType == SkillType.SkillType_BF_DamageHeal)
            {
                if (isSameTeam)
                {
                    flag = true;
                }
            }
            else if (skillInfo.IsHealSkill() || skillInfo.IsBuffSkill())
            {
                flag = true;
            }
            if (flag)
            {
                value = BattleFormula.ComputeHealValue(attackerProperty, targetProperty, skillInfo);
            }
            else
            {
                int targetTerrainBonus = 0;
                if (targetTerrain != null)
                {
                    targetTerrainBonus = targetTerrain.BattleBonus;
                }
                int meleePunish = 0;
                if (gridDistance <= 1 && !isBanMeleePunish)
                {
                    meleePunish = configDataLoader.Const_MeleeATKPunish_Mult;
                }
                if (skillInfo.IsMagic)
                {
                    value = -BattleFormula.ComputeMagicDamageValue(attackerProperty, targetProperty, skillInfo, isCritical, targetTerrainBonus, armyRelation.Magic, armyRelation.MagicDefend, meleePunish, false);
                }
                else if (isBuffForceMagicDamage)
                {
                    value = -BattleFormula.ComputeMagicDamageValue(attackerProperty, targetProperty, skillInfo, isCritical, targetTerrainBonus, armyRelation.Attack, armyRelation.MagicDefend, meleePunish, true);
                }
                else
                {
                    value = -BattleFormula.ComputePhysicalDamageValue(attackerProperty, targetProperty, skillInfo, isCritical, targetTerrainBonus, armyRelation.Attack, armyRelation.Defend, meleePunish);
                }
            }
            return((int)((long)Fix64.Round(value)));
        }
Exemple #15
0
        //===========================================================
        // Initialization Function
        //===========================================================

        /// <summary>
        /// Function to Initialize a Default Particle with default settings
        /// </summary>
        /// <param name="Particle">The Particle to be Initialized</param>
        public override void InitializeParticleUsingInitialProperties(DPSFParticle Particle)
        {
            // Cast the Particle to the type it really is
            DefaultQuadParticle cParticle = (DefaultQuadParticle)Particle;

            // Initialize the Particle according to the values specified in the Initial Settings
            base.InitializeParticleUsingInitialProperties(cParticle, mcInitialProperties);

            // If the Rotation should be interpolated between the Min and Max Rotation
            if (mcInitialProperties.InterpolateBetweenMinAndMaxRotation)
            {
                // Calculate the Particle's initial Rotational values
                Vector3 sRotation = Vector3.Lerp(mcInitialProperties.RotationMin, mcInitialProperties.RotationMax, RandomNumber.NextFloat());
                cParticle.Orientation = Quaternion.CreateFromYawPitchRoll(sRotation.Y, sRotation.X, sRotation.Z);
            }
            // Else the Rotation XYZ values should each be calculated individually
            else
            {
                // Calculate the Particle's initial Rotational values
                Vector3 sRotation = DPSFHelper.RandomVectorBetweenTwoVectors(mcInitialProperties.RotationMin, mcInitialProperties.RotationMax);
                cParticle.Orientation = Quaternion.CreateFromYawPitchRoll(sRotation.Y, sRotation.X, sRotation.Z);
            }

            // If the Rotational Velocity should be interpolated between the Min and Max Rotational Velocities
            if (mcInitialProperties.InterpolateBetweenMinAndMaxRotationalVelocity)
            {
                cParticle.RotationalVelocity = Vector3.Lerp(mcInitialProperties.RotationalVelocityMin, mcInitialProperties.RotationalVelocityMax, RandomNumber.NextFloat());
            }
            // Else the Rotational Velocity XYZ values should each be calculated individually
            else
            {
                cParticle.RotationalVelocity = DPSFHelper.RandomVectorBetweenTwoVectors(mcInitialProperties.RotationalVelocityMin, mcInitialProperties.RotationalVelocityMax);
            }

            // If the Rotational Acceleration should be interpolated between the Min and Max Rotational Acceleration
            if (mcInitialProperties.InterpolateBetweenMinAndMaxRotationalAcceleration)
            {
                cParticle.RotationalAcceleration = Vector3.Lerp(mcInitialProperties.RotationalAccelerationMin, mcInitialProperties.RotationalAccelerationMax, RandomNumber.NextFloat());
            }
            // Else the Rotational Acceleration XYZ values should each be calculated individually
            else
            {
                cParticle.RotationalAcceleration = DPSFHelper.RandomVectorBetweenTwoVectors(mcInitialProperties.RotationalAccelerationMin, mcInitialProperties.RotationalAccelerationMax);
            }

            // Calculate the Particle's Width and Height values
            cParticle.StartWidth  = DPSFHelper.RandomNumberBetween(mcInitialProperties.StartSizeMin > 0 ? mcInitialProperties.StartSizeMin : mcInitialProperties.StartWidthMin, mcInitialProperties.StartSizeMax > 0 ? mcInitialProperties.StartSizeMax : mcInitialProperties.StartWidthMax);
            cParticle.EndWidth    = DPSFHelper.RandomNumberBetween(mcInitialProperties.EndSizeMin > 0 ? mcInitialProperties.EndSizeMin : mcInitialProperties.EndWidthMin, mcInitialProperties.EndSizeMax > 0 ? mcInitialProperties.EndSizeMax : mcInitialProperties.EndWidthMax);
            cParticle.StartHeight = DPSFHelper.RandomNumberBetween(mcInitialProperties.StartSizeMin > 0 ? mcInitialProperties.StartSizeMin : mcInitialProperties.StartHeightMin, mcInitialProperties.StartSizeMax > 0 ? mcInitialProperties.StartSizeMax : mcInitialProperties.StartHeightMax);
            cParticle.EndHeight   = DPSFHelper.RandomNumberBetween(mcInitialProperties.EndSizeMin > 0 ? mcInitialProperties.EndSizeMin : mcInitialProperties.EndHeightMin, mcInitialProperties.EndSizeMax > 0 ? mcInitialProperties.EndSizeMax : mcInitialProperties.EndHeightMax);
            cParticle.Width       = cParticle.StartWidth;
            cParticle.Height      = cParticle.StartHeight;
        }
Exemple #16
0
 /// <summary>
 ///     Get a string with every occurence of '#' replaced with a random number.
 /// </summary>
 public static string Numerify(this string s)
 {
     return(Regex.Replace(s, "#", m => RandomNumber.Next(0, 9).ToString(), RegexOptions.Compiled));
 }
Exemple #17
0
        public async Task should_get_conferences_for_today_filtered_by_judge_firstname()
        {
            var venue1 = @"Manchester";
            var venue2 = @"Birmingham";
            var venue3 = @"Luton";

            var participants1 = new List <Participant>
            {
                new Participant(Guid.NewGuid(), "", "firstJudge", "James", "Judge James", "*****@*****.**",
                                UserRole.Judge, ParticipantBuilder.DetermineHearingRole(UserRole.Individual, "Children Act"),
                                "Children Act", $"{RandomNumber.Next()}@hmcts.net", Phone.Number()),
                new Participant(Guid.NewGuid(), "", "firstname", "lastname", "firstname lastname",
                                "*****@*****.**", UserRole.Individual,
                                ParticipantBuilder.DetermineHearingRole(UserRole.Individual, "Children Act"), "Children Act",
                                $"{RandomNumber.Next()}@hmcts.net", Phone.Number())
            };
            var participants2 = new List <Participant>
            {
                new Participant(Guid.NewGuid(), "", "secondJudge", "James II", "SecondJudge James II",
                                "*****@*****.**", UserRole.Judge,
                                ParticipantBuilder.DetermineHearingRole(UserRole.Judge, "Children Act"), "Children Act",
                                $"{RandomNumber.Next()}@hmcts.net", Phone.Number()),
                new Participant(Guid.NewGuid(), "", "individualFirst", "lastname", "individualFirst lastname",
                                "*****@*****.**", UserRole.Individual,
                                ParticipantBuilder.DetermineHearingRole(UserRole.Individual, "Children Act"), "Children Act",
                                $"{RandomNumber.Next()}@hmcts.net",
                                Phone.Number()),
            };
            var participants3 = new List <Participant>
            {
                new Participant(Guid.NewGuid(), "", "firstJudge", "James", "firstJudge James",
                                "*****@*****.**", UserRole.Judge,
                                ParticipantBuilder.DetermineHearingRole(UserRole.Judge, "Children Act"), "Children Act",
                                $"{RandomNumber.Next()}@hmcts.net", Phone.Number()),
                new Participant(Guid.NewGuid(), "", "representativeFirst", "lastname", "representativeFirst lastname",
                                "*****@*****.**", UserRole.Representative,
                                ParticipantBuilder.DetermineHearingRole(UserRole.Representative, "Children Act"), "Children Act",
                                $"{RandomNumber.Next()}@hmcts.net",
                                Phone.Number()),
            };
            var participants4 = new List <Participant>
            {
                new Participant(Guid.NewGuid(), "", "thirdJudge", "James", "thirdJudge James",
                                "*****@*****.**", UserRole.Judge, ParticipantBuilder.DetermineHearingRole(UserRole.Judge, "Children Act"), "Children Act", $"{RandomNumber.Next()}@hmcts.net", Phone.Number()),
                new Participant(Guid.NewGuid(), "", "representativeFirst", "lastname", "representativeFirst lastname",
                                "*****@*****.**", UserRole.Representative, ParticipantBuilder.DetermineHearingRole(UserRole.Representative, "Children Act"), "Children Act", $"{RandomNumber.Next()}@hmcts.net",
                                Phone.Number()),
            };
            var participants5 = new List <Participant>
            {
                new Participant(Guid.NewGuid(), "", "thirdJudge", "James", "thirdJudge James",
                                "*****@*****.**", UserRole.Judge, ParticipantBuilder.DetermineHearingRole(UserRole.Judge, "Children Act"), "Children Act", $"{RandomNumber.Next()}@hmcts.net", Phone.Number()),
                new Participant(Guid.NewGuid(), "", "representativeSecond", "lastname", "representativeSecond lastname",
                                "*****@*****.**", UserRole.Representative, ParticipantBuilder.DetermineHearingRole(UserRole.Representative, "Children Act"), "Children Act",
                                $"{RandomNumber.Next()}@hmcts.net", Phone.Number()),
            };
            var participants6 = new List <Participant>
            {
                new Participant(Guid.NewGuid(), "", "secondJudge", "James II", "SecondJudge James II",
                                "*****@*****.**", UserRole.Judge,
                                ParticipantBuilder.DetermineHearingRole(UserRole.Judge, "Children Act"), "Children Act",
                                $"{RandomNumber.Next()}@hmcts.net", Phone.Number()),
                new Participant(Guid.NewGuid(), "", "representativeThird", "lastname", "representativeThird lastname",
                                "*****@*****.**", UserRole.Representative,
                                ParticipantBuilder.DetermineHearingRole(UserRole.Representative, "Children Act"), "Children Act",
                                $"{RandomNumber.Next()}@hmcts.net",
                                Phone.Number()),
            };

            var conference1 = new ConferenceBuilder(true, venueName: venue1)
                              .WithParticipants(participants1)
                              .WithMeetingRoom("https://poc.node.com", "*****@*****.**")
                              .Build();

            _newConferenceId1 = conference1.Id;

            var conference2 = new ConferenceBuilder(true, venueName: venue1)
                              .WithParticipants(participants2)
                              .WithMeetingRoom("https://poc.node.com", "*****@*****.**")
                              .Build();

            _newConferenceId2 = conference2.Id;

            var conference3 = new ConferenceBuilder(true, venueName: venue2)
                              .WithParticipants(participants3)
                              .WithMeetingRoom("https://poc.node.com", "*****@*****.**")
                              .Build();

            _newConferenceId3 = conference3.Id;

            var conference4 = new ConferenceBuilder(true, venueName: venue2)
                              .WithParticipants(participants4)
                              .WithMeetingRoom("https://poc.node.com", "*****@*****.**")
                              .Build();

            _newConferenceId4 = conference4.Id;

            var conference5 = new ConferenceBuilder(true, venueName: venue3)
                              .WithParticipants(participants5)
                              .WithMeetingRoom("https://poc.node.com", "*****@*****.**")
                              .Build();

            _newConferenceId5 = conference5.Id;

            var conference6 = new ConferenceBuilder(true, venueName: venue3)
                              .WithParticipants(participants6)
                              .WithMeetingRoom("https://poc.node.com", "*****@*****.**")
                              .Build();

            _newConferenceId6 = conference6.Id;

            await TestDataManager.SeedConference(conference1);

            await TestDataManager.SeedConference(conference2);

            await TestDataManager.SeedConference(conference3);

            await TestDataManager.SeedConference(conference4);

            await TestDataManager.SeedConference(conference5);

            await TestDataManager.SeedConference(conference6);

            var result = await _handler.Handle(new GetConferencesTodayForAdminQuery
            {
                UserNames = new List <string> {
                    participants1[0].FirstName, participants4[0].FirstName
                }
            });

            result.Should().NotBeEmpty();
            result.Count.Should().Be(4);
            result.Should().BeInAscendingOrder(c => c.ScheduledDateTime);

            result[0].Participants.FirstOrDefault(x => x.UserRole == UserRole.Judge)?.FirstName.Should()
            .Be(participants1[0].FirstName);
            result[1].Participants.FirstOrDefault(x => x.UserRole == UserRole.Judge)?.FirstName.Should()
            .Be(participants1[0].FirstName);
            result[2].Participants.FirstOrDefault(x => x.UserRole == UserRole.Judge)?.FirstName.Should()
            .Be(participants4[0].FirstName);
            result[3].Participants.FirstOrDefault(x => x.UserRole == UserRole.Judge)?.FirstName.Should()
            .Be(participants4[0].FirstName);

            TestContext.WriteLine("Cleaning conferences for GetConferencesTodayForAdminQueryHandler");
            await TestDataManager.RemoveConference(_newConferenceId1);

            await TestDataManager.RemoveConference(_newConferenceId2);

            await TestDataManager.RemoveConference(_newConferenceId3);

            await TestDataManager.RemoveConference(_newConferenceId4);

            await TestDataManager.RemoveConference(_newConferenceId5);

            await TestDataManager.RemoveConference(_newConferenceId6);
        }
        public BookNewConferenceRequestBuilder WithJudge(string firstName = null)
        {
            var participant = Builder <ParticipantRequest> .CreateNew()
                              .With(x => x.Name             = $"Automation_{Name.First()}{RandomNumber.Next()}")
                              .With(x => x.FirstName        = $"Automation_{Name.First()}")
                              .With(x => x.LastName         = $"Automation_{Name.Last()}")
                              .With(x => x.DisplayName      = $"Automation_{Internet.UserName()}")
                              .With(x => x.UserRole         = UserRole.Judge)
                              .With(x => x.HearingRole      = "Judge")
                              .With(x => x.ParticipantRefId = Guid.NewGuid())
                              .With(x => x.ContactEmail     = $"Automation_Video_APi_{RandomNumber.Next()}@email.com")
                              .With(x => x.Username         = $"Automation_Video_APi_{RandomNumber.Next()}@username.com")
                              .Build();

            if (!string.IsNullOrWhiteSpace(firstName))
            {
                participant.FirstName = firstName;
            }

            _bookNewConferenceRequest.Participants.Add(participant);

            return(this);
        }
Exemple #19
0
        static string _differentEmail(string firstName, string lastName)
        {
            string[] different = new string[] { "kontakt.pl", "contact.com", "info.com", "mojafirma.pl" };
            string[] domen     = new string[] { ".pl", ".com" };
            string[] contact   = new string[] { "kontakt", "contact", "info", "mojafirma" };

            try
            {
                if (_draw())
                {
                    if (_draw())
                    {
                        if (_draw())
                        {
                            return($"{firstName}@{different[RandomNumber.Draw(0, different.Length - 1)]}");
                        }
                        else
                        {
                            return($"{lastName}@{different[RandomNumber.Draw(0, different.Length - 1)]}");
                        }
                    }
                    else
                    {
                        if (_draw())
                        {
                            return($"{firstName}{lastName}@{different[RandomNumber.Draw(0, different.Length - 1)]}");
                        }
                        else
                        {
                            return($"{lastName}{firstName}@{different[RandomNumber.Draw(0, different.Length - 1)]}");
                        }
                    }
                }
                else
                {
                    if (_draw())
                    {
                        if (_draw())
                        {
                            return($"{firstName}@{lastName}{domen[RandomNumber.Draw(0, domen.Length - 1)]}");
                        }
                        else
                        {
                            return($"{lastName}@{firstName}{domen[RandomNumber.Draw(0, domen.Length - 1)]}");
                        }
                    }
                    else
                    {
                        if (_draw())
                        {
                            return($"{contact[RandomNumber.Draw(0, contact.Length - 1)]}@{firstName}{lastName}{domen[RandomNumber.Draw(0, domen.Length - 1)]}");
                        }
                        else
                        {
                            return($"{contact[RandomNumber.Draw(0, contact.Length - 1)]}@{lastName}{firstName}{domen[RandomNumber.Draw(0, domen.Length - 1)]}");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.log(e);
                return(null);
            }
        }
        public void RandomChaptersTest(int numChapters, int minNumParagraphsPerChapter, int maxNumParagraphsPerChapter,
                                       int minNumSentencesPerParagraph, int maxNumSentencesPerParagraph,
                                       string pChapterHeadings)
        {
            RandomNumber   rn            = new RandomNumber();
            RandomDocument rd            = new RandomDocument();
            int            numParagraphs = 0;
            string         chap          = string.Empty;

            string[] chapterHeadings   = null;
            int      chapHeadingInx    = -1;
            int      chapHeadingMaxInx = -1;

            try
            {
                _msg.Length = 0;
                _msg.Append("RandomChaptersTest started ...\r\n");
                Program._messageLog.WriteLine(_msg.ToString());

                if (pChapterHeadings.Trim().Length > 0)
                {
                    chapterHeadings   = pChapterHeadings.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                    chapHeadingMaxInx = chapterHeadings.Length - 1;
                }

                chapHeadingInx = -1;
                for (int ch = 0; ch < numChapters; ch++)
                {
                    numParagraphs = rn.GenerateRandomInt(minNumParagraphsPerChapter, maxNumParagraphsPerChapter);
                    if (chapterHeadings == null)
                    {
                        _str.Length = 0;
                        _str.Append("Chapter ");
                        _str.Append((ch + 1).ToString());
                        _str.Append(Environment.NewLine);
                        _str.Append(Environment.NewLine);
                        chap = rd.GenerateChapter(numParagraphs, minNumSentencesPerParagraph, maxNumSentencesPerParagraph);
                        _str.Append(chap);
                        chap = _str.ToString();
                    }
                    else
                    {
                        chapHeadingInx++;
                        if (chapHeadingInx > chapHeadingMaxInx)
                        {
                            //More chapters are being generated than there are defined chapter headings
                            _str.Length = 0;
                            _str.Append("Chapter ");
                            _str.Append((ch + 1).ToString());
                            chap = rd.GenerateChapter(_str.ToString(), numParagraphs, minNumSentencesPerParagraph, maxNumSentencesPerParagraph);
                        }
                        else
                        {
                            chap = rd.GenerateChapter(chapterHeadings[chapHeadingInx], numParagraphs, minNumSentencesPerParagraph, maxNumSentencesPerParagraph);
                        }
                    }
                    Program._messageLog.WriteLine(chap);
                }
            }
            catch (System.Exception ex)
            {
                _msg.Length = 0;
                _msg.Append(AppGlobals.AppMessages.FormatErrorMessage(ex));
                Program._messageLog.WriteLine(_msg.ToString());
                AppMessages.DisplayErrorMessage(_msg.ToString(), _saveErrorMessagesToAppLog);
            }
            finally
            {
                _msg.Length = 0;
                _msg.Append("\r\n... RandomChaptersTest finished.");
                Program._messageLog.WriteLine(_msg.ToString());
            }
        }
Exemple #21
0
 private static string _getDomen()
 {
     Logger.emailDomain();
     return(_popularEmail[RandomNumber.Draw(0, _popularEmail.Length - 1)]);
 }
        public override void OnUserSay(RoomUser User, string Message)
        {
            if (User == null)
            {
                return;
            }

            RoomUser Pet = GetRoomUser();

            if (Pet == null)
            {
                return;
            }

            if (Pet.PetData.DBState != DatabaseUpdateState.NeedsInsert)
            {
                Pet.PetData.DBState = DatabaseUpdateState.NeedsUpdate;
            }

            if (Message.ToLower().Equals(Pet.PetData.Name.ToLower()))
            {
                Pet.SetRot(Rotation.Calculate(Pet.X, Pet.Y, User.X, User.Y), false);
                return;
            }

            //if (!Pet.Statusses.ContainsKey("gst thr"))
            //    Pet.Statusses.Add("gst, TextHandling.GetString(Pet.Z));

            if ((Message.ToLower().StartsWith(Pet.PetData.Name.ToLower() + " ") && User.GetClient().GetHabbo().Username.ToLower() == Pet.PetData.OwnerName.ToLower()) || (Message.ToLower().StartsWith(Pet.PetData.Name.ToLower() + " ") && BiosEmuThiago.GetGame().GetChatManager().GetPetCommands().TryInvoke(Message.Substring(Pet.PetData.Name.ToLower().Length + 1)) == 8))
            {
                string Command = Message.Substring(Pet.PetData.Name.ToLower().Length + 1);

                int r = RandomNumber.GenerateRandom(1, 8); // Made Random
                if (Pet.PetData.Energy > 10 && r < 6 || Pet.PetData.Level > 15 || BiosEmuThiago.GetGame().GetChatManager().GetPetCommands().TryInvoke(Command) == 8)
                {
                    RemovePetStatus(); // Remove Status

                    switch (BiosEmuThiago.GetGame().GetChatManager().GetPetCommands().TryInvoke(Command))
                    {
                        // TODO - Level you can use the commands at...



                        #region free

                    case 1:
                        RemovePetStatus();

                        //int randomX = BiosEmuThiago.GetRandomNumber(0, GetRoom().Model.MapSizeX);
                        //int randomY = BiosEmuThiago.GetRandomNumber(0, GetRoom().Model.MapSizeY);
                        Point nextCoord = GetRoom().GetGameMap().GetRandomWalkableSquare();
                        Pet.MoveTo(nextCoord.X, nextCoord.Y);

                        Pet.PetData.Addexperience(10);     // Give XP

                        break;

                        #endregion

                        #region here

                    case 2:

                        RemovePetStatus();

                        int NewX = User.X;
                        int NewY = User.Y;

                        ActionTimer = 30;     // Reset ActionTimer

                        #region Rotation

                        if (User.RotBody == 4)
                        {
                            NewY = User.Y + 1;
                        }
                        else if (User.RotBody == 0)
                        {
                            NewY = User.Y - 1;
                        }
                        else if (User.RotBody == 6)
                        {
                            NewX = User.X - 1;
                        }
                        else if (User.RotBody == 2)
                        {
                            NewX = User.X + 1;
                        }
                        else if (User.RotBody == 3)
                        {
                            NewX = User.X + 1;
                            NewY = User.Y + 1;
                        }
                        else if (User.RotBody == 1)
                        {
                            NewX = User.X + 1;
                            NewY = User.Y - 1;
                        }
                        else if (User.RotBody == 7)
                        {
                            NewX = User.X - 1;
                            NewY = User.Y - 1;
                        }
                        else if (User.RotBody == 5)
                        {
                            NewX = User.X - 1;
                            NewY = User.Y + 1;
                        }

                        #endregion

                        Pet.PetData.Addexperience(10);     // Give XP

                        Pet.MoveTo(NewX, NewY);
                        break;

                        #endregion

                        #region sit

                    case 3:
                        // Remove Status
                        RemovePetStatus();

                        Pet.PetData.Addexperience(10);     // Give XP

                        // Add Status
                        Pet.Statusses.Add("sit", TextHandling.GetString(Pet.Z));
                        Pet.UpdateNeeded = true;

                        ActionTimer = 25;
                        EnergyTimer = 10;
                        break;

                        #endregion

                        #region lay

                    case 4:
                        // Remove Status
                        RemovePetStatus();

                        // Add Status
                        Pet.Statusses.Add("lay", TextHandling.GetString(Pet.Z));
                        Pet.UpdateNeeded = true;

                        Pet.PetData.Addexperience(10);     // Give XP

                        ActionTimer = 30;
                        EnergyTimer = 5;
                        break;

                        #endregion

                        #region dead

                    case 5:
                        // Remove Status
                        RemovePetStatus();

                        // Add Status
                        Pet.Statusses.Add("ded", TextHandling.GetString(Pet.Z));
                        Pet.UpdateNeeded = true;

                        Pet.PetData.Addexperience(10);     // Give XP

                        // Don't move to speak for a set amount of time.
                        SpeechTimer = 45;
                        ActionTimer = 30;

                        break;

                        #endregion

                        #region sleep

                    case 6:
                        // Remove Status
                        RemovePetStatus();

                        Pet.Chat("ZzzZZZzzzzZzz", false);
                        Pet.Statusses.Add("lay", TextHandling.GetString(Pet.Z));
                        Pet.UpdateNeeded = true;

                        Pet.PetData.Addexperience(10);     // Give XP

                        // Don't move to speak for a set amount of time.
                        EnergyTimer = 5;
                        SpeechTimer = 30;
                        ActionTimer = 45;
                        break;

                        #endregion

                        #region jump

                    case 7:
                        // Remove Status
                        RemovePetStatus();

                        // Add Status
                        Pet.Statusses.Add("jmp", TextHandling.GetString(Pet.Z));
                        Pet.UpdateNeeded = true;

                        Pet.PetData.Addexperience(10);     // Give XP

                        // Don't move to speak for a set amount of time.
                        EnergyTimer = 5;
                        SpeechTimer = 10;
                        ActionTimer = 5;
                        break;

                        #endregion

                        #region breed
                    case 46:

                        break;
                        #endregion

                    default:
                        string[] Speech = BiosEmuThiago.GetGame().GetChatManager().GetPetLocale().GetValue("pet.unknowncommand");

                        Pet.Chat(Speech[RandomNumber.GenerateRandom(0, Speech.Length - 1)], false);
                        break;
                    }
                    Pet.PetData.PetEnergy(false); // Remove Energy
                }
                else
                {
                    RemovePetStatus(); // Remove Status

                    if (Pet.PetData.Energy < 10)
                    {
                        //GetRoomUser refers to the pet
                        //User refers to Owner

                        RoomUser UserRiding = GetRoom().GetRoomUserManager().GetRoomUserByVirtualId(Pet.HorseID);;

                        if (UserRiding.RidingHorse)
                        {
                            Pet.Chat("Getof my sit", false);
                            UserRiding.RidingHorse = false;
                            Pet.RidingHorse        = false;
                            UserRiding.ApplyEffect(-1);
                            UserRiding.MoveTo(new Point(GetRoomUser().X + 1, GetRoomUser().Y + 1));
                        }

                        string[] Speech = BiosEmuThiago.GetGame().GetChatManager().GetPetLocale().GetValue("pet.tired");

                        var RandomSpeech = new Random();
                        Pet.Chat(Speech[RandomNumber.GenerateRandom(0, Speech.Length - 1)], false);

                        Pet.Statusses.Add("lay", TextHandling.GetString(Pet.Z));
                        Pet.UpdateNeeded = true;

                        SpeechTimer = 50;
                        ActionTimer = 45;
                        EnergyTimer = 5;
                    }
                    else
                    {
                        string[] Speech = BiosEmuThiago.GetGame().GetChatManager().GetPetLocale().GetValue("pet.lazy");

                        var RandomSpeech = new Random();
                        Pet.Chat(Speech[RandomNumber.GenerateRandom(0, Speech.Length - 1)], false);

                        Pet.PetData.PetEnergy(false); // Remove Energy
                    }
                }
            }
            //Pet = null;
        }
 public static int GetRandomNumber(int Min, int Max)
 {
     return(RandomNumber.GenerateNewRandom(Min, Max));
 }
Exemple #24
0
 private void Start()
 {
     board  = GetComponent <DungeonBoard>();
     random = GetComponent <RandomNumber>();
 }
        public JudiciaryPersonBuilder(Guid?externalRefId = null)
        {
            var settings = new BuilderSettings();

            _judiciaryPerson = new Builder(settings).CreateNew <JudiciaryPerson>().WithFactory(() =>
                                                                                               new JudiciaryPerson(
                                                                                                   externalRefId ?? Guid.NewGuid(),
                                                                                                   $"{RandomNumber.Next(0, 1000)}",
                                                                                                   Name.Prefix(),
                                                                                                   $"Automation_{Name.First()}",
                                                                                                   $"Automation_{Name.Last()}",
                                                                                                   Name.FullName(),
                                                                                                   $"{RandomNumber.Next(1000, 100000)}",
                                                                                                   $"Automation_{RandomNumber.Next()}@hmcts.net"
                                                                                                   , false))
                               .Build();
        }
        // Used to generate random smoke particles around the floor
        public void InitializeParticleFoggySmoke(DefaultSprite3DBillboardParticle cParticle)
        {
            cParticle.Lifetime = RandomNumber.Between(1.0f, 3.0f);

            cParticle.Position  = Emitter.PositionData.Position;
            cParticle.Position += new Vector3(RandomNumber.Next(-500, 500), 0, RandomNumber.Next(-500, 500));
            cParticle.Size      = RandomNumber.Next(10, 25);
            cParticle.Color     = msaColors[miCurrentColor];
            cParticle.Rotation  = RandomNumber.Between(0, MathHelper.TwoPi);

            cParticle.Velocity           = new Vector3(RandomNumber.Next(-30, 30), RandomNumber.Next(0, 10), RandomNumber.Next(-30, 30));
            cParticle.Acceleration       = Vector3.Zero;
            cParticle.RotationalVelocity = RandomNumber.Between(-MathHelper.Pi, MathHelper.Pi);

            cParticle.StartSize = cParticle.Size;

            mfColorBlendAmount = 0.5f;
        }
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            int Data1      = Packet.PopInt(); // ELEMENTO 1
            int Data2      = Packet.PopInt(); // ELEMENTO 2
            int Data3      = Packet.PopInt(); // ELEMENTO 3
            int Data4      = Packet.PopInt(); // SELECTOR
            var RewardName = "";
            var NuxGift    = RavenEnvironment.GetGame().GetNuxUserGiftsListManager().NuxUserGiftsList;

            switch (Data4)
            {
            case 0:
                switch (NuxGift.Type[0])
                {
                case "diamonds":
                    string[] Posibility = NuxGift.Reward[0].Split(',');

                    int Posibility1 = int.Parse(Posibility[0]);
                    int Posibility2 = int.Parse(Posibility[1]);

                    int RewardDiamonds           = RandomNumber.GenerateRandom(Posibility1, Posibility2);
                    Session.GetHabbo().Diamonds += RewardDiamonds;
                    Session.SendMessage(new HabboActivityPointNotificationComposer(Session.GetHabbo().Diamonds, RewardDiamonds, 5));
                    break;

                case "honor":
                    string[] Posibilitya = NuxGift.Reward[0].Split(',');

                    int Posibility1a = int.Parse(Posibilitya[0]);
                    int Posibility2a = int.Parse(Posibilitya[1]);

                    int RewardHonor = RandomNumber.GenerateRandom(Posibility1a, Posibility2a);
                    Session.GetHabbo().GOTWPoints += RewardHonor;
                    Session.SendMessage(new HabboActivityPointNotificationComposer(Session.GetHabbo().GOTWPoints, RewardHonor, 103));
                    break;

                case "item":
                    int      RewardItem = RandomNumber.GenerateRandom(1, 10);
                    string[] Furnis     = NuxGift.Reward[0].Split(',');

                    string[] Present  = Furnis[0].Split(':');
                    string[] Present1 = Furnis[1].Split(':');
                    string[] Present2 = Furnis[2].Split(':');
                    string[] Present3 = Furnis[3].Split(':');
                    string[] Present4 = Furnis[4].Split(':');
                    string[] Present5 = Furnis[5].Split(':');
                    string[] Present6 = Furnis[6].Split(':');
                    string[] Present7 = Furnis[7].Split(':');
                    string[] Present8 = Furnis[8].Split(':');
                    string[] Present9 = Furnis[9].Split(':');

                    var RewardItemId = 0;

                    switch (RewardItem)
                    {
                    case 1:
                        RewardItemId = int.Parse(Present[0]);             // VIP - club_sofa
                        RewardName   = Present[1];
                        break;

                    case 2:
                        RewardItemId = int.Parse(Present1[0]);             // VIP - club_sofa
                        RewardName   = Present1[1];
                        break;

                    case 3:
                        RewardItemId = int.Parse(Present2[0]);             // VIP - club_sofa
                        RewardName   = Present2[1];
                        break;

                    case 4:
                        RewardItemId = int.Parse(Present3[0]);             // VIP - club_sofa
                        RewardName   = Present3[1];
                        break;

                    case 5:
                        RewardItemId = int.Parse(Present4[0]);             // VIP - club_sofa
                        RewardName   = Present4[1];
                        break;

                    case 6:
                        RewardItemId = int.Parse(Present5[0]);             // VIP - club_sofa
                        RewardName   = Present5[1];
                        break;

                    case 7:
                        RewardItemId = int.Parse(Present6[0]);             // VIP - club_sofa
                        RewardName   = Present6[1];
                        break;

                    case 8:
                        RewardItemId = int.Parse(Present7[0]);             // VIP - club_sofa
                        RewardName   = Present7[1];
                        break;

                    case 9:
                        RewardItemId = int.Parse(Present8[0]);             // VIP - club_sofa
                        RewardName   = Present8[1];
                        break;

                    case 10:
                        RewardItemId = int.Parse(Present9[0]);             // VIP - club_sofa
                        RewardName   = Present9[1];
                        break;
                    }

                    ItemData Item = null;
                    if (!RavenEnvironment.GetGame().GetItemManager().GetItem(RewardItemId, out Item))
                    {
                        return;
                    }

                    Item GiveItem = ItemFactory.CreateSingleItemNullable(Item, Session.GetHabbo(), "", "");
                    if (GiveItem != null)
                    {
                        Session.GetHabbo().GetInventoryComponent().TryAddItem(GiveItem);
                        Session.SendMessage(RoomNotificationComposer.SendBubble("image2", "Acabas de recibir un " + RewardName + ".\n\n¡Corre, " + Session.GetHabbo().Username + ", revisa tu inventario, hay algo nuevo al parecer!", "inventory/open/furni"));
                        Session.SendMessage(new FurniListNotificationComposer(GiveItem.Id, 1));
                        Session.SendMessage(new FurniListUpdateComposer());
                    }

                    Session.GetHabbo().GetInventoryComponent().UpdateItems(false);
                    break;
                }
                break;

            case 1:
                switch (NuxGift.Type[1])
                {
                case "diamonds":
                    string[] Posibility = NuxGift.Reward[1].Split(',');

                    int Posibility1 = int.Parse(Posibility[0]);
                    int Posibility2 = int.Parse(Posibility[1]);

                    int RewardDiamonds           = RandomNumber.GenerateRandom(Posibility1, Posibility2);
                    Session.GetHabbo().Diamonds += RewardDiamonds;
                    Session.SendMessage(new HabboActivityPointNotificationComposer(Session.GetHabbo().Diamonds, RewardDiamonds, 5));
                    break;

                case "honor":
                    string[] Posibilitya = NuxGift.Reward[1].Split(',');

                    int Posibility1a = int.Parse(Posibilitya[0]);
                    int Posibility2a = int.Parse(Posibilitya[1]);

                    int RewardHonor = RandomNumber.GenerateRandom(Posibility1a, Posibility2a);
                    Session.GetHabbo().GOTWPoints += RewardHonor;
                    Session.SendMessage(new HabboActivityPointNotificationComposer(Session.GetHabbo().GOTWPoints, RewardHonor, 103));
                    break;

                case "item":
                    int      RewardItem = RandomNumber.GenerateRandom(1, 10);
                    string[] Furnis     = NuxGift.Reward[1].Split(',');

                    string[] Present  = Furnis[0].Split(':');
                    string[] Present1 = Furnis[1].Split(':');
                    string[] Present2 = Furnis[2].Split(':');
                    string[] Present3 = Furnis[3].Split(':');
                    string[] Present4 = Furnis[4].Split(':');
                    string[] Present5 = Furnis[5].Split(':');
                    string[] Present6 = Furnis[6].Split(':');
                    string[] Present7 = Furnis[7].Split(':');
                    string[] Present8 = Furnis[8].Split(':');
                    string[] Present9 = Furnis[9].Split(':');

                    var RewardItemId = 0;

                    switch (RewardItem)
                    {
                    case 1:
                        RewardItemId = int.Parse(Present[0]);             // VIP - club_sofa
                        RewardName   = Present[1];
                        break;

                    case 2:
                        RewardItemId = int.Parse(Present1[0]);             // VIP - club_sofa
                        RewardName   = Present1[1];
                        break;

                    case 3:
                        RewardItemId = int.Parse(Present2[0]);             // VIP - club_sofa
                        RewardName   = Present2[1];
                        break;

                    case 4:
                        RewardItemId = int.Parse(Present3[0]);             // VIP - club_sofa
                        RewardName   = Present3[1];
                        break;

                    case 5:
                        RewardItemId = int.Parse(Present4[0]);             // VIP - club_sofa
                        RewardName   = Present4[1];
                        break;

                    case 6:
                        RewardItemId = int.Parse(Present5[0]);             // VIP - club_sofa
                        RewardName   = Present5[1];
                        break;

                    case 7:
                        RewardItemId = int.Parse(Present6[0]);             // VIP - club_sofa
                        RewardName   = Present6[1];
                        break;

                    case 8:
                        RewardItemId = int.Parse(Present7[0]);             // VIP - club_sofa
                        RewardName   = Present7[1];
                        break;

                    case 9:
                        RewardItemId = int.Parse(Present8[0]);             // VIP - club_sofa
                        RewardName   = Present8[1];
                        break;

                    case 10:
                        RewardItemId = int.Parse(Present9[0]);             // VIP - club_sofa
                        RewardName   = Present9[1];
                        break;
                    }

                    ItemData Item = null;
                    if (!RavenEnvironment.GetGame().GetItemManager().GetItem(RewardItemId, out Item))
                    {
                        return;
                    }

                    Item GiveItem = ItemFactory.CreateSingleItemNullable(Item, Session.GetHabbo(), "", "");
                    if (GiveItem != null)
                    {
                        Session.GetHabbo().GetInventoryComponent().TryAddItem(GiveItem);
                        Session.SendMessage(RoomNotificationComposer.SendBubble("image2", "Acabas de recibir un " + RewardName + ".\n\n¡Corre, " + Session.GetHabbo().Username + ", revisa tu inventario, hay algo nuevo al parecer!", "inventory/open/furni"));
                        Session.SendMessage(new FurniListNotificationComposer(GiveItem.Id, 1));
                        Session.SendMessage(new FurniListUpdateComposer());
                    }

                    Session.GetHabbo().GetInventoryComponent().UpdateItems(false);
                    break;
                }
                break;

            case 2:
                switch (NuxGift.Type[2])
                {
                case "diamonds":
                    string[] Posibility = NuxGift.Reward[2].Split(',');

                    int Posibility1 = int.Parse(Posibility[0]);
                    int Posibility2 = int.Parse(Posibility[1]);

                    int RewardDiamonds           = RandomNumber.GenerateRandom(Posibility1, Posibility2);
                    Session.GetHabbo().Diamonds += RewardDiamonds;
                    Session.SendMessage(new HabboActivityPointNotificationComposer(Session.GetHabbo().Diamonds, RewardDiamonds, 5));
                    break;

                case "honor":
                    string[] Posibilitya = NuxGift.Reward[2].Split(',');

                    int Posibility1a = int.Parse(Posibilitya[0]);
                    int Posibility2a = int.Parse(Posibilitya[1]);

                    int RewardHonor = RandomNumber.GenerateRandom(Posibility1a, Posibility2a);
                    Session.GetHabbo().GOTWPoints += RewardHonor;
                    Session.SendMessage(new HabboActivityPointNotificationComposer(Session.GetHabbo().GOTWPoints, RewardHonor, 103));
                    break;

                case "item":
                    int      RewardItem = RandomNumber.GenerateRandom(1, 10);
                    string[] Furnis     = NuxGift.Reward[2].Split(',');

                    string[] Present  = Furnis[0].Split(':');
                    string[] Present1 = Furnis[1].Split(':');
                    string[] Present2 = Furnis[2].Split(':');
                    string[] Present3 = Furnis[3].Split(':');
                    string[] Present4 = Furnis[4].Split(':');
                    string[] Present5 = Furnis[5].Split(':');
                    string[] Present6 = Furnis[6].Split(':');
                    string[] Present7 = Furnis[7].Split(':');
                    string[] Present8 = Furnis[8].Split(':');
                    string[] Present9 = Furnis[9].Split(':');

                    var RewardItemId = 0;

                    switch (RewardItem)
                    {
                    case 1:
                        RewardItemId = int.Parse(Present[0]);             // VIP - club_sofa
                        RewardName   = Present[1];
                        break;

                    case 2:
                        RewardItemId = int.Parse(Present1[0]);             // VIP - club_sofa
                        RewardName   = Present1[1];
                        break;

                    case 3:
                        RewardItemId = int.Parse(Present2[0]);             // VIP - club_sofa
                        RewardName   = Present2[1];
                        break;

                    case 4:
                        RewardItemId = int.Parse(Present3[0]);             // VIP - club_sofa
                        RewardName   = Present3[1];
                        break;

                    case 5:
                        RewardItemId = int.Parse(Present4[0]);             // VIP - club_sofa
                        RewardName   = Present4[1];
                        break;

                    case 6:
                        RewardItemId = int.Parse(Present5[0]);             // VIP - club_sofa
                        RewardName   = Present5[1];
                        break;

                    case 7:
                        RewardItemId = int.Parse(Present6[0]);             // VIP - club_sofa
                        RewardName   = Present6[1];
                        break;

                    case 8:
                        RewardItemId = int.Parse(Present7[0]);             // VIP - club_sofa
                        RewardName   = Present7[1];
                        break;

                    case 9:
                        RewardItemId = int.Parse(Present8[0]);             // VIP - club_sofa
                        RewardName   = Present8[1];
                        break;

                    case 10:
                        RewardItemId = int.Parse(Present9[0]);             // VIP - club_sofa
                        RewardName   = Present9[1];
                        break;
                    }

                    ItemData Item = null;
                    if (!RavenEnvironment.GetGame().GetItemManager().GetItem(RewardItemId, out Item))
                    {
                        return;
                    }

                    Item GiveItem = ItemFactory.CreateSingleItemNullable(Item, Session.GetHabbo(), "", "");
                    if (GiveItem != null)
                    {
                        Session.GetHabbo().GetInventoryComponent().TryAddItem(GiveItem);
                        Session.SendMessage(RoomNotificationComposer.SendBubble("image2", "Acabas de recibir un " + RewardName + ".\n\n¡Corre, " + Session.GetHabbo().Username + ", revisa tu inventario, hay algo nuevo al parecer!", "inventory/open/furni"));
                        Session.SendMessage(new FurniListNotificationComposer(GiveItem.Id, 1));
                        Session.SendMessage(new FurniListUpdateComposer());
                    }

                    Session.GetHabbo().GetInventoryComponent().UpdateItems(false);
                    break;
                }
                break;
            }
        }
Exemple #28
0
        public void InitializeParticleExplosion(DefaultSprite3DBillboardTextureCoordinatesParticle particle)
        {
            particle.Lifetime = 0.2f;
            particle.Color    = ExplosionColor;
            particle.Position = Emitter.PositionData.Position + new Vector3(RandomNumber.Next(-15, 15), RandomNumber.Next(-15, 15), RandomNumber.Next(-15, 15));
            particle.Size     = particle.StartSize = 1;
            particle.EndSize  = ExplosionParticleSize;

            // Randomly pick which texture coordinates to use for this particle
            Rectangle textureCoordinates;

            switch (RandomNumber.Next(0, 4))
            {
            default:
            case 0: textureCoordinates = _flash1TextureCoordinates; break;

            case 1: textureCoordinates = _flash2TextureCoordinates; break;

            case 2: textureCoordinates = _flash3TextureCoordinates; break;

            case 3: textureCoordinates = _flash4TextureCoordinates; break;
            }

            particle.SetTextureCoordinates(textureCoordinates);
        }
Exemple #29
0
 public void Next_MinValue_MaxValue_WithMultipleThreads()
 {
     RunMultithreaded(() => RandomNumber.Next(-34, 42));
 }
Exemple #30
0
        private BeginSurveyViewModel GenerateBeginSurveyModel(IEnumerable <Answer> answers)
        {
            var options     = new List <OptionViewModel>();
            var photos      = _photoService.ListValidSurveyPhotos().ToList();
            var photoBuffer = new List <Photo>();

            do
            {
                var   randomIndex = RandomNumber.Between(0, photos.Count - 1);
                Photo sortedPhoto = photos.ElementAt(randomIndex);

                var   shouldSortAgain = false;
                var   isSecondOne     = photos.Count % 2 != 0;
                Photo previousPhoto   = photoBuffer.LastOrDefault();
                if (isSecondOne)
                {
                    if (previousPhoto == null)
                    {
                        throw new InvalidOperationException();
                    }

                    shouldSortAgain = previousPhoto.Elected == sortedPhoto.Elected;
                }

                if (shouldSortAgain)
                {
                    continue;
                }

                photoBuffer.Add(sortedPhoto);
                var optionViewModel = new OptionViewModel()
                {
                    PhotoId     = sortedPhoto.Idphoto,
                    Base64Photo = Convert.ToBase64String(sortedPhoto.FileContents)
                };

                options.Add(optionViewModel);
                photos.Remove(sortedPhoto);
            } while (photos.Any());

            var beginSurvey = new BeginSurveyViewModel();

            var savedValueAnswers     = new List <Valueanswer>();
            var optionVIewModelList   = new List <OptionViewModel>();
            var questionViewModelList = new List <QuestionViewModel>();

            foreach (Answer answer in answers)
            {
                var question = new QuestionViewModel {
                    AnswerId = answer.Idanswer
                };
                questionViewModelList.Add(question);

                for (var i = 0; i < Constants.TotalOptions; i++)
                {
                    OptionViewModel optionsViewModel = options.PopAt(0);

                    Valueanswer valueAnswer = GenerateValueAnswer(optionsViewModel, answer);

                    _context.Valueanswer.Add(valueAnswer);
                    question.Options.Add(optionsViewModel);
                    savedValueAnswers.Add(valueAnswer);
                    optionVIewModelList.Add(optionsViewModel);
                    // optionsViewModel.ValueAnswerId = valueAnswer.Idvalueanswer;
                }
            }

            _context.SaveChanges();

            foreach (QuestionViewModel question in questionViewModelList)
            {
                var firstOption  = optionVIewModelList.PopAt(0);
                var secondOption = optionVIewModelList.PopAt(0);

                var firstValueAnswer  = savedValueAnswers.PopAt(0);
                var secondValueAnswer = savedValueAnswers.PopAt(0);

                firstOption.ValueAnswerId  = firstValueAnswer.Idvalueanswer;
                secondOption.ValueAnswerId = secondValueAnswer.Idvalueanswer;

                question.Options = new List <OptionViewModel> {
                    firstOption, secondOption
                };

                beginSurvey.Questions.Add(question);
            }


            beginSurvey.Questions = beginSurvey.Questions.OrderBy(d => d.AnswerId).ToList();
            return(beginSurvey);
        }
Exemple #31
0
 public void NextDouble_Multithreaded()
 {
     RunMultithreaded(() => RandomNumber.NextDouble());
 }
Exemple #32
0
 // Use this for initialization
 void Start()
 {
     orgScale            = transform.localScale;
     orgRotation         = transform.rotation;
     _randNumberBehavior = this.GetComponent <RandomNumber>();
 }
Exemple #33
0
        public Tuple <int, int, int[], List <double[]> > TrainNet(List <double[]> trainingData, int maxIter, int seed, int initialWtCount)
        {
            int dataSetSize = trainingData.Count;

            int[] randomArray = RandomNumber.RandomizeNumberOrder(dataSetSize, seed); //randomize order of trn set

            // bool skippedBecauseFull;
            int[] inputCategory = new int[dataSetSize]; //stores the winning OP node for each current  input signal
            int[] prevCategory  = new int[dataSetSize]; //stores the winning OP node for each previous input signal
            this.InitialiseWtArrays(trainingData, randomArray, initialWtCount);

            //{********* GO THROUGH THE TRAINING SET for 1 to MAX ITERATIONS *********}
            //repeat //{training set until max iter or trn set learned}
            int[] opNodeWins      = null;  //stores the number of times each OP node wins
            int   iterNum         = 0;
            bool  trainSetLearned = false; //     : boolean;

            while (!trainSetLearned && iterNum < maxIter)
            {
                iterNum++;
                opNodeWins = new int[this.OPSize];      //stores the number of times each OP node wins

                //initialise convergence criteria.  Want stable F2node allocations
                trainSetLearned = true;
                int changedCategory = 0;

                //{READ AND PROCESS signals until end of the data file}
                for (int sigNum = 0; sigNum < dataSetSize; sigNum++)
                {
                    //select an input signal. Later use sigID to enable test of convergence
                    int sigID = sigNum; // do signals in order
                    if (RandomiseTrnSetOrder)
                    {
                        sigID = randomArray[sigNum]; //pick at random
                    }

                    //{*********** PASS ONE INPUT SIGNAL THROUGH THE NETWORK ***********}
                    double[] OP        = this.PropagateIP2OP(trainingData[sigID]); //output = AND divided by OR of two vectors
                    int      index     = DataTools.GetMaxIndex(OP);
                    double   winningOP = OP[index];

                    //create new category if similarity OP of best matching node is too low
                    if (winningOP < this.VigilanceRho)
                    {
                        this.ChangeWtsOfFirstUncommittedNode(trainingData[sigID]);
                    }

                    inputCategory[sigID] = index; //winning F2 node for current input
                    opNodeWins[index]++;

                    //{test if training set is learned ie each signal is classified to the same F2 node as previous iteration}
                    if (inputCategory[sigID] != prevCategory[sigID])
                    {
                        trainSetLearned = false;
                        changedCategory++;
                    }
                } //end loop over all signal inputs

                //set the previous categories
                for (int x = 0; x < dataSetSize; x++)
                {
                    prevCategory[x] = inputCategory[x];
                }

                //remove committed F2 nodes that are not having wins
                for (int j = 0; j < this.OPSize; j++)
                {
                    if (this.committedNode[j] && opNodeWins[j] == 0)
                    {
                        this.committedNode[j] = false;
                    }
                }

                if (Verbose)
                {
                    LoggedConsole.WriteLine(" iter={0:D2}  committed=" + this.CountCommittedF2Nodes() + "\t changedCategory=" + changedCategory, iterNum);
                }

                if (trainSetLearned)
                {
                    break;
                }
            } //end of while (! trainSetLearned or (iterNum < maxIter) or terminate);

            return(Tuple.Create(iterNum, this.CountCommittedF2Nodes(), inputCategory, this.wts));
        } //TrainNet()
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            int Quality = Convert.ToInt32(txtQuantity.Text);

            lblResult.Text = "";
            if (Avaiable_Product >= Quality)
            {
                int          TotalCount = chk.int32Check("select count(*) from Barcode where s_id=" + S_ID + " and p_id=" + P_ID);
                RandomNumber ran        = new RandomNumber();
                settings     set        = new settings();
                ran.Number        = true;
                ran.HowMuchNumber = set.Get_InValue_Settings(16);
                string GeneratID = ran.RandomStringNumber("Barcode");
                bool   auto = false; bool manual = false;
                if ((Avaiable_Product - TotalCount) >= Quality && chkAutomatic.Checked && txtQuantity.Text != "")
                {
                    for (int i = 0; i < Quality; i++)
                    {
                        string Code = ran.RandomStringNumber("Barcode");
                        MakeBarcode.Add(new BarcodeStore()
                        {
                            ID          = GeneratID,
                            Amount      = Convert.ToInt32(txtAmount.Text),
                            Barcode     = Code,
                            p_id        = P_ID,
                            s_id        = S_ID,
                            ProductName = Request.QueryString["p"].ToString(),
                            DateTime    = DateTime.Now.ToString()
                        });
                    }
                    showBarCodes();
                    auto   = true;
                    manual = false;
                }
                else if (!chkAutomatic.Checked && txtManualBarcode.Text != "")
                {
                    string Code = txtManualBarcode.Text;
                    if (chk.int32Check("select count(*) from Barcode where BarCode='" + Code + "' ") == 0)
                    {
                        int  limit = Avaiable_Product - TotalCount; int find = 0;
                        bool codeMatch = false;
                        foreach (BarcodeStore b in MakeBarcode)
                        {
                            if (b.p_id == P_ID && b.s_id == S_ID)
                            {
                                find++;
                            }
                            if (Code == b.Barcode)
                            {
                                codeMatch = true;
                            }
                        }
                        if (limit > find && codeMatch)
                        {
                            MakeBarcode.Add(new BarcodeStore()
                            {
                                ID          = GeneratID,
                                Amount      = Convert.ToInt32(txtAmount.Text),
                                Barcode     = Code,
                                p_id        = P_ID,
                                s_id        = S_ID,
                                ProductName = Request.QueryString["p"].ToString(),
                                DateTime    = DateTime.Now.ToString(),
                                ManualMode  = true
                            });
                            showBarCodes();
                        }
                        else
                        {
                            lblResult.Text = "<div class='alert alert-danger'>You can't add already all iteams are avaiable or Code matched Clear manual code.</div>";
                        }
                    }
                    else
                    {
                        lblResult.Text = "<div class='alert alert-danger'>This Barcode is avaiable other products try another code.</div>";
                    }
                }
                else
                {
                    lblResult.Text = "<div class='alert alert-danger'>Already BarCode is avaiable. You can add " + (Avaiable_Product - TotalCount) + " Items.</div>";
                }
            }
            else
            {
                lblResult.Text = "<div class='alert alert-danger'>Your Quality is over the Maximam</div>";
            }
        }
 public void GetOperand_ShouldBeNumberInRange1To9()
 {
     RandomNumber random = new RandomNumber();
     Assert.That(random.GetOperand(), Is.InRange(1, 9));
 }