/// <summary>
 /// Fabrique le IMatch de la QuidditchDataAccessLayerBaseDeDonnees
 /// </summary>
 /// <param name="match">Match de la QuidditchBusinessLayer</param>
 /// <returns>Le match pour la QuidditchDataAccessLayerBaseDeDonnees</returns>
 public static QuidditchDataAccessLayerBaseDeDonnees.IMatch FabriquerMatch(IMatch match)
 {
     IList<QuidditchDataAccessLayerBaseDeDonnees.IReservation> reservations = new List<QuidditchDataAccessLayerBaseDeDonnees.IReservation>();
     return new MatchDal(match.Identifiant, match.DateDuMatch, FabriqueArbitre.FabriquerArbitre(match.ArbitreDuMatch),
         FabriqueStade.FabriquerStade(match.StadeDuMatch), reservations, FabriqueEquipe.FabriquerEquipe(match.EquipeDomicile),
         FabriqueEquipe.FabriquerEquipe(match.EquipeVisiteur), match.ScoreEquipeDomicile, match.ScoreEquipeVisiteur);
 }
Example #2
0
        static void ExecTest(Context context, IMatch testToken)
        {
            var token = new CaptureGroup(testToken);

            if(token.Match(context))
            {
                WriteInfo("Match success.");
                WriteLine(context);

                while (token.MatchNext(context))
                {
                    WriteInfo("MatchNext success.");
                    WriteLine(context);
                }
                WriteError("MatchNext failed.");
                WriteLine(context);
            }
            else
            {
                WriteError("Match failed.");
                WriteLine(context);
            }

            if (context.offset != 0)
                WriteError("Warning: Context offset not reset to 0.");
        }
        public MatchRunner(IMatch match, string playerOneFolder, string playerTwoFolder, IRenderer renderer, bool consoleLoggingDisabled, bool consoleLoggingMustScroll, string replayFolder)
        {
            Match = match;
            Renderer = renderer;

            string runFilename = Environment.OSVersion.Platform == PlatformID.Unix ? Settings.Default.BotRunFilenameLinux : Settings.Default.BotRunFilename;
            _players = new BotRunner[2];
            _players[0] = new BotRunner(
                1,
                playerOneFolder,
                runFilename
                );
            _players[1] = new BotRunner(
                2,
                playerTwoFolder,
                runFilename
                );

            match.SetPlayerName(1, _players[0].PlayerName);
            match.SetPlayerName(2, _players[1].PlayerName);

            _replayLogger = new ReplayLogger(replayFolder);

            SetupLogging(consoleLoggingDisabled, consoleLoggingMustScroll);
        }
 /// <summary>
 /// Fabrique le IMatch de la BusinessLayer
 /// </summary>
 /// <param name="match">Match de la PresentationLayerWPF</param>
 /// <returns>Le match pour la businessLayer</returns>
 public static QuidditchBusinessLayer.IMatch FabriquerMatch(IMatch match)
 {
     return new MatchBusiness(match.Identifiant, match.DateDuMatch, FabriqueArbitre.FabriquerArbitre(match.ArbitreDuMatch),
         FabriqueStade.FabriquerStade(match.StadeDuMatch), FabriqueEquipe.FabriquerEquipe(match.EquipeDomicile), 
         FabriqueEquipe.FabriquerEquipe(match.EquipeVisiteur),
         match.ScoreEquipeDomicile, match.ScoreEquipeVisiteur);
 }
Example #5
0
        public Lexer()
            : base(error => new SyntaxError((IssueId) error))
        {
            var alpha = Match.Letter.Else("_");
            var symbol1 = "({[)}];,".AnyChar();
            var textFrame = "'\"".AnyChar();
            var symbol = "°^!²§³$%&/=?\\@€*+~><|:.-".AnyChar();

            var identifier = (alpha + alpha.Else(Match.Digit).Repeat()).Else(symbol.Repeat(1));

            _any = symbol1.Else(identifier);

            _whiteSpaces = Match.WhiteSpace.Repeat(1);

            _comment =
                ("#" + " \t".AnyChar() + Match.LineEnd.Find)
                    .Else("#(" + Match.WhiteSpace + (Match.WhiteSpace + ")#").Find)
                    .Else("#(" + _any.Value(id => (Match.WhiteSpace + id + ")#").Box().Find))
                    .Else("#(" + Match.End.Find + _invalidComment)
                    .Else("#" + Match.End.Find + _invalidLineComment)
                ;

            _number = Match.Digit.Repeat(1);

            _text = textFrame.Value
            (
                head =>
                {
                    var textEnd = head.Else(Match.LineEnd + _invalidTextEnd);
                    return textEnd.Find + (head + textEnd.Find).Repeat();
                });
        }
