Ejemplo n.º 1
0
        public void ParseSignature_returns_parts()
        {
            var(tx, app) = Duo.ParseSignature("tx:app");

            Assert.Equal("tx", tx);
            Assert.Equal("app", app);
        }
        void IFilterConsumer.SetFilter(object sender, SetFilterEventArgs e)
        {
            string lastName = null;

            string []     arr;
            List <string> names = new List <string> ();

            foreach (string pair in e.FilterExpression.Split(new char [] { '&' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (((arr = pair.Split(new char [] { '=' }, StringSplitOptions.RemoveEmptyEntries))).Length > 1)
                {
                    if (lastName == null)
                    {
                        names.Add(lastName = string.Join("=", arr, 1, arr.Length - 1));
                    }
                    else
                    {
                        filterValues [lastName] = string.Join("=", arr, 1, arr.Length - 1);
                        lastName = null;
                    }
                }
            }
            Fields = new Duo <string [], string []> (names.ToArray(), names.ToArray());
            if ((--consumersWaiting) == 0)
            {
                PartCommunicationMain();
            }
        }
Ejemplo n.º 3
0
        public void DownloadFrame_returns_html_document()
        {
            var flow = new RestFlow().Post("<html></html>");
            var html = Duo.DownloadFrame("tx", flow);

            Assert.Equal("<html></html>", html.DocumentNode.InnerHtml);
        }
 void IParametersOutConsumer.ParametersOutProviderInit(object sender, ParametersOutProviderInitEventArgs e)
 {
     if ((paramOutProps = e.ParameterOutProperties) != null)
     {
         Fields = new Duo <string [], string []> (Array.ConvertAll <ParameterOutProperty, string> (paramOutProps, (pop) => {
             return(pop.ParameterName);
         }), Array.ConvertAll <ParameterOutProperty, string> (paramOutProps, (pop) => {
             return(pop.ParameterDisplayName);
         }));
     }
 }
Ejemplo n.º 5
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = Overall.GetHashCode();
         hashCode = hashCode * 397 ^ (Solo != null ? Solo.GetHashCode() : 0);
         hashCode = hashCode * 397 ^ (Duo != null ? Duo.GetHashCode() : 0);
         hashCode = hashCode * 397 ^ (Trio != null ? Trio.GetHashCode() : 0);
         hashCode = hashCode * 397 ^ (Squad != null ? Squad.GetHashCode() : 0);
         hashCode = hashCode * 397 ^ (Ltm != null ? Ltm.GetHashCode() : 0);
         return(hashCode);
     }
 }
Ejemplo n.º 6
0
        internal static Image GetDisabledImage(Color backColor, Image image)
        {
            Duo <Color, Image> key    = new Duo <Color, Image>(backColor, image);
            Bitmap             bitmap = null;

            if ((image != null) && !disabledImages.TryGetValue(key, out bitmap))
            {
                disabledImages[key] = bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    graphics.Clear(backColor);
                    ControlPaint.DrawImageDisabled(graphics, image, 0, 0, backColor);
                }
            }
            return(bitmap);
        }
Ejemplo n.º 7
0
        public Duo<List<SliceInfo>> Slice(double[] pulseSequence, IList<int> crestIndices) {
            if (crestIndices.Count <= 1) throw new SliceException();
            var tuple = Group(crestIndices);
            var sliceLength = Ruler.MeasureSliceLength(crestIndices, pulseSequence.Length);
            IList<int> startIndices1, startIndices2;

            var crestOffset = Aligner.CrestIndex(_minPtsCntBeforeCrest, sliceLength);
            if (
                SimpleSlicer.FindStartIndices(pulseSequence, tuple.Item1, sliceLength, crestOffset, out startIndices1) &&
                SimpleSlicer.FindStartIndices(pulseSequence, tuple.Item2, sliceLength, crestOffset, out startIndices2)) {
                return Duo.Create(startIndices1, startIndices2)
                    .Select(ints => ints.Select(i => new SliceInfo(i, sliceLength, crestOffset)).ToList())
                    .ToDuo();
            }
            throw new SliceException();
        }
 void IFilterProvider.FilterConsumerInit(object sender, FilterConsumerInitEventArgs e)
 {
     Fields = new Duo <string [], string []> (e.FieldList, e.FieldDisplayList);
 }
