-
Notifications
You must be signed in to change notification settings - Fork 305
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Муканов Арман #223
Open
MNYOU
wants to merge
18
commits into
kontur-courses:master
Choose a base branch
from
MNYOU:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Муканов Арман #223
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
dd3f0ba
Добавил проект TagsCLoud
MNYOU b933e54
Добавил тесты
MNYOU 7fbbb0b
Добавил CircularCloudLayouter
MNYOU 5535aae
Добавил LayouterVisualizer
MNYOU aab9b6b
Добавил пример визуализации
MNYOU a5affb6
Добавил README.md
MNYOU 16c72d0
Поправил тест
MNYOU 5608235
Merge branch 'master' of https://github.com/MNYOU/tdd
MNYOU 346e6e4
Удалил сторонний файл
MNYOU fd377f6
Рефакторинг
MNYOU b71f99d
Изменил README.md
MNYOU 1799420
Реализовал Dispose pattern
MNYOU 14c3e2d
Добавил обработку ошибок
MNYOU 4a6a969
style: перенес в assets
MNYOU 66a1e2b
style: перенес тесты в файл
MNYOU dd6f760
refactor: Переписал с использованием констант
MNYOU d4c7f5a
style: переименовал изображения
MNYOU ceebdaf
fix: исправил пути картинок
MNYOU File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
using System; | ||
using System.Drawing; | ||
|
||
namespace TagsCloudVisualization; | ||
|
||
public class CircularCloudLayouter : ILayouter | ||
{ | ||
private readonly List<Rectangle> rectangles; | ||
private Point center; | ||
private double spiralStep; | ||
private double angle; | ||
private const double DefaultAngleStep = Math.PI / 10; | ||
private const double DefaultSpiralStep = 1; | ||
private const double FullCircle = Math.PI * 2; | ||
private const int SpiralStepThreshold = 10; | ||
|
||
public CircularCloudLayouter(Point center) | ||
{ | ||
this.center = center; | ||
rectangles = new List<Rectangle>(); | ||
spiralStep = 1; | ||
} | ||
|
||
public IReadOnlyList<Rectangle> AddedRectangles => rectangles; | ||
|
||
public Rectangle PutNextRectangle(Size rectangleSize) | ||
{ | ||
if (rectangleSize.Width == 0 || rectangleSize.Height == 0) | ||
throw new ArgumentException($"{nameof(rectangleSize)} should be with positive width and height"); | ||
var location = GetPosition(rectangleSize); | ||
var rectangle = new Rectangle(location, rectangleSize); | ||
rectangles.Add(rectangle); | ||
return rectangle; | ||
} | ||
|
||
private Point GetPosition(Size rectangleSize) | ||
{ | ||
if (rectangles.Count == 0) | ||
{ | ||
center.Offset(new Point(rectangleSize / -2)); | ||
return center; | ||
} | ||
|
||
return FindApproximatePosition(rectangleSize); | ||
} | ||
|
||
private Point FindApproximatePosition(Size rectangleSize) | ||
{ | ||
var currentAngle = angle; | ||
while (true) | ||
{ | ||
var candidateLocation = new Point(center.X + (int)(spiralStep * Math.Cos(currentAngle)), | ||
center.Y + (int)(spiralStep * Math.Sin(currentAngle))); | ||
var candidateRectangle = new Rectangle(candidateLocation, rectangleSize); | ||
|
||
if (!IntersectsWithAny(candidateRectangle)) | ||
{ | ||
rectangles.Add(candidateRectangle); | ||
angle = currentAngle; | ||
return candidateRectangle.Location; | ||
} | ||
|
||
currentAngle = CalculateAngle(currentAngle); | ||
} | ||
} | ||
|
||
private bool IntersectsWithAny(Rectangle candidateRectangle) | ||
{ | ||
return rectangles | ||
.Any(candidateRectangle.IntersectsWith); | ||
} | ||
|
||
private double CalculateAngle(double currentAngle) | ||
{ | ||
currentAngle += GetAngleStep(); | ||
if (currentAngle > FullCircle) | ||
{ | ||
currentAngle %= FullCircle; | ||
UpdateSpiral(); | ||
} | ||
|
||
return currentAngle; | ||
} | ||
|
||
private void UpdateSpiral() | ||
{ | ||
spiralStep += DefaultSpiralStep; | ||
} | ||
|
||
private double GetAngleStep() | ||
{ | ||
var angleStep = DefaultAngleStep; | ||
var stepCount = (int)spiralStep / SpiralStepThreshold; | ||
if (stepCount > 0) | ||
angleStep /= stepCount; | ||
|
||
return angleStep; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Drawing; | ||
using System.Linq; | ||
using System.Text; | ||
using System.Threading.Tasks; | ||
|
||
namespace TagsCloudVisualization | ||
{ | ||
public interface ILayouter | ||
{ | ||
public Rectangle PutNextRectangle(Size rectangleSize); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
using Microsoft.VisualBasic; | ||
using NUnit.Framework; | ||
using System.Drawing; | ||
using System.Drawing.Imaging; | ||
|
||
namespace TagsCloudVisualization; | ||
|
||
public class LayouterVisualizer: IDisposable | ||
{ | ||
private bool isDisposed; | ||
|
||
public LayouterVisualizer(Size imageSize) | ||
{ | ||
Bitmap = new Bitmap(imageSize.Width, imageSize.Height); | ||
Pen = new Pen(Color.White, 3); | ||
} | ||
|
||
public Bitmap Bitmap { get; } | ||
|
||
public Pen Pen { get; set; } | ||
|
||
public void VisualizeRectangle(Rectangle rectangle) | ||
{ | ||
using var g = Graphics.FromImage(Bitmap); | ||
g.DrawRectangle(Pen, rectangle); | ||
} | ||
|
||
public void VisualizeRectangles(IEnumerable<Rectangle> rectangles) | ||
{ | ||
foreach (var rect in rectangles) | ||
{ | ||
VisualizeRectangle(rect); | ||
} | ||
} | ||
|
||
public void SaveImage(string file, ImageFormat format) | ||
{ | ||
if (TrySaveImage(file, format)) | ||
{ | ||
Console.WriteLine($"Tag cloud visualization saved to {file}"); | ||
} | ||
} | ||
|
||
private bool TrySaveImage(string file, ImageFormat format) | ||
{ | ||
try | ||
{ | ||
Bitmap.Save(file, format); | ||
return true; | ||
} | ||
catch (Exception ex) | ||
{ | ||
Console.WriteLine("An error occurred while saving the image: " + ex.Message); | ||
return false; | ||
} | ||
} | ||
|
||
~LayouterVisualizer() | ||
{ | ||
Dispose(false); | ||
} | ||
|
||
public void Dispose() | ||
{ | ||
Dispose(true); | ||
GC.SuppressFinalize(this); | ||
} | ||
|
||
private void Dispose(bool fromDisposeMethod) | ||
{ | ||
if (isDisposed) return; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Как считаешь что лучше? if (isDisposed)
{
return;
} или if (isDisposed) return; или if (!isDisposed)
{
...
} There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 2 вариант, на мой взгляд лучше. Более читаемый, отсутствует вложенность. |
||
if (fromDisposeMethod) | ||
{ | ||
Bitmap.Dispose(); | ||
Pen.Dispose(); | ||
} | ||
|
||
isDisposed = true; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
# Примеры визуализации облака тегов | ||
|
||
| ![Облако с квадратными тегами](./Assets/Images resources/25_rect.jpeg) | | ||
|:----------------------------------------------------------------------:| | ||
| *Визуализация облака с квадратными тегами* | | ||
|
||
| ![Облако с прямоугольными тегами](./Assets/Images resources/70_squares.jpeg) | | ||
|:----------------------------------------------------------------------------:| | ||
| *Визуализация облака с прямоугольными тегами* | | ||
|
||
| ![Облако с различными тегам](./Assets/Images resources/75_rect.jpeg) | | ||
|:--------------------------------------------------------------------:| | ||
| *Визуализация облака с различными тегами* | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>net7.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.3" /> | ||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0-preview-23531-01" /> | ||
<PackageReference Include="NUnit" Version="4.0.1" /> | ||
<PackageReference Include="NUnit.Console" Version="3.16.3" /> | ||
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" /> | ||
<PackageReference Include="System.Drawing.Common" Version="7.0.0" /> | ||
</ItemGroup> | ||
|
||
</Project> |
152 changes: 152 additions & 0 deletions
152
cs/TagsCloudVisualization/Tests/CircularCloudLayouter_Should.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
using System.Drawing; | ||
using System.Drawing.Imaging; | ||
using FluentAssertions; | ||
using NUnit.Framework; | ||
using NUnit.Framework.Interfaces; | ||
using NUnit.Framework.Internal; | ||
|
||
namespace TagsCloudVisualization.Tests; | ||
|
||
[TestFixture] | ||
public class CircularCloudLayouter_Should | ||
{ | ||
private readonly string path = Path.Combine(TestContext.CurrentContext.TestDirectory, "TestsResults"); | ||
private CircularCloudLayouter cloudLayouter; | ||
private Point center; | ||
private Size canvasSize; | ||
|
||
private Randomizer Random => TestContext.CurrentContext.Random; | ||
|
||
[OneTimeSetUp] | ||
public void OneTimeSetUp() | ||
{ | ||
canvasSize = new Size(900, 900); | ||
center = new Point(450, 450); | ||
|
||
DeleteTestResults(); | ||
} | ||
|
||
[SetUp] | ||
public void SetUp() | ||
{ | ||
cloudLayouter = new CircularCloudLayouter(center); | ||
} | ||
|
||
[TearDown] | ||
public void TearDown() | ||
{ | ||
var status = TestContext.CurrentContext.Result.Outcome.Status; | ||
var test = TestContext.CurrentContext.Test; | ||
if (status != TestStatus.Failed) return; | ||
SaveFailedTestResult(test); | ||
} | ||
|
||
[Test] | ||
public void PutNextRectangle_ShouldThrow_WhenSizeNotPositive() | ||
{ | ||
var action = () => cloudLayouter.PutNextRectangle(new Size(0, 0)); | ||
|
||
action.Should().Throw<ArgumentException>(); | ||
} | ||
|
||
[Test] | ||
public void PutNextRectangle_ShouldReturnRectangleWithGivenSize() | ||
{ | ||
var size = new Size(10, 10); | ||
|
||
var rectangle = cloudLayouter.PutNextRectangle(size); | ||
|
||
rectangle.Size.Should().Be(size); | ||
} | ||
|
||
[Test] | ||
public void PutNextRectangle_ShouldPlaceFirstRectangleInCenter() | ||
{ | ||
var size = new Size(50, 50); | ||
var offsettedCenter = center - size / 2; | ||
|
||
var rectangle = cloudLayouter.PutNextRectangle(size); | ||
|
||
rectangle.Location.Should().Be(offsettedCenter); | ||
} | ||
|
||
[Test] | ||
public void PutNextRectangle_ShouldReturnNotIntersectingRectangles() | ||
{ | ||
var sizes = GetRandomSizes(70); | ||
|
||
var actualRectangles = sizes.Select(x => cloudLayouter.PutNextRectangle(x)).ToList(); | ||
|
||
for (var i = 0; i < actualRectangles.Count - 1; i++) | ||
{ | ||
for (var j = i + 1; j < actualRectangles.Count; j++) | ||
{ | ||
actualRectangles[i].IntersectsWith(actualRectangles[j]).Should().BeFalse(); | ||
} | ||
} | ||
} | ||
|
||
[Test] | ||
public void PutNextRectangle_ShouldCreateLayoutCloseToCircle() | ||
{ | ||
var sizes = GetRandomSizes(50); | ||
|
||
var rectangles = sizes.Select(size => cloudLayouter.PutNextRectangle(size)).ToList(); | ||
var rectanglesSquare = rectangles | ||
.Select(x => x.Width * x.Height) | ||
.Sum(); | ||
var circleSquare = CalculateBoundingCircleSquare(rectangles); | ||
|
||
rectanglesSquare.Should().BeInRange((int)(circleSquare * 0.8), (int)(circleSquare * 1.2)); | ||
} | ||
|
||
private void DeleteTestResults() | ||
{ | ||
var di = new DirectoryInfo(path); | ||
foreach (var file in di.GetFiles()) | ||
{ | ||
file.Delete(); | ||
} | ||
} | ||
|
||
private void SaveFailedTestResult(TestContext.TestAdapter test) | ||
{ | ||
Directory.CreateDirectory(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestsResults")); | ||
var pathToImage = Path.Combine(path, test.Name + ".jpeg"); | ||
|
||
var visualizer = new LayouterVisualizer(canvasSize); | ||
visualizer.VisualizeRectangles(cloudLayouter.AddedRectangles); | ||
|
||
visualizer.SaveImage(pathToImage, ImageFormat.Jpeg); | ||
visualizer.Dispose(); | ||
} | ||
|
||
private Size GetRandomSize() | ||
{ | ||
//return new Size(Random.Next(30, 40), Random.Next(30, 40)); | ||
return new Size(Random.Next(100, 120), Random.Next(30, 90)); | ||
} | ||
|
||
private List<Size> GetRandomSizes(int count) | ||
{ | ||
var sizes = new List<Size>(count); | ||
for (var i = 0; i < count; i++) | ||
sizes.Add(GetRandomSize()); | ||
return sizes; | ||
} | ||
|
||
private double CalculateBoundingCircleSquare(List<Rectangle> rectangles) | ||
{ | ||
var rect = rectangles | ||
.Where(x => x.Contains(x.X, center.Y)) | ||
.MaxBy(x => Math.Abs(x.X - center.X)); | ||
var width = Math.Abs(rect.X - center.X); | ||
|
||
rect = rectangles | ||
.Where(x => x.Contains(center.X, x.Y)) | ||
.MaxBy(x => Math.Abs(x.Y - center.Y)); | ||
var height = Math.Abs(rect.Y - center.Y); | ||
|
||
return Math.Max(width, height) * Math.Max(width, height) * Math.PI; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Как считаешь нужен ли тут
String
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Думаю, что нужен, потому что будет неочевидно, куда сохраняется изображение
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Речь про
string
vsString
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
string
- это же просто alias дляString
. Поэтому я не вижу преимуществ в использованииString