Example #6
0
        Lexer()
            : base(error => new ScannerSyntaxError((IssueId) error))
        {
            var alpha = Match.Letter.Else("_");
            var symbol1 = SingleCharSymbol.AnyChar();
            var textFrame = "'\"".AnyChar();
            var symbol = Symbols.AnyChar();

            var identifier = (alpha + alpha.Else(Match.Digit).Repeat()).Else(symbol.Repeat(1));

            _any = symbol1.Else(identifier);

            _lineEnd = "\r\n".Box().Else("\n".Box()).Else("\r" + Match.End);
            _lineEndOrEnd = _lineEnd.Else(Match.End);

            _lineComment = "#"
                +
                _lineEndOrEnd
                    .Else
                    (
                        "(".AnyChar().Not +
                        _lineEnd.Find
                            .Else(Match.End.Find)
                    );

            _whiteSpace = " \t".AnyChar();
            _comment = "#("
                +
                (Match.WhiteSpace + (Match.WhiteSpace + ")#").Find)
                    .Else(identifier.Value(id => (Match.WhiteSpace + id + ")#").Box().Find))
                    .Else(Match.End.Find + _invalidComment)
                ;

            _commentHead = "#(" + Match.WhiteSpace.Else(identifier);

            _number = Match.Digit.Repeat(1);

            var varbatimText = "@("
                    +
                    (Match.WhiteSpace + (Match.WhiteSpace + ")@").Find)
                        .Else(identifier.Value(id => (Match.WhiteSpace + id + ")@").Box().Find))
                        .Else(Match.End.Find + _invalidTextEnd)
                ;

            _varbatimTextHead = "@(" + Match.WhiteSpace.Else(identifier);
            _text = textFrame.Value
                (
                    head =>
                    {
                        var textEnd = head.Else(_lineEndOrEnd + _invalidTextEnd);
                        return textEnd.Find + (head + textEnd.Find).Repeat();
                    })
                .Else(varbatimText);

            LineCommentItem = new LexerItem(new WhiteSpaceTokenType(), LineComment);
            CommentItem = new LexerItem(new WhiteSpaceTokenType(), Comment);
            LineEndItem = new LexerItem(new WhiteSpaceTokenType(), LineEnd);
            WhiteSpaceItem = new LexerItem(new WhiteSpaceTokenType(), WhiteSpace);
        }
Example #7
0
        private static EMElement CreateDecoration(IMatch match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var decorationMatch = match as EMDecorationMatch;

            var element = new EMDecorationElement(doc, origin, parent, decorationMatch.Type);
            element.Content.Parse(decorationMatch.ContentStart, decorationMatch.Content, data);

            return element;
        }
        public void AddMatch(IMatch match)
        {
            if (!this.teams.Contains(match.HomeTeam) || !this.teams.Contains(match.HomeTeam))
                throw new ArgumentOutOfRangeException(nameof(match), "Team is not in Table");

            this.matches.Add(match);
            this.results[match.HomeTeam].AddMatch(match, match.HomeTeam);
            this.results[match.ForeignTeam].AddMatch(match, match.ForeignTeam);
        }
Example #9
0
 public Lexer()
 {
     var alpha = Match.Letter.Else("_");
     var symbol1 = "({[)}];,".AnyChar();
     var symbol = "°^!²§³$%&/=?\\@€*+~><|:.-".AnyChar();
     var identifier = (alpha + alpha.Else(Match.Digit).Repeat()).Else(symbol.Repeat(1));
     _any = symbol1.Else(identifier);
     _whiteSpaces = Match.WhiteSpace.Repeat(1);
     _number = Match.Digit.Repeat(1);
 }
Example #10
0
        public void AddMatch(IMatch match)
        {
            lock (_lockInternalMatches)
              {
            if (match == null)
              throw new ArgumentNullException("match");

            if (match.Result != MatchStatus.Match)
              return;

            InternalMatches.Add(match);
              }
        }
Example #11
0
 public static Model.Match MatchMapper(IMatch match, CodeAnalyzerContainer context)
 {
     return new Model.Match
       {
     LineNumber        = match.LineNumber,
     CodeExtract       = match.CodeExtract,
     RootDirectoryPath = match.RootDirectoryPath,
     Filename          = match.Filename,
     Batch             = BatchMapper(match.Batch, context),
     Status            = (int)match.Result,
         RuleDeclaration   = RuleDeclarationMapper(match.RuleDeclarationRef, context),
       };
 }
Example #12
0
        /// <summary>
        /// Checks whether the matches are symmetric, 
        /// i.e. are covering the same spot in the graph with a permutation of the pattern to graph mapping; 
        /// that might be the case if they are matches of a pattern which is automorph to itself.
        /// This function is employed by the generated automorph filters for rule \ auto.
        /// Ths subpattern derivations must be structurally identical, modulo permutations of matches of the same subpattern type.
        /// </summary>
        /// <param name="this_">The one match to check for being symmetric to the other</param>
        /// <param name="that">The other match to check for being symmetric to the one match</param>
        /// <param name="graph">The graph in which the matches were found</param>
        /// <returns>True if the matches are symmetric, i.e. covering the same spot in the graph, otherwise false.</returns>
        public static bool AreSymmetric(IMatch this_, IMatch that, IGraph graph)
        {
#if LOG_MATCHES
            Console.WriteLine("match this: " + MatchPrinter.ToString(this_, graph, ""));
            Console.WriteLine("match that: " + MatchPrinter.ToString(that, graph, ""));
#endif
            if(this_.Pattern != that.Pattern)
                return false;

            int id = Mark(this_, graph);
            bool allElementsWereMarked = AreAllMarked(that, graph, id);
            Unmark(this_, graph, id);
            if(!allElementsWereMarked)
                return false;

            // if we'd know there was no hom used, locally and in the subpatterns employed, we could get along without this counter direction check, which is needed to reject containment
            id = Mark(that, graph);
            allElementsWereMarked = AreAllMarked(this_, graph, id);
            Unmark(that, graph, id);
            if(!allElementsWereMarked)
                return false;

            // locally the match this_ was a permutation of the match that
            // now check globally the nested and subpatterns
            
            // independents don't need to be checked, there is always only one, existence counts
            // (and negatives prevent a match in the first place, we'd never reach this if they would be found)

            // alternatives/alternative cases must be in a 1:1 correspondence (equal cases are ensured by the identical pattern check)
            for(int i = 0; i < this_.NumberOfAlternatives; ++i)
                if(!AreSymmetric(this_.getAlternativeAt(i), that.getAlternativeAt(i), graph))
                    return false;

            // iterated patterns are all-matches blocker, they are eagerly matched from their inputs on, 
            // with each iterated pattern settling on the first match, not searching for all, even if requested for the action
            // there can't be symmetric matches due to an iterated, only through the elements up to the iterated
            /* the iterateds must be in a 1:1 correspondence -- but the iterations may be permuted, that's handled in the call
            for(int i = 0; i < this_.NumberOfIterateds; ++i)
                if(!AreIterationsSymmetric(this_.getIteratedAt(i), that.getIteratedAt(i), graph))
                    return false;*/

            // the subpatterns of equal type may be permuted, the rest must be in a 1:1 correspondence
            // (by encapsulating the elements above in a subpattern instead of duplicating their content locally they can get symmetry checked)
            if(!AreSubpatternsSymmetric(this_, that, graph))
                return false;

#if LOG_MATCHES
            Console.WriteLine("this is symmetric to that");
#endif
            return true;
        }