Ejemplo n.º 9
0
 internal static string FormatFileSize(Duo <double, FileSize> fileSize)
 {
     return(string.Format("{0} {1}", fileSize.Value1.Equals((double)((long)fileSize.Value1)) ? ((long)fileSize.Value1).ToString() : fileSize.Value1.ToString("N2"), fileSize.Value2));
 }
Ejemplo n.º 10
0
 static public bool StartWith <T>(Duo <T> duo, T node, IEqualityComparer <T> eq)
 {
     return(eq.Equals(duo.Item1, node));
 }
Ejemplo n.º 11
0
 static public bool EndWith <T>(Duo <T> duo, T node, IEqualityComparer <T> eq)
 {
     return(EndWith(duo as Tuple <T, T>, node, eq));
 }
        public override InitEventArgs GetInitEventArgs(string interfaceName)
        {
            Duo <string[], string[]> fields = this.Fields;

            if (((fields == null) || (fields.Value1 == null)) || (fields.Value1.Length == 0))
            {
                fields = new Duo <string[], string[]>(new string[] { interfaceName }, new string[] { interfaceName });
            }
            if (interfaceName == "ICellConsumer")
            {
                return(new CellConsumerInitEventArgs {
                    FieldDisplayName = "ICellConsumer", FieldName = "ICellConsumer"
                });
            }
            if (interfaceName == "IFilterConsumer")
            {
                return(new FilterConsumerInitEventArgs {
                    FieldList = fields.Value1, FieldDisplayList = fields.Value2
                });
            }
            if (interfaceName == "IParametersInConsumer")
            {
                ParameterInProperty[] propertyArray = new ParameterInProperty[fields.Value1.Length];
                for (int i = 0; i < propertyArray.Length; i++)
                {
                    propertyArray[i] = new ParameterInProperty {
                        Description = (fields.Value2.Length > i) ? ((string)fields.Value2[i]) : ((string)fields.Value1[i]), ParameterDisplayName = (fields.Value2.Length > i) ? ((string)fields.Value2[i]) : ((string)fields.Value1[i]), ParameterName = fields.Value1[i], Required = false
                    };
                }
                return(new ParametersInConsumerInitEventArgs {
                    ParameterInProperties = propertyArray
                });
            }
            if (interfaceName == "ICellProvider")
            {
                return(new CellProviderInitEventArgs {
                    FieldName = "ICellProvider", FieldDisplayName = "ICellProvider"
                });
            }
            if (interfaceName == "IListProvider")
            {
                return(new ListProviderInitEventArgs {
                    FieldList = fields.Value1, FieldDisplayList = fields.Value2
                });
            }
            if (interfaceName == "IParametersOutProvider")
            {
                ParameterOutProperty[] propertyArray2 = new ParameterOutProperty[fields.Value1.Length];
                for (int j = 0; j < propertyArray2.Length; j++)
                {
                    propertyArray2[j] = new ParameterOutProperty {
                        Description = (fields.Value2.Length > j) ? ((string)fields.Value2[j]) : ((string)fields.Value1[j]), ParameterDisplayName = (fields.Value2.Length > j) ? ((string)fields.Value2[j]) : ((string)fields.Value1[j]), ParameterName = fields.Value1[j]
                    };
                }
                return(new ParametersOutProviderInitEventArgs {
                    ParameterOutProperties = propertyArray2
                });
            }
            if (interfaceName == "IRowProvider")
            {
                return(new RowProviderInitEventArgs {
                    FieldList = fields.Value1, FieldDisplayList = fields.Value2
                });
            }
            return(base.GetInitEventArgs(interfaceName));
        }
Ejemplo n.º 13
0
        public void DownloadFrame_throws_on_network_error()
        {
            var flow = new RestFlow().Post("", HttpStatusCode.BadRequest);

            Exceptions.AssertThrowsInternalError(() => Duo.DownloadFrame("tx", flow));
        }
