content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Tests for the ProjectTaskOutputPropertyInstanceTests class.</summary> //----------------------------------------------------------------------- using System.IO; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Build.UnitTests.OM.Instance { /// <summary> /// Tests for the ProjectTaskOutputItemInstance class. /// </summary> [TestClass] public class ProjectTaskOutputPropertyInstance_Tests { /// <summary> /// Test accessors /// </summary> [TestMethod] public void Accessors() { var output = GetSampleTaskOutputInstance(); Assert.AreEqual("p", output.TaskParameter); Assert.AreEqual("c", output.Condition); Assert.AreEqual("p1", output.PropertyName); } /// <summary> /// Create a ProjectTaskOutputPropertyInstance with some parameters /// </summary> private static ProjectTaskOutputPropertyInstance GetSampleTaskOutputInstance() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <t1> <Output TaskParameter='p' Condition='c' PropertyName='p1'/> </t1> </Target> </Project> "; ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Project project = new Project(xml); ProjectInstance instance = project.CreateProjectInstance(); ProjectTaskInstance task = (ProjectTaskInstance)instance.Targets["t"].Children[0]; ProjectTaskOutputPropertyInstance output = (ProjectTaskOutputPropertyInstance)task.Outputs[0]; return output; } } }
37.83871
109
0.559676
[ "MIT" ]
OmniSharp/msbuild
src/XMakeBuildEngine/UnitTestsPublicOM/Instance/ProjectTaskOutputPropertyInstance_Tests.cs
2,285
C#
using AutoMapper; using InTheWoods.ActionFilters; using InTheWoods.Contracts; using InTheWoods.Data; using InTheWoods.DataTransferObjects; using InTheWoods.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; namespace InTheWoods.Controllers { [Route("api/authentication")] [ApiController] public class AuthenticationController : ControllerBase { private readonly ApplicationDbContext _context; private readonly UserManager<User> _userManager; private readonly IMapper _mapper; private readonly IAuthenticationManager _authManager; public AuthenticationController(IMapper mapper, UserManager<User> userManager, IAuthenticationManager authManager, ApplicationDbContext context) { _context = context; _mapper = mapper; _userManager = userManager; _authManager = authManager; } [HttpPost] [ServiceFilter(typeof(ValidationFilterAttribute))] public async Task<IActionResult> RegisterUser([FromBody] UserForRegistrationDto userForRegistration) { var user = _mapper.Map<User>(userForRegistration); var result = await _userManager.CreateAsync(user, userForRegistration.Password); if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.TryAddModelError(error.Code, error.Description); } return BadRequest(ModelState); } await _userManager.AddToRoleAsync(user, "USER"); return StatusCode(201, user); } [HttpPost("login")] [ServiceFilter(typeof(ValidationFilterAttribute))] public async Task<IActionResult> Authenticate([FromBody] UserForAuthenticationDto user) { if (!await _authManager.ValidateUser(user)) { return Unauthorized(); } return Ok(new { Token = await _authManager.CreateToken() }); } } }
33.890625
152
0.655141
[ "MIT" ]
Mr-Nelson/IntoTheWoods-Capstone
InTheWoods/Controllers/AuthenticationController.cs
2,171
C#
using Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries.CarouselViewGalleries; using Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries.EmptyViewGalleries; using Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries.GroupingGalleries; using Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries.SelectionGalleries; using Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries.ScrollModeGalleries; using Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries.AlternateLayoutGalleries; using Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries.HeaderFooterGalleries; using Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries.ItemSizeGalleries; namespace Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries { public class CollectionViewGallery : ContentPage { public CollectionViewGallery() { Content = new ScrollView { Content = new StackLayout { Children = { GalleryBuilder.NavButton("Default Text Galleries", () => new DefaultTextGallery(), Navigation), GalleryBuilder.NavButton("DataTemplate Galleries", () => new DataTemplateGallery(), Navigation), GalleryBuilder.NavButton("Observable Collection Galleries", () => new ObservableCollectionGallery(), Navigation), GalleryBuilder.NavButton("Snap Points Galleries", () => new SnapPointsGallery(), Navigation), GalleryBuilder.NavButton("ScrollTo Galleries", () => new ScrollToGallery(), Navigation), GalleryBuilder.NavButton("CarouselView Galleries", () => new CarouselViewGallery(), Navigation), GalleryBuilder.NavButton("EmptyView Galleries", () => new EmptyViewGallery(), Navigation), GalleryBuilder.NavButton("Selection Galleries", () => new SelectionGallery(), Navigation), GalleryBuilder.NavButton("Propagation Galleries", () => new PropagationGallery(), Navigation), GalleryBuilder.NavButton("Grouping Galleries", () => new GroupingGallery(), Navigation), GalleryBuilder.NavButton("Item Size Galleries", () => new ItemsSizeGallery(), Navigation), GalleryBuilder.NavButton("Scroll Mode Galleries", () => new ScrollModeGallery(), Navigation), GalleryBuilder.NavButton("Alternate Layout Galleries", () => new AlternateLayoutGallery(), Navigation), GalleryBuilder.NavButton("Header/Footer Galleries", () => new HeaderFooterGallery(), Navigation), GalleryBuilder.NavButton("Nested CollectionViews", () => new NestedGalleries.NestedCollectionViewGallery(), Navigation), } } }; } } }
57.590909
126
0.771902
[ "MIT" ]
07101994/Xamarin.Forms
Xamarin.Forms.Controls/GalleryPages/CollectionViewGalleries/CollectionViewGallery.cs
2,534
C#
using UnityEngine; using UnityEditor; public class Test9SlicedMesh : Editor { [MenuItem("Edit/NGTools/Make 9-sliced mesh")] static void Make9SlicedMesh() { GameObject go = new GameObject("9sliced"); MeshFilter meshFilter = go.AddComponent<MeshFilter>(); go.AddComponent<MeshRenderer>(); meshFilter.mesh = Geometry.Create9SlicedMesh(); } }
25.866667
62
0.680412
[ "MIT" ]
Naphier/NGTools
Assets/NGTools/IntegrationTests/Editor/Test9SlicedMesh.cs
388
C#
version https://git-lfs.github.com/spec/v1 oid sha256:2858f53bf727a23e8679185664bcdb7777087758b565e4ec82cc7b77f149d077 size 808
32
75
0.882813
[ "MIT" ]
Vakuzar/Multithreaded-Blood-Sim
Blood/Library/PackageCache/com.unity.render-pipelines.universal@8.1.0/Editor/2D/ShapeEditor/GUIFramework/LayoutData.cs
128
C#
/* _BEGIN_TEMPLATE_ { "id": "DRG_650", "name": [ "无敌巨龙迦拉克隆", "Galakrond, the Unbreakable" ], "text": [ "<b>战吼:</b>抽一张随从牌,使其获得+4/+4。<i>(", "[x]<b>Battlecry:</b> Draw 1 minion.\nGive it +4/+4.\n<i>(" ], "cardClass": "WARRIOR", "type": "HERO", "cost": 7, "rarity": "LEGENDARY", "set": "DRAGONS", "collectible": true, "dbfId": 57413 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_DRG_650 : SimTemplate //* 无敌巨龙迦拉克隆 Galakrond, the Unbreakable { //[x]<b>Battlecry:</b> Draw 1 minion.Give it +4/+4.<i>(2)</i> //<b>战吼:</b>抽一张随从牌,使其获得+4/+4。<i>(2)</i> } }
21.482759
75
0.545746
[ "MIT" ]
chi-rei-den/Silverfish
cards/DRAGONS/DRG/Sim_DRG_650.cs
721
C#
using System.Collections.Generic; using Gear.Domain.PmEntities.Enums; using Gear.ProjectManagement.Manager.Domain.Projects.Queries.GetProjectListByGroup; using MediatR; namespace Gear.ProjectManagement.Manager.Domain.Projects.Queries.GetProjectListByStatus { public class GetProjectListByStatusQuery : IRequest<ProjectListViewModel> { public ICollection<ProjectStatus> Filter { get; set; } public bool GetAllProjects { get; set; } } }
31.066667
87
0.781116
[ "MIT" ]
indrivo/bizon360_pm
IndrivoPM/Gear.ProjectManagement.Application/Domain/Projects/Queries/GetProjectListByStatus/GetProjectListByStatusQuery.cs
468
C#
// ----------------------------------------------------------------------------------------- // <copyright file="BlobCancellationUnitTests.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using System; using System.IO; using System.Threading; using System.Threading.Tasks; #if !NETCORE using Windows.Foundation; #endif namespace Microsoft.WindowsAzure.Storage.Blob { [TestClass] public class BlobCancellationUnitTests : BlobTestBase #if XUNIT , IDisposable #endif { #if XUNIT // Todo: The simple/nonefficient workaround is to minimize change and support Xunit, // removed when we support mstest on projectK public BlobCancellationUnitTests() { MyTestInitialize(); } public void Dispose() { MyTestCleanup(); } #endif // // Use TestInitialize to run code before running each test [TestInitialize()] public void MyTestInitialize() { if (TestBase.BlobBufferManager != null) { TestBase.BlobBufferManager.OutstandingBufferCount = 0; } } // // Use TestCleanup to run code after each test has run [TestCleanup()] public void MyTestCleanup() { if (TestBase.BlobBufferManager != null) { Assert.AreEqual(0, TestBase.BlobBufferManager.OutstandingBufferCount); } } [TestMethod] [Description("Cancel blob download to stream")] [TestCategory(ComponentCategory.Blob)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public async Task CloudBlockBlobDownloadToStreamCancelAsync() { byte[] buffer = GetRandomBuffer(1 * 1024 * 1024); CloudBlobContainer container = GetRandomContainerReference(); try { await container.CreateAsync(); CloudBlockBlob blob = container.GetBlockBlobReference("blob1"); using (MemoryStream originalBlob = new MemoryStream(buffer)) { await blob.UploadFromStreamAsync(originalBlob); using (MemoryStream downloadedBlob = new MemoryStream()) { OperationContext operationContext = new OperationContext(); var tokenSource = new CancellationTokenSource(); Task action = blob.DownloadToStreamAsync(downloadedBlob, null, null, operationContext, tokenSource.Token); await Task.Delay(100); tokenSource.Cancel(); try { await action; } catch (Exception) { Assert.AreEqual(operationContext.LastResult.Exception.Message, "A task was canceled."); Assert.AreEqual(operationContext.LastResult.HttpStatusCode, 306); //Assert.AreEqual(operationContext.LastResult.HttpStatusMessage, "Unused"); } TestHelper.AssertNAttempts(operationContext, 1); } } } finally { container.DeleteIfExistsAsync().Wait(); } } [TestMethod] [Description("Cancel upload from stream")] [TestCategory(ComponentCategory.Blob)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public async Task CloudBlockBlobUploadFromStreamCancelAsync() { byte[] buffer = GetRandomBuffer(1 * 1024 * 1024); CloudBlobContainer container = GetRandomContainerReference(); try { await container.CreateAsync(); CloudBlockBlob blob = container.GetBlockBlobReference("blob1"); using (MemoryStream originalBlob = new MemoryStream(buffer)) { using (ManualResetEvent waitHandle = new ManualResetEvent(false)) { OperationContext operationContext = new OperationContext(); var tokenSource = new CancellationTokenSource(); Task action = blob.UploadFromStreamAsync(originalBlob, originalBlob.Length, null, null, operationContext, tokenSource.Token); await Task.Delay(1000); //we need a bit longer time in order to put the cancel output exception to operationContext.LastResult tokenSource.Cancel(); try { await action; } catch (Exception) { Assert.AreEqual(operationContext.LastResult.Exception.Message, "A task was canceled."); Assert.AreEqual(operationContext.LastResult.HttpStatusCode, 306); //Assert.AreEqual(operationContext.LastResult.HttpStatusMessage, "Unused"); } TestHelper.AssertNAttempts(operationContext, 1); } } } finally { container.DeleteIfExistsAsync().Wait(); } } } }
40.462963
150
0.554539
[ "Apache-2.0" ]
Meertman/azure-storage-net
Test/WindowsRuntime/Blob/BlobCancellationUnitTests.cs
6,557
C#
/**** * Exyzer * Copyright (C) 2020-2021 Yigty.ORG; all rights reserved. * Copyright (C) 2020-2021 Takym. * * distributed under the MIT License. ****/ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Exyzer.Apps.Web.Server { internal sealed class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseBlazorFrameworkFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); endpoints.MapFallbackToFile("index.html"); }); } } }
24.244444
74
0.691109
[ "MIT" ]
Takym/Exyzer
src/Exyzer.Apps.Web.Server/Startup.cs
1,047
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Samples.Controls; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using ARelativeLayout = Android.Widget.RelativeLayout; [assembly: ExportRenderer(typeof(VideoPlayer), typeof(Samples.Droid.Renderer.VideoPlayerRenderer))] namespace Samples.Droid.Renderer { public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, ARelativeLayout> { VideoView videoView; MediaController mediaController; // Used to display transport controls bool isPrepared; public VideoPlayerRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<VideoPlayer> args) { base.OnElementChanged(args); if (args.NewElement != null) { if (Control == null) { // Save the VideoView for future reference videoView = new VideoView(Context); // Put the VideoView in a RelativeLayout ARelativeLayout relativeLayout = new ARelativeLayout(Context); relativeLayout.AddView(videoView); // Center the VideoView in the RelativeLayout ARelativeLayout.LayoutParams layoutParams = new ARelativeLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent); layoutParams.AddRule(LayoutRules.CenterInParent); videoView.LayoutParameters = layoutParams; // Handle a VideoView event videoView.Prepared += OnVideoViewPrepared; SetNativeControl(relativeLayout); } SetAreTransportControlsEnabled(); SetSource(); args.NewElement.UpdateStatus += OnUpdateStatus; args.NewElement.PlayRequested += OnPlayRequested; args.NewElement.PauseRequested += OnPauseRequested; args.NewElement.StopRequested += OnStopRequested; } if (args.OldElement != null) { args.OldElement.UpdateStatus -= OnUpdateStatus; args.OldElement.PlayRequested -= OnPlayRequested; args.OldElement.PauseRequested -= OnPauseRequested; args.OldElement.StopRequested -= OnStopRequested; } } protected override void Dispose(bool disposing) { if (Control != null && videoView != null) { videoView.Prepared -= OnVideoViewPrepared; } if (Element != null) { Element.UpdateStatus -= OnUpdateStatus; } base.Dispose(disposing); } void OnVideoViewPrepared(object sender, EventArgs args) { isPrepared = true; ((IVideoPlayerController)Element).Duration = TimeSpan.FromMilliseconds(videoView.Duration); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs args) { base.OnElementPropertyChanged(sender, args); if (args.PropertyName == VideoPlayer.AreTransportControlsEnabledProperty.PropertyName) { SetAreTransportControlsEnabled(); } else if (args.PropertyName == VideoPlayer.SourceProperty.PropertyName) { SetSource(); } else if (args.PropertyName == VideoPlayer.PositionProperty.PropertyName) { if (Math.Abs(videoView.CurrentPosition - Element.Position.TotalMilliseconds) > 1000) { videoView.SeekTo((int)Element.Position.TotalMilliseconds); } } } void SetAreTransportControlsEnabled() { if (Element.AreTransportControlsEnabled) { mediaController = new MediaController(Context); mediaController.SetMediaPlayer(videoView); videoView.SetMediaController(mediaController); } else { videoView.SetMediaController(null); if (mediaController != null) { mediaController.SetMediaPlayer(null); mediaController = null; } } } void SetSource() { isPrepared = false; bool hasSetSource = false; if (Element.Source is UriVideoSource) { string uri = (Element.Source as UriVideoSource).Uri; if (!String.IsNullOrWhiteSpace(uri)) { videoView.SetVideoURI(Android.Net.Uri.Parse(uri)); hasSetSource = true; } } else if (Element.Source is FileVideoSource) { string filename = (Element.Source as FileVideoSource).File; if (!String.IsNullOrWhiteSpace(filename)) { videoView.SetVideoPath(filename); hasSetSource = true; } } else if (Element.Source is ResourceVideoSource) { string package = Context.PackageName; string path = (Element.Source as ResourceVideoSource).Path; if (!String.IsNullOrWhiteSpace(path)) { string filename = Path.GetFileNameWithoutExtension(path).ToLowerInvariant(); string uri = "android.resource://" + package + "/raw/" + filename; videoView.SetVideoURI(Android.Net.Uri.Parse(uri)); hasSetSource = true; } } if (hasSetSource && Element.AutoPlay) { videoView.Start(); } } void OnUpdateStatus(object sender, EventArgs args) { VideoStatus status = VideoStatus.NotReady; if (isPrepared) { status = videoView.IsPlaying ? VideoStatus.Playing : VideoStatus.Paused; } ((IVideoPlayerController)Element).Status = status; TimeSpan timeSpan = TimeSpan.FromMilliseconds(videoView.CurrentPosition); ((IElementController)Element).SetValueFromRenderer(VideoPlayer.PositionProperty, timeSpan); } void OnPlayRequested(object sender, EventArgs args) { videoView.Start(); } void OnPauseRequested(object sender, EventArgs args) { videoView.Pause(); } void OnStopRequested(object sender, EventArgs args) { videoView.StopPlayback(); } } }
32.899083
109
0.557864
[ "MIT" ]
GeorGeWzw/XamarinForms-Samples
Code/Samples/Samples.Android/Renderer/VideoPlayerRenderer.cs
7,174
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Diagnostics; using CalculatorApp; using CalculatorApp.Controls; using Windows.Foundation; using Windows.Devices.Input; using Windows.UI.Xaml; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Controls; namespace CalculatorApp { namespace Controls { public sealed class OperatorPanelListView : Windows.UI.Xaml.Controls.ListView { public OperatorPanelListView() { } protected override void OnApplyTemplate() { m_scrollViewer = GetTemplateChild("ScrollViewer") as ScrollViewer; m_scrollLeft = GetTemplateChild("ScrollLeft") as Button; m_scrollRight = GetTemplateChild("ScrollRight") as Button; m_content = GetTemplateChild("Content") as ItemsPresenter; if (m_scrollLeft != null) { m_scrollLeft.Click += OnScrollClick; m_scrollLeft.PointerExited += OnButtonPointerExited; } if (m_scrollRight != null) { m_scrollRight.Click += OnScrollClick; m_scrollRight.PointerExited += OnButtonPointerExited; } if (m_scrollViewer != null) { m_scrollViewer.ViewChanged += ScrollViewChanged; } this.PointerEntered += OnPointerEntered; this.PointerExited += OnPointerExited; base.OnApplyTemplate(); } private void OnScrollClick(object sender, RoutedEventArgs e) { var clicked = sender as Button; if (clicked == m_scrollLeft) { ScrollLeft(); } else { ScrollRight(); } } private void OnPointerEntered(object sender, PointerRoutedEventArgs e) { if (e.Pointer.PointerDeviceType == PointerDeviceType.Mouse) { UpdateScrollButtons(); m_isPointerEntered = true; } } private void OnPointerExited(object sender, PointerRoutedEventArgs e) { m_scrollLeft.Visibility = Visibility.Collapsed; m_scrollRight.Visibility = Visibility.Collapsed; m_isPointerEntered = false; } private void OnButtonPointerExited(object sender, PointerRoutedEventArgs e) { var button = sender as Button; // Do not bubble up the pointer exit event to the control if the button being exited was not visible if (button.Visibility == Visibility.Collapsed) { e.Handled = true; } } private void ScrollViewChanged(object sender, ScrollViewerViewChangedEventArgs e) { if (m_isPointerEntered && !e.IsIntermediate) { UpdateScrollButtons(); } } private void ShowHideScrollButtons(Visibility vLeft, Visibility vRight) { if (m_scrollLeft != null && m_scrollRight != null) { m_scrollLeft.Visibility = vLeft; m_scrollRight.Visibility = vRight; } } private void UpdateScrollButtons() { if (m_content == null || m_scrollViewer == null) { return; } // When the width is smaller than the container, don't show any if (m_content.ActualWidth <= m_scrollViewer.ActualWidth) { ShowHideScrollButtons(Visibility.Collapsed, Visibility.Collapsed); } // We have more number on both side. Show both arrows else if ((m_scrollViewer.HorizontalOffset > 0) && (m_scrollViewer.HorizontalOffset < (m_scrollViewer.ExtentWidth - m_scrollViewer.ViewportWidth))) { ShowHideScrollButtons(Visibility.Visible, Visibility.Visible); } // Width is larger than the container and left most part of the number is shown. Should be able to scroll left. else if (m_scrollViewer.HorizontalOffset == 0) { ShowHideScrollButtons(Visibility.Collapsed, Visibility.Visible); } else // Width is larger than the container and right most part of the number is shown. Should be able to scroll left. { ShowHideScrollButtons(Visibility.Visible, Visibility.Collapsed); } } private void ScrollLeft() { double offset = m_scrollViewer.HorizontalOffset - (scrollRatio * m_scrollViewer.ViewportWidth); m_scrollViewer.ChangeView(offset, null, null); } private void ScrollRight() { double offset = m_scrollViewer.HorizontalOffset + (scrollRatio * m_scrollViewer.ViewportWidth); m_scrollViewer.ChangeView(offset, null, null); } private double scrollRatio = 0.7; private bool m_isPointerEntered; private Windows.UI.Xaml.Controls.ItemsPresenter m_content; private Windows.UI.Xaml.Controls.ScrollViewer m_scrollViewer; private Windows.UI.Xaml.Controls.Button m_scrollLeft; private Windows.UI.Xaml.Controls.Button m_scrollRight; } } }
36.042169
162
0.54471
[ "MIT" ]
Flre-fly/calculator
src/Calculator/Controls/OperatorPanelListView.cs
5,983
C#
namespace EnoCore.Models { using System; using System.Collections.Generic; using System.Text; /// <summary> /// PK: FlagServiceId, sf.FlagRoundId, sf.FlagOwnerId, sf.FlagRoundOffset, sf.AttackerTeamId /// Flag FK: FlagServiceId, FlagRoundId, FlagOwnerId, FlagRoundOffset /// </summary> public sealed record SubmittedFlag(long FlagServiceId, long FlagOwnerId, long FlagRoundId, int FlagRoundOffset, long AttackerTeamId, long RoundId, long SubmissionsCount, DateTime Timestamp); }
29.4
97
0.651361
[ "MIT" ]
DanielHabenicht/EnoEngine
EnoCore/Models/SubmittedFlag.cs
590
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace LanceTrack.Web.Features.Shared { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class ValidationMessages { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal ValidationMessages() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LanceTrack.Web.Features.Shared.ValidationMessages", typeof(ValidationMessages).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Value is required. /// </summary> public static string Required { get { return ResourceManager.GetString("Required", resourceCulture); } } } }
42.712329
203
0.60712
[ "MIT" ]
rd-dev-ukraine/demo-time-track
LanceTrack.Web/Features/Shared/ValidationMessages.Designer.cs
3,120
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 04:53:22 UTC // </auto-generated> //--------------------------------------------------------- using System.CodeDom.Compiler; using System.Runtime.CompilerServices; using go; #nullable enable namespace go { namespace math { public static partial class big_package { [GeneratedCode("go2cs", "0.1.0.0")] public partial struct RoundingMode { // Value of the RoundingMode struct private readonly byte m_value; public RoundingMode(byte value) => m_value = value; // Enable implicit conversions between byte and RoundingMode struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator RoundingMode(byte value) => new RoundingMode(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator byte(RoundingMode value) => value.m_value; // Enable comparisons between nil and RoundingMode struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(RoundingMode value, NilType nil) => value.Equals(default(RoundingMode)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(RoundingMode value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, RoundingMode value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, RoundingMode value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator RoundingMode(NilType nil) => default(RoundingMode); } } }}
39.203704
115
0.626358
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/math/big/float_RoundingModeStructOf(byte).cs
2,117
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class LogMouseOverPop : MonoBehaviour { private float popPosition; private UpgradeMenu state; private LogRumble logRumble; // Start is called before the first frame update void Start() { state = GetComponentInParent<UpgradeMenu>(); logRumble = GetComponent<LogRumble>(); } // Update is called once per frame void FixedUpdate() { checkClickPos(); } void checkClickPos() { if (state.closed && !logRumble.rumbles) { PointerEventData pointerData = new PointerEventData(EventSystem.current); pointerData.position = Input.mousePosition; if (pointerData.position.x > 990 && pointerData.position.x < 1790 && pointerData.position.y < 120) { MouseEnterAnim(); } else { MouseLeaveAnim(); } } else { MouseLeaveAnim(); } void MouseLeaveAnim() { var rect = GetComponent<RectTransform>(); rect.localPosition = new Vector2(0, -30 +popPosition); popPosition -= 3f; if (popPosition < 0) popPosition = 0; } void MouseEnterAnim() { var rect = GetComponent<RectTransform>(); rect.localPosition = new Vector2(0, -30 + popPosition); popPosition += 4f; if (popPosition > 30) popPosition = 30; } } }
24.969231
110
0.556377
[ "MIT" ]
TreeSloths/IdleClickerGroup
Assets/UI/UpgradeMenu_Log/LogMouseOverPop.cs
1,625
C#
// ----------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------------------------------------------------------- //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.Azure.Commands.Batch.Models { using System.Collections.Generic; public class PSStartTask { internal Microsoft.Azure.Batch.StartTask omObject; private IList<PSEnvironmentSetting> environmentSettings; private IList<PSResourceFile> resourceFiles; public PSStartTask() { this.omObject = new Microsoft.Azure.Batch.StartTask(); } internal PSStartTask(Microsoft.Azure.Batch.StartTask omObject) { if ((omObject == null)) { throw new System.ArgumentNullException("omObject"); } this.omObject = omObject; } public string CommandLine { get { return this.omObject.CommandLine; } set { this.omObject.CommandLine = value; } } public IList<PSEnvironmentSetting> EnvironmentSettings { get { if (((this.environmentSettings == null) && (this.omObject.EnvironmentSettings != null))) { List<PSEnvironmentSetting> list; list = new List<PSEnvironmentSetting>(); IEnumerator<Microsoft.Azure.Batch.EnvironmentSetting> enumerator; enumerator = this.omObject.EnvironmentSettings.GetEnumerator(); for ( ; enumerator.MoveNext(); ) { list.Add(new PSEnvironmentSetting(enumerator.Current)); } this.environmentSettings = list; } return this.environmentSettings; } set { if ((value == null)) { this.omObject.EnvironmentSettings = null; } else { this.omObject.EnvironmentSettings = new List<Microsoft.Azure.Batch.EnvironmentSetting>(); } this.environmentSettings = value; } } public System.Int32? MaxTaskRetryCount { get { return this.omObject.MaxTaskRetryCount; } set { this.omObject.MaxTaskRetryCount = value; } } public IList<PSResourceFile> ResourceFiles { get { if (((this.resourceFiles == null) && (this.omObject.ResourceFiles != null))) { List<PSResourceFile> list; list = new List<PSResourceFile>(); IEnumerator<Microsoft.Azure.Batch.ResourceFile> enumerator; enumerator = this.omObject.ResourceFiles.GetEnumerator(); for ( ; enumerator.MoveNext(); ) { list.Add(new PSResourceFile(enumerator.Current)); } this.resourceFiles = list; } return this.resourceFiles; } set { if ((value == null)) { this.omObject.ResourceFiles = null; } else { this.omObject.ResourceFiles = new List<Microsoft.Azure.Batch.ResourceFile>(); } this.resourceFiles = value; } } public System.Boolean? RunElevated { get { return this.omObject.RunElevated; } set { this.omObject.RunElevated = value; } } public System.Boolean? WaitForSuccess { get { return this.omObject.WaitForSuccess; } set { this.omObject.WaitForSuccess = value; } } } }
32.368421
110
0.443722
[ "MIT" ]
hchungmsft/azure-powershell
src/ResourceManager/AzureBatch/Commands.Batch/Models.Generated/PSStartTask.cs
5,367
C#
namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class BreakpointsView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( BreakpointsView ) ); this.panel_Breakpoints_Search = new System.Windows.Forms.Panel(); this.listBox_Breakpoint_SearchResults = new System.Windows.Forms.ListBox(); this.label_Breakpoint_Search = new System.Windows.Forms.Label(); this.textBox_Breakpoint_Search = new System.Windows.Forms.TextBox(); this.dataGridView_Breakpoints = new System.Windows.Forms.DataGridView(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton_DeleteBreakpoint = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton_DeleteAllBreakpoints = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_ToggleAllBreakpoints = new System.Windows.Forms.ToolStripButton(); this.panel1 = new System.Windows.Forms.Panel(); this.dataGridViewImageColumn_Breakpoints_Status = new System.Windows.Forms.DataGridViewImageColumn(); this.dataGridViewTextBoxColumn_Breakpoints_Method = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn_Breakpoints_Condition = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn_Breakpoints_HitCount = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.panel_Breakpoints_Search.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView_Breakpoints)).BeginInit(); this.toolStrip1.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel_Breakpoints_Search // this.panel_Breakpoints_Search.Controls.Add( this.listBox_Breakpoint_SearchResults ); this.panel_Breakpoints_Search.Controls.Add( this.label_Breakpoint_Search ); this.panel_Breakpoints_Search.Controls.Add( this.textBox_Breakpoint_Search ); this.panel_Breakpoints_Search.Dock = System.Windows.Forms.DockStyle.Top; this.panel_Breakpoints_Search.Location = new System.Drawing.Point( 0, 0 ); this.panel_Breakpoints_Search.Name = "panel_Breakpoints_Search"; this.panel_Breakpoints_Search.Size = new System.Drawing.Size( 572, 187 ); this.panel_Breakpoints_Search.TabIndex = 1; // // listBox_Breakpoint_SearchResults // this.listBox_Breakpoint_SearchResults.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listBox_Breakpoint_SearchResults.FormattingEnabled = true; this.listBox_Breakpoint_SearchResults.HorizontalScrollbar = true; this.listBox_Breakpoint_SearchResults.Location = new System.Drawing.Point( 7, 30 ); this.listBox_Breakpoint_SearchResults.Name = "listBox_Breakpoint_SearchResults"; this.listBox_Breakpoint_SearchResults.Size = new System.Drawing.Size( 560, 147 ); this.listBox_Breakpoint_SearchResults.TabIndex = 2; this.listBox_Breakpoint_SearchResults.DoubleClick += new System.EventHandler( this.listBox_Breakpoint_SearchResults_DoubleClick ); this.listBox_Breakpoint_SearchResults.Click += new System.EventHandler( this.listBox_Breakpoint_SearchResults_Click ); // // label_Breakpoint_Search // this.label_Breakpoint_Search.AutoSize = true; this.label_Breakpoint_Search.Location = new System.Drawing.Point( 4, 7 ); this.label_Breakpoint_Search.Name = "label_Breakpoint_Search"; this.label_Breakpoint_Search.Size = new System.Drawing.Size( 44, 13 ); this.label_Breakpoint_Search.TabIndex = 1; this.label_Breakpoint_Search.Text = "Search:"; // // textBox_Breakpoint_Search // this.textBox_Breakpoint_Search.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox_Breakpoint_Search.Location = new System.Drawing.Point( 54, 4 ); this.textBox_Breakpoint_Search.Name = "textBox_Breakpoint_Search"; this.textBox_Breakpoint_Search.Size = new System.Drawing.Size( 513, 20 ); this.textBox_Breakpoint_Search.TabIndex = 0; this.textBox_Breakpoint_Search.TextChanged += new System.EventHandler( this.textBox_Breakpoint_Search_TextChanged ); // // dataGridView_Breakpoints // this.dataGridView_Breakpoints.AllowUserToAddRows = false; this.dataGridView_Breakpoints.AllowUserToDeleteRows = false; this.dataGridView_Breakpoints.AllowUserToResizeRows = false; this.dataGridView_Breakpoints.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView_Breakpoints.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView_Breakpoints.Columns.AddRange( new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewImageColumn_Breakpoints_Status, this.dataGridViewTextBoxColumn_Breakpoints_Method, this.dataGridViewTextBoxColumn_Breakpoints_Condition, this.dataGridViewTextBoxColumn_Breakpoints_HitCount} ); this.dataGridView_Breakpoints.Location = new System.Drawing.Point( 0, 28 ); this.dataGridView_Breakpoints.Name = "dataGridView_Breakpoints"; this.dataGridView_Breakpoints.ReadOnly = true; this.dataGridView_Breakpoints.RowHeadersWidth = 24; this.dataGridView_Breakpoints.Size = new System.Drawing.Size( 572, 254 ); this.dataGridView_Breakpoints.TabIndex = 2; this.dataGridView_Breakpoints.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_Breakpoints_CellContentClick ); this.dataGridView_Breakpoints.CellContentDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_Breakpoints_CellContentDoubleClick ); this.dataGridView_Breakpoints.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_Breakpoints_CellContentClick ); // // toolStrip1 // this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripButton_DeleteBreakpoint, this.toolStripSeparator1, this.toolStripButton_DeleteAllBreakpoints, this.toolStripButton_ToggleAllBreakpoints} ); this.toolStrip1.Location = new System.Drawing.Point( 0, 0 ); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size( 572, 25 ); this.toolStrip1.TabIndex = 3; this.toolStrip1.Text = "toolStrip1"; // // toolStripButton_DeleteBreakpoint // this.toolStripButton_DeleteBreakpoint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_DeleteBreakpoint.Enabled = false; this.toolStripButton_DeleteBreakpoint.Image = ((System.Drawing.Image)(resources.GetObject( "toolStripButton_DeleteBreakpoint.Image" ))); this.toolStripButton_DeleteBreakpoint.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_DeleteBreakpoint.Name = "toolStripButton_DeleteBreakpoint"; this.toolStripButton_DeleteBreakpoint.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_DeleteBreakpoint.ToolTipText = "Delete Breakpoint"; this.toolStripButton_DeleteBreakpoint.Click += new System.EventHandler( this.toolStripButton_DeleteBreakpoint_Click ); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size( 6, 25 ); // // toolStripButton_DeleteAllBreakpoints // this.toolStripButton_DeleteAllBreakpoints.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_DeleteAllBreakpoints.Enabled = false; this.toolStripButton_DeleteAllBreakpoints.Image = ((System.Drawing.Image)(resources.GetObject( "toolStripButton_DeleteAllBreakpoints.Image" ))); this.toolStripButton_DeleteAllBreakpoints.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_DeleteAllBreakpoints.Name = "toolStripButton_DeleteAllBreakpoints"; this.toolStripButton_DeleteAllBreakpoints.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_DeleteAllBreakpoints.ToolTipText = "Delete All Breakpoints"; this.toolStripButton_DeleteAllBreakpoints.Click += new System.EventHandler( this.toolStripButton_DeleteAllBreakpoints_Click ); // // toolStripButton_ToggleAllBreakpoints // this.toolStripButton_ToggleAllBreakpoints.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_ToggleAllBreakpoints.Enabled = false; this.toolStripButton_ToggleAllBreakpoints.Image = ((System.Drawing.Image)(resources.GetObject( "toolStripButton_ToggleAllBreakpoints.Image" ))); this.toolStripButton_ToggleAllBreakpoints.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_ToggleAllBreakpoints.Name = "toolStripButton_ToggleAllBreakpoints"; this.toolStripButton_ToggleAllBreakpoints.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_ToggleAllBreakpoints.ToolTipText = "Toggle All Breakpoints"; this.toolStripButton_ToggleAllBreakpoints.Click += new System.EventHandler( this.toolStripButton_ToggleAllBreakpoints_Click ); // // panel1 // this.panel1.Controls.Add( this.toolStrip1 ); this.panel1.Controls.Add( this.dataGridView_Breakpoints ); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point( 0, 187 ); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size( 572, 282 ); this.panel1.TabIndex = 4; // // dataGridViewImageColumn_Breakpoints_Status // this.dataGridViewImageColumn_Breakpoints_Status.HeaderText = ""; this.dataGridViewImageColumn_Breakpoints_Status.Name = "dataGridViewImageColumn_Breakpoints_Status"; this.dataGridViewImageColumn_Breakpoints_Status.ReadOnly = true; this.dataGridViewImageColumn_Breakpoints_Status.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridViewImageColumn_Breakpoints_Status.Width = 20; // // dataGridViewTextBoxColumn_Breakpoints_Method // this.dataGridViewTextBoxColumn_Breakpoints_Method.HeaderText = "Method"; this.dataGridViewTextBoxColumn_Breakpoints_Method.Name = "dataGridViewTextBoxColumn_Breakpoints_Method"; this.dataGridViewTextBoxColumn_Breakpoints_Method.ReadOnly = true; this.dataGridViewTextBoxColumn_Breakpoints_Method.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // dataGridViewTextBoxColumn_Breakpoints_Condition // this.dataGridViewTextBoxColumn_Breakpoints_Condition.HeaderText = "Condition"; this.dataGridViewTextBoxColumn_Breakpoints_Condition.Name = "dataGridViewTextBoxColumn_Breakpoints_Condition"; this.dataGridViewTextBoxColumn_Breakpoints_Condition.ReadOnly = true; this.dataGridViewTextBoxColumn_Breakpoints_Condition.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // dataGridViewTextBoxColumn_Breakpoints_HitCount // this.dataGridViewTextBoxColumn_Breakpoints_HitCount.HeaderText = "Hit Count"; this.dataGridViewTextBoxColumn_Breakpoints_HitCount.Name = "dataGridViewTextBoxColumn_Breakpoints_HitCount"; this.dataGridViewTextBoxColumn_Breakpoints_HitCount.ReadOnly = true; this.dataGridViewTextBoxColumn_Breakpoints_HitCount.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // BreakpointsView // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add( this.panel1 ); this.Controls.Add( this.panel_Breakpoints_Search ); this.Name = "BreakpointsView"; this.Size = new System.Drawing.Size( 572, 469 ); this.panel_Breakpoints_Search.ResumeLayout( false ); this.panel_Breakpoints_Search.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView_Breakpoints)).EndInit(); this.toolStrip1.ResumeLayout( false ); this.toolStrip1.PerformLayout(); this.panel1.ResumeLayout( false ); this.panel1.PerformLayout(); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.Panel panel_Breakpoints_Search; private System.Windows.Forms.ListBox listBox_Breakpoint_SearchResults; private System.Windows.Forms.Label label_Breakpoint_Search; private System.Windows.Forms.TextBox textBox_Breakpoint_Search; private System.Windows.Forms.DataGridView dataGridView_Breakpoints; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolStripButton_DeleteBreakpoint; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton toolStripButton_DeleteAllBreakpoints; private System.Windows.Forms.ToolStripButton toolStripButton_ToggleAllBreakpoints; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.DataGridViewImageColumn dataGridViewImageColumn_Breakpoints_Status; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Breakpoints_Method; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Breakpoints_Condition; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Breakpoints_HitCount; } }
66.060241
178
0.702535
[ "MIT" ]
NETMF/llilum
Zelig/Zelig/DebugTime/Debugger/UserControls/BreakpointsView.Designer.cs
16,449
C#
namespace CarShop.Models.Cars { public class AllCarsModel { public string Id { get; set; } public string Model { get; init; } public int Year { get; init; } public string PlateNumber { get; set; } public string Image { get; set; } public int FixedIssues { get; init; } public int RemainingIssues { get; init; } } }
19.5
49
0.571795
[ "MIT" ]
tsborissov/C_Sharp-Web
Exam Prep/CarShop/CSharp-Web-Server-main/CarShop/Models/Cars/AllCarsModel.cs
392
C#
namespace TeamBuilder.App.Core.Commands { using System; using Models; using Data; using Utilities; using System.Linq; public class LoginCommand { public string Execute(string[] args) { Check.CheckLength(2, args); string username = args[0]; string password = args[1]; if (AuthenticationManager.IsAuthenticated()) { throw new InvalidOperationException(Constants.ErrorMessages.LogoutFirst); } User user = this.GetUserByCredentials(username, password); if (user == null) { throw new ArgumentException(Constants.ErrorMessages.UserOrPasswordIsInvalid); } AuthenticationManager.LogIn(user); return $"User {user.Username} successfully loged in!"; } private User GetUserByCredentials(string username, string password) { using (TeamBuilderContext context = new TeamBuilderContext()) { User user = context.Users.FirstOrDefault(u => u.Username == username && u.Password == password && u.IsDeleted == false); return user; } } } }
26.104167
136
0.569034
[ "MIT" ]
ShadyObeyd/DatabaseAdvanced-EntityFramework-June2018
12.Workshop/TeamBuilder.App/Core/Commands/LoginCommand.cs
1,255
C#
/* http://www.cgsoso.com/forum-211-1.html CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源! CGSOSO 主打游戏开发,影视设计等CG资源素材。 插件如若商用,请务必官网购买! daily assets update for try. U should buy the asset from home store if u use it in your project! */ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Diagnostics; using Org.BouncyCastle.Math.Raw; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT409Field { private const ulong M25 = ulong.MaxValue >> 39; private const ulong M59 = ulong.MaxValue >> 5; public static void Add(ulong[] x, ulong[] y, ulong[] z) { z[0] = x[0] ^ y[0]; z[1] = x[1] ^ y[1]; z[2] = x[2] ^ y[2]; z[3] = x[3] ^ y[3]; z[4] = x[4] ^ y[4]; z[5] = x[5] ^ y[5]; z[6] = x[6] ^ y[6]; } public static void AddExt(ulong[] xx, ulong[] yy, ulong[] zz) { for (int i = 0; i < 13; ++i) { zz[i] = xx[i] ^ yy[i]; } } public static void AddOne(ulong[] x, ulong[] z) { z[0] = x[0] ^ 1UL; z[1] = x[1]; z[2] = x[2]; z[3] = x[3]; z[4] = x[4]; z[5] = x[5]; z[6] = x[6]; } public static ulong[] FromBigInteger(BigInteger x) { ulong[] z = Nat448.FromBigInteger64(x); Reduce39(z, 0); return z; } public static void Multiply(ulong[] x, ulong[] y, ulong[] z) { ulong[] tt = Nat448.CreateExt64(); ImplMultiply(x, y, tt); Reduce(tt, z); } public static void MultiplyAddToExt(ulong[] x, ulong[] y, ulong[] zz) { ulong[] tt = Nat448.CreateExt64(); ImplMultiply(x, y, tt); AddExt(zz, tt, zz); } public static void Reduce(ulong[] xx, ulong[] z) { ulong x00 = xx[0], x01 = xx[1], x02 = xx[2], x03 = xx[3]; ulong x04 = xx[4], x05 = xx[5], x06 = xx[6], x07 = xx[7]; ulong u = xx[12]; x05 ^= (u << 39); x06 ^= (u >> 25) ^ (u << 62); x07 ^= (u >> 2); u = xx[11]; x04 ^= (u << 39); x05 ^= (u >> 25) ^ (u << 62); x06 ^= (u >> 2); u = xx[10]; x03 ^= (u << 39); x04 ^= (u >> 25) ^ (u << 62); x05 ^= (u >> 2); u = xx[9]; x02 ^= (u << 39); x03 ^= (u >> 25) ^ (u << 62); x04 ^= (u >> 2); u = xx[8]; x01 ^= (u << 39); x02 ^= (u >> 25) ^ (u << 62); x03 ^= (u >> 2); u = x07; x00 ^= (u << 39); x01 ^= (u >> 25) ^ (u << 62); x02 ^= (u >> 2); ulong t = x06 >> 25; z[0] = x00 ^ t; z[1] = x01 ^ (t << 23); z[2] = x02; z[3] = x03; z[4] = x04; z[5] = x05; z[6] = x06 & M25; } public static void Reduce39(ulong[] z, int zOff) { ulong z6 = z[zOff + 6], t = z6 >> 25; z[zOff ] ^= t; z[zOff + 1] ^= (t << 23); z[zOff + 6] = z6 & M25; } public static void Square(ulong[] x, ulong[] z) { ulong[] tt = Nat.Create64(13); ImplSquare(x, tt); Reduce(tt, z); } public static void SquareAddToExt(ulong[] x, ulong[] zz) { ulong[] tt = Nat.Create64(13); ImplSquare(x, tt); AddExt(zz, tt, zz); } public static void SquareN(ulong[] x, int n, ulong[] z) { Debug.Assert(n > 0); ulong[] tt = Nat.Create64(13); ImplSquare(x, tt); Reduce(tt, z); while (--n > 0) { ImplSquare(z, tt); Reduce(tt, z); } } protected static void ImplCompactExt(ulong[] zz) { ulong z00 = zz[ 0], z01 = zz[ 1], z02 = zz[ 2], z03 = zz[ 3], z04 = zz[ 4], z05 = zz[ 5], z06 = zz[ 6]; ulong z07 = zz[ 7], z08 = zz[ 8], z09 = zz[ 9], z10 = zz[10], z11 = zz[11], z12 = zz[12], z13 = zz[13]; zz[ 0] = z00 ^ (z01 << 59); zz[ 1] = (z01 >> 5) ^ (z02 << 54); zz[ 2] = (z02 >> 10) ^ (z03 << 49); zz[ 3] = (z03 >> 15) ^ (z04 << 44); zz[ 4] = (z04 >> 20) ^ (z05 << 39); zz[ 5] = (z05 >> 25) ^ (z06 << 34); zz[ 6] = (z06 >> 30) ^ (z07 << 29); zz[ 7] = (z07 >> 35) ^ (z08 << 24); zz[ 8] = (z08 >> 40) ^ (z09 << 19); zz[ 9] = (z09 >> 45) ^ (z10 << 14); zz[10] = (z10 >> 50) ^ (z11 << 9); zz[11] = (z11 >> 55) ^ (z12 << 4) ^ (z13 << 63); zz[12] = (z12 >> 60) ^ (z13 >> 1); zz[13] = 0; } protected static void ImplExpand(ulong[] x, ulong[] z) { ulong x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3], x4 = x[4], x5 = x[5], x6 = x[6]; z[0] = x0 & M59; z[1] = ((x0 >> 59) ^ (x1 << 5)) & M59; z[2] = ((x1 >> 54) ^ (x2 << 10)) & M59; z[3] = ((x2 >> 49) ^ (x3 << 15)) & M59; z[4] = ((x3 >> 44) ^ (x4 << 20)) & M59; z[5] = ((x4 >> 39) ^ (x5 << 25)) & M59; z[6] = ((x5 >> 34) ^ (x6 << 30)); } protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz) { ulong[] a = new ulong[7], b = new ulong[7]; ImplExpand(x, a); ImplExpand(y, b); for (int i = 0; i < 7; ++i) { ImplMulwAcc(a, b[i], zz, i); } ImplCompactExt(zz); } protected static void ImplMulwAcc(ulong[] xs, ulong y, ulong[] z, int zOff) { Debug.Assert(y >> 59 == 0); ulong[] u = new ulong[8]; // u[0] = 0; u[1] = y; u[2] = u[1] << 1; u[3] = u[2] ^ y; u[4] = u[2] << 1; u[5] = u[4] ^ y; u[6] = u[3] << 1; u[7] = u[6] ^ y; for (int i = 0; i < 7; ++i) { ulong x = xs[i]; Debug.Assert(x >> 59 == 0); uint j = (uint)x; ulong g, h = 0, l = u[j & 7] ^ (u[(j >> 3) & 7] << 3); int k = 54; do { j = (uint)(x >> k); g = u[j & 7] ^ u[(j >> 3) & 7] << 3; l ^= (g << k); h ^= (g >> -k); } while ((k -= 6) > 0); Debug.Assert(h >> 53 == 0); z[zOff + i ] ^= l & M59; z[zOff + i + 1] ^= (l >> 59) ^ (h << 5); } } protected static void ImplSquare(ulong[] x, ulong[] zz) { for (int i = 0; i < 6; ++i) { Interleave.Expand64To128(x[i], zz, i << 1); } zz[12] = Interleave.Expand32to64((uint)x[6]); } } } #endif
28.326996
115
0.344564
[ "MIT" ]
zhoumingliang/test-git-subtree
Assets/RotateMe/Scripts/Best HTTP (Pro)/BestHTTP/SecureProtocol/math/ec/custom/sec/SecT409Field.cs
7,544
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Bicep.Core.Syntax { public static class StringSyntaxExtensions { /// <summary> /// Checks if the syntax node contains an interpolated string or a literal string. /// </summary> /// <param name="syntax">The string syntax node</param> public static bool IsInterpolated(this StringSyntax syntax) => syntax.SegmentValues.Length > 1; /// <summary> /// Try to get the string literal value for a syntax node. Returns null if the string is interpolated. /// </summary> /// <param name="syntax">The string syntax node</param> public static string? TryGetLiteralValue(this StringSyntax syntax) => syntax.IsInterpolated() ? null : syntax.SegmentValues[0]; } }
37.043478
110
0.644366
[ "MIT" ]
AlanFlorance/bicep
src/Bicep.Core/Syntax/StringSyntaxExtensions.cs
852
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. // Modified for Intuit's Oauth2 implementation using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Intuit.Ipp.Core.Rest; namespace Intuit.Ipp.OAuth2PlatformClient { /// <summary> /// TokenClient Class /// </summary> public class TokenClient : IDisposable { protected HttpClient Client; private bool _disposed; /// <summary> /// Constructor /// </summary> /// <param name="endpoint">endpoint</param> public TokenClient(string endpoint) : this(endpoint, new HttpClientHandler()) { } /// <summary> /// Constructor /// </summary> /// <param name="endpoint">endpoint</param> /// <param name="innerHttpMessageHandler">innerHttpMessageHandler</param> public TokenClient(string endpoint, HttpMessageHandler innerHttpMessageHandler) { if (OAuth2Client.AdvancedLoggerEnabled == false) { //Intialize Logger OAuth2Client.AdvancedLogger = LogHelper.GetAdvancedLogging(enableSerilogRequestResponseLoggingForDebug: false, enableSerilogRequestResponseLoggingForTrace: false, enableSerilogRequestResponseLoggingForConsole: false, enableSerilogRequestResponseLoggingForRollingFile: false, serviceRequestLoggingLocationForFile: System.IO.Path.GetTempPath()); } if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); if (innerHttpMessageHandler == null) throw new ArgumentNullException(nameof(innerHttpMessageHandler)); Client = new HttpClient(innerHttpMessageHandler); Client.DefaultRequestHeaders.Accept.Clear(); Client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); AuthenticationStyle = AuthenticationStyle.OAuth2; Address = endpoint; } /// <summary> /// Constructor /// </summary> /// <param name="endpoint">endpoint</param> /// <param name="clientId">clientId</param> /// <param name="clientSecret">clientSecret</param> /// <param name="style">style</param> public TokenClient(string endpoint, string clientId, string clientSecret, AuthenticationStyle style = AuthenticationStyle.OAuth2) : this(endpoint, clientId, clientSecret, new HttpClientHandler(), style) { } /// <summary> /// Constructor /// </summary> /// <param name="endpoint">endpoint</param> /// <param name="clientId">clientId</param> /// <param name="clientSecret">clientSecret</param> /// <param name="innerHttpMessageHandler">innerHttpMessageHandler</param> /// <param name="style"></param> public TokenClient(string endpoint, string clientId, string clientSecret, HttpMessageHandler innerHttpMessageHandler, AuthenticationStyle style = AuthenticationStyle.OAuth2) : this(endpoint, innerHttpMessageHandler) { if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException(nameof(clientId)); AuthenticationStyle = style; ClientId = clientId; ClientSecret = clientSecret; } /// <summary> /// ClientId /// </summary> public string ClientId { get; set; } /// <summary> /// ClientSecret /// </summary> public string ClientSecret { get; set; } /// <summary> /// Address /// </summary> public string Address { get; set; } /// <summary> /// AuthenticationStyle /// </summary> public AuthenticationStyle AuthenticationStyle { get; set; } /// <summary> /// TimeOut /// </summary> public TimeSpan Timeout { set { Client.Timeout = value; } } /// <summary> /// RequestAsync call /// </summary> /// <param name="form">form</param> /// <param name="cancellationToken">cancellationToken</param> /// <returns>task of TokenResponse</returns> public virtual async Task<TokenResponse> RequestAsync(IDictionary<string, string> form, CancellationToken cancellationToken = default(CancellationToken)) { HttpResponseMessage response; var request = new HttpRequestMessage(HttpMethod.Post, Address); request.Content = new FormUrlEncodedContent(form); if (AuthenticationStyle == AuthenticationStyle.OAuth2) { request.Headers.Authorization = new BasicAuthenticationHeaderValue(ClientId, ClientSecret); request.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } if (OAuth2Client.AdvancedLoggerEnabled != false) { OAuth2Client.AdvancedLogger.Log("Request url- " + Address); OAuth2Client.AdvancedLogger.Log("Request headers- "); OAuth2Client.AdvancedLogger.Log("Authorization Header: " + request.Headers.Authorization.ToString()); OAuth2Client.AdvancedLogger.Log("ContentType header: " + request.Content.Headers.ContentType.ToString()); OAuth2Client.AdvancedLogger.Log("Accept header: " + "application/json"); OAuth2Client.AdvancedLogger.Log("Request Body: " + await request.Content.ReadAsStringAsync().ConfigureAwait(false)); } try { response = await Client.SendAsync(request, cancellationToken).ConfigureAwait(false); } catch (System.Exception ex) { return new TokenResponse(ex); } if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.BadRequest) { var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);//errorDetail can be added here if required for BadRequest. if (OAuth2Client.AdvancedLoggerEnabled != false) { OAuth2Client.AdvancedLogger.Log("Response Status Code- " + response.StatusCode + ", Response Body- " + content); } return new TokenResponse(content); } else { string errorDetail = ""; HttpResponseHeaders headers = response.Headers; if (headers.WwwAuthenticate != null) { errorDetail = headers.WwwAuthenticate.ToString(); } if (errorDetail != null && errorDetail != "") { if (OAuth2Client.AdvancedLoggerEnabled != false) { OAuth2Client.AdvancedLogger.Log("Response: Status Code- " + response.StatusCode + ", Error Details- " + response.ReasonPhrase + ": " + errorDetail); } return new TokenResponse(response.StatusCode, response.ReasonPhrase + ": " + errorDetail); } else { if (OAuth2Client.AdvancedLoggerEnabled != false) { OAuth2Client.AdvancedLogger.Log("Response: Status Code- " + response.StatusCode + ", Error Details- " + response.ReasonPhrase); } return new TokenResponse(response.StatusCode, response.ReasonPhrase); } } } /// <summary> /// Dispose call /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Virtual Dispose call /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { Client.Dispose(); _disposed = true; } } } }
38.986425
359
0.587744
[ "Apache-2.0" ]
RVDtech1/QB-V3-NET-SDK
IPPDotNetDevKitCSV3/Code/Intuit.Ipp.OAuth2PlatformClient/Client/TokenClient.cs
8,618
C#
/* _BEGIN_TEMPLATE_ { "id": "LOOTA_BOSS_11e", "name": [ "鞭打成型", "Whipped Into Shape" ], "text": [ "+2攻击力。", "+2 Attack." ], "cardClass": "NEUTRAL", "type": "ENCHANTMENT", "cost": null, "rarity": null, "set": "LOOTAPALOOZA", "collectible": null, "dbfId": 46316 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_LOOTA_BOSS_11e : SimTemplate { } }
14.925926
42
0.568238
[ "MIT" ]
chi-rei-den/Silverfish
cards/LOOTAPALOOZA/LOOTA/Sim_LOOTA_BOSS_11e.cs
419
C#
using SharpKml.Base; namespace SharpKml.Dom { /// <summary> /// Specifies a description of a <see cref="Feature"/>, which should be /// displayed in the description balloon. /// </summary> /// <remarks> /// <para>OGC KML 2.2 Section 9.1.3.10.</para> /// <para>The text may include HTML content, with any HTML links needing /// special processing. See the standards for details.</para> /// </remarks> [KmlElement("description")] public sealed class Description : Element, IHtmlContent { /// <summary>Gets or sets the content of this instance.</summary> /// <remarks>The value may contain well formed HTML.</remarks> public string Text { get { return this.InnerText; } set { this.ClearInnerText(); this.AddInnerText(value); } } } }
28.606061
76
0.549788
[ "BSD-2-Clause" ]
Pacesetter/KML2SQL
sharpkml-25721/SharpKml/Dom/Features/Description.cs
946
C#
using MinecraftMappings.Internal.Models.Block; namespace MinecraftMappings.Minecraft.Java.Models.Block { public class RedstoneTorchOff : JavaBlockModel { public RedstoneTorchOff() : base("Redstone Torch, Off") { AddVersion("redstone_torch_off", "1.0.0") .WithPath("models/block") .WithParent("block/template_torch") .AddTexture("torch", "block/redstone_torch_off"); } } }
29.375
65
0.619149
[ "MIT" ]
null511/MinecraftMappings.NET
MinecraftMappings.NET/Minecraft/Java/Models/Block/RedstoneTorchOff.cs
472
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Security; using System.Security.Permissions; namespace System.Net.PeerToPeer { #if NET50_OBSOLETIONS [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] #endif [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public sealed class PnrpPermissionAttribute : CodeAccessSecurityAttribute { public PnrpPermissionAttribute(SecurityAction action) : base(action) { } public override IPermission CreatePermission() { return null; } } }
42.95
147
0.779977
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Security.Permissions/src/System/Net/PeerToPeer/PnrpPermissionAttribute.cs
859
C#
using System.Collections.Generic; namespace SharpGEDParser.Model { /// <summary> /// Container for DATA within a source (SOUR) record. /// </summary> public class SourceData : StructCommon, NoteHold { private List<SourEvent> _events; /// <summary> /// Details regarding the events recorded in the source. /// </summary> /// See SourData for an example. /// Will be an empty list if none. public List<SourEvent> Events { get { return _events ?? (_events = new List<SourEvent>()); } } /// <summary> /// Details about those responsible for the source. /// </summary> /// E.g. the person or institution which created the source. public string Agency { get; set; } private List<Note> _notes; /// <summary> /// Any notes associated with the source. /// </summary> /// Will be an empty list if none. public List<Note> Notes { get { return _notes ?? (_notes = new List<Note>()); } } } }
31.848485
102
0.579448
[ "Apache-2.0" ]
ennoborg/YAGP
SharpGEDParse/SharpGEDParser/Model/SourceData.cs
1,051
C#
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ploeh.AutoFixture; namespace Medidata.ZipkinTracer.Core.Test { [TestClass] public class ZipkinConfigTests { private ZipkinConfig _sut; [TestInitialize] public void Init() { var fixture = new Fixture(); _sut = new ZipkinConfig { ZipkinBaseUri = new Uri("http://zipkin.com"), Domain = r => new Uri("http://server.com"), SpanProcessorBatchSize = fixture.Create<uint>(), ExcludedPathList = new List<string>(), SampleRate = 0, NotToBeDisplayedDomainList = new List<string>() }; } [TestMethod] public void Validate() { _sut.Validate(); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void ValidateWithNullDontSampleList() { _sut.ExcludedPathList = null; _sut.Validate(); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void ValidateWithInvalirdDontSampleListItem() { _sut.ExcludedPathList = new List<string> { "xxx" }; _sut.Validate(); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void ValidateWithNegativeSampleRate() { _sut.SampleRate = -1; _sut.Validate(); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void ValidateWithInvalidSampleRate() { _sut.SampleRate = 1.1; _sut.Validate(); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void ValidateWithNullNotToBeDisplayedDomainList() { _sut.NotToBeDisplayedDomainList = null; _sut.Validate(); } /// <summary> /// TODO: Use XUnit to do easier unit test for inline data /// </summary> private class ShouldBeSampledCondition { public string SampledFlag { get; set; } public string RequestPath { get; set; } public double SampleRate { get; set; } public List<string> ExcludedPathList { get; set; } public bool ExpectedOutcome { get; set; } public ShouldBeSampledCondition( string sampledFlag, string requestPath, double sampleRate, List<string> excludedPathList, bool expectedOutcome) { SampledFlag = sampledFlag; RequestPath = requestPath; SampleRate = sampleRate; ExcludedPathList = excludedPathList; ExpectedOutcome = expectedOutcome; } } [TestMethod] public void ShouldBeSampled() { // Arrange List<ShouldBeSampledCondition> testScenarios = new List<ShouldBeSampledCondition>() { // sampledFlag has a valid bool string value { new ShouldBeSampledCondition("0", null, 0, new List<string>(), false) }, { new ShouldBeSampledCondition("1", null, 0, new List<string>(), true) }, { new ShouldBeSampledCondition("false", null, 0, new List<string>(), false) }, { new ShouldBeSampledCondition("true", null, 0, new List<string>(), true) }, { new ShouldBeSampledCondition("FALSE", null, 0, new List<string>(), false) }, { new ShouldBeSampledCondition("TRUE", null, 0, new List<string>(), true) }, { new ShouldBeSampledCondition("FalSe", null, 0, new List<string>(), false) }, { new ShouldBeSampledCondition("TrUe", null, 0, new List<string>(), true) }, // sampledFlag has an invalid bool string value and requestPath is IsInDontSampleList { new ShouldBeSampledCondition(null, "/x", 0, new List<string> { "/x" }, false) }, { new ShouldBeSampledCondition("", "/x", 0, new List<string> { "/x" }, false) }, { new ShouldBeSampledCondition("invalidValue", "/x", 0, new List<string>() { "/x" }, false) }, // sampledFlag has an invalid bool string value, requestPath not in IsInDontSampleList, and sample rate is 0 { new ShouldBeSampledCondition(null, null, 0, new List<string>(), false) }, { new ShouldBeSampledCondition(null, "/x", 0, new List<string>(), false) }, // sampledFlag has an invalid bool string value, requestPath not in IsInDontSampleList, and sample rate is 1 { new ShouldBeSampledCondition(null, null, 1, new List<string>(), true) }, }; foreach (var testScenario in testScenarios) { var fixture = new Fixture(); _sut = new ZipkinConfig { ExcludedPathList = testScenario.ExcludedPathList, SampleRate = testScenario.SampleRate }; // Act var result = _sut.ShouldBeSampled(testScenario.SampledFlag, testScenario.RequestPath); // Assert Assert.AreEqual( testScenario.ExpectedOutcome, result, "Scenario: " + $"SampledFlag({testScenario.SampledFlag ?? "null"}), " + $"RequestPath({testScenario.RequestPath ?? "null"}), " + $"SampleRate({testScenario.SampleRate}), " + $"ExcludedPathList({string.Join(",", testScenario.ExcludedPathList)}),"); } } } }
39.718121
124
0.547482
[ "MIT" ]
ihenjoy/Medidata.ZipkinTracerModule
tests/Medidata.ZipkinTracer.Core.Test/ZipkinConfigTests.cs
5,920
C#
using System.Collections.Generic; namespace Lykke.Job.ChainalysisHistoryExporter.Common { public class Blockchain { public string CryptoCurrency { get; set; } public string BilId { get; set; } public string AssetBlockchain { get; set; } public IReadOnlyCollection<string> AssetReferences { get; set; } } }
27.076923
72
0.678977
[ "MIT" ]
LykkeCity/Lykke.Job.ChainalysisHistoryExporter
src/Lykke.Job.ChainalysisHistoryExporter/Common/Blockchain.cs
354
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Sayisal.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sayisal.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.486111
173
0.601949
[ "MIT" ]
SuatOzcan/WIndowsForms
Sayisal/Sayisal/Properties/Resources.Designer.cs
2,773
C#
using iShape.Clipper.Collision; using iShape.Collections; using iShape.Geometry; using NUnit.Framework; using Tests.Clipper.Data; using Unity.Collections; namespace Tests.Clipper { public class SimplifyTests { private IntGeom iGeom = IntGeom.DefGeom; [Test] public void Test_00() { var data = SimplifyTestData.data[0]; var origin = data.points; var points = new DynamicArray<IntVector>(origin, Allocator.Temp); points.Simplify(); var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_01() { var data = SimplifyTestData.data[1]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = new [] { new IntVector(-100000, -100000), new IntVector(-100000, 100000), new IntVector(0, 0) }; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_02() { var data = SimplifyTestData.data[2]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = new [] { new IntVector(-100000, -100000), new IntVector(-150000, -150000) }; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_03() { var data = SimplifyTestData.data[3]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = new [] { new IntVector(0, -100000), new IntVector(0, 100000), new IntVector(-100000, 100000) }; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_04() { var data = SimplifyTestData.data[4]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = new [] { new IntVector(0, -100000), new IntVector(0, 0), new IntVector(-100000, 0) }; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_05() { var data = SimplifyTestData.data[5]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = new [] { new IntVector(0, -100000), new IntVector(0, 0) }; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_06() { var data = SimplifyTestData.data[6]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = new [] { new IntVector(0, -50000), new IntVector(0, -100000) }; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_07() { var data = SimplifyTestData.data[7]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = new [] { new IntVector(-100000, -100000) }; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_08() { var data = SimplifyTestData.data[8]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = new [] { new IntVector(0, -100000), new IntVector(0, 100000), new IntVector(100000, -100000) }; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_09() { var data = SimplifyTestData.data[9]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = new [] { new IntVector(0, -100000), new IntVector(0, 100000) }; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_10() { var data = SimplifyTestData.data[10]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = new [] { new IntVector(-100000, 0), new IntVector(50000, 0) }; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } [Test] public void Test_11() { var data = SimplifyTestData.data[11]; var points = new DynamicArray<IntVector>(data.points, Allocator.Temp); points.Simplify(); var origin = data.points; var result = points.ConvertToArray(); Assert.AreEqual(origin, result); } } }
30.883598
82
0.497858
[ "MIT" ]
iShapeUnity/Clipper
Tests/Editor/Tests/Clipper/SimplifyTests.cs
5,837
C#
using Zoro.IO; using Zoro.Network.P2P.Payloads; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Text; using System.Threading; namespace Zoro.Cryptography { public static class Helper { private static ThreadLocal<SHA256> _sha256 = new ThreadLocal<SHA256>(() => SHA256.Create()); private static ThreadLocal<RIPEMD160Managed> _ripemd160 = new ThreadLocal<RIPEMD160Managed>(() => new RIPEMD160Managed()); internal static byte[] AES256Decrypt(this byte[] block, byte[] key) { using (Aes aes = Aes.Create()) { aes.Key = key; aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.None; using (ICryptoTransform decryptor = aes.CreateDecryptor()) { return decryptor.TransformFinalBlock(block, 0, block.Length); } } } internal static byte[] AES256Encrypt(this byte[] block, byte[] key) { using (Aes aes = Aes.Create()) { aes.Key = key; aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.None; using (ICryptoTransform encryptor = aes.CreateEncryptor()) { return encryptor.TransformFinalBlock(block, 0, block.Length); } } } internal static byte[] AesDecrypt(this byte[] data, byte[] key, byte[] iv) { if (data == null || key == null || iv == null) throw new ArgumentNullException(); if (data.Length % 16 != 0 || key.Length != 32 || iv.Length != 16) throw new ArgumentException(); using (Aes aes = Aes.Create()) { aes.Padding = PaddingMode.None; using (ICryptoTransform decryptor = aes.CreateDecryptor(key, iv)) { return decryptor.TransformFinalBlock(data, 0, data.Length); } } } internal static byte[] AesEncrypt(this byte[] data, byte[] key, byte[] iv) { if (data == null || key == null || iv == null) throw new ArgumentNullException(); if (data.Length % 16 != 0 || key.Length != 32 || iv.Length != 16) throw new ArgumentException(); using (Aes aes = Aes.Create()) { aes.Padding = PaddingMode.None; using (ICryptoTransform encryptor = aes.CreateEncryptor(key, iv)) { return encryptor.TransformFinalBlock(data, 0, data.Length); } } } public static byte[] Base58CheckDecode(this string input) { byte[] buffer = Base58.Decode(input); if (buffer.Length < 4) throw new FormatException(); byte[] checksum = buffer.Sha256(0, buffer.Length - 4).Sha256(); if (!buffer.Skip(buffer.Length - 4).SequenceEqual(checksum.Take(4))) throw new FormatException(); return buffer.Take(buffer.Length - 4).ToArray(); } public static string Base58CheckEncode(this byte[] data) { byte[] checksum = data.Sha256().Sha256(); byte[] buffer = new byte[data.Length + 4]; Buffer.BlockCopy(data, 0, buffer, 0, data.Length); Buffer.BlockCopy(checksum, 0, buffer, data.Length, 4); return Base58.Encode(buffer); } public static byte[] RIPEMD160(this IEnumerable<byte> value) { return _ripemd160.Value.ComputeHash(value.ToArray()); } public static uint Murmur32(this IEnumerable<byte> value, uint seed) { using (Murmur3 murmur = new Murmur3(seed)) { return murmur.ComputeHash(value.ToArray()).ToUInt32(0); } } public static byte[] Sha256(this IEnumerable<byte> value) { return _sha256.Value.ComputeHash(value.ToArray()); } public static byte[] Sha256(this byte[] value, int offset, int count) { return _sha256.Value.ComputeHash(value, offset, count); } internal static bool Test(this BloomFilter filter, Transaction tx) { if (filter.Check(tx.Hash.ToArray())) return true; if (tx.Outputs.Any(p => filter.Check(p.ScriptHash.ToArray()))) return true; if (tx.Inputs.Any(p => filter.Check(p.ToArray()))) return true; if (tx.Witnesses.Any(p => filter.Check(p.ScriptHash.ToArray()))) return true; #pragma warning disable CS0612 if (tx is RegisterTransaction asset) if (filter.Check(asset.Admin.ToArray())) return true; #pragma warning restore CS0612 return false; } internal static byte[] ToAesKey(this string password) { using (SHA256 sha256 = SHA256.Create()) { byte[] passwordBytes = Encoding.UTF8.GetBytes(password); byte[] passwordHash = sha256.ComputeHash(passwordBytes); byte[] passwordHash2 = sha256.ComputeHash(passwordHash); Array.Clear(passwordBytes, 0, passwordBytes.Length); Array.Clear(passwordHash, 0, passwordHash.Length); return passwordHash2; } } internal static byte[] ToAesKey(this SecureString password) { using (SHA256 sha256 = SHA256.Create()) { byte[] passwordBytes = password.ToArray(); byte[] passwordHash = sha256.ComputeHash(passwordBytes); byte[] passwordHash2 = sha256.ComputeHash(passwordHash); Array.Clear(passwordBytes, 0, passwordBytes.Length); Array.Clear(passwordHash, 0, passwordHash.Length); return passwordHash2; } } internal static byte[] ToArray(this SecureString s) { if (s == null) throw new NullReferenceException(); if (s.Length == 0) return new byte[0]; List<byte> result = new List<byte>(); IntPtr ptr = SecureStringMarshal.SecureStringToGlobalAllocAnsi(s); try { int i = 0; do { byte b = Marshal.ReadByte(ptr, i++); if (b == 0) break; result.Add(b); } while (true); } finally { Marshal.ZeroFreeGlobalAllocAnsi(ptr); } return result.ToArray(); } } }
37.304348
130
0.537005
[ "MIT" ]
ProDog/Zoro
Zoro/Cryptography/Helper.cs
6,866
C#
namespace YourBrand.Payments.Application.Common.Interfaces; public interface IDateTime { DateTime Now { get; } }
20.5
61
0.739837
[ "MIT" ]
marinasundstrom/YourCompany
Finance/Payments/Payments/Application/Common/Interfaces/IDateTime.cs
125
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ClashOfClans.Core { internal class NullableTypes { private readonly HashSet<string> _checkedNullProperties = new HashSet<string>(); private readonly Dictionary<string, int> _nullProperties = new Dictionary<string, int>(); public NullableTypes() { Init(); } internal void Init() { var filename = "CheckedNullableTypes.txt"; if (File.Exists(filename)) { var content = File.ReadAllLines(filename); foreach (var row in content) { // <class:property>, <date>, total <xyz> var index = row.IndexOf(','); if (index > 0) { _checkedNullProperties.Add(row.Substring(0, index)); } } } } /// <summary> /// Adds found nullable properties to storage /// </summary> /// <param name="nullProperties"></param> internal void Add(IEnumerable<string> nullProperties) { foreach (var nullProperty in nullProperties) { if (_nullProperties.ContainsKey(nullProperty)) _nullProperties[nullProperty]++; else _nullProperties.Add(nullProperty, 1); } } /// <summary> /// Returns a sorted list of null properties (KVP) that have not been checked or null /// if all properties have been checked. /// </summary> /// <returns></returns> internal IOrderedEnumerable<KeyValuePair<string, int>>? GetUncheckedNulls() { var keys = _nullProperties.Select(kvp => kvp.Key).Except(_checkedNullProperties); if (keys.Count() == 0) return default; return _nullProperties.Where(kvp => keys.Contains(kvp.Key)).OrderBy(kvp => kvp.Key); } } }
30.867647
97
0.525488
[ "MIT" ]
tparviainen/clashofclans
src/ClashOfClans/Core/NullableTypes.cs
2,101
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Inputs.Monitoring.V1 { /// <summary> /// HTTPGet specifies the http request to perform. /// </summary> public class PrometheusSpecContainersLivenessProbeHttpGetArgs : Pulumi.ResourceArgs { /// <summary> /// Host name to connect to, defaults to the pod IP. You probably want to set "Host" in httpHeaders instead. /// </summary> [Input("host")] public Input<string>? Host { get; set; } [Input("httpHeaders")] private InputList<Pulumi.Kubernetes.Types.Inputs.Monitoring.V1.PrometheusSpecContainersLivenessProbeHttpGetHttpHeadersArgs>? _httpHeaders; /// <summary> /// Custom headers to set in the request. HTTP allows repeated headers. /// </summary> public InputList<Pulumi.Kubernetes.Types.Inputs.Monitoring.V1.PrometheusSpecContainersLivenessProbeHttpGetHttpHeadersArgs> HttpHeaders { get => _httpHeaders ?? (_httpHeaders = new InputList<Pulumi.Kubernetes.Types.Inputs.Monitoring.V1.PrometheusSpecContainersLivenessProbeHttpGetHttpHeadersArgs>()); set => _httpHeaders = value; } /// <summary> /// Path to access on the HTTP server. /// </summary> [Input("path")] public Input<string>? Path { get; set; } /// <summary> /// Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. /// </summary> [Input("port", required: true)] public Input<Pulumi.Kubernetes.Types.Inputs.Monitoring.V1.PrometheusSpecContainersLivenessProbeHttpGetPortArgs> Port { get; set; } = null!; /// <summary> /// Scheme to use for connecting to the host. Defaults to HTTP. /// </summary> [Input("scheme")] public Input<string>? Scheme { get; set; } public PrometheusSpecContainersLivenessProbeHttpGetArgs() { } } }
38.576271
174
0.657293
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/prometheus/dotnet/Kubernetes/Crds/Operators/Prometheus/Monitoring/V1/Inputs/PrometheusSpecContainersLivenessProbeHttpGetArgs.cs
2,276
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SageMaker.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SageMaker.Model.Internal.MarshallTransformations { /// <summary> /// DescribeEndpointConfig Request Marshaller /// </summary> public class DescribeEndpointConfigRequestMarshaller : IMarshaller<IRequest, DescribeEndpointConfigRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribeEndpointConfigRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeEndpointConfigRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.SageMaker"); string target = "SageMaker.DescribeEndpointConfig"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-07-24"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetEndpointConfigName()) { context.Writer.WritePropertyName("EndpointConfigName"); context.Writer.Write(publicRequest.EndpointConfigName); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DescribeEndpointConfigRequestMarshaller _instance = new DescribeEndpointConfigRequestMarshaller(); internal static DescribeEndpointConfigRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeEndpointConfigRequestMarshaller Instance { get { return _instance; } } } }
36.038835
159
0.64278
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/Internal/MarshallTransformations/DescribeEndpointConfigRequestMarshaller.cs
3,712
C#
using AbilityUser; using RimWorld; using Verse; using System.Linq; using System; using System.Collections.Generic; namespace TorannMagic { public class Projectile_SmokeCloud : Projectile_AbilityBase { protected override void Impact(Thing hitThing) { Map map = base.Map; base.Impact(hitThing); ThingDef def = this.def; Pawn p = launcher as Pawn; float explosionRadius = this.def.projectile.explosionRadius; if (p != null) { if (p.GetComp<CompAbilityUserMagic>().MagicData.MagicPowerSkill_Cantrips.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Cantrips_ver").level >= 2) { explosionRadius += 2f; } if (p.GetComp<CompAbilityUserMagic>().MagicData.MagicPowerSkill_Cantrips.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Cantrips_pwr").level >= 1) { List<Pawn> blindedPawns = TM_Calc.FindAllPawnsAround(map, base.Position, explosionRadius); if (blindedPawns != null && blindedPawns.Count > 0) { for (int i = 0; i < blindedPawns.Count; i++) { if (blindedPawns[i].Faction != null && blindedPawns[i].Faction.HostileTo(p.Faction)) { HealthUtility.AdjustSeverity(blindedPawns[i], HediffDef.Named("TM_Blind"), .6f); } else if (blindedPawns[i].Faction != p.Faction) { HealthUtility.AdjustSeverity(blindedPawns[i], HediffDef.Named("TM_Blind"), .6f); if (blindedPawns[i].RaceProps.Animal) { if (Rand.Chance(.5f)) { blindedPawns[i].mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter, null, false, false, null, false); } } } } } } } GenExplosion.DoExplosion(base.Position, map, explosionRadius, this.def.projectile.damageDef, this.launcher, this.def.projectile.GetDamageAmount(1,null), 0, SoundDefOf.Artillery_ShellLoaded, def, this.equipmentDef, null, TorannMagicDefOf.Mote_Base_Smoke, 1f, 1, false, null, 0f, 1, 0f, false); } } }
44.372881
304
0.512605
[ "BSD-3-Clause" ]
Phenrei/RWoM
RimWorldOfMagic/RimWorldOfMagic/Projectile_SmokeCloud.cs
2,620
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HammerSpace.Models")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP Inc.")] [assembly: AssemblyProduct("HammerSpace.Models")] [assembly: AssemblyCopyright("Copyright © HP Inc. 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("97fdb379-de76-40cb-a2e1-47e1ff5ecdfc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.324324
84
0.748237
[ "MIT" ]
Evan-Lacy/HammerSpace
HammerSpace.Models/Properties/AssemblyInfo.cs
1,421
C#
using System; using System.Collections.Generic; using System.IO.BACnet.Serialize; using System.Linq; using System.Text; namespace System.IO.BACnet { public struct BacnetDailySchedule : ASN1.IEncode, ASN1.IDecode { public List<BacnetTimeValue> DaySchedule; public int Decode(byte[] buffer, int offset, uint count) { int len = 0; DaySchedule = new List<BacnetTimeValue>(); //begin of daily sched if (ASN1.IS_OPENING_TAG(buffer[offset + len])) { len++; //end of daily sched while (!ASN1.IS_CLOSING_TAG(buffer[offset + len]) ) { var timeVal = new BacnetTimeValue(); len += timeVal.Decode(buffer, offset + len, count); DaySchedule.Add(timeVal); } //closing tag len++; } return len; } public void Encode(EncodeBuffer buffer) { ASN1.encode_opening_tag(buffer, 0); if (DaySchedule != null) { foreach (var dayItem in DaySchedule) { dayItem.Encode(buffer); } } ASN1.encode_closing_tag(buffer, 0); } public override string ToString() { return $"DaySchedule Len: {DaySchedule?.Count() ?? 0}"; } } }
25.948276
71
0.485714
[ "MIT" ]
mRy0/BACnet
Base/BacnetDailySchedule.cs
1,507
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Audion")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Audion")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.8.2")] [assembly: AssemblyFileVersion("0.8.2")]
36.638889
97
0.756634
[ "MIT" ]
Winrobrine/audion.cscore
Audion/Properties/AssemblyInfo.cs
1,322
C#
using UnityEngine; public class UnityDebugLogService : ILogService { public void LogMessage(string message) { Debug.Log(message); } public void ErrorMessage(string message) { Debug.LogError(message); } }
16.466667
47
0.651822
[ "MIT" ]
et9930/ECS-Game
Assets/Script/Services/UnityServices/UnityDebugLogService.cs
249
C#
using System; using System.Globalization; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Algorithms.Tests { [TestClass] public class MergeSortTest { [TestMethod] public void WhenWeGiveArray_ThenItIsSorted() { int[] array = { 2, 4, 1, 5, 6, 8, 7, 9, 3 }; MergeSort.Sort(array); int i = 1; foreach (int v in array) { Assert.AreEqual(i, v); i++; } } [TestMethod] public void test() { var arr = new int[] {1, 3, 6, 7, 9, 11, 15, 17}; var r = twoSum(arr, 17); var f = Fib(7); Assert.AreEqual(r, true); } private bool twoSum(int[] array, int target) { int leftIndex = 0; int rightIndex = 0; while (leftIndex <= rightIndex) { if (array[leftIndex] + array[rightIndex] == target) { Console.WriteLine(array[leftIndex] + " " + array[rightIndex]); return true; } if (array[leftIndex] + array[rightIndex] < target) { leftIndex++; } else { rightIndex--; } } return true; } private int Fib(int n) { if (n == 0) return 0; var previousFib = 0; var currentFib = 1; for (int i = 2; i <= n; i++) { // loop is skipped if n = 1 var newFib = previousFib + currentFib; previousFib = currentFib; currentFib = newFib; } return currentFib; } } }
23.765432
82
0.415584
[ "MIT" ]
andrei-galkin/Structures-and-Algorithms
Lib/Algorithms.Tests/MergeSortTest.cs
1,927
C#
namespace Exceptionless.Core.Models; public class SummaryData { public string TemplateKey { get; set; } public object Data { get; set; } }
21.285714
43
0.704698
[ "Apache-2.0" ]
491134648/Exceptionless
src/Exceptionless.Core/Models/SummaryData.cs
151
C#
using System; using System.Collections.Generic; using Sitecore.Data.Items; using Sitecore.Security.AccessControl; using Sitecore.Security.Accounts; using Sitecore.Security.Domains; using Sitecore.SecurityModel; namespace Glass.Mapper.Sc.FakeDb { public class Helpers { public static Item CreateFakeItem(Guid fieldId, string fieldValue, string name = "itemName") { var dic = new Dictionary<Guid, string>(); dic.Add(fieldId, fieldValue); return Sc.Utilities.CreateFakeItem(dic, name); } } public class FakeAuthorizationProvider : AuthorizationProvider { public override AccessRuleCollection GetAccessRules(ISecurable entity) { return new AccessRuleCollection(); } public override void SetAccessRules(ISecurable entity, AccessRuleCollection rules) { } protected override AccessResult GetAccessCore(ISecurable entity, Account account, AccessRight accessRight) { return new AccessResult(AccessPermission.Allow, new AccessExplanation("fake")); } } public class FakeAccessRightProvider : AccessRightProvider { public override AccessRight GetAccessRight(string accessRightName) { return new AccessRight(accessRightName); } } public class FakeDomainProvider : DomainProvider { public override void AddDomain(string domainName, bool locallyManaged) { } public override Domain GetDomain(string name) { return new Domain(name); } public override IEnumerable<Domain> GetDomains() { return new Domain[] {}; } public override void RemoveDomain(string domainName) { } } }
26.888889
115
0.612087
[ "Apache-2.0" ]
D4rkiii/Glass.Mapper
Tests/Unit Tests/Glass.Mapper.Sc.FakeDb/Helpers.cs
1,938
C#
using Sitecore.Analytics.Data; using Sitecore.Data.Items; using Sitecore.Feature.ProfileMapper.Abstractions; using Sitecore.Reflection; namespace Sitecore.Feature.ProfileMapper.Models { public class ProfileMapItem : CustomItem { public ProfileMapItem(Item innerItem) : base(innerItem) { } public virtual TrackingField EvaluateProfileMap(Item contextItem) { if (!ProfileMapItemIsValid()) return null; var profileMap = ToProfileMap(); if (profileMap == null || !profileMap.IsValid(InnerItem)) return null; return profileMap.Evaluate(InnerItem, contextItem); } /// <summary> /// Things that all profile maps regardless of type should have /// </summary> /// <returns></returns> protected virtual bool ProfileMapItemIsValid() { if (string.IsNullOrWhiteSpace(InnerItem[FieldNames.TrackingField]) || string.IsNullOrWhiteSpace(InnerItem[Templates.ProfileMap.Fields.ProfileMapAssembly]) || string.IsNullOrWhiteSpace(InnerItem[Templates.ProfileMap.Fields.ProfileMapClass])) return false; return true; } protected virtual IProfileMap ToProfileMap() { return ReflectionUtil.CreateObject( InnerItem[Templates.ProfileMap.Fields.ProfileMapAssembly], InnerItem[Templates.ProfileMap.Fields.ProfileMapClass], new object[] { }) as IProfileMap; } } }
31.94
104
0.622417
[ "MIT" ]
thinkfreshnick/Sitecore.Feature.ProfileMapper
src/Feature/ProfileMapper/code/Models/ProfileMapItem.cs
1,599
C#
using System; using System.Collections; using System.Collections.Generic; using NaughtyAttributes; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Serialization; namespace RabbitStewdio.Unity.UnityTools.SmartVars { /// <summary> /// This base class exists only because we cannot use interfaces in Unity due to serialisation constraints. /// </summary> public abstract class SmartRuntimeSet : ScriptableObject { public abstract Type GetMemberType(); public abstract void Register(object o); public abstract void Unregister(object o); public abstract void Restore(); void OnDisable() { SceneManager.activeSceneChanged -= OnActiveSceneChanged; OnDisableOverride(); } protected virtual void OnDisableOverride() { } void OnEnable() { Restore(); SceneManager.activeSceneChanged -= OnActiveSceneChanged; OnEnableOverride(); } protected virtual void OnEnableOverride() { } void OnActiveSceneChanged(Scene prev, Scene next) { Restore(); } } public class SmartRuntimeSet<T> : SmartRuntimeSet, IReadOnlyList<T> { // ReSharper disable once CollectionNeverUpdated.Local static readonly List<T> empty = new List<T>(); public event Action<T> OnEntryAdded; public event Action<T> OnEntryRemoved; [Tooltip("Predefined Designtime Values")] [FormerlySerializedAs("Values")] [SerializeField] List<T> values; readonly HashSet<T> uniqueValues; readonly List<T> runtimeValues; public SmartRuntimeSet(IEqualityComparer<T> comparer) { values = new List<T>(); uniqueValues = new HashSet<T>(comparer); runtimeValues = new List<T>(); } public ReadOnlyListWrapper<T> Values => new ReadOnlyListWrapper<T>(runtimeValues); public bool Contains(T t) { return uniqueValues.Contains(t); } public override void Restore() { runtimeValues.Clear(); uniqueValues.Clear(); if (values != null) { foreach (var value in values) { Register(value); } } } public override Type GetMemberType() { return typeof(T); } public List<T>.Enumerator GetEnumerator() { if (runtimeValues == null) { return empty.GetEnumerator(); } return runtimeValues.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } public int Count { get { return runtimeValues.Count; } } public T this[int index] { get { return runtimeValues[index]; } } public override void Register(object o) { if (runtimeValues != null && o is T) { var t = (T) o; if (uniqueValues.Add(t)) { runtimeValues.Add(t); OnEntryAdded?.Invoke(t); } } } public void RegisterTyped(T o) => Register(o); public override void Unregister(object o) { if (runtimeValues != null && o is T) { var t = (T) o; if (uniqueValues.Remove(t)) { runtimeValues.Remove(t); OnEntryRemoved?.Invoke(t); } } } public void UnregisterTyped(T o) => Register(o); protected override void OnDisableOverride() { OnEntryAdded = null; OnEntryRemoved = null; } } }
24.701754
112
0.514441
[ "MIT" ]
tmorgner/WeaponSystem
Assets/Plugins/UnityTools/Scripts/SmartVars/SmartRuntimeSet.cs
4,226
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BitTools.Tests { [TestClass] public class ReadingWritingTests { [TestMethod] public void TestWriteReadByte() { // 00000000 00000000 00000000 00000000 // | | | | | // 31 24 16 8 0 byte[] b = new byte[4]; BitWriter.WriteByte(1, 1, b, 0); TestUtils.AssertPattern("00000000 00000000 00000000 00000001", b); BitWriter.WriteByte(1, 1, b, 31); TestUtils.AssertPattern("10000000 00000000 00000000 00000001", b); BitWriter.WriteByte(3, 2, b, 7); TestUtils.AssertPattern("10000000 00000000 00000001 10000001", b); BitWriter.WriteByte(255, 8, b, 9); TestUtils.AssertPattern("10000000 00000001 11111111 10000001", b); TestUtils.AssertPattern("00000001", BitReader.ReadByte(2, b, 0)); TestUtils.AssertPattern("00000001", BitReader.ReadByte(7, b, 0)); TestUtils.AssertPattern("10000001", BitReader.ReadByte(8, b, 0)); TestUtils.AssertPattern("11000000", BitReader.ReadByte(8, b, 1)); TestUtils.AssertPattern("11111000", BitReader.ReadByte(8, b, 4)); TestUtils.AssertPattern("00000000", BitReader.ReadByte(8, b, 20)); TestUtils.AssertPattern("10000000", BitReader.ReadByte(8, b, 24)); TestUtils.AssertPattern("00000000", BitReader.ReadByte(8, b, 23)); BitWriter.WriteByte(3, 2, b, 23); TestUtils.AssertPattern("10000001 10000001 11111111 10000001", b); BitWriter.WriteByte(1, 1, b, 25); TestUtils.AssertPattern("10000011 10000001 11111111 10000001", b); TestUtils.AssertPattern("11000000", BitReader.ReadByte(8, b, 17)); TestUtils.AssertPattern("01000000", BitReader.ReadByte(7, b, 17)); TestUtils.AssertPattern("00000001", BitReader.ReadByte(1, b, 31)); BitWriter.WriteClearBit(b, 10); TestUtils.AssertPattern("10000011 10000001 11111011 10000001", b); BitWriter.WriteClearBit(b, 12); TestUtils.AssertPattern("10000011 10000001 11101011 10000001", b); BitWriter.WriteSetBit(b, 10); TestUtils.AssertPattern("10000011 10000001 11101111 10000001", b); for(int i = 0; i < 32; ++i) BitWriter.WriteClearBit(b, i); TestUtils.AssertPattern("00000000 00000000 00000000 00000000", b); BitWriter.WriteSetBit(b, 22); BitWriter.WriteSetBit(b, 31); TestUtils.AssertPattern("10000000 01000000 00000000 00000000", b); BitWriter.WriteByte(7, 3, b, 23); TestUtils.AssertPattern("10000011 11000000 00000000 00000000", b); TestUtils.AssertPattern("00001111", BitReader.ReadByte(4, b, 22)); } [TestMethod] public void TestWriteReadBytes() { // 00000000 00000000 00000000 00000000 00000000 // | | | | | | // 39 32 24 16 8 0 byte[] b = new byte[5]; byte[] s = new byte[3]; s[0] = 255; s[1] = 255; s[2] = 255; BitWriter.WriteBytes(s, b, 0); TestUtils.AssertPattern("00000000 00000000 11111111 11111111 11111111", b); BitWriter.WriteBytes(s, 0, 1, b, 25); TestUtils.AssertPattern("00000001 11111110 11111111 11111111 11111111", b); BitMath.ClearBytes(b); TestUtils.AssertPattern("00000000 00000000 00000000 00000000 00000000", b); BitWriter.WriteSetBit(b, 0); BitWriter.WriteSetBit(b, 19); TestUtils.AssertPattern("00000000 00000000 00001000 00000000 00000001", b); BitWriter.WriteBytes(s, 0, 2, b, 2); TestUtils.AssertPattern("00000000 00000000 00001011 11111111 11111101", b); TestUtils.AssertPattern("11111101", BitReader.ReadBytes(b, 1, 0)); TestUtils.AssertPattern("11111111 11111101", BitReader.ReadBytes(b, 2, 0)); TestUtils.AssertPattern("11111111 11111110", BitReader.ReadBytes(b, 2, 1)); TestUtils.AssertPattern("11111111 11111111", BitReader.ReadBytes(b, 2, 2)); TestUtils.AssertPattern("01111111 11111111", BitReader.ReadBytes(b, 2, 3)); TestUtils.AssertPattern("00000101 11111111 11111110", BitReader.ReadBytes(b, 3, 1)); BitMath.ClearBytes(s); BitMath.ClearBytes(b); TestUtils.AssertPattern("00000000 00000000 00000000", s); TestUtils.AssertPattern("00000000 00000000 00000000 00000000 00000000", b); s[0] = 1 | 2 | 64; s[1] = 2 | 4 | 8 | 128; s[2] = 128 | 32 | 16; TestUtils.AssertPattern("10110000 10001110 01000011", s); BitWriter.WriteBytes(new byte[] { 255, 255, 255 }, b, 0); TestUtils.AssertPattern("00000000 00000000 11111111 11111111 11111111", b); BitWriter.WriteBytes(s, b, 0); TestUtils.AssertPattern("00000000 00000000 10110000 10001110 01000011", b); BitWriter.WriteBytes(s, 1, 1, b, 25); TestUtils.AssertPattern("00000001 00011100 10110000 10001110 01000011", b); } } }
43.685039
97
0.578767
[ "Unlicense" ]
DMeville/BitTools
Src/BitTools.Tests/ReadingWritingTests.cs
5,550
C#
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace Tests.Migrations { public partial class Inital : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Products", columns: table => new { ProductId = table.Column<int>(nullable: false) .Annotation("MySql:ValueGeneratedOnAdd", true), Cost = table.Column<double>(nullable: false), Description = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Products", x => x.ProductId); }); migrationBuilder.CreateTable( name: "Reviews", columns: table => new { ReviewId = table.Column<int>(nullable: false) .Annotation("MySql:ValueGeneratedOnAdd", true), Author = table.Column<string>(nullable: true), Content = table.Column<string>(nullable: true), ProductId = table.Column<int>(nullable: false), Rating = table.Column<double>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Reviews", x => x.ReviewId); table.ForeignKey( name: "FK_Reviews_Products_ProductId", column: x => x.ProductId, principalTable: "Products", principalColumn: "ProductId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Reviews_ProductId", table: "Reviews", column: "ProductId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Reviews"); migrationBuilder.DropTable( name: "Products"); } } }
36.578125
71
0.492952
[ "Unlicense", "MIT" ]
eyesicedover/GummiBearKingdom
GummiBearKingdomTests/Migrations/20180502205425_Inital.cs
2,343
C#
using FluentValidation; namespace Application.Features.Commands.Create{ public class CreateUserCommandValidator : AbstractValidator<CreateUserCommand> { public CreateUserCommandValidator () { RuleFor (p => p.Name) .NotEmpty () .WithMessage ("{Name} is required.") .NotNull () .MaximumLength (30) .WithMessage ("{Name} must not exceed 30 characters."); RuleFor (p => p.Username) .NotEmpty () .WithMessage ("{Username} is required.") .NotNull (); RuleFor (p => p.Password) .NotEmpty () .WithMessage ("{Password} is required.") .NotNull (); RuleFor (p => p.Email) .NotEmpty () .WithMessage ("{Email} is required.") .EmailAddress () .WithMessage ("A valid {Email} is required"); } } }
36.777778
84
0.49144
[ "MIT" ]
omerozoglu/YazilimYapimiVizeProjesi
ProjectExchange.API/Services/User/Application/Features/Commands/Create/CreateUserCommandValidator.cs
993
C#
using System.Collections.Generic; using System.Globalization; using Ifak.Fast.Json.Utilities; namespace Ifak.Fast.Json.Linq.JsonPath { internal class ArrayIndexFilter : PathFilter { public int? Index { get; set; } public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, JsonSelectSettings? settings) { foreach (JToken t in current) { if (Index != null) { JToken? v = GetTokenIndex(t, settings, Index.GetValueOrDefault()); if (v != null) { yield return v; } } else { if (t is JArray || t is JConstructor) { foreach (JToken v in t) { yield return v; } } else { if (settings?.ErrorWhenNoMatch ?? false) { throw new JsonException("Index * not valid on {0}.".FormatWith(CultureInfo.InvariantCulture, t.GetType().Name)); } } } } } } }
31.090909
140
0.408626
[ "MIT" ]
ifakFAST/Mediator.Net
Mediator.Net/MediatorLib/Json/Linq/JsonPath/ArrayIndexFilter.cs
1,370
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Charlotte { public static class Utilities { public static int RotL(int direction) { return direction / 2 + ((direction / 2) % 2) * 5; } public static int RotR(int direction) { return direction * 2 - (direction / 6) * 10; } } }
16.52381
52
0.668588
[ "MIT" ]
stackprobe/Fairy
wb/t20191102_Dungeon/Dungeon/Dungeon/Utilities.cs
349
C#
using UnityEngine; using System.Collections; /// <summary> /// Controller to retrieve the player inputs /// and send them to the components that need them /// (e.g. : movement, attack, ...) /// </summary> public class PlayerController : MonoBehaviour { [SerializeField] private float joystick = 1; [SerializeField] private GameObject ship; private Movement moveComponent; void Start() { moveComponent = ship.GetComponent<Movement>(); } /// <summary> /// Retrieve the axis translation of the player, and send it to the Move component /// </summary> void Update () { float horizontalTranslation = Input.GetAxis("JoystickHorizontal" + joystick); float verticalTranslation = Input.GetAxis("JoystickVertical" + joystick); moveComponent.AddMovement(horizontalTranslation, verticalTranslation); } }
27.151515
90
0.670759
[ "MIT" ]
SneakyRedSnake/Ultra-Linking-Space-Race-Championship
UltraLinkingSpaceRaceChampionShip/Assets/Scripts/Controller/PlayerController.cs
898
C#
using FortnoxNET.Utils; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FortnoxNET.Models.Inbox { public class File { [JsonProperty(PropertyName = "@url")] public string Url { get; set; } public string Comments { get; set; } public string Id { get; set; } public string ArchiveId { get; set; } public string Name { get; set; } public string Path { get; set; } public string Size { get; set; } } }
18.83871
45
0.626712
[ "MIT" ]
PolrSE/fortnox.NET
Fortnox.NET/Models/Inbox/File.cs
586
C#
using System; using Android.Content; using Android.Graphics; using Android.Support.Annotation; using Android.Support.V4.Content.Res; using Android.Util; using Android.Widget; namespace FoldingTabBarAndroidForms { public class SelectedMenuItem : ImageView { internal Paint mCirclePaint; internal float radius; public SelectedMenuItem(Context context, Color colorRes) : this(context, null, colorRes) { } public SelectedMenuItem(Context context, IAttributeSet attrs, Color colorRes) : this(context, attrs, 0, colorRes) { } public SelectedMenuItem(Context context, IAttributeSet attrs, int defStyleRes, Color colorRes) : base(context, attrs, defStyleRes) { mCirclePaint = new Paint(PaintFlags.AntiAlias) { Color = colorRes }; } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); if (Activated) DrawCircleIcon(canvas); } void DrawCircleIcon(Canvas canvas) { canvas.DrawCircle(canvas.Width / 2.0f, canvas.Height - PaddingBottom / 1.5f, radius, mCirclePaint); if (radius <= canvas.Width / 20.0f) { radius++; Invalidate(); } } } }
24.866667
132
0.726542
[ "MIT" ]
NashZhou/EZAudioXamarinBinding
FoldingTabBar/Forms/FoldingTabBarAndroidForms/FoldingTabBarAndroidForms/Library/SelectedMenuItem.cs
1,121
C#
using Microsoft.AspNetCore.Mvc.RazorPages; using Oqtane.Infrastructure; using Oqtane.Shared; using Oqtane.Modules; using Oqtane.Models; using Oqtane.Themes; using System; using System.Globalization; using System.Linq; using System.Reflection; using Oqtane.Repository; using Microsoft.AspNetCore.Localization; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Antiforgery; namespace Oqtane.Pages { public class HostModel : PageModel { private IConfiguration _configuration; private readonly ITenantManager _tenantManager; private readonly ILocalizationManager _localizationManager; private readonly ILanguageRepository _languages; private readonly IAntiforgery _antiforgery; public HostModel(IConfiguration configuration, ITenantManager tenantManager, ILocalizationManager localizationManager, ILanguageRepository languages, IAntiforgery antiforgery) { _configuration = configuration; _tenantManager = tenantManager; _localizationManager = localizationManager; _languages = languages; _antiforgery = antiforgery; } public string AntiForgeryToken = ""; public string Runtime = "Server"; public RenderMode RenderMode = RenderMode.Server; public string HeadResources = ""; public string BodyResources = ""; public void OnGet() { AntiForgeryToken = _antiforgery.GetAndStoreTokens(HttpContext).RequestToken; if (_configuration.GetSection("Runtime").Exists()) { Runtime = _configuration.GetSection("Runtime").Value; } if (Runtime != "WebAssembly" && _configuration.GetSection("RenderMode").Exists()) { RenderMode = (RenderMode)Enum.Parse(typeof(RenderMode), _configuration.GetSection("RenderMode").Value, true); } var assemblies = AppDomain.CurrentDomain.GetOqtaneAssemblies(); foreach (Assembly assembly in assemblies) { ProcessHostResources(assembly); ProcessModuleControls(assembly); ProcessThemeControls(assembly); } // if framework is installed if (!string.IsNullOrEmpty(_configuration.GetConnectionString("DefaultConnection"))) { var alias = _tenantManager.GetAlias(); if (alias != null) { // if culture not specified if (HttpContext.Request.Cookies[CookieRequestCultureProvider.DefaultCookieName] == null) { // set default language for site if the culture is not supported var languages = _languages.GetLanguages(alias.SiteId); if (languages.Any() && languages.All(l => l.Code != CultureInfo.CurrentUICulture.Name)) { var defaultLanguage = languages.Where(l => l.IsDefault).SingleOrDefault() ?? languages.First(); SetLocalizationCookie(defaultLanguage.Code); } else { SetLocalizationCookie(_localizationManager.GetDefaultCulture()); } } } } } private void ProcessHostResources(Assembly assembly) { var types = assembly.GetTypes().Where(item => item.GetInterfaces().Contains(typeof(IHostResources))); foreach (var type in types) { var obj = Activator.CreateInstance(type) as IHostResources; foreach (var resource in obj.Resources) { ProcessResource(resource); } } } private void ProcessModuleControls(Assembly assembly) { var types = assembly.GetTypes().Where(item => item.GetInterfaces().Contains(typeof(IModuleControl))); foreach (var type in types) { // Check if type should be ignored if (type.IsOqtaneIgnore()) continue; var obj = Activator.CreateInstance(type) as IModuleControl; if (obj.Resources != null) { foreach (var resource in obj.Resources) { if (resource.Declaration == ResourceDeclaration.Global) { ProcessResource(resource); } } } } } private void ProcessThemeControls(Assembly assembly) { var types = assembly.GetTypes().Where(item => item.GetInterfaces().Contains(typeof(IThemeControl))); foreach (var type in types) { // Check if type should be ignored if (type.IsOqtaneIgnore()) continue; var obj = Activator.CreateInstance(type) as IThemeControl; if (obj.Resources != null) { foreach (var resource in obj.Resources) { if (resource.Declaration == ResourceDeclaration.Global) { ProcessResource(resource); } } } } } private void ProcessResource(Resource resource) { switch (resource.ResourceType) { case ResourceType.Stylesheet: if (!HeadResources.Contains(resource.Url, StringComparison.OrdinalIgnoreCase)) { HeadResources += "<link rel=\"stylesheet\" href=\"" + resource.Url + "\"" + CrossOrigin(resource.CrossOrigin) + Integrity(resource.Integrity) + " />" + Environment.NewLine; } break; case ResourceType.Script: if (resource.Location == Shared.ResourceLocation.Body) { if (!BodyResources.Contains(resource.Url, StringComparison.OrdinalIgnoreCase)) { BodyResources += "<script src=\"" + resource.Url + "\"" + CrossOrigin(resource.CrossOrigin) + Integrity(resource.Integrity) + "></script>" + Environment.NewLine; } } else { if (!HeadResources.Contains(resource.Url, StringComparison.OrdinalIgnoreCase)) { HeadResources += "<script src=\"" + resource.Url + "\"" + CrossOrigin(resource.CrossOrigin) + Integrity(resource.Integrity) + "></script>" + Environment.NewLine; } } break; } } private string CrossOrigin(string crossorigin) { if (!string.IsNullOrEmpty(crossorigin)) { return " crossorigin=\"" + crossorigin + "\""; } else { return ""; } } private string Integrity(string integrity) { if (!string.IsNullOrEmpty(integrity)) { return " integrity=\"" + integrity + "\""; } else { return ""; } } private void SetLocalizationCookie(string culture) { HttpContext.Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture))); } } }
38.742718
196
0.529758
[ "MIT" ]
MartyNZ/oqtane.framework
Oqtane.Server/Pages/_Host.cshtml.cs
7,981
C#
 // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Symbols { /// <summary> /// Interface implemented by internal components that are not symbols, but contain symbols that should /// respect a passed compare kind when comparing for equality. /// </summary> internal interface ISymbolCompareKindComparableInternal { /// <summary> /// Allows nested symbols to support comparisons that involve child type symbols /// </summary> /// <remarks> /// Because TypeSymbol equality can differ based on e.g. nullability, any symbols that contain TypeSymbols can also differ in the same way /// This call allows the component to accept a comparison kind that should be used when comparing its contained types /// </remarks> bool Equals(ISymbolCompareKindComparableInternal? other, TypeCompareKind compareKind); } }
44.68
146
0.717099
[ "MIT" ]
BrianFreemanAtlanta/roslyn
src/Compilers/Core/Portable/Symbols/ISymbolCompareKindComparableInternal.cs
1,119
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace codevalr { public class CodeEvalResult { public List<UnitTestResult> PublicUnitTestResults { get; set; } public List<UnitTestResult> PrivateUnitTestResults { get; set; } } }
20.714286
66
0.775862
[ "MIT" ]
anthrich/codevalr
src/codevalr/CodeEvalResult.cs
292
C#
/* * THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text.Json.Serialization; namespace Plotly.Blazor.Traces.FunnelLib { /// <summary> /// The Connector class. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")] [Serializable] public class Connector : IEquatable<Connector> { /// <summary> /// Sets the fill color. /// </summary> [JsonPropertyName(@"fillcolor")] public object FillColor { get; set;} /// <summary> /// Gets or sets the Line. /// </summary> [JsonPropertyName(@"line")] public Plotly.Blazor.Traces.FunnelLib.ConnectorLib.Line Line { get; set;} /// <summary> /// Determines if connector regions and lines are drawn. /// </summary> [JsonPropertyName(@"visible")] public bool? Visible { get; set;} /// <inheritdoc /> public override bool Equals(object obj) { if (!(obj is Connector other)) return false; return ReferenceEquals(this, obj) || Equals(other); } /// <inheritdoc /> public bool Equals([AllowNull] Connector other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; return ( FillColor == other.FillColor || FillColor != null && FillColor.Equals(other.FillColor) ) && ( Line == other.Line || Line != null && Line.Equals(other.Line) ) && ( Visible == other.Visible || Visible != null && Visible.Equals(other.Visible) ); } /// <inheritdoc /> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; if (FillColor != null) hashCode = hashCode * 59 + FillColor.GetHashCode(); if (Line != null) hashCode = hashCode * 59 + Line.GetHashCode(); if (Visible != null) hashCode = hashCode * 59 + Visible.GetHashCode(); return hashCode; } } /// <summary> /// Checks for equality of the left Connector and the right Connector. /// </summary> /// <param name="left">Left Connector.</param> /// <param name="right">Right Connector.</param> /// <returns>Boolean</returns> public static bool operator == (Connector left, Connector right) { return Equals(left, right); } /// <summary> /// Checks for inequality of the left Connector and the right Connector. /// </summary> /// <param name="left">Left Connector.</param> /// <param name="right">Right Connector.</param> /// <returns>Boolean</returns> public static bool operator != (Connector left, Connector right) { return !Equals(left, right); } /// <summary> /// Gets a deep copy of this instance. /// </summary> /// <returns>Connector</returns> public Connector DeepClone() { return this.Copy(); } } }
31.54386
90
0.510845
[ "MIT" ]
BenSzuszkiewicz/Plotly.Blazor
Plotly.Blazor/Traces/FunnelLib/Connector.cs
3,596
C#
version https://git-lfs.github.com/spec/v1 oid sha256:32b3da6190c5d3a02b2e3c5af7e2488a1f57b86267b885046c722602f45dc075 size 2381
32.25
75
0.883721
[ "MIT" ]
Vakuzar/Multithreaded-Blood-Sim
Blood/Library/PackageCache/com.unity.test-framework@1.1.14/UnityEditor.TestRunner/NUnitExtension/Attributes/AssetPipelineIgnore.cs
129
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// MedicalHospitalReportList Data Structure. /// </summary> [Serializable] public class MedicalHospitalReportList : AopObject { /// <summary> /// 报告产出日期 格式为yyyy-MM-dd HH:mm:ss。 /// </summary> [XmlElement("report_date")] public string ReportDate { get; set; } /// <summary> /// 报告说明 /// </summary> [XmlElement("report_desc")] public string ReportDesc { get; set; } /// <summary> /// 报告详情连接 /// </summary> [XmlElement("report_link")] public string ReportLink { get; set; } /// <summary> /// 报告名称 /// </summary> [XmlElement("report_name")] public string ReportName { get; set; } /// <summary> /// 报告类型: CHECK_REPORT 检查报告 EXAM_REPORT检验报告 /// </summary> [XmlElement("report_type")] public string ReportType { get; set; } } }
25.232558
55
0.511521
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/MedicalHospitalReportList.cs
1,157
C#
using PKISharp.WACS.DomainObjects; using PKISharp.WACS.Extensions; using PKISharp.WACS.Plugins.Interfaces; using PKISharp.WACS.Properties; using PKISharp.WACS.Services; using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace PKISharp.WACS.Plugins.StorePlugins { internal class CentralSsl : IStorePlugin { private ILogService _log; private readonly string _path; private readonly string _password; public CentralSsl(ILogService log, CentralSslOptions options) { _log = log; if (!string.IsNullOrWhiteSpace(options.PfxPassword?.Value)) { _password = options.PfxPassword.Value; } else { _password = Settings.Default.DefaultCentralSslPfxPassword; } if (!string.IsNullOrWhiteSpace(options.Path)) { _path = options.Path; } else { _path = Settings.Default.DefaultCentralSslStore; } if (_path.ValidPath(log)) { _log.Debug("Using Centralized SSL path: {_path}", _path); } else { throw new Exception($"Specified CentralSsl path {_path} is not valid."); } } public void Save(CertificateInfo input) { _log.Information("Copying certificate to the Central SSL store"); var source = input.CacheFile; IEnumerable<string> targets = input.HostNames; foreach (var identifier in targets) { var dest = Path.Combine(_path, $"{identifier.Replace("*", "_")}.pfx"); _log.Information("Saving certificate to Central SSL location {dest}", dest); try { File.WriteAllBytes(dest, input.Certificate.Export(X509ContentType.Pfx, _password)); } catch (Exception ex) { _log.Error(ex, "Error copying certificate to Central SSL store"); } } input.StoreInfo.Add(GetType(), new StoreInfo() { Name = CentralSslOptions.PluginName, Path = _path }); } public void Delete(CertificateInfo input) { _log.Information("Removing certificate from the Central SSL store"); var di = new DirectoryInfo(_path); foreach (var fi in di.GetFiles("*.pfx")) { var cert = LoadCertificate(fi); if (cert != null && string.Equals(cert.Thumbprint, input.Certificate.Thumbprint, StringComparison.InvariantCultureIgnoreCase)) { fi.Delete(); } } } /// <summary> /// Load certificate from disk /// </summary> /// <param name="fi"></param> /// <returns></returns> private X509Certificate2 LoadCertificate(FileInfo fi) { X509Certificate2 cert = null; try { cert = new X509Certificate2(fi.FullName, _password); } catch (CryptographicException) { try { cert = new X509Certificate2(fi.FullName, ""); } catch { _log.Warning("Unable to scan certificate {name}", fi.FullName); } } return cert; } } }
31.915254
142
0.513011
[ "Apache-2.0" ]
FuseCP-TRobinson/win-acme
src/main/Plugins/StorePlugins/CentralSsl/CentralSsl.cs
3,768
C#
using System.Collections.ObjectModel; namespace WebApplicationWebAPI1.Areas.HelpPage.ModelDescriptions { public class ComplexTypeModelDescription : ModelDescription { public ComplexTypeModelDescription() { Properties = new Collection<ParameterDescription>(); } public Collection<ParameterDescription> Properties { get; private set; } } }
28.214286
80
0.713924
[ "MIT" ]
scottkoland/web-api-areas
WebApplicationWebAPI1/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs
395
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("01.Staircases")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01.Staircases")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("824cde8e-ef5f-42f2-9a11-72161f434230")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.810811
84
0.744103
[ "MIT" ]
TsvetanRazsolkov/Telerik-Academy
Homeworks/Programming/DSA/16.Workshop-Graphs-DynamicProgramming-2015.11.20/01.Staircases/Properties/AssemblyInfo.cs
1,402
C#
using Abp.Localization; using Abp.Modules; using Abp.Reflection.Extensions; using Abp.Timing; using Abp.Zero; using Abp.Zero.Configuration; using AbpCompanyName.AbpProjectName.Authorization.Roles; using AbpCompanyName.AbpProjectName.Authorization.Users; using AbpCompanyName.AbpProjectName.Configuration; using AbpCompanyName.AbpProjectName.Localization; using AbpCompanyName.AbpProjectName.MultiTenancy; using AbpCompanyName.AbpProjectName.Timing; namespace AbpCompanyName.AbpProjectName { [DependsOn(typeof(AbpZeroCoreModule))] public class AbpProjectNameCoreModule : AbpModule { public override void PreInitialize() { Configuration.Auditing.IsEnabledForAnonymousUsers = true; // Declare entity types Configuration.Modules.Zero().EntityTypes.Tenant = typeof(Tenant); Configuration.Modules.Zero().EntityTypes.Role = typeof(Role); Configuration.Modules.Zero().EntityTypes.User = typeof(User); AbpProjectNameLocalizationConfigurer.Configure(Configuration.Localization); // Enable this line to create a multi-tenant application. Configuration.MultiTenancy.IsEnabled = AbpProjectNameConsts.MultiTenancyEnabled; // Configure roles AppRoleConfig.Configure(Configuration.Modules.Zero().RoleManagement); Configuration.Settings.Providers.Add<AppSettingProvider>(); Configuration.Localization.Languages.Add(new LanguageInfo("fa", "فارسی", "famfamfam-flags ir")); } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(AbpProjectNameCoreModule).GetAssembly()); } public override void PostInitialize() { IocManager.Resolve<AppTimes>().StartupTime = Clock.Now; } } }
35.826923
108
0.711755
[ "MIT" ]
ejohnson-dotnet/module-zero-core-template
aspnet-core/src/AbpCompanyName.AbpProjectName.Core/AbpProjectNameCoreModule.cs
1,870
C#
// ***************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // ***************************************************************** /**************************************************************************** * AlphabetsBvtTestCases.cs * * This file contains the Alphabets BVT test cases. * ******************************************************************************/ using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.IO; using MBF.Util.Logging; using MBF.TestAutomation.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using MBF.Encoding; namespace MBF.TestAutomation { /// <summary> /// Test Automation code for MBF Alphabets and BVT level validations. /// </summary> [TestClass] public class AlphabetsBvtTestCases { #region Constants const string AddInsFolder = "\\Add-ins"; const string MBFTestAutomationDll = "\\MBF.TestAutomation.dll"; #endregion Constants #region Global Variables Utility _utilityObj = new Utility(@"TestUtils\TestsConfig.xml"); #endregion Global Variables #region Constructor /// <summary> /// Static constructor to open log and make other settings needed for test /// </summary> static AlphabetsBvtTestCases() { Trace.Set(Trace.SeqWarnings); if (!ApplicationLog.Ready) { ApplicationLog.Open("mbf.automation.log"); } } #endregion Constructor #region DNA Alphabets Bvt TestCases /// <summary> /// Validate of Add() method for the Dna Alphabets. /// Input Data : Valid Dna Alphabet. /// Output Data : Validate if Read-only is enabled. /// </summary> /// Suppressing the Error "DoNotCatchGeneralExceptionTypes" because the exception is being thrown by DEV code [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"), TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateDnaAlphabetAdd() { // Gets the actual sequence and the alphabet from the Xml string alphabetName = _utilityObj._xmlUtil.GetTextValue(Constants.SimpleDnaAlphabetNode, Constants.AlphabetNameNode); string actualSequence = _utilityObj._xmlUtil.GetTextValue(Constants.SimpleDnaAlphabetNode, Constants.ExpectedSingleChar); ISequence seq = new Sequence(Utility.GetAlphabet(alphabetName), actualSequence); DnaAlphabet alp = DnaAlphabet.Instance; try { alp.Add(seq[0]); Assert.Fail(); } catch (Exception) { // Logs to the NUnit GUI window ApplicationLog.WriteLine("Alphabets BVT: Validation of Add() method completed successfully."); Console.WriteLine("Alphabets BVT: Validation of Add() method completed successfully."); } } /// <summary> /// Validate of Clear() method for the Dna Alphabets. /// Input Data : Valid Dna Alphabet. /// Output Data : Validate if Read-only is enabled. /// </summary> /// Suppressing the Error "DoNotCatchGeneralExceptionTypes" because the exception is being thrown by DEV code [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"), TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateDnaAlphabetClear() { DnaAlphabet alp = DnaAlphabet.Instance; try { alp.Clear(); Assert.Fail(); } catch (Exception) { // Logs to the NUnit GUI window ApplicationLog.WriteLine("Alphabets BVT: Validation of Clear() method completed successfully."); Console.WriteLine("Alphabets BVT: Validation of Clear() method completed successfully."); } } /// <summary> /// Validate of CopyTo() method for the Dna Alphabets. /// Input Data : Valid Dna Alphabet. /// Output Data : Validate if CopyTo is is validated as expected. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateDnaAlphabetCopyTo() { ISequence seq = new Sequence(Alphabets.DNA, "AAAAAAAAAAAAAAAA"); DnaAlphabet alp = DnaAlphabet.Instance; ISequenceItem[] item = seq.ToArray<ISequenceItem>(); alp.CopyTo(item, 0); Assert.AreEqual('A', item[0].Symbol); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of CopyTo() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of CopyTo() method completed successfully."); } /// <summary> /// Validate of GetBasicSymbols() method for the Dna Alphabets. /// Input Data : Valid Dna Alphabet. /// Output Data : Validate if GetBasicSymbols() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateDnaAlphabetGetBasicSymbols() { ISequence seq = new Sequence(Alphabets.DNA, "AGCTB"); DnaAlphabet alp = DnaAlphabet.Instance; ISequenceItem item = seq[4]; Assert.IsNotNull(alp.GetBasicSymbols(item)); item = seq[3]; Assert.IsNotNull(alp.GetBasicSymbols(item)); item = seq[3]; Assert.IsNotNull(alp.GetBasicSymbols(item)); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); } /// <summary> /// Validate of GetConsensusSymbol() method for the Protein Alphabets. /// Input Data : Valid Protein Alphabet. /// Output Data : Validate if GetConsensusSymbol() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateDnaAlphabetGetConsensusSymbol() { ISequence seq = new Sequence(Alphabets.DNA, "ATGCA"); DnaAlphabet alp = DnaAlphabet.Instance; HashSet<ISequenceItem> hashSet = new HashSet<ISequenceItem>(); foreach (ISequenceItem item in seq) { hashSet.Add(item); } Assert.IsNotNull(alp.GetConsensusSymbol(hashSet)); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); } /// <summary> /// Validate of LookupBySymbol() method for the Dna Alphabets. /// Input Data : Valid Dna Alphabet. /// Output Data : Validate if LookupBySymbol() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateDnaAlphabetLookupBySymbol() { DnaAlphabet alp = DnaAlphabet.Instance; ISequenceItem itm = alp.LookupBySymbol("A"); Assert.AreEqual('A', itm.Symbol); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of LookupBySymbol() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of LookupBySymbol() method completed successfully."); } /// <summary> /// Validate of LookupAll() method for the Dna Alphabets. /// Input Data : Valid Dna Alphabet. /// Output Data : Validate if LookupAll() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateDnaAlphabetLookupAll() { DnaAlphabet alp = DnaAlphabet.Instance; List<ISequenceItem> itm = alp.LookupAll(true, true, true, true); Assert.AreEqual(16, itm.Count); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of LookupAll() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of LookupAll() method completed successfully."); } /// <summary> /// Validate of all properties for the Dna Alphabets. /// Input Data : Valid Dna Alphabet. /// Output Data : Validate if all properties is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateDnaAlphabetAllProperties() { DnaAlphabet alp = DnaAlphabet.Instance; Assert.AreEqual(16, alp.Count); Assert.AreEqual('-', alp.DefaultGap.Symbol); Assert.IsTrue(alp.HasAmbiguity); Assert.IsTrue(alp.HasGaps); Assert.IsFalse(alp.HasTerminations); Assert.IsTrue(alp.IsReadOnly); Assert.AreEqual("DNA", alp.Name); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of All properties completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of All properties method completed successfully."); } /// <summary> /// Validate of Alphabet() static constructor. /// Input Data : Valid Dna Alphabet. /// Output Data : Validate Sequences. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void AlphabetStaticCtorValidate() { CreateAddinsFolder(); Sequence seq = new Sequence(Alphabets.DNA, Encodings.Ncbi2NA, "ATAGC"); Assert.AreEqual(seq.Count, 5); Assert.AreEqual(seq.ToString(), "ATAGC"); ApplicationLog.WriteLine( "Alphabets BVT: Validation of Static Constructor completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of Static Constructor method completed successfully."); DeleteAddinsFolder(); } #endregion DNA Alphabets Bvt TestCases #region Protein Alphabets Bvt TestCases /// <summary> /// Validate of Add() method for the Protein Alphabets. /// Input Data : Valid Protein Alphabet. /// Output Data : Validate if Read-only is enabled. /// </summary> /// Suppressing the Error "DoNotCatchGeneralExceptionTypes" because the exception is being thrown by DEV code [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"), TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateProteinAlphabetAdd() { // Gets the actual sequence and the alphabet from the Xml string alphabetName = _utilityObj._xmlUtil.GetTextValue( Constants.SimpleProteinAlphabetNode, Constants.AlphabetNameNode); string actualSequence = _utilityObj._xmlUtil.GetTextValue( Constants.SimpleProteinAlphabetNode, Constants.ExpectedSingleChar); ISequence seq = new Sequence(Utility.GetAlphabet(alphabetName), actualSequence); ProteinAlphabet alp = ProteinAlphabet.Instance; try { alp.Add(seq[0]); Assert.Fail(); } catch (Exception) { // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of Add() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of Add() method completed successfully."); } } /// <summary> /// Validate of Clear() method for the Protein Alphabets. /// Input Data : Valid Protein Alphabet. /// Output Data : Validate if Read-only is enabled. /// </summary> /// Suppressing the Error "DoNotCatchGeneralExceptionTypes" because the exception is being thrown by DEV code [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"), TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateProteinAlphabetClear() { ProteinAlphabet alp = ProteinAlphabet.Instance; try { alp.Clear(); Assert.Fail(); } catch (Exception) { // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of Clear() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of Clear() method completed successfully."); } } /// <summary> /// Validate of CopyTo() method for the Protein Alphabets. /// Input Data : Valid Protein Alphabet. /// Output Data : Validate if CopyTo is is validated as expected. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateProteinAlphabetCopyTo() { ISequence seq = new Sequence(Alphabets.Protein, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); ProteinAlphabet alp = ProteinAlphabet.Instance; ISequenceItem[] item = seq.ToArray<ISequenceItem>(); alp.CopyTo(item, 0); Assert.AreEqual('A', item[0].Symbol); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of CopyTo() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of CopyTo() method completed successfully."); } /// <summary> /// Validate of GetBasicSymbols() method for the Protein Alphabets. /// Input Data : Valid Protein Alphabet. /// Output Data : Validate if GetBasicSymbols() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateProteinAlphabetGetBasicSymbols() { ISequence seq = new Sequence(Alphabets.Protein, "AGCTX"); ProteinAlphabet alp = ProteinAlphabet.Instance; ISequenceItem item = seq[4]; Assert.IsNotNull(alp.GetBasicSymbols(item)); item = seq[3]; Assert.IsNotNull(alp.GetBasicSymbols(item)); item = seq[3]; Assert.IsNotNull(alp.GetBasicSymbols(item)); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); } /// <summary> /// Validate of GetConsensusSymbol() method for the Protein Alphabets. /// Input Data : Valid Protein Alphabet. /// Output Data : Validate if GetConsensusSymbol() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateProteinAlphabetGetConsensusSymbol() { ISequence seq = new Sequence(Alphabets.Protein, "AGCTA"); ProteinAlphabet alp = ProteinAlphabet.Instance; HashSet<ISequenceItem> hashSet = new HashSet<ISequenceItem>(); foreach (ISequenceItem item in seq) { hashSet.Add(item); } Assert.IsNotNull(alp.GetConsensusSymbol(hashSet)); seq = new Sequence(Alphabets.Protein, "AGCTX"); hashSet = new HashSet<ISequenceItem>(); foreach (ISequenceItem item in seq) { hashSet.Add(item); } Assert.IsNotNull(alp.GetConsensusSymbol(hashSet)); seq = new Sequence(Alphabets.Protein, "-"); hashSet = new HashSet<ISequenceItem>(); foreach (ISequenceItem item in seq) { hashSet.Add(item); } Assert.IsNotNull(alp.GetConsensusSymbol(hashSet)); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); } /// <summary> /// Validate of LookupBySymbol() method for the Protein Alphabets. /// Input Data : Valid Protein Alphabet. /// Output Data : Validate if LookupBySymbol() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateProteinAlphabetLookupBySymbol() { ProteinAlphabet alp = ProteinAlphabet.Instance; ISequenceItem itm = alp.LookupBySymbol("A"); Assert.AreEqual('A', itm.Symbol); itm = alp.LookupBySymbol("Ala"); Assert.AreEqual('A', itm.Symbol); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of LookupBySymbol() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of LookupBySymbol() method completed successfully."); } /// <summary> /// Validate of LookupAll() method for the Protein Alphabets. /// Input Data : Valid Protein Alphabet. /// Output Data : Validate if LookupAll() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateProteinAlphabetLookupAll() { ProteinAlphabet alp = ProteinAlphabet.Instance; List<ISequenceItem> itm = alp.LookupAll(true, true, true, true); Assert.AreEqual(28, itm.Count); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of LookupAll() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of LookupAll() method completed successfully."); } /// <summary> /// Validate of all properties for the Protein Alphabets. /// Input Data : Valid Protein Alphabet. /// Output Data : Validate if all properties is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateProteinAlphabetAllProperties() { ProteinAlphabet alp = ProteinAlphabet.Instance; Assert.AreEqual(28, alp.Count); Assert.AreEqual('-', alp.DefaultGap.Symbol); Assert.IsTrue(alp.HasAmbiguity); Assert.IsTrue(alp.HasGaps); Assert.IsTrue(alp.HasTerminations); Assert.IsTrue(alp.IsReadOnly); Assert.AreEqual("Protein", alp.Name); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of All properties completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of All properties method completed successfully."); } #endregion Protein Alphabets Bvt TestCases #region Rna Alphabets Bvt TestCases /// <summary> /// Validate of Add() method for the Rna Alphabets. /// Input Data : Valid Rna Alphabet. /// Output Data : Validate if Read-only is enabled. /// </summary> /// Suppressing the Error "DoNotCatchGeneralExceptionTypes" because the exception is being thrown by DEV code [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"), TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRnaAlphabetAdd() { // Gets the actual sequence and the alphabet from the Xml string alphabetName = _utilityObj._xmlUtil.GetTextValue( Constants.SimpleRnaAlphabetNode, Constants.AlphabetNameNode); string actualSequence = _utilityObj._xmlUtil.GetTextValue( Constants.SimpleRnaAlphabetNode, Constants.ExpectedSingleChar); ISequence seq = new Sequence(Utility.GetAlphabet(alphabetName), actualSequence); RnaAlphabet alp = RnaAlphabet.Instance; try { alp.Add(seq[0]); Assert.Fail(); } catch (Exception) { // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of Add() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of Add() method completed successfully."); } } /// <summary> /// Validate of Clear() method for the Rna Alphabets. /// Input Data : Valid Rna Alphabet. /// Output Data : Validate if Read-only is enabled. /// </summary> /// Suppressing the Error "DoNotCatchGeneralExceptionTypes" because the exception is being thrown by DEV code [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"), TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRnaAlphabetClear() { RnaAlphabet alp = RnaAlphabet.Instance; try { alp.Clear(); Assert.Fail(); } catch (Exception) { // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of Clear() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of Clear() method completed successfully."); } } /// <summary> /// Validate of CopyTo() method for the Rna Alphabets. /// Input Data : Valid Rna Alphabet. /// Output Data : Validate if CopyTo is is validated as expected. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRnaAlphabetCopyTo() { ISequence seq = new Sequence(Alphabets.RNA, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); RnaAlphabet alp = RnaAlphabet.Instance; ISequenceItem[] item = seq.ToArray<ISequenceItem>(); alp.CopyTo(item, 0); Assert.AreEqual('A', item[0].Symbol); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of CopyTo() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of CopyTo() method completed successfully."); } /// <summary> /// Validate of GetBasicSymbols() method for the Rna Alphabets. /// Input Data : Valid Rna Alphabet. /// Output Data : Validate if GetBasicSymbols() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRnaAlphabetGetBasicSymbols() { ISequence seq = new Sequence(Alphabets.RNA, "AGCUB"); RnaAlphabet alp = RnaAlphabet.Instance; ISequenceItem item = seq[4]; Assert.IsNotNull(alp.GetBasicSymbols(item)); item = seq[3]; Assert.IsNotNull(alp.GetBasicSymbols(item)); item = seq[3]; Assert.IsNotNull(alp.GetBasicSymbols(item)); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); } /// <summary> /// Validate of LookupBySymbol() method for the Rna Alphabets. /// Input Data : Valid Rna Alphabet. /// Output Data : Validate if LookupBySymbol() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRnaAlphabetLookupBySymbol() { RnaAlphabet alp = RnaAlphabet.Instance; ISequenceItem itm = alp.LookupBySymbol("A"); Assert.AreEqual('A', itm.Symbol); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of LookupBySymbol() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of LookupBySymbol() method completed successfully."); } /// <summary> /// Validate of LookupAll() method for the Rna Alphabets. /// Input Data : Valid Rna Alphabet. /// Output Data : Validate if LookupAll() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRnaAlphabetLookupAll() { RnaAlphabet alp = RnaAlphabet.Instance; List<ISequenceItem> itm = alp.LookupAll(true, true, true, true); Assert.AreEqual(16, itm.Count); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of LookupAll() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of LookupAll() method completed successfully."); } /// <summary> /// Validate of all properties for the Rna Alphabets. /// Input Data : Valid Rna Alphabet. /// Output Data : Validate if all properties is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRnaAlphabetAllProperties() { RnaAlphabet alp = RnaAlphabet.Instance; Assert.AreEqual(16, alp.Count); Assert.AreEqual('-', alp.DefaultGap.Symbol); Assert.IsTrue(alp.HasAmbiguity); Assert.IsTrue(alp.HasGaps); Assert.IsFalse(alp.HasTerminations); Assert.IsTrue(alp.IsReadOnly); Assert.AreEqual("RNA", alp.Name); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of All properties completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of All properties method completed successfully."); } /// <summary> /// Validate of GetConsensusSymbol() method for the Protein Alphabets. /// Input Data : Valid Protein Alphabet. /// Output Data : Validate if GetConsensusSymbol() method is returning valid value. /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRnaAlphabetGetConsensusSymbol() { ISequence seq = new Sequence(Alphabets.RNA, "CGUGA"); RnaAlphabet alp = RnaAlphabet.Instance; HashSet<ISequenceItem> hashSet = new HashSet<ISequenceItem>(); foreach (ISequenceItem item in seq) { hashSet.Add(item); } Assert.IsNotNull(alp.GetConsensusSymbol(hashSet)); // Logs to the NUnit GUI window ApplicationLog.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); Console.WriteLine( "Alphabets BVT: Validation of GetBasicSymbols() method completed successfully."); } #endregion Rna Alphabets Bvt TestCases #region Helper Method /// <summary> /// Creates the Add-ins folder /// </summary> private static void CreateAddinsFolder() { // Gets the Add-ins folder name Uri uri = new Uri(Assembly.GetCallingAssembly().CodeBase); string addInsFolderPath = Uri.UnescapeDataString(string.Concat( Path.GetDirectoryName(uri.AbsolutePath), AddInsFolder)); if (!Directory.Exists(addInsFolderPath)) // Creates the Add-ins folder Directory.CreateDirectory(addInsFolderPath); // Copies the MBF.TestAutomation.dll to Add-ins folder File.Copy(Uri.UnescapeDataString(uri.AbsolutePath), string.Concat(addInsFolderPath, MBFTestAutomationDll), false); } /// <summary> /// Deletes the Add-ins folder if exists /// </summary> private static void DeleteAddinsFolder() { Uri uri = new Uri(Assembly.GetCallingAssembly().CodeBase); string addInsFolderPath = string.Concat( Path.GetDirectoryName(uri.AbsolutePath), AddInsFolder); // If the Add-ins folder exists delete the same if (Directory.Exists(addInsFolderPath)) Directory.Delete(addInsFolderPath, true); } #endregion Helper Method } }
38.972466
131
0.585407
[ "Apache-2.0" ]
jdm7dv/Microsoft-Biology-Foundation
archive/Changesets/beta/Tests/MBF.TestAutomation/AlphabetsBvtTestCases.cs
31,141
C#
/// <summary> /// Origin: http://formats.kaitai.io/tr_dos_image/ /// Done some aesthetic updates. /// </summary> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kaitai { public partial class PositionAndLengthCode : KaitaiStruct { public static PositionAndLengthCode FromFile(string fileName) { return new PositionAndLengthCode(new KaitaiStream(fileName)); } public PositionAndLengthCode(KaitaiStream p__io, File p__parent = null, TrDosImage p__root = null) : base(p__io) { Parent = p__parent; Root = p__root; Read(); } private void Read() { StartAddress = m_io.ReadU2le(); Length = m_io.ReadU2le(); } /// <summary> /// Default memory address to load this byte array into /// </summary> public ushort StartAddress { get; private set; } public ushort Length { get; private set; } public TrDosImage Root { get; } public File Parent { get; } } }
26.511628
120
0.604386
[ "MIT" ]
mikkleini/trdos-extract
TRDOS-Extract/Kaitai/PositionAndLengthCode.cs
1,142
C#
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace NSSDB.Resources { public class Status { [Required][DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ID { get; set; } [Required] public string Name { get; set; } public string Description { get; set; } } }
24.052632
71
0.684902
[ "CC0-1.0", "MIT" ]
USGS-WiM/NSSServices
NSSDB/Resources/Status.cs
459
C#
using System; using Newtonsoft.Json; namespace TdLib { /// <summary> /// Autogenerated TDLib APIs /// </summary> public partial class TdApi { /// <summary> /// An audio message /// </summary> public partial class PushMessageContent : Object { /// <summary> /// An audio message /// </summary> public class PushMessageContentAudio : PushMessageContent { /// <summary> /// Data type for serialization /// </summary> [JsonProperty("@type")] public override string DataType { get; set; } = "pushMessageContentAudio"; /// <summary> /// Extra data attached to the message /// </summary> [JsonProperty("@extra")] public override string Extra { get; set; } /// <summary> /// Message content; may be null /// </summary> [JsonConverter(typeof(Converter))] [JsonProperty("audio")] public Audio Audio { get; set; } /// <summary> /// True, if the message is a pinned message with the specified content /// </summary> [JsonConverter(typeof(Converter))] [JsonProperty("is_pinned")] public bool IsPinned { get; set; } } } } }
30.857143
90
0.463624
[ "MIT" ]
mostafa8026/tdsharp
TDLib.Api/Objects/PushMessageContentAudio.cs
1,512
C#
using System; using System.Linq; using Data; using Enums; using UnityEngine; using UnityEngine.UI; using Random = UnityEngine.Random; namespace Game.Pages.GameEvent { /// <summary> /// Страница игрового события, описывающая ситуацию /// </summary> public class EventMainPage: Page { [Header("Поля")] [SerializeField] private Text nameText; [SerializeField] private Text descriptionText; [Header("Кнопки выбора решения")] [SerializeField] private Button peacefullyButton; [SerializeField] private Button aggressivelyButton; [SerializeField] private Button neutralButton; [SerializeField] private Button randomButton; [Header("Страница результат выбора")] [SerializeField] private EventDecisionPage eventDecisionPage; private GameEventInfo _eventInfo; private void Start() { peacefullyButton.onClick.AddListener(() => Decide(GameEventDecisionType.Peacefully)); aggressivelyButton.onClick.AddListener(() => Decide(GameEventDecisionType.Aggressively)); neutralButton.onClick.AddListener(() => Decide(GameEventDecisionType.Neutral)); randomButton.onClick.AddListener(DecideRandom); } /// <summary> /// Функция показа страницы игрового события /// </summary> public void Show(GameEventInfo eventInfo) { _eventInfo = eventInfo; Open(); } /// <summary> /// Выбирает решение определенного типа и отображает его на странице "eventDecisionPage" /// </summary> private void Decide(GameEventDecisionType type) { var decisionResult = _eventInfo.DecisionResults.FirstOrDefault(e => e.DecisionType == type); if (decisionResult != null) eventDecisionPage.Show(_eventInfo.Name, decisionResult); else Debug.LogError($"Не найден результат случайного события для решения типа {type}!"); Close(); } /// <summary> /// Выбирает случайное решение /// </summary> private void DecideRandom() { var decisionTypes = (GameEventDecisionType[]) Enum.GetValues(typeof(GameEventDecisionType)); Decide(decisionTypes[Random.Range(0, decisionTypes.Length)]); } protected override void BeforePageOpen() { nameText.text = GetLocale(_eventInfo.Name); descriptionText.text = GetLocale(_eventInfo.Description); } protected override void AfterPageClose() { nameText.text = string.Empty; descriptionText.text = string.Empty; _eventInfo = null; } } }
33.404762
104
0.6201
[ "Unlicense" ]
Mispon/rap-way
Assets/Scripts/Game/Pages/GameEvent/EventMainPage.cs
3,058
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection; using ScriptCs.Contracts; namespace ScriptCs { public class ScriptExecutor : IScriptExecutor { private readonly ILog _log; public static readonly string[] DefaultReferences = { "System", "System.Core", "System.Data", "System.Data.DataSetExtensions", "System.Xml", "System.Xml.Linq", "System.Net.Http", "Microsoft.CSharp", typeof(ScriptExecutor).Assembly.Location, typeof(IScriptEnvironment).Assembly.Location }; public static readonly string[] DefaultNamespaces = { "System", "System.Collections.Generic", "System.Linq", "System.Text", "System.Threading.Tasks", "System.IO", "System.Net.Http", "System.Dynamic" }; private const string ScriptLibrariesInjected = "ScriptLibrariesInjected"; public IFileSystem FileSystem { get; private set; } public IFilePreProcessor FilePreProcessor { get; private set; } public IScriptEngine ScriptEngine { get; private set; } public AssemblyReferences References { get; private set; } public IReadOnlyCollection<string> Namespaces { get; private set; } public ScriptPackSession ScriptPackSession { get; protected set; } public IScriptLibraryComposer ScriptLibraryComposer { get; protected set; } public IScriptInfo ScriptInfo { get; protected set; } public ScriptExecutor( IFileSystem fileSystem, IFilePreProcessor filePreProcessor, IScriptEngine scriptEngine, ILogProvider logProvider, IScriptInfo scriptInfo) : this(fileSystem, filePreProcessor, scriptEngine, logProvider, new NullScriptLibraryComposer(), scriptInfo) { } public ScriptExecutor( IFileSystem fileSystem, IFilePreProcessor filePreProcessor, IScriptEngine scriptEngine, ILogProvider logProvider, IScriptLibraryComposer composer, IScriptInfo scriptInfo) { Guard.AgainstNullArgument("fileSystem", fileSystem); Guard.AgainstNullArgumentProperty("fileSystem", "BinFolder", fileSystem.BinFolder); Guard.AgainstNullArgumentProperty("fileSystem", "DllCacheFolder", fileSystem.DllCacheFolder); Guard.AgainstNullArgument("filePreProcessor", filePreProcessor); Guard.AgainstNullArgument("scriptEngine", scriptEngine); Guard.AgainstNullArgument("logProvider", logProvider); Guard.AgainstNullArgument("composer", composer); Guard.AgainstNullArgument("scriptInfo", scriptInfo); References = new AssemblyReferences(new[] { GetAssemblyFromName("System.Runtime") }, DefaultReferences); Namespaces = new ReadOnlyCollection<string>(DefaultNamespaces); FileSystem = fileSystem; FilePreProcessor = filePreProcessor; ScriptEngine = scriptEngine; _log = logProvider.ForCurrentType(); ScriptLibraryComposer = composer; ScriptInfo = scriptInfo; } public virtual void ImportNamespaces(params string[] namespaces) { Guard.AgainstNullArgument("namespaces", namespaces); Namespaces = new ReadOnlyCollection<string>(Namespaces.Union(namespaces).ToArray()); } public virtual void RemoveNamespaces(params string[] namespaces) { Guard.AgainstNullArgument("namespaces", namespaces); Namespaces = new ReadOnlyCollection<string>(Namespaces.Except(namespaces).ToArray()); } public virtual void AddReferences(params Assembly[] assemblies) { Guard.AgainstNullArgument("assemblies", assemblies); References = References.Union(assemblies); } public virtual void RemoveReferences(params Assembly[] assemblies) { Guard.AgainstNullArgument("assemblies", assemblies); References = References.Except(assemblies); } public virtual void AddReferences(params string[] paths) { Guard.AgainstNullArgument("paths", paths); References = References.Union(paths); } public virtual void RemoveReferences(params string[] paths) { Guard.AgainstNullArgument("paths", paths); References = References.Except(paths); } public virtual void Initialize( IEnumerable<string> paths, IEnumerable<IScriptPack> scriptPacks, params string[] scriptArgs) { AddReferences(paths.ToArray()); var bin = Path.Combine(FileSystem.CurrentDirectory, FileSystem.BinFolder); var cache = Path.Combine(FileSystem.CurrentDirectory, FileSystem.DllCacheFolder); ScriptEngine.BaseDirectory = bin; ScriptEngine.CacheDirectory = cache; _log.Debug("Initializing script packs"); var scriptPackSession = new ScriptPackSession(scriptPacks, scriptArgs); ScriptPackSession = scriptPackSession; scriptPackSession.InitializePacks(); } public virtual void Reset() { References = new AssemblyReferences(DefaultReferences); Namespaces = new ReadOnlyCollection<string>(DefaultNamespaces); ScriptPackSession.State.Clear(); } public virtual void Terminate() { _log.Debug("Terminating packs"); ScriptPackSession.TerminatePacks(); } public virtual ScriptResult Execute(string script, params string[] scriptArgs) { var path = Path.IsPathRooted(script) ? script : Path.Combine(FileSystem.CurrentDirectory, script); var result = FilePreProcessor.ProcessFile(path); ScriptEngine.FileName = Path.GetFileName(path); ScriptInfo.ScriptPath = Path.GetFullPath(path); return EngineExecute(Path.GetDirectoryName(path), scriptArgs, result); } public virtual ScriptResult ExecuteScript(string script, params string[] scriptArgs) { var result = FilePreProcessor.ProcessScript(script); return EngineExecute(FileSystem.CurrentDirectory, scriptArgs, result); } protected internal virtual ScriptResult EngineExecute( string workingDirectory, string[] scriptArgs, FilePreProcessorResult result ) { InjectScriptLibraries(workingDirectory, result, ScriptPackSession.State); var namespaces = Namespaces.Union(result.Namespaces); var references = References.Union(result.References); ScriptInfo.ScriptPath = result.ScriptPath; foreach (var loadedScript in result.LoadedScripts) { ScriptInfo.LoadedScripts.Add(loadedScript); } _log.Debug("Starting execution in engine"); return ScriptEngine.Execute(result.Code, scriptArgs, references, namespaces, ScriptPackSession); } protected internal virtual void InjectScriptLibraries( string workingDirectory, FilePreProcessorResult result, IDictionary<string, object> state ) { Guard.AgainstNullArgument("result", result); Guard.AgainstNullArgument("state", state); if (state.ContainsKey(ScriptLibrariesInjected)) { return; } var scriptLibrariesPreProcessorResult = LoadScriptLibraries(workingDirectory); // script libraries should be injected just before the #line directive // if there is no #line directive, they can be injected at the beginning of code if (result.Code == null) result.Code = string.Empty; var safeInsertIndex = result.Code.IndexOf("#line"); if (safeInsertIndex < 0) safeInsertIndex = 0; if (scriptLibrariesPreProcessorResult != null) { result.Code = result.Code.Insert(safeInsertIndex, scriptLibrariesPreProcessorResult.Code + Environment.NewLine + "Env.Initialize();" + Environment.NewLine); result.References.AddRange(scriptLibrariesPreProcessorResult.References); result.Namespaces.AddRange(scriptLibrariesPreProcessorResult.Namespaces); } else { result.Code = result.Code.Insert(safeInsertIndex, "Env.Initialize();" + Environment.NewLine); } state.Add(ScriptLibrariesInjected, null); } protected internal virtual FilePreProcessorResult LoadScriptLibraries(string workingDirectory) { if (string.IsNullOrWhiteSpace(ScriptLibraryComposer.ScriptLibrariesFile)) { return null; } var scriptLibrariesPath = Path.Combine(workingDirectory, FileSystem.PackagesFolder, ScriptLibraryComposer.ScriptLibrariesFile); if (FileSystem.FileExists(scriptLibrariesPath)) { _log.DebugFormat("Found Script Library at {0}", scriptLibrariesPath); return FilePreProcessor.ProcessFile(scriptLibrariesPath); } return null; } private static Assembly GetAssemblyFromName(string assemblyName) { try { return Assembly.Load(new AssemblyName(assemblyName)); } catch { return null; } } } }
37.666667
149
0.62681
[ "Apache-2.0" ]
BlackFrog1/scriptcs
src/ScriptCs.Core/ScriptExecutor.cs
9,946
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// This data type is used as a response element to <code>DownloadDBLogFilePortion</code>. /// </summary> public partial class DownloadDBLogFilePortionResponse : AmazonWebServiceResponse { private bool? _additionalDataPending; private string _logFileData; private string _marker; /// <summary> /// Gets and sets the property AdditionalDataPending. /// <para> /// Boolean value that if true, indicates there is more data to be downloaded. /// </para> /// </summary> public bool AdditionalDataPending { get { return this._additionalDataPending.GetValueOrDefault(); } set { this._additionalDataPending = value; } } // Check to see if AdditionalDataPending property is set internal bool IsSetAdditionalDataPending() { return this._additionalDataPending.HasValue; } /// <summary> /// Gets and sets the property LogFileData. /// <para> /// Entries from the specified log file. /// </para> /// </summary> public string LogFileData { get { return this._logFileData; } set { this._logFileData = value; } } // Check to see if LogFileData property is set internal bool IsSetLogFileData() { return this._logFileData != null; } /// <summary> /// Gets and sets the property Marker. /// <para> /// A pagination token that can be used in a later DownloadDBLogFilePortion request. /// </para> /// </summary> public string Marker { get { return this._marker; } set { this._marker = value; } } // Check to see if Marker property is set internal bool IsSetMarker() { return this._marker != null; } } }
30.421053
101
0.616609
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/DownloadDBLogFilePortionResponse.cs
2,890
C#
// ============================================================================================================== // Microsoft patterns & practices // CQRS Journey project // ============================================================================================================== // Copyright (c) Microsoft Corporation and contributors http://cqrsjourney.github.com/contributors/members // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. // ============================================================================================================== namespace Registration.Handlers { using System.Threading; using System.Threading.Tasks; using Common; using Registration.Commands; /// <summary> /// Handles delayed commands in-memory, sending them to the bus /// after waiting for the specified time. /// </summary> /// <devdoc> /// This will be replaced with an AzureDelayCommandHandler that will /// leverage azure service bus capabilities for sending delayed messages. /// </devdoc> public class MemoryDelayCommandHandler : ICommandHandler<DelayCommand> { private ICommandBus commandBus; public MemoryDelayCommandHandler(ICommandBus commandBus) { this.commandBus = commandBus; } public void Handle(DelayCommand command) { Task.Factory.StartNew(() => { Thread.Sleep(command.SendDelay); this.commandBus.Send(command); }); } } }
44.06383
115
0.556736
[ "Apache-2.0" ]
craiggwilson/cqrs-journey-code
source/Conference/Registration/Handlers/MemoryDelayCommandHandler.cs
2,073
C#
/* * Copyright 2015-2017 Mohawk College of Applied Arts and Technology * * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * User: justi * Date: 2017-3-20 */ using OpenIZ.Core.Model.Acts; using OpenIZ.OrmLite; using OpenIZ.Persistence.Data.ADO.Data.Model.Acts; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Principal; using OpenIZ.Persistence.Data.ADO.Data; namespace OpenIZ.Persistence.Data.ADO.Services.Persistence { /// <summary> /// Protocol service /// </summary> public class ProtocolPersistenceService : BaseDataPersistenceService<Protocol, DbProtocol, CompositeResult<DbProtocol, DbProtocolHandler>> { /// <summary> /// Convert to model instance /// </summary> public override Protocol ToModelInstance(object dataInstance, DataContext context, IPrincipal principal) { if(dataInstance == null) return null; var dbProtoInstance = (dataInstance as CompositeResult<DbProtocol, DbProtocolHandler>)?.Values.OfType<DbProtocol>().FirstOrDefault() ?? dataInstance as DbProtocol; var dbHandlerInstance = (dataInstance as CompositeResult<DbProtocol, DbProtocolHandler>)?.Values.OfType<DbProtocolHandler>().FirstOrDefault() ?? context.FirstOrDefault<DbProtocolHandler>(o => o.Key == dbProtoInstance.HandlerKey); // Protocol return new Protocol() { Key = dbProtoInstance.Key, CreatedByKey = dbProtoInstance.CreatedByKey, CreationTime = dbProtoInstance.CreationTime, Definition = dbProtoInstance.Definition, HandlerClassName = dbHandlerInstance.TypeName, Name = dbProtoInstance.Name, ObsoletedByKey = dbProtoInstance.ObsoletedByKey, ObsoletionTime = dbProtoInstance.ObsoletionTime, Oid = dbProtoInstance.Oid }; } /// <summary> /// Convert from model instance /// </summary> public override object FromModelInstance(Protocol modelInstance, DataContext context, IPrincipal princpal) { var existingHandler = context.FirstOrDefault<DbProtocolHandler>(o => o.TypeName == modelInstance.HandlerClassName); if(existingHandler == null) { existingHandler = new DbProtocolHandler() { Key = Guid.NewGuid(), CreatedByKey = modelInstance.CreatedByKey ?? princpal.GetUserKey(context).Value, CreationTime = DateTime.Now, IsActive = true, Name = modelInstance.HandlerClass.Name, TypeName = modelInstance.HandlerClassName }; context.Insert(existingHandler); } // DbProtocol return new DbProtocol() { Key = modelInstance.Key ?? Guid.NewGuid(), CreatedByKey = modelInstance.CreatedByKey ?? princpal.GetUserKey(context).Value, CreationTime = modelInstance.CreationTime, Name = modelInstance.Name, ObsoletedByKey = modelInstance.ObsoletedByKey, ObsoletionTime = modelInstance.ObsoletionTime, Oid = modelInstance.Oid, HandlerKey = existingHandler.Key }; } } }
40.484848
241
0.636976
[ "Apache-2.0" ]
MohawkMEDIC/openiz
OpenIZ.Persistence.Data.ADO/Services/Persistence/ProtocolPersistenceService.cs
4,010
C#
using System; using System.Collections; using System.Text.RegularExpressions; using NUnit.Framework; namespace NBehave.Spec.NUnit { public static class Extensions { public static Exception GetException(this Action action) { Exception e = null; try { action(); } catch (Exception exc) { e = exc; } return e; } public static void ShouldApproximatelyEqual<T>(this T actual, T expected, T delta) { if (typeof(T) != typeof(decimal) && typeof(T) != typeof(double) && typeof(T) != typeof(float)) Assert.Fail("type (T) must be float, double or decimal"); if (typeof(T) == typeof(decimal)) Assert.AreEqual(Decimal.ToDouble(Convert.ToDecimal(expected)), Decimal.ToDouble(Convert.ToDecimal(actual)), Decimal.ToDouble(Convert.ToDecimal(delta))); if (typeof(T) == typeof(double)) Assert.AreEqual(Convert.ToDouble(expected), Convert.ToDouble(actual), Convert.ToDouble(delta)); if (typeof(T) == typeof(float)) Assert.AreEqual(Convert.ToSingle(expected), Convert.ToSingle(actual), Convert.ToSingle(delta)); } public static void ShouldBeAssignableFrom<TExpectedType>(this Object actual) { Assert.IsAssignableFrom(typeof(TExpectedType), actual); } public static void ShouldBeAssignableFrom(this object actual, Type expected) { Assert.That(actual, Is.AssignableFrom(expected)); } public static void ShouldBeEmpty(this string value) { Assert.That(value, Is.Empty); } public static void ShouldBeEmpty(this IEnumerable collection) { Assert.That(collection, Is.Empty); } public static void ShouldBeEqualTo(this ICollection actual, ICollection expected) { CollectionAssert.AreEqual(expected, actual); } public static void ShouldBeEquivalentTo(this ICollection actual, ICollection expected) { CollectionAssert.AreEquivalent(expected, actual); } public static void ShouldBeFalse(this bool condition) { Assert.That(condition, Is.False); } public static void ShouldBeGreaterThan(this IComparable arg1, IComparable arg2) { Assert.That(arg1, Is.GreaterThan(arg2)); } public static void ShouldBeGreaterThanOrEqualTo(this IComparable arg1, IComparable arg2) { Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2)); } public static void ShouldBeInstanceOfType<TExpectedType>(this object actual) { actual.ShouldBeInstanceOfType(typeof(TExpectedType)); } public static void ShouldBeInstanceOfType(this object actual, Type expected) { Assert.That(actual, Is.InstanceOf(expected)); } public static void ShouldBeLessThan(this IComparable arg1, IComparable arg2) { Assert.That(arg1, Is.LessThan(arg2)); } public static void ShouldBeLessThanOrEqualTo(this IComparable arg1, IComparable arg2) { Assert.That(arg1, Is.LessThanOrEqualTo(arg2)); } public static void ShouldBeNaN(this double value) { Assert.That(value, Is.NaN); } public static void ShouldBeNull(this object value) { Assert.That(value, Is.Null); } public static void ShouldBeTheSameAs<T>(this T actual, T expected) where T : class { Assert.That(actual, Is.SameAs(expected)); } public static void ShouldBeThrownBy(this Type exceptionType, ThrowingAction action) { Exception e = null; try { action.Invoke(); } catch (Exception ex) { e = ex; } e.ShouldNotBeNull(); e.ShouldBeInstanceOfType(exceptionType); } public static void ShouldBeTrue(this bool condition) { Assert.That(condition, Is.True); } public static void ShouldContain(this ICollection actual, object expected) { Assert.Contains(expected, actual); } public static void ShouldContain(this string actual, string expected) { StringAssert.Contains(expected, actual); } public static void ShouldContain(this IEnumerable actual, object expected) { var lst = new ArrayList(); foreach (var o in actual) { lst.Add(o); } ShouldContain(lst, expected); } public static void ShouldEndWith(this string value, string substring) { StringAssert.EndsWith(substring, value); } public static void ShouldEqual<T>(this T actual, T expected) { Assert.That(actual, Is.EqualTo(expected)); } public static void ShouldMatch(this string value, Regex pattern) { Assert.IsTrue(pattern.IsMatch(value), string.Format("string \"{0}\" does not match pattern {1}", value, pattern)); } public static void ShouldMatch(this string actual, string regexPattern, RegexOptions regexOptions) { var r = new Regex(regexPattern, regexOptions); ShouldMatch(actual, r); } public static void ShouldNotBeAssignableFrom<TExpectedType>(this object actual) { actual.ShouldNotBeAssignableFrom(typeof(TExpectedType)); } public static void ShouldNotBeAssignableFrom(this object actual, Type expected) { Assert.That(actual, Is.Not.AssignableFrom(expected)); } public static void ShouldNotBeEmpty(this string value) { Assert.That(value, Is.Not.Empty); } public static void ShouldNotBeEmpty(this ICollection collection) { Assert.That(collection, Is.Not.Empty); } public static void ShouldNotBeEqualTo(this ICollection actual, ICollection expected) { CollectionAssert.AreNotEqual(expected, actual); } public static void ShouldNotBeEquivalentTo(this ICollection actual, ICollection expected) { CollectionAssert.AreNotEquivalent(expected, actual); } public static void ShouldNotBeInstanceOfType<TExpectedType>(this object actual) { actual.ShouldNotBeInstanceOfType(typeof(TExpectedType)); } public static void ShouldNotBeInstanceOfType(this object actual, Type expected) { Assert.That(actual, Is.Not.InstanceOf(expected)); } public static void ShouldNotBeNull(this object value) { Assert.That(value, Is.Not.Null); } public static void ShouldNotBeTheSameAs(this object actual, object notExpected) { Assert.That(actual, Is.Not.SameAs(notExpected)); } public static void ShouldNotContain(this IEnumerable list, object expected) { Assert.That(list, Is.Not.Contains(expected)); } public static void ShouldNotContain(this string actual, string expected) { Assert.IsTrue(actual.IndexOf(expected) == -1, string.Format("{0} should not contain {1}", actual, expected)); } public static void ShouldNotEqual<T>(this T actual, T notExpected) { Assert.That(actual, Is.Not.EqualTo(notExpected)); } public static void ShouldNotMatch(this string value, Regex pattern) { Assert.IsTrue(pattern.IsMatch(value) == false, string.Format("string \"{0}\" should not match pattern {1}", value, pattern)); } public static void ShouldStartWith(this string value, string substring) { StringAssert.StartsWith(substring, value); } public static IActionSpecification<T> ShouldThrow<T>(this T value, Type exception) { return new ActionSpecification<T>(value, e => { e.ShouldNotBeNull(); e.ShouldBeInstanceOfType(exception); }); } public static Exception ShouldThrow<T>(this Action action) { var failed = false; var ex = new Exception(""); try { action(); failed = true; } catch (Exception e) { e.ShouldBeInstanceOfType(typeof(T)); ex = e; } if (failed) Assert.Fail(string.Format("Exception of type <{0}> expected but no exception occurred", typeof(T))); return ex; } public static void WithExceptionMessage(this Exception e, string exceptionMessage) { exceptionMessage.ShouldEqual(e.Message); } } }
32.703072
138
0.563139
[ "BSD-3-Clause" ]
MorganPersson/NBehave
src/NBehave.Spec.NUnit/Extensions.cs
9,584
C#
/* * Copyright(c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Xml; using Tizen.NUI.Binding.Internals; using Tizen.NUI.Binding; namespace Tizen.NUI.Xaml { internal class CreateValuesVisitor : IXamlNodeVisitor { public CreateValuesVisitor(HydrationContext context) { Context = context; } Dictionary<INode, object> Values { get { return Context.Values; } } HydrationContext Context { get; } public TreeVisitingMode VisitingMode => TreeVisitingMode.BottomUp; public bool StopOnDataTemplate => true; public bool StopOnResourceDictionary => false; public bool VisitNodeOnDataTemplate => false; public bool SkipChildren(INode node, INode parentNode) => false; public bool IsResourceDictionary(ElementNode node) => typeof(ResourceDictionary).IsAssignableFrom(Context.Types[node]); public void Visit(ValueNode node, INode parentNode) { Values[node] = node.Value; } public void Visit(MarkupNode node, INode parentNode) { } public void Visit(ElementNode node, INode parentNode) { object value = null; XamlParseException xpe; var type = XamlParser.GetElementType(node.XmlType, node, Context.RootElement?.GetType().GetTypeInfo().Assembly, out xpe); if (type == null) throw new ArgumentNullException(null, "type should not be null"); if (xpe != null) throw xpe; Context.Types[node] = type; string ctorargname; if (IsXaml2009LanguagePrimitive(node)) value = CreateLanguagePrimitive(type, node); else if (node.Properties.ContainsKey(XmlName.xArguments) || node.Properties.ContainsKey(XmlName.xFactoryMethod)) value = CreateFromFactory(type, node); else if ( type.GetTypeInfo() .DeclaredConstructors.Any( ci => ci.IsPublic && ci.GetParameters().Length != 0 && ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof(ParameterAttribute)))) && ValidateCtorArguments(type, node, out ctorargname)) value = CreateFromParameterizedConstructor(type, node); else if (!type.GetTypeInfo().DeclaredConstructors.Any(ci => ci.IsPublic && ci.GetParameters().Length == 0) && !ValidateCtorArguments(type, node, out ctorargname)) { throw new XamlParseException($"The Property {ctorargname} is required to create a {type?.FullName} object.", node); } else { //this is a trick as the DataTemplate parameterless ctor is internal, and we can't CreateInstance(..., false) on WP7 try { if (type == typeof(DataTemplate)) value = new DataTemplate(); if (type == typeof(ControlTemplate)) value = new ControlTemplate(); if (value == null && node.CollectionItems.Any() && node.CollectionItems.First() is ValueNode) { var serviceProvider = new XamlServiceProvider(node, Context); var converted = ((ValueNode)node.CollectionItems.First()).Value.ConvertTo(type, () => type.GetTypeInfo(), serviceProvider); if (converted != null && converted.GetType() == type) value = converted; } if (value == null) { if (type.GetTypeInfo().DeclaredConstructors.Any(ci => ci.IsPublic && ci.GetParameters().Length == 0)) { //default constructor value = Activator.CreateInstance(type); } else { ConstructorInfo constructorInfo = null; //constructor with all default parameters foreach (var constructor in type.GetConstructors()) { if (!constructor.IsStatic) { bool areAllParamsDefault = true; foreach (var param in constructor.GetParameters()) { if (!param.HasDefaultValue) { areAllParamsDefault = false; break; } } if (areAllParamsDefault) { if (null == constructorInfo) { constructorInfo = constructor; } else { throw new XamlParseException($"{type.FullName} has more than one constructor which params are all default.", node); } } } } if (null == constructorInfo) { throw new XamlParseException($"{type.FullName} has no constructor which params are all default.", node); } List<object> defaultParams = new List<object>(); foreach (var param in constructorInfo.GetParameters()) { defaultParams.Add(param.DefaultValue); } value = Activator.CreateInstance(type, defaultParams.ToArray()); } if (value is Element element) { if (null != Application.Current) { Application.Current.XamlResourceChanged += element.OnResourcesChanged; } element.IsCreateByXaml = true; element.LineNumber = node.LineNumber; element.LinePosition = node.LinePosition; } } } catch (TargetInvocationException e) { if (e.InnerException is XamlParseException || e.InnerException is XmlException) throw e.InnerException; throw; } } Values[node] = value; var markup = value as IMarkupExtension; if (markup != null && (value is TypeExtension || value is StaticExtension || value is ArrayExtension)) { var serviceProvider = new XamlServiceProvider(node, Context); var visitor = new ApplyPropertiesVisitor(Context); foreach (var cnode in node.Properties.Values.ToList()) cnode.Accept(visitor, node); foreach (var cnode in node.CollectionItems) cnode.Accept(visitor, node); value = markup.ProvideValue(serviceProvider); INode xKey; if (!node.Properties.TryGetValue(XmlName.xKey, out xKey)) xKey = null; node.Properties.Clear(); node.CollectionItems.Clear(); if (xKey != null) node.Properties.Add(XmlName.xKey, xKey); Values[node] = value; } if (value is BindableObject) NameScope.SetNameScope(value as BindableObject, node.Namescope); } public void Visit(RootNode node, INode parentNode) { var rnode = (XamlLoader.RuntimeRootNode)node; Values[node] = rnode.Root; Context.Types[node] = rnode.Root.GetType(); var bindableRoot = rnode.Root as BindableObject; if (bindableRoot != null) NameScope.SetNameScope(bindableRoot, node.Namescope); } public void Visit(ListNode node, INode parentNode) { //this is a gross hack to keep ListNode alive. ListNode must go in favor of Properties XmlName name; if (ApplyPropertiesVisitor.TryGetPropertyName(node, parentNode, out name)) node.XmlName = name; } bool ValidateCtorArguments(Type nodeType, IElementNode node, out string missingArgName) { missingArgName = null; var ctorInfo = nodeType.GetTypeInfo() .DeclaredConstructors.FirstOrDefault( ci => ci.GetParameters().Length != 0 && ci.IsPublic && ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof(ParameterAttribute)))); if (ctorInfo == null) return true; foreach (var parameter in ctorInfo.GetParameters()) { // Modify the namespace var propname = parameter.CustomAttributes.First(ca => ca.AttributeType.FullName == "Tizen.NUI.Binding.ParameterAttribute")? .ConstructorArguments.First() .Value as string; if (!node.Properties.ContainsKey(new XmlName("", propname))) { missingArgName = propname; return false; } } return true; } public object CreateFromParameterizedConstructor(Type nodeType, IElementNode node) { var ctorInfo = nodeType.GetTypeInfo() .DeclaredConstructors.FirstOrDefault( ci => ci.GetParameters().Length != 0 && ci.IsPublic && ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof(ParameterAttribute)))); object[] arguments = CreateArgumentsArray(node, ctorInfo); if (arguments != null) { return ctorInfo?.Invoke(arguments); } else { return null; } } public object CreateFromFactory(Type nodeType, IElementNode node) { object[] arguments = CreateArgumentsArray(node); if (!node.Properties.ContainsKey(XmlName.xFactoryMethod)) { //non-default ctor object ret = Activator.CreateInstance(nodeType, BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance | BindingFlags.OptionalParamBinding, null, arguments, CultureInfo.CurrentCulture); if (ret is Element element) { if (null != Application.Current) { Application.Current.XamlResourceChanged += element.OnResourcesChanged; } element.IsCreateByXaml = true; element.LineNumber = (node as ElementNode)?.LineNumber ?? -1; element.LinePosition = (node as ElementNode)?.LinePosition ?? -1; } return ret; } var factoryMethod = ((string)((ValueNode)node.Properties[XmlName.xFactoryMethod]).Value); Type[] types = arguments == null ? System.Array.Empty<Type>() : arguments.Select(a => a.GetType()).ToArray(); Func<MethodInfo, bool> isMatch = m => { if (m.Name != factoryMethod) return false; var p = m.GetParameters(); if (p.Length != types.Length) return false; if (!m.IsStatic) return false; for (var i = 0; i < p.Length; i++) { if ((p[i].ParameterType.IsAssignableFrom(types[i]))) continue; var op_impl = p[i].ParameterType.GetImplicitConversionOperator(fromType: types[i], toType: p[i].ParameterType) ?? types[i].GetImplicitConversionOperator(fromType: types[i], toType: p[i].ParameterType); if (op_impl == null) return false; arguments[i] = op_impl.Invoke(null, new[] { arguments[i] }); } return true; }; var mi = nodeType.GetRuntimeMethods().FirstOrDefault(isMatch); if (mi == null) { if (node is ElementNode elementNode) { var nodeTypeExtension = XamlParser.GetElementTypeExtension(node.XmlType, elementNode, Context.RootElement?.GetType().GetTypeInfo().Assembly); mi = nodeTypeExtension?.GetRuntimeMethods().FirstOrDefault(isMatch); } } if (mi == null) { throw new MissingMemberException($"No static method found for {nodeType.FullName}::{factoryMethod} ({string.Join(", ", types.Select(t => t.FullName))})"); } return mi.Invoke(null, arguments); } public object[] CreateArgumentsArray(IElementNode enode) { if (!enode.Properties.ContainsKey(XmlName.xArguments)) return null; var node = enode.Properties[XmlName.xArguments]; var elementNode = node as ElementNode; if (elementNode != null) { var array = new object[1]; array[0] = Values[elementNode]; if (array[0].GetType().IsClass) { elementNode.Accept(new ApplyPropertiesVisitor(Context, true), null); } return array; } var listnode = node as ListNode; if (listnode != null) { var array = new object[listnode.CollectionItems.Count]; for (var i = 0; i < listnode.CollectionItems.Count; i++) array[i] = Values[(ElementNode)listnode.CollectionItems[i]]; return array; } return null; } public object[] CreateArgumentsArray(IElementNode enode, ConstructorInfo ctorInfo) { if (ctorInfo != null) { var n = ctorInfo.GetParameters().Length; var array = new object[n]; for (var i = 0; i < n; i++) { var parameter = ctorInfo.GetParameters()[i]; var propname = parameter?.CustomAttributes?.First(attr => attr.AttributeType == typeof(ParameterAttribute))? .ConstructorArguments.First() .Value as string; var name = new XmlName("", propname); INode node; if (!enode.Properties.TryGetValue(name, out node)) { String msg = ""; if (propname != null) { msg = String.Format("The Property {0} is required to create a {1} object.", propname, ctorInfo.DeclaringType.FullName); } else { msg = "propname is null."; } throw new XamlParseException(msg, enode as IXmlLineInfo); } if (!enode.SkipProperties.Contains(name)) enode.SkipProperties.Add(name); var value = Context.Values[node]; var serviceProvider = new XamlServiceProvider(enode, Context); var convertedValue = value?.ConvertTo(parameter?.ParameterType, () => parameter, serviceProvider); array[i] = convertedValue; } return array; } return null; } static bool IsXaml2009LanguagePrimitive(IElementNode node) { return node.NamespaceURI == XamlParser.X2009Uri; } static object CreateLanguagePrimitive(Type nodeType, IElementNode node) { object value = null; if (nodeType == typeof(string)) value = String.Empty; else if (nodeType == typeof(Uri)) value = null; else { value = Activator.CreateInstance(nodeType); if (value is Element element) { if (null != Application.Current) { Application.Current.XamlResourceChanged += element.OnResourcesChanged; } element.IsCreateByXaml = true; element.LineNumber = (node as ElementNode)?.LineNumber ?? -1; element.LinePosition = (node as ElementNode)?.LinePosition ?? -1; } } if (node.CollectionItems.Count == 1 && node.CollectionItems[0] is ValueNode && ((ValueNode)node.CollectionItems[0]).Value is string) { var valuestring = ((ValueNode)node.CollectionItems[0]).Value as string; if (nodeType == typeof(SByte)) { sbyte retval; if (sbyte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(Int16)) { return Convert.ToInt16(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring)); } if (nodeType == typeof(Int32)) { return Convert.ToInt32(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring)); } if (nodeType == typeof(Int64)) { return Convert.ToInt64(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring)); } if (nodeType == typeof(Byte)) { byte retval; if (byte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(UInt16)) { return Convert.ToUInt16(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring)); } if (nodeType == typeof(UInt32)) { return Convert.ToUInt32(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring)); } if (nodeType == typeof(UInt64)) { return Convert.ToUInt64(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring)); } if (nodeType == typeof(Single)) { return GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring); } if (nodeType == typeof(Double)) { return Convert.ToDouble(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring)); } if (nodeType == typeof(Boolean)) { bool outbool; if (bool.TryParse(valuestring, out outbool)) return outbool; } if (nodeType == typeof(TimeSpan)) { TimeSpan retval; if (TimeSpan.TryParse(valuestring, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(char)) { char retval; if (char.TryParse(valuestring, out retval)) return retval; } if (nodeType == typeof(string)) return valuestring; if (nodeType == typeof(decimal)) { decimal retval; if (decimal.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } else if (nodeType == typeof(Uri)) { Uri retval; if (Uri.TryCreate(valuestring, UriKind.RelativeOrAbsolute, out retval)) return retval; } } return value; } } }
42.182674
220
0.487388
[ "Apache-2.0", "MIT" ]
lavataste/TizenFX
src/Tizen.NUI/src/internal/Xaml/CreateValuesVisitor.cs
22,399
C#
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System; namespace LibObjectFile.Elf { /// <summary> /// Gets the type of a <see cref="ElfNoteType"/>. /// </summary> public readonly partial struct ElfNoteTypeEx : IEquatable<ElfNoteTypeEx> { public ElfNoteTypeEx(uint value) { Value = (ElfNoteType)value; } public ElfNoteTypeEx(ElfNoteType value) { Value = value; } /// <summary> /// The value of this note type. /// </summary> public readonly ElfNoteType Value; public override string ToString() { return ToStringInternal() ?? $"Unknown {nameof(ElfNoteTypeEx)} (0x{Value:X4})"; } public bool Equals(ElfNoteTypeEx other) { return Value == other.Value; } public override bool Equals(object obj) { return obj is ElfNoteTypeEx other && Equals(other); } public override int GetHashCode() { return (int)Value; } public static bool operator ==(ElfNoteTypeEx left, ElfNoteTypeEx right) { return left.Equals(right); } public static bool operator !=(ElfNoteTypeEx left, ElfNoteTypeEx right) { return !left.Equals(right); } public static explicit operator byte(ElfNoteTypeEx noteType) => (byte)noteType.Value; public static implicit operator ElfNoteTypeEx(ElfNoteType noteType) => new ElfNoteTypeEx(noteType); public static implicit operator ElfNoteType(ElfNoteTypeEx noteType) => noteType.Value; } }
27.846154
107
0.599448
[ "BSD-2-Clause" ]
tmds/LibObjectFile
src/LibObjectFile/Elf/Sections/ElfNoteType.cs
1,812
C#
using System.Reflection; namespace BanallyMe.QuickReflect.Models { /// <summary> /// Pair of an object Property and its corresponding value on an object. /// </summary> public class PropertyValuePair { /// <summary> /// The object's property. /// </summary> public PropertyInfo Property { get; } /// <summary> /// The value of this property on a certain object. /// </summary> public object CorrespondingValue { get; } /// <summary> /// Creates a new PropertyValuePair. /// </summary> /// <param name="property">An object's property.</param> /// <param name="correspondingValue">The value of this property on a certain object.</param> public PropertyValuePair(PropertyInfo property, object correspondingValue) { Property = property; CorrespondingValue = correspondingValue; } /// <summary> /// Creates a new PropertyValuePair from an existing object and one of its properties. /// </summary> /// <param name="containingObject">Object to be read.</param> /// <param name="property">Property to read the corresponding Value from.</param> /// <returns>A Pair of the property and its corresponding value.</returns> public static PropertyValuePair CreateFromObjectsProperty(object containingObject, PropertyInfo property) { return new PropertyValuePair(property, property.GetValue(containingObject)); } } }
36.44186
113
0.623484
[ "MIT" ]
BanallyMe/QuickReflect
QuickReflect/QuickReflect/Models/PropertyValuePair.cs
1,569
C#
using ARMeilleure.Decoders; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; using ARMeilleure.Translation; using System; using System.Reflection; using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; namespace ARMeilleure.Instructions { static partial class InstEmit { private const int DczSizeLog2 = 4; // Log2 size in words public const int DczSizeInBytes = 4 << DczSizeLog2; public static void Hint(ArmEmitterContext context) { // Execute as no-op. } public static void Isb(ArmEmitterContext context) { // Execute as no-op. } public static void Mrs(ArmEmitterContext context) { OpCodeSystem op = (OpCodeSystem)context.CurrOp; MethodInfo info; switch (GetPackedId(op)) { case 0b11_011_0000_0000_001: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCtrEl0)); break; case 0b11_011_0000_0000_111: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetDczidEl0)); break; case 0b11_011_0100_0010_000: EmitGetNzcv(context); return; case 0b11_011_0100_0100_000: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetFpcr)); break; case 0b11_011_0100_0100_001: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetFpsr)); break; case 0b11_011_1101_0000_010: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetTpidrEl0)); break; case 0b11_011_1101_0000_011: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetTpidr)); break; case 0b11_011_1110_0000_000: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntfrqEl0)); break; case 0b11_011_1110_0000_001: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntpctEl0)); break; case 0b11_011_1110_0000_010: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntvctEl0)); break; default: throw new NotImplementedException($"Unknown MRS 0x{op.RawOpCode:X8} at 0x{op.Address:X16}."); } SetIntOrZR(context, op.Rt, context.Call(info)); } public static void Msr(ArmEmitterContext context) { OpCodeSystem op = (OpCodeSystem)context.CurrOp; MethodInfo info; switch (GetPackedId(op)) { case 0b11_011_0100_0010_000: EmitSetNzcv(context); return; case 0b11_011_0100_0100_000: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.SetFpcr)); break; case 0b11_011_0100_0100_001: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.SetFpsr)); break; case 0b11_011_1101_0000_010: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.SetTpidrEl0)); break; default: throw new NotImplementedException($"Unknown MSR 0x{op.RawOpCode:X8} at 0x{op.Address:X16}."); } context.Call(info, GetIntOrZR(context, op.Rt)); } public static void Nop(ArmEmitterContext context) { // Do nothing. } public static void Sys(ArmEmitterContext context) { // This instruction is used to do some operations on the CPU like cache invalidation, // address translation and the like. // We treat it as no-op here since we don't have any cache being emulated anyway. OpCodeSystem op = (OpCodeSystem)context.CurrOp; switch (GetPackedId(op)) { case 0b11_011_0111_0100_001: { // DC ZVA Operand t = GetIntOrZR(context, op.Rt); for (long offset = 0; offset < DczSizeInBytes; offset += 8) { Operand address = context.Add(t, Const(offset)); InstEmitMemoryHelper.EmitStore(context, address, RegisterConsts.ZeroIndex, 3); } break; } // No-op case 0b11_011_0111_1110_001: // DC CIVAC break; case 0b11_011_0111_0101_001: // IC IVAU Operand target = Register(op.Rt, RegisterType.Integer, OperandType.I64); context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.InvalidateCacheLine)), target); break; } } private static int GetPackedId(OpCodeSystem op) { int id; id = op.Op2 << 0; id |= op.CRm << 3; id |= op.CRn << 7; id |= op.Op1 << 11; id |= op.Op0 << 14; return id; } private static void EmitGetNzcv(ArmEmitterContext context) { OpCodeSystem op = (OpCodeSystem)context.CurrOp; Operand vSh = context.ShiftLeft(GetFlag(PState.VFlag), Const((int)PState.VFlag)); Operand cSh = context.ShiftLeft(GetFlag(PState.CFlag), Const((int)PState.CFlag)); Operand zSh = context.ShiftLeft(GetFlag(PState.ZFlag), Const((int)PState.ZFlag)); Operand nSh = context.ShiftLeft(GetFlag(PState.NFlag), Const((int)PState.NFlag)); Operand nzcvSh = context.BitwiseOr(context.BitwiseOr(nSh, zSh), context.BitwiseOr(cSh, vSh)); SetIntOrZR(context, op.Rt, nzcvSh); } private static void EmitSetNzcv(ArmEmitterContext context) { OpCodeSystem op = (OpCodeSystem)context.CurrOp; Operand t = GetIntOrZR(context, op.Rt); t = context.ConvertI64ToI32(t); Operand v = context.ShiftRightUI(t, Const((int)PState.VFlag)); v = context.BitwiseAnd (v, Const(1)); Operand c = context.ShiftRightUI(t, Const((int)PState.CFlag)); c = context.BitwiseAnd (c, Const(1)); Operand z = context.ShiftRightUI(t, Const((int)PState.ZFlag)); z = context.BitwiseAnd (z, Const(1)); Operand n = context.ShiftRightUI(t, Const((int)PState.NFlag)); n = context.BitwiseAnd (n, Const(1)); SetFlag(context, PState.VFlag, v); SetFlag(context, PState.CFlag, c); SetFlag(context, PState.ZFlag, z); SetFlag(context, PState.NFlag, n); } } }
41.278788
132
0.59213
[ "MIT" ]
2579768776/Ryujinx
ARMeilleure/Instructions/InstEmitSystem.cs
6,811
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { [Serializable] public sealed class SerializableVersionStamp { private readonly byte[] bytes; public SerializableVersionStamp(VersionStamp versionStamp) { using (var memoryStream = new MemoryStream()) { using (var objectWriter = new ObjectWriter(memoryStream)) { versionStamp.WriteTo(objectWriter); } bytes = memoryStream.ToArray(); } } public VersionStamp VersionStamp { get { using (var stream = new MemoryStream(bytes)) { using (var objectReader = new ObjectReader(stream)) { return VersionStamp.ReadFrom(objectReader); } } } } } }
24.795455
73
0.52429
[ "Apache-2.0" ]
enginekit/copy_of_roslyn
Src/Workspaces/Core/Desktop/Workspace/Solution/SerializableVersionStamp.cs
1,093
C#
#if NETSTANDARD2_0 using System; using System.Net; using System.Linq; using System.IO; using System.Threading.Tasks; using System.Collections.Generic; using System.Threading; using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Internal; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets; using Microsoft.AspNetCore.Http.Features; using Kooboo.Data.Context; using Microsoft.Extensions.Logging; using System.Collections.Specialized; using Microsoft.AspNetCore.Http; using System.Text; using Kooboo.Lib.Helper; namespace Kooboo.Data.Server { public class KestrelWebServer : IWebServer { private KestrelServer _server { get; set; } private KoobooHttpApplication _application { get; set; } private List<IKoobooMiddleWare> MiddleWares { get; set; } = new List<IKoobooMiddleWare>(); private IKoobooMiddleWare StartWare { get; set; } = null; public KestrelWebServer(int port, List<IKoobooMiddleWare> middlewares, bool forcessl = false) { var life = new ApplicationLifetime(null); var log = new Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory(); SocketTransportFactory usesocket = new SocketTransportFactory(new koobooSocketOption(), life, log); _server = new KestrelServer(new KoobooServerOption(port, forcessl), usesocket, log); _server.Options.Limits.MaxRequestBodySize = 1024 * 1024 * 800; SetMiddleWares(middlewares); } public void Start() { _application = new KoobooHttpApplication(StartWare); _server.StartAsync(_application, CancellationToken.None); } public void Stop() { _server.StopAsync(CancellationToken.None); } public void SetMiddleWares(List<IKoobooMiddleWare> middlewares) { this.MiddleWares = middlewares; OrganizeChain(); } private void OrganizeChain() { bool HasEnd = false; foreach (var item in this.MiddleWares) { if (item.GetType() == typeof(EndMiddleWare)) { HasEnd = true; } } if (!HasEnd) { this.MiddleWares.Add(new EndMiddleWare()); } int count = this.MiddleWares.Count; for (int i = 0; i < count; i++) { if (i < count - 1) { this.MiddleWares[i].Next = this.MiddleWares[i + 1]; } } this.StartWare = this.MiddleWares[0]; } public class koobooSocketOption : IOptions<SocketTransportOptions> { public SocketTransportOptions Value { get { var op = new SocketTransportOptions(); op.IOQueueCount = 0; return op; } } } public class KoobooServerOption : IOptions<KestrelServerOptions> { int port { get; set; } bool forcessl { get; set; } public KoobooServerOption(int port, bool forcessl) { this.port = port; this.forcessl = forcessl; } public KestrelServerOptions op { get; set; } public KestrelServerOptions Value { get { if (op == null) { op = new KestrelServerOptions(); op.Limits.MaxRequestBodySize = 1024 * 1024 * 128; op.Listen(IPAddress.Any, port, Configure); } return op; } } public void Configure(ListenOptions lisOption) { lisOption.Protocols = HttpProtocols.Http1AndHttp2; var services = new ServiceCollection(); var log = new Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory(); services.AddSingleton<ILoggerFactory>(log); lisOption.KestrelServerOptions.ApplicationServices = services.BuildServiceProvider(); if (port == 443 || forcessl) { // use https Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions ssloption = new Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions(); ssloption.ServerCertificateSelector = SelectSsl; ssloption.ClientCertificateMode = Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode.NoCertificate; ssloption.ClientCertificateValidation = (x, y, z) => { return true; }; ssloption.HandshakeTimeout = new TimeSpan(0, 0, 30); ssloption.SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls; lisOption.UseHttps(ssloption); } } public X509Certificate2 SelectSsl(Microsoft.AspNetCore.Connections.ConnectionContext context, string host) { return Kooboo.Data.Server.SslCertificateProvider.SelectCertificate2(host); } } public class KoobooHttpApplication : IHttpApplication<RenderContext> { private IKoobooMiddleWare start { get; set; } public KoobooHttpApplication(IKoobooMiddleWare start) { this.start = start; } public RenderContext CreateContext(IFeatureCollection contextFeatures) { var context = GetRenderContext(contextFeatures); context.SetItem<IFeatureCollection>(contextFeatures); return context; } public void DisposeContext(RenderContext context, Exception exception) { context = null; } public async Task ProcessRequestAsync(RenderContext context) { // process the context.... await this.start.Invoke(context); await SetResponse(context); } public static RenderContext GetRenderContext(IFeatureCollection Feature) { RenderContext context = new RenderContext(); context.Request = GetRequest(Feature); return context; } private static Context.HttpRequest GetRequest(IFeatureCollection requestFeature) { Context.HttpRequest httprequest = new Context.HttpRequest(); var req = requestFeature.Get<IHttpRequestFeature>(); var connection = requestFeature.Get<IHttpConnectionFeature>(); httprequest.Port = connection.LocalPort; httprequest.IP = connection.RemoteIpAddress.ToString(); Microsoft.Extensions.Primitives.StringValues forwardip; if (req.Headers.TryGetValue("X-Forwarded-For", out forwardip)) { httprequest.IP = forwardip.First(); } Microsoft.Extensions.Primitives.StringValues host; req.Headers.TryGetValue("Host", out host); string domainhost = host.First().ToString(); int delimiterIndex = domainhost.IndexOf(":"); if (delimiterIndex > 0) { domainhost = domainhost.Substring(0, delimiterIndex); } httprequest.Host = domainhost; foreach (var item in req.Headers) { httprequest.Headers.Add(item.Key, item.Value); } httprequest.Path = req.Path; httprequest.Url = GetUrl(req.RawTarget); httprequest.RawRelativeUrl = httprequest.Url; httprequest.Method = req.Method; httprequest.Scheme = req.Scheme; httprequest.QueryString = GetQueryString(requestFeature); httprequest.Cookies = GetCookie(requestFeature); if (httprequest.Method != "GET") { if (req.Body != null && req.Body.CanRead) { MemoryStream ms = new MemoryStream(); var body = req.Body; req.Body.CopyTo(ms); httprequest.PostData = ms.ToArray(); ms.Dispose(); } var contenttype = httprequest.Headers.Get("Content-Type"); if (contenttype != null && contenttype.ToLower().Contains("multipart")) { var formresult = Kooboo.Lib.NETMultiplePart.FormReader.ReadForm(httprequest.PostData); httprequest.Forms = new NameValueCollection(); if (formresult.FormData != null) { foreach (var item in formresult.FormData) { httprequest.Forms.Add(item.Key, item.Value); } } httprequest.Files = formresult.Files; } else { httprequest.Forms.Add(GetForm(httprequest.PostData, contenttype)); } } return httprequest; } private static string GetUrl(string target) { if (string.IsNullOrEmpty(target)) { return "/"; } else { return System.Net.WebUtility.UrlDecode(target); } } internal static NameValueCollection GetForm(byte[] inputstream, string contenttype = null) { bool hasEncoded = false; if (contenttype != null && contenttype.ToLower().Contains("urlencoded")) { hasEncoded = true; } // The encoding type of a form is determined by the attribute enctype.It can have three values, //application / x - www - form - urlencoded - Represents an URL encoded form. This is the default value if enctype attribute is not set to anything. //multipart / form - data - Represents a Multipart form.This type of form is used when the user wants to upload files //text / plain - A new form type introduced in HTML5, that as the name suggests, simply sends the data without any encoding NameValueCollection result = new NameValueCollection(); string text = System.Text.Encoding.UTF8.GetString(inputstream); if (text == null) { return result; } //if (hasEncoded && text !=null) //{ // text = System.Net.WebUtility.UrlDecode(text); //} int textLength = text.Length; int equalIndex = text.IndexOf('='); if (equalIndex == -1) { equalIndex = textLength; } int scanIndex = 0; while (scanIndex < textLength) { int delimiterIndex = text.IndexOf("&", scanIndex); if (delimiterIndex == -1) { delimiterIndex = textLength; } if (equalIndex < delimiterIndex) { while (scanIndex != equalIndex && char.IsWhiteSpace(text[scanIndex])) { ++scanIndex; } string name = text.Substring(scanIndex, equalIndex - scanIndex); if (hasEncoded) { name = System.Net.WebUtility.UrlDecode(name); } // name= Uri.UnescapeDataString(name); string value = text.Substring(equalIndex + 1, delimiterIndex - equalIndex - 1); // value= Uri.UnescapeDataString(value); if (hasEncoded) { value = System.Net.WebUtility.UrlDecode(value); } result.Add(name, value); equalIndex = text.IndexOf('=', delimiterIndex); if (equalIndex == -1) { equalIndex = textLength; } } scanIndex = delimiterIndex + 1; } return result; } private static Dictionary<string, string> GetCookie(IFeatureCollection feature) { Dictionary<string, string> cookies = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); var cookiefeture = feature.Get<IRequestCookiesFeature>(); if (cookiefeture == null) { cookiefeture = new RequestCookiesFeature(feature); } if (cookiefeture.Cookies != null && cookiefeture.Cookies.Any()) { foreach (var item in cookiefeture.Cookies) { if (!cookies.ContainsKey(item.Key)) { cookies.Add(item.Key, item.Value); } } } return cookies; } private static NameValueCollection GetQueryString(IFeatureCollection feature) { NameValueCollection query = new NameValueCollection(); var requestfeature = feature.Get<IQueryFeature>(); if (requestfeature == null) { requestfeature = new QueryFeature(feature); } if (requestfeature.Query != null && requestfeature.Query.Any()) { foreach (var item in requestfeature.Query) { query.Add(item.Key, item.Value); } } return query; } public static async Task SetResponse(RenderContext renderContext) { var feature = renderContext.GetItem<IFeatureCollection>(); var response = renderContext.Response; var res = feature.Get<IHttpResponseFeature>(); var request = feature.Get<IHttpRequestFeature>(); res.Headers.Add("server", "http://www.kooboo.com"); res.StatusCode = response.StatusCode; res.Headers.Add("Content-Type", response.ContentType); foreach (var item in response.Headers) { res.Headers[item.Key] = item.Value; } #region cookie if (response.DeletedCookieNames.Any() || response.AppendedCookies.Any()) { var cookieres = feature.Get<IResponseCookiesFeature>(); if (cookieres == null) { cookieres = new ResponseCookiesFeature(feature); } foreach (var item in response.DeletedCookieNames) { var options = new CookieOptions() { Domain = renderContext.Request.Host, Path = "/", Expires = DateTime.Now.AddDays(-30) }; cookieres.Cookies.Append(item, "", options); response.AppendedCookies.RemoveAll(o => o.Name == item); } foreach (var item in response.AppendedCookies) { if (string.IsNullOrEmpty(item.Domain)) { item.Domain = renderContext.Request.Host; } if (string.IsNullOrEmpty(item.Path)) { item.Path = "/"; } if (item.Expires == default(DateTime)) { var time = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local); time = time.AddSeconds(-1); item.Expires = time; } var options = new CookieOptions() { Domain = item.Domain, Path = item.Path, Expires = item.Expires }; cookieres.Cookies.Append(item.Name, item.Value, options); } } #endregion if (response.StatusCode == 200) { if (response.Body != null && renderContext.Request.Method != "HEAD") { try { res.Headers["Content-Length"] = response.Body.Length.ToString(); await res.Body.WriteAsync(response.Body, 0, response.Body.Length).ConfigureAwait(false); } catch (Exception) { res.Body.Close(); } } else { if (response.Stream != null) { await response.Stream.CopyToAsync(res.Body); } else if (response.FilePart != null) { await WritePartToResponse(response.FilePart, res); } else { // 404. //string filename = Lib.Helper.IOHelper.CombinePath(AppSettings.RootPath, Kooboo.DataConstants.Default404Page) + ".html"; //if (System.IO.File.Exists(filename)) //{ // string text = System.IO.File.ReadAllText(filename); // var bytes = System.Text.Encoding.UTF8.GetBytes(text); // res.Headers["Content-Length"] = bytes.Length.ToString(); // res.StatusCode = 404; // await res.Body.WriteAsync(bytes, 0, bytes.Length); //} } } } else { string location = response.RedirectLocation; if (!string.IsNullOrEmpty(location)) { var host = renderContext.Request.Port == 80 || renderContext.Request.Port == 443 ? renderContext.Request.Host : string.Format("{0}:{1}", renderContext.Request.Host, renderContext.Request.Port); string BaseUrl = renderContext.Request.Scheme + "://" + host + renderContext.Request.Path; var newUrl = UrlHelper.Combine(BaseUrl, location); if (response.StatusCode != 200) { res.StatusCode = response.StatusCode; } //status code doesn't start with 3xx,it'will not redirect. if (!response.StatusCode.ToString().StartsWith("3")) { res.StatusCode = StatusCodes.Status302Found; } res.Headers["location"] = newUrl; res.Body.Dispose(); Log(renderContext); return; } if (response.Body != null && response.Body.Length > 0) { res.StatusCode = response.StatusCode; await res.Body.WriteAsync(response.Body, 0, response.Body.Length).ConfigureAwait(false); res.Body.Dispose(); Log(renderContext); return; } res.StatusCode = response.StatusCode; string responsebody = null; switch (response.StatusCode) { case 404: responsebody = " The requested resource not found"; break; case 301: responsebody = " The requested resource has moved."; break; case 302: responsebody = " The requested resource has moved."; break; case 401: responsebody = " Unauthorized access"; break; case 403: responsebody = " Unauthorized access"; break; case 407: responsebody = "Reach Limitation"; break; case 500: responsebody = "Internal server error"; break; case 503: responsebody = " Service Unavailable"; break; default: break; } if (string.IsNullOrEmpty(responsebody)) { if (response.StatusCode >= 400 && response.StatusCode < 500) { responsebody = " Client error"; } else if (response.StatusCode >= 500) { responsebody = " Server error"; } else { responsebody = " Unknown error"; } } var bytes = Encoding.UTF8.GetBytes(responsebody); await res.Body.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); } res.Body.Dispose(); Log(renderContext); res = null; } public static void Log(RenderContext context) { if (Data.AppSettings.Global.EnableLog) { string log = context.Response.StatusCode.ToString() + " " + context.Request.IP + ": " + DateTime.Now.ToLongTimeString() + " " + context.Request.Host + " " + context.Request.Method + " " + context.Request.Url; Kooboo.Data.Log.Instance.Http.Write(log); } } private static async Task WritePartToResponse(Kooboo.IndexedDB.FilePart part, IHttpResponseFeature Res) { long offset = part.BlockPosition + part.RelativePosition; //byte[] buffer = new byte[209715200]; byte[] buffer = new byte[8096]; long totalToSend = part.Length; int count = 0; Res.Headers["Content-Length"] = totalToSend.ToString(); long bytesRemaining = totalToSend; var stream = Kooboo.IndexedDB.StreamManager.OpenReadStream(part.FullFileName); stream.Position = offset; try { while (bytesRemaining > 0) { if (bytesRemaining <= buffer.Length) count = await stream.ReadAsync(buffer, 0, (int)bytesRemaining); else count = await stream.ReadAsync(buffer, 0, buffer.Length); if (count == 0) return; await Res.Body.WriteAsync(buffer, 0, count); bytesRemaining -= count; } } catch (IndexOutOfRangeException) { } finally { await Res.Body.FlushAsync(); } } } } } #endif
37.524638
228
0.461957
[ "MIT" ]
ShubinKooboo/Kooboo
Kooboo.Data/Server/KestrelServer.cs
25,894
C#
using System; using AppRopio.Base.Droid.Adapters; using AppRopio.ECommerce.Products.Droid.Views.Catalog; namespace AppRopio.ECommerce.Products.Droid.Views.Categories.Disabled { public class DCatalogTemplateSelector : IARFlatGroupTemplateSelector { private CatalogCollectionType _collectionType; public DCatalogTemplateSelector(CatalogCollectionType collectionType) { _collectionType = collectionType; } public int GetFooterViewType(object forItemObject) { return Resource.Layout.app_products_sscategories_footer; } public int GetHeaderViewType(object forItemObject) { return Resource.Layout.app_products_sscategories_header; } public int GetItemLayoutId(int fromViewType) { return fromViewType; } public int GetItemViewType(object forItemObject) { return _collectionType == CatalogCollectionType.Grid ? Resource.Layout.app_products_catalog_item_grid : Resource.Layout.app_products_catalog_item_list; } } }
32.35
106
0.601236
[ "Apache-2.0" ]
cryptobuks/AppRopio.Mobile
src/app-ropio/AppRopio.ECommerce/Products/Droid/Views/Categories/Disabled/DCatalogTemplateSelector.cs
1,296
C#
using Car.Data.Enums; using Microsoft.AspNetCore.Http; namespace Car.Domain.Dto { public class UpdateCarDto { public int Id { get; set; } public int ModelId { get; set; } public Color Color { get; set; } public string? PlateNumber { get; set; } public IFormFile? Image { get; set; } } }
18.157895
48
0.594203
[ "MIT" ]
ita-social-projects/Car-Back-End
Car.Backend/Car.Domain/Dto/Car/UpdateCarDto.cs
347
C#
using System.Collections; using System.Collections.Generic; using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.CollectionsGeneric; using NetOffice.MSProjectApi; namespace NetOffice.MSProjectApi.Behind { /// <summary> /// DispatchInterface Calendars /// SupportByVersion MSProject, 11,12,14 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff920564(v=office.14).aspx </remarks> public class Calendars : COMObject, NetOffice.MSProjectApi.Calendars { #pragma warning disable #region Type Information /// <summary> /// Contract Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type ContractType { get { if(null == _contractType) _contractType = typeof(NetOffice.MSProjectApi.Calendars); return _contractType; } } private static Type _contractType; /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(Calendars); return _type; } } #endregion #region Ctor /// <summary> /// Stub Ctor, not indented to use /// </summary> public Calendars() : base() { } #endregion #region Properties /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// Get /// </summary> [SupportByVersion("MSProject", 11,12,14)] public virtual NetOffice.MSProjectApi.Application Application { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.MSProjectApi.Application>(this, "Application", typeof(NetOffice.MSProjectApi.Application)); } } /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// Get /// </summary> [SupportByVersion("MSProject", 11,12,14)] public virtual NetOffice.MSProjectApi.Project Parent { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.MSProjectApi.Project>(this, "Parent", typeof(NetOffice.MSProjectApi.Project)); } } /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// Get /// </summary> [SupportByVersion("MSProject", 11,12,14)] public virtual Int32 Count { get { return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "Count"); } } /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// Get /// </summary> /// <param name="index">object index</param> [SupportByVersion("MSProject", 11,12,14)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty] public virtual NetOffice.MSProjectApi.Calendar this[object index] { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.MSProjectApi.Calendar>(this, "Item", typeof(NetOffice.MSProjectApi.Calendar), index); } } #endregion #region Methods #endregion #region IEnumerableProvider<NetOffice.MSProjectApi.Calendar> ICOMObject IEnumerableProvider<NetOffice.MSProjectApi.Calendar>.GetComObjectEnumerator(ICOMObject parent) { return NetOffice.Utils.GetComObjectEnumeratorAsProperty(parent, this, false); } IEnumerable IEnumerableProvider<NetOffice.MSProjectApi.Calendar>.FetchVariantComObjectEnumerator(ICOMObject parent, ICOMObject enumerator) { return NetOffice.Utils.FetchVariantComObjectEnumerator(parent, enumerator, false); } #endregion #region IEnumerable<NetOffice.MSProjectApi.Calendar> /// <summary> /// SupportByVersion MSProject, 11,12,14 /// </summary> [SupportByVersion("MSProject", 11, 12, 14)] public virtual IEnumerator<NetOffice.MSProjectApi.Calendar> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (NetOffice.MSProjectApi.Calendar item in innerEnumerator) yield return item; } #endregion #region IEnumerable /// <summary> /// SupportByVersion MSProject, 11,12,14 /// </summary> [SupportByVersion("MSProject", 11,12,14)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsProperty(this, false); } #endregion #pragma warning restore } }
27.204301
175
0.664427
[ "MIT" ]
igoreksiz/NetOffice
Source/MSProject/Behind/DispatchInterfaces/Calendars.cs
5,062
C#
using System; namespace Nez.LibGdxAtlases { public class LibGdxAtlasPoint { public float x; public float y; public LibGdxAtlasPoint() {} public LibGdxAtlasPoint( float x, float y ) { this.x = x; this.y = y; } } }
10.166667
45
0.635246
[ "MIT" ]
AlmostBearded/monogame-platformer
Platformer/Nez/Nez.PipelineImporter/LibGdxAtlases/LibGdxAtlasPoint.cs
246
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DataFactory.Inputs { /// <summary> /// A copy activity Azure Blob sink. /// </summary> public sealed class BlobSinkArgs : Pulumi.ResourceArgs { /// <summary> /// Blob writer add header. Type: boolean (or Expression with resultType boolean). /// </summary> [Input("blobWriterAddHeader")] public Input<object>? BlobWriterAddHeader { get; set; } /// <summary> /// Blob writer date time format. Type: string (or Expression with resultType string). /// </summary> [Input("blobWriterDateTimeFormat")] public Input<object>? BlobWriterDateTimeFormat { get; set; } /// <summary> /// Blob writer overwrite files. Type: boolean (or Expression with resultType boolean). /// </summary> [Input("blobWriterOverwriteFiles")] public Input<object>? BlobWriterOverwriteFiles { get; set; } /// <summary> /// The type of copy behavior for copy sink. /// </summary> [Input("copyBehavior")] public Input<object>? CopyBehavior { get; set; } /// <summary> /// If true, disable data store metrics collection. Default is false. Type: boolean (or Expression with resultType boolean). /// </summary> [Input("disableMetricsCollection")] public Input<object>? DisableMetricsCollection { get; set; } /// <summary> /// The maximum concurrent connection count for the sink data store. Type: integer (or Expression with resultType integer). /// </summary> [Input("maxConcurrentConnections")] public Input<object>? MaxConcurrentConnections { get; set; } [Input("metadata")] private InputList<Inputs.MetadataItemArgs>? _metadata; /// <summary> /// Specify the custom metadata to be added to sink data. Type: array of objects (or Expression with resultType array of objects). /// </summary> public InputList<Inputs.MetadataItemArgs> Metadata { get => _metadata ?? (_metadata = new InputList<Inputs.MetadataItemArgs>()); set => _metadata = value; } /// <summary> /// Sink retry count. Type: integer (or Expression with resultType integer). /// </summary> [Input("sinkRetryCount")] public Input<object>? SinkRetryCount { get; set; } /// <summary> /// Sink retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> [Input("sinkRetryWait")] public Input<object>? SinkRetryWait { get; set; } /// <summary> /// Copy sink type. /// Expected value is 'BlobSink'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; /// <summary> /// Write batch size. Type: integer (or Expression with resultType integer), minimum: 0. /// </summary> [Input("writeBatchSize")] public Input<object>? WriteBatchSize { get; set; } /// <summary> /// Write batch timeout. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> [Input("writeBatchTimeout")] public Input<object>? WriteBatchTimeout { get; set; } public BlobSinkArgs() { } } }
37.27451
148
0.59495
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DataFactory/Inputs/BlobSinkArgs.cs
3,802
C#
using ND.MCJ.Framework; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Security.Cryptography; using System.Text; using ND.MCJ.Framework.Converter; namespace ND.MCJ.AOP.Security { public class Signature { /// <summary> /// 验证签名 /// </summary> /// <param name="nv"></param> /// <returns></returns> public static bool VerifySign(NameValueCollection nv) { //H5接口免加密 //if (nv.AllKeys.Contains("Platform") && nv["Platform"] == "3") { return true; } if (!(nv.AllKeys.Contains("Sign") && nv.AllKeys.Contains("PlatformId"))) return false; var sign = nv["Sign"].Replace(" ", "+"); var dic = nv.ToDictionary(true); dic.Remove("Sign"); var str = MakeSign(dic); return sign == str; } /// <summary> /// 生成签名 /// </summary> /// <param name="dic"></param> /// <returns></returns> public static string MakeSign(IDictionary<String, String> dic) { var appKey = System.Configuration.ConfigurationManager.AppSettings["AppSignatureKey"]; var signStr = dic.OrderBy(q => q.Key).Aggregate("", (c, q) => c + dic[q.Key] + "|"); var sb = new StringBuilder(32); MD5 md5 = new MD5CryptoServiceProvider(); var t = md5.ComputeHash(Encoding.UTF8.GetBytes(signStr + appKey)); foreach (var t1 in t) { sb.Append(t1.ToString("x").PadLeft(2, '0')); } return sb.ToString(); } } }
35.041667
99
0.540428
[ "Apache-2.0" ]
PengXX0/ND.MCJ
Infrastructure/ND.MCJ.AOP/Security/Signature.cs
1,710
C#
using System; using System.IO; using System.Linq; using System.Reflection; using System.Collections.Generic; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Package; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.LanguageServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; using NuGet.VisualStudio; using Excess.Compiler.Roslyn; using Excess.Compiler.Reflection; using Excess.Compiler; using Excess.Compiler.Core; using xslang; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Excess.VisualStudio.VSPackage { using RoslynCompilationAnalysis = CompilationAnalysisBase<SyntaxToken, SyntaxNode, SemanticModel>; using CompilerFunc = Action<RoslynCompiler, Scope>; using CompilerAnalysisFunc = Action<CompilationAnalysisBase<SyntaxToken, SyntaxNode, SemanticModel>>; class ExcessLanguageService : LanguageService { VisualStudioWorkspace _workspace; public ExcessLanguageService(VisualStudioWorkspace workspace) { _workspace = workspace; } public override string Name { get { return "xs"; } } IVsPackageInstallerServices _nuget; IVsPackageInstallerEvents _nugetEvents; private void ensureNuget() { if (_nuget == null) { var componentModel = (IComponentModel)GetService(typeof(SComponentModel)); _nuget = componentModel.GetService<IVsPackageInstallerServices>(); _nugetEvents = componentModel.GetService<IVsPackageInstallerEvents>(); } if (_nuget == null || _nugetEvents == null) throw new InvalidOperationException("nuget"); } DTE2 _dte; private EnvDTE.Events _dteEvents; private BuildEvents _buildEvents; public void ensureDTE() { if (_dte == null) { _dte = (DTE2)GetService(typeof(DTE)); _dteEvents = _dte.Events; _buildEvents = _dteEvents.BuildEvents; _buildEvents.OnBuildBegin += BeforeBuild; } } private void BeforeBuild(vsBuildScope buildScope, vsBuildAction buildAction) { if (buildAction == vsBuildAction.vsBuildActionClean) { log($"Clean xs solution not yey implemented"); return; //td: } log($"Start building xs..."); var projects = _dte.Solution.Projects.Cast<EnvDTE.Project>(); var allDocuments = new Dictionary<string, RoslynDocument>(); var documentIds = new Dictionary<string, DocumentId>(); var projectAnalysis = new Dictionary<string, RoslynCompilationAnalysis>(); var compilationAnalysis = new Dictionary<string, CompilerAnalysisFunc>(); var extensions = loadExtensions(compilationAnalysis); //global scope var scope = new Scope(null); scope.set(extensions); //grab info per project var codeFiles = new List<ProjectItem>(); foreach (var project in projects) { log($"Project {project.Name}..."); var projectExtensions = new List<string>(); var documents = compile( project, filter: doc => buildAction == vsBuildAction.vsBuildActionRebuildAll ? true : isDirty(doc), scope: scope, extensions: projectExtensions, codeFiles: codeFiles); if (!documents.Any()) continue; foreach (var doc in documents) allDocuments[doc.Key] = doc.Value; mapDocuments(documents, documentIds); var compilation = new RoslynCompilationAnalysis(); var needsIt = false; foreach (var ext in projectExtensions.Distinct()) { var func = default(CompilerAnalysisFunc); if (compilationAnalysis.TryGetValue(ext, out func)) { func(compilation); needsIt = true; } } if (needsIt) projectAnalysis[project.FileName] = compilation; } build(allDocuments, documentIds, scope); postCompilation(projectAnalysis); saveAllFiles(codeFiles); } private void saveAllFiles(IEnumerable<ProjectItem> allFiles) { foreach (var file in allFiles) { if (!file.Saved) file.Save(); } } private void build(Dictionary<string, RoslynDocument> documents, Dictionary<string, DocumentId> documentIds, Scope scope) { //now we must join all files for semantic stuff try { while (documents.Any()) { var temp = new Dictionary<string, RoslynDocument>(documents); documents.Clear(); foreach (var request in temp) { var docId = default(DocumentId); if (!documentIds.TryGetValue(request.Key, out docId)) continue; saveCodeBehind(request.Value, docId, false); if (!request.Value.HasSemanticalChanges()) continue; documents[request.Key] = request.Value; } if (documents.Any()) link(documents, documentIds, scope); } } catch (Exception ex) { log($"Failed linking with: {ex.ToString()}"); } } private void mapDocuments(Dictionary<string, RoslynDocument> documents, Dictionary<string, DocumentId> documentIds) { foreach (var path in documents.Keys) { var csFile = path + ".cs"; var docId = _workspace .CurrentSolution .GetDocumentIdsWithFilePath(csFile) .FirstOrDefault(); if (docId != null) { documentIds[path] = docId; } else { log($"Cannot find document: {path}"); //td: add to project } } } private void postCompilation(Dictionary<string, RoslynCompilationAnalysis> projectAnalysis) { foreach (var project in _workspace.CurrentSolution.Projects) { var analysis = default(RoslynCompilationAnalysis); if (!projectAnalysis.TryGetValue(project.FilePath, out analysis)) continue; //post compilation try { var scope = new Scope(null); var compilation = new VSCompilation(project, scope); compilation.PerformAnalysis(analysis); if (!_workspace.TryApplyChanges(compilation.Project.Solution)) log($"Failed applies changes to solution"); } catch (Exception ex) { log($"Failed post-compile with: {ex.ToString()}"); } } } private void link(Dictionary<string, RoslynDocument> documents, Dictionary<string, DocumentId> ids, Scope scope) { foreach (var request in documents) { var docId = ids[request.Key]; var doc = _workspace.CurrentSolution.GetDocument(docId); var xs = request.Value; var semanticRoot = doc.GetSyntaxRootAsync().Result; xs.Mapper.Map(xs.SyntaxRoot, semanticRoot); var model = doc.GetSemanticModelAsync().Result; xs.Model = model; xs.applyChanges(CompilerStage.Semantical); } } private Dictionary<string, RoslynDocument> compile(EnvDTE.Project project, Func<ProjectItem, bool> filter, Scope scope, List<string> extensions, List<ProjectItem> codeFiles) { var documents = new Dictionary<string, RoslynDocument>(); var wait = new ManualResetEvent(false); var xsFiles = new List<ProjectItem>(); foreach (var item in project.ProjectItems.Cast<ProjectItem>()) { collectXsFiles(item, xsFiles, codeFiles); } foreach (var file in xsFiles) { if (!filter(file)) continue; var fileName = file.FileNames[0]; log($"Compiling {fileName}"); try { var text = File.ReadAllText(fileName); var doc = VSCompiler.Parse(text, scope, extensions); documents[fileName] = doc; } catch (Exception ex) { var inner = ex ?.InnerException .Message ?? "no inner exception"; log($"Failed compiling {fileName} with {ex.Message} \n {inner} \n {ex.StackTrace}"); } } return documents; } private void collectXsFiles(ProjectItem item, List<ProjectItem> result, List<ProjectItem> codeFiles) { if (isXsFile(item)) result.Add(item); else if (isXsCodeFile(item)) codeFiles.Add(item); if (item.ProjectItems != null) { foreach (var nested in item.ProjectItems.Cast<ProjectItem>()) collectXsFiles(nested, result, codeFiles); } } private bool isXsFile(ProjectItem item) { return item.Name.EndsWith(".xs"); } private bool isXsCodeFile(ProjectItem item) { return item.Name.EndsWith(".xs.cs"); } private bool isDirty(ProjectItem file) { return true; //td: } private Dictionary<string, CompilerFunc> loadExtensions(Dictionary<string, CompilerAnalysisFunc> analysis) { var result = new Dictionary<string, CompilerFunc>(); ensureDTE(); ensureNuget(); var packages = _nuget.GetInstalledPackages(); foreach (var package in packages) { var toolPath = Path.Combine(package.InstallPath, "tools"); if (!Directory.Exists(toolPath)) continue; //td: ask to restore packages var dlls = Directory.EnumerateFiles(toolPath) .Where(file => Path.GetExtension(file) == ".dll"); foreach (var dll in dlls) { var assembly = Assembly.LoadFrom(dll); if (assembly == null) continue; //var extension = loadReference(dll, name); var name = string.Empty; var compilationFunc = null as Action<RoslynCompilationAnalysis>; var extension = Loader<RoslynCompiler, RoslynCompilationAnalysis>.CreateFrom(assembly, out name, out compilationFunc); if (extension != null) { if (compilationFunc != null) { if (analysis != null) analysis[name] = compilationFunc; } log($"Found extension {name}"); result[name] = extension; } } } return result; } private bool saveCodeBehind(RoslynDocument doc, DocumentId id, bool mapLines) { doc.SyntaxRoot = doc.SyntaxRoot .NormalizeWhitespace(elasticTrivia: true); //td: optimize var solution = _workspace.CurrentSolution; if (mapLines) { var mapper = doc.Mapper; var vsDocument = solution.GetDocument(id); var filePath = vsDocument?.FilePath; if (filePath != null) filePath = filePath.Remove(filePath.Length - ".cs".Length); solution = solution.WithDocumentText(id, SourceText.From(doc.Mapper .RenderMapping(doc.SyntaxRoot, filePath))); } else solution = solution.WithDocumentSyntaxRoot(id, doc.SyntaxRoot); log($"Saved {id}"); return _workspace.TryApplyChanges(solution); } public override string GetFormatFilterList() { return "XS files (*.xs)\n*.xs\n"; } private LanguagePreferences _preferences; public override LanguagePreferences GetLanguagePreferences() { if (_preferences == null) _preferences = new LanguagePreferences(Site, typeof(ExcessLanguageService).GUID, Name); return _preferences; } private DocumentId GetDocumentId(IVsTextLines buffer) { var filePath = FilePathUtilities.GetFilePath(buffer) + ".cs"; var documents = _workspace .CurrentSolution .GetDocumentIdsWithFilePath(filePath); return documents.SingleOrDefault(); } public override IScanner GetScanner(IVsTextLines buffer) { return new Scanner(XSLanguage.Keywords); //td: } public override AuthoringScope ParseSource(ParseRequest req) { return new ExcessAuthoringScope(); } private OutputWindowPane _logPane; private void log(string what) { if (_logPane == null) { ensureDTE(); _logPane = _dte.ToolWindows.OutputWindow.OutputWindowPanes.Add("Excess"); } _logPane.OutputString(what + Environment.NewLine); } //create a hard reference to templating, so the dll is in included class Templating : RazorGenerator.Templating.RazorTemplateBase { } } }
34.08238
138
0.523164
[ "MIT" ]
xs-admin/Excess
Excess.VisualStudio/Excess.VisualStudio.Package/LanguageService.cs
14,896
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Enyim.Caching.Memcached.Results.StatusCodes; using Xunit; namespace Enyim.Caching.Tests { public class MemcachedClientGetTests : MemcachedClientTestsBase { [Fact] public void When_Getting_Existing_Item_Value_Is_Not_Null_And_Result_Is_Successful() { var key = GetUniqueKey("get"); var value = GetRandomString(); var storeResult = Store(key: key, value: value); StoreAssertPass(storeResult); var getResult = _client.ExecuteGet(key); GetAssertPass(getResult, value); } [Fact] public void When_Getting_Item_For_Invalid_Key_HasValue_Is_False_And_Result_Is_Not_Successful() { var key = GetUniqueKey("get"); var getResult = _client.ExecuteGet(key); Assert.True(getResult.StatusCode == (int)StatusCodeEnums.NotFound, "Invalid status code"); GetAssertFail(getResult); } [Fact] public void When_TryGetting_Existing_Item_Value_Is_Not_Null_And_Result_Is_Successful() { var key = GetUniqueKey("get"); var value = GetRandomString(); var storeResult = Store(key: key, value: value); StoreAssertPass(storeResult); object temp; var getResult = _client.ExecuteTryGet(key, out temp); GetAssertPass(getResult, temp); } [Fact] public void When_Generic_TryGetting_Existing_Item_Value_Is_Not_Null_And_Result_Is_Successful() { var key = GetUniqueKey("get"); var value = GetRandomString(); var storeResult = Store(key: key, value: value); StoreAssertPass(storeResult); string temp; var getResult = _client.ExecuteTryGet(key, out temp); GetAssertPass(getResult, temp); } [Fact] public void When_Generic_Getting_Existing_Item_Value_Is_Not_Null_And_Result_Is_Successful() { var key = GetUniqueKey("get"); var value = GetRandomString(); var storeResult = Store(key: key, value: value); StoreAssertPass(storeResult); var getResult = _client.ExecuteGet<string>(key); Assert.True(getResult.Success, "Success was false"); Assert.True(getResult.Cas > 0, "Cas value was 0"); Assert.True((getResult.StatusCode ?? 0) == 0, "StatusCode was neither 0 nor null"); Assert.Equal(value, getResult.Value); } [Fact] public void When_Getting_Multiple_Keys_Result_Is_Successful() { var keys = GetUniqueKeys().Distinct(); foreach (var key in keys) { Store(key: key, value: "Value for" + key); } var dict = _client.ExecuteGet(keys); Assert.Equal(keys.Count(), dict.Keys.Count); foreach (var key in dict.Keys) { Assert.True(dict[key].Success, "Get failed for key: " + key); } } [Fact] public void When_Getting_Byte_Result_Is_Successful() { var key = GetUniqueKey("Get"); const byte expectedValue = 1; Store(key: key, value: expectedValue); var getResult = _client.ExecuteGet(key); GetAssertPass(getResult, expectedValue); } [Fact] public void When_Getting_SByte_Result_Is_Successful() { var key = GetUniqueKey("Get"); const sbyte expectedValue = 1; Store(key: key, value: expectedValue); var getResult = _client.ExecuteGet(key); GetAssertPass(getResult, expectedValue); } [Fact] public async Task When_Getting_Empty_String_Async_Result_Is_Successful() { var key = GetUniqueKey("Get"); var empty = string.Empty; Store(key: key, value: empty); var getResult = await _client.GetValueAsync<string>(key); Assert.Equal(getResult, empty); } [Fact] public async Task GetValueOrCreateAsyncTest() { var key = "GetValueOrCreateAsyncTest_" + Guid.NewGuid(); var posts1 = await _client.GetValueOrCreateAsync( key, 10, async () => await GenerateValue()); Assert.NotNull(posts1); var posts2 = await _client.GetValueAsync<IEnumerable<BlogPost>>(key); Assert.NotNull(posts2); Assert.Equal(posts1.First().Title, posts2.First().Title); } private Task<IEnumerable<BlogPost>> GenerateValue() { var posts = new List<BlogPost>() { new BlogPost{ Title = "test title 1", Body = "test body 1" }, new BlogPost{ Title = "test title 2", Body = "test body 2" }, }; return Task.FromResult(posts.AsEnumerable()); } } internal class BlogPost { public string Title { get; set; } public string Tags { get; set; } public string Body { get; set; } } } #region [ License information ] /* ************************************************************ * * @author Couchbase <info@couchbase.com> * @copyright 2012 Couchbase, Inc. * @copyright 2012 Attila Kiskó, enyim.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ************************************************************/ #endregion
34.644444
102
0.579859
[ "Apache-2.0" ]
RexMorgan/EnyimMemcachedCore
Enyim.Caching.Tests/MemcachedClientGetTests.cs
6,239
C#
using System; using System.Collections.Generic; using System.Linq; using BattleSystem.Core.Random; namespace BattleSystem.Core.Characters.Targets { /// <summary> /// Calculates the action target as one of the characters at random. /// </summary> public class RandomCharacterActionTargetCalculator : IActionTargetCalculator { /// <summary> /// The random number generator. /// </summary> private readonly IRandom _random; /// <summary> /// Creates a new <see cref="RandomCharacterActionTargetCalculator"/> instance. /// </summary> /// <param name="random">The random number generator.</param> public RandomCharacterActionTargetCalculator(IRandom random) { _random = random ?? throw new ArgumentNullException(nameof(random)); } /// <inheritdoc /> public bool IsReactive => false; /// <inheritdoc /> public (bool success, IEnumerable<Character> targets) Calculate(Character user, IEnumerable<Character> otherCharacters) { var targets = otherCharacters.Prepend(user).ToArray(); var r = _random.Next(targets.Length); return (true, new[] { targets[r] }); } } }
32.512821
127
0.629338
[ "MIT" ]
phrasmotica/BattleSystem
BattleSystem.Core/Characters/Targets/RandomCharacterActionTargetCalculator.cs
1,270
C#
using Symbolica.Abstraction; using Symbolica.Expression; namespace Symbolica.Representation.Functions { internal sealed class GetRandom : IFunction { public GetRandom(FunctionId id, IParameters parameters) { Id = id; Parameters = parameters; } public FunctionId Id { get; } public IParameters Parameters { get; } public void Call(IState state, ICaller caller, IArguments arguments) { var address = arguments.Get(0); var size = (Bytes) (uint) arguments.Get(1).Constant; state.Memory.Write(address, state.Space.CreateGarbage(size.ToBits())); state.Stack.SetVariable(caller.Id, state.Space.CreateConstant(caller.Size, arguments.Get(1).Constant)); } } }
28.714286
115
0.630597
[ "MIT" ]
SymbolicaDev/Symbolica
src/Representation/Functions/GetRandom.cs
806
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Xml; using Microsoft.Build.Framework; using Xamarin.MacDev; using Xamarin.MacDev.Tasks; using Xamarin.Utils; namespace Xamarin.iOS.Tasks { public abstract class GetMlaunchArgumentsTaskBase : XamarinTask { [Required] public bool SdkIsSimulator { get; set; } [Required] public string SdkVersion { get; set; } [Required] public string AppBundlePath { get; set; } [Required] public string AppManifestPath { get; set; } [Required] public string SdkDevPath { get; set; } public string DeviceName { get; set; } public string LaunchApp { get; set; } public string InstallApp { get; set; } public bool CaptureOutput { get; set; } // Set to true to capture output. If StandardOutput|ErrorPath is not set, write to the current terminal's stdout/stderr (requires WaitForExit) public string StandardOutputPath { get; set; } // Set to a path to capture output there public string StandardErrorPath { get; set; } // Set to a path to capture output there public bool WaitForExit { get; set; } // Required for capturing stdout/stderr output [Required] public string MlaunchPath { get; set; } [Output] public string MlaunchArguments { get; set; } public IPhoneDeviceType DeviceType { get { switch (Platform) { case ApplePlatform.iOS: case ApplePlatform.TVOS: case ApplePlatform.WatchOS: var plist = PDictionary.FromFile (AppManifestPath); return plist.GetUIDeviceFamily (); default: throw new InvalidOperationException ($"Invalid platform: {Platform}"); } } } List<string> GetDeviceTypes () { var tmpfile = Path.GetTempFileName (); try { var output = new StringBuilder (); var result = ExecuteAsync (MlaunchPath, new string [] { "--listsim", tmpfile }, SdkDevPath).Result; if (result.ExitCode != 0) return null; // Which product family are we looking for? string productFamily; switch (DeviceType) { case IPhoneDeviceType.IPhone: case IPhoneDeviceType.IPad: case IPhoneDeviceType.TV: case IPhoneDeviceType.Watch: productFamily = DeviceType.ToString (); break; case IPhoneDeviceType.IPhoneAndIPad: productFamily = "IPad"; break; default: throw new InvalidOperationException ($"Invalid device type: {DeviceType}"); } // Load mlaunch's output var xml = new XmlDocument (); xml.Load (tmpfile); // Get the device types for the product family we're looking for var nodes = xml.SelectNodes ($"/MTouch/Simulator/SupportedDeviceTypes/SimDeviceType[ProductFamilyId='{productFamily}']").Cast<XmlNode> (); // Create a list of them all var deviceTypes = new List<(long Min, long Max, string Identifier)> (); foreach (var node in nodes) { var minRuntimeVersionValue = node.SelectSingleNode ("MinRuntimeVersion").InnerText; var maxRuntimeVersionValue = node.SelectSingleNode ("MaxRuntimeVersion").InnerText; var identifier = node.SelectSingleNode ("Identifier").InnerText; if (!long.TryParse (minRuntimeVersionValue, out var minRuntimeVersion)) continue; if (!long.TryParse (maxRuntimeVersionValue, out var maxRuntimeVersion)) continue; deviceTypes.Add ((minRuntimeVersion, maxRuntimeVersion, identifier)); } // Sort by minRuntimeVersion, this is a rudimentary way of sorting so that the last device is at the end. deviceTypes.Sort ((a, b) => a.Min.CompareTo (b.Min)); // Return the sorted list return deviceTypes.Select (v => v.Identifier).ToList (); } finally { File.Delete (tmpfile); } } protected string GenerateCommandLineCommands () { var sb = new CommandLineArgumentBuilder (); if (!string.IsNullOrEmpty (LaunchApp)) { sb.Add (SdkIsSimulator ? "--launchsim" : "--launchdev"); sb.AddQuoted (LaunchApp); } if (!string.IsNullOrEmpty (InstallApp)) { sb.Add (SdkIsSimulator ? "--installsim" : "--installdev"); sb.AddQuoted (InstallApp); } if (SdkIsSimulator && string.IsNullOrEmpty (DeviceName)) { var simruntime = $"com.apple.CoreSimulator.SimRuntime.{PlatformName}-{SdkVersion.Replace ('.', '-')}"; var simdevicetypes = GetDeviceTypes (); string simdevicetype; if (simdevicetypes?.Count > 0) { // Use the latest device type we can find. This seems to be what Xcode does by default. simdevicetype = simdevicetypes.Last (); } else { // We couldn't find any device types, so pick one. switch (Platform) { case ApplePlatform.iOS: // Don't try to launch an iPad-only app on an iPhone if (DeviceType == IPhoneDeviceType.IPad) { simdevicetype = "com.apple.CoreSimulator.SimDeviceType.iPad--7th-generation-"; } else { simdevicetype = "com.apple.CoreSimulator.SimDeviceType.iPhone-11"; } break; case ApplePlatform.TVOS: simdevicetype = "com.apple.CoreSimulator.SimDeviceType.Apple-TV-4K-1080p"; break; case ApplePlatform.WatchOS: simdevicetype = "com.apple.CoreSimulator.SimDeviceType.Apple-Watch-Series-5-40mm"; break; default: throw new InvalidOperationException ($"Invalid platform: {Platform}"); } } DeviceName = $":v2:runtime={simruntime},devicetype={simdevicetype}"; } if (!string.IsNullOrEmpty (DeviceName)) { if (SdkIsSimulator) { sb.Add ("--device"); } else { sb.Add ("--devname"); } sb.AddQuoted (DeviceName); } if (CaptureOutput && string.IsNullOrEmpty (StandardOutputPath)) StandardOutputPath = GetTerminalName (1); if (CaptureOutput && string.IsNullOrEmpty (StandardErrorPath)) StandardErrorPath = GetTerminalName (2); if (!string.IsNullOrEmpty (StandardOutputPath)) { sb.Add ("--stdout"); sb.AddQuoted (StandardOutputPath); } if (!string.IsNullOrEmpty (StandardErrorPath)) { sb.Add ("--stderr"); sb.AddQuoted (StandardErrorPath); } if (WaitForExit) sb.Add ("--wait-for-exit"); return sb.ToString (); } static string GetTerminalName (int fd) { if (isatty (fd) != 1) return null; return Marshal.PtrToStringAuto (ttyname (fd)); } public override bool Execute () { MlaunchArguments = GenerateCommandLineCommands (); return !Log.HasLoggedErrors; } [DllImport ("/usr/lib/libc.dylib")] extern static IntPtr ttyname (int filedes); [DllImport ("/usr/lib/libc.dylib")] extern static int isatty (int fd); } }
31.242857
184
0.684804
[ "BSD-3-Clause" ]
eerhardt/xamarin-macios
msbuild/Xamarin.iOS.Tasks.Core/Tasks/GetMlaunchArgumentsTaskBase.cs
6,561
C#
using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Http.Filters; using System.Net.Http; public class ValidateModelAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { var modelState = actionExecutedContext.ActionContext.ModelState; if (!modelState.IsValid) actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, modelState); base.OnActionExecuted(actionExecutedContext); } }
32.882353
96
0.765653
[ "CC0-1.0" ]
firepacket/Trustfreemarket
Filters/ValidateFilterAttribute.cs
561
C#
// Copyright 2009-2020 Josh Close and Contributors // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. // https://github.com/JoshClose/CsvHelper using System; using System.IO; using CsvHelper.Configuration; using System.Threading.Tasks; // This file is generated from a T4 template. // Modifying it directly won't do you any good. namespace CsvHelper { /// <summary> /// Reads fields from a <see cref="TextReader"/>. /// </summary> public partial class CsvFieldReader : IFieldReader { private ReadingContext context; private bool disposed; /// <summary> /// Gets the reading context. /// </summary> public virtual ReadingContext Context => context; /// <summary> /// Gets a value indicating if the buffer is empty. /// True if the buffer is empty, otherwise false. /// </summary> public virtual bool IsBufferEmpty => context.BufferPosition >= context.CharsRead; /// <summary> /// Fills the buffer. /// </summary> /// <returns>True if there is more data left. /// False if all the data has been read.</returns> public virtual bool FillBuffer() { if (!IsBufferEmpty) { throw new InvalidOperationException($"The buffer can't be filled if it's not empty."); } if (context.Buffer.Length == 0) { context.Buffer = new char[context.ParserConfiguration.BufferSize]; } if (context.CharsRead > 0) { // Create a new buffer with extra room for what is left from // the old buffer. Copy the remaining contents onto the new buffer. var charactersUsed = Math.Min(context.FieldStartPosition, context.RawRecordStartPosition); var bufferLeft = context.CharsRead - charactersUsed; var bufferUsed = context.CharsRead - bufferLeft; var tempBuffer = new char[bufferLeft + context.ParserConfiguration.BufferSize]; Array.Copy(context.Buffer, charactersUsed, tempBuffer, 0, bufferLeft); context.Buffer = tempBuffer; context.BufferPosition = context.BufferPosition - bufferUsed; context.FieldStartPosition = context.FieldStartPosition - bufferUsed; context.FieldEndPosition = Math.Max(context.FieldEndPosition - bufferUsed, 0); context.RawRecordStartPosition = context.RawRecordStartPosition - bufferUsed; context.RawRecordEndPosition = context.RawRecordEndPosition - bufferUsed; } context.CharsRead = context.Reader.Read(context.Buffer, context.BufferPosition, context.ParserConfiguration.BufferSize); if (context.CharsRead == 0) { // End of file return false; } // Add the char count from the previous buffer that was copied onto this one. context.CharsRead += context.BufferPosition; return true; } /// <summary> /// Fills the buffer. /// </summary> /// <returns>True if there is more data left. /// False if all the data has been read.</returns> public virtual async Task<bool> FillBufferAsync() { if (!IsBufferEmpty) { throw new InvalidOperationException($"The buffer can't be filled if it's not empty."); } if (context.Buffer.Length == 0) { context.Buffer = new char[context.ParserConfiguration.BufferSize]; } if (context.CharsRead > 0) { // Create a new buffer with extra room for what is left from // the old buffer. Copy the remaining contents onto the new buffer. var charactersUsed = Math.Min(context.FieldStartPosition, context.RawRecordStartPosition); var bufferLeft = context.CharsRead - charactersUsed; var bufferUsed = context.CharsRead - bufferLeft; var tempBuffer = new char[bufferLeft + context.ParserConfiguration.BufferSize]; Array.Copy(context.Buffer, charactersUsed, tempBuffer, 0, bufferLeft); context.Buffer = tempBuffer; context.BufferPosition = context.BufferPosition - bufferUsed; context.FieldStartPosition = context.FieldStartPosition - bufferUsed; context.FieldEndPosition = Math.Max(context.FieldEndPosition - bufferUsed, 0); context.RawRecordStartPosition = context.RawRecordStartPosition - bufferUsed; context.RawRecordEndPosition = context.RawRecordEndPosition - bufferUsed; } context.CharsRead = await context.Reader.ReadAsync(context.Buffer, context.BufferPosition, context.ParserConfiguration.BufferSize).ConfigureAwait(false); if (context.CharsRead == 0) { // End of file return false; } // Add the char count from the previous buffer that was copied onto this one. context.CharsRead += context.BufferPosition; return true; } /// <summary> /// Creates a new <see cref="CsvFieldReader"/> using the given /// <see cref="TextReader"/> and <see cref="Configuration.CsvConfiguration"/>. /// </summary> /// <param name="reader">The text reader.</param> /// <param name="configuration">The configuration.</param> public CsvFieldReader(TextReader reader, Configuration.CsvConfiguration configuration) : this(reader, configuration, false) { } /// <summary> /// Creates a new <see cref="CsvFieldReader"/> using the given /// <see cref="TextReader"/>, <see cref="Configuration.CsvConfiguration"/> /// and leaveOpen flag. /// </summary> /// <param name="reader">The text reader.</param> /// <param name="configuration">The configuration.</param> /// <param name="leaveOpen">A value indicating if the <see cref="TextReader"/> should be left open when disposing.</param> public CsvFieldReader(TextReader reader, Configuration.CsvConfiguration configuration, bool leaveOpen) { context = new ReadingContext(reader, configuration, leaveOpen); } /// <summary> /// Gets the next char as an <see cref="int"/>. /// </summary> public virtual int GetChar() { var c = context.Buffer[context.BufferPosition]; context.BufferPosition++; context.RawRecordEndPosition = context.BufferPosition; context.CharPosition++; return c; } /// <summary> /// Gets the field. This will append any reading progress. /// </summary> /// <returns>The current field.</returns> public virtual string GetField() { AppendField(); if (context.IsFieldBad) { context.ParserConfiguration.BadDataFound?.Invoke(context); } context.IsFieldBad = false; var result = context.FieldBuilder.ToString(); context.FieldBuilder.Clear(); return result; } /// <summary> /// Appends the current reading progress. /// </summary> public virtual void AppendField() { if (context.ParserConfiguration.CountBytes) { context.BytePosition += context.ParserConfiguration.Encoding.GetByteCount(context.Buffer, context.RawRecordStartPosition, context.BufferPosition - context.RawRecordStartPosition); } context.RawRecordBuilder.Append(new string(context.Buffer, context.RawRecordStartPosition, context.RawRecordEndPosition - context.RawRecordStartPosition)); context.RawRecordStartPosition = context.RawRecordEndPosition; var length = context.FieldEndPosition - context.FieldStartPosition; context.FieldBuilder.Append(new string(context.Buffer, context.FieldStartPosition, length)); context.FieldStartPosition = context.BufferPosition; context.FieldEndPosition = 0; } /// <summary> /// Move's the buffer position according to the given offset. /// </summary> /// <param name="offset">The offset to move the buffer.</param> public virtual void SetBufferPosition(int offset = 0) { var position = context.BufferPosition + offset; if (position >= 0) { context.BufferPosition = position; } } /// <summary> /// Sets the start of the field to the current buffer position. /// </summary> /// <param name="offset">An offset for the field start. /// The offset should be less than 1.</param> public virtual void SetFieldStart(int offset = 0) { var position = context.BufferPosition + offset; if (position >= 0) { context.FieldStartPosition = position; } } /// <summary> /// Sets the end of the field to the current buffer position. /// </summary> /// <param name="offset">An offset for the field start. /// The offset should be less than 1.</param> public virtual void SetFieldEnd(int offset = 0) { var position = context.BufferPosition + offset; if (position >= 0) { context.FieldEndPosition = position; } } /// <summary> /// Sets the raw record start to the current buffer position; /// </summary> /// <param name="offset">An offset for the raw record start. /// The offset should be less than 1.</param> public virtual void SetRawRecordStart(int offset) { var position = context.BufferPosition + offset; if (position >= 0) { context.RawRecordStartPosition = position; } } /// <summary> /// Sets the raw record end to the current buffer position. /// </summary> /// <param name="offset">An offset for the raw record end. /// The offset should be less than 1.</param> public virtual void SetRawRecordEnd(int offset) { var position = context.BufferPosition + offset; if (position >= 0) { context.RawRecordEndPosition = position; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public virtual void Dispose() { Dispose(!context?.LeaveOpen ?? true); GC.SuppressFinalize(this); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <param name="disposing">True if the instance needs to be disposed of.</param> protected virtual void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { context?.Dispose(); } context = null; disposed = true; } } }
32.498361
183
0.702684
[ "MIT" ]
unity-game-framework/ugf-csv
Packages/UGF.Csv/Runtime/Plugins/CsvHelper/CsvFieldReader.cs
9,914
C#
/*************************************************************************** * Copyright Andy Brummer 2004-2005 * * This code is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * This code may be used in compiled form in any way you desire. This * file may be redistributed unmodified by any means provided it is * not sold for profit without the authors written consent, and * providing that this notice and the authors name is included. If * the source code in this file is used in any commercial application * then a simple email would be nice. * **************************************************************************/ using System; using System.Collections; namespace AutoDarkTheme.Schedule.ScheduledItems { /// <summary> /// The event queue is a collection of scheduled items that represents the union of all child scheduled items. /// This is useful for events that occur every 10 minutes or at multiple intervals not covered by the simple /// scheduled items. /// </summary> public class EventQueue : IScheduledItem { public EventQueue() { _List = new ArrayList(); } /// <summary> /// Adds a ScheduledTime to the queue. /// </summary> /// <param name="time">The scheduled time to add</param> public void Add(IScheduledItem time) { _List.Add(time); } /// <summary> /// Clears the list of scheduled times. /// </summary> public void Clear() { _List.Clear(); } /// <summary> /// Adds the running time for all events in the list. /// </summary> /// <param name="Begin">The beginning time of the interval</param> /// <param name="End">The end time of the interval</param> /// <param name="List">The list to add times to.</param> public void AddEventsInInterval(DateTime Begin, DateTime End, ArrayList List) { foreach(IScheduledItem st in _List) st.AddEventsInInterval(Begin, End, List); List.Sort(); } /// <summary> /// Returns the first time after the starting time for all events in the list. /// </summary> /// <param name="time">The starting time.</param> /// <param name="AllowExact">If this is true then it allows the return time to match the time parameter, false forces the return time to be greater then the time parameter</param> /// <returns>Either the next event after the input time or greater or equal to depending on the AllowExact parameter.</returns> public DateTime NextRunTime(DateTime time, bool AllowExact) { DateTime next = DateTime.MaxValue; //Get minimum datetime from the list. foreach(IScheduledItem st in _List) { DateTime Proposed = st.NextRunTime(time, AllowExact); next = (Proposed < next) ? Proposed : next; } return next; } private ArrayList _List; } }
35.419753
182
0.642384
[ "MIT" ]
biosmanager/AutoDarkTheme
Editor/Schedule/ScheduledItems/EventQueue.cs
2,869
C#
/* Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.ComponentModel; using Tizen.NUI.BaseComponents; using Tizen.NUI.Accessibility; namespace Tizen.NUI.Components { /// <summary> /// DefaultGridItem is one kind of common component, a DefaultGridItem clearly describes what action will occur when the user selects it. /// DefaultGridItem may contain text or an icon. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public partial class DefaultGridItem : RecyclerViewItem { private TextLabel itemLabel; private ImageView itemImage; private View itemBadge; private LabelOrientation labelOrientation; private bool layoutChanged; private DefaultGridItemStyle ItemStyle => ViewStyle as DefaultGridItemStyle; static DefaultGridItem() { } /// <summary> /// Creates a new instance of DefaultGridItem. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public DefaultGridItem() : base() { } /// <summary> /// Creates a new instance of DefaultGridItem with style /// </summary> /// <param name="style=">Create DefaultGridItem by special style defined in UX.</param> [EditorBrowsable(EditorBrowsableState.Never)] public DefaultGridItem(string style) : base(style) { } /// <summary> /// Creates a new instance of DefaultGridItem with style /// </summary> /// <param name="itemStyle=">Create DefaultGridItem by style customized by user.</param> [EditorBrowsable(EditorBrowsableState.Never)] public DefaultGridItem(DefaultGridItemStyle itemStyle) : base(itemStyle) { } /// <summary> /// Label orientation. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public enum LabelOrientation { /// <summary> /// Outside of image bottom edge. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] OutsideBottom, /// <summary> /// Outside of image top edge. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] OutsideTop, /// <summary> /// inside of image bottom edge. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] InsideBottom, /// <summary> /// inside of image top edge. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] InsideTop, } /// <summary> /// DefaultGridItem's icon part. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public ImageView Image { get { if (itemImage == null) { itemImage = CreateImage(ItemStyle.Image); if (itemImage != null) { Add(itemImage); itemImage.Relayout += OnImageRelayout; layoutChanged = true; } } return itemImage; } internal set { if (itemImage != null) Remove(itemImage); itemImage = value; if (itemImage != null) { //FIXME: User applied image's style can be overwritten! if (ItemStyle != null) itemImage.ApplyStyle(ItemStyle.Image); Add(itemImage); itemImage.Relayout += OnImageRelayout; } layoutChanged = true; } } /// <summary> /// DefaultGridItem's badge object. will be placed in right-top edge. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public View Badge { get { return GetValue(BadgeProperty) as View; } set { SetValue(BadgeProperty, value); NotifyPropertyChanged(); } } private View InternalBadge { get { return itemBadge; } set { if (itemBadge != null) Remove(itemBadge); itemBadge = value; if (itemBadge != null) { //FIXME: User applied badge's style can be overwritten! if (ItemStyle != null) itemBadge.ApplyStyle(ItemStyle.Badge); Add(itemBadge); } layoutChanged = true; } } /* open when ImageView using Uri not string /// <summary> /// Image image's resource url in DefaultGridItem. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public string ImageUrl { get { return Image.ResourceUrl; } set { Image.ResourceUrl = value; } } */ /// <summary> /// DefaultGridItem's text part. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public TextLabel Label { get { if (itemLabel == null) { itemLabel = CreateLabel(ItemStyle.Label); if (itemLabel != null) { Add(itemLabel); layoutChanged = true; } } return itemLabel; } internal set { itemLabel = value; layoutChanged = true; } } /// <summary> /// The text of DefaultGridItem. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public string Text { get { return GetValue(TextProperty) as string; } set { SetValue(TextProperty, value); NotifyPropertyChanged(); } } private string InternalText { get { return Label.Text; } set { Label.Text = value; } } /// <summary> /// Label relative orientation with image in DefaultGridItem. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public LabelOrientation LabelOrientationType { get { return (Tizen.NUI.Components.DefaultGridItem.LabelOrientation)GetValue(LabelOrientationTypeProperty); } set { SetValue(LabelOrientationTypeProperty, value); NotifyPropertyChanged(); } } private Tizen.NUI.Components.DefaultGridItem.LabelOrientation InternalLabelOrientationType { get { return labelOrientation; } set { labelOrientation = value; layoutChanged = true; } } /// <summary> /// Apply style to DefaultLinearItemStyle. /// </summary> /// <param name="viewStyle">The style to apply.</param> [EditorBrowsable(EditorBrowsableState.Never)] public override void ApplyStyle(ViewStyle viewStyle) { base.ApplyStyle(viewStyle); if (viewStyle != null && viewStyle is DefaultGridItemStyle defaultStyle) { if (itemLabel != null) itemLabel.ApplyStyle(defaultStyle.Label); if (itemImage != null) itemImage.ApplyStyle(defaultStyle.Image); if (itemBadge != null) itemBadge.ApplyStyle(defaultStyle.Badge); } } /// <summary> /// Creates Item's text part. /// </summary> /// <return>The created Item's text part.</return> [EditorBrowsable(EditorBrowsableState.Never)] protected virtual TextLabel CreateLabel(TextLabelStyle textStyle) { return new TextLabel(textStyle) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; } /// <summary> /// Creates Item's icon part. /// </summary> /// <return>The created Item's icon part.</return> [EditorBrowsable(EditorBrowsableState.Never)] protected virtual ImageView CreateImage(ImageViewStyle imageStyle) { return new ImageView(imageStyle); } /// <inheritdoc/> [EditorBrowsable(EditorBrowsableState.Never)] protected override void MeasureChild() { //nothing to do. if (itemLabel) { var pad = Padding; var margin = itemLabel.Margin; itemLabel.SizeWidth = SizeWidth - pad.Start - pad.End - margin.Start - margin.End; } } /// <inheritdoc/> [EditorBrowsable(EditorBrowsableState.Never)] protected override void LayoutChild() { if (!layoutChanged) return; if (itemImage == null) return; layoutChanged = false; RelativeLayout.SetLeftTarget(itemImage, this); RelativeLayout.SetLeftRelativeOffset(itemImage, 0.0F); RelativeLayout.SetRightTarget(itemImage, this); RelativeLayout.SetRightRelativeOffset(itemImage, 1.0F); RelativeLayout.SetHorizontalAlignment(itemImage, RelativeLayout.Alignment.Center); if (itemLabel != null) { itemLabel.RaiseAbove(itemImage); RelativeLayout.SetLeftTarget(itemLabel, itemImage); RelativeLayout.SetLeftRelativeOffset(itemLabel, 0.0F); RelativeLayout.SetRightTarget(itemLabel, itemImage); RelativeLayout.SetRightRelativeOffset(itemLabel, 1.0F); RelativeLayout.SetHorizontalAlignment(itemLabel, RelativeLayout.Alignment.Center); RelativeLayout.SetFillHorizontal(itemLabel, true); } else { RelativeLayout.SetTopTarget(itemImage, this); RelativeLayout.SetTopRelativeOffset(itemImage, 0.0F); RelativeLayout.SetBottomTarget(itemImage, this); RelativeLayout.SetBottomRelativeOffset(itemImage, 1.0F); RelativeLayout.SetVerticalAlignment(itemImage, RelativeLayout.Alignment.Center); } if (itemBadge) { itemBadge.RaiseAbove(itemImage); RelativeLayout.SetLeftTarget(itemBadge, itemImage); RelativeLayout.SetLeftRelativeOffset(itemBadge, 1.0F); RelativeLayout.SetRightTarget(itemBadge, itemImage); RelativeLayout.SetRightRelativeOffset(itemBadge, 1.0F); RelativeLayout.SetHorizontalAlignment(itemBadge, RelativeLayout.Alignment.End); } switch (labelOrientation) { case LabelOrientation.OutsideBottom: if (itemLabel != null) { RelativeLayout.SetTopTarget(itemLabel, this); RelativeLayout.SetTopRelativeOffset(itemLabel, 1.0F); RelativeLayout.SetBottomTarget(itemLabel, this); RelativeLayout.SetBottomRelativeOffset(itemLabel, 1.0F); RelativeLayout.SetVerticalAlignment(itemLabel, RelativeLayout.Alignment.End); RelativeLayout.SetTopTarget(itemImage, this); RelativeLayout.SetTopRelativeOffset(itemImage, 0.0F); RelativeLayout.SetBottomTarget(itemImage, itemLabel); RelativeLayout.SetBottomRelativeOffset(itemImage, 0.0F); RelativeLayout.SetVerticalAlignment(itemImage, RelativeLayout.Alignment.Center); } if (itemBadge) { RelativeLayout.SetTopTarget(itemBadge, itemImage); RelativeLayout.SetTopRelativeOffset(itemBadge, 0.0F); RelativeLayout.SetBottomTarget(itemBadge, itemImage); RelativeLayout.SetBottomRelativeOffset(itemBadge, 0.0F); RelativeLayout.SetVerticalAlignment(itemBadge, RelativeLayout.Alignment.Start); } break; case LabelOrientation.OutsideTop: if (itemLabel != null) { RelativeLayout.SetTopTarget(itemLabel, this); RelativeLayout.SetTopRelativeOffset(itemLabel, 0.0F); RelativeLayout.SetBottomTarget(itemLabel, this); RelativeLayout.SetBottomRelativeOffset(itemLabel, 0.0F); RelativeLayout.SetVerticalAlignment(itemLabel, RelativeLayout.Alignment.Start); RelativeLayout.SetTopTarget(itemImage, itemLabel); RelativeLayout.SetTopRelativeOffset(itemImage, 1.0F); RelativeLayout.SetBottomTarget(itemImage, this); RelativeLayout.SetBottomRelativeOffset(itemImage, 1.0F); RelativeLayout.SetVerticalAlignment(itemImage, RelativeLayout.Alignment.Center); } if (itemBadge) { RelativeLayout.SetTopTarget(itemBadge, itemImage); RelativeLayout.SetTopRelativeOffset(itemBadge, 1.0F); RelativeLayout.SetBottomTarget(itemBadge, itemImage); RelativeLayout.SetBottomRelativeOffset(itemBadge, 1.0F); RelativeLayout.SetVerticalAlignment(itemBadge, RelativeLayout.Alignment.End); } break; case LabelOrientation.InsideBottom: if (itemLabel != null) { RelativeLayout.SetTopTarget(itemLabel, this); RelativeLayout.SetTopRelativeOffset(itemLabel, 1.0F); RelativeLayout.SetBottomTarget(itemLabel, this); RelativeLayout.SetBottomRelativeOffset(itemLabel, 1.0F); RelativeLayout.SetVerticalAlignment(itemLabel, RelativeLayout.Alignment.End); Console.WriteLine("Item Label Inside Bottom!"); RelativeLayout.SetTopTarget(itemImage, this); RelativeLayout.SetTopRelativeOffset(itemImage, 0.0F); RelativeLayout.SetBottomTarget(itemImage, this); RelativeLayout.SetBottomRelativeOffset(itemImage, 1.0F); RelativeLayout.SetVerticalAlignment(itemImage, RelativeLayout.Alignment.Center); } if (itemBadge) { RelativeLayout.SetTopTarget(itemBadge, itemImage); RelativeLayout.SetTopRelativeOffset(itemBadge, 0.0F); RelativeLayout.SetBottomTarget(itemBadge, itemImage); RelativeLayout.SetBottomRelativeOffset(itemBadge, 0.0F); RelativeLayout.SetVerticalAlignment(itemBadge, RelativeLayout.Alignment.Start); } break; case LabelOrientation.InsideTop: if (itemLabel != null) { RelativeLayout.SetTopTarget(itemLabel, this); RelativeLayout.SetTopRelativeOffset(itemLabel, 0.0F); RelativeLayout.SetBottomTarget(itemLabel, this); RelativeLayout.SetBottomRelativeOffset(itemLabel, 0.0F); RelativeLayout.SetVerticalAlignment(itemLabel, RelativeLayout.Alignment.Start); RelativeLayout.SetTopTarget(itemImage, this); RelativeLayout.SetTopRelativeOffset(itemImage, 0.0F); RelativeLayout.SetBottomTarget(itemImage, this); RelativeLayout.SetBottomRelativeOffset(itemImage, 1.0F); RelativeLayout.SetVerticalAlignment(itemImage, RelativeLayout.Alignment.Center); } if (itemBadge) { RelativeLayout.SetTopTarget(itemBadge, itemImage); RelativeLayout.SetTopRelativeOffset(itemBadge, 1.0F); RelativeLayout.SetBottomTarget(itemBadge, itemImage); RelativeLayout.SetBottomRelativeOffset(itemBadge, 1.0F); RelativeLayout.SetVerticalAlignment(itemBadge, RelativeLayout.Alignment.End); } break; } } /// <summary> /// Gets accessibility name. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] protected override string AccessibilityGetName() { return itemLabel.Text; } /// <summary> /// Initializes AT-SPI object. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public override void OnInitialize() { base.OnInitialize(); Layout = new RelativeLayout(); layoutChanged = true; LayoutDirectionChanged += OnLayoutDirectionChanged; EnableControlStatePropagation = true; } /// <summary> /// Dispose Item and all children on it. /// </summary> /// <param name="type">Dispose type.</param> [EditorBrowsable(EditorBrowsableState.Never)] protected override void Dispose(DisposeTypes type) { if (disposed) { return; } if (type == DisposeTypes.Explicit) { //Extension : Extension?.OnDispose(this); // Arugable to disposing user-created members. /* if (itemBadge != null) { Utility.Dispose(itemBadge); } */ if (itemImage != null) { Utility.Dispose(itemImage); itemImage = null; } if (itemLabel != null) { Utility.Dispose(itemLabel); itemLabel = null; } } base.Dispose(type); } private void OnLayoutDirectionChanged(object sender, LayoutDirectionChangedEventArgs e) { MeasureChild(); LayoutChild(); } private void OnImageRelayout(object sender, EventArgs e) { MeasureChild(); LayoutChild(); } } }
36.769369
141
0.525947
[ "Apache-2.0", "MIT" ]
lol-github/TizenFX
src/Tizen.NUI.Components/Controls/RecyclerView/Item/DefaultGridItem.cs
20,407
C#
#region License /* LzxDecoder.cs - C# port of libmsport's lzxd.c * Copyright 2003-2004 Stuart Caie * Copyright 2011 Ali Scissons * * Released under a dual MSPL/LGPL license. * See lzxdecoder.LICENSE for details. */ #endregion #region Using Statements using System; #endregion using System.IO; public class LzxDecoder { public static uint[] position_base = null; public static byte[] extra_bits = null; private LzxState m_state; public LzxDecoder (int window) { uint wndsize = (uint)(1 << window); int posn_slots; // Setup proper exception. if(window < 15 || window > 21) throw new UnsupportedWindowSizeRange(); // Let's initialize our state. m_state = new LzxState(); m_state.actual_size = 0; m_state.window = new byte[wndsize]; for(int i = 0; i < wndsize; i++) m_state.window[i] = 0xDC; m_state.actual_size = wndsize; m_state.window_size = wndsize; m_state.window_posn = 0; // Initialize static tables. if(extra_bits == null) { extra_bits = new byte[52]; for(int i = 0, j = 0; i <= 50; i += 2) { extra_bits[i] = extra_bits[i+1] = (byte)j; if ((i != 0) && (j < 17)) j++; } } if(position_base == null) { position_base = new uint[51]; for(int i = 0, j = 0; i <= 50; i++) { position_base[i] = (uint)j; j += 1 << extra_bits[i]; } } // Calculate required position slots. if(window == 20) posn_slots = 42; else if(window == 21) posn_slots = 50; else posn_slots = window << 1; m_state.R0 = m_state.R1 = m_state.R2 = 1; m_state.main_elements = (ushort)(LzxConstants.NUM_CHARS + (posn_slots << 3)); m_state.header_read = 0; m_state.frames_read = 0; m_state.block_remaining = 0; m_state.block_type = LzxConstants.BLOCKTYPE.INVALID; m_state.intel_curpos = 0; m_state.intel_started = 0; m_state.PRETREE_table = new ushort[(1 << LzxConstants.PRETREE_TABLEBITS) + (LzxConstants.PRETREE_MAXSYMBOLS << 1)]; m_state.PRETREE_len = new byte[LzxConstants.PRETREE_MAXSYMBOLS + LzxConstants.LENTABLE_SAFETY]; m_state.MAINTREE_table = new ushort[(1 << LzxConstants.MAINTREE_TABLEBITS) + (LzxConstants.MAINTREE_MAXSYMBOLS << 1)]; m_state.MAINTREE_len = new byte[LzxConstants.MAINTREE_MAXSYMBOLS + LzxConstants.LENTABLE_SAFETY]; m_state.LENGTH_table = new ushort[(1 << LzxConstants.LENGTH_TABLEBITS) + (LzxConstants.LENGTH_MAXSYMBOLS << 1)]; m_state.LENGTH_len = new byte[LzxConstants.LENGTH_MAXSYMBOLS + LzxConstants.LENTABLE_SAFETY]; m_state.ALIGNED_table = new ushort[(1 << LzxConstants.ALIGNED_TABLEBITS) + (LzxConstants.ALIGNED_MAXSYMBOLS << 1)]; m_state.ALIGNED_len = new byte[LzxConstants.ALIGNED_MAXSYMBOLS + LzxConstants.LENTABLE_SAFETY]; // Initialize tables to 0 (because deltas will be applied to them). for(int i = 0; i < LzxConstants.MAINTREE_MAXSYMBOLS; i++) m_state.MAINTREE_len[i] = 0; for(int i = 0; i < LzxConstants.LENGTH_MAXSYMBOLS; i++) m_state.LENGTH_len[i] = 0; } public int Decompress(Stream inData, int inLen, Stream outData, int outLen) { BitBuffer bitbuf = new BitBuffer(inData); long startpos = inData.Position; long endpos = inData.Position + inLen; byte[] window = m_state.window; uint window_posn = m_state.window_posn; uint window_size = m_state.window_size; uint R0 = m_state.R0; uint R1 = m_state.R1; uint R2 = m_state.R2; uint i, j; int togo = outLen, this_run, main_element, match_length, match_offset, length_footer, extra, verbatim_bits; int rundest, runsrc, copy_length, aligned_bits; bitbuf.InitBitStream(); // Read header if necessary. if(m_state.header_read == 0) { uint intel = bitbuf.ReadBits(1); if(intel != 0) { // Read the filesize. i = bitbuf.ReadBits(16); j = bitbuf.ReadBits(16); m_state.intel_filesize = (int)((i << 16) | j); } m_state.header_read = 1; } // Main decoding loop. while(togo > 0) { // last block finished, new block expected. if(m_state.block_remaining == 0) { // TODO may screw something up here if(m_state.block_type == LzxConstants.BLOCKTYPE.UNCOMPRESSED) { if((m_state.block_length & 1) == 1) inData.ReadByte(); /* realign bitstream to word */ bitbuf.InitBitStream(); } m_state.block_type = (LzxConstants.BLOCKTYPE)bitbuf.ReadBits(3);; i = bitbuf.ReadBits(16); j = bitbuf.ReadBits(8); m_state.block_remaining = m_state.block_length = (uint)((i << 8) | j); switch(m_state.block_type) { case LzxConstants.BLOCKTYPE.ALIGNED: for(i = 0, j = 0; i < 8; i++) { j = bitbuf.ReadBits(3); m_state.ALIGNED_len[i] = (byte)j; } MakeDecodeTable(LzxConstants.ALIGNED_MAXSYMBOLS, LzxConstants.ALIGNED_TABLEBITS, m_state.ALIGNED_len, m_state.ALIGNED_table); // Rest of aligned header is same as verbatim goto case LzxConstants.BLOCKTYPE.VERBATIM; case LzxConstants.BLOCKTYPE.VERBATIM: ReadLengths(m_state.MAINTREE_len, 0, 256, bitbuf); ReadLengths(m_state.MAINTREE_len, 256, m_state.main_elements, bitbuf); MakeDecodeTable(LzxConstants.MAINTREE_MAXSYMBOLS, LzxConstants.MAINTREE_TABLEBITS, m_state.MAINTREE_len, m_state.MAINTREE_table); if(m_state.MAINTREE_len[0xE8] != 0) m_state.intel_started = 1; ReadLengths(m_state.LENGTH_len, 0, LzxConstants.NUM_SECONDARY_LENGTHS, bitbuf); MakeDecodeTable(LzxConstants.LENGTH_MAXSYMBOLS, LzxConstants.LENGTH_TABLEBITS, m_state.LENGTH_len, m_state.LENGTH_table); break; case LzxConstants.BLOCKTYPE.UNCOMPRESSED: m_state.intel_started = 1; // Because we can't assume otherwise. bitbuf.EnsureBits(16); // Get up to 16 pad bits into the buffer. if(bitbuf.GetBitsLeft() > 16) inData.Seek(-2, SeekOrigin.Current); /* and align the bitstream! */ byte hi, mh, ml, lo; lo = (byte)inData.ReadByte(); ml = (byte)inData.ReadByte(); mh = (byte)inData.ReadByte(); hi = (byte)inData.ReadByte(); R0 = (uint)(lo | ml << 8 | mh << 16 | hi << 24); lo = (byte)inData.ReadByte(); ml = (byte)inData.ReadByte(); mh = (byte)inData.ReadByte(); hi = (byte)inData.ReadByte(); R1 = (uint)(lo | ml << 8 | mh << 16 | hi << 24); lo = (byte)inData.ReadByte(); ml = (byte)inData.ReadByte(); mh = (byte)inData.ReadByte(); hi = (byte)inData.ReadByte(); R2 = (uint)(lo | ml << 8 | mh << 16 | hi << 24); break; default: return -1; // TODO throw proper exception } } // Buffer exhaustion check. if(inData.Position > (startpos + inLen)) { /* It's possible to have a file where the next run is less than * 16 bits in size. In this case, the READ_HUFFSYM() macro used * in building the tables will exhaust the buffer, so we should * allow for this, but not allow those accidentally read bits to * be used (so we check that there are at least 16 bits * remaining - in this boundary case they aren't really part of * the compressed data). */ if(inData.Position > (startpos+inLen+2) || bitbuf.GetBitsLeft() < 16) return -1; //TODO throw proper exception } while((this_run = (int)m_state.block_remaining) > 0 && togo > 0) { if(this_run > togo) this_run = togo; togo -= this_run; m_state.block_remaining -= (uint)this_run; // Apply 2^x-1 mask. window_posn &= window_size - 1; // Runs can't straddle the window wraparound. if((window_posn + this_run) > window_size) return -1; // TODO: throw proper exception switch(m_state.block_type) { case LzxConstants.BLOCKTYPE.VERBATIM: while(this_run > 0) { main_element = (int)ReadHuffSym(m_state.MAINTREE_table, m_state.MAINTREE_len, LzxConstants.MAINTREE_MAXSYMBOLS, LzxConstants.MAINTREE_TABLEBITS, bitbuf); if(main_element < LzxConstants.NUM_CHARS) { // Literal: 0 to NUM_CHARS-1. window[window_posn++] = (byte)main_element; this_run--; } else { // Match: NUM_CHARS + ((slot<<3) | length_header (3 bits)) main_element -= LzxConstants.NUM_CHARS; match_length = main_element & LzxConstants.NUM_PRIMARY_LENGTHS; if(match_length == LzxConstants.NUM_PRIMARY_LENGTHS) { length_footer = (int)ReadHuffSym(m_state.LENGTH_table, m_state.LENGTH_len, LzxConstants.LENGTH_MAXSYMBOLS, LzxConstants.LENGTH_TABLEBITS, bitbuf); match_length += length_footer; } match_length += LzxConstants.MIN_MATCH; match_offset = main_element >> 3; if(match_offset > 2) { // Not repeated offset. if(match_offset != 3) { extra = extra_bits[match_offset]; verbatim_bits = (int)bitbuf.ReadBits((byte)extra); match_offset = (int)position_base[match_offset] - 2 + verbatim_bits; } else { match_offset = 1; } // Update repeated offset LRU queue. R2 = R1; R1 = R0; R0 = (uint)match_offset; } else if(match_offset == 0) { match_offset = (int)R0; } else if(match_offset == 1) { match_offset = (int)R1; R1 = R0; R0 = (uint)match_offset; } else // match_offset == 2 { match_offset = (int)R2; R2 = R0; R0 = (uint)match_offset; } rundest = (int)window_posn; this_run -= match_length; // Copy any wrapped around source data if(window_posn >= match_offset) { // No wrap runsrc = rundest - match_offset; } else { runsrc = rundest + ((int)window_size - match_offset); copy_length = match_offset - (int)window_posn; if(copy_length < match_length) { match_length -= copy_length; window_posn += (uint)copy_length; while(copy_length-- > 0) window[rundest++] = window[runsrc++]; runsrc = 0; } } window_posn += (uint)match_length; // Copy match data - no worries about destination wraps while(match_length-- > 0) window[rundest++] = window[runsrc++]; } } break; case LzxConstants.BLOCKTYPE.ALIGNED: while(this_run > 0) { main_element = (int)ReadHuffSym(m_state.MAINTREE_table, m_state.MAINTREE_len, LzxConstants.MAINTREE_MAXSYMBOLS, LzxConstants.MAINTREE_TABLEBITS, bitbuf); if(main_element < LzxConstants.NUM_CHARS) { // Literal 0 to NUM_CHARS-1 window[window_posn++] = (byte)main_element; this_run -= 1; } else { // Match: NUM_CHARS + ((slot<<3) | length_header (3 bits)) main_element -= LzxConstants.NUM_CHARS; match_length = main_element & LzxConstants.NUM_PRIMARY_LENGTHS; if(match_length == LzxConstants.NUM_PRIMARY_LENGTHS) { length_footer = (int)ReadHuffSym(m_state.LENGTH_table, m_state.LENGTH_len, LzxConstants.LENGTH_MAXSYMBOLS, LzxConstants.LENGTH_TABLEBITS, bitbuf); match_length += length_footer; } match_length += LzxConstants.MIN_MATCH; match_offset = main_element >> 3; if(match_offset > 2) { // Not repeated offset. extra = extra_bits[match_offset]; match_offset = (int)position_base[match_offset] - 2; if(extra > 3) { // Verbatim and aligned bits. extra -= 3; verbatim_bits = (int)bitbuf.ReadBits((byte)extra); match_offset += (verbatim_bits << 3); aligned_bits = (int)ReadHuffSym(m_state.ALIGNED_table, m_state.ALIGNED_len, LzxConstants.ALIGNED_MAXSYMBOLS, LzxConstants.ALIGNED_TABLEBITS, bitbuf); match_offset += aligned_bits; } else if(extra == 3) { // Aligned bits only. aligned_bits = (int)ReadHuffSym(m_state.ALIGNED_table, m_state.ALIGNED_len, LzxConstants.ALIGNED_MAXSYMBOLS, LzxConstants.ALIGNED_TABLEBITS, bitbuf); match_offset += aligned_bits; } else if (extra > 0) // extra==1, extra==2 { // Verbatim bits only. verbatim_bits = (int)bitbuf.ReadBits((byte)extra); match_offset += verbatim_bits; } else // extra == 0 { // ??? match_offset = 1; } // Update repeated offset LRU queue. R2 = R1; R1 = R0; R0 = (uint)match_offset; } else if( match_offset == 0) { match_offset = (int)R0; } else if(match_offset == 1) { match_offset = (int)R1; R1 = R0; R0 = (uint)match_offset; } else // match_offset == 2 { match_offset = (int)R2; R2 = R0; R0 = (uint)match_offset; } rundest = (int)window_posn; this_run -= match_length; // Copy any wrapped around source data if(window_posn >= match_offset) { // No wrap runsrc = rundest - match_offset; } else { runsrc = rundest + ((int)window_size - match_offset); copy_length = match_offset - (int)window_posn; if(copy_length < match_length) { match_length -= copy_length; window_posn += (uint)copy_length; while(copy_length-- > 0) window[rundest++] = window[runsrc++]; runsrc = 0; } } window_posn += (uint)match_length; // Copy match data - no worries about destination wraps. while(match_length-- > 0) window[rundest++] = window[runsrc++]; } } break; case LzxConstants.BLOCKTYPE.UNCOMPRESSED: if((inData.Position + this_run) > endpos) return -1; // TODO: Throw proper exception byte[] temp_buffer = new byte[this_run]; inData.Read(temp_buffer, 0, this_run); temp_buffer.CopyTo(window, (int)window_posn); window_posn += (uint)this_run; break; default: return -1; // TODO: Throw proper exception } } } if(togo != 0) return -1; // TODO: Throw proper exception int start_window_pos = (int)window_posn; if(start_window_pos == 0) start_window_pos = (int)window_size; start_window_pos -= outLen; outData.Write(window, start_window_pos, outLen); m_state.window_posn = window_posn; m_state.R0 = R0; m_state.R1 = R1; m_state.R2 = R2; // TODO: Finish intel E8 decoding. // Intel E8 decoding. if((m_state.frames_read++ < 32768) && m_state.intel_filesize != 0) { if(outLen <= 6 || m_state.intel_started == 0) { m_state.intel_curpos += outLen; } else { int dataend = outLen - 10; uint curpos = (uint)m_state.intel_curpos; m_state.intel_curpos = (int)curpos + outLen; while(outData.Position < dataend) { if(outData.ReadByte() != 0xE8) { curpos++; continue; } } } return -1; } return 0; } // TODO: Make returns throw exceptions private int MakeDecodeTable(uint nsyms, uint nbits, byte[] length, ushort[] table) { ushort sym; uint leaf; byte bit_num = 1; uint fill; uint pos = 0; // The current position in the decode table. uint table_mask = (uint)(1 << (int)nbits); uint bit_mask = table_mask >> 1; // Don't do 0 length codes. uint next_symbol = bit_mask; // Base of allocation for long codes. // Fill entries for codes short enough for a direct mapping. while (bit_num <= nbits ) { for(sym = 0; sym < nsyms; sym++) { if(length[sym] == bit_num) { leaf = pos; if ((pos += bit_mask) > table_mask) { return 1; // Table overrun } /* Fill all possible lookups of this symbol with the * symbol itself. */ fill = bit_mask; while(fill-- > 0) table[leaf++] = sym; } } bit_mask >>= 1; bit_num++; } // If there are any codes longer than nbits if(pos != table_mask) { // Clear the remainder of the table. for(sym = (ushort)pos; sym < table_mask; sym++) table[sym] = 0; // Give ourselves room for codes to grow by up to 16 more bits. pos <<= 16; table_mask <<= 16; bit_mask = 1 << 15; while(bit_num <= 16) { for(sym = 0; sym < nsyms; sym++) { if(length[sym] == bit_num) { leaf = pos >> 16; for(fill = 0; fill < bit_num - nbits; fill++) { // if this path hasn't been taken yet, 'allocate' two entries. if(table[leaf] == 0) { table[(next_symbol << 1)] = 0; table[(next_symbol << 1) + 1] = 0; table[leaf] = (ushort)(next_symbol++); } // Follow the path and select either left or right for next bit. leaf = (uint)(table[leaf] << 1); if(((pos >> (int)(15-fill)) & 1) == 1) leaf++; } table[leaf] = sym; if((pos += bit_mask) > table_mask) return 1; } } bit_mask >>= 1; bit_num++; } } // full table? if(pos == table_mask) return 0; // Either erroneous table, or all elements are 0 - let's find out. for(sym = 0; sym < nsyms; sym++) if(length[sym] != 0) return 1; return 0; } // TODO: Throw exceptions instead of returns private void ReadLengths(byte[] lens, uint first, uint last, BitBuffer bitbuf) { uint x, y; int z; // hufftbl pointer here? for(x = 0; x < 20; x++) { y = bitbuf.ReadBits(4); m_state.PRETREE_len[x] = (byte)y; } MakeDecodeTable(LzxConstants.PRETREE_MAXSYMBOLS, LzxConstants.PRETREE_TABLEBITS, m_state.PRETREE_len, m_state.PRETREE_table); for(x = first; x < last;) { z = (int)ReadHuffSym(m_state.PRETREE_table, m_state.PRETREE_len, LzxConstants.PRETREE_MAXSYMBOLS, LzxConstants.PRETREE_TABLEBITS, bitbuf); if(z == 17) { y = bitbuf.ReadBits(4); y += 4; while(y-- != 0) lens[x++] = 0; } else if(z == 18) { y = bitbuf.ReadBits(5); y += 20; while(y-- != 0) lens[x++] = 0; } else if(z == 19) { y = bitbuf.ReadBits(1); y += 4; z = (int)ReadHuffSym(m_state.PRETREE_table, m_state.PRETREE_len, LzxConstants.PRETREE_MAXSYMBOLS, LzxConstants.PRETREE_TABLEBITS, bitbuf); z = lens[x] - z; if(z < 0) z += 17; while(y-- != 0) lens[x++] = (byte)z; } else { z = lens[x] - z; if(z < 0) z += 17; lens[x++] = (byte)z; } } } private uint ReadHuffSym(ushort[] table, byte[] lengths, uint nsyms, uint nbits, BitBuffer bitbuf) { uint i, j; bitbuf.EnsureBits(16); if((i = table[bitbuf.PeekBits((byte)nbits)]) >= nsyms) { j = (uint)(1 << (int)((sizeof(uint)*8) - nbits)); do { j >>= 1; i <<= 1; i |= (bitbuf.GetBuffer() & j) != 0 ? (uint)1 : 0; if(j == 0) return 0; // TODO: throw proper exception } while((i = table[i]) >= nsyms); } j = lengths[i]; bitbuf.RemoveBits((byte)j); return i; } #region Our BitBuffer Class private class BitBuffer { uint buffer; byte bitsleft; Stream byteStream; public BitBuffer(Stream stream) { byteStream = stream; InitBitStream(); } public void InitBitStream() { buffer = 0; bitsleft = 0; } public void EnsureBits(byte bits) { while(bitsleft < bits) { int lo = (byte)byteStream.ReadByte(); int hi = (byte)byteStream.ReadByte(); buffer |= (uint)(((hi << 8) | lo) << (sizeof(uint)*8 - 16 - bitsleft)); bitsleft += 16; } } public uint PeekBits(byte bits) { return (buffer >> ((sizeof(uint)*8) - bits)); } public void RemoveBits(byte bits) { buffer <<= bits; bitsleft -= bits; } public uint ReadBits(byte bits) { uint ret = 0; if(bits > 0) { EnsureBits(bits); ret = PeekBits(bits); RemoveBits(bits); } return ret; } public uint GetBuffer() { return buffer; } public byte GetBitsLeft() { return bitsleft; } } #endregion struct LzxState { public uint R0, R1, R2; // For the LRU offset system public ushort main_elements; // Number of main tree elements public int header_read; // Have we started decoding at all yet? public LzxConstants.BLOCKTYPE block_type; // Type of this block public uint block_length; // Uncompressed length of this block public uint block_remaining; // Uncompressed bytes still left to decode public uint frames_read; // The number of CFDATA blocks processed public int intel_filesize; // Magic header value used for transform public int intel_curpos; // Current offset in transform space public int intel_started; // Have we seen any translateable data yet? public ushort[] PRETREE_table; public byte[] PRETREE_len; public ushort[] MAINTREE_table; public byte[] MAINTREE_len; public ushort[] LENGTH_table; public byte[] LENGTH_len; public ushort[] ALIGNED_table; public byte[] ALIGNED_len; /* NEEDED MEMBERS * CAB actualsize * CAB window * CAB window_size * CAB window_posn */ public uint actual_size; public byte[] window; public uint window_size; public uint window_posn; } } // CONSTANTS struct LzxConstants { public const ushort MIN_MATCH = 2; public const ushort MAX_MATCH = 257; public const ushort NUM_CHARS = 256; public enum BLOCKTYPE { INVALID = 0, VERBATIM = 1, ALIGNED = 2, UNCOMPRESSED = 3 } public const ushort PRETREE_NUM_ELEMENTS = 20; public const ushort ALIGNED_NUM_ELEMENTS = 8; public const ushort NUM_PRIMARY_LENGTHS = 7; public const ushort NUM_SECONDARY_LENGTHS = 249; public const ushort PRETREE_MAXSYMBOLS = PRETREE_NUM_ELEMENTS; public const ushort PRETREE_TABLEBITS = 6; public const ushort MAINTREE_MAXSYMBOLS = NUM_CHARS + 50*8; public const ushort MAINTREE_TABLEBITS = 12; public const ushort LENGTH_MAXSYMBOLS = NUM_SECONDARY_LENGTHS + 1; public const ushort LENGTH_TABLEBITS = 12; public const ushort ALIGNED_MAXSYMBOLS = ALIGNED_NUM_ELEMENTS; public const ushort ALIGNED_TABLEBITS = 7; public const ushort LENTABLE_SAFETY = 64; } // EXCEPTIONS class UnsupportedWindowSizeRange : Exception { }
29.808883
124
0.619063
[ "MIT" ]
renaudbedard/HoloFEZ
Assets/FezUnity/LzxDecoder.cs
22,148
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HiveProject.Models { public class Message { public int MessageId { get; set; } public string SenderId { get; set; } public virtual ApplicationUser Sender { get; set; } public string ReceiverId { get; set; } public virtual ApplicationUser Receiver { get; set; } public string Body { get; set; } public DateTime DateSent { get; set; } public bool Read { get; set; } public Message() { DateSent = DateTime.Now; } } }
21.1
61
0.592417
[ "MIT" ]
ginisth/Hive-Project
HiveProject/Models/Message.cs
635
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.TemplateEngine.Abstractions.Installer { /// <summary> /// Defines possible error codes for <see cref="IInstaller"/> operations. /// </summary> public enum InstallerErrorCode { /// <summary> /// The operation completed successfully. /// </summary> Success = 0, /// <summary> /// The template package is not found. /// </summary> PackageNotFound = 1, /// <summary> /// The installation source (e.g. NuGet feed) is invalid. /// </summary> InvalidSource = 2, /// <summary> /// The download from remote source (e.g. NuGet feed) has failed. /// </summary> DownloadFailed = 3, /// <summary> /// The request is not supported by the installer. /// </summary> UnsupportedRequest = 4, /// <summary> /// Generic error. /// </summary> GenericError = 5, /// <summary> /// The template package is already installed. /// </summary> AlreadyInstalled = 6, /// <summary> /// The update has failed due to uninstallation of previous template package version has failed. /// </summary> UpdateUninstallFailed = 7, /// <summary> /// The requested package is invalid and cannot be processed. /// </summary> InvalidPackage = 8 } }
27.807018
104
0.555836
[ "MIT" ]
2mol/templating
src/Microsoft.TemplateEngine.Abstractions/Installer/InstallerErrorCode.cs
1,587
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; [System.Serializable] public class GridObjectDie : UnityEvent<GridObject> { } [System.Serializable] public class GridObjectHurt : UnityEvent<GridObject, int> { } public enum GridObjectFacing { NONE = 0000, UP_RIGHT = 1000, UP_LEFT = 2000, DOWN_RIGHT = 3000, DOWN_LEFT = 4000, } public class GridObject : MonoBehaviour { public GridObjectData data; public GridPathfinder pathfinder; public GridAction action; public GameObject avatar; public Animator animator; // ...I am lazy private GameObject icon; private GenericWorldSpaceToCanvasIcon iconScript; private GridObjectIcon iconUIScript; // This is a static bool, shared across everything, since only one object can be selected at a time! public static GridObject selected; public int health; public int actionpoints; public bool dead; public Vector2Int facing; public GridObjectDie deathEvent; public GridObjectHurt hurtEvent; // Start is called before the first frame update void Start () { if (data == null) { Debug.LogWarning ("Object does not have data object attached!", gameObject); } if (pathfinder == null) { pathfinder = GetComponentInChildren<GridPathfinder> (); } // set up pathfinder //pathfinder.maxDistance = data.actionpoints; // set up animator if (animator != null) { pathfinder.moveStartedEvent.AddListener (AnimateMovement); pathfinder.moveFinishedEvent.AddListener (StopMoving); pathfinder.waypointReachedEvent.AddListener (AnimateMovement); } // Spawn character icon if (icon == null && data.iconPrefab_ != null) { iconScript = GetComponent<GenericWorldSpaceToCanvasIcon> (); if (iconScript != null) { icon = Instantiate (data.iconPrefab_, GridUIManager.instance.canvas.transform); iconScript.target = avatar; iconScript.canvasObject = icon.GetComponent<RectTransform> (); }; } // setup icon iconUIScript = icon.GetComponent<GridObjectIcon> (); iconUIScript.SetName (data.name_); GridUIManager.instance.AddGridObjectIcon (this, iconUIScript); // setup controls if (data.type_ == GridObjectType.PLAYABLE) { GridCameraController.instance.mouseLeftClickEvent.AddListener (ClickedToMove); GridCameraController.instance.mouseRightClickEvent.AddListener (ClickToChangeFacing); } // setup action if (action == null) { action = GetComponent<GridAction> (); } action.SetActions (data.defaultActions); // setup other things health = data.health; actionpoints = data.actionpoints; } [EasyButtons.Button] void SelectDebug () { SelectObject (true); } [EasyButtons.Button] void AttackDebug () { if (!dead) { action.DoAction ("attack_simple"); }; } public void DoAction (string id) { if (selected == this && !dead) { GridObjectInteractDataBase theaction = action.GetAction (id); if (theaction != null) { if (theaction.actionCost <= actionpoints) { actionpoints -= theaction.actionCost; action.DoAction (id); GridUIManager.instance.UpdateCharacter (this); }; }; } } public void DoAction (GridObjectInteractDataBase data) { DoAction (data.id); } public void SelectObject (bool select) { if (select) { selected = this; GridCameraController.instance.SetCamTarget (avatar.transform); GridUIManager.instance.SelectCharacter (this); } } void ClickedToMove (TileInfo info) { if (!dead && selected == this && data.type_ == GridObjectType.PLAYABLE && GridUIManager.instance.playerTurn) { pathfinder.ClickedToMove (info); }; } void ClickToChangeFacing (TileInfo info) { // change facing in the direction of a right-click when selected if (!dead && selected == this && data.type_ == GridObjectType.PLAYABLE && actionpoints > 0) { Vector2Int oldfacing = facing; Vector3Int mousePos = GridManager.instance.maingrid.WorldToCell (GridCameraController.instance.mainCam.ScreenToWorldPoint (Input.mousePosition)); Vector3Int avatarPos = pathfinder.selfLocation; //Debug.Log ("Mouse X" + mousePos.x + "Avatar X: " + avatarPos.x + "Mouse Y: " + mousePos.y + "Avatar Y: " + avatarPos.y); if (mousePos.x == avatarPos.x && mousePos.y > avatarPos.y) { ChangeFacing (GridObjectFacing.UP_LEFT); } else if (mousePos.x == avatarPos.x && mousePos.y < avatarPos.y) { ChangeFacing (GridObjectFacing.DOWN_RIGHT); } else if (mousePos.x > avatarPos.x && mousePos.y == avatarPos.y) { ChangeFacing (GridObjectFacing.UP_RIGHT); } else if (mousePos.x < avatarPos.x && mousePos.y == avatarPos.y) { ChangeFacing (GridObjectFacing.DOWN_LEFT); } if (facing != oldfacing) { actionpoints--; GridUIManager.instance.UpdateCharacter (this); } } } void AnimateMovement (GridPathfinder pf, Vector3Int startPoint, Vector3Int endPoint) { if (animator != null) { Vector2Int movementDirection = GetMovementDirection (startPoint, endPoint); animator.SetInteger ("FaceX", (int) movementDirection.x); animator.SetInteger ("FaceY", (int) movementDirection.y); animator.SetBool ("Moving", true); facing.x = movementDirection.x; facing.y = movementDirection.y; } } public void ChangeFacing (GridObjectFacing facing) { Vector2Int facingVector = GridObjectManager.instance.ConvertFacingEnumToNumbers (facing); ChangeFacing (facingVector.x, facingVector.y); } public void ChangeFacing (int x, int y) { animator.SetFloat ("IdleBlend", GetDirectionFloat (x, y)); facing.x = x; facing.y = y; } void StopMoving (GridPathfinder pf, Vector3Int startPoint, Vector3Int endPoint) { if (animator != null) { animator.SetBool ("Moving", false); // set facing in blendtree //0 = up right, 1 = down left, 2 = down right, 3 = up left //1,0 = up right, down left = -1, 0, down right = 0, -1, up left = 0, 1 ChangeFacing (animator.GetInteger ("FaceX"), animator.GetInteger ("FaceY")); } } float GetDirectionFloat (int x, int y) { if (x == 1 && y == 0) { return 0f; } else if (x == -1 && y == 0) { return 1f; } else if (x == 0 && y == 1) { return 2f; } else if (x == 0 && y == -1) { return 3f; } else { return 0f; } } void AnimateDamage (float damage) { if (animator != null) { animator.SetTrigger ("Hurt"); iconUIScript.healthBarFill = damage; } } void AnimateDeath (bool death = true) { if (animator != null) { animator.SetBool ("Dead", death); iconUIScript.healthBarFill = health; } } public void Damage (int damage) { if (!dead) { health -= damage; hurtEvent.Invoke (this, damage); if (health > 0) { AnimateDamage ((float) health / (float) data.health); } else { AnimateDeath (); dead = true; deathEvent.Invoke (this); } }; } public Vector2Int GetMovementDirection (Vector3Int start, Vector3Int end) { // For the animator Vector2Int movementDirection = new Vector2Int (0, 0); if (end.x > start.x) { movementDirection.x = 1; } else if (end.x < start.x) { movementDirection.x = -1; } else { movementDirection.x = 0; } if (end.y > start.y) { movementDirection.y = 1; } else if (end.y < start.y) { movementDirection.y = -1; } else { movementDirection.y = 0; } return movementDirection; } // Update is called once per frame void Update () { } }
35.855372
157
0.584534
[ "MIT" ]
wolfrug/ldjam46
LDJAM 46/Assets/GridMover/Scripts/GridObject.cs
8,679
C#
using BloomFilter; using BloomFilter.Configurations; using BloomFilter.CSRedis.Configurations; using System; namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { /// <summary> /// Uses the EasyCaching redis. /// </summary> /// <param name="options">Options.</param> /// <param name="name"></param> /// <param name="setupActions"></param> public static BloomFilterOptions UseEasyCachingRedis(this BloomFilterOptions options, string name = BloomFilterConstValue.DefaultRedisName, Action<FilterEasyCachingRedisOptions> setupActions = null) { var filterRedisOptions = new FilterEasyCachingRedisOptions { Name = name }; setupActions?.Invoke(filterRedisOptions); options.RegisterExtension(new FilterEasyCachingRedisExtension(filterRedisOptions)); return options; } /// <summary> /// Uses the EasyCaching redis. /// </summary> /// <param name="options">Options.</param> /// <param name="filterRedisOptions"></param> public static BloomFilterOptions UseEasyCachingRedis(this BloomFilterOptions options, FilterEasyCachingRedisOptions filterRedisOptions) { if (filterRedisOptions == null) throw new ArgumentNullException(nameof(filterRedisOptions)); options.RegisterExtension(new FilterEasyCachingRedisExtension(filterRedisOptions)); return options; } } }
39.55
143
0.659924
[ "MIT" ]
chrisreiter/BloomFilter.NetCore
src/BloomFilter.EasyCaching/Configurations/ServiceCollectionExtensions.cs
1,584
C#