Example #13
0
        public override EMElement Create(IMatch match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            if (match is EMBracketedImagesAndLinksMatch)
            {
                return CreateBracketed(match, doc, origin, parent, data);
            }

            if (match is EMDecorationMatch)
            {
                return CreateDecoration(match, doc, origin, parent, data);
            }

            throw new InvalidOperationException("Should not happend!");
        }
 internal void AddMatch(IMatch match, ITeam team)
 {
     if (match.HomeTeam == team)        // TODO ???? jestli staci
     {
         this.MyGoals += match.HomeScore;
         this.OtherGoals += match.ForeignScore;
         this.Points += match.HomePoint;
     }
     else
     {
         this.MyGoals += match.ForeignScore;
         this.OtherGoals += match.HomeScore;
         this.Points += match.ForeignPoint;
     }
 }
 public int? GuardedMatch(SourcePosn sourcePosn, IMatch match)
 {
     try
     {
         return sourcePosn.Match(match);
     }
     catch(Match.Exception exception)
     {
         throw new TwoLayerScanner.Exception
         (
             exception.SourcePosn,
             Convert(exception.Error)
         );
     }
 }
Example #16
0
        public void ShouldReturnFalseForNullHex()
        {
            var digit = new Choice(
                new Character('0'),
                new Range('1', '9'));

            var hex = new Choice(
                digit,
                new Choice(
                    new Range('a', 'f'),
                    new Range('A', 'F')));

            IMatch actual = hex.Match(null);

            Assert.False(actual.Succes());
        }
Example #17
0
        public void ShouldReturnRemainingTextForFalseForg8Hex()
        {
            var digit = new Choice(
                new Character('0'),
                new Range('1', '9'));

            var hex = new Choice(
                digit,
                new Choice(
                    new Range('a', 'f'),
                    new Range('A', 'F')));

            IMatch actual = hex.Match("g8");

            Assert.Equal("g8", actual.RemainingText());
        }
Example #18
0
        public async Task <IMatch> FindMatch()
        {
            var  found   = false;
            long grainId = 0;

            while (!found)
            {
                currentMatch = this.GrainFactory.GetGrain <IMatch>(grainId);
                found        = await currentMatch.AddPlayer(this);

                grainId++;
            }
            logger.LogInformation($"Player joined game {grainId}");

            return(currentMatch);
        }
Example #19
0
 public void CreateMatch(IMatch match)
 {
     lock (s_lockInstance)
     {
         try
         {
             Manager.CreateMatch(match);
         }
         catch (Exception e)
         {
             throw new DataAccessComponentException(this, -1,
                                                    $"Failed to create match: BatchId={match.Batch.Id}; Id={match.Id}; RuleDeclaration={match.RuleDeclarationRef}; RootDirectoryPath={match.RootDirectoryPath}; Filename={match.Filename}; LineNumber={match.LineNumber}",
                                                    e);
         }
     }
 }
Example #20
0
        public void ShouldReturnTrueForA9Hex()
        {
            var digit = new Choice(
                new Character('0'),
                new Range('1', '9'));

            var hex = new Choice(
                digit,
                new Choice(
                    new Range('a', 'f'),
                    new Range('A', 'F')));

            IMatch actual = hex.Match("A9");

            Assert.True(actual.Succes());
        }
Example #21
0
 private static bool IsCLL(IMatch match)
 {
     if (match.Format != MagicFormat.Legacy)
     {
         return(false);
     }
     if (match.Comments.ToUpper().Contains("CLL"))
     {
         return(true);
     }
     if (match.Comments.ToLower().Contains("community legacy league"))
     {
         return(true);
     }
     return(false);
 }
Example #22
0
 public static Gatherling.Models.Event GetEvent(IMatch match)
 {
     foreach (var tournament in TournamentManager.ActiveEvents)
     {
         var pairing = tournament.Value.Matches.FirstOrDefault(p => match.Players.Contains(p.A) && match.Players.Contains(p.B));
         if (pairing != null)
         {
             TournamentManager.ActiveMatches.Add(match);
             if (tournament.Key.Channel != null)
             {
                 return(tournament.Key);
             }
         }
     }
     return(null);
 }
Example #23
0
        public IMatch Match(string text)
        {
            var    remText = text;
            IMatch match   = pattern.Match(remText);
            var    Headers = new Dictionary <string, string>();

            while (remText != "\r\n")
            {
                var head = new HeaderMatch(match.RemainingText(), ExtractHeaders(remText, match.RemainingText())).header;
                Headers.Add(head.Key, head.Value);
                remText = match.RemainingText();
                match   = pattern.Match(remText);
            }

            return(new HeaderMatch(match.RemainingText(), Headers));
        }
Example #24
0
        public void ShouldReturnNullForNullHex()
        {
            var digit = new Choice(
                new Character('0'),
                new Range('1', '9'));

            var hex = new Choice(
                digit,
                new Choice(
                    new Range('a', 'f'),
                    new Range('A', 'F')));

            IMatch actual = hex.Match(null);

            Assert.Null(actual.RemainingText());
        }
