public TableStorageScaleMetricsRepository(IConfiguration configuration, IHostIdProvider hostIdProvider, IOptions <ScaleOptions> scaleOptions, ILoggerFactory loggerFactory) { _configuration = configuration; _hostIdProvider = hostIdProvider; _scaleOptions = scaleOptions.Value; _logger = loggerFactory.CreateLogger <TableStorageScaleMetricsRepository>(); }
public static void Scale(Rectangle boundsBeforeResize, Positions gripperPosition, int cursorX, int cursorY, ref RectangleF boundsAfterResize, IDoubleProcessor angleRoundBehavior) { ScaleOptions opts = GetScaleOptions(); bool rationalScale = (opts & ScaleOptions.Rational) == ScaleOptions.Rational; bool centeredScale = (opts & ScaleOptions.Centered) == ScaleOptions.Centered; if (rationalScale) { double angle = GeometryHelper.Angle2D(boundsBeforeResize.X, boundsBeforeResize.Y, cursorX, cursorY); if (angleRoundBehavior != null) { angle = angleRoundBehavior.Process(angle); } int dist = GeometryHelper.Distance2D(boundsBeforeResize.X, boundsBeforeResize.Y, cursorX, cursorY); boundsAfterResize.Width = (int)Math.Round(dist * Math.Cos(angle / 180 * Math.PI)); boundsAfterResize.Height = (int)Math.Round(dist * Math.Sin(angle / 180 * Math.PI)); } if (centeredScale) { float wdiff = boundsAfterResize.Width - boundsBeforeResize.Width; float hdiff = boundsAfterResize.Height - boundsBeforeResize.Height; boundsAfterResize.Width += wdiff; boundsAfterResize.Height += hdiff; boundsAfterResize.X -= wdiff; boundsAfterResize.Y -= hdiff; } }
internal TableStorageScaleMetricsRepository(IConfiguration configuration, IHostIdProvider hostIdProvider, IOptions <ScaleOptions> scaleOptions, ILoggerFactory loggerFactory, int tableCreationRetries) { _configuration = configuration; _hostIdProvider = hostIdProvider; _scaleOptions = scaleOptions.Value; _logger = loggerFactory.CreateLogger <TableStorageScaleMetricsRepository>(); _tableCreationRetries = tableCreationRetries; }
internal TableStorageScaleMetricsRepository(IConfiguration configuration, IHostIdProvider hostIdProvider, IOptions <ScaleOptions> scaleOptions, ILoggerFactory loggerFactory, int tableCreationRetries, IDelegatingHandlerProvider delegatingHandlerProvider) { _configuration = configuration; _hostIdProvider = hostIdProvider; _scaleOptions = scaleOptions.Value; _logger = loggerFactory.CreateLogger <TableStorageScaleMetricsRepository>(); _tableCreationRetries = tableCreationRetries; _delegatingHandlerProvider = delegatingHandlerProvider ?? throw new ArgumentNullException(nameof(delegatingHandlerProvider)); }
public FunctionsScaleMonitorService(IScaleMonitorManager monitorManager, IScaleMetricsRepository metricsRepository, IPrimaryHostStateProvider primaryHostStateProvider, IEnvironment environment, ILoggerFactory loggerFactory, IOptions <ScaleOptions> scaleOptions) { _monitorManager = monitorManager; _metricsRepository = metricsRepository; _primaryHostStateProvider = primaryHostStateProvider; _environment = environment; _logger = loggerFactory.CreateLogger <FunctionsScaleMonitorService>(); _scaleOptions = scaleOptions.Value; _interval = _scaleOptions.ScaleMetricsSampleInterval; _timer = new Timer(OnTimer, null, Timeout.Infinite, Timeout.Infinite); }
public override void Reset() { base.Reset(); fromOptions = ScaleOptions.CurrentScale; fromTarget = null; fromScale = new FsmVector3 { Value = Vector3.one }; toOptions = ScaleOptions.LocalScale; toTarget = null; toScale = new FsmVector3 { Value = Vector3.one }; }
/// <returns>the current ScaleOptions depending on modifier keys held down</returns> public static ScaleOptions GetScaleOptions() { bool anchorAtCenter = (Control.ModifierKeys & Keys.Control) != 0; bool maintainAspectRatio = (Control.ModifierKeys & Keys.Shift) != 0; ScaleOptions opts = ScaleOptions.Default; if (anchorAtCenter) { opts |= ScaleOptions.Centered; } if (maintainAspectRatio) { opts |= ScaleOptions.Rational; } return(opts); }
void DoSubdiviosion(ScaleOptions scaleOptions) { int w = 0; int h = 0; try { w = Convert.ToInt32(SubdivisionWidthTextBox.Text); h = Convert.ToInt32(SubdivisionHeightTextBox.Text); } catch { MessageBox.Show("Помилка з конвертуванням параметрів для процедури Subdivision"); return; } m_workImage = ImageScaleChanger.SubdivisionImageResize(m_workImage, w, h, scaleOptions); RefreshWorkImage(); }
public TableStorageScaleMetricsRepositoryTests() { var configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build(); _hostIdProviderMock = new Mock <IHostIdProvider>(MockBehavior.Strict); _hostIdProviderMock.Setup(p => p.GetHostIdAsync(It.IsAny <CancellationToken>())).ReturnsAsync(TestHostId); _scaleOptions = new ScaleOptions { MetricsPurgeEnabled = false }; _loggerProvider = new TestLoggerProvider(); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); _repository = new TableStorageScaleMetricsRepository(configuration, _hostIdProviderMock.Object, new OptionsWrapper <ScaleOptions>(_scaleOptions), loggerFactory); EmptyMetricsTableAsync().GetAwaiter().GetResult(); }
private void UpdateScale(bool a, ScaleOptions o) { if (a) { if (!o.m_active) { m_targetScale += o.m_scaleOffset; } o.m_active = true; } else { if (o.m_active) { m_targetScale -= o.m_scaleOffset; } o.m_active = false; } }
public static double[,,] ResizeImage(double[,,] image, double k, ScaleOptions scaleOptions) { int N = (int)(image.GetLength(1) * k); int M = (int)(image.GetLength(2) * k); double[,,] scaledImage = new double[3, N, M]; for (int i_new = 0; i_new < N; i_new++) { for (int j_new = 0; j_new < M; j_new++) { double yy = i_new / k; double xx = j_new / k; int i = (int)xx; int j = (int)yy; double x = 2 * (xx - i); double y = 2 * (yy - j); //chosing gama double[][] gama = null; if (scaleOptions == ScaleOptions.S20) { gama = getGama20(x, y); } else if (scaleOptions == ScaleOptions.S21) { gama = getGama21(x, y); } double[] resultRGB = ApplyConvolutionFilterByCoords(image, i, j, gama); scaledImage[0, i_new, j_new] = resultRGB[0]; scaledImage[1, i_new, j_new] = resultRGB[1]; scaledImage[2, i_new, j_new] = resultRGB[2]; } } return(scaledImage); }
public TableStorageScaleMetricsRepositoryTests() { var configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build(); _hostIdProviderMock = new Mock <IHostIdProvider>(MockBehavior.Strict); _hostIdProviderMock.Setup(p => p.GetHostIdAsync(It.IsAny <CancellationToken>())).ReturnsAsync(TestHostId); _scaleOptions = new ScaleOptions { MetricsPurgeEnabled = false }; _loggerProvider = new TestLoggerProvider(); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); // Allow for up to 30 seconds of creation retries for tests due to slow table deletes _repository = new TableStorageScaleMetricsRepository(configuration, _hostIdProviderMock.Object, new OptionsWrapper <ScaleOptions>(_scaleOptions), loggerFactory, 60, new DefaultDelegatingHandlerProvider(new TestEnvironment())); EmptyMetricsTableAsync().GetAwaiter().GetResult(); }
public static Vector3 GetTargetScale(ScaleOptions option, Transform owner, Transform target, Vector3 scale) { if (owner == null) { return(Vector3.one); } switch (option) { case ScaleOptions.CurrentScale: return(owner.localScale); case ScaleOptions.LocalScale: return(scale); case ScaleOptions.MultiplyScale: var localScale = owner.localScale; return(new Vector3(localScale.x * scale.x, localScale.y * scale.y, localScale.z * scale.z)); case ScaleOptions.AddToScale: var localScale1 = owner.localScale; return(new Vector3(localScale1.x + scale.x, localScale1.y + scale.y, localScale1.z + scale.z)); case ScaleOptions.MatchGameObject: if (target == null) { return(owner.localScale); } return(target.localScale); /* Useful...? * case ScaleOptions.MatchGameObjectMultiply: * if (target == null) return owner.localScale; * if (scale == Vector3.one) return target.localScale; * return new Vector3(target.localScale.x * scale.x, target.localScale.y * scale.y, target.localScale.z * scale.z); */ } return(owner.localScale); // leave as is }
public static ProcessResult <Clip[]> Apply(ScaleOptions options, params Clip[] clips) { if (options.By != null) { clips = clips.Prepend(options.By).ToArray(); } ClipUtilities.NormalizeClipLengths(clips); if (clips.Length < 2) { return(new ProcessResult <Clip[]>(clips)); } var masterClip = clips[0]; var slaveClips = clips.Skip(1).ToArray(); var processedClips = slaveClips.Select(c => new Clip(c.Length, c.IsLooping)).ToArray(); for (var i = 0; i < slaveClips.Length; i++) { var slaveClip = slaveClips[i]; foreach (var note in slaveClip.Notes) { var masterNotes = SortedList <NoteEvent> .Empty; if (options.PositionAware) { masterNotes = masterClip.Notes.Where(x => x.StartsInsideIntervalInclusive(note.Start, note.End) || x.CoversInterval(note.Start, note.End)).ToSortedList(); } if (masterNotes.Count == 0) { masterNotes = masterClip.Notes; } var constrainedNote = note with { }; constrainedNote.Pitch = options.Strict ? ClipUtilities.FindNearestNotePitchInSet(note, masterNotes) : ClipUtilities.FindNearestNotePitchInSetMusical(note, masterNotes); processedClips[i].Notes.Add(constrainedNote); } } return(new ProcessResult <Clip[]>(processedClips)); }
public FunctionsScaleMonitorServiceTests() { _isPrimaryHost = true; _monitors = new List <IScaleMonitor>(); _monitorManagerMock = new Mock <IScaleMonitorManager>(MockBehavior.Strict); _monitorManagerMock.Setup(p => p.GetMonitors()).Returns(() => _monitors); _metricsRepository = new TestMetricsRepository(); _primaryHostStateProviderMock = new Mock <IPrimaryHostStateProvider>(MockBehavior.Strict); _primaryHostStateProviderMock.SetupGet(p => p.IsPrimary).Returns(() => _isPrimaryHost); _environment = new TestEnvironment(); _loggerProvider = new TestLoggerProvider(); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); var scaleOptions = new ScaleOptions(TimeSpan.FromMilliseconds(50)); var options = new OptionsWrapper <ScaleOptions>(scaleOptions); _environment.SetEnvironmentVariable(EnvironmentSettingNames.FunctionsRuntimeScaleMonitoringEnabled, "1"); _monitor = new FunctionsScaleMonitorService(_monitorManagerMock.Object, _metricsRepository, _primaryHostStateProviderMock.Object, _environment, loggerFactory, options); }
public async Task InvalidStorageConnection_Handled() { var configuration = new ConfigurationBuilder().Build(); Assert.Null(configuration.GetWebJobsConnectionString(ConnectionStringNames.Storage)); var options = new ScaleOptions(); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); var localRepository = new TableStorageScaleMetricsRepository(configuration, _hostIdProviderMock.Object, new OptionsWrapper <ScaleOptions>(options), loggerFactory, new TestEnvironment()); var monitor1 = new TestScaleMonitor1(); var monitor2 = new TestScaleMonitor2(); var monitor3 = new TestScaleMonitor3(); var monitors = new IScaleMonitor[] { monitor1, monitor2, monitor3 }; var result = await localRepository.ReadMetricsAsync(monitors); Assert.Empty(result); var logs = _loggerProvider.GetAllLogMessages(); Assert.Single(logs); Assert.Equal("Azure Storage connection string is empty or invalid. Unable to read/write scale metrics.", logs[0].FormattedMessage); _loggerProvider.ClearAllLogMessages(); Dictionary <IScaleMonitor, ScaleMetrics> metricsMap = new Dictionary <IScaleMonitor, ScaleMetrics>(); metricsMap.Add(monitor1, new TestScaleMetrics1 { Count = 10 }); metricsMap.Add(monitor2, new TestScaleMetrics2 { Num = 50 }); metricsMap.Add(monitor3, new TestScaleMetrics3 { Length = 100 }); await localRepository.WriteMetricsAsync(metricsMap); }
private static byte[] DownScaleImage(byte[] data, ScaleOptions options) { try { using var memoryStream = new MemoryStream(data); var originalImage = System.Drawing.Image.FromStream(memoryStream); if (originalImage.Width + originalImage.Height <= options.Width + options.Height) { return(data); } Bitmap resizedImage; if (options.MaintainRatio) { var ratio = (double)originalImage.Width / originalImage.Height; var scale = options.Width > options.Height ? options.Width : options.Height; resizedImage = scale * ratio <= originalImage.Width ? new Bitmap(originalImage, (int)(scale * ratio), scale) : new Bitmap(originalImage, scale, (int)(scale / ratio)); } else { resizedImage = new Bitmap(originalImage, options.Width, options.Height); } using var anotherMemoryStreamYippee = new MemoryStream(); resizedImage.Save(anotherMemoryStreamYippee, originalImage.RawFormat); return(anotherMemoryStreamYippee.ToArray()); } catch (Exception) { return(data); } }
/// <summary> /// Sets an image or gif/apng from a resource path /// </summary> /// <param name="image">Image component to set the image to</param> /// <param name="location">Resource path, file path, or url of image. Can prefix with # to find and use a base game sprite. May need to prefix resource paths with 'AssemblyName:'</param> /// <param name="loadingAnimation">Whether a loading animation is shown as a placeholder until the image is loaded</param> /// <param name="scaleOptions">If the image should be downscaled and what it should be downscaled to</param> /// <param name="callback">Method to call once SetImage has finished</param> public static void SetImage(this Image image, string location, bool loadingAnimation, ScaleOptions scaleOptions, Action callback) { AnimationStateUpdater oldStateUpdater = image.GetComponent <AnimationStateUpdater>(); if (oldStateUpdater != null) { MonoBehaviour.DestroyImmediate(oldStateUpdater); } if (location.Length > 1 && location[0] == '#') { string imgName = location.Substring(1); image.sprite = Utilities.FindSpriteCached(imgName); if (image.sprite == null) { Logger.log.Error($"Could not find Sprite with image name {imgName}"); } return; } bool isURL = Uri.TryCreate(location, UriKind.Absolute, out Uri uri); if (IsAnimated(location) || isURL && IsAnimated(uri.LocalPath)) { AnimationStateUpdater stateUpdater = image.gameObject.AddComponent <AnimationStateUpdater>(); stateUpdater.image = image; if (loadingAnimation) { stateUpdater.controllerData = AnimationController.instance.loadingAnimation; } if (AnimationController.instance.RegisteredAnimations.TryGetValue(location, out AnimationControllerData animControllerData)) { stateUpdater.controllerData = animControllerData; } else { Utilities.GetData(location, (byte[] data) => { AnimationLoader.Process( (location.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) || (isURL && uri.LocalPath.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))) ? AnimationType.GIF : AnimationType.APNG, data, (Texture2D tex, Rect[] uvs, float[] delays, int width, int height) => { AnimationControllerData controllerData = AnimationController.instance.Register(location, tex, uvs, delays); stateUpdater.controllerData = controllerData; callback?.Invoke(); }); }); return; } } else { AnimationStateUpdater stateUpdater = image.gameObject.AddComponent <AnimationStateUpdater>(); stateUpdater.image = image; if (loadingAnimation) { stateUpdater.controllerData = AnimationController.instance.loadingAnimation; } Utilities.GetData(location, async(byte[] data) => { if (stateUpdater != null) { GameObject.DestroyImmediate(stateUpdater); } if (scaleOptions.ShouldScale) { var imageBytes = await Task.Run(() => DownScaleImage(data, scaleOptions)).ConfigureAwait(false); _ = UnityMainThreadTaskScheduler.Factory.StartNew(() => { image.sprite = Utilities.LoadSpriteRaw(imageBytes); image.sprite.texture.wrapMode = TextureWrapMode.Clamp; }); } else { image.sprite = Utilities.LoadSpriteRaw(data); image.sprite.texture.wrapMode = TextureWrapMode.Clamp; } callback?.Invoke(); }); return; } callback?.Invoke(); }
/// <summary> /// Calculates target size of a given rectangle scaled by dragging one of its handles (corners) /// </summary> /// <param name="originalRectangle">bounds of the current rectangle, scaled values will be written to this reference</param> /// <param name="resizeHandlePosition">position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT</param> /// <param name="resizeHandleCoords">coordinates of the used handle/gripper</param> /// <param name="options">ScaleOptions to use when scaling</param> public static void Scale(ref RectangleF originalRectangle, int resizeHandlePosition, PointF resizeHandleCoords, ScaleOptions? options) { if(options == null) { options = GetScaleOptions(); } if((options & ScaleOptions.Rational) == ScaleOptions.Rational) { adjustCoordsForRationalScale(originalRectangle, resizeHandlePosition, ref resizeHandleCoords); } if((options & ScaleOptions.Centered) == ScaleOptions.Centered) { // store center coordinates of rectangle float rectCenterX = originalRectangle.Left + originalRectangle.Width / 2; float rectCenterY = originalRectangle.Top + originalRectangle.Height / 2; // scale rectangle using handle coordinates scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords); // mirror handle coordinates via rectangle center coordinates resizeHandleCoords.X -= 2 * (resizeHandleCoords.X - rectCenterX); resizeHandleCoords.Y -= 2 * (resizeHandleCoords.Y - rectCenterY); // scale again with opposing handle and mirrored coordinates resizeHandlePosition = (resizeHandlePosition + 4) % 8; scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords); } else { scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords); } }
public FixedDocument ViewsToDocument <TView>(IEnumerable <ViewRequest> viewRequests, Size pageSize, ScaleOptions scaleOptions = null) where TView : FrameworkElement, IView { scaleOptions = scaleOptions ?? new ScaleOptions { Padding = new Thickness(), ScaleToFit = true, ScaleFitting = ScaleFitting.BothDirections, MaxScale = 1.0, MinScale = 0.0 }; var viewSize = new Size( pageSize.Width - (scaleOptions.Padding.Left + scaleOptions.Padding.Right), pageSize.Height - (scaleOptions.Padding.Top + scaleOptions.Padding.Bottom) ); var document = new FixedDocument(); foreach (var viewRequest in viewRequests) { var view = Container.Resolve <TView>(); if (view.ViewModel is IInitializableViewModel initializibleViewModel) { initializibleViewModel.Initialize(viewRequest); } if (view.ViewModel is IActivatableViewModel activatableViewModel) { activatableViewModel.Activate(viewRequest); } view.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); view.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); view.Arrange(new Rect(0, 0, view.DesiredSize.Width, view.DesiredSize.Height)); view.RenderTransform = new TranslateTransform(scaleOptions.Padding.Left, scaleOptions.Padding.Top); if (scaleOptions.ScaleToFit) { var viewStretched = view as IStretchedSizeView; var scaleX = viewStretched != null ? viewSize.Width / viewStretched.StretchedWidth : viewSize.Width / view.ActualWidth; var scaleY = viewStretched != null ? viewSize.Height / viewStretched.StretchedHeight : viewSize.Height / view.ActualHeight; var scale = scaleOptions.ScaleFitting.HasFlag(ScaleFitting.BothDirections) ? Math.Min(scaleX, scaleY) : scaleOptions.ScaleFitting.HasFlag(ScaleFitting.Horizontal) ? scaleX : scaleOptions.ScaleFitting.HasFlag(ScaleFitting.Vertical) ? scaleY : 1.0; scale = Math.Min(scaleOptions.MaxScale, Math.Max(scaleOptions.MinScale, scale)); if (Math.Abs(scale - 1.0) > 0.001) { view.LayoutTransform = new ScaleTransform(scale, scale, scaleOptions.Padding.Left, scaleOptions.Padding.Top); view.Width = Math.Ceiling(viewSize.Width / scale); view.Height = Math.Ceiling(viewSize.Height / scale); } else { view.Width = viewSize.Width; view.Height = viewSize.Height; } } else { view.Width = viewSize.Width; view.Height = viewSize.Height; } var page = new FixedPage(); page.Children.Add(view); page.Width = pageSize.Width; page.Height = pageSize.Height; var pageContent = new PageContent { Child = page }; document.Pages.Add(pageContent); } return(document); }
public static double[,,] SubdivisionImageResize(double[,,] image, int M, int N, ScaleOptions scaleOptions) { int V = image.GetLength(1); int U = image.GetLength(2); double[,,] scaledImage = new double[3, N, M]; for (int n = 0; n < N; n++) { for (int m = 0; m < M; m++) { double u_star = (U * (2 * m + 1)) / (2d * M); double v_star = (V * (2 * n + 1)) / (2d * N); int u = (int)u_star; int v = (int)v_star; double x = 2 * (u_star - u) - 1; double y = 2 * (v_star - v) - 1; //chosing gama double[][] gama = null; if (scaleOptions == ScaleOptions.S20) { gama = getGama20(x, y); } else if (scaleOptions == ScaleOptions.S21) { gama = getGama21(x, y); } double[] resultRGB = ApplyConvolutionFilterByCoords(image, u, v, gama); scaledImage[0, n, m] = resultRGB[0]; scaledImage[1, n, m] = resultRGB[1]; scaledImage[2, n, m] = resultRGB[2]; } } return(scaledImage); }
/// <summary> /// Sets an image or gif/apng from a resource path /// </summary> /// <param name="image">Image component to set the image to</param> /// <param name="location">Resource path, file path, or url of image. Can prefix with # to find and use a base game sprite. May need to prefix resource paths with 'AssemblyName:'</param> /// <param name="loadingAnimation">Whether a loading animation is shown as a placeholder until the image is loaded</param> /// <param name="scaleOptions">If the image should be downscaled and what it should be downscaled to</param> public static void SetImage(this Image image, string location, bool loadingAnimation, ScaleOptions scaleOptions) { SetImage(image, location, loadingAnimation, scaleOptions, null); }