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
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Bam.Net.Data; namespace Bam.Net.ServiceProxy.Secure { public class SecureSessionColumns: QueryFilter<SecureSessionColumns>, IFilterToken { public SecureSessionColumns() { } public SecureSessionColumns(string columnName, bool isForeignKey = false) : base(columnName) { _isForeignKey = isForeignKey; } public bool IsKey() { return (bool)ColumnName?.Equals(KeyColumn.ColumnName); } private bool? _isForeignKey; public bool IsForeignKey { get { if (_isForeignKey == null) { PropertyInfo prop = DaoType .GetProperties() .FirstOrDefault(pi => ((MemberInfo) pi) .HasCustomAttributeOfType<ForeignKeyAttribute>(out ForeignKeyAttribute foreignKeyAttribute) && foreignKeyAttribute.Name.Equals(ColumnName)); _isForeignKey = prop != null; } return _isForeignKey.Value; } set => _isForeignKey = value; } public SecureSessionColumns KeyColumn => new SecureSessionColumns("Id"); public SecureSessionColumns Id => new SecureSessionColumns("Id"); public SecureSessionColumns Uuid => new SecureSessionColumns("Uuid"); public SecureSessionColumns Cuid => new SecureSessionColumns("Cuid"); public SecureSessionColumns Identifier => new SecureSessionColumns("Identifier"); public SecureSessionColumns AsymmetricKey => new SecureSessionColumns("AsymmetricKey"); public SecureSessionColumns SymmetricKey => new SecureSessionColumns("SymmetricKey"); public SecureSessionColumns SymmetricIV => new SecureSessionColumns("SymmetricIV"); public SecureSessionColumns CreationDate => new SecureSessionColumns("CreationDate"); public SecureSessionColumns TimeOffset => new SecureSessionColumns("TimeOffset"); public SecureSessionColumns LastActivity => new SecureSessionColumns("LastActivity"); public SecureSessionColumns IsActive => new SecureSessionColumns("IsActive"); public SecureSessionColumns ApplicationId => new SecureSessionColumns("ApplicationId", true); public Type DaoType => typeof(SecureSession); public string Operator { get; set; } public override string ToString() { return base.ColumnName; } } }
38.57971
119
0.640872
[ "MIT" ]
BryanApellanes/bam.net.shared
ServiceProxy/Secure/SecureServiceProxy_Generated/SecureSessionColumns.cs
2,662
C#
using System; using System.Windows.Input; using System.Windows.Threading; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; namespace Demo.NonModalCustomDialog { public class CurrentTimeCustomDialogViewModel : ObservableObject { // ReSharper disable once NotAccessedField.Local private DispatcherTimer? timer; public CurrentTimeCustomDialogViewModel() { StartClockCommand = new RelayCommand(StartClock); } public ICommand StartClockCommand { get; } public DateTime CurrentTime => DateTime.Now; private void StartClock() { timer = new DispatcherTimer( TimeSpan.FromSeconds(1), DispatcherPriority.Normal, OnTick, Dispatcher.CurrentDispatcher); } private void OnTick(object? sender, EventArgs e) { OnPropertyChanged(nameof(CurrentTime)); } } }
26.131579
68
0.638469
[ "Apache-2.0" ]
Glepooek/mvvm-dialogs
samples/wpf/Demo.NonModalCustomDialog/CurrentTimeCustomDialogViewModel.cs
995
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace PaymentServiceSample.Migrations { public partial class ConfiguredHasColumnTypeForWithdrawalRecordAmount : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<decimal>( name: "Amount", table: "EasyAbpPaymentServicePrepaymentWithdrawalRecords", type: "decimal(20,8)", nullable: false, oldClrType: typeof(decimal), oldType: "decimal(18,2)"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<decimal>( name: "Amount", table: "EasyAbpPaymentServicePrepaymentWithdrawalRecords", type: "decimal(18,2)", nullable: false, oldClrType: typeof(decimal), oldType: "decimal(20,8)"); } } }
33.766667
85
0.589339
[ "MIT" ]
LGinC/PaymentService
samples/PaymentServiceSample/aspnet-core/src/PaymentServiceSample.EntityFrameworkCore.DbMigrations/Migrations/20200917102731_ConfiguredHasColumnTypeForWithdrawalRecordAmount.cs
1,015
C#
using System; using System.Collections.Generic; using System.Globalization; using Localization.Resources.AbpUi; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Acme.BookStore.Localization; using Acme.BookStore.Web; using Acme.BookStore.Web.Menus; using Volo.Abp; using Volo.Abp.AspNetCore.TestBase; using Volo.Abp.Localization; using Volo.Abp.Modularity; using Volo.Abp.UI.Navigation; using Volo.Abp.Validation.Localization; namespace Acme.BookStore { [DependsOn( typeof(AbpAspNetCoreTestBaseModule), typeof(BookStoreWebModule), typeof(BookStoreApplicationTestModule) )] public class BookStoreWebTestModule : AbpModule { public override void PreConfigureServices(ServiceConfigurationContext context) { context.Services.PreConfigure<IMvcBuilder>(builder => { builder.PartManager.ApplicationParts.Add(new AssemblyPart(typeof(BookStoreWebModule).Assembly)); }); } public override void ConfigureServices(ServiceConfigurationContext context) { ConfigureLocalizationServices(context.Services); ConfigureNavigationServices(context.Services); } private static void ConfigureLocalizationServices(IServiceCollection services) { var cultures = new List<CultureInfo> { new CultureInfo("en"), new CultureInfo("tr") }; services.Configure<RequestLocalizationOptions>(options => { options.DefaultRequestCulture = new RequestCulture("en"); options.SupportedCultures = cultures; options.SupportedUICultures = cultures; }); services.Configure<AbpLocalizationOptions>(options => { options.Resources .Get<BookStoreResource>() .AddBaseTypes( typeof(AbpValidationResource), typeof(AbpUiResource) ); }); } private static void ConfigureNavigationServices(IServiceCollection services) { services.Configure<AbpNavigationOptions>(options => { options.MenuContributors.Add(new BookStoreMenuContributor()); }); } public override void OnApplicationInitialization(ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); var env = context.GetEnvironment(); app.Use(async (ctx, next) => { try { await next(); } catch (Exception e) { Console.WriteLine(e); throw; } }); app.UseVirtualFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseAbpRequestLocalization(); app.Use(async (ctx, next) => { try { await next(); } catch (Exception e) { Console.WriteLine(e); throw; } }); app.UseConfiguredEndpoints(); } } }
31.070175
112
0.57284
[ "MIT" ]
AbdallahYahyia/abp-samples
Authentication-Customization/test/Acme.BookStore.Web.Tests/BookStoreWebTestModule.cs
3,544
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("JsonProjectStorage")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("JsonProjectStorage")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("c015851b-6246-47c7-9b1b-9669e597a6f7")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.756757
106
0.762599
[ "MIT" ]
Nukleon84/OpenFMSL
source/JsonProjectStorage/JsonProjectStorage/Properties/AssemblyInfo.cs
1,525
C#
using NUnit.Framework; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Nemesis.Essentials.Design; namespace Nemesis.Essentials.Tests { [TestFixture(TestOf = typeof(EnumerableEqualityComparer<>))] public class EnumerableEqualityComparerTests { private static IList<string> Empty() => new List<string>(); private static IList<string> From(params string[] elements) => new List<string>(elements); [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] private static string Format(IEnumerable<string> list) => list == null ? "NULL" : ( !list.Any() ? "∅" : string.Join("|", list.Select(FormatElement)) ); private static string FormatElement(string element) => element == null ? "NULL_ELEMENT" : (element.Length == 0 ? "EMPTY_ELEMENT" : element); private static IEnumerable<TestCaseData> GetPositiveCases() => new[] { (null, null), (Empty(), Empty()), (Empty().AddFluent("1"), Empty().AddFluent("1")), (Empty().AddFluent("1", "2"), Empty().AddFluent("1").AddFluent("2")), (Empty().AddFluent("1", "2").AddFluent("3"), Empty().AddFluent("1").AddFluent("2").AddFluent(3.ToString())), (From("1", "2", "3"), From("1", "2", "3")), (From("1", "2", "3", "4"), From("1", "2", "3").AddFluent("4")), }.DuplicateWithElementReversal() .Select((elem, i) => new TestCaseData(elem).SetName($"{i + 1:00}. {Format(elem.Item1)} == {Format(elem.Item2)}")); [TestCaseSource(nameof(GetPositiveCases))] public void Equals_Positive((IList<string> left, IList<string> right) data) { var (left, right) = data; if (ReferenceEquals(left, right) && left != null && right != null) Assert.Fail("Reference equality should be checked using trivial path"); var comparer = EnumerableEqualityComparer<string>.DefaultInstance; Assert.That(left, Is.EqualTo(right).Using(comparer), "Equals assert"); Assert.That( comparer.GetHashCode(left), Is.EqualTo( comparer.GetHashCode(right) ), "GetHashCode"); Assert.That(comparer.Equals(left, right), Is.True, "Equals"); } private static IEnumerable<TestCaseData> GetNegativeCases() => new[] { (Empty(), null), (Empty().AddFluent("1"), null), (From("1", "2", "3", "4"), From("1", "2", "3")), (From("1", "2", "3", ""), From("1", "2", "3")), (From("1", "2", "3", "4", "5"), From("1", "2", "3").AddFluent("4")), (From("1", "2", "3", "4", "5", "6"), From("1", "2", "3").AddFluent("4")), }.DuplicateWithElementReversal() .Select((elem, i) => new TestCaseData(elem).SetName($"{i + 1:00}. {Format(elem.Item1)} != {Format(elem.Item2)}")); [TestCaseSource(nameof(GetNegativeCases))] public void Equals_Negative((IList<string> left, IList<string> right) data) { var (left, right) = data; var comparer = EnumerableEqualityComparer<string>.DefaultInstance; Assert.That(left, Is.Not.EqualTo(right).Using(comparer), "Equals assert"); Assert.That(comparer.Equals(left, right), Is.False, "Equals"); } } internal static class EnumerableEqualityComparerTestsHelper { internal static IList<T> AddFluent<T>(this IList<T> list, params T[] elements) { foreach (var element in elements) list.Add(element); return list; } internal static IEnumerable<(T, T)> DuplicateWithElementReversal<T>(this IList<(T, T)> list) { foreach (var t in list) yield return t; for (int i = 0; i < list.Count; i++) yield return (list[i].Item2, list[i].Item1); } } }
41.979592
126
0.548858
[ "MIT" ]
nemesissoft/Nemesis.Essentials
Nemesis.Essentials.Tests/EnumerableEqualityComparerTests.cs
4,118
C#
using System; using System.IO; using System.Windows; using Microsoft.Win32; namespace OpenFileDialogSample { /// <summary> /// MainWindow.xaml에 대한 상호 작용 논리 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btnOpenFile_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; if (openFileDialog.ShowDialog() == true) txtEditor.Text = File.ReadAllText(openFileDialog.FileName); } } }
25.925926
83
0.6
[ "MIT" ]
kerry-Cho/WPF-Example
Dialog/OpenFileDialogSample/OpenFileDialogSample/MainWindow.xaml.cs
720
C#
using System; namespace dgPower.KMS.Net.MimeTypes { /* Copied from: * http://stackoverflow.com/questions/10362140/asp-mvc-are-there-any-constants-for-the-default-content-types */ /// <summary> /// Common mime types. /// </summary> public static class MimeTypeNames { ///<summary>Used to denote the encoding necessary for files containing JavaScript source code. The alternative MIME type for this file type is text/javascript.</summary> public const string ApplicationXJavascript = "application/x-javascript"; ///<summary>24bit Linear PCM audio at 8-48kHz, 1-N channels; Defined in RFC 3190</summary> public const string AudioL24 = "audio/L24"; ///<summary>Adobe Flash files for example with the extension .swf</summary> public const string ApplicationXShockwaveFlash = "application/x-shockwave-flash"; ///<summary>Arbitrary binary data.[5] Generally speaking this type identifies files that are not associated with a specific application. Contrary to past assumptions by software packages such as Apache this is not a type that should be applied to unknown files. In such a case, a server or application should not indicate a content type, as it may be incorrect, but rather, should omit the type in order to allow the recipient to guess the type.[6]</summary> public const string ApplicationOctetStream = "application/octet-stream"; ///<summary>Atom feeds</summary> public const string ApplicationAtomXml = "application/atom+xml"; ///<summary>Cascading Style Sheets; Defined in RFC 2318</summary> public const string TextCss = "text/css"; ///<summary>commands; subtype resident in Gecko browsers like Firefox 3.5</summary> public const string TextCmd = "text/cmd"; ///<summary>Comma-separated values; Defined in RFC 4180</summary> public const string TextCsv = "text/csv"; ///<summary>deb (file format), a software package format used by the Debian project</summary> public const string ApplicationXDeb = "application/x-deb"; ///<summary>Defined in RFC 1847</summary> public const string MultipartEncrypted = "multipart/encrypted"; ///<summary>Defined in RFC 1847</summary> public const string MultipartSigned = "multipart/signed"; ///<summary>Defined in RFC 2616</summary> public const string MessageHttp = "message/http"; ///<summary>Defined in RFC 4735</summary> public const string ModelExample = "model/example"; ///<summary>device-independent document in DVI format</summary> public const string ApplicationXDvi = "application/x-dvi"; ///<summary>DTD files; Defined by RFC 3023</summary> public const string ApplicationXmlDtd = "application/xml-dtd"; ///<summary>ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to application/ecmascript but with looser processing rules) It is not accepted in IE 8 or earlier - text/javascript is accepted but it is defined as obsolete in RFC 4329. The "type" attribute of the <script> tag in HTML5 is optional and in practice omitting the media type of JavaScript programs is the most interoperable solution since all browsers have always assumed the correct default even before HTML5.</summary> public const string ApplicationJavascript = "application/javascript"; ///<summary>ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to application/javascript but with stricter processing rules)</summary> public const string ApplicationEcmascript = "application/ecmascript"; ///<summary>EDI EDIFACT data; Defined in RFC 1767</summary> public const string ApplicationEdifact = "application/EDIFACT"; ///<summary>EDI X12 data; Defined in RFC 1767</summary> public const string ApplicationEdiX12 = "application/EDI-X12"; ///<summary>Email; Defined in RFC 2045 and RFC 2046</summary> public const string MessagePartial = "message/partial"; ///<summary>Email; EML files, MIME files, MHT files, MHTML files; Defined in RFC 2045 and RFC 2046</summary> public const string MessageRfc822 = "message/rfc822"; ///<summary>Extensible Markup Language; Defined in RFC 3023</summary> public const string TextXml = "text/xml"; ///<summary>Flash video (FLV files)</summary> public const string VideoXFlv = "video/x-flv"; ///<summary>GIF image; Defined in RFC 2045 and RFC 2046</summary> public const string ImageGif = "image/gif"; ///<summary>GoogleWebToolkit data</summary> public const string TextXGwtRpc = "text/x-gwt-rpc"; ///<summary>Gzip</summary> public const string ApplicationXGzip = "application/x-gzip"; ///<summary>HTML; Defined in RFC 2854</summary> public const string TextHtml = "text/html"; ///<summary>ICO image; Registered[9]</summary> public const string ImageVndMicrosoftIcon = "image/vnd.microsoft.icon"; ///<summary>IGS files, IGES files; Defined in RFC 2077</summary> public const string ModelIges = "model/iges"; ///<summary>IMDN Instant Message Disposition Notification; Defined in RFC 5438</summary> public const string MessageImdnXml = "message/imdn+xml"; ///<summary>JavaScript Object Notation JSON; Defined in RFC 4627</summary> public const string ApplicationJson = "application/json"; ///<summary>JavaScript Object Notation (JSON) Patch; Defined in RFC 6902</summary> public const string ApplicationJsonPatch = "application/json-patch+json"; ///<summary>JavaScript - Defined in and obsoleted by RFC 4329 in order to discourage its usage in favor of application/javascript. However,text/javascript is allowed in HTML 4 and 5 and, unlike application/javascript, has cross-browser support. The "type" attribute of the <script> tag in HTML5 is optional and there is no need to use it at all since all browsers have always assumed the correct default (even in HTML 4 where it was required by the specification).</summary> [Obsolete] public const string TextJavascript = "text/javascript"; ///<summary>JPEG JFIF image; Associated with Internet Explorer; Listed in ms775147(v=vs.85) - Progressive JPEG, initiated before global browser support for progressive JPEGs (Microsoft and Firefox).</summary> public const string ImagePjpeg = "image/pjpeg"; ///<summary>JPEG JFIF image; Defined in RFC 2045 and RFC 2046</summary> public const string ImageJpeg = "image/jpeg"; ///<summary>jQuery template data</summary> public const string TextXJqueryTmpl = "text/x-jquery-tmpl"; ///<summary>KML files (e.g. for Google Earth)</summary> public const string ApplicationVndGoogleEarthKmlXml = "application/vnd.google-earth.kml+xml"; ///<summary>LaTeX files</summary> public const string ApplicationXLatex = "application/x-latex"; ///<summary>Matroska open media format</summary> public const string VideoXMatroska = "video/x-matroska"; ///<summary>Microsoft Excel 2007 files</summary> public const string ApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; ///<summary>Microsoft Excel files</summary> public const string ApplicationVndMsExcel = "application/vnd.ms-excel"; ///<summary>Microsoft Powerpoint 2007 files</summary> public const string ApplicationVndOpenxmlformatsOfficedocumentPresentationmlPresentation = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; ///<summary>Microsoft Powerpoint files</summary> public const string ApplicationVndMsPowerpoint = "application/vnd.ms-powerpoint"; ///<summary>Microsoft Word 2007 files</summary> public const string ApplicationVndOpenxmlformatsOfficedocumentWordprocessingmlDocument = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; ///<summary>Microsoft Word files[15]</summary> public const string ApplicationMsword = "application/msword"; ///<summary>MIME Email; Defined in RFC 2045 and RFC 2046</summary> public const string MultipartAlternative = "multipart/alternative"; ///<summary>MIME Email; Defined in RFC 2045 and RFC 2046</summary> public const string MultipartMixed = "multipart/mixed"; ///<summary>MIME Email; Defined in RFC 2387 and used by MHTML (HTML mail)</summary> public const string MultipartRelated = "multipart/related"; ///<summary>MIME Webform; Defined in RFC 2388</summary> public const string MultipartFormData = "multipart/form-data"; ///<summary>Mozilla XUL files</summary> public const string ApplicationVndMozillaXulXml = "application/vnd.mozilla.xul+xml"; ///<summary>MP3 or other MPEG audio; Defined in RFC 3003</summary> public const string AudioMpeg = "audio/mpeg"; ///<summary>MP4 audio</summary> public const string AudioMp4 = "audio/mp4"; ///<summary>MP4 video; Defined in RFC 4337</summary> public const string VideoMp4 = "video/mp4"; ///<summary>MPEG-1 video with multiplexed audio; Defined in RFC 2045 and RFC 2046</summary> public const string VideoMpeg = "video/mpeg"; ///<summary>MSH files, MESH files; Defined in RFC 2077, SILO files</summary> public const string ModelMesh = "model/mesh"; ///<summary>mulaw audio at 8 kHz, 1 channel; Defined in RFC 2046</summary> public const string AudioBasic = "audio/basic"; ///<summary>Ogg Theora or other video (with audio); Defined in RFC 5334</summary> public const string VideoOgg = "video/ogg"; ///<summary>Ogg Vorbis, Speex, Flac and other audio; Defined in RFC 5334</summary> public const string AudioOgg = "audio/ogg"; ///<summary>Ogg, a multimedia bitstream container format; Defined in RFC 5334</summary> public const string ApplicationOgg = "application/ogg"; ///<summary>OP</summary> public const string ApplicationXopXml = "application/xop+xml"; ///<summary>OpenDocument Graphics; Registered[14]</summary> public const string ApplicationVndOasisOpendocumentGraphics = "application/vnd.oasis.opendocument.graphics"; ///<summary>OpenDocument Presentation; Registered[13]</summary> public const string ApplicationVndOasisOpendocumentPresentation = "application/vnd.oasis.opendocument.presentation"; ///<summary>OpenDocument Spreadsheet; Registered[12]</summary> public const string ApplicationVndOasisOpendocumentSpreadsheet = "application/vnd.oasis.opendocument.spreadsheet"; ///<summary>OpenDocument Text; Registered[11]</summary> public const string ApplicationVndOasisOpendocumentText = "application/vnd.oasis.opendocument.text"; ///<summary>p12 files</summary> public const string ApplicationXPkcs12 = "application/x-pkcs12"; ///<summary>p7b and spc files</summary> public const string ApplicationXPkcs7Certificates = "application/x-pkcs7-certificates"; ///<summary>p7c files</summary> public const string ApplicationXPkcs7Mime = "application/x-pkcs7-mime"; ///<summary>p7r files</summary> public const string ApplicationXPkcs7Certreqresp = "application/x-pkcs7-certreqresp"; ///<summary>p7s files</summary> public const string ApplicationXPkcs7Signature = "application/x-pkcs7-signature"; ///<summary>Portable Document Format, PDF has been in use for document exchange on the Internet since 1993; Defined in RFC 3778</summary> public const string ApplicationPdf = "application/pdf"; ///<summary>Portable Network Graphics; Registered,[8] Defined in RFC 2083</summary> public const string ImagePng = "image/png"; ///<summary>PostScript; Defined in RFC 2046</summary> public const string ApplicationPostscript = "application/postscript"; ///<summary>QuickTime video; Registered[10]</summary> public const string VideoQuicktime = "video/quicktime"; ///<summary>RAR archive files</summary> public const string ApplicationXRarCompressed = "application/x-rar-compressed"; ///<summary>RealAudio; Documented in RealPlayer Customer Support Answer 2559</summary> public const string AudioVndRnRealaudio = "audio/vnd.rn-realaudio"; ///<summary>Resource Description Framework; Defined by RFC 3870</summary> public const string ApplicationRdfXml = "application/rdf+xml"; ///<summary>RSS feeds</summary> public const string ApplicationRssXml = "application/rss+xml"; ///<summary>SOAP; Defined by RFC 3902</summary> public const string ApplicationSoapXml = "application/soap+xml"; ///<summary>StuffIt archive files</summary> public const string ApplicationXStuffit = "application/x-stuffit"; ///<summary>SVG vector image; Defined in SVG Tiny 1.2 Specification Appendix M</summary> public const string ImageSvgXml = "image/svg+xml"; ///<summary>Tag Image File Format (only for Baseline TIFF); Defined in RFC 3302</summary> public const string ImageTiff = "image/tiff"; ///<summary>Tarball files</summary> public const string ApplicationXTar = "application/x-tar"; ///<summary>Textual data; Defined in RFC 2046 and RFC 3676</summary> public const string TextPlain = "text/plain"; ///<summary>TrueType Font No registered MIME type, but this is the most commonly used</summary> public const string ApplicationXFontTtf = "application/x-font-ttf"; ///<summary>vCard (contact information); Defined in RFC 6350</summary> public const string TextVcard = "text/vcard"; ///<summary>Vorbis encoded audio; Defined in RFC 5215</summary> public const string AudioVorbis = "audio/vorbis"; ///<summary>WAV audio; Defined in RFC 2361</summary> public const string AudioVndWave = "audio/vnd.wave"; ///<summary>Web Open Font Format; (candidate recommendation; use application/x-font-woff until standard is official)</summary> public const string ApplicationFontWoff = "application/font-woff"; ///<summary>WebM Matroska-based open media format</summary> public const string VideoWebm = "video/webm"; ///<summary>WebM open media format</summary> public const string AudioWebm = "audio/webm"; ///<summary>Windows Media Audio Redirector; Documented in Microsoft help page</summary> public const string AudioXMsWax = "audio/x-ms-wax"; ///<summary>Windows Media Audio; Documented in Microsoft KB 288102</summary> public const string AudioXMsWma = "audio/x-ms-wma"; ///<summary>Windows Media Video; Documented in Microsoft KB 288102</summary> public const string VideoXMsWmv = "video/x-ms-wmv"; ///<summary>WRL files, VRML files; Defined in RFC 2077</summary> public const string ModelVrml = "model/vrml"; ///<summary>X3D ISO standard for representing 3D computer graphics, X3D XML files</summary> public const string ModelX3DXml = "model/x3d+xml"; ///<summary>X3D ISO standard for representing 3D computer graphics, X3DB binary files</summary> public const string ModelX3DBinary = "model/x3d+binary"; ///<summary>X3D ISO standard for representing 3D computer graphics, X3DV VRML files</summary> public const string ModelX3DVrml = "model/x3d+vrml"; ///<summary>XHTML; Defined by RFC 3236</summary> public const string ApplicationXhtmlXml = "application/xhtml+xml"; ///<summary>ZIP archive files; Registered[7]</summary> public const string ApplicationZip = "application/zip"; } }
51.573718
493
0.698776
[ "MIT" ]
PowerDG/Dg.KMS.Web
PowerDgKMS/dgPower.KMS/5.4.0/aspnet-core/src/dgPower.KMS.Application/Net/MimeTypes/MimeTypeNames.cs
16,093
C#
using Newtonsoft.Json; namespace Slack.NetStandard.Messages.Elements { public class MultiChannelsSelect : IMessageElement { public MultiChannelsSelect(){} public MultiChannelsSelect(string actionId, string placeholder) { ActionId = actionId; Placeholder = placeholder; } public const string ElementType = "multi_channels_select"; [JsonProperty("type")] public string Type => ElementType; [JsonProperty("placeholder")] public PlainText Placeholder { get; set; } [JsonProperty("action_id")] public string ActionId { get; set; } [JsonProperty("initial_channels", NullValueHandling = NullValueHandling.Ignore)] public string[] InitialChannels { get; set; } [JsonProperty("confirm", NullValueHandling = NullValueHandling.Ignore)] public Confirmation Confirm { get; set; } [JsonProperty("max_selected_items", NullValueHandling = NullValueHandling.Ignore)] public int? MaxSelectedItems { get; set; } } }
32.393939
90
0.664172
[ "MIT" ]
stoiveyp/Slack.NetStandard
Slack.NetStandard/Messages/Elements/MultiChannelsSelect.cs
1,071
C#
 namespace Sparkle.Data.Entity.Networks { using Sparkle.Data.Networks; using Sparkle.Entities.Networks; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class CompanyRelationshipTypesRepository : BaseNetworkRepositoryInt<CompanyRelationshipType>, ICompanyRelationshipTypesRepository { [System.Diagnostics.DebuggerStepThrough] public CompanyRelationshipTypesRepository(NetworksEntities context, Func<NetworksEntities> factory) : base(context, factory, m => m.CompanyRelationshipTypes) { } public IList<CompanyRelationshipType> GetAll(int networkId) { return this.Set .Where(o => o.NetworkId == networkId) .ToList(); } public CompanyRelationshipType GetByAlias(string alias, int networkId) { return this.Set .Where(o => o.Alias == alias && o.NetworkId == networkId) .SingleOrDefault(); } public IList<CompanyRelationshipType> GetByKnownType(KnownCompanyRelationshipType type, int networkId) { return this.Set .Where(o => o.NetworkId == networkId && o.KnownType == (byte)type) .ToList(); } } }
33.309524
141
0.610436
[ "MPL-2.0" ]
SparkleNetworks/SparkleNetworks
src/Sparkle.Data.Entity/Networks/CompanyRelationshipTypesRepository.cs
1,401
C#
using System; using System.Collections.Generic; using System.Text; namespace Bitter.Core { public class BList<T>:List<T>where T:class,new() { } }
13.333333
51
0.6875
[ "MIT" ]
DavidChild/Bitter.Core.Orm.NetCore
src/Bitter.NetCore/Extention/BList.cs
162
C#
using YAF.Lucene.Net.Analysis.Util; using System.Collections.Generic; namespace YAF.Lucene.Net.Analysis.Miscellaneous { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /// <summary> /// Factory for <see cref="LengthFilter"/>. /// <code> /// &lt;fieldType name="text_lngth" class="solr.TextField" positionIncrementGap="100"&gt; /// &lt;analyzer&gt; /// &lt;tokenizer class="solr.WhitespaceTokenizerFactory"/&gt; /// &lt;filter class="solr.LengthFilterFactory" min="0" max="1" /&gt; /// &lt;/analyzer&gt; /// &lt;/fieldType&gt;</code> /// </summary> public class LengthFilterFactory : TokenFilterFactory { private readonly int min; private readonly int max; private readonly bool enablePositionIncrements; public const string MIN_KEY = "min"; public const string MAX_KEY = "max"; /// <summary> /// Creates a new <see cref="LengthFilterFactory"/> </summary> public LengthFilterFactory(IDictionary<string, string> args) : base(args) { min = RequireInt32(args, MIN_KEY); max = RequireInt32(args, MAX_KEY); enablePositionIncrements = GetBoolean(args, "enablePositionIncrements", true); if (args.Count > 0) { throw new System.ArgumentException("Unknown parameters: " + args); } } public override TokenStream Create(TokenStream input) { #pragma warning disable 612, 618 var filter = new LengthFilter(m_luceneMatchVersion, enablePositionIncrements, input, min, max); #pragma warning restore 612, 618 return filter; } } }
41.095238
108
0.628428
[ "Apache-2.0" ]
AlbertoP57/YAFNET
yafsrc/Lucene.Net/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LengthFilterFactory.cs
2,529
C#
#region License /* Copyright 2019 James F. Bellinger <http://www.zer7.com/software/hidsharp> 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 using System; namespace HidSharp.Experimental { [Flags] public enum BleCccd : ushort { None = 0, Notification = 1, Indication = 2 } }
27.966667
76
0.706794
[ "Apache-2.0" ]
AkiSakurai/HIDSharpCore
HidSharp/Experimental/BleCccd.cs
841
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace lpubsppop01.AnyTextFilterVSIX { // ref. http://stackoverflow.com/questions/717299/wpf-setting-the-width-and-height-as-a-percentage-value class DoubleToMultipliedConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { try { return System.Convert.ToDouble(value) * System.Convert.ToDouble(parameter); } catch { return value; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { try { return System.Convert.ToDouble(value) / System.Convert.ToDouble(parameter); } catch { return value; } } #endregion } class DoubleToHalfBinding : Binding { #region Constructor public DoubleToHalfBinding(string path) : base(path) { Converter = new DoubleToMultipliedConverter(); ConverterParameter = 0.5; } #endregion } }
26.087719
125
0.563551
[ "MIT" ]
lpubsppop01/AnyFilterVSIX
AnyTextFilterVSIX/_MyLib/Converters/DoubleToMultipliedConverter.cs
1,489
C#
namespace Avalonia.Media { public sealed class LineSegment : PathSegment { /// <summary> /// Defines the <see cref="Point"/> property. /// </summary> public static readonly StyledProperty<Point> PointProperty = AvaloniaProperty.Register<LineSegment, Point>(nameof(Point)); /// <summary> /// Gets or sets the point. /// </summary> /// <value> /// The point. /// </value> public Point Point { get { return GetValue(PointProperty); } set { SetValue(PointProperty, value); } } protected internal override void ApplyTo(StreamGeometryContext ctx) { ctx.LineTo(Point); } public override string ToString() => $"L {Point}"; } }
27.129032
87
0.524376
[ "MIT" ]
0x0ade/Avalonia
src/Avalonia.Base/Media/LineSegment.cs
841
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using ExcelToDbf.Sources.Core; using ExcelToDbf.Sources.Core.Data; using ExcelToDbf.Sources.Core.Data.TData; using ExcelToDbf.Sources.Core.Data.Xml; using ExcelToDbf.Sources.Core.External; using Microsoft.VisualStudio.TestTools.UnitTesting; using SocialExplorer.IO.FastDBF; using UnitTests; namespace DomofonExcelToDbfTests.Tests.DBFClass { [TestClass] public class FileTests { private string dbfFileName; private DBF dbf; private Encoding encoding; private List<Xml_DbfField> fields; private Dictionary<string, TVariable> variables; [TestInitialize] public void Startup() { Logger.SetLevel(Logger.LogLevel.DEBUG); encoding = Encoding.UTF8; fields = TestRepository.getFields(); variables = TestRepository.getVariables(); dbfFileName = Path.GetTempFileName(); dbf = new DBF(dbfFileName, fields, encoding); dbf.appendRecord(variables); Assert.AreEqual(dbf.Writed, 1); dbf.close(); } [TestCleanup] public void Cleanup() { TestLibrary.safeDelete(dbfFileName); } [TestMethod] public void IsHeadersCorrect() { DbfFile dbfFile = new DbfFile(encoding); dbfFile.Open(dbfFileName, FileMode.Open); Assert.AreEqual(fields.Count, dbfFile.Header.ColumnCount); for (int i=0;i<fields.Count;i++) Assert.AreEqual(dbfFile.Header[i].Name, fields[i].name); } [TestMethod] public void IsDataCorrect() { DbfFile dbfFile = new DbfFile(encoding); dbfFile.Open(dbfFileName, FileMode.Open); DbfRecord orec = new DbfRecord(dbfFile.Header); Assert.IsTrue(dbfFile.ReadNext(orec)); Assert.AreEqual(DbfColumn.DbfColumnType.Character, orec.Column(0).ColumnType); Assert.AreEqual(DbfColumn.DbfColumnType.Number, orec.Column(1).ColumnType); Assert.AreEqual(DbfColumn.DbfColumnType.Date, orec.Column(2).ColumnType); // DBF возвращает строки такой длины, какая указана в хедерах при создании string fio = "Ivanov Ivan Ivanovich"; Assert.AreEqual(fio + new String(' ', 40 - fio.Length), orec[0]); string num = "12.3456"; Assert.AreEqual(new String(' ',10 - num.Length) + num, orec[1]); Assert.AreEqual("20011122", orec[2]); } [TestMethod] public void RepeatClose() { dbf.close(); dbf.close(); } [TestMethod] public void IsFileCreated() { bool exists = File.Exists(dbfFileName); Assert.IsTrue(exists); } [TestMethod] public void IsFileDeleted() { dbf.delete(); bool exists = File.Exists(dbfFileName); Assert.IsFalse(exists); } } public class TestRepository { public static List<Xml_DbfField> getFields() { List<Xml_DbfField> data = new List<Xml_DbfField> { new Xml_DbfField { name = "fio", type = "string", length = "40", text = "$FIO"}, new Xml_DbfField { name = "summa", type = "numeric", length = "10,4", text = "$SUMMA"}, new Xml_DbfField { name = "data", type = "date", length = "8", text = "$DATE"}, new Xml_DbfField { name = "test", type = "string", length = "8", text = "$TEST"}, }; return data; } public static Dictionary<string, TVariable> getVariables() { Dictionary<string, TVariable> data = new Dictionary<string, TVariable>(); var tvariable = new TVariable("FIO"); tvariable.Set("Ivanov Ivan Ivanovich"); data.Add(tvariable.name, tvariable); var tnumeric = new TNumeric("SUMMA"); tnumeric.Set(12.3456f); data.Add(tnumeric.name, tnumeric); var tdate = new TDate("DATE"); tdate.Set("22.11.2001"); data.Add(tdate.name, tdate); return data; } } }
30.794326
103
0.573468
[ "Apache-2.0" ]
NoTimeForHero/ExcelToDbf
UnitTests/Tests/DBFClass/FileTests.cs
4,401
C#
using UnityEditor; using UnityEngine; // Using a property drawer to allow any class to have a field of type GuidRefernce and still get good UX // If you are writing your own inspector for a class that uses a GuidReference, drawing it with // EditorLayout.PropertyField(prop) or similar will get this to show up automatically namespace SaG.GuidReferences.Editor { [CustomPropertyDrawer(typeof(GuidReference))] public class GuidReferenceDrawer : PropertyDrawer { SerializedProperty guidProp; SerializedProperty sceneProp; SerializedProperty nameProp; // cache off GUI content to avoid creating garbage every frame in editor GUIContent sceneLabel = new GUIContent("Containing Scene", "The target object is expected in this scene asset."); GUIContent clearButtonGUI = new GUIContent("Clear", "Remove Cross Scene Reference"); // add an extra line to display source scene for targets public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return base.GetPropertyHeight(property, label) + EditorGUIUtility.singleLineHeight; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { guidProp = property.FindPropertyRelative("serializedGuid"); nameProp = property.FindPropertyRelative("cachedName"); sceneProp = property.FindPropertyRelative("cachedScene"); // Using BeginProperty / EndProperty on the parent property means that // prefab override logic works on the entire property. EditorGUI.BeginProperty(position, label, property); position.height = EditorGUIUtility.singleLineHeight; // Draw prefix label, returning the new rect we can draw in var guidCompPosition = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); System.Guid currentGuid; GameObject currentGO = null; // working with array properties is a bit unwieldy // you have to get the property at each index manually byte[] byteArray = new byte[16]; int arraySize = guidProp.arraySize; for( int i = 0; i < arraySize; ++i ) { var byteProp = guidProp.GetArrayElementAtIndex(i); byteArray[i] = (byte)byteProp.intValue; } currentGuid = new System.Guid(byteArray); currentGO = GuidManagerSingleton.ResolveGuid(currentGuid); GuidComponent currentGuidComponent = currentGO != null ? currentGO.GetComponent<GuidComponent>() : null; GuidComponent component = null; if (currentGuid != System.Guid.Empty && currentGuidComponent == null) { // if our reference is set, but the target isn't loaded, we display the target and the scene it is in, and provide a way to clear the reference float buttonWidth = 55.0f; guidCompPosition.xMax -= buttonWidth; bool guiEnabled = GUI.enabled; GUI.enabled = false; EditorGUI.LabelField(guidCompPosition, new GUIContent(nameProp.stringValue, "Target GameObject is not currently loaded."), EditorStyles.objectField); GUI.enabled = guiEnabled; Rect clearButtonRect = new Rect(guidCompPosition); clearButtonRect.xMin = guidCompPosition.xMax; clearButtonRect.xMax += buttonWidth; if (GUI.Button(clearButtonRect, clearButtonGUI, EditorStyles.miniButton)) { ClearPreviousGuid(); } } else { // if our object is loaded, we can simply use an object field directly component = EditorGUI.ObjectField(guidCompPosition, currentGuidComponent, typeof(GuidComponent), true) as GuidComponent; } if (currentGuidComponent != null && component == null) { ClearPreviousGuid(); } // if we have a valid reference, draw the scene name of the scene it lives in so users can find it if (component != null) { nameProp.stringValue = component.name; string scenePath = component.gameObject.scene.path; sceneProp.objectReferenceValue = AssetDatabase.LoadAssetAtPath<SceneAsset>(scenePath); // only update the GUID Prop if something changed. This fixes multi-edit on GUID References if (component != currentGuidComponent) { byteArray = component.GetGuid().ToByteArray(); arraySize = guidProp.arraySize; for (int i = 0; i < arraySize; ++i) { var byteProp = guidProp.GetArrayElementAtIndex(i); byteProp.intValue = byteArray[i]; } } } EditorGUI.indentLevel++; position.y += EditorGUIUtility.singleLineHeight; bool cachedGUIState = GUI.enabled; GUI.enabled = false; EditorGUI.ObjectField(position, sceneLabel, sceneProp.objectReferenceValue, typeof(SceneAsset), false); GUI.enabled = cachedGUIState; EditorGUI.indentLevel--; EditorGUI.EndProperty(); } void ClearPreviousGuid() { nameProp.stringValue = string.Empty; sceneProp.objectReferenceValue = null; int arraySize = guidProp.arraySize; for (int i = 0; i < arraySize; ++i) { var byteProp = guidProp.GetArrayElementAtIndex(i); byteProp.intValue = 0; } } } }
43.445255
165
0.606519
[ "MIT" ]
STARasGAMES/Guid-References
Assets/SaG/GuidReferences/Editor/GuidReferenceDrawer.cs
5,954
C#
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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 NakedObjects.Architecture.Component { public interface ITransactionManager { void StartTransaction(); bool FlushTransaction(); void AbortTransaction(); void UserAbortTransaction(); void EndTransaction(); /// <summary> /// Number of nested transaction levels; 0 indicates that no transaction is running /// </summary> int TransactionLevel {get;} } // Copyright (c) Naked Objects Group Ltd. }
50.272727
136
0.71519
[ "Apache-2.0" ]
Giovanni-Russo-Boscoli/NakedObjectsFramework
Core/NakedObjects.Architecture/Component/ITransactionManager.cs
1,106
C#
using System; using System.IO; using System.Text.Json; namespace SKIT.FlurlHttpClient.Wechat.Work.UnitTests { class TestConfigs { static TestConfigs() { // NOTICE: 请在项目根目录下按照 appsettings.json 的格式填入测试参数。 // WARN: 敏感信息请不要提交到 git! using var stream = File.OpenRead("appsettings.json"); using var json = JsonDocument.Parse(stream); var config = json.RootElement.GetProperty("WechatConfig"); WechatCorpId = config.GetProperty("CorpId").GetString(); WechatAgentId = int.Parse(config.GetProperty("AgentId").GetString()); WechatAgentSecret = config.GetProperty("AgentSecret").GetString(); ProjectSourceDirectory = json.RootElement.GetProperty("ProjectSourceDirectory").GetString(); ProjectTestDirectory = json.RootElement.GetProperty("ProjectTestDirectory").GetString(); } public static readonly string WechatCorpId; public static readonly int WechatAgentId; public static readonly string WechatAgentSecret; public static readonly string ProjectSourceDirectory; public static readonly string ProjectTestDirectory; } }
35.647059
104
0.676568
[ "MIT" ]
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
test/SKIT.FlurlHttpClient.Wechat.Work.UnitTests/TestConfigs.cs
1,276
C#
using Avalonia; using System; namespace Aura.UI.Helpers { public static class Maths { public static double ToSexagesimalDegrees(this double centesimalDegrees) => centesimalDegrees * 180 / 200; public static double ToDegrees(this double radians) => 180 * radians / Math.PI; public static double ToRadians(this double degrees) => degrees * Math.PI / 180; public static byte ToByte(this double d) => (byte)d; public static float ToFloat(this double d) => (float)d; public static byte FromFloat(float d) => (d < 0 || d > 1) ? throw new ArgumentOutOfRangeException($"the numbre {d} is less than 0 or greater than 1") : (byte)(d * 255); public static double ValueFromMinMaxAngle(double angle, double min, double max) { //example: max:100 min:-100 angle:180 expected value:0 double range = max - min; //max - min = 100 - (-100) = 200 double angle_percent = PercentageOf(360, angle);//percentage:50% double percentage_resolved = ValueByPercentage(range, angle_percent); //percent(200,50) = 100 double value = min + percentage_resolved;//-100 + 100 = 0! the expected value return value;// * 180 / Math.PI; } public static double AngleFromMinMaxValue(double value, double min, double max) { var range = max - min; var vm = value - min; return 360 * vm / range; } public static bool CircleContainsPoint(Point point, Point circleCenter, double radius) { double x1, x2, y1, y2; x1 = point.X; y1 = point.Y; x2 = circleCenter.X; y2 = circleCenter.Y; return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)) <= radius; } public static bool CircularCrownContainsPoint(Point point, Point circleCenter, double internalRadius, double externalRadius) => CircleContainsPoint(point, circleCenter, externalRadius) && !CircleContainsPoint(point, circleCenter, internalRadius); public static bool TriangleContains(Point a, Point b, Point c, Point point) { var p = point; //Sea d el segmento ab. var d = b - a; //Sea e el segmento ac. var e = c - a; //Variable de ponderación a~b var w1 = (e.X * (a.Y - p.Y) + e.Y * (p.X - a.X)) / (d.X * e.Y - d.Y * e.X); //Variable de ponderación a~c var w2 = (p.Y - a.Y - w1 * d.Y) / e.Y; //El punto p se encuentra dentro del triángulo //si se cumplen las 3 condiciones: if ((w1 >= 0.0) && (w2 >= 0.0) && ((w1 + w2) <= 1.0)) return true; else return false; } //Source: https://social.msdn.microsoft.com/Forums/en-US/02681c52-a491-4fde-a6e7-3d5e81c3cdad/radial-slider-implementation-in-xaml?forum=wpf public static double AngleOf(Point pos, double radius) { Point center = new Point(radius, radius); double xDiff = center.X - pos.X; double yDiff = center.Y - pos.Y; double r = Math.Sqrt(xDiff * xDiff + yDiff * yDiff); //Calculate the angle double angle = Math.Acos((center.Y - pos.Y) / r); if (pos.X < radius) angle = 2 * Math.PI - angle; if (double.IsNaN(angle)) return 0.0; else return angle; } public static double PercentageOf(double total, double value) => value * 100 / total; public static double ValueByPercentage(double total, double percentage) => total * percentage / 100; public static double Pitagoras(double AB, double BC) => Math.Sqrt(Math.Pow(AB, 2) + Math.Pow(BC, 2)); public static double TriangleSideByRadius(double r) => Math.Sqrt(4 * (Math.Pow(r, 2) - Math.Pow(r / 2, 2))); public static double TriangleHeightBySide(double side) => Math.Sqrt(3) * side / 2; public static Point Rotate(this Point pointToRotate, Point centerPoint, double angleInDegrees) { double angleInRadians = angleInDegrees * (Math.PI / 180); double cosTheta = Math.Cos(angleInRadians); double sinTheta = Math.Sin(angleInRadians); return new Point( (cosTheta * (pointToRotate.X - centerPoint.X) - sinTheta * (pointToRotate.Y - centerPoint.Y) + centerPoint.X), (sinTheta * (pointToRotate.X - centerPoint.X) + cosTheta * (pointToRotate.Y - centerPoint.Y) + centerPoint.Y)); } public static double DistanceBetweenTwoPoints(Point p1, Point p2) => DistanceBetweenTwoPoints(p1.X, p2.X, p1.Y, p2.Y); public static double DistanceBetweenTwoPoints(double x1, double x2, double y1, double y2) { return ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } private static void MinMaxRgb(out double min, out double max, double r, double g, double b) { if (r > g) { max = r; min = g; } else { max = g; min = r; } if (b > max) { max = b; } else if (b < min) { min = b; } } public static double GetHue(double r, double g, double b) { if (r == g && g == b) return 0f; MinMaxRgb(out double min, out double max, r, g, b); double delta = max - min; double hue; if (r == max) hue = (g - b) / delta; else if (g == max) hue = (b - r) / delta + 2f; else hue = (r - g) / delta + 4f; hue *= 60f; if (hue < 0f) hue += 360f; return hue; } } }
36.140351
148
0.52233
[ "MIT" ]
punker76/Aura.UI
src/Aura.UI/Helpers/Maths.cs
6,185
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.AzureNextGen.Network.V20190401 { public static class GetConnectionMonitor { public static Task<GetConnectionMonitorResult> InvokeAsync(GetConnectionMonitorArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetConnectionMonitorResult>("azure-nextgen:network/v20190401:getConnectionMonitor", args ?? new GetConnectionMonitorArgs(), options.WithVersion()); } public sealed class GetConnectionMonitorArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the connection monitor. /// </summary> [Input("connectionMonitorName", required: true)] public string ConnectionMonitorName { get; set; } = null!; /// <summary> /// The name of the Network Watcher resource. /// </summary> [Input("networkWatcherName", required: true)] public string NetworkWatcherName { get; set; } = null!; /// <summary> /// The name of the resource group containing Network Watcher. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetConnectionMonitorArgs() { } } [OutputType] public sealed class GetConnectionMonitorResult { /// <summary> /// Determines if the connection monitor will start automatically once created. /// </summary> public readonly bool? AutoStart; /// <summary> /// Describes the destination of connection monitor. /// </summary> public readonly Outputs.ConnectionMonitorDestinationResponse Destination; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string? Etag; /// <summary> /// Connection monitor location. /// </summary> public readonly string? Location; /// <summary> /// Monitoring interval in seconds. /// </summary> public readonly int? MonitoringIntervalInSeconds; /// <summary> /// The monitoring status of the connection monitor. /// </summary> public readonly string? MonitoringStatus; /// <summary> /// Name of the connection monitor. /// </summary> public readonly string Name; /// <summary> /// The provisioning state of the connection monitor. /// </summary> public readonly string ProvisioningState; /// <summary> /// Describes the source of connection monitor. /// </summary> public readonly Outputs.ConnectionMonitorSourceResponse Source; /// <summary> /// The date and time when the connection monitor was started. /// </summary> public readonly string? StartTime; /// <summary> /// Connection monitor tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Connection monitor type. /// </summary> public readonly string Type; [OutputConstructor] private GetConnectionMonitorResult( bool? autoStart, Outputs.ConnectionMonitorDestinationResponse destination, string? etag, string? location, int? monitoringIntervalInSeconds, string? monitoringStatus, string name, string provisioningState, Outputs.ConnectionMonitorSourceResponse source, string? startTime, ImmutableDictionary<string, string>? tags, string type) { AutoStart = autoStart; Destination = destination; Etag = etag; Location = location; MonitoringIntervalInSeconds = monitoringIntervalInSeconds; MonitoringStatus = monitoringStatus; Name = name; ProvisioningState = provisioningState; Source = source; StartTime = startTime; Tags = tags; Type = type; } } }
32.594203
201
0.606936
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Network/V20190401/GetConnectionMonitor.cs
4,498
C#
using System.Collections.Generic; using AutofacWebApiSample.Services; using Microsoft.AspNetCore.Mvc; namespace AutofacWebApiSample.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { readonly IValuesService _valuesService; public ValuesController(IValuesService valuesService) { _valuesService = valuesService; } // GET api/values [HttpGet] public IEnumerable<string> Get() { return _valuesService.FindAll(); } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return _valuesService.Find(id); } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
21.82
61
0.546288
[ "MIT" ]
augustoproiete-forks/autofac--Autofac
samples/AutofacWebApiSample/Controllers/ValuesController.cs
1,093
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AS.Data; using AS.Data.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using AutoMapper; namespace AS.Web { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ASDbContext>(options => options.UseSqlServer( this.Configuration.GetConnectionString("ASDbContextConnection"))); services.AddDefaultIdentity<ASUser>(options => { options.SignIn.RequireConfirmedAccount = false; // Password settings. options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 3; options.Password.RequiredUniqueChars = 0; options.User.RequireUniqueEmail = true; }).AddRoles<IdentityRole>() .AddDefaultUI() .AddEntityFrameworkStores<ASDbContext>(); services.AddControllersWithViews(); services.AddRazorPages(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
34.193182
143
0.605849
[ "MIT" ]
ValeriSt/AnimalShelter
Web/AS.Web/Startup.cs
3,009
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("LowPoints")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LowPoints")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("900f6df2-f0c1-4f09-91f6-9a569d86ac71")] // 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.432432
85
0.727848
[ "MIT" ]
augustogoncalves/civil3d-lowpoints
Properties/AssemblyInfo.cs
1,425
C#
using ShaderTools.LanguageServer.Protocol.MessageProtocol; using Newtonsoft.Json.Linq; namespace ShaderTools.LanguageServer.Protocol.LanguageServer { public class CodeActionRequest { public static readonly RequestType<CodeActionParams, CodeActionCommand[], object, TextDocumentRegistrationOptions> Type = RequestType<CodeActionParams, CodeActionCommand[], object, TextDocumentRegistrationOptions>.Create("textDocument/codeAction"); } /// <summary> /// Parameters for CodeActionRequest. /// </summary> public class CodeActionParams { /// <summary> /// The document in which the command was invoked. /// </summary> public TextDocumentIdentifier TextDocument { get; set; } /// <summary> /// The range for which the command was invoked. /// </summary> public Range Range { get; set; } /// <summary> /// Context carrying additional information. /// </summary> public CodeActionContext Context { get; set; } } public class CodeActionContext { public Diagnostic[] Diagnostics { get; set; } } public class CodeActionCommand { public string Title { get; set; } public string Command { get; set; } public JArray Arguments { get; set; } } }
29.375
143
0.613475
[ "Apache-2.0" ]
comfanter/HLSLTools-for-Source
src/ShaderTools.LanguageServer.Protocol/LanguageServer/CodeAction.cs
1,365
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using GafExplode.Gaf; using FsCheck; using System.Linq; namespace GafExplode.Tests { [TestClass] public class CompressedFrameWriterTest { private static readonly Arbitrary<Tuple<int, byte[]>> WidthAlignedItems = Arb.From<Tuple<int, byte[]>>() .Filter(tuple => { var (width, data) = tuple; return width > 0 && width <= data.Length; }) .MapFilter( tuple => { var (width, data) = tuple; var choppedLen = width * (data.Length / width); return Tuple.Create(width, data.Take(choppedLen).ToArray()); }, tuple => { var (width, data) = tuple; return data.Length % width == 0; }); private static byte[] CompressImage(byte transparencyIndex, int width, byte[] data) { var compressedDataStream = new MemoryStream(); CompressedFrameWriter.WriteCompressedImage(new MemoryStream(data, false), new BinaryWriter(compressedDataStream), width, transparencyIndex); return compressedDataStream.ToArray(); } private static byte[] CompressAndUncompressImage(byte transparencyIndex, int width, byte[] data) { var compressedData = CompressImage(transparencyIndex, width, data); return CompressedFrameReader.ReadCompressedImage(new BinaryReader(new MemoryStream(compressedData, false)), width, data.Length / width, transparencyIndex); } private static byte[] CompressRow(byte transparencyIndex, byte[] data) { var compressedDataStream = new MemoryStream(); CompressedFrameWriter.CompressRow(new MemoryStream(data, false), compressedDataStream, transparencyIndex); return compressedDataStream.ToArray(); } private static byte[] CompressAndUncompressRow(byte transparencyIndex, byte[] data) { var compressedData = CompressRow(transparencyIndex, data); return UncompressRow(transparencyIndex, data.Length, compressedData); } private static byte[] UncompressRow(byte transparencyIndex, int rowLength, byte[] compressedData) { var uncompressedDataStream = new MemoryStream(); CompressedFrameReader.DecompressRow(compressedData, uncompressedDataStream, rowLength, transparencyIndex); return uncompressedDataStream.ToArray(); } [TestMethod] public void TestWriteReadRowIdentity() { Prop.ForAll<byte, byte[]>((transparencyIndex, data) => { var uncompressedData = CompressAndUncompressRow(transparencyIndex, data); return uncompressedData.SequenceEqual(data).Collect(data.Length); }).QuickCheckThrowOnFailure(); } [TestMethod] public void TestWriteReadImageIdentity() { Prop.ForAll<byte>(transparencyIndex => Prop.ForAll(WidthAlignedItems, tuple => { var (width, data) = tuple; var uncompressedData = CompressAndUncompressImage(transparencyIndex, width, data); return uncompressedData.SequenceEqual(data).Collect($"width: {width}, height: {data.Length/width}, len: {data.Length}"); })).QuickCheckThrowOnFailure(); } [TestMethod] public void TestSimpleImage() { var transparencyIndex = (byte)231; var width = 1; var data = new byte[] { 1 }; var uncompressedData = CompressAndUncompressImage(transparencyIndex, width, data); CollectionAssert.AreEqual(data, uncompressedData); } [TestMethod] public void TestTransparentImage() { var transparencyIndex = (byte)9; var width = 4; var data = new byte[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, }; var compressedData = CompressImage(transparencyIndex, width, data); var expectedData = new byte[] { 0, 0, 0, 0, 0, 0 }; CollectionAssert.AreEqual(expectedData, compressedData); } [TestMethod] public void TestLongRow() { var data = new byte[250]; for (var i = 0; i < data.Length; ++i) { data[i] = 50; } data[data.Length - 1] = 6; var compressedData = CompressRow(9, data); var expectedData = new byte[] { 254, 50, 254, 50, 254, 50, 226, 50, 0, 6, }; CollectionAssert.AreEqual(expectedData, compressedData); CollectionAssert.AreEqual(data, UncompressRow(9, data.Length, compressedData)); } [TestMethod] public void TestLongNonRepeatingRow() { var data = new byte[250]; for (var i = 0; i < data.Length; ++i) { data[i] = (byte)(i+1); } var compressedData = CompressRow(0, data); var expectedData = new byte[254]; expectedData[0] = 252; Array.Copy(data, 0, expectedData, 1, 64); expectedData[65] = 252; Array.Copy(data, 64, expectedData, 66, 64); expectedData[130] = 252; Array.Copy(data, 128, expectedData, 131, 64); expectedData[195] = 228; Array.Copy(data, 192, expectedData, 196, 58); CollectionAssert.AreEqual(expectedData, compressedData); CollectionAssert.AreEqual(data, UncompressRow(9, data.Length, compressedData)); } [TestMethod] public void TestUncompressThisRow() { var data = new byte[] { 0x09, 0x00, 0x2e, 0x07, 0x00, 0xad, 0x03, 0x00, 0x2e, 0x03, 0x10, 0xaf, 0xf5, 0x2f, 0xaf, 0xf5, 0x03, 0x0c, 0xf5, 0xaf, 0x5f, 0x5f, 0x0b, }; var data2 = new byte[] { 0x09, 0x00, 0x2e, 0x07, 0x00, 0xad, 0x03, 0x00, 0x2e, 0x03, 0x10, 0xaf, 0xf5, 0x2f, 0xaf, 0xf5, 0x03, 0x04, 0xf5, 0xaf, 0x06, 0x5f, 0x0b, }; var s = new MemoryStream(); CompressedFrameReader.DecompressRow(data, s, 27, 9); var ss = s.ToArray(); var s2 = new MemoryStream(); CompressedFrameReader.DecompressRow(data2, s2, 27, 9); var ss2 = s.ToArray(); CollectionAssert.AreEqual(ss, ss2); } } }
33.004219
168
0.486321
[ "MIT", "BSD-3-Clause" ]
MHeasell/GafExplode
GafExplode.Tests/CompressedFrameWriterTest.cs
7,824
C#
/* The MIT License (MIT) Copyright (c) 2014-2017 Marc de Verdelhan & respective authors (see AUTHORS) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using TA4Net.Indicators.Helpers; using TA4Net.Interfaces; namespace TA4Net.Indicators.Adx { /** * ADX indicator. * Part of the Directional Movement System * <p> * </p> */ public class ADXIndicator : CachedIndicator<decimal> { private readonly MMAIndicator _averageDXIndicator; private readonly int _diTimeFrame; private readonly int _adxTimeFrame; public ADXIndicator(ITimeSeries series, int diTimeFrame, int adxTimeFrame) : base(series) { _diTimeFrame = diTimeFrame; _adxTimeFrame = adxTimeFrame; _averageDXIndicator = new MMAIndicator(new DXIndicator(series, diTimeFrame), adxTimeFrame); } public ADXIndicator(ITimeSeries series, int timeFrame) : this(series, timeFrame, timeFrame) { } protected override decimal Calculate(int index) { return _averageDXIndicator.GetValue(index); } public override string GetConfiguration() { return $"{GetType()}, DiTimeFrame: {_diTimeFrame}, AdxTimeFrame: {_adxTimeFrame}, MMAIndicator: {_averageDXIndicator.GetConfiguration()}"; } } }
36.723077
150
0.702137
[ "MIT" ]
Taats/TA4Net
TA4Net/Indicators/adx/ADXIndicator.cs
2,387
C#
using System.ComponentModel.DataAnnotations; namespace AspNetCoreSpa.STS.Models { public class ForgotPasswordViewModel { [Required(ErrorMessage = "EMAIL_REQUIRED")] [EmailAddress(ErrorMessage = "EMAIL_INVALID")] public string Email { get; set; } } }
24
54
0.690972
[ "MIT" ]
Anberm/AspNetCoreSpa
src/AspNetCoreSpa.STS/Models/AccountViewModels/ForgotPasswordViewModel.cs
290
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Threading.Tasks; using Microsoft.Coyote.Specifications; using Xunit; using Xunit.Abstractions; using Monitor = System.Threading.Monitor; namespace Microsoft.Coyote.SystematicTesting.Tests.Threading { public class LockStatementTests : BaseSystematicTest { private readonly object SyncObject1 = new object(); private string Value; public LockStatementTests(ITestOutputHelper output) : base(output) { } [Fact(Timeout = 5000)] public void TestSimpleLock() { this.Test(() => { lock (this.SyncObject1) { this.Value = "1"; this.TestReentrancy(); } var expected = "2"; Specification.Assert(this.Value == expected, "Value is {0} instead of {1}.", this.Value, expected); }); } private void TestReentrancy() { lock (this.SyncObject1) { this.Value = "2"; } } [Fact(Timeout = 5000)] public void TestWaitPulse() { this.Test(async () => { var t1 = Task.Run(this.TakeTask); var t2 = Task.Run(this.PutTask); await Task.WhenAll(t1, t2); var expected = "taken"; Specification.Assert(this.Value == expected, "Value is {0} instead of {1}.", this.Value, expected); }); } private void TakeTask() { lock (this.SyncObject1) { if (this.Value != "put") { Monitor.Wait(this.SyncObject1); } this.Value = "taken"; } } private void PutTask() { lock (this.SyncObject1) { this.Value = "put"; Monitor.Pulse(this.SyncObject1); } } [Fact(Timeout = 5000)] public void TestMonitorWithLockTaken() { this.Test(() => { object obj = new object(); bool lockTaken = false; Monitor.TryEnter(obj, ref lockTaken); if (lockTaken) { Monitor.Exit(obj); } Specification.Assert(lockTaken, "lockTaken is false"); }, GetConfiguration()); } } }
25.656863
115
0.462744
[ "MIT" ]
arunt1204/coyote
Tests/Tests.SystematicTesting/Threading/Locks/LockStatementTests.cs
2,619
C#
//------------------------------------------------------------ // Game Framework v3.x // Copyright © 2013-2017 Jiang Yin. All rights reserved. // Homepage: http://gameframework.cn/ // Feedback: mailto:jiangyin@gameframework.cn //------------------------------------------------------------ using UnityEngine; namespace UnityGameFramework.Runtime { internal sealed class WWWFormInfo { private readonly WWWForm m_WWWForm; private readonly object m_UserData; public WWWFormInfo(WWWForm wwwForm, object userData) { m_WWWForm = wwwForm; m_UserData = userData; } public WWWForm WWWForm { get { return m_WWWForm; } } public object UserData { get { return m_UserData; } } } }
22.55
63
0.465632
[ "MIT" ]
Echoflyer/ILGameFramework
Assets/Framework/Scripts/Runtime/WebRequest/WWWFormInfo.cs
905
C#
using System.Drawing; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; using SpriteVortex.Helpers; namespace SpriteVortex { public partial class AboutSplash : KryptonForm { public AboutSplash() { InitializeComponent(); versionLabel.Parent = splashPictureBox; versionLabel.BackColor = Color.Transparent; versionLabel.BringToFront(); versionLabel.ForeColor = Color.White; versionLabel.AutoSize = true; versionLabel.Text = Application.Version; } private const int Dropshadow = 0x20000; protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ClassStyle |= Dropshadow; return cp; } } private void splashPictureBox_Click(object sender, System.EventArgs e) { Close(); } } }
22.382979
78
0.554183
[ "MIT" ]
rafaelvasco/SpriteVortex
SpriteVortex/Forms/AboutSplash.cs
1,052
C#
using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Response { /// <summary> /// AlipayMobilePublicMenuUpdateResponse. /// </summary> public class AlipayMobilePublicMenuUpdateResponse : AlipayResponse { /// <summary> /// 结果码 /// </summary> [JsonPropertyName("code")] public override string Code { get; set; } /// <summary> /// 成功 /// </summary> [JsonPropertyName("msg")] public override string Msg { get; set; } } }
23.565217
70
0.573801
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Response/AlipayMobilePublicMenuUpdateResponse.cs
554
C#
namespace MMSComunication { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public interface IClient { } }
16.076923
37
0.674641
[ "MIT" ]
MartinNorberg/800xA-mms
.Net/800xAmms/MMSComunication/IClient.cs
211
C#
namespace Uqs.AppointmentBooking.Domain.DomainObjects; public class Appointment { public int Id { get; set; } public DateTime Starting { get; set; } public DateTime Ending { get; set; } public int CustomerId { get; set; } public Customer? Customer { get; set; } public int EmployeeId { get; set; } public Employee? Employee { get; set; } public int ServiceId { get; set; } public Service? Service { get; set; } }
30.066667
55
0.660754
[ "MIT" ]
PacktPublishing/Pragmatic-Test-Driven-Development-in-C-.NET
ch08/UqsAppointmentBooking/Uqs.AppointmentBooking.Domain/DomainObjects/Appointment.cs
453
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RightButtonView : MonoBehaviour { public FATController fatController; public Button btnBMZReset; public Button btnBrandfallAb; private Color previousTestModeColor; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void switchOnBrandFallLED() { Image img = btnBrandfallAb.GetComponent<Image>(); if(img.color == Color.yellow) img.color = Color.white; else img.color = Color.yellow; fatController.switchonBrandFallLED(); //LED and Button light //Set status that UE is abgeschaltet } public void switchOffBrandFallLED() { Image img = btnBrandfallAb.GetComponent<Image>(); img.color = Color.white; } public void BMZResetClicked() { fatController.resetBMZ(); } public void testModeOn() { Image img = btnBrandfallAb.GetComponent<Image>(); previousTestModeColor = img.color; img.color = Color.yellow; } public void testModeOff() { Image img = btnBrandfallAb.GetComponent<Image>(); img.color = previousTestModeColor; } }
21.166667
57
0.616321
[ "MIT" ]
Siedlerchr/safetydaysBMA
Assets/Scripts/FWControlPanel/RightButtonView.cs
1,399
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NaiveLanguageTools.Common; using System.Collections.ObjectModel; using NaiveLanguageTools.Parser.InOut; using NaiveLanguageTools.Generator.InOut; using NaiveLanguageTools.Parser; namespace NaiveLanguageTools.Generator.Builder { public class ProductionsBuilder<SYMBOL_ENUM,TREE_NODE> where SYMBOL_ENUM : struct where TREE_NODE : class { private readonly List<Production<SYMBOL_ENUM, TREE_NODE>> productions; private readonly StringRep<SYMBOL_ENUM> symbolsRep; public Productions<SYMBOL_ENUM, TREE_NODE> GetProductions( SYMBOL_ENUM eofSymbol, SYMBOL_ENUM syntaxErrorSymbol, GrammarReport<SYMBOL_ENUM,TREE_NODE> report) { return Productions<SYMBOL_ENUM, TREE_NODE>.Create(symbolsRep, productions, eofSymbol, syntaxErrorSymbol, report); } public ProductionsBuilder(StringRep<SYMBOL_ENUM> symbolsRep) { this.productions = new List<Production<SYMBOL_ENUM, TREE_NODE>>(); if (symbolsRep == null) throw new ArgumentNullException(); this.symbolsRep = symbolsRep; } private Production<SYMBOL_ENUM, TREE_NODE> addProduction(Production<SYMBOL_ENUM, TREE_NODE> prod) { productions.Add(prod); return prod; } #region user functions public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, params SYMBOL_ENUM[] ss) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, ss, null)); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, Func<TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, Func<object, TREE_NODE> action,int identityParamIndex = Production.NoIdentityFunction) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1 }, ProductionAction<TREE_NODE>.Convert(action), identityParamIndex)); } public Production<SYMBOL_ENUM, TREE_NODE> AddIdentityProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1) { return AddProduction(nonterm,recursive, s1, (object x) => (TREE_NODE)x, 0); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, Func<object, object, TREE_NODE> action, int identityParamIndex = Production.NoIdentityFunction) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2 }, ProductionAction<TREE_NODE>.Convert(action),identityParamIndex)); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, Func<object, object, object, TREE_NODE> action, int identityParamIndex = Production.NoIdentityFunction) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3 }, ProductionAction<TREE_NODE>.Convert(action),identityParamIndex)); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, Func<object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, Func<object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, Func<object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, Func<object, object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, Func<object, object, object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, SYMBOL_ENUM s9, Func<object, object, object, object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8, s9 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, SYMBOL_ENUM s9, SYMBOL_ENUM s10, Func<object, object, object, object, object, object, object, object, object, object,TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, SYMBOL_ENUM s9, SYMBOL_ENUM s10, SYMBOL_ENUM s11, Func<object, object, object, object, object, object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11 }, ProductionAction<TREE_NODE>.Convert(action))); } #endregion #region arbitrary functions /* public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, Func<TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, Func<object, TREE_NODE> action, int identityParamIndex = Production.NoIdentityFunction) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1 }, ProductionAction<TREE_NODE>.Convert(action), identityParamIndex)); } public Production<SYMBOL_ENUM, TREE_NODE> AddIdentityProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1) { return AddProduction(nonterm, recursive, lhsOrigin, s1, (object x) => (TREE_NODE)x, 0); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, SYMBOL_ENUM s2, Func<object, object, TREE_NODE> action, int identityParamIndex = Production.NoIdentityFunction) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1, s2 }, ProductionAction<TREE_NODE>.Convert(action), identityParamIndex)); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, Func<object, object, object, TREE_NODE> action, int identityParamIndex = Production.NoIdentityFunction) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1, s2, s3 }, ProductionAction<TREE_NODE>.Convert(action), identityParamIndex)); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, Func<object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1, s2, s3, s4 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, Func<object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, Func<object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, Func<object, object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, Func<object, object, object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, SYMBOL_ENUM s9, Func<object, object, object, object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8, s9 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, SYMBOL_ENUM s9, SYMBOL_ENUM s10, Func<object, object, object, object, object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddProduction(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM lhsOrigin, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, SYMBOL_ENUM s9, SYMBOL_ENUM s10, SYMBOL_ENUM s11, Func<object, object, object, object, object, object, object, object, object, object, object, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, lhsOrigin, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11 }, ProductionAction<TREE_NODE>.Convert(action))); } */ #endregion /*#region with template public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, Func<T1, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1, T2>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, Func<T1, T2, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1, T2, T3>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, Func<T1, T2, T3, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1, T2, T3, T4>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, Func<T1, T2, T3, T4, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1, T2, T3, T4, T5>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, Func<T1, T2, T3, T4, T5, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1, T2, T3, T4, T5, T6>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, Func<T1, T2, T3, T4, T5, T6, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1, T2, T3, T4, T5, T6, T7>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, Func<T1, T2, T3, T4, T5, T6, T7, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1, T2, T3, T4, T5, T6, T7, T8>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, Func<T1, T2, T3, T4, T5, T6, T7, T8, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1, T2, T3, T4, T5, T6, T7, T8, T9>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, SYMBOL_ENUM s9, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8, s9 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, SYMBOL_ENUM s9, SYMBOL_ENUM s10, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10,TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm, recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8, s9,s10 }, ProductionAction<TREE_NODE>.Convert(action))); } public Production<SYMBOL_ENUM, TREE_NODE> AddTemplateProduction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(SYMBOL_ENUM nonterm, RecursiveEnum recursive, SYMBOL_ENUM s1, SYMBOL_ENUM s2, SYMBOL_ENUM s3, SYMBOL_ENUM s4, SYMBOL_ENUM s5, SYMBOL_ENUM s6, SYMBOL_ENUM s7, SYMBOL_ENUM s8, SYMBOL_ENUM s9, SYMBOL_ENUM s10, SYMBOL_ENUM s11, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TREE_NODE> action) { return addProduction(new Production<SYMBOL_ENUM, TREE_NODE>(symbolsRep, nonterm,recursive, new SYMBOL_ENUM[] { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10,s11 }, ProductionAction<TREE_NODE>.Convert(action))); } #endregion*/ } }
57.477833
164
0.63627
[ "MIT" ]
macias/NaiveLanguageTools
NaiveLanguageTools.Generator/Builder/ProductionsBuilder.cs
23,338
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.trade.fastpay.ete.didi.pay /// </summary> public class AlipayTradeFastpayEteDidiPayRequest : IAopRequest<AlipayTradeFastpayEteDidiPayResponse> { /// <summary> /// 滴滴自动化测试支付 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.trade.fastpay.ete.didi.pay"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.545455
104
0.604247
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Request/AlipayTradeFastpayEteDidiPayRequest.cs
2,608
C#
using System; using System.Collections.Concurrent; using System.Diagnostics; using PacketDotNet; namespace TCC.Sniffing { public class TcpSniffer { private readonly ConcurrentDictionary<ConnectionId, TcpConnection> _connections = new ConcurrentDictionary<ConnectionId, TcpConnection>(); private readonly object _lock = new object(); private string SnifferType; //internal struct QPacket //{ // internal TcpConnection Connection; // internal uint SequenceNumber; // internal ArraySegment<byte> Packet; // internal QPacket(TcpConnection connection, uint sequenceNumber, ArraySegment<byte> packet) // { // Connection = connection; // SequenceNumber = sequenceNumber; // var data = new byte[packet.Count]; // Array.Copy(packet.Array, packet.Offset, data, 0, packet.Count); // Packet = new ArraySegment<byte>(data,0,data.Length); // } //} //private ConcurrentQueue<QPacket> _buffer = new ConcurrentQueue<QPacket>(); public TcpSniffer(IpSniffer ipSniffer) { ipSniffer.PacketReceived += Receive; SnifferType = ipSniffer.GetType().FullName; //Task.Run(()=>ParsePacketsLoop()); } public string TcpLogFile { get; set; } public event Action<TcpConnection> NewConnection; public event Action<TcpConnection> EndConnection; protected void OnNewConnection(TcpConnection connection) { var handler = NewConnection; handler?.Invoke(connection); } protected void OnEndConnection(TcpConnection connection) { var handler = EndConnection; handler?.Invoke(connection); } internal void RemoveConnection(TcpConnection connection) { TcpConnection temp; if (_connections.ContainsKey(connection.ConnectionId)) _connections.TryRemove(connection.ConnectionId, out temp); } //private void ParsePacketsLoop() //{ // while (true) // { // QPacket toProcess; // if (_buffer.TryDequeue(out toProcess)) // toProcess.Connection.HandleTcpReceived(toProcess.SequenceNumber, toProcess.Packet); // else System.Threading.Thread.Sleep(1); // } //} private void Receive(IPv4Packet ipData) { var tcpPacket = ipData.PayloadPacket as TcpPacket; if (tcpPacket == null || tcpPacket.DataOffset*4 > ipData.PayloadLength) return; //if (tcpPacket.Checksum!=0 && !tcpPacket.ValidTCPChecksum) return; var isFirstPacket = tcpPacket.Syn; var connectionId = new ConnectionId(ipData.SourceAddress, tcpPacket.SourcePort, ipData.DestinationAddress, tcpPacket.DestinationPort); TcpConnection connection; bool isInterestingConnection; if (isFirstPacket) { connection = new TcpConnection(connectionId, tcpPacket.SequenceNumber, RemoveConnection, SnifferType); OnNewConnection(connection); isInterestingConnection = connection.HasSubscribers; if (!isInterestingConnection) return; _connections[connectionId] = connection; Debug.Assert(tcpPacket.PayloadData.Length == 0); } else { isInterestingConnection = _connections.TryGetValue(connectionId, out connection); if (!isInterestingConnection) return; byte[] payload; try { payload = tcpPacket.PayloadData; } catch { return; } //_buffer.Enqueue(new QPacket(connection, tcpPacket.SequenceNumber, tcpPacket.Payload)); lock (_lock) { if (tcpPacket.Fin || tcpPacket.Rst) {OnEndConnection(connection); return;} connection.HandleTcpReceived(tcpPacket.SequenceNumber, payload); } //if (!string.IsNullOrEmpty(TcpLogFile)) // File.AppendAllText(TcpLogFile, // string.Format("{0} {1}+{4} | {2} {3}+{4} ACK {5} ({6})\r\n", // connection.CurrentSequenceNumber, tcpPacket.SequenceNumber, connection.BytesReceived, // connection.SequenceNumberToBytesReceived(tcpPacket.SequenceNumber), // tcpPacket.Payload.Count, tcpPacket.AcknowledgementNumber, // connection.BufferedPacketDescription)); } } } }
41.293103
118
0.587474
[ "MIT" ]
sarisia/Tera-custom-cooldowns
TCC.Core/Sniffing/TcpSniffer.cs
4,792
C#
using Autofac; using CompanyName.MyMeetings.BuildingBlocks.Application.Events; using CompanyName.MyMeetings.BuildingBlocks.Domain; using CompanyName.MyMeetings.BuildingBlocks.Infrastructure; using CompanyName.MyMeetings.BuildingBlocks.Infrastructure.DomainEventsDispatching; using CompanyName.MyMeetings.Modules.Payments.Application.Configuration.Commands; using CompanyName.MyMeetings.Modules.Payments.Infrastructure.AggregateStore; using CompanyName.MyMeetings.Modules.Payments.Infrastructure.Configuration.Processing.InternalCommands; using MediatR; using ICommandsScheduler = CompanyName.MyMeetings.Modules.Payments.Application.Configuration.Commands.ICommandsScheduler; namespace CompanyName.MyMeetings.Modules.Payments.Infrastructure.Configuration.Processing { internal class ProcessingModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<DomainEventsDispatcher>() .As<IDomainEventsDispatcher>() .InstancePerLifetimeScope(); builder.RegisterType<AggregateStoreDomainEventsAccessor>() .As<IDomainEventsAccessor>() .InstancePerLifetimeScope(); builder.RegisterType<PaymentsUnitOfWork>() .As<IUnitOfWork>() .InstancePerLifetimeScope(); builder.RegisterType<CommandsScheduler>() .As<ICommandsScheduler>() .InstancePerLifetimeScope(); builder.RegisterGenericDecorator( typeof(UnitOfWorkCommandHandlerDecorator<>), typeof(ICommandHandler<>)); builder.RegisterGenericDecorator( typeof(UnitOfWorkCommandHandlerWithResultDecorator<,>), typeof(ICommandHandler<,>)); builder.RegisterGenericDecorator( typeof(ValidationCommandHandlerDecorator<>), typeof(ICommandHandler<>)); builder.RegisterGenericDecorator( typeof(ValidationCommandHandlerWithResultDecorator<,>), typeof(ICommandHandler<,>)); builder.RegisterGenericDecorator( typeof(LoggingCommandHandlerDecorator<>), typeof(ICommandHandler<>)); builder.RegisterGenericDecorator( typeof(LoggingCommandHandlerWithResultDecorator<,>), typeof(ICommandHandler<,>)); builder.RegisterGenericDecorator( typeof(DomainEventsDispatcherNotificationHandlerDecorator<>), typeof(INotificationHandler<>)); builder.RegisterAssemblyTypes(Assemblies.Application) .AsClosedTypesOf(typeof(IDomainEventNotification<>)) .InstancePerDependency() .FindConstructorsWith(new AllConstructorFinder()); } } }
42.235294
121
0.682451
[ "MIT" ]
AndreiGanichev/modular-monolith-with-ddd
src/Modules/Payments/Infrastructure/Configuration/Processing/ProcessingModule.cs
2,874
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using RagnaLib.Domain.Entities; namespace RagnaLib.Infra.Data.Mappings { public static class ItemTypeMapping { public static void MappingItemType(this EntityTypeBuilder<ItemType> entity) { entity.HasKey(x => x.Id) .HasName("PK_ITEM_TYPE"); entity.ToTable("ItemType"); entity.Property(x => x.Id) .UseIdentityColumn(); entity.Property(x => x.Name) .IsRequired(); } } // public int Id { get; set; } // public string Name { get; set; } // public SubType SubType { get; set; } }
26.444444
83
0.598039
[ "MIT" ]
Berthot/RagnaLib
RagnaLib.Infra/Data/Mappings/ItemTypeMapping.cs
714
C#
/* _BEGIN_TEMPLATE_ { "id": "TB_RandomHand_ench", "name": [ "Random Hand Enchant - Not Player Facing", "Random Hand Enchant - Not Player Facing" ], "text": [ null, null ], "cardClass": "NEUTRAL", "type": "ENCHANTMENT", "cost": null, "rarity": null, "set": "TB", "collectible": null, "dbfId": 54478 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_TB_RandomHand_ench : SimTemplate { } }
16.481481
46
0.602247
[ "MIT" ]
chi-rei-den/Silverfish
cards/TB/TB/Sim_TB_RandomHand_ench.cs
445
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DummyRecord.cs" company="Daniel Dabrowski - rod.42n.pl"> // Copyright (c) 2008 Daniel Dabrowski - 42n. All rights reserved. // </copyright> // <summary> // Defines the DummyRecord type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Four2n.Orchard.MiniProfiler.Models { using global::Orchard.ContentManagement.Records; /// <summary> /// Dummy record for including this module in data configuring. /// </summary> public class DummyRecord : ContentPartRecord { } }
36.7
120
0.46049
[ "BSD-3-Clause" ]
bill-cooper/catc-cms
src/Orchard.Web/Modules/Four2n.MiniProfiler/Models/DummyRecord.cs
736
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ServicesCars { public partial class FrmOpacity : Form { public FrmOpacity() { InitializeComponent(); } private void FrmOpacity_Click(object sender, EventArgs e) { this.Hide(); } private void FrmOpacity_KeyPress(object sender, KeyPressEventArgs e) { this.Hide(); } } }
19.870968
76
0.631494
[ "Apache-2.0" ]
RaulMatias7/ServicesCar
ServicesCars/Forms/FrmOpacity.cs
618
C#
using System; using Com.QueoFlow.Peanuts.Net.Core.Domain.ProposedUsers.Dto; using Com.QueoFlow.Peanuts.Net.Core.Domain.Users; using Com.QueoFlow.Peanuts.Net.Core.Infrastructure; using NUnit.Framework; namespace Com.QueoFlow.Peanuts.Net.Core.Domain { [TestFixture] public class ProposedUserTest { [Test] public void TestProposedUserDataDto() { ProposedUserDataDto userDataDto = new ProposedUserDataDto(null, null, null, Salutation.Mister, null); ProposedUserDataDto otherUserDataDto = new ProposedUserDataDto("Vorname","Nachname","Titel",Salutation.Miss, new DateTime(1970,07,07)); DtoAssert.TestEqualsAndGetHashCode(userDataDto,otherUserDataDto); } [Test] public void TestProposedUserContactDto() { ProposedUserContactDto userContactDto = new ProposedUserContactDto("info@queo.com", "Straße-des-1.", "1", "01111", "Ort 1", Country.DE, "Unternehmen 1", "http://www.1.de", "0123/456789", "0123/4567890", "0151/123456"); ProposedUserContactDto userContactDto2 = new ProposedUserContactDto("info@csharp.com", "Straße-des-2.", "2", "02222", "Ort 2", Country.AT, "Unternehmen 2", "http://www.2.de", "0223/456789", "0223/4567890", "0251/123456"); DtoAssert.TestEqualsAndGetHashCode(userContactDto,userContactDto2); } } }
41.529412
233
0.672096
[ "MIT" ]
queoGmbH/peanuts
Peanuts.Net.Core.Test/src/Domain/ProposedUserTest.cs
1,416
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using Microsoft.CodeAnalysis.CodeLens; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Remote.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal partial class CodeAnalysisService { public async Task<ReferenceCount> GetReferenceCountAsync(DocumentId documentId, TextSpan textSpan, int maxResultCount) { try { using (Internal.Log.Logger.LogBlock(FunctionId.CodeAnalysisService_GetReferenceCountAsync, documentId.ProjectId.DebugName, CancellationToken)) { var solution = await GetSolutionAsync().ConfigureAwait(false); var syntaxNode = (await solution.GetDocument(documentId).GetSyntaxRootAsync().ConfigureAwait(false)).FindNode(textSpan); return await CodeLensReferencesServiceFactory.Instance.GetReferenceCountAsync(solution, documentId, syntaxNode, maxResultCount, CancellationToken).ConfigureAwait(false); } } catch (IOException) { // stream to send over result has closed before we // had chance to check cancellation } catch (OperationCanceledException) { // rpc connection has closed. // this can happen if client side cancelled the // operation } return null; } public async Task<IEnumerable<ReferenceLocationDescriptor>> FindReferenceLocationsAsync(DocumentId documentId, TextSpan textSpan) { try { using (Internal.Log.Logger.LogBlock(FunctionId.CodeAnalysisService_FindReferenceLocationsAsync, documentId.ProjectId.DebugName, CancellationToken)) { var solution = await GetSolutionAsync().ConfigureAwait(false); var syntaxNode = (await solution.GetDocument(documentId).GetSyntaxRootAsync().ConfigureAwait(false)).FindNode(textSpan); return await CodeLensReferencesServiceFactory.Instance.FindReferenceLocationsAsync(solution, documentId, syntaxNode, CancellationToken).ConfigureAwait(false); } } catch (IOException) { // stream to send over result has closed before we // had chance to check cancellation } catch (OperationCanceledException) { // rpc connection has closed. // this can happen if client side cancelled the // operation } return null; } public async Task<IEnumerable<ReferenceMethodDescriptor>> FindReferenceMethodsAsync(DocumentId documentId, TextSpan textSpan) { try { using (Internal.Log.Logger.LogBlock(FunctionId.CodeAnalysisService_FindReferenceMethodsAsync, documentId.ProjectId.DebugName, CancellationToken)) { var solution = await GetSolutionAsync().ConfigureAwait(false); var syntaxNode = (await solution.GetDocument(documentId).GetSyntaxRootAsync().ConfigureAwait(false)).FindNode(textSpan); return await CodeLensReferencesServiceFactory.Instance.FindReferenceMethodsAsync(solution, documentId, syntaxNode, CancellationToken).ConfigureAwait(false); } } catch (IOException) { // stream to send over result has closed before we // had chance to check cancellation } catch (OperationCanceledException) { // rpc connection has closed. // this can happen if client side cancelled the // operation } return null; } public async Task<string> GetFullyQualifiedName(DocumentId documentId, TextSpan textSpan) { try { using (Internal.Log.Logger.LogBlock(FunctionId.CodeAnalysisService_GetFullyQualifiedName, documentId.ProjectId.DebugName, CancellationToken)) { var solution = await GetSolutionAsync().ConfigureAwait(false); var syntaxNode = (await solution.GetDocument(documentId).GetSyntaxRootAsync().ConfigureAwait(false)).FindNode(textSpan); return await CodeLensReferencesServiceFactory.Instance.GetFullyQualifiedName(solution, documentId, syntaxNode, CancellationToken).ConfigureAwait(false); } } catch (IOException) { // stream to send over result has closed before we // had chance to check cancellation } catch (OperationCanceledException) { // rpc connection has closed. // this can happen if client side cancelled the // operation } return null; } } }
42.341085
163
0.603991
[ "Apache-2.0" ]
Trieste-040/https-github.com-dotnet-roslyn
src/Workspaces/Remote/ServiceHub/Services/CodeAnalysisService_CodeLens.cs
5,464
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoreCommand.Resolver { public abstract class ACommandResolver { private Dictionary<string, Func<Stream, Stream, bool>> _commands = new Dictionary<string, Func<Stream, Stream, bool>>(); /// <summary> /// Get the key used for a command registration from version and command name /// </summary> /// <param name="version">Version of the command</param> /// <param name="command">Name of the command</param> /// <returns>Key of the command to register</returns> private string GetCommandKey(string version, string command) { return version + command; } /// <summary> /// Register a command in the resolver with a specific version /// </summary> /// <param name="version">Version of the command</param> /// <param name="command">Name of the command to register</param> /// <param name="callback">Function to call in order to resolve command</param> public void Register(string version, string command, Func<Stream, Stream, bool> callback) { _commands[GetCommandKey(version, command)] = callback; } /// <summary> /// Resolve a command from its name and version /// </summary> /// <param name="version">Version of the command</param> /// <param name="command">Name of the command</param> /// <param name="input">Input stream to pass at resolution</param> /// <param name="output">Output stream to pass at resolution</param> /// <returns>False if resolution failed, true either</returns> protected bool Resolve(string version, string command, Stream input, Stream output) { if (!_commands.ContainsKey(GetCommandKey(version, command))) throw new KeyNotFoundException("No such package named " + command + " for version " + version); return _commands[GetCommandKey(version, command)](input, output); } /// <summary> /// Resolve a command only from it name /// Abstract to let children pass version name /// </summary> /// <param name="command">Name of the command to resolve</param> /// <param name="input">Input stream to pass at resolution</param> /// <param name="output">Output stream to pass at resolution</param> /// <returns>False if resolution failed, true either</returns> public abstract bool Resolve(string command, Stream input, Stream output); } }
43.322581
128
0.630678
[ "MIT" ]
FernandVEYRIER/DNAI
CoreCommand/Resolver/ACommandResolver.cs
2,688
C#
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ using NewRelic.Collections; using NUnit.Framework; namespace NewRelic.Core.Tests.NewRelic.Collections { class StaticCounterTests { [Test] public void StaticCounterTests_Battery() { const long nextIters = 1000L; StaticCounter.Reset(); Assert.That(StaticCounter.Value, Is.EqualTo(0), "counter should be 0 after Reset()"); for (var counter = 1L; counter < nextIters; ++counter) { Assert.That(StaticCounter.Next(), Is.EqualTo(counter), "Next() should return the next value in the sequence"); Assert.That(StaticCounter.Value, Is.EqualTo(counter), "Value should return current value"); } Assert.That(StaticCounter.Next(), Is.EqualTo(nextIters), "Next() should return the next value in the sequence"); Assert.That(StaticCounter.Reset(), Is.EqualTo(nextIters), "Reset() should return the value before being set to 0"); Assert.That(StaticCounter.Value, Is.EqualTo(0), "The result of Reset() should be a value of 0"); } } }
40.166667
127
0.642324
[ "Apache-2.0" ]
Faithlife/newrelic-dotnet-agent
tests/NewRelic.Core.Tests/NewRelic.Collections/StaticCounterTests.cs
1,205
C#
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 Lucene.Net.Spatial.Utils; using System.Data; namespace Lucene.Net.Spatial.Geometry { public class FloatLatLng : LatLng { private readonly double _lat; private readonly double _lng; private bool _normalized; public FloatLatLng(double lat, double lng) { if (lat > 90.0 || lat < -90.0) { throw new ConstraintException("Illegal latitude value " + lat); } _lat = lat; _lng = lng; } public FloatLatLng(LatLng ll) { _lat = ll.GetLat(); _lng = ll.GetLng(); } public override bool IsNormalized() { return _normalized || (_lng >= -180 && _lng <= 180); } public override bool IsFixedPoint() { return false; } public override LatLng Normalize() { if (IsNormalized()) return this; double delta = 0; if (_lng < 0) delta = 360; if (_lng >= 0) delta = -360; double newLng = _lng; while (newLng <= -180 || newLng >= 180) { newLng += delta; } var ret = new FloatLatLng(_lat, newLng) { _normalized = true }; return ret; } public override int GetFixedLat() { return FixedLatLng.DoubleToFixed(_lat); } public override int GetFixedLng() { return FixedLatLng.DoubleToFixed(_lng); } public override double GetLat() { return _lat; } public override double GetLng() { return _lng; } public override LatLng Copy() { return new FloatLatLng(this); } public override FixedLatLng ToFixed() { return new FixedLatLng(this); } public override FloatLatLng ToFloat() { return this; } public override LatLng CalculateMidpoint(LatLng other) { return new FloatLatLng((_lat + other.GetLat()) / 2.0, (_lng + other.GetLng()) / 2.0); } public override int GetHashCode() { const int prime = 31; long temp = Convert.ToInt64(_lat); int result = prime + (int)(temp ^ BitwiseHelper.ZeroFillRightShift(temp, 32)); temp = Convert.ToInt64(_lng); result = prime * result + (int)(temp ^ BitwiseHelper.ZeroFillRightShift(temp, 32)); result = prime * result + (_normalized ? 1231 : 1237); return result; } public override bool Equals(object obj) { if (this == obj) return true; if (GetType() != obj.GetType()) return false; var other = (FloatLatLng)obj; if (Convert.ToInt64(_lat) != Convert.ToInt64(other._lat)) return false; if (Convert.ToInt64(_lng) != Convert.ToInt64(other._lng)) return false; return _normalized == other._normalized; } } }
22.924138
88
0.662455
[ "Apache-2.0" ]
dineshkummarc/lucene.net
src/contrib/Spatial/Geometry/FloatLatLng.cs
3,326
C#
using System; using System.Threading.Tasks; namespace SteamSharp { /// <summary> /// Class allowing for abstracted querying of the IPlayerService interface /// </summary> public partial class PlayerService : SteamInterface { #region GetOwnedGames /// <summary> /// (Requires UserAuthenticator, APIKeyAuthenticator) Returns a list of games a player owns along with some playtime information, if the profile is publicly visible. /// Throws <see cref="SteamRequestException"/> on failure. /// <a href="https://developer.valvesoftware.com/wiki/Steam_Web_API#GetOwnedGames_.28v0001.29">See official documentation.</a> /// </summary> /// <param name="client"><see cref="SteamClient"/> instance to use.</param> /// <param name="steamID">SteamID to return friend's list for.</param> /// <param name="getAppInfo">Include game name and logo information in the output?</param> /// <param name="getPlayedFreeGames">By default, free games are excluded (as technically everyone owns them). If flag is true, all games the user has played at some point will be returned.</param> /// <returns><see cref="OwnedGames"/> object containing information about the specified user's game collection.</returns> public static OwnedGames GetOwnedGames( SteamClient client, string steamID, bool getAppInfo = true, bool getPlayedFreeGames = true ) { try { return GetOwnedGamesAsync( client, steamID, getAppInfo, getPlayedFreeGames ).Result; } catch( AggregateException e ) { if( e.InnerException != null ) throw e.InnerException; throw e; } } /// <summary> /// (Async) (Requires UserAuthenticator, APIKeyAuthenticator) /// Returns a list of games a player owns along with some playtime information, if the profile is publicly visible. /// Throws <see cref="SteamRequestException"/> on failure. /// <a href="https://developer.valvesoftware.com/wiki/Steam_Web_API#GetOwnedGames_.28v0001.29">See official documentation.</a> /// </summary> /// <param name="client"><see cref="SteamClient"/> instance to use.</param> /// <param name="steamID">SteamID to return friend's list for.</param> /// <param name="getAppInfo">Include game name and logo information in the output?</param> /// <param name="getPlayedFreeGames">By default, free games are excluded (as technically everyone owns them). If flag is true, all games the user has played at some point will be returned.</param> /// <returns><see cref="OwnedGames"/> object containing information about the specified user's game collection.</returns> public async static Task<OwnedGames> GetOwnedGamesAsync( SteamClient client, string steamID, bool getAppInfo = true, bool getPlayedFreeGames = true ) { client.IsAuthorizedCall( new Type[] { typeof( Authenticators.UserAuthenticator ), // Executes in User Context (private) typeof( Authenticators.APIKeyAuthenticator ) // Executes in API context (public) } ); SteamRequest request = new SteamRequest( SteamAPIInterface.IPlayerService, "GetOwnedGames", SteamMethodVersion.v0001 ); request.AddParameter( "steamid", steamID, ParameterType.QueryString ); request.AddParameter( "include_appinfo", ( ( getAppInfo ) ? 1 : 0 ), ParameterType.QueryString ); request.AddParameter( "include_played_free_games", ( ( getPlayedFreeGames ) ? 1 : 0 ), ParameterType.QueryString ); return VerifyAndDeserialize<GetOwnedGamesResponse>( ( await client.ExecuteAsync( request ) ) ).OwnedGames; } #endregion #region GetRecentlyPlayedGames /// <summary> /// (Requires Authentication) Returns a list of games a player has played in the last two weeks. /// Throws <see cref="SteamRequestException"/> on failure. /// <a href="https://developer.valvesoftware.com/wiki/Steam_Web_API#GetRecentlyPlayedGames_.28v0001.29">See official documentation.</a> /// </summary> /// <param name="client"><see cref="SteamClient"/> instance to use.</param> /// <param name="steamID">SteamID to return friend's list for.</param> /// <param name="maxSelect">Optionally limit response to a certain number of games. Defaults to -1, meaning no limit is imposed.</param> /// <returns><see cref="OwnedGames"/> object containing information about the specified user's game collection.</returns> public static PlayedGames GetRecentlyPlayedGames( SteamClient client, string steamID, int maxSelect = -1 ) { try { return GetRecentlyPlayedGamesAsync( client, steamID, maxSelect ).Result; } catch( AggregateException e ) { if( e.InnerException != null ) throw e.InnerException; throw e; } } /// <summary> /// (Requires Authentication) (Async) Returns a list of games a player has played in the last two weeks. /// Throws <see cref="SteamRequestException"/> on failure. /// <a href="https://developer.valvesoftware.com/wiki/Steam_Web_API#GetRecentlyPlayedGames_.28v0001.29">See official documentation.</a> /// </summary> /// <param name="client"><see cref="SteamClient"/> instance to use.</param> /// <param name="steamID">SteamID to return friend's list for.</param> /// <param name="maxSelect">Optionally limit response to a certain number of games. Defaults to -1, meaning no limit is imposed.</param> /// <returns><see cref="OwnedGames"/> object containing information about the specified user's game collection.</returns> public async static Task<PlayedGames> GetRecentlyPlayedGamesAsync( SteamClient client, string steamID, int maxSelect = -1 ) { SteamRequest request = new SteamRequest( SteamAPIInterface.IPlayerService, "GetRecentlyPlayedGames", SteamMethodVersion.v0001 ); request.AddParameter( "steamid", steamID, ParameterType.QueryString ); if( maxSelect > 0 ) request.AddParameter( "count", maxSelect, ParameterType.QueryString ); return VerifyAndDeserialize<GetRecentlyPlayedGamesResponse>( ( await client.ExecuteAsync( request ) ) ).PlayedGames; } #endregion #region IsPlayingSharedGame /// <summary> /// (Requires Authentication) Returns the original owner's SteamID if a borrowing account is currently playing the specified game. Null if not borrowed, or the borrower isn't currently playing the game. /// Throws <see cref="SteamRequestException"/> on failure. /// <a href="https://developer.valvesoftware.com/wiki/Steam_Web_API#IsPlayingSharedGame_.28v0001.29">See official documentation.</a> /// </summary> /// <param name="client"><see cref="SteamClient"/> instance to use.</param> /// <param name="steamID">SteamID to return friend's list for.</param> /// <param name="gameID">GameID (AppID) of the game you're interested in querying.</param> /// <returns></returns> public static SharedGameData IsPlayingSharedGame( SteamClient client, string steamID, int gameID ) { try { return IsPlayingSharedGameAsync( client, steamID, gameID ).Result; } catch( AggregateException e ) { if( e.InnerException != null ) throw e.InnerException; throw e; } } /// <summary> /// (Requires Authentication) (Async) Returns the original owner's SteamID if a borrowing account is currently playing the specified game. Null if not borrowed, or the borrower isn't currently playing the game. /// Throws <see cref="SteamRequestException"/> on failure. /// <a href="https://developer.valvesoftware.com/wiki/Steam_Web_API#IsPlayingSharedGame_.28v0001.29">See official documentation.</a> /// </summary> /// <param name="client"><see cref="SteamClient"/> instance to use.</param> /// <param name="steamID">SteamID to return friend's list for.</param> /// <param name="gameID">GameID (AppID) of the game you're interested in querying.</param> /// <returns></returns> public async static Task<SharedGameData> IsPlayingSharedGameAsync( SteamClient client, string steamID, int gameID ) { SteamRequest request = new SteamRequest( SteamAPIInterface.IPlayerService, "IsPlayingSharedGame", SteamMethodVersion.v0001 ); request.AddParameter( "steamid", steamID, ParameterType.QueryString ); request.AddParameter( "appid_playing", gameID, ParameterType.QueryString ); IsPlayingSharedGameObject obj = VerifyAndDeserialize<IsPlayingSharedGameResponse>( ( await client.ExecuteAsync( request ) ) ).IsPlayingSharedGame; if( String.IsNullOrEmpty( obj.LenderSteamID ) || obj.LenderSteamID == "0" ) { return new SharedGameData { IsUserPlayingSharedGame = false, GameOwnerSteamID = null, GameBorrowerSteamID = null }; } else { return new SharedGameData { IsUserPlayingSharedGame = true, GameOwnerSteamID = obj.LenderSteamID, GameBorrowerSteamID = steamID }; } } #endregion } }
54.220126
212
0.731702
[ "Apache-2.0" ]
ShaneC/SteamSharp
SteamSharp/SteamInterfaces/PlayerService.cs
8,623
C#
using System.IO; using Xunit; using Semmle.Util.Logging; using System.Runtime.InteropServices; namespace Semmle.Extraction.Tests { public class Layout { readonly ILogger Logger = new LoggerMock(); [Fact] public void TestDefaultLayout() { var layout = new Semmle.Extraction.Layout(null, null, null); var project = layout.LookupProjectOrNull("foo.cs"); // All files are mapped when there's no layout file. Assert.True(layout.FileInLayout("foo.cs")); // Test trap filename var tmpDir = Path.GetTempPath(); Directory.SetCurrentDirectory(tmpDir); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // `Directory.SetCurrentDirectory()` doesn't seem to work on macOS, // so disable this test on macOS, for now Assert.NotEqual(Directory.GetCurrentDirectory(), tmpDir); return; } var f1 = project.GetTrapPath(Logger, "foo.cs", TrapWriter.CompressionMode.Gzip); var g1 = TrapWriter.NestPaths(Logger, tmpDir, "foo.cs.trap.gz", TrapWriter.InnerPathComputation.ABSOLUTE); Assert.Equal(f1, g1); // Test trap file generation var trapwriterFilename = project.GetTrapPath(Logger, "foo.cs", TrapWriter.CompressionMode.Gzip); using (var trapwriter = project.CreateTrapWriter(Logger, "foo.cs", false, TrapWriter.CompressionMode.Gzip)) { trapwriter.Emit("1=*"); Assert.False(File.Exists(trapwriterFilename)); } Assert.True(File.Exists(trapwriterFilename)); File.Delete(trapwriterFilename); } [Fact] public void TestLayoutFile() { File.WriteAllLines("layout.txt", new string[] { "# Section", "TRAP_FOLDER=" + Path.GetFullPath("snapshot\\trap"), "ODASA_DB=snapshot\\db-csharp", "SOURCE_ARCHIVE=" + Path.GetFullPath("snapshot\\archive"), "ODASA_BUILD_ERROR_DIR=snapshot\build-errors", "-foo.cs", "bar.cs", "-excluded", "excluded/foo.cs", "included" }); var layout = new Semmle.Extraction.Layout(null, null, "layout.txt"); // Test general pattern matching Assert.True(layout.FileInLayout("bar.cs")); Assert.False(layout.FileInLayout("foo.cs")); Assert.False(layout.FileInLayout("goo.cs")); Assert.False(layout.FileInLayout("excluded/bar.cs")); Assert.True(layout.FileInLayout("excluded/foo.cs")); Assert.True(layout.FileInLayout("included/foo.cs")); // Test the trap file var project = layout.LookupProjectOrNull("bar.cs"); var trapwriterFilename = project.GetTrapPath(Logger, "bar.cs", TrapWriter.CompressionMode.Gzip); Assert.Equal(TrapWriter.NestPaths(Logger, Path.GetFullPath("snapshot\\trap"), "bar.cs.trap.gz", TrapWriter.InnerPathComputation.ABSOLUTE), trapwriterFilename); // Test the source archive var trapWriter = project.CreateTrapWriter(Logger, "bar.cs", false, TrapWriter.CompressionMode.Gzip); trapWriter.Archive("layout.txt", System.Text.Encoding.ASCII); var writtenFile = TrapWriter.NestPaths(Logger, Path.GetFullPath("snapshot\\archive"), "layout.txt", TrapWriter.InnerPathComputation.ABSOLUTE); Assert.True(File.Exists(writtenFile)); File.Delete("layout.txt"); } [Fact] public void TestTrapOverridesLayout() { // When you specify both a trap file and a layout, use the trap file. var layout = new Semmle.Extraction.Layout(Path.GetFullPath("snapshot\\trap"), null, "something.txt"); Assert.True(layout.FileInLayout("bar.cs")); var f1 = layout.LookupProjectOrNull("foo.cs").GetTrapPath(Logger, "foo.cs", TrapWriter.CompressionMode.Gzip); var g1 = TrapWriter.NestPaths(Logger, Path.GetFullPath("snapshot\\trap"), "foo.cs.trap.gz", TrapWriter.InnerPathComputation.ABSOLUTE); Assert.Equal(f1, g1); } [Fact] public void TestMultipleSections() { File.WriteAllLines("layout.txt", new string[] { "# Section 1", "TRAP_FOLDER=" + Path.GetFullPath("snapshot\\trap1"), "ODASA_DB=snapshot\\db-csharp", "SOURCE_ARCHIVE=" + Path.GetFullPath("snapshot\\archive1"), "ODASA_BUILD_ERROR_DIR=snapshot\build-errors", "foo.cs", "# Section 2", "TRAP_FOLDER=" + Path.GetFullPath("snapshot\\trap2"), "ODASA_DB=snapshot\\db-csharp", "SOURCE_ARCHIVE=" + Path.GetFullPath("snapshot\\archive2"), "ODASA_BUILD_ERROR_DIR=snapshot\build-errors", "bar.cs", }); var layout = new Semmle.Extraction.Layout(null, null, "layout.txt"); // Use Section 2 Assert.True(layout.FileInLayout("bar.cs")); var f1 = layout.LookupProjectOrNull("bar.cs").GetTrapPath(Logger, "bar.cs", TrapWriter.CompressionMode.Gzip); var g1 = TrapWriter.NestPaths(Logger, Path.GetFullPath("snapshot\\trap2"), "bar.cs.trap.gz", TrapWriter.InnerPathComputation.ABSOLUTE); Assert.Equal(f1, g1); // Use Section 1 Assert.True(layout.FileInLayout("foo.cs")); var f2 = layout.LookupProjectOrNull("foo.cs").GetTrapPath(Logger, "foo.cs", TrapWriter.CompressionMode.Gzip); var g2 = TrapWriter.NestPaths(Logger, Path.GetFullPath("snapshot\\trap1"), "foo.cs.trap.gz", TrapWriter.InnerPathComputation.ABSOLUTE); Assert.Equal(f2, g2); // boo.dll is not in the layout, so use layout from first section. Assert.False(layout.FileInLayout("boo.dll")); var f3 = layout.LookupProjectOrDefault("boo.dll").GetTrapPath(Logger, "boo.dll", TrapWriter.CompressionMode.Gzip); var g3 = TrapWriter.NestPaths(Logger, Path.GetFullPath("snapshot\\trap1"), "boo.dll.trap.gz", TrapWriter.InnerPathComputation.ABSOLUTE); Assert.Equal(f3, g3); // boo.cs is not in the layout, so return null Assert.False(layout.FileInLayout("boo.cs")); Assert.Null(layout.LookupProjectOrNull("boo.cs")); } [Fact] public void MissingLayout() { Assert.Throws<Extraction.Layout.InvalidLayoutException>(() => new Semmle.Extraction.Layout(null, null, "nosuchfile.txt")); } [Fact] public void EmptyLayout() { File.Create("layout.txt").Close(); Assert.Throws<Extraction.Layout.InvalidLayoutException>(() => new Semmle.Extraction.Layout(null, null, "layout.txt")); } [Fact] public void InvalidLayout() { File.WriteAllLines("layout.txt", new string[] { "# Section 1" }); Assert.Throws<Extraction.Layout.InvalidLayoutException>(() => new Semmle.Extraction.Layout(null, null, "layout.txt")); } class LoggerMock : ILogger { public void Dispose() { } public void Log(Severity s, string text) { } public void Log(Severity s, string text, params object[] args) { } } } static class TrapWriterTestExtensions { public static void Emit(this TrapWriter trapFile, string s) { trapFile.Emit(new StringTrapEmitter(s)); } class StringTrapEmitter : ITrapEmitter { readonly string Content; public StringTrapEmitter(string content) { Content = content; } public void EmitTrap(TextWriter trapFile) { trapFile.Write(Content); } } } }
41.00995
154
0.580856
[ "MIT" ]
Aphirak2018/codeql
csharp/extractor/Semmle.Extraction.Tests/Layout.cs
8,245
C#
using System; using System.Linq; using System.Collections.Generic; namespace _5.SoftuniParking { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); Dictionary<string, string> validations = new Dictionary<string, string>(); for (int i = 0; i < n; i++) { List<string> user = Console.ReadLine().Split().ToList(); string type = user[0]; string username = user[1]; if(type == "register") { if (!validations.ContainsKey(username)) { validations[username] = user[2]; Console.WriteLine($"{username} registered {user[2]} successfully"); } else { Console.WriteLine($"ERROR: already registered with plate number {validations[username]}"); } } else { if (!validations.ContainsKey(username)) { Console.WriteLine($"ERROR: user {username} not found"); } else { Console.WriteLine($"{username} unregistered successfully"); validations.Remove(username); } } } foreach (var kvp in validations) { Console.WriteLine($"{kvp.Key} => {kvp.Value}"); } } } }
31.169811
114
0.419492
[ "MIT" ]
VinsantSavov/SoftUni-Software-Engineering
CSharp-Fundamentals/Fundamentals - 2018/AssociativeArrays/AssociativeArrays-Exercise/5.SoftuniParking/Program.cs
1,654
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 waf-2015-08-24.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.WAF.Model { /// <summary> /// Container for the parameters to the GetLoggingConfiguration operation. /// <note> /// <para> /// This is <b>AWS WAF Classic</b> documentation. For more information, see <a href="https://docs.aws.amazon.com/waf/latest/developerguide/classic-waf-chapter.html">AWS /// WAF Classic</a> in the developer guide. /// </para> /// /// <para> /// <b>For the latest version of AWS WAF</b>, use the AWS WAFV2 API and see the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">AWS /// WAF Developer Guide</a>. With the latest version, AWS WAF has a single set of endpoints /// for regional and global use. /// </para> /// </note> /// <para> /// Returns the <a>LoggingConfiguration</a> for the specified web ACL. /// </para> /// </summary> public partial class GetLoggingConfigurationRequest : AmazonWAFRequest { private string _resourceArn; /// <summary> /// Gets and sets the property ResourceArn. /// <para> /// The Amazon Resource Name (ARN) of the web ACL for which you want to get the <a>LoggingConfiguration</a>. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=1224)] public string ResourceArn { get { return this._resourceArn; } set { this._resourceArn = value; } } // Check to see if ResourceArn property is set internal bool IsSetResourceArn() { return this._resourceArn != null; } } }
34.438356
172
0.64996
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/WAF/Generated/Model/GetLoggingConfigurationRequest.cs
2,514
C#
// Copyright (c) CBC/Radio-Canada. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using LinkIt.PublicApi; namespace LinkIt.Diagnostics { internal class LoadLinkDetails<TLinkedSource, TLinkedSourceModel> : ILoadLinkDetails where TLinkedSource : class, ILinkedSource<TLinkedSourceModel> { private readonly Stopwatch _stopwatch; private int _currentStepIndex; public LoadLinkDetails(LoadLinkCallDetails callDetails, IReadOnlyList<IReadOnlyList<Type>> referenceTypesToBeLoadedForEachLoadingLevel) { CallDetails = callDetails; Steps = GetSteps(referenceTypesToBeLoadedForEachLoadingLevel); CurrentStep = Steps[0]; _stopwatch = Stopwatch.StartNew(); } private static IReadOnlyList<LoadLinkStepDetails> GetSteps(IReadOnlyList<IReadOnlyList<Type>> referenceTypesToBeLoadedForEachLoadingLevel) { return referenceTypesToBeLoadedForEachLoadingLevel .Select((referenceTypes, index) => new LoadLinkStepDetails(referenceTypes, index + 1)) .ToList(); } public Type LinkedSourceType => typeof(TLinkedSource); public Type LinkedSourceModelType => typeof(TLinkedSourceModel); public LoadLinkCallDetails CallDetails { get; } public IReadOnlyList<object> Result { get; private set; } = new List<object>(); public IReadOnlyList<LoadLinkStepDetails> Steps { get; } public LoadLinkStepDetails CurrentStep { get; private set; } public TimeSpan? Took { get; private set; } internal void NextStep() { ++_currentStepIndex; CurrentStep = Steps[_currentStepIndex]; } internal void SetResult(IEnumerable<object> linkedSources) { Result = linkedSources.ToList(); } internal void LoadLinkEnd() { _stopwatch.Stop(); Took = _stopwatch.Elapsed; } } }
31.735294
146
0.670992
[ "MIT" ]
fynnen/LinkIt
src/LinkIt/Diagnostics/LoadLinkDetails.cs
2,158
C#
using System.Reflection; using System.Resources; 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("Extended Controls")] [assembly: AssemblyDescription("An extention to the Krypton toolkit suite for .NET framework 4.7 (https://github.com/Wagnerp/Krypton-NET-5.470).")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Extended Controls")] [assembly: AssemblyCopyright("Copyright © Peter Wagner (aka Wagnerp) & Simon Coghlan (aka Smurf-IV) 2018 - 2020 et al. All rights reserved.")] [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("1c9153e4-cdc4-44c9-9794-1d144fe87a1f")] // 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("5.470.1393.0")] [assembly: AssemblyFileVersion("5.470.1393.0")] [assembly: NeutralResourcesLanguage("en-GB")] [assembly: Dependency("System", LoadHint.Always)] [assembly: Dependency("System.Xml", LoadHint.Always)] [assembly: Dependency("System.Drawing", LoadHint.Always)] [assembly: Dependency("System.Windows.Forms", LoadHint.Always)] [assembly: Dependency("ComponentFactory.Krypton.Toolkit", LoadHint.Always)]
44.2
147
0.757164
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.470
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/Properties/AssemblyInfo.cs
1,992
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.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SageMaker.Model { /// <summary> /// This is the response object from the DescribeEndpointConfig operation. /// </summary> public partial class DescribeEndpointConfigResponse : AmazonWebServiceResponse { private AsyncInferenceConfig _asyncInferenceConfig; private DateTime? _creationTime; private DataCaptureConfig _dataCaptureConfig; private string _endpointConfigArn; private string _endpointConfigName; private string _kmsKeyId; private List<ProductionVariant> _productionVariants = new List<ProductionVariant>(); /// <summary> /// Gets and sets the property AsyncInferenceConfig. /// <para> /// Returns the description of an endpoint configuration created using the <a href="https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html"> /// <code>CreateEndpointConfig</code> </a> API. /// </para> /// </summary> public AsyncInferenceConfig AsyncInferenceConfig { get { return this._asyncInferenceConfig; } set { this._asyncInferenceConfig = value; } } // Check to see if AsyncInferenceConfig property is set internal bool IsSetAsyncInferenceConfig() { return this._asyncInferenceConfig != null; } /// <summary> /// Gets and sets the property CreationTime. /// <para> /// A timestamp that shows when the endpoint configuration was created. /// </para> /// </summary> [AWSProperty(Required=true)] public DateTime CreationTime { get { return this._creationTime.GetValueOrDefault(); } set { this._creationTime = value; } } // Check to see if CreationTime property is set internal bool IsSetCreationTime() { return this._creationTime.HasValue; } /// <summary> /// Gets and sets the property DataCaptureConfig. /// </summary> public DataCaptureConfig DataCaptureConfig { get { return this._dataCaptureConfig; } set { this._dataCaptureConfig = value; } } // Check to see if DataCaptureConfig property is set internal bool IsSetDataCaptureConfig() { return this._dataCaptureConfig != null; } /// <summary> /// Gets and sets the property EndpointConfigArn. /// <para> /// The Amazon Resource Name (ARN) of the endpoint configuration. /// </para> /// </summary> [AWSProperty(Required=true, Min=20, Max=2048)] public string EndpointConfigArn { get { return this._endpointConfigArn; } set { this._endpointConfigArn = value; } } // Check to see if EndpointConfigArn property is set internal bool IsSetEndpointConfigArn() { return this._endpointConfigArn != null; } /// <summary> /// Gets and sets the property EndpointConfigName. /// <para> /// Name of the SageMaker endpoint configuration. /// </para> /// </summary> [AWSProperty(Required=true, Max=63)] public string EndpointConfigName { get { return this._endpointConfigName; } set { this._endpointConfigName = value; } } // Check to see if EndpointConfigName property is set internal bool IsSetEndpointConfigName() { return this._endpointConfigName != null; } /// <summary> /// Gets and sets the property KmsKeyId. /// <para> /// Amazon Web Services KMS key ID Amazon SageMaker uses to encrypt data when storing /// it on the ML storage volume attached to the instance. /// </para> /// </summary> [AWSProperty(Max=2048)] public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } // Check to see if KmsKeyId property is set internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } /// <summary> /// Gets and sets the property ProductionVariants. /// <para> /// An array of <code>ProductionVariant</code> objects, one for each model that you want /// to host at this endpoint. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=10)] public List<ProductionVariant> ProductionVariants { get { return this._productionVariants; } set { this._productionVariants = value; } } // Check to see if ProductionVariants property is set internal bool IsSetProductionVariants() { return this._productionVariants != null && this._productionVariants.Count > 0; } } }
33.511364
181
0.609698
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/DescribeEndpointConfigResponse.cs
5,898
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.ProjectSystem.LanguageServices; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Xunit; using IOleAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.IAsyncServiceProvider; namespace Microsoft.VisualStudio.ProjectSystem.VS.LanguageServices { public class VsContainedLanguageComponentsFactoryTests { private const string LanguageServiceId = "{517FA117-46EB-4402-A0D5-D4B7D89FCC33}"; [Fact] public void GetContainedLanguageFactoryForFile_WhenIsDocumentInProjectFails_ReturnE_FAIL() { var project = IVsProject_Factory.ImplementIsDocumentInProject(HResult.Fail); var factory = CreateInstance(project); var result = factory.GetContainedLanguageFactoryForFile("FilePath", out var hierarchyResult, out var itemIdResult, out var containedLanguageFactoryResult); AssertFailed(result, hierarchyResult, itemIdResult, containedLanguageFactoryResult); } [Fact] public void GetContainedLanguageFactoryForFile_WhenFilePathNotFound_ReturnE_FAIL() { var project = IVsProject_Factory.ImplementIsDocumentInProject(found: false); var factory = CreateInstance(project); var result = factory.GetContainedLanguageFactoryForFile("FilePath", out var hierarchyResult, out var itemIdResult, out var containedLanguageFactoryResult); AssertFailed(result, hierarchyResult, itemIdResult, containedLanguageFactoryResult); } [Theory] [InlineData("")] [InlineData("ABC")] [InlineData("ABCD-ABC")] public void GetContainedLanguageFactoryForFile_WhenLanguageServiceIdEmptyOrInvalid_ReturnE_FAIL(string languageServiceId) { var project = IVsProject_Factory.ImplementIsDocumentInProject(found: true); var properties = ProjectPropertiesFactory.Create(ConfigurationGeneral.SchemaName, ConfigurationGeneral.LanguageServiceIdProperty, languageServiceId); var factory = CreateInstance(project, properties: properties); var result = factory.GetContainedLanguageFactoryForFile("FilePath", out var hierarchyResult, out var itemIdResult, out var containedLanguageFactoryResult); AssertFailed(result, hierarchyResult, itemIdResult, containedLanguageFactoryResult); } [Fact] public void GetContainedLanguageFactoryForFile_WhenNoContainedLanguageFactory_ReturnE_FAIL() { var project = IVsProject_Factory.ImplementIsDocumentInProject(found: true); var properties = ProjectPropertiesFactory.Create(ConfigurationGeneral.SchemaName, ConfigurationGeneral.LanguageServiceIdProperty, LanguageServiceId); var factory = CreateInstance(project, containedLanguageFactory: null!, properties: properties); var result = factory.GetContainedLanguageFactoryForFile("FilePath", out var hierarchyResult, out var itemIdResult, out var containedLanguageFactoryResult); AssertFailed(result, hierarchyResult, itemIdResult, containedLanguageFactoryResult); } [Fact] public void GetContainedLanguageFactoryForFile_WhenReturnsResult_ReturnsS_OK() { var hierarchy = IVsHierarchyFactory.Create(); var project = IVsProject_Factory.ImplementIsDocumentInProject(found: true, itemid: 1); var properties = ProjectPropertiesFactory.Create(ConfigurationGeneral.SchemaName, ConfigurationGeneral.LanguageServiceIdProperty, LanguageServiceId); var containedLanguageFactory = IVsContainedLanguageFactoryFactory.Create(); var factory = CreateInstance(project, containedLanguageFactory: containedLanguageFactory, hierarchy: hierarchy, properties: properties); var result = factory.GetContainedLanguageFactoryForFile("FilePath", out var hierarchyResult, out var itemIdResult, out var containedLanguageFactoryResult); Assert.Equal(VSConstants.S_OK, result); Assert.Same(hierarchy, hierarchyResult); Assert.Same(containedLanguageFactory, containedLanguageFactoryResult); Assert.Equal(1u, itemIdResult); } private static void AssertFailed(int result, IVsHierarchy hierarchy, uint itemid, IVsContainedLanguageFactory containedLanguageFactory) { Assert.Equal(VSConstants.E_FAIL, result); Assert.Null(hierarchy); Assert.Null(containedLanguageFactory); Assert.Equal((uint)VSConstants.VSITEMID.Nil, itemid); } private static VsContainedLanguageComponentsFactory CreateInstance( IVsProject4 project, IVsContainedLanguageFactory? containedLanguageFactory = null, IVsHierarchy? hierarchy = null, ProjectProperties? properties = null, IActiveWorkspaceProjectContextHost? projectContextHost = null) { var serviceProvider = IOleAsyncServiceProviderFactory.ImplementQueryServiceAsync(containedLanguageFactory, new Guid(LanguageServiceId)); var projectVsServices = new IUnconfiguredProjectVsServicesMock(); projectVsServices.ImplementVsHierarchy(hierarchy); projectVsServices.ImplementVsProject(project); projectVsServices.ImplementThreadingService(IProjectThreadingServiceFactory.Create()); projectVsServices.ImplementActiveConfiguredProjectProperties(properties); return CreateInstance(serviceProvider, projectVsServices.Object, projectContextHost); } private static VsContainedLanguageComponentsFactory CreateInstance( IOleAsyncServiceProvider? serviceProvider = null, IUnconfiguredProjectVsServices? projectVsServices = null, IActiveWorkspaceProjectContextHost? projectContextHost = null) { projectVsServices ??= IUnconfiguredProjectVsServicesFactory.Create(); projectContextHost ??= IActiveWorkspaceProjectContextHostFactory.Create(); return new VsContainedLanguageComponentsFactory(IVsServiceFactory.Create<SAsyncServiceProvider, IOleAsyncServiceProvider>(serviceProvider), projectVsServices, projectContextHost); } } }
53.110236
168
0.713566
[ "Apache-2.0" ]
MSLukeWest/project-system
tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/ProjectSystem/VS/LanguageServices/VsContainedLanguageComponentsFactoryTests.cs
6,621
C#
using System; using BACnet.Types; using BACnet.Types.Schemas; namespace BACnet.Ashrae { public partial class LifeSafetyOperationRequest { public uint RequestingProcessIdentifier { get; private set; } public string RequestingSource { get; private set; } public LifeSafetyOperation Request { get; private set; } public Option<ObjectId> ObjectIdentifier { get; private set; } public LifeSafetyOperationRequest(uint requestingProcessIdentifier, string requestingSource, LifeSafetyOperation request, Option<ObjectId> objectIdentifier) { this.RequestingProcessIdentifier = requestingProcessIdentifier; this.RequestingSource = requestingSource; this.Request = request; this.ObjectIdentifier = objectIdentifier; } public static readonly ISchema Schema = new SequenceSchema(false, new FieldSchema("RequestingProcessIdentifier", 0, Value<uint>.Schema), new FieldSchema("RequestingSource", 1, Value<string>.Schema), new FieldSchema("Request", 2, Value<LifeSafetyOperation>.Schema), new FieldSchema("ObjectIdentifier", 3, Value<Option<ObjectId>>.Schema)); public static LifeSafetyOperationRequest Load(IValueStream stream) { stream.EnterSequence(); var requestingProcessIdentifier = Value<uint>.Load(stream); var requestingSource = Value<string>.Load(stream); var request = Value<LifeSafetyOperation>.Load(stream); var objectIdentifier = Value<Option<ObjectId>>.Load(stream); stream.LeaveSequence(); return new LifeSafetyOperationRequest(requestingProcessIdentifier, requestingSource, request, objectIdentifier); } public static void Save(IValueSink sink, LifeSafetyOperationRequest value) { sink.EnterSequence(); Value<uint>.Save(sink, value.RequestingProcessIdentifier); Value<string>.Save(sink, value.RequestingSource); Value<LifeSafetyOperation>.Save(sink, value.Request); Value<Option<ObjectId>>.Save(sink, value.ObjectIdentifier); sink.LeaveSequence(); } } }
36.924528
158
0.775166
[ "MIT" ]
LorenVS/bacstack
BACnet.Ashrae/Generated/LifeSafetyOperationRequest.cs
1,957
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Axe.Windows.Core.Bases; using Axe.Windows.Core.Enums; using Axe.Windows.Core.Types; using Axe.Windows.Rules.Resources; using static Axe.Windows.Rules.PropertyConditions.ControlType; using static Axe.Windows.Rules.PropertyConditions.IntProperties; namespace Axe.Windows.Rules.Library { [RuleInfo(ID = RuleId.OrientationPropertyExists)] class OrientationPropertyExists : Rule { public OrientationPropertyExists() { this.Info.Description = Descriptions.OrientationPropertyExists; this.Info.HowToFix = HowToFix.OrientationPropertyExists; this.Info.Standard = A11yCriteriaId.ObjectInformation; this.Info.PropertyID = PropertyType.UIA_OrientationPropertyId; } public override EvaluationCode Evaluate(IA11yElement e) { if (e == null) throw new ArgumentNullException(nameof(e)); return Orientation.Exists.Matches(e) ? EvaluationCode.Pass : EvaluationCode.Error; } protected override Condition CreateCondition() { return ScrollBar | Tab; } } // class } // namespace
36.216216
102
0.685075
[ "MIT" ]
Bhaskers-Blu-Org2/axe-windows
src/Rules/Library/OrientationPropertyExists.cs
1,304
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.StreamTubeLib.ColorBarLib { /// <summary> /// The Title class. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")] [Serializable] public class Title : IEquatable<Title> { /// <summary> /// Sets this color bar&#39;s title font. Note that the title&#39;s font used /// to be set by the now deprecated <c>titlefont</c> attribute. /// </summary> [JsonPropertyName(@"font")] public Plotly.Blazor.Traces.StreamTubeLib.ColorBarLib.TitleLib.Font Font { get; set;} /// <summary> /// Determines the location of color bar&#39;s title with respect to the color /// bar. Defaults to <c>top</c> when <c>orientation</c> if <c>v</c> and defaults /// to <c>right</c> when <c>orientation</c> if <c>h</c>. Note that the title&#39;s /// location used to be set by the now deprecated <c>titleside</c> attribute. /// </summary> [JsonPropertyName(@"side")] public Plotly.Blazor.Traces.StreamTubeLib.ColorBarLib.TitleLib.SideEnum? Side { get; set;} /// <summary> /// Sets the title of the color bar. Note that before the existence of <c>title.text</c>, /// the title&#39;s contents used to be defined as the <c>title</c> attribute /// itself. This behavior has been deprecated. /// </summary> [JsonPropertyName(@"text")] public string Text { get; set;} /// <inheritdoc /> public override bool Equals(object obj) { if (!(obj is Title other)) return false; return ReferenceEquals(this, obj) || Equals(other); } /// <inheritdoc /> public bool Equals([AllowNull] Title other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; return ( Font == other.Font || Font != null && Font.Equals(other.Font) ) && ( Side == other.Side || Side != null && Side.Equals(other.Side) ) && ( Text == other.Text || Text != null && Text.Equals(other.Text) ); } /// <inheritdoc /> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; if (Font != null) hashCode = hashCode * 59 + Font.GetHashCode(); if (Side != null) hashCode = hashCode * 59 + Side.GetHashCode(); if (Text != null) hashCode = hashCode * 59 + Text.GetHashCode(); return hashCode; } } /// <summary> /// Checks for equality of the left Title and the right Title. /// </summary> /// <param name="left">Left Title.</param> /// <param name="right">Right Title.</param> /// <returns>Boolean</returns> public static bool operator == (Title left, Title right) { return Equals(left, right); } /// <summary> /// Checks for inequality of the left Title and the right Title. /// </summary> /// <param name="left">Left Title.</param> /// <param name="right">Right Title.</param> /// <returns>Boolean</returns> public static bool operator != (Title left, Title right) { return !Equals(left, right); } /// <summary> /// Gets a deep copy of this instance. /// </summary> /// <returns>Title</returns> public Title DeepClone() { return this.Copy(); } } }
34.816667
101
0.517951
[ "MIT" ]
ScriptBox99/Plotly.Blazor
Plotly.Blazor/Traces/StreamTubeLib/ColorBarLib/Title.cs
4,178
C#
using System; using System.Windows; using System.Windows.Controls; namespace GTA_SA_PathsRedactor.Controls { public class StretchingTreeViewItem : TreeViewItem { public StretchingTreeViewItem() { this.Loaded += new RoutedEventHandler(StretchingTreeViewItem_Loaded); } private void StretchingTreeViewItem_Loaded(object sender, RoutedEventArgs e) { if (this.VisualChildrenCount > 0) { Grid grid = this.GetVisualChild(0) as Grid; if (grid != null && grid.ColumnDefinitions.Count == 3) { grid.ColumnDefinitions.RemoveAt(2); grid.ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Star); } } } protected override DependencyObject GetContainerForItemOverride() { return new StretchingTreeViewItem(); } protected override bool IsItemItsOwnContainerOverride(object item) { return item is StretchingTreeViewItem; } } public class StretchingTreeView : TreeView { protected override DependencyObject GetContainerForItemOverride() { return new StretchingTreeViewItem(); } protected override bool IsItemItsOwnContainerOverride(object item) { return item is StretchingTreeViewItem; } } }
28.588235
91
0.605624
[ "MIT" ]
MrNails/GTA_SA_PathsRedactor
GTA_SA_PathsRedactor/Controls/StretchingTreeView.cs
1,460
C#
namespace WordWebService { partial class TextEntryForm { /// <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 Windows Form 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() { this.list = new System.Windows.Forms.ListBox(); this.edit = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // list // this.list.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.list.FormattingEnabled = true; this.list.Location = new System.Drawing.Point(12, 38); this.list.Name = "list"; this.list.Size = new System.Drawing.Size(260, 212); this.list.TabIndex = 1; // // edit // this.edit.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.edit.Location = new System.Drawing.Point(12, 12); this.edit.Name = "edit"; this.edit.Size = new System.Drawing.Size(260, 20); this.edit.TabIndex = 0; // // TextEntryForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 262); this.Controls.Add(this.edit); this.Controls.Add(this.list); this.Name = "TextEntryForm"; this.Text = "Text entry"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ListBox list; private System.Windows.Forms.TextBox edit; } }
29.828947
144
0.68637
[ "BSD-3-Clause" ]
MiloszKrajewski/dnug-rx
src/WordWebService/TextEntryForm.Designer.cs
2,269
C#
using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace ToHDL.Migrations { public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "SuperPowers", columns: table => new { Id = table.Column<int>(type: "integer", nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Damage = table.Column<int>(type: "integer", nullable: false), Description = table.Column<string>(type: "text", nullable: true), Name = table.Column<string>(type: "text", nullable: true) }, constraints: table => { table.PrimaryKey("PK_SuperPowers", x => x.Id); }); migrationBuilder.CreateTable( name: "Heroes", columns: table => new { Id = table.Column<int>(type: "integer", nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), HeroName = table.Column<string>(type: "text", nullable: true), ElementType = table.Column<int>(type: "integer", nullable: false), HP = table.Column<int>(type: "integer", nullable: false), SuperPowerId = table.Column<int>(type: "integer", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Heroes", x => x.Id); table.ForeignKey( name: "FK_Heroes_SuperPowers_SuperPowerId", column: x => x.SuperPowerId, principalTable: "SuperPowers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Heroes_SuperPowerId", table: "Heroes", column: "SuperPowerId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Heroes"); migrationBuilder.DropTable( name: "SuperPowers"); } } }
41.063492
125
0.520294
[ "MIT" ]
210215-USF-NET/WestonDavidson-code
ToHDevOps/TourOfHeros/ToHDL/Migrations/20210304145535_Initial.cs
2,589
C#
$persistentObjectSet = new SimSet();
19
37
0.736842
[ "BSD-2-Clause" ]
Torque3D-Resources/Twillex
Twillex_Test/game/managed/persistent.cs
38
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace EasyGameServer { static class Program { /// <summary> /// 해당 응용 프로그램의 주 진입점입니다. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
21.434783
65
0.602434
[ "MIT" ]
flashscope/EasyMobileGameServer
C_Sharp_Server/EasyGameServer/EasyGameServer/Program.cs
527
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.AcademicFoundation { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Educational_Institution_Course_DesignationObjectIDType : INotifyPropertyChanged { private string typeField; private string valueField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string type { get { return this.typeField; } set { this.typeField = value; this.RaisePropertyChanged("type"); } } [XmlText] public string Value { get { return this.valueField; } set { this.valueField = value; this.RaisePropertyChanged("Value"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
21.229508
136
0.734363
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.AcademicFoundation/Educational_Institution_Course_DesignationObjectIDType.cs
1,295
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Core; using Azure.ResourceManager.Network; namespace Azure.ResourceManager.Network.Models { /// <summary> Creates a VirtualHubRouteTableV2 resource if it doesn&apos;t exist else updates the existing VirtualHubRouteTableV2. </summary> public partial class VirtualHubRouteTableV2CreateOrUpdateOperation : Operation<VirtualHubRouteTableV2>, IOperationSource<VirtualHubRouteTableV2> { private readonly OperationInternals<VirtualHubRouteTableV2> _operation; private readonly ArmResource _operationBase; /// <summary> Initializes a new instance of VirtualHubRouteTableV2CreateOrUpdateOperation for mocking. </summary> protected VirtualHubRouteTableV2CreateOrUpdateOperation() { } internal VirtualHubRouteTableV2CreateOrUpdateOperation(ArmResource operationsBase, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response) { _operation = new OperationInternals<VirtualHubRouteTableV2>(this, clientDiagnostics, pipeline, request, response, OperationFinalStateVia.AzureAsyncOperation, "VirtualHubRouteTableV2CreateOrUpdateOperation"); _operationBase = operationsBase; } /// <inheritdoc /> public override string Id => _operation.Id; /// <inheritdoc /> public override VirtualHubRouteTableV2 Value => _operation.Value; /// <inheritdoc /> public override bool HasCompleted => _operation.HasCompleted; /// <inheritdoc /> public override bool HasValue => _operation.HasValue; /// <inheritdoc /> public override Response GetRawResponse() => _operation.GetRawResponse(); /// <inheritdoc /> public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); /// <inheritdoc /> public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<VirtualHubRouteTableV2>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<VirtualHubRouteTableV2>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); VirtualHubRouteTableV2 IOperationSource<VirtualHubRouteTableV2>.CreateResult(Response response, CancellationToken cancellationToken) { using var document = JsonDocument.Parse(response.ContentStream); var data = VirtualHubRouteTableV2Data.DeserializeVirtualHubRouteTableV2Data(document.RootElement); return new VirtualHubRouteTableV2(_operationBase, data); } async ValueTask<VirtualHubRouteTableV2> IOperationSource<VirtualHubRouteTableV2>.CreateResultAsync(Response response, CancellationToken cancellationToken) { using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); var data = VirtualHubRouteTableV2Data.DeserializeVirtualHubRouteTableV2Data(document.RootElement); return new VirtualHubRouteTableV2(_operationBase, data); } } }
47.2625
237
0.753504
[ "MIT" ]
BaherAbdullah/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/LongRunningOperation/VirtualHubRouteTableV2CreateOrUpdateOperation.cs
3,781
C#
using NAutowired.Core.Attributes; namespace NAutowiredConsoleSample { public class Startup : NAutowired.Core.Startup { [Autowired] private readonly FooService fooService; public override void Run(string[] args) { System.Console.WriteLine(fooService.Foo()); System.Console.ReadLine(); } } }
21.705882
55
0.626016
[ "MIT" ]
FatTigerWang/NAutowired
Sample/NAutowired.Console.Sample/Startup.cs
371
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Utils; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Beatmaps.Timing; using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Overlays.Settings; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu.Beatmaps; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Rulesets.Osu.UI; using osu.Game.Rulesets.Osu.Utils; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModTarget : ModWithVisibilityAdjustment, IApplicableToDrawableRuleset<OsuHitObject>, IApplicableToHealthProcessor, IApplicableToDifficulty, IApplicableFailOverride, IHasSeed, IHidesApproachCircles { public override string Name => "Target"; public override string Acronym => "TP"; public override ModType Type => ModType.Conversion; public override IconUsage? Icon => OsuIcon.ModTarget; public override string Description => @"Practice keeping up with the beat of the song."; public override double ScoreMultiplier => 1; public override Type[] IncompatibleMods => new[] { typeof(IRequiresApproachCircles) }; [SettingSource("Seed", "Use a custom seed instead of a random one", SettingControlType = typeof(SettingsNumberBox))] public Bindable<int?> Seed { get; } = new Bindable<int?> { Default = null, Value = null }; #region Constants /// <summary> /// Jump distance for circles in the last combo /// </summary> private const float max_base_distance = 333f; /// <summary> /// The maximum allowed jump distance after multipliers are applied /// </summary> private const float distance_cap = 380f; /// <summary> /// The extent of rotation towards playfield centre when a circle is near the edge /// </summary> private const float edge_rotation_multiplier = 0.75f; /// <summary> /// Number of recent circles to check for overlap /// </summary> private const int overlap_check_count = 5; /// <summary> /// Duration of the undimming animation /// </summary> private const double undim_duration = 96; /// <summary> /// Acceptable difference for timing comparisons /// </summary> private const double timing_precision = 1; #endregion #region Private Fields private ControlPointInfo controlPointInfo; private List<OsuHitObject> originalHitObjects; private Random rng; #endregion #region Sudden Death (IApplicableFailOverride) public bool PerformFail() => true; public bool RestartOnFail => false; public void ApplyToHealthProcessor(HealthProcessor healthProcessor) { // Sudden death healthProcessor.FailConditions += (_, result) => result.Type.AffectsCombo() && !result.IsHit; } #endregion #region Reduce AR (IApplicableToDifficulty) public void ReadFromDifficulty(IBeatmapDifficultyInfo difficulty) { } public void ApplyToDifficulty(BeatmapDifficulty difficulty) { // Decrease AR to increase preempt time difficulty.ApproachRate *= 0.5f; } #endregion #region Circle Transforms (ModWithVisibilityAdjustment) protected override void ApplyIncreasedVisibilityState(DrawableHitObject drawable, ArmedState state) { } protected override void ApplyNormalVisibilityState(DrawableHitObject drawable, ArmedState state) { if (!(drawable is DrawableHitCircle circle)) return; double startTime = circle.HitObject.StartTime; double preempt = circle.HitObject.TimePreempt; using (circle.BeginAbsoluteSequence(startTime - preempt)) { // initial state circle.ScaleTo(0.5f) .FadeColour(OsuColour.Gray(0.5f)); // scale to final size circle.ScaleTo(1f, preempt); // Remove approach circles circle.ApproachCircle.Hide(); } using (circle.BeginAbsoluteSequence(startTime - controlPointInfo.TimingPointAt(startTime).BeatLength - undim_duration)) circle.FadeColour(Colour4.White, undim_duration); } #endregion #region Beatmap Generation (IApplicableToBeatmap) public override void ApplyToBeatmap(IBeatmap beatmap) { Seed.Value ??= RNG.Next(); rng = new Random(Seed.Value.Value); var osuBeatmap = (OsuBeatmap)beatmap; if (osuBeatmap.HitObjects.Count == 0) return; controlPointInfo = osuBeatmap.ControlPointInfo; originalHitObjects = osuBeatmap.HitObjects.OrderBy(x => x.StartTime).ToList(); var hitObjects = generateBeats(osuBeatmap) .Select(beat => { var newCircle = new HitCircle(); newCircle.ApplyDefaults(controlPointInfo, osuBeatmap.Difficulty); newCircle.StartTime = beat; return (OsuHitObject)newCircle; }).ToList(); addHitSamples(hitObjects); fixComboInfo(hitObjects); randomizeCirclePos(hitObjects); osuBeatmap.HitObjects = hitObjects; base.ApplyToBeatmap(beatmap); } private IEnumerable<double> generateBeats(IBeatmap beatmap) { double startTime = originalHitObjects.First().StartTime; double endTime = originalHitObjects.Last().GetEndTime(); var beats = beatmap.ControlPointInfo.TimingPoints // Ignore timing points after endTime .Where(timingPoint => !definitelyBigger(timingPoint.Time, endTime)) // Generate the beats .SelectMany(timingPoint => getBeatsForTimingPoint(timingPoint, endTime)) // Remove beats before startTime .Where(beat => almostBigger(beat, startTime)) // Remove beats during breaks .Where(beat => !isInsideBreakPeriod(beatmap.Breaks, beat)) .ToList(); // Remove beats that are too close to the next one (e.g. due to timing point changes) for (int i = beats.Count - 2; i >= 0; i--) { double beat = beats[i]; if (!definitelyBigger(beats[i + 1] - beat, beatmap.ControlPointInfo.TimingPointAt(beat).BeatLength / 2)) beats.RemoveAt(i); } return beats; } private void addHitSamples(IEnumerable<OsuHitObject> hitObjects) { foreach (var obj in hitObjects) { var samples = getSamplesAtTime(originalHitObjects, obj.StartTime); // If samples aren't available at the exact start time of the object, // use samples (without additions) in the closest original hit object instead obj.Samples = samples ?? getClosestHitObject(originalHitObjects, obj.StartTime).Samples.Where(s => !HitSampleInfo.AllAdditions.Contains(s.Name)).ToList(); } } private void fixComboInfo(List<OsuHitObject> hitObjects) { // Copy combo indices from an original object at the same time or from the closest preceding object // (Objects lying between two combos are assumed to belong to the preceding combo) hitObjects.ForEach(newObj => { var closestOrigObj = originalHitObjects.FindLast(y => almostBigger(newObj.StartTime, y.StartTime)); // It shouldn't be possible for closestOrigObj to be null // But if it is, obj should be in the first combo newObj.ComboIndex = closestOrigObj?.ComboIndex ?? 0; }); // The copied combo indices may not be continuous if the original map starts and ends a combo in between beats // e.g. A stream with each object starting a new combo // So combo indices need to be reprocessed to ensure continuity // Other kinds of combo info are also added in the process var combos = hitObjects.GroupBy(x => x.ComboIndex).ToList(); for (int i = 0; i < combos.Count; i++) { var group = combos[i].ToList(); group.First().NewCombo = true; group.Last().LastInCombo = true; for (int j = 0; j < group.Count; j++) { var x = group[j]; x.ComboIndex = i; x.IndexInCurrentCombo = j; } } } private void randomizeCirclePos(IReadOnlyList<OsuHitObject> hitObjects) { if (hitObjects.Count == 0) return; float nextSingle(float max = 1f) => (float)(rng.NextDouble() * max); const float two_pi = MathF.PI * 2; float direction = two_pi * nextSingle(); int maxComboIndex = hitObjects.Last().ComboIndex; for (int i = 0; i < hitObjects.Count; i++) { var obj = hitObjects[i]; var lastPos = i == 0 ? Vector2.Divide(OsuPlayfield.BASE_SIZE, 2) : hitObjects[i - 1].Position; float distance = maxComboIndex == 0 ? (float)obj.Radius : mapRange(obj.ComboIndex, 0, maxComboIndex, (float)obj.Radius, max_base_distance); if (obj.NewCombo) distance *= 1.5f; if (obj.Kiai) distance *= 1.2f; distance = Math.Min(distance_cap, distance); // Attempt to place the circle at a place that does not overlap with previous ones int tryCount = 0; // for checking overlap var precedingObjects = hitObjects.SkipLast(hitObjects.Count - i).TakeLast(overlap_check_count).ToList(); do { if (tryCount > 0) direction = two_pi * nextSingle(); var relativePos = new Vector2( distance * MathF.Cos(direction), distance * MathF.Sin(direction) ); // Rotate the new circle away from playfield border relativePos = OsuHitObjectGenerationUtils.RotateAwayFromEdge(lastPos, relativePos, edge_rotation_multiplier); direction = MathF.Atan2(relativePos.Y, relativePos.X); var newPosition = Vector2.Add(lastPos, relativePos); obj.Position = newPosition; clampToPlayfield(obj); tryCount++; if (tryCount % 10 == 0) distance *= 0.9f; } while (distance >= obj.Radius * 2 && checkForOverlap(precedingObjects, obj)); if (obj.LastInCombo) direction = two_pi * nextSingle(); else direction += distance / distance_cap * (nextSingle() * two_pi - MathF.PI); } } #endregion #region Metronome (IApplicableToDrawableRuleset) public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset) { drawableRuleset.Overlays.Add(new Metronome(drawableRuleset.Beatmap.HitObjects.First().StartTime)); } #endregion #region Helper Subroutines /// <summary> /// Check if a given time is inside a <see cref="BreakPeriod"/>. /// </summary> /// <remarks> /// The given time is also considered to be inside a break if it is earlier than the /// start time of the first original hit object after the break. /// </remarks> /// <param name="breaks">The breaks of the beatmap.</param> /// <param name="time">The time to be checked.</param>= private bool isInsideBreakPeriod(IEnumerable<BreakPeriod> breaks, double time) { return breaks.Any(breakPeriod => { var firstObjAfterBreak = originalHitObjects.First(obj => almostBigger(obj.StartTime, breakPeriod.EndTime)); return almostBigger(time, breakPeriod.StartTime) && definitelyBigger(firstObjAfterBreak.StartTime, time); }); } private IEnumerable<double> getBeatsForTimingPoint(TimingControlPoint timingPoint, double mapEndTime) { var beats = new List<double>(); int i = 0; double currentTime = timingPoint.Time; while (!definitelyBigger(currentTime, mapEndTime) && controlPointInfo.TimingPointAt(currentTime) == timingPoint) { beats.Add(Math.Floor(currentTime)); i++; currentTime = timingPoint.Time + i * timingPoint.BeatLength; } return beats; } private OsuHitObject getClosestHitObject(List<OsuHitObject> hitObjects, double time) { int precedingIndex = hitObjects.FindLastIndex(h => h.StartTime < time); if (precedingIndex == hitObjects.Count - 1) return hitObjects[precedingIndex]; // return the closest preceding/succeeding hit object, whoever is closer in time return hitObjects[precedingIndex + 1].StartTime - time < time - hitObjects[precedingIndex].StartTime ? hitObjects[precedingIndex + 1] : hitObjects[precedingIndex]; } /// <summary> /// Get samples (if any) for a specific point in time. /// </summary> /// <remarks> /// Samples will be returned if a hit circle or a slider node exists at that point of time. /// </remarks> /// <param name="hitObjects">The list of hit objects in a beatmap, ordered by StartTime</param> /// <param name="time">The point in time to get samples for</param> /// <returns>Hit samples</returns> private IList<HitSampleInfo> getSamplesAtTime(IEnumerable<OsuHitObject> hitObjects, double time) { // Get a hit object that // either has StartTime equal to the target time // or has a repeat node at the target time var sampleObj = hitObjects.FirstOrDefault(hitObject => { if (almostEquals(time, hitObject.StartTime)) return true; if (!(hitObject is IHasRepeats s)) return false; // If time is outside the duration of the IHasRepeats, // then this hitObject isn't the one we want if (!almostBigger(time, hitObject.StartTime) || !almostBigger(s.EndTime, time)) return false; return nodeIndexFromTime(s, time - hitObject.StartTime) != -1; }); if (sampleObj == null) return null; IList<HitSampleInfo> samples; if (sampleObj is IHasRepeats slider) samples = slider.NodeSamples[nodeIndexFromTime(slider, time - sampleObj.StartTime)]; else samples = sampleObj.Samples; return samples; } /// <summary> /// Get the repeat node at a point in time. /// </summary> /// <param name="curve">The slider.</param> /// <param name="timeSinceStart">The time since the start time of the slider.</param> /// <returns>Index of the node. -1 if there isn't a node at the specific time.</returns> private int nodeIndexFromTime(IHasRepeats curve, double timeSinceStart) { double spanDuration = curve.Duration / curve.SpanCount(); double nodeIndex = timeSinceStart / spanDuration; if (almostEquals(nodeIndex, Math.Round(nodeIndex))) return (int)Math.Round(nodeIndex); return -1; } private bool checkForOverlap(IEnumerable<OsuHitObject> objectsToCheck, OsuHitObject target) { return objectsToCheck.Any(h => Vector2.Distance(h.Position, target.Position) < target.Radius * 2); } /// <summary> /// Move the hit object into playfield, taking its radius into account. /// </summary> /// <param name="obj">The hit object to be clamped.</param> private void clampToPlayfield(OsuHitObject obj) { var position = obj.Position; float radius = (float)obj.Radius; if (position.Y < radius) position.Y = radius; else if (position.Y > OsuPlayfield.BASE_SIZE.Y - radius) position.Y = OsuPlayfield.BASE_SIZE.Y - radius; if (position.X < radius) position.X = radius; else if (position.X > OsuPlayfield.BASE_SIZE.X - radius) position.X = OsuPlayfield.BASE_SIZE.X - radius; obj.Position = position; } /// <summary> /// Re-maps a number from one range to another. /// </summary> /// <param name="value">The number to be re-mapped.</param> /// <param name="fromLow">Beginning of the original range.</param> /// <param name="fromHigh">End of the original range.</param> /// <param name="toLow">Beginning of the new range.</param> /// <param name="toHigh">End of the new range.</param> /// <returns>The re-mapped number.</returns> private static float mapRange(float value, float fromLow, float fromHigh, float toLow, float toHigh) { return (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow; } private static bool almostBigger(double value1, double value2) { return Precision.AlmostBigger(value1, value2, timing_precision); } private static bool definitelyBigger(double value1, double value2) { return Precision.DefinitelyBigger(value1, value2, timing_precision); } private static bool almostEquals(double value1, double value2) { return Precision.AlmostEquals(value1, value2, timing_precision); } #endregion } }
39.490119
171
0.56716
[ "MIT" ]
Azyyyyyy/osu
osu.Game.Rulesets.Osu/Mods/OsuModTarget.cs
19,479
C#
using UnityEngine; using System.Collections; public class LogicController : MonoBehaviour { public string switchTriggerName = "Switch"; public Transform activeObject; Animator anim; // Use this for initialization void Start () { anim = GetComponent<Animator>(); } // Update is called once per frame void Update () { //If player presses Space, we set the switch trigger //in the animator - that controls the graph flow if (Input.GetKeyDown(KeyCode.Space)) { anim.SetTrigger(switchTriggerName); } } }
20.964286
60
0.650767
[ "MIT" ]
PacktPublishing/Unity-5.x-Animation-Cookbook
Assets/Chapter 10/Recipe 05/Scripts/LogicController.cs
589
C#
using Codecool.DungeonCrawl.Logic.Actors; using Codecool.DungeonCrawl.Logic.Items; namespace Codecool.DungeonCrawl.Logic { /// <summary> /// Represents a cell in the map. /// </summary> public class Cell : IDrawable { private readonly GameMap _gameMap; /// <summary> /// Initializes a new instance of the <see cref="Cell"/> class. /// </summary> /// <param name="gameMap">The game map</param> /// <param name="x">X coordinate of the cell</param> /// <param name="y">Y coordinate of the cell</param> /// <param name="type">Type of the cell</param> public Cell(GameMap gameMap, int x, int y, CellType type) { _gameMap = gameMap; X = x; Y = y; Type = type; } /// <summary> /// Type of the cell /// </summary> public CellType Type; /// <summary> /// The actor on the cell, null of none. /// </summary> public Actor Actor; // public Item Item { get; set; } public Item Item; /// <summary> /// Returns a cell in the given distance /// </summary> /// <param name="dx">X distance from this cell</param> /// <param name="dy">Y distance from this cell</param> /// <returns>The cell in the given distance</returns> public Cell GetNeighbor(int dx, int dy) { return _gameMap.GetCell(X + dx, Y + dy); } /// <summary> /// Gets the type of this cell as string. /// </summary> public string Tilename => Type.ToString(); /// <summary> /// Gets the X coordinate /// </summary> public int X { get; private set; } /// <summary> /// Gets the Y coordinate /// </summary> public int Y { get; private set; } } }
28.58209
71
0.518538
[ "CC0-1.0" ]
h0axx/gameCSharp
src/Codecool.DungeonCrawl/Logic/Cell.cs
1,915
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("05.Phonebook")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("05.Phonebook")] [assembly: AssemblyCopyright("Copyright © Microsoft 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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0bafc4c5-810b-432c-b28a-cac4ba575864")] // 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")]
39.081081
85
0.730982
[ "MIT" ]
stoyanov7/SoftwareUniversity
C#Development/C#Advanced/SetsAndDictionaries-Exercise/05.Phonebook/05.Phonebook/Properties/AssemblyInfo.cs
1,449
C#
using CCXT.NET.Shared.Coin; using CCXT.NET.Shared.Coin.Private; using CCXT.NET.Shared.Coin.Types; using CCXT.NET.Shared.Configuration; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CCXT.NET.Bitfinex.Private { /// <summary> /// /// </summary> public class PrivateApi : CCXT.NET.Shared.Coin.Private.PrivateApi, IPrivateApi { private readonly string __connect_key; private readonly string __secret_key; /// <summary> /// /// </summary> public PrivateApi(string connect_key, string secret_key) { __connect_key = connect_key; __secret_key = secret_key; } /// <summary> /// /// </summary> public override XApiClient privateClient { get { if (base.privateClient == null) base.privateClient = new BitfinexClient("private", __connect_key, __secret_key); return base.privateClient; } } /// <summary> /// /// </summary> public override CCXT.NET.Shared.Coin.Public.PublicApi publicApi { get { if (base.publicApi == null) base.publicApi = new CCXT.NET.Bitfinex.Public.PublicApi(); return base.publicApi; } } /// <summary> /// Return your deposit address to make a new deposit. /// </summary> /// <param name="currency_name">base coin or quote coin name</param> /// <param name="args">Add additional attributes for each exchange</param> /// <returns></returns> public override async ValueTask<Address> CreateAddressAsync(string currency_name, Dictionary<string, object> args = null) { var _result = new Address(); var _currency_nick = await publicApi.LoadCurrencyNickAsync(currency_name); if (_currency_nick.success == true) { privateClient.ExchangeInfo.ApiCallWait(TradeType.Private); var _params = new Dictionary<string, object>(); { _params.Add("method", _currency_nick.result); _params.Add("wallet_name", "exchange"); _params.Add("renew", 1); privateClient.MergeParamsAndArgs(_params, args); } var _json_value = await privateClient.CallApiPost1Async("/v1/deposit/new", _params); #if DEBUG _result.rawJson = _json_value.Content; #endif var _json_result = privateClient.GetResponseMessage(_json_value.Response); if (_json_result.success == true) { var _address = privateClient.DeserializeObject<BAddressItem>(_json_value.Content); { _address.currency = currency_name; if (_address.method == "ripple") { _address.tag = _address.address; _address.address = _address.address_pool; } _result.result = _address; if (_address.success == false) _json_result.SetFailure("could not create address", ErrorCode.TooManyAddress); } } _result.SetResult(_json_result); } else { _result.SetResult(_currency_nick); } return _result; } /// <summary> /// Return your deposit address to make a new deposit. /// </summary> /// <param name="currency_name">base coin or quote coin name</param> /// <param name="args">Add additional attributes for each exchange</param> /// <returns></returns> public override async ValueTask<Address> FetchAddressAsync(string currency_name, Dictionary<string, object> args = null) { var _result = new Address(); var _currency_nick = await publicApi.LoadCurrencyNickAsync(currency_name); if (_currency_nick.success == true) { privateClient.ExchangeInfo.ApiCallWait(TradeType.Private); var _params = new Dictionary<string, object>(); { _params.Add("method", _currency_nick.result); _params.Add("wallet_name", "exchange"); //_params.Add("renew", 0); privateClient.MergeParamsAndArgs(_params, args); } var _json_value = await privateClient.CallApiPost1Async("/v1/deposit/new", _params); #if DEBUG _result.rawJson = _json_value.Content; #endif var _json_result = privateClient.GetResponseMessage(_json_value.Response); if (_json_result.success == true) { var _address = privateClient.DeserializeObject<BAddressItem>(_json_value.Content); { _address.currency = currency_name; if (_address.method == "ripple") { _address.tag = _address.address; _address.address = _address.address_pool; } _result.result = _address; _json_result.success = _address.success; } } _result.SetResult(_json_result); } else { _result.SetResult(_currency_nick); } return _result; } /// <summary> /// Allow you to request a withdrawal from one of your wallet. /// </summary> /// <param name="currency_name">base coin or quote coin name</param> /// <param name="address">coin address for send</param> /// <param name="tag">Secondary address identifier for coins like XRP,XMR etc.</param> /// <param name="quantity">amount of coin</param> /// <param name="args">Add additional attributes for each exchange</param> /// <returns></returns> public override async ValueTask<Transfer> CoinWithdrawAsync(string currency_name, string address, string tag, decimal quantity, Dictionary<string, object> args = null) { var _result = new Transfer(); var _currency_nick = await publicApi.LoadCurrencyNickAsync(currency_name); if (_currency_nick.success == true) { privateClient.ExchangeInfo.ApiCallWait(TradeType.Private); var _params = new Dictionary<string, object>(); { _params.Add("withdraw_type", _currency_nick.result); _params.Add("walletselected", "exchange"); _params.Add("amount", quantity.ToString()); _params.Add("address", address); privateClient.MergeParamsAndArgs(_params, args); } var _json_value = await privateClient.CallApiPost1Async("/v1/withdraw", _params); #if DEBUG _result.rawJson = _json_value.Content; #endif var _json_result = privateClient.GetResponseMessage(_json_value.Response); if (_json_result.success == true) { var _json_data = privateClient.DeserializeObject<BTransfer>(_json_value.Content); if (_json_data.success == true) { var _withdraw = new BTransferItem { transferId = _json_data.transferId, transactionId = privateClient.GenerateNonceString(16), timestamp = CUnixTime.NowMilli, transactionType = TransactionType.Withdraw, currency = currency_name, toAddress = address, toTag = tag, amount = quantity, fee = 0, confirmations = 0, isCompleted = _json_data.success, }; _result.result = _withdraw; } else { _json_result.SetFailure(_json_data.message); } } _result.SetResult(_json_result); } else { _result.SetResult(_currency_nick); } return _result; } /// <summary> /// View your past deposits/withdrawals. /// </summary> /// <param name="currency_name">base coin or quote coin name</param> /// <param name="timeframe">time frame interval (optional): default "1d"</param> /// <param name="since">return committed data since given time (milli-seconds) (optional): default 0</param> /// <param name="limits">You can set the maximum number of transactions you want to get with this parameter</param> /// <param name="args">Add additional attributes for each exchange</param> /// <returns></returns> public override async ValueTask<Transfers> FetchTransfersAsync(string currency_name, string timeframe = "1d", long since = 0, int limits = 20, Dictionary<string, object> args = null) { var _result = new Transfers(); var _currency_id = await publicApi.LoadCurrencyIdAsync(currency_name); if (_currency_id.success == true) { privateClient.ExchangeInfo.ApiCallWait(TradeType.Private); var _timestamp = privateClient.ExchangeInfo.GetTimestamp(timeframe); var _timeframe = privateClient.ExchangeInfo.GetTimeframe(timeframe); var _params = new Dictionary<string, object>(); { _params.Add("currency", _currency_id.result); _params.Add("since", since / 1000); _params.Add("limit", limits); privateClient.MergeParamsAndArgs(_params, args); } var _json_value = await privateClient.CallApiPost1Async("/v1/history/movements", _params); #if DEBUG _result.rawJson = _json_value.Content; #endif var _json_result = privateClient.GetResponseMessage(_json_value.Response); if (_json_result.success == true) { var _json_data = privateClient.DeserializeObject<List<BTransferItem>>(_json_value.Content); { var _transfers = _json_data .Where(t => t.timestamp >= since) .OrderByDescending(t => t.timestamp) .Take(limits); foreach (var _t in _transfers) { if (_t.transactionType == TransactionType.Withdraw) { _t.toAddress = _t.fromAddress; _t.toTag = _t.fromTag; _t.fromAddress = ""; _t.fromTag = ""; } //_t.transferId = _t.timestamp.ToString(); // transferId 있음 _t.transactionId = (_t.timestamp * 1000).ToString(); _result.result.Add(_t); } } } _result.SetResult(_json_result); } else { _result.SetResult(_currency_id); } return _result; } /// <summary> /// See your balances /// </summary> /// <param name="base_name">The type of trading base-currency of which information you want to query for.</param> /// <param name="quote_name">The type of trading quote-currency of which information you want to query for.</param> /// <param name="args">Add additional attributes for each exchange</param> /// <returns></returns> public override async ValueTask<Balance> FetchBalanceAsync(string base_name, string quote_name, Dictionary<string, object> args = null) { var _result = new Balance(); var _currency_id = await publicApi.LoadCurrencyIdAsync(base_name); if (_currency_id.success == true) { privateClient.ExchangeInfo.ApiCallWait(TradeType.Private); var _params = privateClient.MergeParamsAndArgs(args); var _json_value = await privateClient.CallApiPost1Async("/v1/balances", _params); #if DEBUG _result.rawJson = _json_value.Content; #endif var _json_result = privateClient.GetResponseMessage(_json_value.Response); if (_json_result.success == true) { var _balances = privateClient.DeserializeObject<List<BBalanceItem>>(_json_value.Content); { foreach (var _balance in _balances) { if (_balance.currency.ToLower() != _currency_id.result.ToLower()) continue; _balance.currency = base_name; _balance.free = _balance.total - _balance.used; _result.result = _balance; break; } } } _result.SetResult(_json_result); } else { _result.SetResult(_currency_id); } return _result; } /// <summary> /// See your balances /// </summary> /// <param name="args">Add additional attributes for each exchange</param> /// <returns></returns> public override async ValueTask<Balances> FetchBalancesAsync(Dictionary<string, object> args = null) { var _result = new Balances(); var _markets = await publicApi.LoadMarketsAsync(); if (_markets.success == true) { privateClient.ExchangeInfo.ApiCallWait(TradeType.Private); var _params = privateClient.MergeParamsAndArgs(args); var _json_value = await privateClient.CallApiPost1Async("/v1/balances", _params); #if DEBUG _result.rawJson = _json_value.Content; #endif var _json_result = privateClient.GetResponseMessage(_json_value.Response); if (_json_result.success == true) { var _json_data = privateClient.DeserializeObject<List<BBalanceItem>>(_json_value.Content); { foreach (var _currency_id in _markets.CurrencyNames) { var _balances = _json_data.Where(b => b.currency == _currency_id.Key); foreach (var _balance in _balances) { _balance.currency = _currency_id.Value; _balance.free = _balance.total - _balance.used; _result.result.Add(_balance); } } } } _result.SetResult(_json_result); } else { _result.SetResult(_markets); } return _result; } } }
38.935096
190
0.511206
[ "MIT" ]
ccxt-net/ccxt.net
src/exchanges/gbr/bitfinex/private/privateApi.cs
16,203
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.OutlookApi { /// <summary> /// CoClass Reminder /// SupportByVersion Outlook, 10,11,12,14,15,16 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff868711.aspx </remarks> [SupportByVersion("Outlook", 10,11,12,14,15,16)] [EntityType(EntityType.IsCoClass)] [TypeId("0006F028-0000-0000-C000-000000000046")] public interface Reminder : _Reminder { } }
25.380952
105
0.731707
[ "MIT" ]
igoreksiz/NetOffice
Source/Outlook/Classes/Reminder.cs
535
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2015 Ingo Herbote * http://www.yetanotherforum.net/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 YAF.Pages { // YAF.Pages #region Using using System; using System.Web.Security; using YAF.Controls; using YAF.Core; using YAF.Types; using YAF.Types.Constants; using YAF.Types.Extensions; using YAF.Types.Interfaces; using YAF.Utils; #endregion /// <summary> /// Class to communicate in XMPP. /// </summary> public partial class im_xmpp : ForumPage { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref = "im_xmpp" /> class. /// </summary> public im_xmpp() : base("IM_XMPP") { } #endregion #region Properties /// <summary> /// Gets UserID. /// </summary> public int UserID { get { return (int)Security.StringToLongOrRedirect(this.Request.QueryString.GetFirstOrDefault("u")); } } #endregion #region Methods /// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.User == null) { YafBuildLink.AccessDenied(); } if (!this.IsPostBack) { // get user data... MembershipUser userHe = UserMembershipHelper.GetMembershipUserById(this.UserID); string displayNameHe = UserMembershipHelper.GetDisplayNameFromID(this.UserID); this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, YafBuildLink.GetLink(ForumPages.forum)); this.PageLinks.AddLink( this.PageContext.BoardSettings.EnableDisplayName ? displayNameHe : userHe.UserName, YafBuildLink.GetLink( ForumPages.profile, "u={0}&name={1}", this.UserID, this.PageContext.BoardSettings.EnableDisplayName ? displayNameHe : userHe.UserName)); this.PageLinks.AddLink(this.GetText("TITLE"), string.Empty); if (this.UserID == this.PageContext.PageUserID) { this.NotifyLabel.Text = this.GetText("SERVERYOU"); } else { if (userHe == null) { YafBuildLink.AccessDenied( /*No such user exists*/); } // Data for current page user MembershipUser userMe = UserMembershipHelper.GetMembershipUserById(this.PageContext.PageUserID); // get full user data... var userDataHe = new CombinedUserDataHelper(userHe, this.UserID); var userDataMe = new CombinedUserDataHelper(userMe, this.PageContext.PageUserID); string serverHe = userDataHe.Profile.XMPP.Substring(userDataHe.Profile.XMPP.IndexOf("@") + 1).Trim(); string serverMe = userDataMe.Profile.XMPP.Substring(userDataMe.Profile.XMPP.IndexOf("@") + 1).Trim(); if (serverMe == serverHe) { this.NotifyLabel.Text = this.GetTextFormatted("SERVERSAME", userDataHe.Profile.XMPP); } else { this.NotifyLabel.Text = this.GetTextFormatted("SERVEROTHER", "http://" + serverHe); } } } } #endregion } }
30.444444
112
0.611086
[ "Apache-2.0" ]
TristanTong/bbsWirelessTag
yafsrc/YetAnotherForum.NET/pages/im_xmpp.ascx.cs
4,242
C#
using TenantManagement.Processor.Models; namespace TenantManagement.Processor.Validations { public interface ITenantValidator { bool ValidateCode(Tenant tenant); } }
21
48
0.740741
[ "MIT" ]
Hussain9384/TenantManagement
TenantManagement.Processor/Validations/ITenantValidator.cs
191
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.EntityFrameworkCore; using PhanTichChungKhoan.WebApp.Data; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using PhanTichChungKhoan.Application.Configs; using PhanTichChungKhoan.Infrastructure; using PhanTichChungKhoan.Application; using Microsoft.AspNetCore.Diagnostics; namespace PhanTichChungKhoan.WebApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<JwtConfig>(Configuration.GetSection("JwtConfig")); services.Configure<SecurityEndpointOption>(Configuration.GetSection("SecurityEndpoint")); services.AddHttpContextAccessor(); services.AddInfrastructureServices(Configuration); services.AddApplicationServices(); services.AddWebServices(Configuration); services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
31.357143
106
0.672437
[ "Unlicense" ]
phongnq007/phantichchungkhoan
backend/PhanTichChungKhoan.WebApp/Startup.cs
2,195
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Server.Abstractions; namespace OmniSharp.Extensions.LanguageServer.Server { internal class ClientCapabilityProvider { private readonly IHandlerCollection _collection; public ClientCapabilityProvider(IHandlerCollection collection) { _collection = collection; } public bool HasStaticHandler<T>(Supports<T> capability) where T : DynamicCapability, ConnectedCapability<IJsonRpcHandler> { if (!capability.IsSupported) return false; if (capability.Value == null) return false; if (capability.Value.DynamicRegistration == true) return false; var handlerType = typeof(T).GetTypeInfo().ImplementedInterfaces .Single(x => x.GetTypeInfo().IsGenericType && x.GetTypeInfo().GetGenericTypeDefinition() == typeof(ConnectedCapability<>)) .GetTypeInfo().GetGenericArguments()[0].GetTypeInfo(); return !capability.Value.DynamicRegistration == true && _collection.ContainsHandler(handlerType); } public IOptionsGetter GetStaticOptions<T>(Supports<T> capability) where T : DynamicCapability, ConnectedCapability<IJsonRpcHandler> { return !HasStaticHandler(capability) ? Null : new OptionsGetter(_collection); } private static readonly IOptionsGetter Null = new NullOptionsGetter(); public interface IOptionsGetter { /// <summary> /// Gets a single option from a given interface. /// </summary> /// <param name="action"></param> /// <typeparam name="TInterface"></typeparam> /// <typeparam name="TOptions"></typeparam> /// <returns></returns> TOptions Get<TInterface, TOptions>(Func<TInterface, TOptions> action) where TOptions : class; /// <summary> /// Reduces the options from multiple interfaces to a single option. /// </summary> /// <typeparam name="TInterface"></typeparam> /// <typeparam name="TOptions"></typeparam> /// <param name="action"></param> /// <returns></returns> TOptions Reduce<TInterface, TOptions>(Func<IEnumerable<TInterface>, TOptions> action) where TOptions : class; } private class NullOptionsGetter : IOptionsGetter { public TOptions Get<TInterface, TOptions>(Func<TInterface, TOptions> action) where TOptions : class { return null; } public TOptions Reduce<TInterface, TOptions>(Func<IEnumerable<TInterface>, TOptions> action) where TOptions : class { return null; } } private class OptionsGetter : IOptionsGetter { private readonly IHandlerCollection _collection; public OptionsGetter(IHandlerCollection collection) { _collection = collection; } public TOptions Get<TInterface, TOptions>(Func<TInterface, TOptions> action) where TOptions : class { return _collection .Select(x => x.Registration?.RegisterOptions is TInterface cl ? action(cl) : null) .FirstOrDefault(x => x != null); } public Supports<TOptions> Can<TInterface, TOptions>(Func<TInterface, TOptions> action) where TOptions : class { var options = _collection .Select(x => x.Registration?.RegisterOptions is TInterface cl ? action(cl) : null) .FirstOrDefault(x => x != null); if (options == null) return Supports.OfBoolean<TOptions>(false); return _collection .Select(x => x.Registration?.RegisterOptions is TInterface cl ? action(cl) : null) .FirstOrDefault(x => x != null); } public TOptions Reduce<TInterface, TOptions>(Func<IEnumerable<TInterface>, TOptions> action) where TOptions : class { return action(_collection .Select(x => x.Registration?.RegisterOptions is TInterface cl ? cl : default) .Where(x => x != null)); } } } }
39.396694
138
0.587791
[ "MIT" ]
Bia10/csharp-language-server-protocol
src/Server/ClientCapabilityProvider.cs
4,767
C#
using NUnit.Framework; namespace Man.Dapr.Sidekick.AspNetCore.Metrics { public class PrometheusModelTests { public class Constructor { [Test] public void Should_initialize_properties() { var model = new PrometheusModel(); Assert.That(model.Metrics, Is.Not.Null); Assert.That(model.Unknown, Is.Not.Null); } } public class GetOrAddMetric { [Test] public void Should_add_new() { var model = new PrometheusModel(); var metric = model.GetOrAddMetric("TEST"); Assert.That(metric, Is.Not.Null); Assert.That(metric.Name, Is.EqualTo("TEST")); Assert.That(metric.ToString(), Is.EqualTo("TEST")); } [Test] public void Should_get_existing() { var model = new PrometheusModel(); var metric1 = model.GetOrAddMetric("TEST"); var metric2 = model.GetOrAddMetric("TEST"); Assert.That(metric1, Is.SameAs(metric2)); } } } }
29.365854
67
0.503322
[ "Apache-2.0" ]
Benknightdark/dapr-sidekick-dotnet
tests/Man.Dapr.Sidekick.AspNetCore.Tests/Metrics/PrometheusModelTests.cs
1,206
C#
using System; using System.Data; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using Telligent.Glow; using Graffiti.Core; namespace Graffiti.Web { public class upload : MultipleUploadFileHandler { public override void ProcessRequest(HttpContext context) { if (context.Request.QueryString["Username"] != null && context.Request.QueryString["Ticket"] != null) { IGraffitiUser user = GraffitiUsers.GetUser(context.Request.QueryString["Username"], true); if (user == null || user.UniqueId.ToString() != context.Request.QueryString["Ticket"] || user.UniqueId == Guid.Empty) throw new InvalidOperationException("The upload form can only be used by users who are logged in"); } else { IGraffitiUser user = GraffitiUsers.Current; if (user == null) throw new InvalidOperationException("The upload form can only be used by users who are logged in"); } base.ProcessRequest(context); } } }
35.69697
133
0.617997
[ "MIT" ]
harder/GraffitiCMS
src/Graffiti.Web/graffiti-admin/upload.ashx.cs
1,178
C#
// Conjure application framework. // Copyright (C) Conjure. using System.Linq.Expressions; using Conjure.Binding; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; namespace Conjure.BlazorKit.Data; public delegate Task<LoadDataPage<TDataItem>> LoadDataHandler<TDataItem>(LoadDataArgs<TDataItem> args); public static class DataItemLoader { public static LoadDataHandler<TDataItem> Create<TDataItem>(ValueBinder<IEnumerable<TDataItem>> binder, Func<IDataSearchField<TDataItem>[]>? searchFieldsProvider = null) where TDataItem : class { // Temporarily disabled CS1998 until the async issue below is addressed #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously return async (args) => #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { // TODO: THIS NEEDS FURTHER INVESTIGATION // Down below we tried to make use of Async variants of the IQueryable extension methods // from EF Core (.CountAsync(), .ToListAsync(), etc...), HOWEVER, as the same DbContext // may be used by multiple data-query-aware controls on the same page, they may actually // invoke query operations against the same DbContext simulataneously from different // async pool threads, a big no-no with DbContext (which is not multi-thread capable). // For now we revert back to the sync versions, and we'll need to later investigate // if there is some way to synch calls within DbContext itself to force serializing // such activity against the same DbContext instance, and still support async calls // across different instances and different async I/O calls in general IEnumerable<TDataItem> items; var totalItems = 0; if (binder.TryGetValue(out var enumerable)) { var pageSize = args.PageSize; if (enumerable is IQueryable<TDataItem> queryable) { // Remember this if it's applicable var dbset = queryable as DbSet<TDataItem>; //totalItems = await queryable.CountAsync(); totalItems = queryable.Count(); if (args.Search != null && searchFieldsProvider != null) { var searchFields = searchFieldsProvider(); if (searchFields.Length > 0) { var pred = searchFields[0].Predicate!(args.Search)!; for (var i = 1; i < searchFields.Length; i++) { pred = PredicateBuilder.Or(pred, searchFields[i].Predicate!(args.Search)); } queryable = queryable.Where(pred); } } if (args.SortKey?.Expression != null) { queryable = args.SortKey.Expression(queryable, args.SortDirection); } queryable = queryable.Skip(pageSize * args.Page).Take(pageSize); //items = await queryable.ToListAsync(); items = queryable.ToList(); if (dbset != null && dbset.GetDbContext() is DbContext db) { //// Add in any newly added entities var added = db.ChangeTracker.Entries<TDataItem>() .Where(x => x.State == EntityState.Added) .Select(x => x.Entity).ToArray(); if (added.Length > 0) { items = items.Concat(added); } } } else { totalItems = enumerable.Count(); if (args.Search != null && searchFieldsProvider != null) { var searchFields = searchFieldsProvider(); if (searchFields.Length > 0) { var pred = searchFields[0].Predicate!(args.Search)!; for (var i = 1; i < searchFields.Length; i++) { pred = PredicateBuilder.Or(pred, searchFields[i].Predicate!(args.Search)); } enumerable = enumerable.AsQueryable().Where(pred); } } if (args.SortKey?.Expression != null) { enumerable = args.SortKey.Expression(enumerable.AsQueryable(), args.SortDirection); } enumerable = enumerable.Skip(pageSize * args.Page).Take(pageSize); items = enumerable.ToList(); } } else { items = Enumerable.Empty<TDataItem>(); } return new() { Items = items, TotalItems = totalItems, }; }; } // From: // https://dev.to/j_sakamoto/how-to-get-a-dbcontext-from-a-dbset-in-entityframework-core-c6m public static DbContext? GetDbContext<TDataItem>(this DbSet<TDataItem> dbSet) where TDataItem : class { var infrastructure = dbSet as IInfrastructure<IServiceProvider>; var serviceProvider = infrastructure.Instance; var currentDbContext = serviceProvider.GetService(typeof(ICurrentDbContext)) as ICurrentDbContext; return currentDbContext?.Context; } }
44.096296
107
0.52293
[ "MIT" ]
ebekker/conjure
src/Conjure.BlazorKit/Data/LoadDataHandler.cs
5,955
C#
namespace AspNetCoreBoilerplateApplication1.Services { using System; using System.Collections.Generic; using System.Threading.Tasks; using Boilerplate.AspNetCore; using Boilerplate.AspNetCore.Caching; using Boilerplate.AspNetCore.Sitemap; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using AspNetCoreBoilerplateApplication1.Constants; using AspNetCoreBoilerplateApplication1.Settings; /// <summary> /// Generates sitemap XML for the current site. /// </summary> public class SitemapService : SitemapGenerator, ISitemapService { private readonly IOptionsSnapshot<CacheProfileSettings> cacheProfileSettings; private readonly IDistributedCache distributedCache; private readonly ILogger<SitemapService> logger; private readonly IUrlHelper urlHelper; /// <summary> /// Initializes a new instance of the <see cref="SitemapService" /> class. /// </summary> /// <param name="cacheProfileSettings">The cache profile settings.</param> /// <param name="distributedCache">The distributed cache for the application.</param> /// <param name="logger">The <see cref="SitemapService"/> logger.</param> /// <param name="urlHelper">The URL helper.</param> public SitemapService( IOptionsSnapshot<CacheProfileSettings> cacheProfileSettings, IDistributedCache distributedCache, ILogger<SitemapService> logger, IUrlHelper urlHelper) { this.cacheProfileSettings = cacheProfileSettings; this.distributedCache = distributedCache; this.logger = logger; this.urlHelper = urlHelper; } /// <summary> /// Gets the sitemap XML for the current site. If an index of null is passed and there are more than 25,000 /// sitemap nodes, a sitemap index file is returned (A sitemap index file contains links to other sitemap files /// and is a way of splitting up your sitemap into separate files). If an index is specified, a standard /// sitemap is returned for the specified index parameter. See http://www.sitemaps.org/protocol.html /// </summary> /// <param name="index">The index of the sitemap to retrieve. <c>null</c> if you want to retrieve the root /// sitemap or sitemap index document, depending on the number of sitemap nodes.</param> /// <returns>The sitemap XML for the current site or <c>null</c> if the sitemap index is out of range.</returns> public async Task<string> GetSitemapXml(int? index = null) { // Here we are caching the entire set of sitemap documents. We cannot use the caching attribute because // cache expiry could get out of sync if the number of sitemaps changes. var sitemapDocuments = await this.distributedCache.GetAsJsonAsync<List<string>>(CacheProfileName.SitemapNodes); if (sitemapDocuments == null) { IReadOnlyCollection<SitemapNode> sitemapNodes = this.GetSitemapNodes(); sitemapDocuments = this.GetSitemapDocuments(sitemapNodes); await this.distributedCache.SetAsJsonAsync( CacheProfileName.SitemapNodes, sitemapDocuments, options: new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = this.GetExpirationDuration() }); } if (index.HasValue && ((index < 1) || (index.Value >= sitemapDocuments.Count))) { return null; } return sitemapDocuments[index.HasValue ? index.Value : 0]; } /// <summary> /// Gets a collection of sitemap nodes for the current site. /// TODO: Add code here to create nodes to all your important sitemap URL's. /// You may want to do this from a database or in code. /// </summary> /// <returns>A collection of sitemap nodes for the current site.</returns> protected virtual IReadOnlyCollection<SitemapNode> GetSitemapNodes() { List<SitemapNode> nodes = new List<SitemapNode>(); nodes.Add( new SitemapNode(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex)) { Priority = 1 }); nodes.Add( new SitemapNode(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetAbout)) { Priority = 0.9 }); nodes.Add( new SitemapNode(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetContact)) { Priority = 0.9 }); // An example of how to add many pages into your sitemap. // foreach (int productId in myProductRepository.GetProductIds()) // { // nodes.Add( // new SitemapNode(this.urlHelper.AbsoluteRouteUrl(ProductControllerRoute.GetProduct, new { id = productId })) // { // Frequency = SitemapFrequency.Weekly, // LastModified = DateTime.Now, // Priority = 0.8 // }); // } return nodes; } protected override string GetSitemapUrl(int index) { return this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetSitemapXml).TrimEnd('/') + "?index=" + index; } protected override void LogWarning(Exception exception) { this.logger.LogWarning(exception.Message, exception); } private TimeSpan GetExpirationDuration() { var cacheProfile = this.cacheProfileSettings.Value.CacheProfiles[CacheProfileName.SitemapNodes]; return TimeSpan.FromSeconds(cacheProfile.Duration.Value); } } }
44.912409
129
0.614985
[ "MIT" ]
jramos-br/PlayGround
VS2017-15.9.18/CS/AspNetCoreBoilerplateApplication1/AspNetCoreBoilerplateApplication1/Services/Sitemap/SitemapService.cs
6,155
C#
using Newtonsoft.Json; namespace MessageBird.Objects { public class ContactMessageReference { [JsonProperty("href")] public string Href { get; set; } [JsonProperty("totalCount")] public int TotalCount { get; set; } } }
19.928571
44
0.591398
[ "ISC" ]
Faultless/csharp-rest-api
MessageBird/Objects/ContactMessageReference.cs
268
C#
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using SixLabors.ImageSharp.Drawing.Processing.Processors.Drawing; using SixLabors.ImageSharp.Processing; namespace SixLabors.ImageSharp.Drawing.Processing { /// <summary> /// Adds extensions that allow the filling of polygon outlines to the <see cref="Image{TPixel}"/> type. /// </summary> public static class ClearPathExtensions { /// <summary> /// Clones the shape graphic options and applies changes required to force clearing. /// </summary> /// <param name="shapeOptions">The options to clone</param> /// <returns>A clone of shapeOptions with ColorBlendingMode, AlphaCompositionMode, and BlendPercentage set</returns> internal static DrawingOptions CloneForClearOperation(this DrawingOptions shapeOptions) { GraphicsOptions options = shapeOptions.GraphicsOptions.DeepClone(); options.ColorBlendingMode = PixelFormats.PixelColorBlendingMode.Normal; options.AlphaCompositionMode = PixelFormats.PixelAlphaCompositionMode.Src; options.BlendPercentage = 1; return new DrawingOptions(options, shapeOptions.ShapeOptions, shapeOptions.TextOptions, shapeOptions.Transform); } /// <summary> /// Flood fills the image in the shape of the provided polygon with the specified brush without any blending. /// </summary> /// <param name="source">The image this method extends.</param> /// <param name="options">The graphics options.</param> /// <param name="brush">The brush.</param> /// <param name="path">The shape.</param> /// <returns>The <see cref="IImageProcessingContext"/> to allow chaining of operations.</returns> public static IImageProcessingContext Clear( this IImageProcessingContext source, DrawingOptions options, IBrush brush, IPath path) => source.Fill(options.CloneForClearOperation(), brush, path); /// <summary> /// Flood fills the image in the shape of the provided polygon with the specified brush without any blending. /// </summary> /// <param name="source">The image this method extends.</param> /// <param name="brush">The brush.</param> /// <param name="path">The path.</param> /// <returns>The <see cref="IImageProcessingContext"/> to allow chaining of operations.</returns> public static IImageProcessingContext Clear(this IImageProcessingContext source, IBrush brush, IPath path) => source.Clear(source.GetDrawingOptions(), brush, path); /// <summary> /// Flood fills the image in the shape of the provided polygon with the specified brush without any blending. /// </summary> /// <param name="source">The image this method extends.</param> /// <param name="options">The options.</param> /// <param name="color">The color.</param> /// <param name="path">The path.</param> /// <returns>The <see cref="IImageProcessingContext"/> to allow chaining of operations.</returns> public static IImageProcessingContext Clear( this IImageProcessingContext source, DrawingOptions options, Color color, IPath path) => source.Clear(options, new SolidBrush(color), path); /// <summary> /// Flood fills the image in the shape of the provided polygon with the specified brush without any blending. /// </summary> /// <param name="source">The image this method extends.</param> /// <param name="color">The color.</param> /// <param name="path">The path.</param> /// <returns>The <see cref="IImageProcessingContext"/> to allow chaining of operations.</returns> public static IImageProcessingContext Clear(this IImageProcessingContext source, Color color, IPath path) => source.Clear(new SolidBrush(color), path); } }
50.8625
124
0.655444
[ "Apache-2.0" ]
obayomy/ImageSharp.Drawing
src/ImageSharp.Drawing/Processing/Extensions/ClearPathExtensions.cs
4,069
C#
// Copyright Epic Games, Inc. All Rights Reserved. // This file is automatically generated. Changes to this file may be overwritten. namespace Epic.OnlineServices.Friends { /// <summary> /// Function prototype definition for callbacks passed to <see cref="FriendsInterface.AcceptInvite" /> /// </summary> /// <param name="data">A <see cref="AcceptInviteCallbackInfo" /> containing the output information and result.</param> public delegate void OnAcceptInviteCallback(AcceptInviteCallbackInfo data); [System.Runtime.InteropServices.UnmanagedFunctionPointer(Config.LibraryCallingConvention)] internal delegate void OnAcceptInviteCallbackInternal(System.IntPtr data); }
48.285714
119
0.795858
[ "MIT" ]
CreepyAnt/EpicOnlineTransport
Mirror/Runtime/Transport/EpicOnlineTransport/EOSSDK/Generated/Friends/OnAcceptInviteCallback.cs
676
C#
using System.Web; using System.Web.Mvc; using System.Web.Mvc.Filters; namespace Livraria.App_Start { public class Autenticacao : ActionFilterAttribute, IAuthenticationFilter { public void OnAuthentication(AuthenticationContext filterContext) { //throw new NotImplementedException(); } public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) { var user = HttpContext.Current.Session["Usuario"]; if (user == null) { filterContext.Result = new RedirectResult("/Usuario/TelaLogar"); } } } }
28.043478
91
0.644961
[ "MIT" ]
lsantoss/Livraria-Asp.net-MVC5
Livraria/App_Start/Autenticacao.cs
647
C#
#region License Terms // ================================================================================ // RosSharp // // Software License Agreement (BSD License) // // Copyright (C) 2012 zoetrope // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ================================================================================ #endregion using CookComputing.XmlRpc; namespace RosSharp.Slave { /// <summary> /// Defines interface for Slave API /// </summary> /// <remarks> /// http://www.ros.org/wiki/ROS/Slave_API /// </remarks> [XmlRpcUrl("")] internal interface ISlave { /// <summary> /// Retrieve transport/topic statistics. /// </summary> /// <param name="callerId"> ROS caller ID. </param> /// <returns> /// [0] = int: code <br /> /// [1] = str: status message <br /> /// [2] = stats: [publishStats, subscribeStats, serviceStats] <br /> /// publishStats: [[topicName, messageDataSent, pubConnectionData]...] <br /> /// subscribeStats: [[topicName, subConnectionData]...] <br /> /// serviceStats: (proposed) [numRequests, bytesReceived, bytesSent] <br /> /// pubConnectionData: [connectionId, bytesSent, numSent, connected]* <br /> /// subConnectionData: [connectionId, bytesReceived, numSent, dropEstimate, connected]* /// </returns> [XmlRpcMethod("getBusStats")] object[] GetBusStats(string callerId); /// <summary> /// Retrieve transport/topic connection information. /// </summary> /// <param name="callerId"> ROS caller ID. </param> /// <returns> /// [0] = int: code <br/> /// [1] = str: status message<br/> /// [2] = businfo: [[connectionId1, destinationId1, direction1, transport1, topic1, connected1]... ] <br/> /// connectionId is defined by the node and is opaque. <br/> /// destinationId is the XMLRPC URI of the destination. <br/> /// direction is one of 'i', 'o', or 'b' (in, out, both). <br/> /// transport is the transport type (e.g. 'TCPROS'). <br/> /// topic is the topic name. <br/> /// connected1 indicates connection status. /// </returns> [XmlRpcMethod("getBusInfo")] object[] GetBusInfo(string callerId); /// <summary> /// Get the URI of the master node. /// </summary> /// <param name="callerId"> ROS caller ID. </param> /// <returns> /// [0] = int: code <br/> /// [1] = str: status message <br/> /// [2] = str: URI of the master /// </returns> [XmlRpcMethod("getMasterUri")] object[] GetMasterUri(string callerId); /// <summary> /// Stop this server. /// </summary> /// <param name="callerId"> ROS caller ID. </param> /// <param name="msg"> A message describing why the node is being shutdown. </param> /// <returns> /// [0] = int: code <br/> /// [1] = str: status message <br/> /// [2] = int: ignore /// </returns> [XmlRpcMethod("shutdown")] object[] Shutdown(string callerId, string msg); /// <summary> /// Get the PID of this server. /// </summary> /// <param name="callerId"> ROS caller ID. </param> /// <returns> /// [0] = int: code <br/> /// [1] = str: status message <br/> /// [2] = int: server process pid /// </returns> [XmlRpcMethod("getPid")] object[] GetPid(string callerId); /// <summary> /// Retrieve a list of topics that this node subscribes to /// </summary> /// <param name="callerId"> ROS caller ID. </param> /// <returns> /// [0] = int: code <br/> /// [1] = str: status message <br/> /// [2] = topicList is a list of topics this node subscribes to and is of the form [ [topic1, topicType1]...[topicN, topicTypeN]]] /// </returns> [XmlRpcMethod("getSubscriptions")] object[] GetSubscriptions(string callerId); /// <summary> /// Retrieve a list of topics that this node publishes. /// </summary> /// <param name="callerId"> ROS caller ID. </param> /// <returns> /// [0] = int: code <br/> /// [1] = str: status message <br/> /// [2] = topicList is a list of topics published by this node and is of the form [ [topic1, topicType1]...[topicN, topicTypeN]]] /// </returns> [XmlRpcMethod("getPublications")] object[] GetPublications(string callerId); /// <summary> /// Callback from master with updated value of subscribed parameter. /// </summary> /// <param name="callerId"> ROS caller ID. </param> /// <param name="parameterKey"> Parameter name, globally resolved. </param> /// <param name="parameterValue"> New parameter value. </param> /// <returns> /// [0] = int: code <br/> /// [1] = str: status message <br/> /// [2] = int: ignore /// </returns> [XmlRpcMethod("paramUpdate")] object[] ParamUpdate(string callerId, string parameterKey, object parameterValue); /// <summary> /// Callback from master of current publisher list for specified topic. /// </summary> /// <param name="callerId"> ROS caller ID. </param> /// <param name="topic"> Topic name. </param> /// <param name="publishers"> List of current publishers for topic in the form of XMLRPC URIs </param> /// <returns> /// [0] = int: code <br/> /// [1] = str: status message <br/> /// [2] = int: ignore /// </returns> [XmlRpcMethod("publisherUpdate")] object[] PublisherUpdate(string callerId, string topic, string[] publishers); /// <summary> /// Publisher node API method called by a subscriber node. <br/> /// This requests that source allocate a channel for communication. <br/> /// Subscriber provides a list of desired protocols for communication. <br/> /// Publisher returns the selected protocol along with any additional params required for establishing connection. <br/> /// For example, for a TCP/IP-based connection, the source node may return a port number of TCP/IP server. /// </summary> /// <param name="callerId"> ROS caller ID. </param> /// <param name="topic"> Topic name. </param> /// <param name="protocols"> List of desired protocols for communication in order of preference. Each protocol is a list of the form [ProtocolName, ProtocolParam1, ProtocolParam2...N] </param> /// <returns> /// [0] = int: code <br/> /// [1] = str: status message <br/> /// [2] = protocolParams may be an empty list if there are no compatible protocols. /// </returns> [XmlRpcMethod("requestTopic")] object[] RequestTopic(string callerId, string topic, object[] protocols); } }
45.952128
201
0.563375
[ "BSD-2-Clause" ]
mamamaisused/RosSharp
RosSharp/Slave/ISlave.cs
8,641
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 elasticbeanstalk-2010-12-01.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.ElasticBeanstalk.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.ElasticBeanstalk.Model.Internal.MarshallTransformations { /// <summary> /// DescribeConfigurationOptions Request Marshaller /// </summary> public class DescribeConfigurationOptionsRequestMarshaller : IMarshaller<IRequest, DescribeConfigurationOptionsRequest> , 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((DescribeConfigurationOptionsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeConfigurationOptionsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.ElasticBeanstalk"); request.Parameters.Add("Action", "DescribeConfigurationOptions"); request.Parameters.Add("Version", "2010-12-01"); if(publicRequest != null) { if(publicRequest.IsSetApplicationName()) { request.Parameters.Add("ApplicationName", StringUtils.FromString(publicRequest.ApplicationName)); } if(publicRequest.IsSetEnvironmentName()) { request.Parameters.Add("EnvironmentName", StringUtils.FromString(publicRequest.EnvironmentName)); } if(publicRequest.IsSetOptions()) { int publicRequestlistValueIndex = 1; foreach(var publicRequestlistValue in publicRequest.Options) { if(publicRequestlistValue.IsSetNamespace()) { request.Parameters.Add("Options" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Namespace", StringUtils.FromString(publicRequestlistValue.Namespace)); } if(publicRequestlistValue.IsSetOptionName()) { request.Parameters.Add("Options" + "." + "member" + "." + publicRequestlistValueIndex + "." + "OptionName", StringUtils.FromString(publicRequestlistValue.OptionName)); } if(publicRequestlistValue.IsSetResourceName()) { request.Parameters.Add("Options" + "." + "member" + "." + publicRequestlistValueIndex + "." + "ResourceName", StringUtils.FromString(publicRequestlistValue.ResourceName)); } publicRequestlistValueIndex++; } } if(publicRequest.IsSetPlatformArn()) { request.Parameters.Add("PlatformArn", StringUtils.FromString(publicRequest.PlatformArn)); } if(publicRequest.IsSetSolutionStackName()) { request.Parameters.Add("SolutionStackName", StringUtils.FromString(publicRequest.SolutionStackName)); } if(publicRequest.IsSetTemplateName()) { request.Parameters.Add("TemplateName", StringUtils.FromString(publicRequest.TemplateName)); } } return request; } private static DescribeConfigurationOptionsRequestMarshaller _instance = new DescribeConfigurationOptionsRequestMarshaller(); internal static DescribeConfigurationOptionsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeConfigurationOptionsRequestMarshaller Instance { get { return _instance; } } } }
43.317073
200
0.586149
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ElasticBeanstalk/Generated/Model/Internal/MarshallTransformations/DescribeConfigurationOptionsRequestMarshaller.cs
5,328
C#
using System; using System.Threading; using System.Threading.Tasks; using CronScheduler.Extensions.Scheduler; using Microsoft.Extensions.Logging; namespace CronSchedulerApp.Jobs { public class TestJob : IScheduledJob { private readonly ILogger<TestJob> _logger; private SchedulerOptions _options; public TestJob( SchedulerOptions options, ILogger<TestJob> logger) { _options = options; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public string Name { get; } = nameof(TestJob); // will be removed in the next release public Task ExecuteAsync(CancellationToken cancellationToken) { _logger.LogInformation("{cronSchedule} - {id}", _options.CronSchedule, Guid.NewGuid()); return Task.CompletedTask; } } }
25.714286
99
0.646667
[ "MIT" ]
kdcllc/CronScheduler.AspNetCore
src/CronSchedulerApp/Jobs/TestJob.cs
902
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Yamaanco.Domain.Entities.GroupEntities; namespace Yamaanco.Infrastructure.EF.Persistence.Configurations.GroupConf { public class GroupMessageViewerConfiguration : IEntityTypeConfiguration<GroupMessageViewer> { public void Configure(EntityTypeBuilder<GroupMessageViewer> builder) { } } }
32.461538
95
0.791469
[ "MIT" ]
YamanNasser/Yamaanco
Yamaanco.EF.Persistence/Configurations/GroupConf/GroupMessageViewerConfiguration.cs
424
C#
using System.Collections.ObjectModel; namespace Hotel.Areas.HelpPage.ModelDescriptions { public class ComplexTypeModelDescription : ModelDescription { public ComplexTypeModelDescription() { Properties = new Collection<ParameterDescription>(); } public Collection<ParameterDescription> Properties { get; private set; } } }
27.071429
80
0.701847
[ "MIT" ]
TorresFelipeD/Axede_PruebaTecnica
Hotel/Hotel/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs
379
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. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.Intune { using Management.Intune; using Management.Intune.Models; using Microsoft.Azure.Commands.Intune.Properties; using System; using System.Globalization; using System.Management.Automation; /// <summary> /// A cmdlet that creates a new iOS Intune MAM policy azure resource. /// </summary> [Cmdlet(VerbsCommon.New, "AzureRmIntuneiOSMAMPolicy"), OutputType(typeof(IOSMAMPolicy))] public sealed class NewIntuneiOSMAMPolicyCmdlet : IntuneBaseCmdlet { /// <summary> /// Gets or sets the kind. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy friendly name.")] [ValidateNotNullOrEmpty] public string FriendlyName { get; set; } /// <summary> /// The description of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy description.")] [ValidateNotNullOrEmpty] public string Description { get; set; } /// <summary> /// The AppSharingFromLevel of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether the application is allowed to receive information shared by other applications. Information can be restricted to no applications, only managed applications, or be allowed from all applications.")] [ValidateNotNullOrEmpty, ValidateSet("none", "policyManagedApps","allApps"), PSDefaultValue(Value = AppSharingType.none)] public AppSharingType AppSharingFromLevel { get; set; } /// <summary> /// The AppSharingToLevel of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether the application is allowed to share information with other applications. Information can be shared with no applications, only managed applications, or shared to all applications.")] [ValidateNotNullOrEmpty, ValidateSet("none", "policyManagedApps", "allApps"), PSDefaultValue(Value = AppSharingType.none)] public AppSharingType AppSharingToLevel{ get; set; } /// <summary> /// The Authentication of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether corporate credentials are required to access the application.")] [ValidateNotNullOrEmpty, ValidateSet("required","notRequired"), PSDefaultValue(Value = ChoiceType.required)] public ChoiceType Authentication { get; set; } /// <summary> /// The ClipboardSharingLevel of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether to restrict cut, copy and paste with other applications.")] [ValidateNotNullOrEmpty, ValidateSet("blocked", "policyManagedApps", "policyManagedAppsWithPasteIn", "allApps"), PSDefaultValue(Value = ClipboardSharingLevelType.blocked)] public ClipboardSharingLevelType ClipboardSharingLevel{ get; set; } /// <summary> /// The DataBackup of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether to prevent iTunes and iCloud backups.")] [ValidateNotNullOrEmpty, ValidateSet("allow", "block"), PSDefaultValue(Value = FilterType.allow)] public FilterType DataBackup { get; set; } /// <summary> /// The FileSharingSaveAs of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether to prevent ‘Save As’ from the application.")] [ValidateNotNullOrEmpty, ValidateSet("allow", "block"), PSDefaultValue(Value = FilterType.allow)] public FilterType FileSharingSaveAs { get; set; } /// <summary> /// The Pin of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether simple PIN is required to access the application.")] [ValidateNotNullOrEmpty, ValidateSet("required", "notRequired"), PSDefaultValue(Value = ChoiceType.required)] public ChoiceType Pin { get; set;} /// <summary> /// The PinNumRetry of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "When a simple PIN is required to access the application, this indicates the number of attempts before a PIN reset.")] [ValidateNotNullOrEmpty, ValidateRange(0, 200)] public int? PinNumRetry { get; set; } /// <summary> /// The DeviceCompliance of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether managed applications are blocked from running on rooted or jailbroken devices.")] [ValidateNotNullOrEmpty, ValidateSet("enable","disable"), PSDefaultValue(Value = OptionType.enable)] public OptionType DeviceCompliance { get; set; } /// <summary> /// The ManagedBrowser of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether web content from the application is forced to run in the managed browser.")] [ValidateNotNullOrEmpty, ValidateSet("required", "notRequired"), PSDefaultValue(Value = ChoiceType.required)] public ChoiceType ManagedBrowser { get; set; } /// <summary> /// The AccessRecheckOfflineTimeout of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates how long to wait in minutes before re-checking access requirements on the device if the device is offline.")] [ValidateNotNullOrEmpty] public int? AccessRecheckOfflineTimeout { get; set; } /// <summary> /// The AccessRecheckOnlineTimeout of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates how long to wait in minutes before re-checking access requirements on the device.")] public int? AccessRecheckOnlineTimeout { get; set; } /// <summary> /// The OfflineWipeTimeout of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates the number of days a device must be offline before application data is automatically wiped.")] public int? OfflineWipeTimeout { get; set; } /// <summary> /// The FileEncryptionLevel of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates the level of encryption for application data.")] [ValidateNotNullOrEmpty, PSDefaultValue(Value = DeviceLockType.deviceLocked)] public DeviceLockType FileEncryptionLevel { get; set; } /// <summary> /// The TouchId of the policy /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicates whether fingerprints are allowed instead of PIN to access the application.")] [ValidateNotNullOrEmpty, PSDefaultValue(Value = OptionType.enable, Help ="Defaults to 'enable'")] public OptionType TouchId { get; set; } /// <summary> /// Executes the cmdlet. /// </summary> public override void ExecuteCmdlet() { InitializeDefaultValuesForParams(); var policyId = (IntuneBaseCmdlet.iOSPolicyIdsQueue.Count == 0 ? Guid.NewGuid() : IntuneBaseCmdlet.iOSPolicyIdsQueue.Dequeue()).ToString(); ValidateNumericParameters(); var policyObj = this.IntuneClient.Ios.CreateOrUpdateMAMPolicy(this.AsuHostName, policyId, this.PrepareIOSPolicyBody()); this.WriteObject(policyObj); } /// <summary> /// Initialize the number & string parameters if the value is not provided as part of commandlet execution.. /// Looks like Parameter PSDefaultValue() does not initialize integers & string params /// </summary> private void InitializeDefaultValuesForParams() { this.PinNumRetry = this.PinNumRetry ?? IntuneConstants.DefaultPinNumRetry; this.AccessRecheckOfflineTimeout = this.AccessRecheckOfflineTimeout ?? IntuneConstants.DefaultAccessRecheckOfflineTimeout; this.AccessRecheckOnlineTimeout = this.AccessRecheckOnlineTimeout ?? IntuneConstants.DefaultAccessRecheckOnlineTimeout; this.OfflineWipeTimeout = this.OfflineWipeTimeout ?? IntuneConstants.DefaultOfflineWipeTimeout; this.Description = this.Description ?? string.Format(CultureInfo.CurrentCulture, Resources.NewResource, Resources.IosPolicy); } /// <summary> /// Verify that numeric parameters are non negative /// </summary> private void ValidateNumericParameters() { NumericParameterValueChecker.CheckIfNegativeAndThrowException( new System.Collections.Generic.Dictionary<string, int> { {IntuneConstants.PinNumRetryProperty, PinNumRetry.Value}, {IntuneConstants.AccessRecheckOfflineTimeoutProperty, this.AccessRecheckOfflineTimeout.Value}, {IntuneConstants.AccessRecheckOnlineTimeoutProperty, this.AccessRecheckOnlineTimeout.Value}, {IntuneConstants.OfflineWipeTimeoutProperty, this.OfflineWipeTimeout.Value } }); } /// <summary> /// Prepares iOS Policy body for the new policy request /// </summary> /// <returns>policy request body</returns> private IOSMAMPolicy PrepareIOSPolicyBody() { var policyBody = new IOSMAMPolicy() { FriendlyName = this.FriendlyName, Description = this.Description, AppSharingFromLevel = this.AppSharingFromLevel.ToString(), AppSharingToLevel = this.AppSharingToLevel.ToString(), Authentication = this.Authentication.ToString(), ClipboardSharingLevel = this.ClipboardSharingLevel.ToString(), DataBackup = this.DataBackup.ToString(), FileSharingSaveAs = this.FileSharingSaveAs.ToString(), Pin = this.Pin.ToString(), PinNumRetry = this.PinNumRetry, DeviceCompliance = this.DeviceCompliance.ToString(), ManagedBrowser = this.ManagedBrowser.ToString(), AccessRecheckOfflineTimeout = TimeSpan.FromMinutes(this.AccessRecheckOfflineTimeout.Value), AccessRecheckOnlineTimeout = TimeSpan.FromMinutes(this.AccessRecheckOnlineTimeout.Value), OfflineWipeTimeout = TimeSpan.FromDays(this.OfflineWipeTimeout.Value), FileEncryptionLevel = this.FileEncryptionLevel.ToString(), TouchId = this.TouchId.ToString() }; return policyBody; } } }
57.40367
308
0.654867
[ "MIT" ]
DalavanCloud/azure-powershell
src/ResourceManager/Intune/Commands.Intune/Policy/NewIntuneiOSMAMPolicyCmdlet.cs
12,303
C#
//------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </auto-generated> //------------------------------------------------------------------------------ namespace GetTheFoodAlready.Ui.Wpf.Resources { using System; /// <summary> /// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д. /// </summary> // Этот класс создан автоматически классом StronglyTypedResourceBuilder // с помощью такого средства, как ResGen или Visual Studio. // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen // с параметром /str или перестройте свой проект VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class BrowserHelper { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal BrowserHelper() { } /// <summary> /// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GetTheFoodAlready.Ui.Wpf.Resources.BrowserHelper", typeof(BrowserHelper).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Перезаписывает свойство CurrentUICulture текущего потока для всех /// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Ищет локализованную строку, похожую на &lt;!DOCTYPE html&gt; ///&lt;html&gt; ///&lt;head&gt; /// &lt;script src=&quot;https://code.jquery.com/jquery-3.5.1.min.js&quot; /// integrity=&quot;sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=&quot; /// crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; /// &lt;script src=&quot;https://polyfill.io/v3/polyfill.min.js?features=default&quot;&gt;&lt;/script&gt; /// &lt;script src=&quot;https://maps.googleapis.com/maps/api/js?key=AIzaSyDq3LH7PoQlHWUil0vLdUt3Bc7J5Hyjksc&amp;callback=initMap&amp;libraries=geometry,places&amp;v=weekly&amp;language=ru&quot; /// defer&gt;&lt;/script&gt; /// &lt;style&gt; /// #map { height: 10 [остаток строки не уместился]&quot;;. /// </summary> internal static string SetupLocationGoogleMapsDummy { get { return ResourceManager.GetString("SetupLocationGoogleMapsDummy", resourceCulture); } } } }
48.024096
202
0.62293
[ "MIT" ]
Fildrance/GetTheFoodAlready
src/GetTheFoodAlready.Ui.Wpf/Resources/BrowserHelper.Designer.cs
4,554
C#
using System; namespace Utils { public static class Dimensions { /// <summary> /// Returns rectangle dimensions for nice alignment of passed cells /// </summary> public static (int, int) Calculate(int cells) { var cols = (int)Math.Ceiling(Math.Sqrt(cells)); while (true) { var rows = (int)Math.Ceiling((double)cells / cols); if (cols * rows == cells) return (cols, rows); cols += 1; } } } }
25.863636
76
0.472759
[ "MIT" ]
tarpaha/ProcessorCoresTrainer
Utils/Dimensions.cs
571
C#
/*********************************************************************************************************************** Copyright (c) 2016, Imagination Technologies Limited and/or its affiliated group companies. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace DTLS { internal static class NetworkByteOrderConverter { public static short ToInt16(Stream stream) { short result = 0; byte[] buffer = new byte[2]; int read = stream.Read(buffer, 0, 2); if (read == 2) result = ToInt16(buffer, 0); else throw new EndOfStreamException(); return result; } public static short ToInt16(byte[] value, uint startIndex) { short result; result = (short)((int)(value[startIndex]) << 8 | (int)value[startIndex + 1]); return result; } public static int ToInt24(Stream stream) { int result = 0; byte[] buffer = new byte[3]; int read = stream.Read(buffer, 0, 3); if (read == 3) result = ToInt24(buffer, 0); else throw new EndOfStreamException(); return result; } public static int ToInt24(byte[] value, uint startIndex) { int result; result = (((int)value[startIndex]) << 16 | ((int)value[startIndex + 1]) << 8 | (int)value[startIndex + 2]); return result; } public static int ToInt32(Stream stream) { int result = 0; byte[] buffer = new byte[4]; int read = stream.Read(buffer, 0, 4); if (read == 4) result = ToInt32(buffer, 0); else throw new EndOfStreamException(); return result; } public static int ToInt32(byte[] value, uint startIndex) { int result; result = (((int)value[startIndex]) << 24 | ((int)value[startIndex + 1]) << 16 | ((int)value[startIndex + 2]) << 8 | (int)value[startIndex + 3]); return result; } public static long ToInt48(Stream stream) { long result = 0; byte[] buffer = new byte[6]; int read = stream.Read(buffer, 0, 6); if (read == 6) result = ToInt48(buffer, 0); else throw new EndOfStreamException(); return result; } public static long ToInt48(byte[] value, uint startIndex) { long result; result = ToUInt32(value, startIndex + 2); result = result | (((long)ToUInt16(value, startIndex)) << 32); return result; } public static ushort ToUInt16(Stream stream) { ushort result = 0; byte[] buffer = new byte[2]; int read = stream.Read(buffer, 0, 2); if (read == 2) result = ToUInt16(buffer, 0); else throw new EndOfStreamException(); return result; } public static ushort ToUInt16(byte[] value, uint startIndex) { ushort result; result = (ushort)((uint)(value[startIndex]) << 8 | (uint)value[startIndex + 1]); return result; } public static uint ToUInt24(Stream stream) { uint result = 0; byte[] buffer = new byte[3]; int read = stream.Read(buffer, 0, 3); if (read == 3) result = ToUInt24(buffer, 0); else throw new EndOfStreamException(); return result; } public static uint ToUInt24(byte[] value, uint startIndex) { uint result; result = (((uint)value[startIndex]) << 16 | ((uint)value[startIndex + 1]) << 8 | (uint)value[startIndex + 2]); return result; } public static uint ToUInt32(Stream stream) { uint result = 0; byte[] buffer = new byte[4]; int read = stream.Read(buffer, 0, 4); if (read == 4) result = ToUInt32(buffer, 0); else throw new EndOfStreamException(); return result; } public static uint ToUInt32(byte[] value, uint startIndex) { uint result; result = (((uint)value[startIndex]) << 24 | ((uint)value[startIndex + 1]) << 16 | ((uint)value[startIndex + 2]) << 8 | (uint)value[startIndex + 3]); return result; } public static ulong ToUInt48(Stream stream) { ulong result = 0; byte[] buffer = new byte[6]; int read = stream.Read(buffer, 0, 6); if (read == 6) result = ToUInt48(buffer, 0); else throw new EndOfStreamException(); return result; } public static ulong ToUInt48(byte[] value, uint startIndex) { ulong result; result = ToUInt32(value, startIndex + 2); result = result | (((ulong)ToUInt16(value,startIndex)) << 32); return result; } public static void WriteInt16(Stream stream, short value) { byte[] buffer = new byte[4]; buffer[0] = (byte)(value >> 8); buffer[1] = (byte)(value & 0xFF); stream.Write(buffer, 0, 2); } public static void WriteInt24(Stream stream, int value) { byte[] buffer = new byte[3]; buffer[0] = (byte)(value >> 16); buffer[1] = (byte)(value >> 8); buffer[2] = (byte)(value & 0xFF); stream.Write(buffer, 0, 3); } public static void WriteInt32(Stream stream, int value) { byte[] buffer = new byte[4]; buffer[0] = (byte)(value >> 24); buffer[1] = (byte)(value >> 16); buffer[2] = (byte)(value >> 8); buffer[3] = (byte)(value & 0xFF); stream.Write(buffer, 0, 4); } public static void WriteInt32(byte[] buffer, int startIndex, int value) { buffer[startIndex] = (byte)(value >> 24); buffer[startIndex + 1] = (byte)(value >> 16); buffer[startIndex + 2] = (byte)(value >> 8); buffer[startIndex + 3] = (byte)(value & 0xFF); } public static void WriteInt48(Stream stream, long value) { byte[] buffer = new byte[6]; buffer[0] = (byte)(value >> 40); buffer[1] = (byte)(value >> 32); buffer[2] = (byte)(value >> 24); buffer[3] = (byte)(value >> 16); buffer[4] = (byte)(value >> 8); buffer[5] = (byte)(value & 0xFF); stream.Write(buffer, 0, 6); } public static void WriteUInt16(Stream stream, ushort value) { byte[] buffer = new byte[4]; buffer[0]= (byte)(value >> 8); buffer[1] = (byte)(value & 0xFF); stream.Write(buffer, 0, 2); } public static void WriteUInt24(Stream stream, uint value) { byte[] buffer = new byte[3]; buffer[0] = (byte)(value >> 16); buffer[1] = (byte)(value >> 8); buffer[2] = (byte)(value & 0xFF); stream.Write(buffer, 0, 3); } public static void WriteUInt32(Stream stream, uint value) { byte[] buffer = new byte[4]; buffer[0]= (byte)(value >> 24); buffer[1]= (byte)(value >> 16); buffer[2]= (byte)(value >> 8); buffer[3]= (byte)(value & 0xFF); stream.Write(buffer, 0, 4); } public static void WriteUInt16(byte[] buffer, int startIndex, ushort value) { buffer[startIndex] = (byte)(value >> 8); buffer[startIndex+ 1] = (byte)(value & 0xFF); } public static void WriteUInt32(byte[] buffer, int startIndex, uint value) { buffer[startIndex] = (byte)(value >> 24); buffer[startIndex + 1] = (byte)(value >> 16); buffer[startIndex + 2] = (byte)(value >> 8); buffer[startIndex + 3] = (byte)(value & 0xFF); } public static void WriteUInt48(Stream stream, ulong value) { byte[] buffer = new byte[6]; buffer[0] = (byte)(value >> 40); buffer[1] = (byte)(value >> 32); buffer[2] = (byte)(value >> 24); buffer[3] = (byte)(value >> 16); buffer[4] = (byte)(value >> 8); buffer[5] = (byte)(value & 0xFF); stream.Write(buffer, 0, 6); } } }
29.904437
151
0.62577
[ "BSD-3-Clause" ]
CreatorDev/DTLS.Net
src/DTLS.Net/Util/NetworkByteOrderConverter.cs
8,764
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Oci.Database { /// <summary> /// This resource provides the Backup Destination resource in Oracle Cloud Infrastructure Database service. /// /// Creates a backup destination in an Exadata Cloud@Customer system. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Oci = Pulumi.Oci; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var testBackupDestination = new Oci.Database.BackupDestination("testBackupDestination", new Oci.Database.BackupDestinationArgs /// { /// CompartmentId = @var.Compartment_id, /// DisplayName = @var.Backup_destination_display_name, /// Type = @var.Backup_destination_type, /// ConnectionString = @var.Backup_destination_connection_string, /// DefinedTags = @var.Backup_destination_defined_tags, /// FreeformTags = /// { /// { "Department", "Finance" }, /// }, /// LocalMountPointPath = @var.Backup_destination_local_mount_point_path, /// MountTypeDetails = new Oci.Database.Inputs.BackupDestinationMountTypeDetailsArgs /// { /// MountType = @var.Backup_destination_mount_type_details_mount_type, /// LocalMountPointPath = @var.Backup_destination_mount_type_details_local_mount_point_path, /// NfsServers = @var.Backup_destination_mount_type_details_nfs_server, /// NfsServerExport = @var.Backup_destination_mount_type_details_nfs_server_export, /// }, /// VpcUsers = @var.Backup_destination_vpc_users, /// }); /// } /// /// } /// ``` /// /// ## Import /// /// BackupDestinations can be imported using the `id`, e.g. /// /// ```sh /// $ pulumi import oci:database/backupDestination:BackupDestination test_backup_destination "id" /// ``` /// </summary> [OciResourceType("oci:database/backupDestination:BackupDestination")] public partial class BackupDestination : Pulumi.CustomResource { /// <summary> /// List of databases associated with the backup destination. /// </summary> [Output("associatedDatabases")] public Output<ImmutableArray<Outputs.BackupDestinationAssociatedDatabase>> AssociatedDatabases { get; private set; } = null!; /// <summary> /// (Updatable) The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment. /// </summary> [Output("compartmentId")] public Output<string> CompartmentId { get; private set; } = null!; /// <summary> /// (Updatable) The connection string for connecting to the Recovery Appliance. /// </summary> [Output("connectionString")] public Output<string?> ConnectionString { get; private set; } = null!; /// <summary> /// (Updatable) Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). /// </summary> [Output("definedTags")] public Output<ImmutableDictionary<string, object>> DefinedTags { get; private set; } = null!; /// <summary> /// The user-provided name of the backup destination. /// </summary> [Output("displayName")] public Output<string> DisplayName { get; private set; } = null!; /// <summary> /// (Updatable) Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}` /// </summary> [Output("freeformTags")] public Output<ImmutableDictionary<string, object>> FreeformTags { get; private set; } = null!; /// <summary> /// A descriptive text associated with the lifecycleState. Typically contains additional displayable text /// </summary> [Output("lifecycleDetails")] public Output<string> LifecycleDetails { get; private set; } = null!; /// <summary> /// The local directory path on each VM cluster node where the NFS server location is mounted. The local directory path and the NFS server location must each be the same across all of the VM cluster nodes. Ensure that the NFS mount is maintained continuously on all of the VM cluster nodes. /// </summary> [Output("localMountPointPath")] public Output<string> LocalMountPointPath { get; private set; } = null!; /// <summary> /// Mount type details for backup destination. /// </summary> [Output("mountTypeDetails")] public Output<Outputs.BackupDestinationMountTypeDetails> MountTypeDetails { get; private set; } = null!; /// <summary> /// NFS Mount type for backup destination. /// </summary> [Output("nfsMountType")] public Output<string> NfsMountType { get; private set; } = null!; /// <summary> /// Specifies the directory on which to mount the file system /// </summary> [Output("nfsServerExport")] public Output<string> NfsServerExport { get; private set; } = null!; /// <summary> /// IP addresses for NFS Auto mount. /// </summary> [Output("nfsServers")] public Output<ImmutableArray<string>> NfsServers { get; private set; } = null!; /// <summary> /// The current lifecycle state of the backup destination. /// </summary> [Output("state")] public Output<string> State { get; private set; } = null!; /// <summary> /// The date and time the backup destination was created. /// </summary> [Output("timeCreated")] public Output<string> TimeCreated { get; private set; } = null!; /// <summary> /// Type of the backup destination. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// (Updatable) The Virtual Private Catalog (VPC) users that are used to access the Recovery Appliance. /// </summary> [Output("vpcUsers")] public Output<ImmutableArray<string>> VpcUsers { get; private set; } = null!; /// <summary> /// Create a BackupDestination resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public BackupDestination(string name, BackupDestinationArgs args, CustomResourceOptions? options = null) : base("oci:database/backupDestination:BackupDestination", name, args ?? new BackupDestinationArgs(), MakeResourceOptions(options, "")) { } private BackupDestination(string name, Input<string> id, BackupDestinationState? state = null, CustomResourceOptions? options = null) : base("oci:database/backupDestination:BackupDestination", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing BackupDestination resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static BackupDestination Get(string name, Input<string> id, BackupDestinationState? state = null, CustomResourceOptions? options = null) { return new BackupDestination(name, id, state, options); } } public sealed class BackupDestinationArgs : Pulumi.ResourceArgs { /// <summary> /// (Updatable) The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment. /// </summary> [Input("compartmentId", required: true)] public Input<string> CompartmentId { get; set; } = null!; /// <summary> /// (Updatable) The connection string for connecting to the Recovery Appliance. /// </summary> [Input("connectionString")] public Input<string>? ConnectionString { get; set; } [Input("definedTags")] private InputMap<object>? _definedTags; /// <summary> /// (Updatable) Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). /// </summary> public InputMap<object> DefinedTags { get => _definedTags ?? (_definedTags = new InputMap<object>()); set => _definedTags = value; } /// <summary> /// The user-provided name of the backup destination. /// </summary> [Input("displayName", required: true)] public Input<string> DisplayName { get; set; } = null!; [Input("freeformTags")] private InputMap<object>? _freeformTags; /// <summary> /// (Updatable) Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}` /// </summary> public InputMap<object> FreeformTags { get => _freeformTags ?? (_freeformTags = new InputMap<object>()); set => _freeformTags = value; } /// <summary> /// The local directory path on each VM cluster node where the NFS server location is mounted. The local directory path and the NFS server location must each be the same across all of the VM cluster nodes. Ensure that the NFS mount is maintained continuously on all of the VM cluster nodes. /// </summary> [Input("localMountPointPath")] public Input<string>? LocalMountPointPath { get; set; } /// <summary> /// Mount type details for backup destination. /// </summary> [Input("mountTypeDetails")] public Input<Inputs.BackupDestinationMountTypeDetailsArgs>? MountTypeDetails { get; set; } /// <summary> /// Type of the backup destination. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; [Input("vpcUsers")] private InputList<string>? _vpcUsers; /// <summary> /// (Updatable) The Virtual Private Catalog (VPC) users that are used to access the Recovery Appliance. /// </summary> public InputList<string> VpcUsers { get => _vpcUsers ?? (_vpcUsers = new InputList<string>()); set => _vpcUsers = value; } public BackupDestinationArgs() { } } public sealed class BackupDestinationState : Pulumi.ResourceArgs { [Input("associatedDatabases")] private InputList<Inputs.BackupDestinationAssociatedDatabaseGetArgs>? _associatedDatabases; /// <summary> /// List of databases associated with the backup destination. /// </summary> public InputList<Inputs.BackupDestinationAssociatedDatabaseGetArgs> AssociatedDatabases { get => _associatedDatabases ?? (_associatedDatabases = new InputList<Inputs.BackupDestinationAssociatedDatabaseGetArgs>()); set => _associatedDatabases = value; } /// <summary> /// (Updatable) The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment. /// </summary> [Input("compartmentId")] public Input<string>? CompartmentId { get; set; } /// <summary> /// (Updatable) The connection string for connecting to the Recovery Appliance. /// </summary> [Input("connectionString")] public Input<string>? ConnectionString { get; set; } [Input("definedTags")] private InputMap<object>? _definedTags; /// <summary> /// (Updatable) Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). /// </summary> public InputMap<object> DefinedTags { get => _definedTags ?? (_definedTags = new InputMap<object>()); set => _definedTags = value; } /// <summary> /// The user-provided name of the backup destination. /// </summary> [Input("displayName")] public Input<string>? DisplayName { get; set; } [Input("freeformTags")] private InputMap<object>? _freeformTags; /// <summary> /// (Updatable) Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}` /// </summary> public InputMap<object> FreeformTags { get => _freeformTags ?? (_freeformTags = new InputMap<object>()); set => _freeformTags = value; } /// <summary> /// A descriptive text associated with the lifecycleState. Typically contains additional displayable text /// </summary> [Input("lifecycleDetails")] public Input<string>? LifecycleDetails { get; set; } /// <summary> /// The local directory path on each VM cluster node where the NFS server location is mounted. The local directory path and the NFS server location must each be the same across all of the VM cluster nodes. Ensure that the NFS mount is maintained continuously on all of the VM cluster nodes. /// </summary> [Input("localMountPointPath")] public Input<string>? LocalMountPointPath { get; set; } /// <summary> /// Mount type details for backup destination. /// </summary> [Input("mountTypeDetails")] public Input<Inputs.BackupDestinationMountTypeDetailsGetArgs>? MountTypeDetails { get; set; } /// <summary> /// NFS Mount type for backup destination. /// </summary> [Input("nfsMountType")] public Input<string>? NfsMountType { get; set; } /// <summary> /// Specifies the directory on which to mount the file system /// </summary> [Input("nfsServerExport")] public Input<string>? NfsServerExport { get; set; } [Input("nfsServers")] private InputList<string>? _nfsServers; /// <summary> /// IP addresses for NFS Auto mount. /// </summary> public InputList<string> NfsServers { get => _nfsServers ?? (_nfsServers = new InputList<string>()); set => _nfsServers = value; } /// <summary> /// The current lifecycle state of the backup destination. /// </summary> [Input("state")] public Input<string>? State { get; set; } /// <summary> /// The date and time the backup destination was created. /// </summary> [Input("timeCreated")] public Input<string>? TimeCreated { get; set; } /// <summary> /// Type of the backup destination. /// </summary> [Input("type")] public Input<string>? Type { get; set; } [Input("vpcUsers")] private InputList<string>? _vpcUsers; /// <summary> /// (Updatable) The Virtual Private Catalog (VPC) users that are used to access the Recovery Appliance. /// </summary> public InputList<string> VpcUsers { get => _vpcUsers ?? (_vpcUsers = new InputList<string>()); set => _vpcUsers = value; } public BackupDestinationState() { } } }
42.805288
298
0.611333
[ "ECL-2.0", "Apache-2.0" ]
EladGabay/pulumi-oci
sdk/dotnet/Database/BackupDestination.cs
17,807
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Script : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
15.315789
52
0.618557
[ "MIT" ]
Drakelia/cercleprojet2019
G4Enigme VR/Assets/Script.cs
293
C#
using System; using System.Globalization; using System.Linq; using System.Reflection; namespace EZOper.TechTester.JWTOAuthWebSI3.Areas.Help { internal static class ModelNameHelper { // Modify this to provide custom model name mapping. public static string GetModelName(Type type) { ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>(); if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) { return modelNameAttribute.Name; } string modelName = type.Name; if (type.IsGenericType) { // Format the generic type name to something like: GenericOfAgurment1AndArgument2 Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.Name; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); } return modelName; } } }
39.972222
140
0.635163
[ "MIT" ]
erikzhouxin/CSharpSolution
TechTester/JWTOAuthWebSI3/Areas/Help/ModelDescriptions/ModelNameHelper.cs
1,439
C#
using Automation.Framework.Pages; using Automation.Tests.Common; using FluentAssertions; using NUnit.Framework; namespace Automation.Tests.Google { public class Home : BaseUI { private GoogleHomePage _googleHomePage; [SetUp] public override void SetUp() { base.SetUp(); _googleHomePage = new GoogleHomePage(Driver); Driver.BrowseTo("https://www.google.co.uk/"); } //[SetUp] //public void SetUp() //{ // Driver.BrowseTo("https://www.google.co.uk/"); //} [Test] public void SelectGoogleApps() { _googleHomePage.SelectGoogleApps(); } [Test] public void NavigateToCalendarApp() { _googleHomePage.GoToCalendarViaGoogleApps(); Driver.Title.Should().Contain("Calendar"); } [Test] public void NavigateToContactsApp() { _googleHomePage.GoToContactsViaGoogleApps(); Driver.Title.Should().Contain("Sign in - Google Accounts"); } [Test] public void NavigateToDriveApp() { _googleHomePage.GoToDriveViaGoogleApps(); Driver.Title.Should().Contain("Drive"); } [Test] public void NavigateToGmailApp() { _googleHomePage.GoToGmailViaGoogleApps(); Driver.Title.Should().Contain("Gmail"); } [Test] public void NavigateToGooglePlusApp() { _googleHomePage.GoToGooglePlusViaGoogleApps(); Driver.Title.Should().Contain("+"); } [Test] public void NavigateToMapApp() { _googleHomePage.GoToMapViaGoogleApps(); Driver.Title.Should().Contain("Maps"); } [Test] public void NavigateToNewsApp() { _googleHomePage.GoToNewsViaGoogleApps(); Driver.Title.Should().Contain("News"); } [Test] public void NavigateToPhotosApp() { _googleHomePage.GoToPhotosViaGoogleApps(); Driver.Title.Should().Contain("Photos"); } [Test] public void NavigateToPlayApp() { _googleHomePage.GoToPlayViaGoogleApps(); Driver.Title.Should().Contain("Play"); } [Test] public void NavigateToSearchApp() { _googleHomePage.GoToSearchViaGoogleApps(); Driver.Title.Should().Contain("Google"); } [Test] public void NavigateToTranslateApp() { _googleHomePage.GoToTranslateViaGoogleApps(); Driver.Title.Should().Contain("Translate"); } [Test] public void NavigateToYoutubeApp() { _googleHomePage.GoToYoutubeViaGoogleApps(); Driver.Title.Should().Contain("YouTbe"); } } }
25.333333
71
0.548246
[ "MIT" ]
SHall21/SeleniumDemo_TestYork
Automation.Tests/Google/Home.cs
2,966
C#
using Fortnox.SDK.Serialization; using Newtonsoft.Json; // ReSharper disable UnusedMember.Global namespace Fortnox.SDK.Entities { /// <remarks/> [Entity(SingularName = "SalaryTransaction", PluralName = "SalaryTransactions")] public class SalaryTransactionSubset : SalaryTransaction { ///<summary> Direct URL to the record </summary> [ReadOnly] [JsonProperty("@url")] public string Url { get; private set; } } }
25.833333
83
0.675269
[ "Unlicense", "MIT" ]
LukasLonnroth/csharp-api-sdk
FortnoxSDK/Entities.Subsets/SalaryTransactionSubset.cs
465
C#
using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Orleans; using Orleans.Runtime; using Tester.StorageFacet.Abstractions; using Orleans.Hosting; namespace Tester.StorageFacet.Implementations { public class TableExampleStorage<TState> : IExampleStorage<TState>, ILifecycleParticipant<IGrainLifecycle> { private IExampleStorageConfig config; private bool activateCalled; public string Name => this.config.StateName; public TState State { get; set; } public Task Save() { return Task.CompletedTask; } public string GetExtendedInfo() { return $"Table:{this.Name}-ActivateCalled:{this.activateCalled}, StateType:{typeof(TState).Name}"; } public Task LoadState(CancellationToken ct) { this.activateCalled = true; return Task.CompletedTask; } public void Participate(IGrainLifecycle lifecycle) { lifecycle.Subscribe(OptionFormattingUtilities.Name<TableExampleStorage<TState>>(this.Name), GrainLifecycleStage.SetupState, LoadState); } public void Configure(IExampleStorageConfig cfg) { this.config = cfg; } } public class TableExampleStorageFactory : IExampleStorageFactory { private readonly IGrainActivationContext context; public TableExampleStorageFactory(IGrainActivationContext context) { this.context = context; } public IExampleStorage<TState> Create<TState>(IExampleStorageConfig config) { var storage = this.context.ActivationServices.GetRequiredService<TableExampleStorage<TState>>(); storage.Configure(config); storage.Participate(this.context.ObservableLifecycle); return storage; } } public static class TableExampleStorageExtensions { public static void UseTableExampleStorage(this ISiloHostBuilder builder, string name) { builder.ConfigureServices(services => { services.AddTransientNamedService<IExampleStorageFactory, TableExampleStorageFactory>(name); services.AddTransient(typeof(TableExampleStorage<>)); }); } } }
31.52
147
0.661591
[ "MIT" ]
1007lu/orleans
test/Tester/StorageFacet/Feature.Implementations/TableExampleStorage.cs
2,366
C#