Example #25
0
 private static bool IsPCT(IMatch match)
 {
     if (match.Format != MagicFormat.Pauper)
     {
         return(false);
     }
     if (match.Comments.ToLower().Contains("pct"))
     {
         return(true);
     }
     if (match.Comments.ToLower().Contains("pauper classic tuesdays"))
     {
         return(true);
     }
     return(false);
 }
Example #26
0
        public void ShouldReturnEmptyStringForTrueFor8Hex()
        {
            var digit = new Choice(
                new Character('0'),
                new Range('1', '9'));

            var hex = new Choice(
                digit,
                new Choice(
                    new Range('a', 'f'),
                    new Range('A', 'F')));

            IMatch actual = hex.Match("8");

            Assert.Equal(string.Empty, actual.RemainingText());
        }
Example #27
0
 private static bool IsPauperPower(IMatch match)
 {
     if (match.Format != MagicFormat.Pauper)
     {
         return(false);
     }
     if (match.Comments.ToLower().Contains("pauperpower"))
     {
         return(true);
     }
     if (match.Comments.ToLower().Contains("pauper power"))
     {
         return(true);
     }
     return(false);
 }
Example #28
0
        public MatchSummary RenderSummary(IMatch renderMatch)
        {
            var match = (Match)renderMatch;

            var result = new MatchSummary
            {
                Rounds = match.GetRoundNumber()
            };

            result.Players.Add(RenderPlayer(match, 1));
            result.Players.Add(RenderPlayer(match, 2));

            RenderWinDetails(result, match);

            return(result);
        }
        public MatchSummary RenderSummary(IMatch renderMatch)
        {
            var match = (Match)renderMatch;

            var result = new MatchSummary
            {
                Rounds = match.GetRoundNumber()
            };

            result.Players.Add(RenderPlayer(match, 1));
            result.Players.Add(RenderPlayer(match, 2));

            RenderWinDetails(result, match);

            return result;
        }
Example #30
0
        public bool Match(StringSlice slice, int startFrom, ref IMatch outMatch)
        {
            var matchImpl = GetOfCreateOutMatchImpl(ref outMatch);

            RENS.Match srcMatch;
            if ((options & ReOptions.RightToLeft) == 0)
            {
                srcMatch = impl.Match(slice.Buffer, slice.StartIndex + startFrom, slice.Length - startFrom, ref matchImpl.match);
            }
            else
            {
                srcMatch = impl.Match(slice.Buffer, slice.StartIndex, startFrom, ref matchImpl.match);
            }
            matchImpl.Reload(-slice.StartIndex);
            return(srcMatch.Success);
        }
Example #31
0
        /// <summary>
        /// Mark the elements of the match in the graph with a visited flag.
        /// Allocates a visited flag.
        /// </summary>
        /// <param name="match">The match to mark in the graph with a visited flag</param>
        /// <param name="graph">The graph in which the match was found, needed for visited flag access</param>
        /// <returns>The visited flag id, for later checks and the unmarking</returns>
        private static int Mark(IMatch match, IGraph graph)
        {
            int id = graph.AllocateVisitedFlag();

            for (int i = 0; i < match.NumberOfNodes; ++i)
            {
                graph.SetVisited(match.getNodeAt(i), id, true);
            }

            for (int i = 0; i < match.NumberOfEdges; ++i)
            {
                graph.SetVisited(match.getEdgeAt(i), id, true);
            }

            return(id);
        }
Example #32
0
        public Task <IGameObserver> GetInstanceForMatchAsync(IMatch match)
        {
            if (match.Format != MagicFormat.PennyDreadful && match.Format != MagicFormat.PennyDreadfulCommander)
            {
                return(Task.FromResult <IGameObserver>(null));
            }

            if (Tourney.GetEvent(match) != null)
            {
                return(Task.FromResult <IGameObserver>(null)); // Tournament Matches aren't League Matches.
            }
            var obs = new LeagueObserver(match);

            obs.CheckForLeagueAsync().GetAwaiter();
            return(Task.FromResult <IGameObserver>(obs));
        }
Example #33
0
        public MatchContract ToContract(IMatch model)
        {
            var contract = new MatchContract
            {
                Id = model.Id,
                Created = model.Created,
                UserId = model.UserId
            };

            if (model.Messages != null)
            {
                contract.Messages = model.Messages.Select(_messageMapper.ToContract);
            }

            return contract;
        }
Example #34
0
        private List <IResult> _Expect(List <Tuple <IMatch, Action <IResult> > > matchers, int timeout = 0, bool timeout_throws = false)
        {
            if (timeout == 0)
            {
                timeout = this.Timeout;
            }
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken       ct          = tokenSource.Token;
            List <Tuple <IResult, Action <IResult> > > results = matchers.Select(m => new Tuple <IResult, Action <IResult> >(m.Item1 as IResult, m.Item2)).ToList();
            StringBuilder matchOutputBuilder = new StringBuilder(1000);
            Task          task = Task.Run(() =>
            {
                bool completed = false;
                while (!ct.IsCancellationRequested && !results.Any(r => r.Item1.IsMatch) && !completed)
                {
                    matchOutputBuilder.Append(_spawnable.Read(out completed));
                    foreach (Tuple <IResult, Action <IResult> > r in results)
                    {
                        IMatch m = r.Item1 as IMatch;
                        m.Execute(matchOutputBuilder.ToString());
                        if (r.Item1.IsMatch)
                        {
                            r.Item2?.Invoke(r.Item1);
                            break;
                        }
                    }
                }
            }, ct);

            if (task.Wait(timeout, ct))
            {
                tokenSource.Dispose();
                return(results.Select(r => r.Item1).ToList());
            }
            else
            {
                tokenSource.Cancel();
                tokenSource.Dispose();
                bool at_least_one_match = results.Any(r => r.Item1.IsMatch);
                if (!at_least_one_match && timeout_throws)
                {
                    results = null;
                    throw new TimeoutException(string.Format("Timed out waiting for at least one match for {0} in output {1}.", matchers.Select(m => m.Item1.Query).Aggregate((p, n) => { return(p + "or" + n); }), matchOutputBuilder.ToString()));
                }
                return(results.Select(r => r.Item1).ToList());
            }
        }
