public MatchResult Evaluate(string input, string pattern) { var matchResult = new MatchResult(); if (input == null) { return matchResult; } if (pattern == null) { matchResult.StringParts.Add(new StringPart(input)); return matchResult; } if (!InputStartsWithPattern(input, pattern)) { matchResult.StringParts.Add(new StringPart(input)); return matchResult; } var matchedPart = input.Substring(0, pattern.Length); var restOfInput = input.Substring(pattern.Length); matchResult.Matched = true; matchResult.Score = 4; matchResult.StringParts.Add(new StringPart(matchedPart, true)); matchResult.StringParts.Add(new StringPart(restOfInput, false)); return matchResult; }
public static void EndMatch(MatchResult result) { if (StopSend()) return; Channel.networkView.RPC("EndMatchRPC", RPCMode.Others, (int)result); }
public MatchResult SimulateMatch(FootballMatch match) { var field = new Field(); const int interval = 10; var result = new MatchResult(); bool team1HasBall = true; for (int seconds = 0; seconds < 90 * 60; seconds += interval) { bool otherTeamWinsBall = Random.Next(4) == 0; if (otherTeamWinsBall) team1HasBall = !team1HasBall; int widthDelta = GetWidthDelta(field); int lengthDelta = GetLengthDelta(field, team1HasBall); field.MoveBall(widthDelta, lengthDelta); if (field.BallIsAtGoal1()) { result.Goals2++; field.ResetBallPosition(); team1HasBall = true; } if (field.BallIsAtGoal2()) { result.Goals1++; field.ResetBallPosition(); team1HasBall = false; } } return result; }
public override int PointsEarned(MatchResult outcome, Match MatchOfWeek) { int Multiple = outcome.Match == MatchOfWeek ? 2 : 1; if (outcome.Winner == null || (!outcome.Winner.Equals(Winner) || outcome.ResultType.HasRounds)) return 0; //did you get correct type of decision? if (By == outcome.DecisionType()) { //E.g. if the decisionType is same as yours +1 if (outcome.DecisionType() == Decision.Unanimous) { return ((3 + 1) * Multiple); } else if (outcome.DecisionType() == Decision.Majority) { return ((3 + 3) * Multiple); } else if (outcome.DecisionType() == Decision.Split) { return ((3 + 3) * Multiple); } } //you went Points correctly but didnt get the right type return (3 * Multiple); }
public override int PointsEarned(MatchResult outcome, Match MatchOfWeek) { int Multiple = outcome.Match == MatchOfWeek ? 2 : 1; if (outcome.Winner != null && !outcome.Winner.Equals(Winner)) return 0; //Is a stoppage! if (outcome.ResultType.HasRounds) { if (outcome.Round == Round) { return ((3 + 5) * Multiple); } else if (outcome.Round <= Round + 1 && outcome.Round >= Round - 1) { return ((3 + 3) * Multiple); } else if (outcome.Round <= Round + 2 && outcome.Round >= Round - 2) { return ((3 + 1) * Multiple); } else { return (3 * Multiple); } } return 0; }
public AuthorizationEntry(string userId, string activityId, MatchResult result) { CodeContract.ArgumentNotNullOrWhitespace("userId", userId); CodeContract.ArgumentNotNullOrWhitespace("activityId", activityId); if (userId.EndsWith("*", StringComparison.OrdinalIgnoreCase)) { this.userIdIsWildcard = true; this.UserId = userId.Substring(0, userId.Length - 1); } else { this.UserId = userId; } if (activityId.EndsWith("*", StringComparison.OrdinalIgnoreCase)) { this.activityIdIsWildcard = true; this.ActivityId = activityId.Substring(0, activityId.Length - 1); } else { this.ActivityId = activityId; } this.Result = result; }
public void Update(int w, int l, int d, MatchResult matchResult) { WonRounds = w; LostRounds = l; TiedRounds = d; MatchResult = matchResult; }
public NamedGraphMatch(Uri namedGraph, MatchResult idMatch, MatchResult predicateMatch, MatchResult typeMatch) : this() { NamedGraph = namedGraph; IdMatch = idMatch; PredicateMatch = predicateMatch; TypeMatch = typeMatch; }
// PRE : buffer can be null, is there are no results public void AddResult(MatchResult result) { Debug.Assert(!IsReady); if (Matches == null) Matches = new List<MatchResult>(); Matches.Add(result); }
public MatchStructure(MatchStructure org) { this.matchResult = org.matchResult; this.responseJsonType = org.responseJsonType; this.jsonEntryNotFound = new HashSet<string>(org.jsonEntryNotFound); this.xmlItemNotFound = new HashSet<string>(org.xmlItemNotFound); this.subListItemMatchResult = new Dictionary<string, MatchStructure>(org.subListItemMatchResult); this.isSubItemNotMatch = org.isSubItemNotMatch; }
public override int PointsEarned(MatchResult outcome, Match MatchOfWeek) { int Multiple = outcome.Match == MatchOfWeek ? 2 : 1; if (outcome.Winner == null) { return (15 * Multiple); } return (-5 * Multiple); }
public void Exact_literal_match_should_be_greater_than_datatype_match(MatchResult datatypeMatch) { // given var left = new LiteralConversionMatch { LiteralFormatMatches = MatchResult.ExactMatch }; var right = new LiteralConversionMatch { DatatypeMatches = datatypeMatch }; // when var compareTo = left.CompareTo(right); // then compareTo.Should().BeGreaterThan(0); }
public override int PointsEarned(MatchResult outcome, Match MatchOfWeek) { int Multiple = outcome.Match == MatchOfWeek ? 2 : 1; if (outcome.Winner != null && outcome.Winner.Equals(Winner)) { return (3 * Multiple); }else if(outcome.Winner == null) { return 0; } return (-5 * Multiple); }
public void Datatype_match_should_be_greater_than_no_match(MatchResult datatypeMatch) { // given var left = new LiteralConversionMatch { DatatypeMatches = datatypeMatch }; var right = new LiteralConversionMatch(); // when var compareTo = left.CompareTo(right); // then compareTo.Should().BeGreaterThan(0); left.Should().NotBe(right); }
public void AddResult(MatchResult matchResult) { var entry = _results.SingleOrDefault(r => r.Result == matchResult); if (entry == null) { entry = new ResultProbability { Result = matchResult }; _results.Add(entry); } entry.Count++; int totalCount = _results.Sum(r => r.Count); foreach (var item in _results) { item.Probability = (item.Count * 1d) / (1d * totalCount); } }
public void objectがintにマッチした場合にintの処理が呼び出される(object target, MatchResult expected) { try { target.TypeMatch( (int _) => { if (expected == MatchResult.Success) return 0; else throw new FailureException(); }); } catch (FailureException) { if (expected != MatchResult.Failure) Assert.Fail(); } catch (MatchFailureException) { if(expected != MatchResult.Failure) Assert.Fail(); } }
public void Should_match_segment() { var command = "test".Split(' '); var commandRoute = new CommandRoute("test"); var matchResult = new MatchResult(); var mockSegment = new Mock<ISegment>(); mockSegment.Setup(x => x.Match("test")).Returns(() => matchResult); commandRoute.AddSegment(mockSegment.Object); var result = commandRoute.Match(command); Assert.NotNull(result); Assert.Equal(1, result.MatchResults.Count); Assert.Equal(0, result.OptionalMatchResults.Count); Assert.True(result.MatchResults.Contains(matchResult)); }
public void EstablishContext() { EstablishAgencyContext(); saver = new Mock<ICanSave>(); saver .Expect(s => s.AddToContext(It.IsAny<Campaign>())) .Callback((Campaign c) => c.Id = SAVED_CAMPAIGN_ID) // This is a bit of a hack. I'm setting the Id here because Campaign is not passed to SaveAll where the Id should be set. .Verifiable(); saver.Expect(s => s.SaveAll()).Verifiable(); calendar = new Mock<ICalendarService>(); calendar.Expect(c => c.CurrentDateTime).Returns(new DateTime(2009, 1, 25, 11, 48, 12)); matchResult = new MatchResult(new BuyerBuilder().Build(), new List<Product> {new ProductBuilder().Build()}); campaignService = new Mock<ICampaignService>(); campaignService.Expect(cs => cs.Match(It.IsAny<Campaign>())).Callback((Campaign c) => c.Matches = new List<MatchResult> {matchResult}); campaignService.Expect(cs => cs.RetrieveById(SAVED_CAMPAIGN_ID)).Returns( new CampaignBuilder().WithId(SAVED_CAMPAIGN_ID).WithMessage(new MessageBuilder().Build()).Build()); messageService = new Mock<IMessagingService>(); controller = new CampaignController(campaignService.Object, messageService.Object,calendar.Object,null,null,saver.Object); }
public virtual void EndMatch(MatchResult result) { if (!this.matchEnding) matchEnding = true; else return; Debug.Log("Ending match."); if (Network.peerType == NetworkPeerType.Server) { MatchRPC.EndMatch(result); this.countDown = true; this.result = result; } else if (result == MatchResult.Disconnected) { this.countDown = true; this.result = result; } }
/// <summary> /// Method to Match new property with properties in DB /// </summary> /// <param name="agencyProperty"></param> /// <returns></returns> public override MatchResult IsMatch(Property agencyProperty, List<Property> databaseProperty) { var lstProperty = databaseProperty; MatchResult result = new MatchResult(); MatchRuleEngineFactory matchRuleEngine; StringBuilder errorSb = new StringBuilder(); #region Agency:OTBRE if (agencyProperty.AgencyCode.Equals(Agency.OTBRE.ToString())) { try { matchRuleEngine = new PunctuationRuleConcrete(); result.IsValidMatch = matchRuleEngine.AbstractMatchPropertyDetails(agencyProperty, lstProperty); } catch (Exception ex) { errorSb.Append("*****************************Error Processing Agency: The Best Real Estate*****************************"); errorSb.Append("Exception Message:" + ex.Message.ToString()); errorSb.Append(Environment.NewLine); errorSb.Append("Exception Stack:" + ex.StackTrace.ToString()); errorSb.Append(Environment.NewLine); } } #endregion #region Error if (errorSb.ToString() != string.Empty) { result.IsException = true; result.ExceptionMessage = errorSb.ToString(); result.IsValidMatch = false; } #endregion return result; }
private IList <MatchResult> FindNearestMatchesWithin(MatchableBagOfTokens matchable_entity_bag, IList <MatchableBagOfTokens> matchable_names, double threshold) { IList <MatchResult> matches = new List <MatchResult>(); foreach (var matchable_name in matchable_names) { double score = ComputeSimilarityScore(matchable_entity_bag, matchable_name); MatchResult match = new MatchResult { Element = matchable_name, Score = score }; matches.Add(match); } matches = matches.OrderByDescending(match => match.Score).ToList(); IList <MatchResult> selected_matches = new List <MatchResult>(); if (matches.Any()) { double max_score = matches[0].Score; if (max_score > 0) { foreach (var match in matches) { if (match.Score >= threshold) { selected_matches.Add(match); } } } } return(selected_matches); }
public void MatchDrawn() { //Arrange var matchResult = new MatchResult(1); var participantOne = new Participant(_mockContestService.Object) { CompetitorId = 10, ContestId = 1 }; var participantTwo = new Participant(_mockContestService.Object) { CompetitorId = 20, ContestId = 1 }; matchResult.AddParticipant(participantOne); matchResult.AddParticipant(participantTwo); matchResult.IsDrawn = true; //Act matchResult.Notify(); //Assert _mockContestService.Verify(ls => ls.Add(1, 10, Infrastructure.GameResult.Drawn), Times.AtLeastOnce); _mockContestService.Verify(ls => ls.Add(1, 20, Infrastructure.GameResult.Drawn), Times.AtLeastOnce); }
private static void ApplyStyles(FlowDocument document, MatchResult matchResult, TextRange textRange) { if (matchResult != null) { foreach (var matchPosition in matchResult.Positions) { var initialPointer = document.ContentStart; var start = CustomTextBox.GetPoint(initialPointer, matchPosition.Index); var endPos = CustomTextBox.GetPoint(initialPointer, matchPosition.Index + matchPosition.Length); if (start == null || endPos == null) { continue; } textRange.Select(start, endPos); var color = (SolidColorBrush) new BrushConverter().ConvertFrom("#EAC684"); if (color != null) { textRange.ApplyPropertyValue(TextElement.BackgroundProperty, color); } } } }
private static bool TryOptimiseToNot(ILInstructionExpression expression, MatchResult matchResult) { var(left, right) = GetOperands(matchResult); if (left.Variable == right.Variable) { // Unregister one of the variable uses. right.Variable = null; // Replace with NOT pseudo opcode. var newExpression = new ILInstructionExpression( expression.OriginalOffset, ILOpCodes.__NOT_DWORD, null, VMType.Dword); newExpression.Arguments.Add((ILExpression)left.Parent.Remove()); newExpression.FlagsVariable = expression.FlagsVariable; expression.FlagsVariable = null; expression.ReplaceWith(newExpression); return(true); } return(false); }
public static string Build(MatchResult MR, Rule R, Padyam P) { StringBuilder sb = new StringBuilder(); { sb.Append("<h2 style='color:blue; text-align:left; width:100%;'>" + R.Name); if (MR.Percentage != 100) { sb.Append(": <b style='color:red'>" + MR.Percentage.ToString("0") + "<span class='symbol'>%</span></b>(" + MR.Score + "/" + MR.Total + ")"); } sb.AppendLine("</h2>"); sb.AppendLine("<br/>"); sb.AppendLine("<p style='width:100%; text-align:left;border:1px solid Blue; border-left:4px solid #EEEEEE; '>"); sb.AppendLine(P.Build2(MR)); sb.AppendLine("</p>"); sb.AppendLine("<br/>"); sb.AppendLine("<br/>"); sb.AppendLine("<h2 style='color:blue; text-align:center; width:100%;'>గణ విభజన</h2>"); sb.AppendLine("<br/>"); sb.AppendLine(P.Build(MR)); if (MR.Percentage != 100) { sb.AppendLine("<br/>"); sb.AppendLine("<h2 style='color:blue; text-align:center; width:100%;'>దోషాలు</h2>"); sb.AppendLine("<br/>"); sb.AppendLine(MR.ShowErrors(OutputFormat.HTML)); } } return(sb.ToString()); }
public void Should_match_multiple_segments() { var command = "test value".Split(' '); var commandRoute = new CommandRoute("test {value}"); var matchResult = new MatchResult(); var namedMatchResult = new NamedValueMatchResult("value", "value"); var mockSegment = new Mock<ISegment>(); var mockVariableSegment = new Mock<ISegment>(); mockSegment.Setup(x => x.Match("test")).Returns(() => matchResult); mockVariableSegment.Setup(x => x.Match("value")).Returns(() => namedMatchResult); commandRoute.AddSegment(mockSegment.Object); commandRoute.AddSegment(mockVariableSegment.Object); var result = commandRoute.Match(command); Assert.NotNull(result); Assert.Equal(2, result.MatchResults.Count); Assert.Equal(0, result.OptionalMatchResults.Count); Assert.True(result.MatchResults.Contains(matchResult)); Assert.True(result.MatchResults.Contains(namedMatchResult)); }
public void Should_match_segment_and_flag() { var command = "test -f".Split(' '); var commandRoute = new CommandRoute("test [-f|flag]"); var matchResult = new MatchResult(); var namedMatchResult = new NamedValueMatchResult("flag", true); var mockSegment = new Mock<ISegment>(); var mockOptionalSegment = new Mock<ISegment>(); mockSegment.Setup(x => x.Match("test")).Returns(() => matchResult); mockOptionalSegment.Setup(x => x.Match("-f")).Returns(() => namedMatchResult); commandRoute.AddSegment(mockSegment.Object); commandRoute.AddOptionalSegment(mockOptionalSegment.Object); var result = commandRoute.Match(command); Assert.NotNull(result); Assert.Equal(1, result.MatchResults.Count); Assert.Equal(1, result.OptionalMatchResults.Count); Assert.True(result.MatchResults.Contains(matchResult)); Assert.True(result.OptionalMatchResults.Contains(namedMatchResult)); }
/// <summary> /// 这里应该只有 /// </summary> /// <returns></returns> public MatchResult Match(int row, int col) { int minCol = Mathf.Max(0, col - 2); int maxCol = Mathf.Min(GameRoot.GetInstance().CurLevel.ColNum - 1, minCol + 4); CellData cellData = GameRoot.GetInstance().GetGrid().GetCellData(row, col); for (int i = minCol; i < maxCol; i++) { if (cellData.Color != GameRoot.GetInstance().GetGrid().GetCellData(row, i).Color) { return null; } } MatchResult result = new MatchResult(); for (int i = minCol; i < maxCol; i++) { result.RemoveCellResults.Add(new ColMatchResult(i,row,row+1)); } return result; }
public void Should_match_segment_and_flag_with_value() { var command = "test -f test".Split(' '); var commandRoute = new CommandRoute("test [-f|flag]"); var matchResult = new MatchResult(); var namedMatchResult = new NamedValueMatchResult("flag", "test"); var mockSegment = new Mock <ISegment>(); var mockOptionalSegment = new Mock <ISegment>(); mockSegment.Setup(x => x.Match("test")).Returns(() => matchResult); mockOptionalSegment.Setup(x => x.Match("-f test")).Returns(() => namedMatchResult); commandRoute.AddSegment(mockSegment.Object); commandRoute.AddOptionalSegment(mockOptionalSegment.Object); var result = commandRoute.Match(command); Assert.NotNull(result); Assert.Equal(1, result.MatchResults.Count); Assert.Equal(1, result.OptionalMatchResults.Count); Assert.True(result.MatchResults.Contains(matchResult)); Assert.True(result.OptionalMatchResults.Contains(namedMatchResult)); }
public void Should_match_multiple_segments() { var command = "test value".Split(' '); var commandRoute = new CommandRoute("test {value}"); var matchResult = new MatchResult(); var namedMatchResult = new NamedValueMatchResult("value", "value"); var mockSegment = new Mock <ISegment>(); var mockVariableSegment = new Mock <ISegment>(); mockSegment.Setup(x => x.Match("test")).Returns(() => matchResult); mockVariableSegment.Setup(x => x.Match("value")).Returns(() => namedMatchResult); commandRoute.AddSegment(mockSegment.Object); commandRoute.AddSegment(mockVariableSegment.Object); var result = commandRoute.Match(command); Assert.NotNull(result); Assert.Equal(2, result.MatchResults.Count); Assert.Equal(0, result.OptionalMatchResults.Count); Assert.True(result.MatchResults.Contains(matchResult)); Assert.True(result.MatchResults.Contains(namedMatchResult)); }
public List <ExtractResult> Extract(string source) { var result = new List <ExtractResult>(); if (!PreCheckStr(source)) { return(result); } var mappingPrefix = new Dictionary <int, PrefixUnitResult>(); var sourceLen = source.Length; var prefixMatched = false; MatchCollection nonUnitMatches = null; var prefixMatch = prefixMatcher.Find(source).OrderBy(o => o.Start).ToList(); var suffixMatch = suffixMatcher.Find(source).OrderBy(o => o.Start).ToList(); if (prefixMatch.Count > 0 || suffixMatch.Count > 0) { var numbers = this.config.UnitNumExtractor.Extract(source).OrderBy(o => o.Start); // Special case for cases where number multipliers clash with unit var ambiguousMultiplierRegex = this.config.AmbiguousUnitNumberMultiplierRegex; if (ambiguousMultiplierRegex != null) { foreach (var number in numbers) { var match = ambiguousMultiplierRegex.Matches(number.Text); if (match.Count == 1) { var newLength = number.Text.Length - match[0].Length; number.Text = number.Text.Substring(0, newLength); number.Length = newLength; } } } foreach (var number in numbers) { if (number.Start == null || number.Length == null) { continue; } int start = (int)number.Start, length = (int)number.Length; var maxFindPref = Math.Min(maxPrefixMatchLen, number.Start.Value); var maxFindSuff = sourceLen - start - length; if (maxFindPref != 0) { // Scan from left to right, find the longest match var lastIndex = start; MatchResult <string> bestMatch = null; foreach (var m in prefixMatch) { if (m.Length > 0 && m.End > start) { break; } if (m.Length > 0 && source.Substring(m.Start, lastIndex - m.Start).Trim() == m.Text) { bestMatch = m; break; } } if (bestMatch != null) { var offSet = lastIndex - bestMatch.Start; var unitStr = source.Substring(bestMatch.Start, offSet); mappingPrefix.Add(number.Start.Value, new PrefixUnitResult { Offset = offSet, UnitStr = unitStr }); } } mappingPrefix.TryGetValue(start, out PrefixUnitResult prefixUnit); if (maxFindSuff > 0) { // find the best suffix unit var maxlen = 0; var firstIndex = start + length; foreach (var m in suffixMatch) { if (m.Length > 0 && m.Start >= firstIndex) { var endpos = m.Start + m.Length - firstIndex; if (maxlen < endpos) { var midStr = source.Substring(firstIndex, m.Start - firstIndex); if (string.IsNullOrWhiteSpace(midStr) || midStr.Trim().Equals(this.config.ConnectorToken)) { maxlen = endpos; } } } } if (maxlen != 0) { var substr = source.Substring(start, length + maxlen); var er = new ExtractResult { Start = start, Length = length + maxlen, Text = substr, Type = this.config.ExtractType, }; if (prefixUnit != null) { prefixMatched = true; er.Start -= prefixUnit.Offset; er.Length += prefixUnit.Offset; er.Text = prefixUnit.UnitStr + er.Text; } // Relative position will be used in Parser number.Start = start - er.Start; er.Data = number; // Special treatment, handle cases like '2:00 pm', '00 pm' is not dimension var isNotUnit = false; if (er.Type.Equals(Constants.SYS_UNIT_DIMENSION, StringComparison.Ordinal)) { if (nonUnitMatches == null) { nonUnitMatches = this.config.NonUnitRegex.Matches(source); } foreach (Match time in nonUnitMatches) { if (er.Start >= time.Index && er.Start + er.Length <= time.Index + time.Length) { isNotUnit = true; break; } } } if (isNotUnit) { continue; } result.Add(er); } } if (prefixUnit != null && !prefixMatched) { var er = new ExtractResult { Start = number.Start - prefixUnit.Offset, Length = number.Length + prefixUnit.Offset, Text = prefixUnit.UnitStr + number.Text, Type = this.config.ExtractType, }; // Relative position will be used in Parser number.Start = start - er.Start; er.Data = number; result.Add(er); } } } // Extract Separate unit if (separateRegex != null) { if (nonUnitMatches == null) { nonUnitMatches = this.config.NonUnitRegex.Matches(source); } ExtractSeparateUnits(source, result, nonUnitMatches); // Remove common ambiguous cases result = FilterAmbiguity(result, source); } return(result); }
protected virtual void OnGameCompleted(MatchResult e) { var handler = GameCompleted; handler?.Invoke(this, e); }
public List <ExtractResult> Extract(string source) { var result = new List <ExtractResult>(); if (!PreCheckStr(source)) { return(result); } var mappingPrefix = new Dictionary <int, PrefixUnitResult>(); var sourceLen = source.Length; var prefixMatched = false; var unitIsPrefix = new List <bool>(); MatchCollection nonUnitMatches = null; var prefixMatches = prefixMatcher.Find(source).OrderBy(o => o.Start).ToList(); var suffixMatches = suffixMatcher.Find(source).OrderBy(o => o.Start).ToList(); if (prefixMatches.Count > 0 || suffixMatches.Count > 0) { var numbers = this.config.UnitNumExtractor.Extract(source).OrderBy(o => o.Start); // Checking if there are conflicting interpretations between currency unit as prefix and suffix for each number. // For example, in Chinese, "$20,300美圆" should be broken into two entities instead of treating 20,300 as one number: "$20" and "300美圆". if (numbers.Count() > 0 && CheckExtractorType(Constants.SYS_UNIT_CURRENCY) && prefixMatches.Count() > 0 && suffixMatches.Count() > 0) { foreach (var number in numbers) { int start = (int)number.Start, length = (int)number.Length; var numberPrefix = prefixMatches.Any(o => o.Start + o.Length == number.Start); var numberSuffix = suffixMatches.Any(o => o.Start == number.Start + number.Length); if (numberPrefix != false && numberSuffix != false && number.Text.Contains(",")) { int commaIndex = (int)number.Start + number.Text.IndexOf(","); source = source.Substring(0, commaIndex) + " " + source.Substring(commaIndex + 1); } } numbers = this.config.UnitNumExtractor.Extract(source).OrderBy(o => o.Start); } // Special case for cases where number multipliers clash with unit var ambiguousMultiplierRegex = this.config.AmbiguousUnitNumberMultiplierRegex; if (ambiguousMultiplierRegex != null) { foreach (var number in numbers) { var match = ambiguousMultiplierRegex.Matches(number.Text); if (match.Count == 1) { var newLength = number.Text.Length - match[0].Length; number.Text = number.Text.Substring(0, newLength); number.Length = newLength; } } } foreach (var number in numbers) { if (number.Start == null || number.Length == null) { continue; } int start = (int)number.Start, length = (int)number.Length; var maxFindPref = Math.Min(maxPrefixMatchLen, number.Start.Value); var maxFindSuff = sourceLen - start - length; var closeMatch = false; if (maxFindPref != 0) { // Scan from left to right, find the longest match var lastIndex = start; MatchResult <string> bestMatch = null; foreach (var m in prefixMatches) { if (m.Length > 0 && m.End > start) { break; } var unitStr = source.Substring(m.Start, lastIndex - m.Start); if (m.Length > 0 && unitStr.Trim() == m.Text) { if (unitStr == m.Text) { closeMatch = true; } bestMatch = m; break; } } if (bestMatch != null) { var offSet = lastIndex - bestMatch.Start; var unitStr = source.Substring(bestMatch.Start, offSet); mappingPrefix[number.Start.Value] = new PrefixUnitResult { Offset = offSet, UnitStr = unitStr }; } } mappingPrefix.TryGetValue(start, out PrefixUnitResult prefixUnit); // For currency unit, such as "$ 10 $ 20", get candidate "$ 10" "10 $" "$20" then select to get result. // So add "$ 10" to result here, then get "10 $" in the suffixMatch. // But for case like "摄氏温度10度", "摄氏温度10" will skip this and continue to extend the suffix. if (prefixUnit != null && !prefixMatched && CheckExtractorType(Constants.SYS_UNIT_CURRENCY)) { var er = new ExtractResult { Start = number.Start - prefixUnit.Offset, Length = number.Length + prefixUnit.Offset, Text = prefixUnit.UnitStr + number.Text, Type = this.config.ExtractType, }; // Relative position will be used in Parser var numberData = number.Clone(); numberData.Start = start - er.Start; er.Data = numberData; result.Add(er); unitIsPrefix.Add(true); } if (maxFindSuff > 0) { // If the number already get close prefix currency unit, skip the suffix match. if (CheckExtractorType(Constants.SYS_UNIT_CURRENCY) && closeMatch) { continue; } // find the best suffix unit var maxlen = 0; var firstIndex = start + length; foreach (var m in suffixMatches) { if (m.Length > 0 && m.Start >= firstIndex) { var endpos = m.Start + m.Length - firstIndex; if (maxlen < endpos) { var midStr = source.Substring(firstIndex, m.Start - firstIndex); if (string.IsNullOrWhiteSpace(midStr) || midStr.Trim().Equals(this.config.ConnectorToken, StringComparison.Ordinal)) { maxlen = endpos; } } } } if (maxlen != 0) { var substr = source.Substring(start, length + maxlen); var er = new ExtractResult { Start = start, Length = length + maxlen, Text = substr, Type = this.config.ExtractType, }; if (prefixUnit != null && !CheckExtractorType(Constants.SYS_UNIT_CURRENCY)) { prefixMatched = true; er.Start -= prefixUnit.Offset; er.Length += prefixUnit.Offset; er.Text = prefixUnit.UnitStr + er.Text; } // Relative position will be used in Parser var numberData = number.Clone(); numberData.Start = start - er.Start; er.Data = numberData; // Special treatment, handle cases like '2:00 pm', '00 pm' is not dimension var isNotUnit = false; if (er.Type.Equals(Constants.SYS_UNIT_DIMENSION, StringComparison.Ordinal)) { if (nonUnitMatches == null) { nonUnitMatches = this.config.NonUnitRegex.Matches(source); } foreach (Match time in nonUnitMatches) { if (er.Start >= time.Index && er.Start + er.Length <= time.Index + time.Length) { isNotUnit = true; break; } } } if (isNotUnit) { continue; } result.Add(er); unitIsPrefix.Add(false); } } if (prefixUnit != null && !prefixMatched && !CheckExtractorType(Constants.SYS_UNIT_CURRENCY)) { var er = new ExtractResult { Start = number.Start - prefixUnit.Offset, Length = number.Length + prefixUnit.Offset, Text = prefixUnit.UnitStr + number.Text, Type = this.config.ExtractType, }; // Relative position will be used in Parser var numberData = number.Clone(); numberData.Start = start - er.Start; er.Data = numberData; result.Add(er); } } } // Extract Separate unit if (separateRegex != null) { if (nonUnitMatches == null) { nonUnitMatches = this.config.NonUnitRegex.Matches(source); } ExtractSeparateUnits(source, result, nonUnitMatches); } // Remove common ambiguous cases result = FilterAmbiguity(result, source); if (CheckExtractorType(Constants.SYS_UNIT_CURRENCY)) { result = SelectCandidates(source, result, unitIsPrefix); } return(result); }
private ResolveResult BuildResult(NancyContext context, MatchResult result) { var associatedModule = this.GetModuleFromMatchResult(context, result); var route = associatedModule.Routes.ElementAt(result.RouteIndex); var parameters = DynamicDictionary.Create(result.Parameters); return new ResolveResult { Route = route, Parameters = parameters, Before = associatedModule.Before, After = associatedModule.After, OnError = associatedModule.OnError }; }
/// <summary> /// Facilitates play between the two engines for the given position with the /// given match option. /// </summary> /// <param name="white">The engine instance playing as white.</param> /// <param name="black">The engine instance playing as black.</param> /// <param name="position">The position the match is played on.</param> /// <param name="option">The match option specifying the conditions of the match.</param> /// <returns>The result of the match from white's perspective.</returns> public static MatchResult Play(IEngine white, IEngine black, Position position, MatchOptions option = MatchOptions.None) { // If randomize colour is given as the match option, give a 50% chance of // of swapping white and black. The result is still returned from the // original white's perspective. if (option == MatchOptions.RandomizeColour) { if (Random.Boolean()) { MatchResult result = Play(black, white, position, MatchOptions.None); return(result == MatchResult.Win ? MatchResult.Loss : result == MatchResult.Loss ? MatchResult.Win : result); } else { return(Play(white, black, position, MatchOptions.None)); } } Int32 halfMovesLimit = HalfMovesLimit; if (option == MatchOptions.UnlimitedLength) { halfMovesLimit = Int32.MaxValue; } // Play the match. while (true) { IPlayer player = (position.SideToMove == Colour.White) ? white : black; position.Make(player.GetMove(position)); if (position.LegalMoves().Count == 0) { if (position.InCheck(position.SideToMove)) { return(player.Equals(white) ? MatchResult.Win : MatchResult.Loss); } else { return(MatchResult.Draw); } } if (position.FiftyMovesClock >= 100 || position.InsufficientMaterial() || position.HasRepeated(3)) { return(MatchResult.Draw); } if (position.HalfMoves >= halfMovesLimit) { int materialDifference = position.Material[Colour.White] - position.Material[Colour.Black]; if (Math.Abs(materialDifference) >= MaterialLimit) { return(materialDifference > 0 ? MatchResult.Win : MatchResult.Loss); } return(MatchResult.Unresolved); } } }
static bool MatchName (Dictionary<string, MatchResult> savedMatches, StringMatcher matcher, string name, out int matchRank) { if (name == null) { matchRank = -1; return false; } MatchResult savedMatch; if (!savedMatches.TryGetValue (name, out savedMatch)) { bool doesMatch = matcher.CalcMatchRank (name, out matchRank); savedMatches [name] = savedMatch = new MatchResult (doesMatch, matchRank); } matchRank = savedMatch.Rank; return savedMatch.Match; }
public NoMatch(string input, MatchResult status) : base(input) { this.status = status; }
/// <summary> /// Creates an instance of this class. /// </summary> /// <param name="match">The current MatchResult</param> /// <param name="removeWhiteSpace">Determines if leading white space was removed</param> /// <history> /// [Curtis_Beard] 04/08/2015 ADD: switch from Rich Text Box to AvalonEdit /// </history> public ResultHighlighter(MatchResult match, bool removeWhiteSpace) { this.match = match; this.removeWhiteSpace = removeWhiteSpace; }
public void AddMatchResult(MatchResult result) { Results.Add(result); }
public async Task <IActionResult> UpdateTeams([FromBody] MatchResult Match) { return(new OkObjectResult(await _adminService.UpdateTeams(Match))); }
public Message(MessageType type, MatchResult matchResult) { MessageType = type; MatchResult = matchResult; }
/// <summary> /// Creates an instance of MatchEndEvent. /// </summary> /// <param name="matchResult">the Match's end result</param> /// <param name="winner">the winner for the Match</param> internal MatchEndEvent(MatchResult matchResult, Player winner) { MatchResult = matchResult; Winner = winner; }
protected virtual void Awake() { this.name = GlobalSettings.MatchControlName; this.GameEndDelay = 5; this.result = MatchResult.Undefined; }
bool MatchName (string name, out int matchRank) { if (name == null) { matchRank = -1; return false; } MatchResult savedMatch; if (!savedMatches.TryGetValue (name, out savedMatch)) { bool doesMatch; if (firstChars != null) { int idx = name.IndexOfAny (firstChars); doesMatch = idx >= 0; if (doesMatch) { matchRank = int.MaxValue - (name.Length - 1) * 10 - idx; if (name [idx] != firstChar) matchRank /= 2; savedMatches [name] = savedMatch = new MatchResult (true, matchRank); return true; } matchRank = -1; savedMatches [name] = savedMatch = new MatchResult (false, -1); return false; } doesMatch = matcher.CalcMatchRank (name, out matchRank); savedMatches [name] = savedMatch = new MatchResult (doesMatch, matchRank); } matchRank = savedMatch.Rank; return savedMatch.Match; }
public async Task <bool> PublishSessionsSchedulesAsync(List <LeagueSessionScheduleViewModel> newLeagueSessionsSchedules, CancellationToken ct = default(CancellationToken)) { List <LeagueSessionSchedule> leagueSessionOperations = new List <LeagueSessionSchedule>(); foreach (LeagueSessionScheduleViewModel newSchedule in newLeagueSessionsSchedules) { LeagueSessionSchedule leagueSessionSchedule = new LeagueSessionSchedule() { Active = newSchedule.Active, LeagueID = newSchedule.LeagueID, ByeWeeks = newSchedule.ByeWeeks, NumberOfWeeks = newSchedule.NumberOfWeeks, SessionStart = newSchedule.SessionStart, SessionEnd = newSchedule.SessionEnd }; // create game day entry for all configured game days foreach (GameDayViewModel gameDay in newSchedule.GamesDays) { GameDay newGameDay = new GameDay() { GamesDay = gameDay.GamesDay }; // create game time entry for every game day foreach (GameTimeViewModel gameTime in gameDay.GamesTimes) { GameTime newGameTime = new GameTime() { GamesTime = DateTimeOffset.FromUnixTimeSeconds(gameTime.GamesTime).DateTime.ToLocalTime(), }; newGameDay.GamesTimes.Add(newGameTime); } leagueSessionSchedule.GamesDays.Add(newGameDay); } // update teams sessions foreach (TeamSessionViewModel teamSession in newSchedule.TeamsSessions) { // retrieve the team with the corresponding id Team team = await this._teamRepository.GetByIdAsync(teamSession.TeamId, ct); if (team != null) { TeamSession newTeamSession = new TeamSession() { Team = team, LeagueSessionSchedule = leagueSessionSchedule }; leagueSessionSchedule.TeamsSessions.Add(newTeamSession); } } // update matches for this session foreach (MatchViewModel match in newSchedule.Matches) { // if match DateTime is not set do not add it to the database if (match.DateTime != 0) { Match newMatch = new Match() { DateTime = match.DateTime, HomeTeamId = match.HomeTeamId, AwayTeamId = match.AwayTeamId, LeagueID = match.LeagueID }; MatchResult newMatchResult = new MatchResult() { LeagueId = match.LeagueID, HomeTeamId = match.HomeTeamId, AwayTeamId = match.AwayTeamId }; newMatch.MatchResult = newMatchResult; leagueSessionSchedule.Matches.Add(newMatch); } } leagueSessionOperations.Add(await this._sessionScheduleRepository.AddScheduleAsync(leagueSessionSchedule, ct)); } // ensure all leagueSessionOperations did not return any null values return(leagueSessionOperations.All(op => op != null)); }
/// <summary> /// Run LocatorHub Search /// </summary> internal void RunSearch() { try { if (LocatorCombo.Current.SelectedIndex == -1) { return; } //Get locator OnlineLocator onlineLocator = DataHubConfiguration.Current.Locators[LocatorCombo.Current.SelectedIndex]; //Get Query String String Query = LocatorSearchQuery.Current.TextValue; //Get use Fuzzy bool UseFuzzy = DataHubConfiguration.Current.UseFuzzy; //create popup form LocatorHub.LocatorHub client = LocatorManager.CreateClient(onlineLocator); LocatorPopupForm locatorPopupForm = new LocatorPopupForm(client); int factcode = -1; try { IMxDocument mxDocument = ArcMap.Application.Document as IMxDocument; //get map IMap map = mxDocument.FocusMap; factcode = map.SpatialReference.FactoryCode; } catch (Exception) { factcode = -1; } //Setup form locatorPopupForm.Setup(onlineLocator.Target, Query, onlineLocator.GazId, UseFuzzy, LocatorCombo.Current.TextValue, factcode); //Show popup if multiple records if (locatorPopupForm.FoundRecord == null && locatorPopupForm.FailReason == MatchResultCodes.PickList) { //Show Dialog locatorPopupForm.ShowDialog(); } if (locatorPopupForm.DialogResult == DialogResult.OK) { //get the matchresult from the popupform MatchResult matchResult = locatorPopupForm.FoundRecord; ClearGraphics(); string[] values = matchResult.MatchedRecord.R.V; string[] point = values[locatorPopupForm.ColumnLookup["LOCATOR_POINT"]].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); // string description = values[locatorPopupForm.ColumnLookup["LOCATOR_DESCRIPTION"]]; string[] fieldNames = onlineLocator.FieldList(); StringBuilder sb = new StringBuilder(values[locatorPopupForm.ColumnLookup[fieldNames[0]]]); for (int i = 1; i < fieldNames.Length; i++) { sb.Append("|LOCATOR_SEPARATOR|"); sb.Append(values[locatorPopupForm.ColumnLookup[fieldNames[i]]]); } string description = sb.ToString(); string[] extent = values[locatorPopupForm.ColumnLookup["LOCATOR_ENVELOPE"]].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); AddPoint(point[0].ToDouble(), point[1].ToDouble(), matchResult.ReturnedCoordinateSystem, description, extent[0].ToDouble(), extent[1].ToDouble(), extent[2].ToDouble(), extent[3].ToDouble()); } else if (locatorPopupForm.DialogResult == DialogResult.Abort) { switch (locatorPopupForm.FailReason) { case MatchResultCodes.NoMatchNoResult: MessageBox.Show("No Match. There were no matches for the specified query.", "Query"); break; case MatchResultCodes.NoMatchTooVague: MessageBox.Show("Query too vague. There were too many possible matches for the specified query.", "Query"); break; } } locatorPopupForm = null; } catch (Exception ex) { ShowError(ex); } }
public IndexModule() { Get["/"] = parameters => { return(View["index"]); }; Get["/upload"] = parameters => { return(View["upload"]); }; Get["/certificate"] = parameters => { return(View["cert"]); }; Get["/result"] = parameters => { string enhancedQRCodePath = Path.Combine("data", "qrdata") + @"\" + "EnhancedqrImage.bmp"; Bitmap QRcodeImage = new Bitmap(Bitmap.FromFile(enhancedQRCodePath)); Rectangle cropArea = new Rectangle(); cropArea.Width = 357; cropArea.Height = 392; cropArea.X = (QRcodeImage.Width - cropArea.Width) / 2; cropArea.Y = (QRcodeImage.Height - cropArea.Height) / 2; Bitmap bmpCrop = QRcodeImage.Clone(cropArea, QRcodeImage.PixelFormat); string rawFPImage = Path.Combine("data", "qrdata") + @"\" + "fingerprint.bmp"; bmpCrop.Save(rawFPImage); LuminanceSource source = new BitmapLuminanceSource(QRcodeImage); BinaryBitmap newbitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result = new MultiFormatReader().decodeWithState(newbitmap); if (result.Text != requestTime) { return(Response.AsJson(new { Result = "Authentication failure" })); } else { //Write your code here!(next time!) //return Response.AsJson(new { Result = result.Text }); } return(Response.AsImage(rawFPImage)); }; Get["/securityUpload"] = parameters => { return(View["secert"]); }; Post["/severification"] = parameters => { var file = this.Request.Files.ElementAt <HttpFile>(0); string uploadPath = Path.Combine("data", "test", file.Name); if (!Directory.Exists(Path.Combine("data", "test"))) { Directory.CreateDirectory(Path.Combine("data", "test")); } using (var fileStream = new FileStream(uploadPath, FileMode.Create)) { file.Value.CopyTo(fileStream); } string QRcodePath = Path.Combine("data", "qrdata") + @"\" + "qrImage.bmp"; Bitmap fpImage = new Bitmap(Bitmap.FromFile(uploadPath)); Bitmap RawQRImage = new Bitmap(Bitmap.FromFile(QRcodePath)); Bitmap QRImage = new Bitmap(RawQRImage.Width, RawQRImage.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(QRImage)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.DrawImage(RawQRImage, 0, 0); } int middleImgW = Math.Min((int)(realSize.Width / 3.5), fpImage.Width); int middleImgH = Math.Min((int)(realSize.Height / 3.5), fpImage.Height); int middleImgL = (QRImage.Width - middleImgW) / 2; int middleImgT = (QRImage.Height - middleImgH) / 2; System.Drawing.Graphics MyGraphic = System.Drawing.Graphics.FromImage(QRImage); MyGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH); MyGraphic.DrawImage(fpImage, middleImgL, middleImgT, middleImgW, middleImgH); string enhancedQRCodePath = Path.Combine("data", "qrdata") + @"\" + "EnhancedqrImage.bmp"; QRImage.Save(enhancedQRCodePath); return(Response.AsImage(enhancedQRCodePath)); }; Get["/barcode"] = parameters => { BarcodeWriter writer = new BarcodeWriter(); writer.Format = BarcodeFormat.QR_CODE; writer.Options = new QrCodeEncodingOptions { DisableECI = true, CharacterSet = "UTF-8", Width = 1840, Height = 1840, ErrorCorrection = ErrorCorrectionLevel.H }; requestTime = DateTime.Now.ToString(); Bitmap qrImage = writer.Write(requestTime); string path = Path.Combine("data", "qrdata"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string imagePath = path + @"\" + "qrImage.bmp"; qrImage.Save(imagePath); return(Response.AsImage(imagePath)); }; Post["/verification"] = parameters => { string userId = (string)this.Request.Form.userId; List <Model.Fingerprint> fingerprints = SqlHelper.getImages(userId); var file = this.Request.Files.ElementAt <HttpFile>(0); string uploadPath = Path.Combine("data", "test", file.Name); if (!Directory.Exists(Path.Combine("data", "test"))) { Directory.CreateDirectory(Path.Combine("data", "test")); } using (var fileStream = new FileStream(uploadPath, FileMode.Create)) { file.Value.CopyTo(fileStream); } SourceAFIS.Simple.Fingerprint fp1 = new SourceAFIS.Simple.Fingerprint(); fp1.AsBitmap = new Bitmap(Bitmap.FromFile(uploadPath)); Person person1 = new Person(); person1.Fingerprints.Add(fp1); Afis.Extract(person1); List <MatchResult> results = new List <MatchResult>(); foreach (var fp in fingerprints) { SourceAFIS.Simple.Fingerprint fp2 = new SourceAFIS.Simple.Fingerprint(); fp2.AsBitmap = new Bitmap(Bitmap.FromFile(fp.fpPath)); Person person2 = new Person(); person2.Fingerprints.Add(fp2); Afis.Extract(person2); MatchResult result = new MatchResult(); result.fingerprint = fp.fpName + fp.sampleNumber.ToString(); result.score = Afis.Verify(person1, person2); results.Add(result); } return(Response.AsJson <List <MatchResult> >(results)); }; Post["/upload"] = parameters => { User user = new User(); Model.Fingerprint fp1 = new Model.Fingerprint(); Model.Fingerprint fp2 = new Model.Fingerprint(); Model.Fingerprint fp3 = new Model.Fingerprint(); Model.Fingerprint fp4 = new Model.Fingerprint(); Model.Fingerprint fp5 = new Model.Fingerprint(); user.userId = (string)this.Request.Form.id; user.userName = (string)this.Request.Form.name; fp1.fpName = (string)this.Request.Form.fpname1; fp2.fpName = (string)this.Request.Form.fpname2; fp3.fpName = (string)this.Request.Form.fpname3; fp4.fpName = (string)this.Request.Form.fpname4; fp5.fpName = (string)this.Request.Form.fpname5; fp1.sampleNumber = (int)this.Request.Form.samplenumber1; fp2.sampleNumber = (int)this.Request.Form.samplenumber2; fp3.sampleNumber = (int)this.Request.Form.samplenumber3; fp4.sampleNumber = (int)this.Request.Form.samplenumber4; fp5.sampleNumber = (int)this.Request.Form.samplenumber5; fp1.userID = user.userId; fp2.userID = user.userId; fp3.userID = user.userId; fp4.userID = user.userId; fp5.userID = user.userId; fp1.fpID = fp1.userID + fp1.fpName + fp1.sampleNumber.ToString(); fp2.fpID = fp1.userID + fp2.fpName + fp2.sampleNumber.ToString(); fp3.fpID = fp3.userID + fp3.fpName + fp3.sampleNumber.ToString(); fp4.fpID = fp4.userID + fp4.fpName + fp4.sampleNumber.ToString(); fp5.fpID = fp5.userID + fp5.fpName + fp5.sampleNumber.ToString(); var file1 = this.Request.Files.ElementAt <HttpFile>(0); var file2 = this.Request.Files.ElementAt <HttpFile>(1); var file3 = this.Request.Files.ElementAt <HttpFile>(2); var file4 = this.Request.Files.ElementAt <HttpFile>(3); var file5 = this.Request.Files.ElementAt <HttpFile>(4); fp1.fpPath = @"data\" + user.userName + @"\" + fp1.fpID + file1.Name.Substring(file1.Name.Length - 4, 4); fp2.fpPath = @"data\" + user.userName + @"\" + fp2.fpID + file2.Name.Substring(file2.Name.Length - 4, 4); fp3.fpPath = @"data\" + user.userName + @"\" + fp3.fpID + file3.Name.Substring(file3.Name.Length - 4, 4); fp4.fpPath = @"data\" + user.userName + @"\" + fp4.fpID + file4.Name.Substring(file4.Name.Length - 4, 4); fp5.fpPath = @"data\" + user.userName + @"\" + fp5.fpID + file5.Name.Substring(file5.Name.Length - 4, 4); //fp1.fpPath = Path.Combine("data", user.userName, fp1.fpID + file1.Name.Substring(file1.Name.Length - 4, 4)); if (!Directory.Exists(Path.Combine("data", user.userName))) { Directory.CreateDirectory(Path.Combine("data", user.userName)); } using (var fileStream = new FileStream(fp1.fpPath, FileMode.Create)) { file1.Value.CopyTo(fileStream); } using (var fileStream = new FileStream(fp2.fpPath, FileMode.Create)) { file2.Value.CopyTo(fileStream); } using (var fileStream = new FileStream(fp3.fpPath, FileMode.Create)) { file3.Value.CopyTo(fileStream); } using (var fileStream = new FileStream(fp4.fpPath, FileMode.Create)) { file4.Value.CopyTo(fileStream); } using (var fileStream = new FileStream(fp5.fpPath, FileMode.Create)) { file5.Value.CopyTo(fileStream); } if (!SqlHelper.isExistUser(user)) { SqlHelper.insertToUser(user); } int i1 = SqlHelper.insertToFingerprint(fp1); int i2 = SqlHelper.insertToFingerprint(fp2); int i3 = SqlHelper.insertToFingerprint(fp3); int i4 = SqlHelper.insertToFingerprint(fp4); int i5 = SqlHelper.insertToFingerprint(fp5); if (i1 != 0 && i2 != 0 && i3 != 0 && i4 != 0 && i5 != 0) { return(Response.AsJson(new { Result = "Insert Sucess" })); } else { return(Response.AsJson(new { Result = "Insert Failed" })); } }; Get["/getUser"] = parameters => { string myconn = "Database='fingerprint';Data Source=localhost;User ID=lich;Password=123456;CharSet=utf8;"; string mysql = "SELECT * from user"; MySqlConnection myconnection = new MySqlConnection(myconn); myconnection.Open(); MySqlCommand mycommand = new MySqlCommand(mysql, myconnection); MySqlDataReader myreader = mycommand.ExecuteReader(); List <User> userList = new List <User>(); while (myreader.Read()) { User user = new User(); user.userId = myreader.GetString(0); user.userName = myreader.GetString(1); userList.Add(user); } myreader.Close(); myconnection.Close(); return(Response.AsJson <List <User> >(userList)); }; Get["/inserttest"] = parameters => { User user = new User(); user.userId = "13T2001"; user.userName = "******"; int i = SqlHelper.insertToUser(user); if (i != 0) { return(Response.AsJson(new { Result = "Insert Sucess" })); } else { return(Response.AsJson(new { Result = "Insert Failed" })); } }; }
public Matcher Matcher(MatchResult res, int groupId) { Matcher m = new Matcher(this); if(res is Matcher){ m.SetTarget((Matcher)res, groupId); } else{ m.SetTarget(res.TargetChars, res.GetStart(groupId)+res.TargetStart, res.GetLength(groupId)); } return m; }
private INancyModule GetModuleFromMatchResult(NancyContext context, MatchResult result) { var module = this.catalog.GetModule(result.ModuleType, context); return this.moduleBuilder.BuildModule(module, context); }
public Matcher Matcher(MatchResult res, string groupName) { int id = res.Pattern.GroupId(groupName); return Matcher(res, id); }
public static string Find(string pattern, string flags, string[] files) { Directory.SetCurrentDirectory(Path.GetTempPath()); var readFiles = files.Select(file => { return(new ReadContext() { FileName = file, Context = File.ReadAllText($"{Path.GetTempPath()}/{file}") .Split('\n') .Where(str => !IsNullOrEmpty(str)) }); }); var cmd = new Command(flags, files.Length > 1); var part = new Regex(cmd.IsCaseInsenstive ? $"(?i){pattern}" : pattern); var matches = new List <MatchResult>(); foreach (var file in readFiles) { var context = file.Context .Select((section, index) => { var match = new MatchResult(); if (cmd.IsMatchEntireLines) { if (cmd.IsCaseInsenstive && section.ToLower().Equals(pattern.ToLower())) { match = SetupMatchResult(index, section, file.FileName, cmd); } else if (section.Equals(pattern)) { match = SetupMatchResult(index, section, file.FileName, cmd); } else if (cmd.IsInverMatches) { match = SetupMatchResult(index, section, file.FileName, cmd); } return(match); } else if (part.IsMatch(section)) { if (cmd.IsInverMatches) { return(match); } else { return(SetupMatchResult(index, section, file.FileName, cmd)); } } else if (cmd.IsInverMatches) { return(match = SetupMatchResult(index, section, file.FileName, cmd)); } else { return(match); } }) .Where(matchReuslt => !string.IsNullOrEmpty(matchReuslt.Context)); matches.AddRange(context); } return(cmd.IsPrintFileName ? Concat(matches.GroupBy(item => item.FileName).Select(match => match.Key + '\n')) : Concat(matches.CombinMatches())); }
/// <summary> /// Searches the given file for the given search text. /// </summary> /// <param name="file">FileInfo object</param> /// <param name="searchSpec">ISearchSpec interface value</param> /// <param name="ex">Exception holder if error occurs</param> /// <returns>Hitobject containing grep results, null if on error</returns> public MatchResult Grep(FileInfo file, ISearchSpec searchSpec, ref Exception ex) { // initialize Exception object to null ex = null; MatchResult match = null; if (Parser.IsParseable(file.FullName)) { string fileContent = Parser.Parse(file.FullName); if (!string.IsNullOrEmpty(fileContent)) { string[] lines = fileContent.Split(new char[] { '\n', '\r' }); for (int i = 0; i < lines.Length; i++) { string line = lines[i]; int posInStr = -1; Regex reg = null; MatchCollection regCol = null; if (searchSpec.UseRegularExpressions) { string pattern = string.Format("{0}{1}{0}", searchSpec.UseWholeWordMatching ? "\\b" : string.Empty, searchSpec.SearchText); RegexOptions options = searchSpec.UseCaseSensitivity ? RegexOptions.None : RegexOptions.IgnoreCase; reg = new Regex(pattern, options); regCol = reg.Matches(line); if (regCol.Count > 0) { posInStr = 1; } } else { // If we are looking for whole worlds only, perform the check. if (searchSpec.UseWholeWordMatching) { reg = new Regex("\\b" + Regex.Escape(searchSpec.SearchText) + "\\b", searchSpec.UseCaseSensitivity ? RegexOptions.None : RegexOptions.IgnoreCase); // if match is found, also check against our internal line hit count method to be sure they are in sync Match mtc = reg.Match(line); if (mtc != null && mtc.Success && libbSearch.Grep.RetrieveLineMatches(line, searchSpec).Count > 0) { posInStr = mtc.Index; } } else { posInStr = line.IndexOf(searchSpec.SearchText, searchSpec.UseCaseSensitivity ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); } } if (posInStr > -1) { if (match == null) { match = new MatchResult(file); // found hit in file so just return if (searchSpec.ReturnOnlyFileNames) { break; } } var matchLineFound = new MatchResultLine() { Line = line, LineNumber = -1, HasMatch = true }; if (searchSpec.UseRegularExpressions) { posInStr = regCol[0].Index; match.SetHitCount(regCol.Count); foreach (Match regExMatch in regCol) { matchLineFound.Matches.Add(new MatchResultLineMatch(regExMatch.Index, regExMatch.Length)); } } else { var lineMatches = libbSearch.Grep.RetrieveLineMatches(line, searchSpec); match.SetHitCount(lineMatches.Count); matchLineFound.Matches = lineMatches; } matchLineFound.ColumnNumber = 1; match.Matches.Add(matchLineFound); } } } } return(match); }
/// <summary>Creates an instance of the <see cref="NamedGraphMatch"/>.</summary> /// <param name="namedGraph"><see cref="Uri"/> of the named graph.</param> /// <param name="idMatch">Match for entity identifiers.</param> /// <param name="predicateMatch">Match for predicates.</param> /// <param name="typeMatch">Match for types.</param> public NamedGraphMatch(Uri namedGraph, MatchResult idMatch, MatchResult predicateMatch, MatchResult typeMatch) : this() { NamedGraph = namedGraph; IdMatch = idMatch; PredicateMatch = predicateMatch; TypeMatch = typeMatch; }
public void ToggleTurn() { var turn = Turn; if (AllScored()) { /// Match result throw here... //SendMatchResultMsg resultMsg = new SendMatchResultMsg(); var Winner = ScoreOne > ScoreTwo ? WinCase.Player1 : WinCase.Player2; if (ScoreOne == ScoreTwo) { Winner = WinCase.Draw; } var matchResult = new MatchResult(); matchResult.Winner = Winner; matchResult.ScoreOne = ScoreOne; matchResult.ScoreTwo = ScoreTwo; //Call endgme local here //PhotonView.RPC("EndGameRPC", RpcTarget.All, matchResult); EndGameRPC(matchResult); return; } if (QueenScored) { QueenScoredTurnCount += 1; if (QueenScoredTurnCount == 2) { QueenScored = false; QueenScoredTurnCount = 0; if (!CurrentPlayerScored) { if (turn == PlayerType.Player1) { ScoreOne -= 50; GameSetupScript.GetInstance().respawnQueen(); // Call update score here //PhotonView.RPC("UpdateScoreRPC", RpcTarget.All, ScoreOne, ScoreTwo); UpdateScoreRPC(ScoreOne, ScoreTwo); } } } } switch (turn) { case PlayerType.Player1: turn = CurrentPlayerScored ? PlayerType.Player1 : PlayerType.Player2; break; case PlayerType.Player2: turn = CurrentPlayerScored ? PlayerType.Player2 : PlayerType.Player1; break; default: break; } if (CurrentPlayerScored) { CurrentPlayerScored = false; } if (Striger != null) { // Set Striger here Striger.GetComponent <StrigerControllerSingle>().setStriger(turn); } //Upodate turn here //PhotonView.RPC("updateTurnRPC", RpcTarget.All, turn); updateTurnRPC(turn); notifyRPC(turn == PlayerType.Player1 ? "Turn: Player 1" : "Turn: Player 2"); if (Turn == PlayerType.Player2) { // Player Computer turn here StartCoroutine(Striger.GetComponent <StrigerControllerSingle>().ComputerMovePossibleShot()); } }
internal async Task <ScoreResult[]> CalculatePlayerScores(string tenantId, string tournamentId, MatchResult result) { // 1. Get Players from tournament // 1.1 Get Tournament Entry var entry = await GetStateEntry(tenantId); // 1.2 Convert into List var tournaments = ToList(entry); // 1.3 Try get Tournament if (!tournaments.Any(t => t.Id == tournamentId)) { throw new NotFoundException($"Tournament Id {tournamentId} is not found"); } var tournament = tournaments.First(t => t.Id == tournamentId); // 1.4 Players must exist in Tournament if (!tournament.Players.Any(p => p.Id == result.Player1Id)) { throw new BadRequestException($"Player Id \"{result.Player1Id}\" does not exist in this Tournament."); } if (!tournament.Players.Any(p => p.Id == result.Player2Id)) { throw new BadRequestException($"Player Id \"{result.Player2Id}\" does not exist in this Tournament."); } var players = tournament.Players.ToDictionary(p => p.Id); // 1.5 Get each player's current score and parse to ScoreResult ScoreResult playerOne = new ScoreResult(result.Player1Id, players[result.Player1Id].RankingScore); ScoreResult playerTwo = new ScoreResult(result.Player2Id, players[result.Player2Id].RankingScore); ScoreResult[] scores = { playerOne, playerTwo }; // 2. Calculate score ScoreResult[] newScores = _scoreCalculator.Calculate(scores, result.WinnerId); // 3. Return score results return(newScores); }
private static MatchResult FindMatchKMP(byte[] input, int readPos) { var result = new MatchResult(); var startPos = Math.Max(readPos - SEARCH_SIZE, 0); var searchSize = Math.Min(SEARCH_SIZE, readPos - startPos); var maxLength = Math.Min(input.Length - readPos, MAX_LENGTH); maxLength = Math.Min(maxLength, readPos); if (maxLength < 3) { result.Found = false; result.Distance = 0; result.Length = 1; return(result); } var bestPos = 0; var bestLength = 0; var kmpTable = FillTable(input, readPos, maxLength); var k = 0; var i = 0; while (k + i < searchSize && i < maxLength) { if (input[readPos + i] == input[startPos + k + i]) { i++; if (i == maxLength) { bestLength = i; bestPos = k + startPos; break; } } else { if (i > bestLength) { bestLength = i; bestPos = k + startPos; } k = k + i - kmpTable[i]; i = kmpTable[i] > 0 ? kmpTable[i] : 0; } } if (bestLength >= 3) { result.Found = true; result.Distance = readPos - bestPos; result.Length = bestLength; } else { result.Found = false; result.Distance = 0; result.Length = 1; } return(result); }
/// <summary> /// Creates an instance of this class. /// </summary> /// <param name="match">The current MatchResult</param> /// <param name="removeWhiteSpace">Determines if leading white space was removed</param> /// <param name="showingFullFile">Determines if showing full file contents or just matches</param> /// <history> /// [Curtis_Beard] 04/08/2015 ADD: switch from Rich Text Box to AvalonEdit /// </history> public ResultHighlighter(MatchResult match, bool removeWhiteSpace, bool showingFullFile) : this(match, removeWhiteSpace) { this.showingFullFile = showingFullFile; }
internal override MatchResult SubBeginProcessMatch(Tracker tracker, IEventStream eventenum, CaptureList CapturedList) { if (eventenum.Current == null) { return(MatchResult.None); } MatchResult tres = MatchResult.None; var sbag = GetQuantifierState(tracker); if (!sbag.MatchCount.HasValue) { sbag.MatchCount = new Nullable <int>(0); tracker.SetMyStateBag(this, sbag); } var specEventStream = eventenum;//eventenum.CreateSpeculator(); do { MatchResult subRes = MatchResult.None; subRes = ContainedElement.BeginProcessMatch(tracker, eventenum, sbag.CaptureList); if (!subRes.Is_Match()) { //if we matched our minimun we can make a final decisison if it did not match if (sbag.MatchCount.Value >= MinOccours) { tres = MatchResult.Match | MatchResult.Forward; } else//if we have not yet matched our minimun then we just need to continue { tres = MatchResult.Continue | MatchResult.Capture; } } //if we did match if (subRes.Is_Match()) { //if we reached the max then return a match if (sbag.MatchCount.Value + 1 == MaxOccours) { tres = IsMatchResult.IsMatch; } else { //if we matched at least min then mark as match and contineu if (sbag.MatchCount.Value + 1 >= MinOccours) { tres = MatchResult.Match | MatchResult.Continue | MatchResult.Capture; } else { //just continue matching //if the subres has a forward , then don't capture , just relay the forward if (subRes.Is_Forward()) { tres = MatchResult.Continue | MatchResult.Forward; } else { tres = MatchResult.Continue | MatchResult.Capture; } } } } //if its the end (either a match or not) , then remove our bag state if (!tres.Is_Continue()) { tracker.RemoveMyStateBag(this); } else { //if its a continue then increment the bagstate sbag.MatchCount++; tracker.SetMyStateBag(this, sbag); } if (subRes.Is_Forward()) { tres = tres | MatchResult.Forward; } //if this is a match without a continue then grab the commmit the speculator //and add the spculative captures to the tracker captures if (tres.Is_Match() && !tres.Is_Continue()) { //specEventStream.EndApplyAll(); if (CapturedList != null) { CapturedList.AddRange(sbag.CaptureList.Items); } return(tres); } //if this is not a match and not a continue then rollback the speculator and return the result if (!tres.Is_Match() && !tres.Is_Continue()) { //specEventStream.EndDiscardAll(); return(tres); } //its a continue so allow the loop to continue }while ( specEventStream.MoveNextIfNotForward(tres)); //if we are here it means that we ran out of events so we got to deal with that if (tres.Is_Match()) { if (CapturedList != null) { CapturedList.AddRange(sbag.CaptureList.Items); } } //remove the continue if its there if (tres.Is_Continue()) { var mask = ~MatchResult.Continue; tres = tres & mask; } return(tres); }
private Module GetModuleFromMatchResult(Context context, MatchResult result) { var module = _catalog.GetModule(result.ModuleType); return(_moduleBuilder.BuildModule(module, context)); }
private async Task Loop(CancellationToken cancellationToken) { var teams = new Teams { Blue = ImmutableList.Create(MatchTesting.TestVenonatForOverlay), Red = ImmutableList.Create(MatchTesting.TestVenonatForOverlay), }; await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken); IMatchCycle match = new CoinflipMatchCycle(_loggerFactory.CreateLogger <CoinflipMatchCycle>()); Task setupTask = match.SetUp(new MatchInfo(teams.Blue, teams.Red), cancellationToken); await _overlayConnection.Send(new MatchCreatedEvent(), cancellationToken); await _overlayConnection.Send(new MatchBettingEvent(), cancellationToken); await _overlayConnection.Send(new MatchModesChosenEvent(), cancellationToken); // TODO await _overlayConnection.Send(new MatchSettingUpEvent { MatchId = 1234, Teams = teams, BettingDuration = _matchmodeConfig.DefaultBettingDuration.TotalSeconds, RevealDuration = 0, Gimmick = "speed", Switching = SwitchingPolicy.Never, BattleStyle = BattleStyle.Singles, InputOptions = new InputOptions { Moves = new MovesInputOptions { Policy = MoveSelectingPolicy.Always, Permitted = ImmutableList.Create("a", "b", "c", "d") }, Switches = new SwitchesInputOptions { Policy = SwitchingPolicy.Never, Permitted = ImmutableList <string> .Empty, RandomChance = 0 }, Targets = new TargetsInputOptions { Policy = TargetingPolicy.Disabled, Permitted = ImmutableList <string> .Empty, AllyHitChance = 0 }, }, BetBonus = 35, BetBonusType = "bet", }, cancellationToken); Duration bettingBeforeWarning = _matchmodeConfig.DefaultBettingDuration - _matchmodeConfig.WarningDuration; await Task.Delay(bettingBeforeWarning.ToTimeSpan(), cancellationToken); await _overlayConnection.Send(new MatchWarningEvent(), cancellationToken); await Task.Delay(_matchmodeConfig.WarningDuration.ToTimeSpan(), cancellationToken); await setupTask; Task <MatchResult> performTask = match.Perform(cancellationToken); await _overlayConnection.Send(new MatchPerformingEvent { Teams = teams }, cancellationToken); MatchResult result = await performTask; await _overlayConnection.Send(new MatchOverEvent { MatchResult = result }, cancellationToken); await Task.Delay(_matchmodeConfig.ResultDuration.ToTimeSpan(), cancellationToken); await _overlayConnection.Send(new ResultsFinishedEvent(), cancellationToken); }