Ejemplo n.º 14
0
 public void ParseSignature_throws_on_invalid_signature(string invalid)
 {
     Exceptions.AssertThrowsInternalError(() => Duo.ParseSignature(invalid), "signature is invalid");
 }
 void IRowConsumer.RowProviderInit(object sender, RowProviderInitEventArgs e)
 {
     Fields = new Duo <string [], string []> (e.FieldList, e.FieldDisplayList);
 }
        public override InitEventArgs GetInitEventArgs(string interfaceName)
        {
            Duo <string [], string []> fields = Fields;

            ParameterInProperty []  pips;
            ParameterOutProperty [] pops;
            if ((fields == null) || (fields.Value1 == null) || (fields.Value1.Length == 0))
            {
                fields = new Duo <string [], string []> (new string [] { interfaceName }, new string [] { interfaceName });
            }
            if (interfaceName == "ICellConsumer")
            {
                return new CellConsumerInitEventArgs()
                       {
                           FieldDisplayName = "ICellConsumer", FieldName = "ICellConsumer"
                       }
            }
            ;
            if (interfaceName == "IFilterConsumer")
            {
                return new FilterConsumerInitEventArgs()
                       {
                           FieldList = fields.Value1, FieldDisplayList = fields.Value2
                       }
            }
            ;
            if (interfaceName == "IParametersInConsumer")
            {
                pips = new ParameterInProperty [fields.Value1.Length];

                for (int i = 0; i < pips.Length; i++)
                {
                    pips [i] = new ParameterInProperty()
                    {
                        Description = ((fields.Value2.Length > i) ? fields.Value2 [i] : fields.Value1 [i]), ParameterDisplayName = ((fields.Value2.Length > i) ? fields.Value2 [i] : fields.Value1 [i]), ParameterName = fields.Value1 [i], Required = false
                    }
                }
                ;
                return(new ParametersInConsumerInitEventArgs()
                {
                    ParameterInProperties = pips
                });
            }
            if (interfaceName == "ICellProvider")
            {
                return new CellProviderInitEventArgs()
                       {
                           FieldName = "ICellProvider", FieldDisplayName = "ICellProvider"
                       }
            }
            ;
            if (interfaceName == "IListProvider")
            {
                return new ListProviderInitEventArgs()
                       {
                           FieldList = fields.Value1, FieldDisplayList = fields.Value2
                       }
            }
            ;
            if (interfaceName == "IParametersOutProvider")
            {
                pops = new ParameterOutProperty [fields.Value1.Length];

                for (int i = 0; i < pops.Length; i++)
                {
                    pops [i] = new ParameterOutProperty()
                    {
                        Description = ((fields.Value2.Length > i) ? fields.Value2 [i] : fields.Value1 [i]), ParameterDisplayName = ((fields.Value2.Length > i) ? fields.Value2 [i] : fields.Value1 [i]), ParameterName = fields.Value1 [i]
                    }
                }
                ;
                return(new ParametersOutProviderInitEventArgs()
                {
                    ParameterOutProperties = pops
                });
            }
            if (interfaceName == "IRowProvider")
            {
                return new RowProviderInitEventArgs()
                       {
                           FieldList = fields.Value1, FieldDisplayList = fields.Value2
                       }
            }
            ;
            return(base.GetInitEventArgs(interfaceName));
        }