Example #35
0
        private async Task <IResult> _ExpectAsync(IMatch matcher, Action <IResult> handler, int timeout = 0, bool timeout_throws = false)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            IResult result      = matcher;
            Task    timeoutTask = null;

            if (timeout == 0)
            {
                timeout = this.Timeout;
            }
            if (timeout > 0)
            {
                timeoutTask = Task.Delay(timeout);
            }
            StringBuilder matchOutputBuilder = new StringBuilder(1000);
            Task <string> readTask           = _spawnable.ReadAsync();
            IList <Task>  tasks = new List <Task>();

            tasks.Add(readTask);
            if (timeoutTask != null)
            {
                tasks.Add(timeoutTask);
            }
            Task completed = await Task.WhenAny(tasks).ConfigureAwait(false);

            if (completed == readTask)
            {
                string output = readTask.Result;
                OutputBuilder.Append(output);
                matchOutputBuilder.Append(output);
                matcher.Execute(matchOutputBuilder.ToString());
                if (result.IsMatch)
                {
                    handler?.Invoke(result);
                }
            }
            else
            {
                if (timeout_throws)
                {
                    throw new TimeoutException(string.Format("Timed out waiting for match for {0} in output {1}.", matcher.Query, matchOutputBuilder.ToString()));
                }
                ;
            }
            tokenSource.Dispose();
            return(result);
        }
Example #36
0
        /// <summary>
        /// Gets the new <see cref="IOutcomeOdds"/> instances
        /// </summary>
        /// <param name="sportEvent">The <see cref="ISportEvent"/> associated with the market</param>
        /// <param name="nameProvider">The <see cref="INameProvider"/> used to generate outcome name</param>
        /// <param name="mappingProvider">The <see cref="IMarketMappingProvider"/> used to provide market mapping</param>
        /// <param name="outcome">The <see cref="oddsChangeMarketOutcome"/> representing the outcome to be mapped</param>
        /// <param name="cultures">A <see cref="IEnumerable{CultureInfo}"/> specifying languages the current instance supports</param>
        /// <param name="outcomeDefinition">The associated <see cref="IOutcomeDefinition"/></param>
        /// <returns>IOutcomeOdds</returns>
        protected virtual IOutcomeOdds GetOutcomeWithOdds(ISportEvent sportEvent, INameProvider nameProvider, IMarketMappingProvider mappingProvider, oddsChangeMarketOutcome outcome, IEnumerable <CultureInfo> cultures, IOutcomeDefinition outcomeDefinition)
        {
            var    isValidPlayerOutcome = false;
            IMatch match = null;

            if (outcome.teamSpecified)
            {
                match = sportEvent as IMatch;
                isValidPlayerOutcome = !(match == null || outcome.team < 1 || outcome.team > 2);
            }

            var additionalProbabilities = new AdditionalProbabilities(
                outcome.win_probabilitiesSpecified ? outcome.win_probabilities : (double?)null,
                outcome.lose_probabilitiesSpecified ? outcome.lose_probabilities : (double?)null,
                outcome.half_win_probabilitiesSpecified ? outcome.half_win_probabilities : (double?)null,
                outcome.half_lose_probabilitiesSpecified ? outcome.half_lose_probabilities : (double?)null,
                outcome.refund_probabilitiesSpecified ? outcome.refund_probabilities : (double?)null);

            if (isValidPlayerOutcome)
            {
                return(new PlayerOutcomeOdds(outcome.id,
                                             outcome.activeSpecified ? (bool?)(outcome.active != 0) : null,
                                             outcome.odds,
                                             outcome.probabilitiesSpecified
                                                ? (double?)outcome.probabilities
                                                : null,
                                             nameProvider,
                                             mappingProvider,
                                             match,
                                             outcome.team,
                                             cultures,
                                             outcomeDefinition,
                                             additionalProbabilities));
            }

            return(new OutcomeOdds(outcome.id,
                                   outcome.activeSpecified ? (bool?)(outcome.active != 0) : null,
                                   outcome.odds,
                                   outcome.probabilitiesSpecified
                                        ? (double?)outcome.probabilities
                                        : null,
                                   nameProvider,
                                   mappingProvider,
                                   cultures,
                                   outcomeDefinition,
                                   additionalProbabilities));
        }
