public SpamProbability GetSpamProbability(ServerMessagesCacheService serverMessagesCacheService, DiscordRequest request, Contexts contexts) { var userId = contexts.User.Id; var serverId = contexts.Server.Id; var lastFewMessages = serverMessagesCacheService.GetLastUserMessages(userId, serverId) .TakeLast(4) .ToList(); if (lastFewMessages.Count < 2) { return(SpamProbability.None); } var content = request.OriginalMessage; var percentOfSimilarityToSuspectSpam = this._configurationService.GetConfigurationItem <PercentOfSimilarityBetweenMessagesToSuspectSpam>(serverId).Value; var similarMessagesCount = lastFewMessages.Count(x => this.GetDifferencePercent(x.Content, content) < percentOfSimilarityToSuspectSpam); var isUserSafe = this.UserSafetyChecker.IsUserSafe(userId, serverId); return(similarMessagesCount switch { 0 => SpamProbability.None, 1 => SpamProbability.Low, 2 when isUserSafe => SpamProbability.Low, 2 => SpamProbability.Medium, _ when isUserSafe => SpamProbability.Medium, _ => SpamProbability.Sure });
private T GetDotNetPropertyImpl <T>(object obj, string propertyName, MemberNamePredicate predicate = null) where T : PSMemberInfo { bool lookingForProperties = typeof(T).IsAssignableFrom(typeof(PSProperty)); bool lookingForParameterizedProperties = IsTypeParameterizedProperty(typeof(T)); if (!lookingForProperties && !lookingForParameterizedProperties) { return(null); } CacheTable typeTable = _isStatic ? GetStaticPropertyReflectionTable((Type)obj) : GetInstancePropertyReflectionTable(obj.GetType()); object entry = typeTable[propertyName]; return(entry switch { null => null, PropertyCacheEntry cacheEntry when lookingForProperties => new PSProperty( cacheEntry.member.Name, this, obj, cacheEntry) as T, ParameterizedPropertyCacheEntry paramCacheEntry when lookingForParameterizedProperties => new PSParameterizedProperty( paramCacheEntry.propertyName, this, obj, paramCacheEntry) as T, _ => null, });
public SpamProbability GetSpamProbability(ServerMessagesCacheService serverMessagesCacheService, Contexts contexts) { var userId = contexts.User.Id; var serverId = contexts.Server.Id; var lastFewMessages = serverMessagesCacheService.GetLastUserMessages(userId, serverId) .TakeLast(5) .ToList(); if (lastFewMessages.Count < 2) { return(SpamProbability.None); } var percentOfSimilarityToSuspectSpam = this._configurationService.GetConfigurationItem <PercentOfSimilarityBetweenMessagesToSuspectSpam>(serverId).Value; var content = lastFewMessages.Last().Content; var similarMessagesCount = lastFewMessages .SkipLast(1) // because I'm comparing all the other messages to the last message .Count(x => this.GetDifferencePercent(x.Content, content) < percentOfSimilarityToSuspectSpam); var isUserSafe = this._userSafetyChecker.IsUserSafe(userId, serverId); return(similarMessagesCount switch { 0 => SpamProbability.None, 1 => SpamProbability.Low, 2 when isUserSafe => SpamProbability.Low, 2 => SpamProbability.Medium, _ when isUserSafe => SpamProbability.Medium, _ => SpamProbability.Sure });
public ISpecification <NodeModelBase> GetSpecification() => (IsSearchEnabled, IsRegexSearchEnabled) switch { (true, true)when IsValid => new NodeNameRegexSpecification(_regexService, SearchText, IsSearchCaseSensitive), (true, false) => new NodeNameTextSpecification(SearchText, IsSearchCaseSensitive), _ => new EmptySpecification() };
private static string ParseConstant(string expression, int currentPosition) { var stringBuilder = new StringBuilder(); var firstRound = true; while (currentPosition < expression.Length) { char result; var nextAvailable = currentPosition + 1 < expression.Length; var couldParse = nextAvailable switch { true when firstRound => TryParseCurrentCharFirstRoundAndNextAvailable(expression, currentPosition, out result), true => TryParseCurrentCharWhenNextAvailable(expression, currentPosition, out result), _ => TryParseCurrentCharWhenNextUnavailable(expression, currentPosition, out result) }; if (couldParse) { stringBuilder.Append(result); currentPosition++; firstRound = false; continue; } break; } return(stringBuilder.ToString()); }
private AliceResponse Enter(AliceRequest request, bool restart = false) { bool newUser = _gameplayService.EnterIsNewUser(request.State.User, request.State.Session); Phrase phrase = restart switch { true => new Phrase( "[audio|dialogs-upload/008dafcd-99bc-4fd1-9561-4686c375eec6/cb19ca47-2ef6-4788-b09f-0d47776e4de3.opus]" + "Начинаем новую игру. Перечисли имена игроков:", _prepareButtons ), false when newUser => new Phrase( "[audio|dialogs-upload/008dafcd-99bc-4fd1-9561-4686c375eec6/cb19ca47-2ef6-4788-b09f-0d47776e4de3.opus]" + "Привет. В этой игре я буду загадывать тебе или вам с друзьями определения, " + "а вы должны называть слова. Кто больше угадал — тот и выиграл.\n\n" + "Для начала перечисли имена игроков:", _prepareButtons ), _ => new Phrase( "[audio|dialogs-upload/008dafcd-99bc-4fd1-9561-4686c375eec6/cb19ca47-2ef6-4788-b09f-0d47776e4de3.opus]" + "Привет! Чтобы начать игру, перечисли имена игроков:", _prepareButtons ) }; return(phrase.Generate(request)); }
public void EveryNth(Action <int> everyNthAction, Action <int, bool> everyAction) { for (var i = 1; i < _total + 1; i++) { var must = MustRunNth(i); if (must) { everyNthAction(i); } if (must && !_runBothOnEvery) { continue; } everyAction(i, must); } bool MustRunNth(int current) => current switch { 0 when _runOnStart => true, 0 => false, _ => current % _everyNth == 0 }; } }
public INodeSpecification GetSpecification() => (IsSearchEnabled, IsRegexSearchEnabled) switch { (true, true)when HasText && IsValid => new NodeNameRegexSpecification(_regexService, SearchText, IsSearchCaseSensitive, IsRecursiveSearchEnabled), (true, false)when HasText => new NodeNameTextSpecification(SearchText, IsSearchCaseSensitive, IsRecursiveSearchEnabled), _ => new EmptySpecification(false) };
public int GetInvalidForm(int species, bool galar, PersonalTable stats) { return(species switch { (int)Pikachu when stats.TableLength == 1192 => 8, // LGPE Partner Pikachu (int)Slowbro when galar => 1, // Mega Slowbro _ => throw new ArgumentOutOfRangeException(nameof(species)) });
private void InitializeDashboardProjectInformation(StrykerOptions options, ProjectInfo projectInfo) { var dashboardReporterEnabled = options.Reporters.Contains(Reporter.Dashboard) || options.Reporters.Contains(Reporter.All); var dashboardBaselineEnabled = options.WithBaseline && options.BaselineProvider == BaselineProvider.Dashboard; var requiresProjectInformation = dashboardReporterEnabled || dashboardBaselineEnabled; if (!requiresProjectInformation) { return; } // try to read the repository URL + version for the dashboard report or dashboard baseline var missingProjectName = string.IsNullOrEmpty(options.ProjectName); var missingProjectVersion = string.IsNullOrEmpty(options.ProjectVersion); if (missingProjectName || missingProjectVersion) { var subject = missingProjectName switch { true when missingProjectVersion => "Project name and project version", true => "Project name", _ => "Project version" }; var projectFilePath = projectInfo.ProjectUnderTestAnalyzerResult.ProjectFilePath; if (!projectInfo.ProjectUnderTestAnalyzerResult.Properties.TryGetValue("TargetPath", out var targetPath)) { throw new InputException($"Can't read {subject.ToLowerInvariant()} because the TargetPath property was not found in {projectFilePath}"); } _logger.LogTrace("{Subject} missing for the dashboard reporter, reading it from {TargetPath}. " + "Note that this requires SourceLink to be properly configured in {ProjectPath}", subject, targetPath, projectFilePath); try { var targetName = Path.GetFileName(targetPath); using var module = ModuleDefinition.ReadModule(targetPath); var details = $"To solve this issue, either specify the {subject.ToLowerInvariant()} in the stryker configuration or configure [SourceLink](https://github.com/dotnet/sourcelink#readme) in {projectFilePath}"; if (missingProjectName) { options.ProjectName = ReadProjectName(module, details); _logger.LogDebug("Using {ProjectName} as project name for the dashboard reporter. (Read from the AssemblyMetadata/RepositoryUrl assembly attribute of {TargetName})", options.ProjectName, targetName); } if (missingProjectVersion) { options.ProjectVersion = ReadProjectVersion(module, details); _logger.LogDebug("Using {ProjectVersion} as project version for the dashboard reporter. (Read from the AssemblyInformationalVersion assembly attribute of {TargetName})", options.ProjectVersion, targetName); } } catch (Exception e) when(e is not InputException) { throw new InputException($"Failed to read {subject.ToLowerInvariant()} from {targetPath} because of error {e.Message}"); } } }
/// <param name="allowSlow">When "allowSlow" is false, method will not use Linq.Count() method and will return 0 or 1 instead.</param> private int GetCount(bool allowSlow) { return(DataSource switch { ICollection collection => collection.Count, DataGridCollectionView cv => cv.Count, IEnumerable enumerable when allowSlow => enumerable.Cast <object>().Count(), IEnumerable enumerable when !allowSlow => enumerable.Cast <object>().Any() ? 1 : 0, _ => 0 });
public static T CheckWin32Result <T>(T result) { return(result switch { SafeHandle handle when !handle.IsInvalid => result, HANDLE handle when PInvoke.INVALID_HANDLE_VALUE != handle.Value => result, uint n when n != 0xffffffff => result, bool b when b => result, BOOL b when b => result, _ => throw new Win32Exception() });
private void UpdateIsPaused() { bool IsPausedByFullScreen() => _settingsService.IsPauseWhenFullScreenEnabled && _externalApplicationService.IsForegroundApplicationFullScreen(); bool IsPausedByWhitelistedApplication() => _settingsService.IsApplicationWhitelistEnabled && _settingsService.WhitelistedApplications != null && _settingsService.WhitelistedApplications.Contains(_externalApplicationService.TryGetForegroundApplication()); IsPaused = IsPausedByFullScreen() || IsPausedByWhitelistedApplication(); }
public override object Convert(object v, Type t, object parameter, CultureInfo c) { return(v switch { bool bool_value when bool_value => Inverse ? Collapse ? Visibility.Collapsed : Visibility.Hidden : Visibility.Visible, bool bool_value when !bool_value => Inverse ? Visibility.Visible : Collapse ? Visibility.Collapsed : Visibility.Hidden, Visibility visible when visible == Visibility.Visible => !Inverse, Visibility visible when visible == Visibility.Hidden => Inverse, Visibility visible when visible == Visibility.Collapsed => Inverse, _ => null });
public char GetLetter() { bool isEven = row % 2 == 0; return(col switch { 0 when !isEven => 'A', 0 when isEven => 'B', 1 when !isEven => 'C', 1 when isEven => 'D', 2 when !isEven => 'E', 2 when isEven => 'F', 3 when !isEven => 'G', 3 when isEven => 'H', 4 => 'I', _ => 'J' });
public TextMeshPro GetLetterText(Index index, List <TextMeshPro> letters) { bool isEven = index.row % 2 == 0; return(index.col switch { 0 when !isEven => letters[0], 0 when isEven => letters[1], 1 when !isEven => letters[2], 1 when isEven => letters[3], 2 when !isEven => letters[4], 2 when isEven => letters[5], 3 when !isEven => letters[6], 3 when isEven => letters[7], 4 => letters[8], _ => null });
public async Task <TaskResponse[]> GetTasks( IManyTasksSettings settings, bool includeAllIfBlank = false) { var tasks = settings.Tasks; return((tasks.Length switch { 0 when includeAllIfBlank => await Host.GetTasks(), 0 => Array.Empty <TaskResponse>(), 1 => await Host.GetTasks(tasks.Single()), _ => await Host.GetTasks(BuildTaskExpression(tasks) ?? "false"), }).OrderBy(t => t.Name).ToArray());
/// <summary> /// Updates the color of the sprite based on the current wire state /// </summary> private void UpdateColor() { CurrentColor = _hovered switch { true when _wired => _hoverWire, true when !_wired => _hoverTint, false when _wired => _noHoverWire, false when !_wired => _noHoverTint, _ => new Color() }; }
// Takes an enumerable of 8 or fewer cells that represent the neighbours // The array itself is not nullable public void ShouldBeAlive(IEnumerable <Cell> neighbours) { int livingNeighbours = neighbours.Sum(neighbour => neighbour.IsAlive ? 1 : 0); // Using C# 8's new switch expression willBeAlive = livingNeighbours switch { 2 when IsAlive => true, 3 => true, _ => false }; }
private static string ReadTriple(string triple, bool showZeroHundred) { var(a, b, c) = triple.Select(ch => int.Parse(ch.ToString())).ToArray(); return(a switch { 0 when b == 0 && c == 0 => "", 0 when showZeroHundred => "không trăm " + ReadPair(b, c), 0 when b == 0 => Digits[c], 0 => ReadPair(b, c), _ => Digits[a] + " trăm " + ReadPair(b, c) });
private string DecodeLine(MemoryStream builder, bool foundCRLF, bool foundLF) { // Drop the final CRLF or LF, if any var length = foundCRLF switch { true => builder.Length - 2, false when foundLF => builder.Length - 1, false => builder.Length, }; return(Encoding.UTF8.GetString(builder.ToArray(), 0, (int)length)); }
private bool IsMatch(int aunt, string key, int value, bool ranges) { if (!_aunts[aunt].ContainsKey(key)) { return(false); } return(key switch { "cats" or "trees" when ranges => _aunts[aunt][key] > value, "pomeranians" or "goldfish" when ranges => _aunts[aunt][key] < value, _ => _aunts[aunt][key] == value });
public override void AppendTo(ref SpanWriter writer, OrderedHashSet <string> strings, ref int entries, ref int switches) { var hasHue = Hue != 0; var hasClass = !string.IsNullOrEmpty(Class); writer.WriteAscii( hasHue switch { true when hasClass => $"{{ gumppic {X} {Y} {GumpID} hue={Hue} class={Class} }}", true => $"{{ gumppic {X} {Y} {GumpID} hue={Hue} }}", false when hasClass => $"{{ gumppic {X} {Y} {GumpID} class={Class} }}", false => $"{{ gumppic {X} {Y} {GumpID} }}", }
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic) { if (familyName.Equals("OpenSans", StringComparison.CurrentCultureIgnoreCase)) { return(isBold switch { true when isItalic => new FontResolverInfo(Path.Combine(MFiles.PublicPath, "fonts", "OpenSans-BoldItalic.ttf")), true => new FontResolverInfo(Path.Combine(MFiles.PublicPath, "fonts", "OpenSans-Bold.ttf")), _ => isItalic ? new FontResolverInfo(Path.Combine(MFiles.PublicPath, "fonts", "OpenSans-Italic.ttf")) : new FontResolverInfo(Path.Combine(MFiles.PublicPath, "fonts", "OpenSans-Regular.ttf")) });
public void CalculateChessStatus(PieceColor color) { Boolean isCheck = IsCheck(color); Boolean hasMoves = HasMoves(color); ChessStatus = isCheck switch { true when hasMoves => ChessStatus.Check, true => ChessStatus.Mate, false when hasMoves => ChessStatus.Ok, false => ChessStatus.Stalemate }; }
/// <summary>Try get number of DataSource itmes.</summary> /// <param name="allowSlow">When "allowSlow" is false, method will not use Linq.Count() method and will return 0 or 1 instead.</param> /// <param name="getAny">If "getAny" is true, method can use Linq.Any() method to speedup.</param> /// <param name="count">number of DataSource itmes.</param> /// <returns>true if able to retrieve number of DataSource itmes; otherwise, false.</returns> internal bool TryGetCount(bool allowSlow, bool getAny, out int count) { bool result; (result, count) = DataSource switch { ICollection collection => (true, collection.Count), DataGridCollectionView cv => (true, cv.Count), IEnumerable enumerable when allowSlow&& !getAny => (true, enumerable.Cast <object>().Count()), IEnumerable enumerable when getAny => (true, enumerable.Cast <object>().Any() ? 1 : 0), _ => (false, 0) }; return(result); }
public static (Coordinate cell, bool cellState) Get(TGrid grid, KeyValuePair <Coordinate, bool> kvp) { var(cell, alive) = kvp; var neighbors = Grid.NeighborCount(cell, grid); var cellState = neighbors switch { 2 when alive => true, 3 => true, _ => false }; return(cell, cellState); } }
public static long Part2(string input) { foreach (var n in floor.Keys.SelectMany(c => c.Neighbors).ToList()) { if (!floor.ContainsKey(n)) { floor[n] = false; } } for (var i = 0; i < 100; ++i) { var next = new Dictionary <Hex, bool>(); foreach (var(tile, wasSet) in floor) { var countBlack = 0; foreach (var neigh in tile.Neighbors) { if (floor.TryGetValue(neigh, out var blackNeighbor)) { if (blackNeighbor) { countBlack++; } } else { next[neigh] = false; } } next[tile] = countBlack switch { 0 or > 2 when wasSet => false, 2 when !wasSet => true, _ => wasSet }; } floor = next; } return(floor.Values.Count(c => c)); }
public CellOffset GetForRotation(int currentRotation, bool clockWise) { return(currentRotation switch { 0 when clockWise => Rotation0R, 0 => Rotation0L, 1 when clockWise => RotationR2, 1 => RotationR0, 2 when clockWise => Rotation2R, 2 => Rotation2L, 3 when clockWise => RotationL0, 3 => RotationL2, _ => throw new System.Exception($"Unexpected rotation {currentRotation}"), });
/// <summary> /// Write the PNG file bytes to the provided stream. /// </summary> public void Save(Stream outputStream) { outputStream.Write(HeaderValidationResult.ExpectedHeader, 0, HeaderValidationResult.ExpectedHeader.Length); var stream = new PngStreamWriteHelper(outputStream); stream.WriteChunkLength(13); stream.WriteChunkHeader(ImageHeader.HeaderBytes); StreamHelper.WriteBigEndianInt32(stream, width); StreamHelper.WriteBigEndianInt32(stream, height); stream.WriteByte(8); var colorType = ColorType.ColorUsed; if (hasAlphaChannel) { colorType |= ColorType.AlphaChannelUsed; } stream.WriteByte((byte)colorType); stream.WriteByte((byte)CompressionMethod.DeflateWithSlidingWindow); stream.WriteByte((byte)FilterMethod.AdaptiveFiltering); stream.WriteByte((byte)InterlaceMethod.None); stream.WriteCrc(); byte[] imageData = bytesPerPixel switch { 4 when flipRb => CompressFlipRb4(rawData, height, width * 4), 4 => Compress(rawData, height, width * 4), 3 when flipRb => CompressFlipRb3(rawData, height, width * 3), 3 => Compress(rawData, height, width * 3), _ => throw new ArgumentOutOfRangeException() }; stream.WriteChunkLength(imageData.Length); stream.WriteChunkHeader(Encoding.ASCII.GetBytes("IDAT")); stream.Write(imageData, 0, imageData.Length); stream.WriteCrc(); stream.WriteChunkLength(0); stream.WriteChunkHeader(Encoding.ASCII.GetBytes("IEND")); stream.WriteCrc(); }
public void AddWhen(string text, when method) { Whens.Add(method, text); }
Yotei _GetSchedule( DateTime date, when when ) { foreach( var item in when.Items ) { if( item is EventDateTimeType ) { var eventDateTimeType = (EventDateTimeType)item; // 開始日時 DateTime? startDateTime = null; { var startDateTimeLocal = eventDateTimeType.start.ToLocalTime(); if( date < startDateTimeLocal.Date ) { continue; } startDateTime = startDateTimeLocal; } // 終了日時 DateTime? endDateTime = null; if( eventDateTimeType.endSpecified ) { var endDateTimeLocal = eventDateTimeType.end.ToLocalTime(); if( date > endDateTimeLocal.Date ) { continue; } endDateTime = endDateTimeLocal; } return new Yotei( startDateTime, endDateTime ); } } return null; }