Ejemplo n.º 17
0
        public async Task SetRankAsync(string mode, string teamSize)
        {
            if (!(Context.User is IGuildUser guildUser))
            {
                return;
            }

            using var state = Context.Channel.EnterTypingState();

            var nickname = guildUser.Nickname ?? guildUser.Username;

            PlayerModel model;

            try
            {
                model = await _battlegroundsService.GetPlayerStats(nickname);
            }
            catch (HttpRequestException ex)
            {
                await ReplyAsync(ex.Message);

                return;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }


            switch (mode.ToLower())
            {
            case "fpp":
                break;

            case "tpp":
                break;

            default:
                await ReplyAsync("Incorrect mode, use tpp or fpp.");

                return;
            }

            int team = 4;

            switch (teamSize.ToLower())
            {
            case "squad":
                team = 4;
                break;

            case "duo":
                team = 2;
                break;

            case "solo":
                await ReplyAsync("Solo doesn't count.");

                return;

            default:
                await ReplyAsync("Incorrect team size, use duo or squad.");

                return;
            }

            Duo playerData = null;

            switch (mode)
            {
            case "fpp":
            {
                if (team == 4)
                {
                    playerData = model.Data.Attributes.GameModeStats.SquadFpp;
                }
                else if (team == 2)
                {
                    playerData = model.Data.Attributes.GameModeStats.DuoFpp;
                }
                else
                {
                    return;
                }

                break;
            }

            case "tpp":
            {
                if (team == 4)
                {
                    playerData = model.Data.Attributes.GameModeStats.SoloFpp;
                }
                else if (team == 2)
                {
                    playerData = model.Data.Attributes.GameModeStats.Duo;
                }
                else
                {
                    return;
                }
                break;
            }

            default:
                return;
            }

            if (playerData.RoundsPlayed == 0)
            {
                await ReplyAsync("***No games played!***");

                return;
            }

            var roleIds  = guildUser.RoleIds.Intersect(RoleIds);
            var oldRoles = Context.Guild.Roles.Where(t => roleIds.Contains(t.Id));

            await guildUser.RemoveRolesAsync(oldRoles); // remove any old role

            long  gamesPlayed = playerData.Losses + playerData.Wins;
            float winRate     = (float)playerData.Wins / gamesPlayed * 100;
            float kd          = (float)playerData.Kills / playerData.Losses;
            var   newRoleIds  = GetRoles(playerData.RankPoints, winRate, kd);
            var   newRoles    = Context.Guild.Roles.Where(t => newRoleIds.Contains(t.Id));

            string description = "You've got these roles:\n";

            int i = 0;

            foreach (var role in newRoles)
            {
                i++;
                description += $"{role.Mention}\n";
            }

            if (i == 0)
            {
                description = String.Empty;
            }

            await guildUser.AddRolesAsync(newRoles);

            var embedBuilder = new EmbedBuilder()
                               .WithColor(Color.Orange)
                               .WithAuthor(mode.ToUpper() + " " + teamSize.ToUpper(), "http://www.csie.ase.ro/Media/Default/images/Statistics_logo.png")
                               .WithTitle($"Statistics for {nickname}")
                               .WithDescription($"{guildUser.Mention}\n{description}")
                               .AddField("Rating:", Math.Round(playerData.RankPoints, 0), true)
                               .AddField("Games played:", playerData.Wins + playerData.Losses, true)
                               .AddField("Victories:", playerData.Wins, true)
                               .AddField("WR:", $"{Math.Round(winRate, 2)}%", true)
                               .AddField("ADR:", Math.Round(playerData.DamageDealt / gamesPlayed, 1), true)
                               .AddField("KDR:", Math.Round(kd, 2), true)
                               .WithThumbnailUrl(Context.Guild.IconUrl)
                               .WithCurrentTimestamp()
                               .WithFooter("Source: https://api.playbattlegrounds.com", "https://png.icons8.com/ios/1600/bot.png");

            await ReplyAsync(embed : embedBuilder.Build());
        }