Example #37
0
        private static EMElement CreateBracketed(
            IMatch match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var taggedMatch = match as EMBracketedImagesAndLinksMatch;

            // Check if image.
            if (taggedMatch.Text.StartsWith("!") && !string.IsNullOrWhiteSpace(taggedMatch.Parameters))
            {
                EMElement outElement = null;

                var fragments = new List <TextFragment>()
                {
                    new TextFragment(origin.Start, match.Text)
                };

                EMParsingHelper.ParseElements(
                    data, doc, parent, fragments, EMImage.GetParser(), element => { outElement = element; });

                if (outElement == null)
                {
                    string imageError = "Could not find image in given text: " + origin.Text;
                    throw new InvalidOperationException(imageError);
                }

                return(outElement);
            }

            // Check if shortcut ref
            if (string.IsNullOrWhiteSpace(taggedMatch.Parameters))
            {
                return(EMLink.CreateFromAnchorRefShortcut(
                           EMLink.AnchorRefShortcut.Match(taggedMatch.Text), doc, origin, parent, data));
            }

            // If not an image and not a shortcut link, then must have been other link.

            // Parse span content for internal elements.
            var span = new EMSpanElements(doc, origin, parent);

            span.Parse(taggedMatch.ContentStart, taggedMatch.Content, data);

            // Check if ref link
            return(taggedMatch.Parameters.StartsWith("[")
                       ? EMLink.CreateFromAnchorRef(doc, origin, parent, data, span, taggedMatch.Parameters)
                       : EMLink.CreateFromInline(doc, origin, parent, data, span, taggedMatch.Parameters));
        }
 /// <summary>
 /// Check whether this observer cares enough to trigger joining a game.
 /// </summary>
 /// <param name="match"></param>
 /// <returns></returns>
 public bool ShouldJoin(IMatch match)
 {
     if (match.Format != MagicFormat.Freeform)
     {
         return(false);
     }
     else
     {
         // If all players are part of Austream
         var r = match.Players.All(p => AustreamMembers.Contains(p, StringComparer.CurrentCultureIgnoreCase));
         if (r)
         {
             return(true);
         }
         return(false);
     }
 }
Example #39
0
        public void Add(IMatch match)
        {
            Matches[match.Id] = match;
            match.MatchEnd   -= OnMatchEnd;
            match.MatchEnd   += OnMatchEnd;

            foreach (var player in match.AllPlayers)
            {
                player.Chat -= OnChat;
                player.Chat += OnChat;

                player.Popup -= OnPopup;
                player.Popup += OnPopup;
            }

            Task.Delay(3000).ContinueWith(t => match.Start());
        }
        private void AnnotateIndependentsMatches(IMatch parentMatch, bool addAnnotation, string prefix, int nestingLevel)
        {
            IPatternGraph        pattern = parentMatch.Pattern;
            IEnumerable <IMatch> matches = parentMatch.Independents;
            int i = 0;

            foreach (IMatch match in matches)
            {
                String name = "&(.)";
                if (pattern.IndependentPatternGraphs.Length > 1)
                {
                    name += "'" + i;
                }
                AnnotateMatch(match, addAnnotation, prefix + "/" + name, nestingLevel + 1, false);
                ++i;
            }
        }
Example #41
0
        public Bet(IMatch match, IBetLine line, string mark, decimal amount, decimal coefficient, ITipster tipster)
        {
            if (match == null)
            {
                throw new ArgumentNullException(string.Format(EngineConstants.ObjectCannotBeNullErrorMessage, "Match"));
            }

            if (line == null)
            {
                throw new ArgumentNullException(string.Format(EngineConstants.ObjectCannotBeNullErrorMessage, "Line"));
            }

            if (tipster == null)
            {
                throw new ArgumentNullException(string.Format(EngineConstants.ObjectCannotBeNullErrorMessage, "Tipster"));
            }

            this.Line           = line;
            this.Match          = match;
            this.Amount         = amount;
            this.Coefficient    = coefficient;
            this.CurrentBetType = currentBetType;
            this.Mark           = mark;
            this.isChecked      = false;
            this.Tipster        = tipster;

            if (this.Match.Results != null && this.Match.Results.ContainsKey(resultType))
            {
                throw new ArgumentException(EngineConstants.CannotAddBetToMatchWithResultErrorMessage);
            }

            if (this.Line.HasCompleteBet)
            {
                throw new ArgumentException(EngineConstants.AlreadyCompletedLineErrorMessage);
            }

            if (this.CalculateWinningBetAmount() > (this.Line.LeftValueToBeBet() + 0.3m))
            {
                throw new ArgumentException(EngineConstants.BetIsGreaterThenNeededErrorMessage);
            }

            this.Line.HasCompleteBet = this.IsReadyToBeComplete();

            match.AddBet(this);
            line.AddBet(this);
        }
Example #42
0
 /// <summary>
 /// Constructs a Riot Client with given implemented service for each Riot service group.
 /// </summary>
 /// <param name="champion">The champion.</param>
 /// <param name="currentGame">The current game.</param>
 /// <param name="featuredGames">The featured games.</param>
 /// <param name="game">The game.</param>
 /// <param name="league">The league.</param>
 /// <param name="lolStaticData">The lol static data.</param>
 /// <param name="lolStatus">The lol status.</param>
 /// <param name="match">The match.</param>
 /// <param name="matchHistory">The match history.</param>
 /// <param name="matchList">The match list.</param>
 /// <param name="stats">The stats.</param>
 /// <param name="summoner">The summoner.</param>
 /// <param name="team">The team.</param>
 public RiotClient(IChampion champion, ICurrentGame currentGame, IFeaturedGames featuredGames, IGame game, ILeague league, ILolStaticData lolStaticData,
     ILolStatus lolStatus, IMatch match, IMatchHistory matchHistory, IMatchList matchList, IStats stats, ISummoner summoner, ITeam team)
 {
     this.Champion = champion;
     this.CurrentGame = currentGame;
     this.FeaturedGames = featuredGames;
     this.Game = game;
     this.League = league;
     this.LolStaticData = lolStaticData;
     this.LolStatus = lolStatus;
     this.Match = match;
     this.MatchHistory = matchHistory;
     this.MatchList = matchList;
     this.Stats = stats;
     this.Summoner = summoner;
     this.Team = team;
 }
Example #43
0
 /// <summary>
 /// Constructs a Riot Client with given implemented service for each Riot service group.
 /// </summary>
 /// <param name="champion">The champion.</param>
 /// <param name="currentGame">The current game.</param>
 /// <param name="featuredGames">The featured games.</param>
 /// <param name="game">The game.</param>
 /// <param name="league">The league.</param>
 /// <param name="lolStaticData">The lol static data.</param>
 /// <param name="lolStatus">The lol status.</param>
 /// <param name="match">The match.</param>
 /// <param name="matchHistory">The match history.</param>
 /// <param name="matchList">The match list.</param>
 /// <param name="stats">The stats.</param>
 /// <param name="summoner">The summoner.</param>
 /// <param name="team">The team.</param>
 /// <param name="championMastery">Champion Masteries</param>
 public RiotClient(IChampion champion, ICurrentGame currentGame, IFeaturedGames featuredGames, IGame game, ILeague league, ILolStaticData lolStaticData,
                   ILolStatus lolStatus, IMatch match, IMatchList matchList, IStats stats, ISummoner summoner, ITeam team, IChampionMastery championMastery)
 {
     this.Champion        = champion;
     this.CurrentGame     = currentGame;
     this.FeaturedGames   = featuredGames;
     this.Game            = game;
     this.League          = league;
     this.LolStaticData   = lolStaticData;
     this.LolStatus       = lolStatus;
     this.Match           = match;
     this.MatchList       = matchList;
     this.Stats           = stats;
     this.Summoner        = summoner;
     this.Team            = team;
     this.ChampionMastery = championMastery;
 }
Example #44
0
        public void CreateMatch(IMatch match)
        {
            if (match == null)
            {
                throw new ArgumentNullException("match");
            }

            using (CodeAnalyzerContainer context = new CodeAnalyzerContainer())
            {
                // Mapping: Domain Model => Entity Model.
                Model.Match m = ToEntityModelMapper.MatchMapper(match, context);

                // Do the actual DB update.
                context.Match.Add(m);
                context.SaveChanges();
            }
        }
Example #45
0
        public void AddMatch(IMatch match)
        {
            lock (_lockInternalMatches)
            {
                if (match == null)
                {
                    throw new ArgumentNullException("match");
                }

                if (match.Result != MatchStatus.Match)
                {
                    return;
                }

                InternalMatches.Add(match);
            }
        }
Example #46
0
 public static Key ResolveSheriff(IMatch match)
 {
     return(match.AllPlayers
            .Where(player =>
     {
         var role = player.Role;
         return role.Team.Id == "Mafia" ||
         role.Team.Id == "Triad" ||
         role.IsCategory("Neutral Killing") ||
         role.Id == "Cultist" ||
         role.Id == "Witch Doctor";
     })
            .OrderByDescending(player => player.Alive)
            .Select(player => player.Role.DetectionProfile.GuiltyKey())
            .DefaultIfEmpty(SheriffKey.Mafia)
            .Random(match.Random));
 }
Example #47
0
    public async void JoinMatchIdAsync(string matchId)
    {
        if (matchSocket == null)
        {
            matchSocket = client.NewSocket();
            await matchSocket.ConnectAsync(session);
        }
        activeSceneMatchId = matchId;
        match = await matchSocket.JoinMatchAsync(matchId);

        EventManager.onRoomJoin.Invoke();

        //foreach (var presence in match.Presences)
        //{
        //    Debug.LogFormat("User id '{0}' name '{1}'.", presence.UserId, presence.Username);
        //}
    }
        public IMatch CreateMatch()
        {
            IMatch m = null;

            if (_tournament.IsStarted && _teams == null)
            {
                _teams = Winner.ToList();
            }

            if (_tournament != null && _tournament.IsStarted && !_played)
            {
                m       = new Match(_teams.ElementAt(0), _teams.ElementAt(1), AmountGameSets, AmountGoalsPerSet);
                _played = true;
            }

            return(m);
        }
Example #49
0
 /// <summary>
 /// Constructs a Riot Client with given implemented service for each Riot service group.
 /// </summary>
 /// <param name="champion">The champion.</param>
 /// <param name="currentGame">The current game.</param>
 /// <param name="featuredGames">The featured games.</param>
 /// <param name="game">The game.</param>
 /// <param name="league">The league.</param>
 /// <param name="lolStaticData">The lol static data.</param>
 /// <param name="lolStatus">The lol status.</param>
 /// <param name="match">The match.</param>
 /// <param name="matchHistory">The match history.</param>
 /// <param name="matchList">The match list.</param>
 /// <param name="stats">The stats.</param>
 /// <param name="summoner">The summoner.</param>
 /// <param name="team">The team.</param>
 public RiotClient(IChampion champion, ICurrentGame currentGame, IFeaturedGames featuredGames, IGame game, ILeague league, ILolStaticData lolStaticData,
     ILolStatus lolStatus, IMatch match, IMatchHistory matchHistory, IMatchList matchList, IStats stats, ISummoner summoner, ITeam team)
 {
     //we need to let Ninject know which concrete type to use to satisfy the interface.
     this.Champion = champion;
     this.CurrentGame = currentGame;
     this.FeaturedGames = featuredGames;
     this.Game = game;
     this.League = league;
     this.LolStaticData = lolStaticData;
     this.LolStatus = lolStatus;
     this.Match = match;
     this.MatchHistory = matchHistory;
     this.MatchList = matchList;
     this.Stats = stats;
     this.Summoner = summoner;
     this.Team = team;
 }