Ejemplo n.º 18
0
        internal static string Login(string username,
                                     byte[] passwordHash,
                                     string deviceId,
                                     IUi ui,
                                     ISecureStorage storage,
                                     RestClient rest)
        {
            // Try simple password login, potentially with a stored second factor token if
            // "remember me" was used before.
            var rememberMeOptions = GetRememberMeOptions(storage);
            var response          = RequestAuthToken(username, passwordHash, deviceId, rememberMeOptions, rest);

            // Simple password login (no 2FA) succeeded
            if (response.AuthToken != null)
            {
                return(response.AuthToken);
            }

            var secondFactor = response.SecondFactor;

            if (secondFactor.Methods == null || secondFactor.Methods.Count == 0)
            {
                throw new InternalErrorException("Expected a non empty list of available 2FA methods");
            }

            // We had a "remember me" token saved, but the login failed anyway. This token is not valid anymore.
            if (rememberMeOptions != null)
            {
                EraseRememberMeToken(storage);
            }

            var      method   = ChooseSecondFactorMethod(secondFactor, ui);
            var      extra    = secondFactor.Methods[method];
            Passcode passcode = null;

            switch (method)
            {
            case Response.SecondFactorMethod.GoogleAuth:
                passcode = ui.ProvideGoogleAuthPasscode();
                break;

            case Response.SecondFactorMethod.Email:
                // When only the email 2FA present, the email is sent by the server right away.
                // Trigger only when other methods are present.
                if (secondFactor.Methods.Count != 1)
                {
                    TriggerEmailMfaPasscode(username, passwordHash, rest);
                }

                passcode = ui.ProvideEmailPasscode((string)extra["Email"] ?? "");
                break;

            case Response.SecondFactorMethod.Duo:
            case Response.SecondFactorMethod.DuoOrg:
            {
                var duo = Duo.Authenticate((string)extra["Host"] ?? "",
                                           (string)extra["Signature"] ?? "",
                                           ui,
                                           rest.Transport);

                if (duo != null)
                {
                    passcode = new Passcode(duo.Passcode, duo.RememberMe);
                }

                break;
            }

            case Response.SecondFactorMethod.YubiKey:
                passcode = ui.ProvideYubiKeyPasscode();
                break;

            case Response.SecondFactorMethod.U2f:
                passcode = AskU2fPasscode(JObject.Parse((string)extra["Challenge"]), ui);
                break;

            default:
                throw new UnsupportedFeatureException($"2FA method {method} is not supported");
            }

            // We're done interacting with the UI
            ui.Close();

            if (passcode == null)
            {
                throw MakeCancelledMfaError();
            }

            var secondFactorResponse = RequestAuthToken(username,
                                                        passwordHash,
                                                        deviceId,
                                                        new SecondFactorOptions(method,
                                                                                passcode.Code,
                                                                                passcode.RememberMe),
                                                        rest);

            // Password + 2FA is successful
            if (secondFactorResponse.AuthToken != null)
            {
                SaveRememberMeToken(secondFactorResponse, storage);
                return(secondFactorResponse.AuthToken);
            }

            throw new BadMultiFactorException("Second factor code is not correct");
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Returns the optimal card in 'PlayerHandCards' to discard.
        /// There will always be a valid card returned, no need for null checks
        /// </summary>
        public static Card GetCardToDiscard(List <Card> PlayerHandCards, List <Single> singleLayDownCards, bool HasLaidDown, ref List <string> thoughts)
        {
            var possibleDiscards = new List <Card>(PlayerHandCards);

            // Try to keep the best combo and known singles on hand for laying down later
            if (!HasLaidDown)
            {
                possibleDiscards = KeepUsableCards(PlayerHandCards, singleLayDownCards, ref thoughts);
            }

            // Don't allow discarding joker cards unless they're all that's left
            var jokerCards = possibleDiscards.Where(c => c.IsJoker());

            if (possibleDiscards.Count == jokerCards.Count())
            {
                return(jokerCards.First());
            }

            possibleDiscards = possibleDiscards.Except(jokerCards).ToList();

            // Check for duo sets&runs in the remaining cards
            // and keep them on hand, if possible (only for >3 cards, because
            // keeping a duo and discarding the third card makes no sense)
            if (possibleDiscards.Count > 3)
            {
                var laidDownCards = Tb.I.GameMaster.GetAllCardSpotCards();
                var allDuos       = CardUtil.GetAllDuoSets(possibleDiscards, laidDownCards, ref thoughts);
                allDuos.AddRange(CardUtil.GetAllDuoRuns(possibleDiscards, laidDownCards, ref thoughts));

                // Only save unique duos
                var duos = new List <Duo>();
                for (int i = 0; i < allDuos.Count; i++)
                {
                    var canAdd = true;
                    foreach (var duo in duos)
                    {
                        if (Duo.AreHalfDuplicates(allDuos[i], duo))
                        {
                            canAdd = false;
                            break;
                        }
                    }
                    if (canAdd)
                    {
                        duos.Add(allDuos[i]);
                    }
                }

                // Keep high value duos if the player has yet to lay down any cards
                duos = (HasLaidDown ? duos.OrderBy(duo => duo.Value) : duos.OrderByDescending(duo => duo.Value)).ToList();

                var keptDuos    = new List <Duo>();
                var notKeptDuos = new List <Duo>();
                foreach (var duo in duos)
                {
                    if (possibleDiscards.Except(duo.GetList()).Count() >= 1)
                    {
                        possibleDiscards.Remove(duo.A);
                        possibleDiscards.Remove(duo.B);
                        keptDuos.Add(duo);
                    }
                    else
                    {
                        notKeptDuos.Add(duo);
                    }
                }
                if (keptDuos.Count > 0)
                {
                    thoughts.Add(keptDuos.GetListMsg("Keep duo"));
                }
                if (notKeptDuos.Count > 0)
                {
                    thoughts.Add(notKeptDuos.GetListMsg("Cannot keep duo"));
                }
            }

            // Discard the card with the highest value
            return(possibleDiscards.OrderByDescending(c => c.Value).First());
        }