Example #50
0
        private static EMElement CreateBracketed(
            IMatch match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var taggedMatch = match as EMBracketedImagesAndLinksMatch;

            // Check if image.
            if (taggedMatch.Text.StartsWith("!") && !string.IsNullOrWhiteSpace(taggedMatch.Parameters))
            {
                EMElement outElement = null;

                var fragments = new List<TextFragment>() { new TextFragment(origin.Start, match.Text) };

                EMParsingHelper.ParseElements(
                    data, doc, parent, fragments, EMImage.GetParser(), element => { outElement = element; });

                if (outElement == null)
                {
                    string imageError = "Could not find image in given text: " + origin.Text;
                    throw new InvalidOperationException(imageError);
                }

                return outElement;
            }

            // Check if shortcut ref
            if (string.IsNullOrWhiteSpace(taggedMatch.Parameters))
            {
                return EMLink.CreateFromAnchorRefShortcut(
                    EMLink.AnchorRefShortcut.Match(taggedMatch.Text), doc, origin, parent, data);
            }

            // If not an image and not a shortcut link, then must have been other link.

            // Parse span content for internal elements.
            var span = new EMSpanElements(doc, origin, parent);
            span.Parse(taggedMatch.ContentStart, taggedMatch.Content, data);

            // Check if ref link
            return taggedMatch.Parameters.StartsWith("[")
                       ? EMLink.CreateFromAnchorRef(doc, origin, parent, data, span, taggedMatch.Parameters)
                       : EMLink.CreateFromInline(doc, origin, parent, data, span, taggedMatch.Parameters);
        }
        public override EMElement Create(IMatch match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            if (match is EMRawHTMLMatch)
            {
                var htmlMatch = match as EMRawHTMLMatch;
                if (htmlMatch.Name.ToLower() == "code")
                {
                    return new EMCodeBlock(doc, origin, parent, htmlMatch.Content, true);
                }

                var element = new EMRawHTML(doc, origin, parent, htmlMatch.Name, htmlMatch.AttributesString);

                element.Elements.Parse(Markdown.Outdent(htmlMatch.Content, element.Elements.TextMap), data);

                return element;
            }

            if (match is EMMarkdownTaggedElementMatch)
            {
                var markdownMatch = match as EMMarkdownTaggedElementMatch;

                switch (markdownMatch.Name.ToLower())
                {
                    case "region":
                        return EMRegion.CreateRegion(origin, doc, parent, data, markdownMatch, markdownMatch.Parameters);
                    case "include":
                        return EMInclude.CreateFromText(markdownMatch.Text, doc, origin, parent, data);
                    case "include_files":
                        return EMInclude.CreateIncludeFilesFromText(markdownMatch.Text, doc, origin, parent, data);
                    case "relative":
                        return EMRelativeLink.CreateFromText(markdownMatch.Parameters, doc, origin, parent, data);
                    case "relative_img":
                        return EMRelativeLink.CreateFromText(markdownMatch.Parameters, doc, origin, parent, data, true);
                    case "object":
                        return EMObject.CreateFromText(markdownMatch.Parameters, markdownMatch, doc, origin, parent, data);
                    default:
                        return EMErrorElement.Create(doc, origin, parent, data, "UnsupportedTaggedMarkdownElement");
                }
            }

            return EMErrorElement.Create(doc, origin, parent, data, "UnknownMatchTypeForTaggedElementsParser");
        }
        public MatchRender Render(IMatch renderMatch)
        {
            var match = (Match)renderMatch;

            var result = new MatchRender
            {
                Map = RenderMap(match),
                MapAdvanced = RenderMapAdvanced(match),
                State = RenderState(match),
                RoundNumber = match.GetRoundNumber(),
                Round = String.Format("Round {0}", match.GetRoundNumber())
            };

            result.Moves[0] = String.Format("Player {0}: {1,-20} > {2}",
                1, match.GetPlayerLastMove(1), match.GetPlayerLastMoveResult(1));
            result.Moves[1] = String.Format("Player {0}: {1,-20} > {2}",
                2, match.GetPlayerLastMove(2), match.GetPlayerLastMoveResult(2));

            return result;
        }
Example #53
0
        public static bool IsMatched(LGSPEdge edge, IMatch lastMatchAtPreviousNestingLevel)
        {
            Debug.Assert(lastMatchAtPreviousNestingLevel != null);

            // move through matches stack backwards to starting rule,
            // check if edge is already matched somewhere on the derivation path
            IMatch match = lastMatchAtPreviousNestingLevel;
            while (match != null)
            {
                for (int i = 0; i < match.NumberOfEdges; ++i)
                {
                    if (match.getEdgeAt(i) == edge)
                    {
                        return true;
                    }
                }
                match = match.MatchOfEnclosingPattern;
            }
            return false;
        }
Example #54
0
        /// <summary>
        /// Constructeur d'un Match par copie
        /// </summary>
        /// <param name="matchToCopy">L'instance de Match à copier</param>
        public Match(IMatch matchToCopy)
            : this(matchToCopy.Identifiant, matchToCopy.DateDuMatch, matchToCopy.ArbitreDuMatch,
            matchToCopy.StadeDuMatch, matchToCopy.ReservationsPourLeMatch, matchToCopy.EquipeDomicile,
            matchToCopy.EquipeVisiteur, matchToCopy.ScoreEquipeDomicile, matchToCopy.ScoreEquipeVisiteur)
        {

        }
Example #55
0
 public Sequence(IMatch data, IMatch other)
 {
     _data = data;
     _other = other;
 }
Example #56
0
 public NotMatch(IMatch data) { _data = data; }
Example #57
0
 public Match Else(IMatch other) => _data.Else(other);
Example #58
0
 internal Match(IMatch data)
 {
     Tracer.Assert(!(data is Match));
     _data = data;
 }
Example #59
0
 public ValueMatch(IMatch data, Func<string, IMatch> func)
 {
     _data = data;
     _func = func;
 }
Example #60
0
 public FindMatch(IMatch data) { _data = data; }