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.Globalization; using System.IO; using System.Web; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Routing; using Subtext.Framework.Syndication; using Subtext.Framework.Syndication.Admin; using UnitTests.Subtext.Framework.Util; namespace UnitTests.Subtext.Framework.Syndication.Admin { [TestClass] public class ModeratedCommentRssWriterTests : SyndicationTestBase { /// <summary> /// Tests that a valid feed is produced even if a post has no comments. /// </summary> [DatabaseIntegrationTestMethod] public void CommentRssWriterProducesValidEmptyFeed() { UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "blog"); var blogInfo = new Blog(); blogInfo.Host = "localhost"; blogInfo.Subfolder = "blog"; blogInfo.Email = "Subtext@example.com"; blogInfo.RFC3229DeltaEncodingEnabled = true; blogInfo.Title = "My Blog Rulz"; blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId; HttpContext.Current.Items.Add("BlogInfo-", blogInfo); var entry = new Entry(PostType.None); entry.AllowComments = true; entry.Title = "Comments requiring your approval."; entry.Body = "The following items are waiting approval."; entry.PostType = PostType.None; var urlHelper = new Mock<BlogUrlHelper>(); urlHelper.Setup(url => url.ImageUrl(It.IsAny<string>())).Returns("/images/RSS2Image.gif"); urlHelper.Setup(url => url.GetVirtualPath(It.IsAny<string>(), It.IsAny<object>())).Returns( "/blog/Admin/Feedback.aspx?status=2"); urlHelper.Setup(url => url.EntryUrl(It.IsAny<Entry>())).Returns("/blog/Admin/Feedback.aspx?status=2"); urlHelper.Setup(url => url.AdminUrl(It.IsAny<string>(), It.IsAny<object>())).Returns( "/blog/Admin/Feedback.aspx?status=2"); var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(blogInfo); subtextContext.Setup(c => c.UrlHelper).Returns(urlHelper.Object); var writer = new ModeratedCommentRssWriter(new StringWriter(), new List<FeedbackItem>(), entry, subtextContext.Object); string expected = @"<rss version=""2.0"" " + @"xmlns:dc=""http://purl.org/dc/elements/1.1/"" " + @"xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" " + @"xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" " + @"xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" " + @"xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" " + @"xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine + indent() + @"<channel>" + Environment.NewLine + indent(2) + @"<title>Comments requiring your approval.</title>" + Environment.NewLine + indent(2) + @"<link>http://localhost/blog/Admin/Feedback.aspx?status=2</link>" + Environment.NewLine + indent(2) + @"<description>The following items are waiting approval.</description>" + Environment.NewLine + indent(2) + @"<language>en-US</language>" + Environment.NewLine + indent(2) + @"<copyright>Subtext Weblog</copyright>" + Environment.NewLine + indent(2) + @"<generator>{0}</generator>" + Environment.NewLine + indent(2) + @"<image>" + Environment.NewLine + indent(3) + @"<title>Comments requiring your approval.</title>" + Environment.NewLine + indent(3) + @"<url>http://localhost/images/RSS2Image.gif</url>" + Environment.NewLine + indent(3) + @"<link>http://localhost/blog/Admin/Feedback.aspx?status=2</link>" + Environment.NewLine + indent(3) + @"<width>77</width>" + Environment.NewLine + indent(3) + @"<height>60</height>" + Environment.NewLine + indent(2) + @"</image>" + Environment.NewLine + indent(1) + @"</channel>" + Environment.NewLine + @"</rss>"; expected = string.Format(expected, VersionInfo.VersionDisplayText); Assert.AreEqual(expected, writer.Xml); } /// <summary> /// Tests that a valid feed is produced even if a post has no comments. /// </summary> [DatabaseIntegrationTestMethod] public void Xml_WithOneCommentNeedingModeration_ProducesValidRSSFeedWithTheOneComment() { // Arrange UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "", "Subtext.Web"); var blogInfo = new Blog(); blogInfo.Host = "localhost"; blogInfo.Email = "Subtext@example.com"; blogInfo.RFC3229DeltaEncodingEnabled = true; blogInfo.Title = "My Blog Rulz"; blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId; HttpContext.Current.Items.Add("BlogInfo-", blogInfo); var rootEntry = new Entry(PostType.None); rootEntry.AllowComments = true; rootEntry.Title = "Comments requiring your approval."; rootEntry.Body = "The following items are waiting approval."; rootEntry.PostType = PostType.None; Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication(blogInfo, "haacked", "title of the post", "Body of the post."); entry.EntryName = "titleofthepost"; entry.DateCreatedUtc = entry.DatePublishedUtc = entry.DateModifiedUtc = DateTime.ParseExact("2006/02/01 08:00", "yyyy/MM/dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime(); entry.Id = 1001; var comment = new FeedbackItem(FeedbackType.Comment); comment.Id = 1002; comment.DateCreatedUtc = comment.DateModifiedUtc = DateTime.ParseExact("2006/02/02 07:00", "yyyy/MM/dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime(); comment.Title = "re: titleofthepost"; comment.ParentEntryName = entry.EntryName; comment.ParentDateCreatedUtc = entry.DateCreatedUtc; comment.Body = "<strong>I rule!</strong>"; comment.Author = "Jane Schmane"; comment.Email = "jane@example.com"; comment.EntryId = entry.Id; comment.Status = FeedbackStatusFlag.NeedsModeration; var comments = new List<FeedbackItem>(); comments.Add(comment); var urlHelper = new Mock<BlogUrlHelper>(); urlHelper.Setup(url => url.EntryUrl(It.IsAny<Entry>())).Returns( "/Subtext.Web/archive/2006/02/01/titleofthepost.aspx"); urlHelper.Setup(url => url.FeedbackUrl(It.IsAny<FeedbackItem>())).Returns( "/Subtext.Web/archive/2006/02/01/titleofthepost.aspx#1002"); urlHelper.Setup(url => url.ImageUrl(It.IsAny<string>())).Returns("/Subtext.Web/images/RSS2Image.gif"); urlHelper.Setup(url => url.AdminUrl(It.IsAny<string>(), It.IsAny<object>())).Returns( "/Subtext.Web/Admin/Feedback.aspx?status=2"); var context = new Mock<ISubtextContext>(); context.Setup(c => c.UrlHelper).Returns(urlHelper.Object); context.Setup(c => c.Blog).Returns(blogInfo); var writer = new ModeratedCommentRssWriter(new StringWriter(), comments, rootEntry, context.Object); string expected = @"<rss version=""2.0"" " + @"xmlns:dc=""http://purl.org/dc/elements/1.1/"" " + @"xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" " + @"xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" " + @"xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" " + @"xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" " + @"xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine + indent() + @"<channel>" + Environment.NewLine + indent(2) + @"<title>Comments requiring your approval.</title>" + Environment.NewLine + indent(2) + @"<link>http://localhost/Subtext.Web/Admin/Feedback.aspx?status=2</link>" + Environment.NewLine + indent(2) + @"<description>The following items are waiting approval.</description>" + Environment.NewLine + indent(2) + @"<language>en-US</language>" + Environment.NewLine + indent(2) + @"<copyright>Subtext Weblog</copyright>" + Environment.NewLine + indent(2) + @"<generator>{0}</generator>" + Environment.NewLine + indent(2) + @"<image>" + Environment.NewLine + indent(3) + @"<title>Comments requiring your approval.</title>" + Environment.NewLine + indent(3) + @"<url>http://localhost/Subtext.Web/images/RSS2Image.gif</url>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/archive/2006/02/01/titleofthepost.aspx</link>" + Environment.NewLine + indent(3) + @"<width>77</width>" + Environment.NewLine + indent(3) + @"<height>60</height>" + Environment.NewLine + indent(2) + @"</image>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>re: titleofthepost</title>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/archive/2006/02/01/titleofthepost.aspx#1002</link>" + Environment.NewLine + indent(3) + @"<description>&lt;strong&gt;I rule!&lt;/strong&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Jane Schmane</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/archive/2006/02/01/titleofthepost.aspx#1002</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Thu, 02 Feb 2006 07:00:00 GMT</pubDate>" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent() + @"</channel>" + Environment.NewLine + @"</rss>"; expected = string.Format(expected, VersionInfo.VersionDisplayText); // Act string rss = writer.Xml; // Assert UnitTestHelper.AssertStringsEqualCharacterByCharacter(expected, rss); //Assert.AreEqual(expected, writer.Xml); } [TestMethod] public void Ctor_WithNullEntryCollection_ThrowsArgumentNullException() { UnitTestHelper.AssertThrowsArgumentNullException(() => new CommentRssWriter(new StringWriter(), null, new Entry(PostType.BlogPost), new Mock<ISubtextContext>().Object) ); } [TestMethod] public void Ctor_WithNullEntry_ThrowsArgumentNullException() { UnitTestHelper.AssertThrowsArgumentNullException(() => new CommentRssWriter(new StringWriter(), new List<FeedbackItem>(), null, new Mock<ISubtextContext>().Object) ); } } }
57.833333
182
0.546538
[ "MIT" ]
technology-toolbox/Subtext
src/UnitTests.Subtext/Framework/Syndication/Admin/ModeratedCommentRssWriterTests.cs
12,839
C#
using System; namespace WebAppUSingDocker.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
19.545455
70
0.67907
[ "MIT" ]
CNinnovation/html5jan2019
Day4/WebAppUSingDocker/WebAppUSingDocker/Models/ErrorViewModel.cs
215
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using JetBrains.Annotations; // ReSharper disable NonReadonlyMemberInGetHashCode namespace JsonApiDotNetCore.Resources.Annotations { /// <summary> /// Used to expose a property on a resource class as a JSON:API to-many relationship (https://jsonapi.org/format/#document-resource-object-relationships) /// through a many-to-many join relationship. /// </summary> /// <example> /// In the following example, we expose a relationship named "tags" /// through the navigation property `ArticleTags`. /// The `Tags` property is decorated with `NotMapped` so that EF does not try /// to map this to a database relationship. /// <code><![CDATA[ /// public sealed class Article : Identifiable /// { /// [NotMapped] /// [HasManyThrough(nameof(ArticleTags), PublicName = "tags")] /// public ISet<Tag> Tags { get; set; } /// public ISet<ArticleTag> ArticleTags { get; set; } /// } /// /// public class Tag : Identifiable /// { /// [Attr] /// public string Name { get; set; } /// } /// /// public sealed class ArticleTag /// { /// public int ArticleId { get; set; } /// public Article Article { get; set; } /// /// public int TagId { get; set; } /// public Tag Tag { get; set; } /// } /// ]]></code> /// </example> [PublicAPI] [AttributeUsage(AttributeTargets.Property)] public sealed class HasManyThroughAttribute : HasManyAttribute { /// <summary> /// The name of the join property on the parent resource. /// In the example described above, this would be "ArticleTags". /// </summary> public string ThroughPropertyName { get; } /// <summary> /// The join type. /// In the example described above, this would be `ArticleTag`. /// </summary> public Type ThroughType { get; internal set; } /// <summary> /// The navigation property back to the parent resource from the through type. /// In the example described above, this would point to the `Article.ArticleTags.Article` property. /// </summary> public PropertyInfo LeftProperty { get; internal set; } /// <summary> /// The ID property back to the parent resource from the through type. /// In the example described above, this would point to the `Article.ArticleTags.ArticleId` property. /// </summary> public PropertyInfo LeftIdProperty { get; internal set; } /// <summary> /// The navigation property to the related resource from the through type. /// In the example described above, this would point to the `Article.ArticleTags.Tag` property. /// </summary> public PropertyInfo RightProperty { get; internal set; } /// <summary> /// The ID property to the related resource from the through type. /// In the example described above, this would point to the `Article.ArticleTags.TagId` property. /// </summary> public PropertyInfo RightIdProperty { get; internal set; } /// <summary> /// The join resource property on the parent resource. /// In the example described above, this would point to the `Article.ArticleTags` property. /// </summary> public PropertyInfo ThroughProperty { get; internal set; } /// <summary> /// The internal navigation property path to the related resource. /// In the example described above, this would contain "ArticleTags.Tag". /// </summary> public override string RelationshipPath => $"{ThroughProperty.Name}.{RightProperty.Name}"; /// <summary> /// Required for a self-referencing many-to-many relationship. /// Contains the name of the property back to the parent resource from the through type. /// </summary> public string LeftPropertyName { get; set; } /// <summary> /// Required for a self-referencing many-to-many relationship. /// Contains the name of the property to the related resource from the through type. /// </summary> public string RightPropertyName { get; set; } /// <summary> /// Optional. Can be used to indicate a non-default name for the ID property back to the parent resource from the through type. /// Defaults to the name of <see cref="LeftProperty"/> suffixed with "Id". /// In the example described above, this would be "ArticleId". /// </summary> public string LeftIdPropertyName { get; set; } /// <summary> /// Optional. Can be used to indicate a non-default name for the ID property to the related resource from the through type. /// Defaults to the name of <see cref="RightProperty"/> suffixed with "Id". /// In the example described above, this would be "TagId". /// </summary> public string RightIdPropertyName { get; set; } /// <summary> /// Creates a HasMany relationship through a many-to-many join relationship. /// </summary> /// <param name="throughPropertyName">The name of the navigation property that will be used to access the join relationship.</param> public HasManyThroughAttribute(string throughPropertyName) { ArgumentGuard.NotNull(throughPropertyName, nameof(throughPropertyName)); ThroughPropertyName = throughPropertyName; } /// <summary> /// Traverses through the provided resource and returns the value of the relationship on the other side of the through type. /// In the example described above, this would be the value of "Articles.ArticleTags.Tag". /// </summary> public override object GetValue(object resource) { ArgumentGuard.NotNull(resource, nameof(resource)); var throughEntity = ThroughProperty.GetValue(resource); if (throughEntity == null) { return null; } IEnumerable<object> rightResources = ((IEnumerable) throughEntity) .Cast<object>() .Select(rightResource => RightProperty.GetValue(rightResource)); return TypeHelper.CopyToTypedCollection(rightResources, Property.PropertyType); } /// <summary> /// Traverses through the provided resource and sets the value of the relationship on the other side of the through type. /// In the example described above, this would be the value of "Articles.ArticleTags.Tag". /// </summary> public override void SetValue(object resource, object newValue) { ArgumentGuard.NotNull(resource, nameof(resource)); base.SetValue(resource, newValue); if (newValue == null) { ThroughProperty.SetValue(resource, null); } else { List<object> throughResources = new List<object>(); foreach (IIdentifiable rightResource in (IEnumerable)newValue) { var throughEntity = TypeHelper.CreateInstance(ThroughType); LeftProperty.SetValue(throughEntity, resource); RightProperty.SetValue(throughEntity, rightResource); throughResources.Add(throughEntity); } var typedCollection = TypeHelper.CopyToTypedCollection(throughResources, ThroughProperty.PropertyType); ThroughProperty.SetValue(resource, typedCollection); } } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } if (obj is null || GetType() != obj.GetType()) { return false; } var other = (HasManyThroughAttribute) obj; return ThroughPropertyName == other.ThroughPropertyName && ThroughType == other.ThroughType && LeftProperty == other.LeftProperty && LeftIdProperty == other.LeftIdProperty && RightProperty == other.RightProperty && RightIdProperty == other.RightIdProperty && ThroughProperty == other.ThroughProperty && base.Equals(other); } public override int GetHashCode() { return HashCode.Combine(ThroughPropertyName, ThroughType, LeftProperty, LeftIdProperty, RightProperty, RightIdProperty, ThroughProperty, base.GetHashCode()); } } }
41.182243
157
0.612618
[ "MIT" ]
jlits/JsonApiDotNetCore
src/JsonApiDotNetCore/Resources/Annotations/HasManyThroughAttribute.cs
8,813
C#
#if !DNXCORE50 using Discord.API; using RestSharp; using System; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Discord.Net.Rest { internal sealed class SharpRestEngine : IRestEngine { private readonly DiscordAPIClientConfig _config; private readonly RestSharp.RestClient _client; public SharpRestEngine(DiscordAPIClientConfig config) { _config = config; _client = new RestSharp.RestClient(Endpoints.BaseApi) { PreAuthenticate = false, ReadWriteTimeout = _config.APITimeout, UserAgent = _config.UserAgent }; if (_config.ProxyUrl != null) _client.Proxy = new WebProxy(_config.ProxyUrl, true, new string[0], _config.ProxyCredentials); else _client.Proxy = null; _client.RemoveDefaultParameter("Accept"); _client.AddDefaultHeader("accept", "*/*"); _client.AddDefaultHeader("accept-encoding", "gzip,deflate"); } public void SetToken(string token) { _client.RemoveDefaultParameter("authorization"); if (token != null) _client.AddDefaultHeader("authorization", token); } public Task<string> Send(HttpMethod method, string path, string json, CancellationToken cancelToken) { var request = new RestRequest(path, GetMethod(method)); request.AddParameter("application/json", json, ParameterType.RequestBody); return Send(request, cancelToken); } public Task<string> SendFile(HttpMethod method, string path, string filePath, CancellationToken cancelToken) { var request = new RestRequest(path, Method.POST); request.AddFile("file", filePath); return Send(request, cancelToken); } private async Task<string> Send(RestRequest request, CancellationToken cancelToken) { int retryCount = 0; while (true) { var response = await _client.ExecuteTaskAsync(request, cancelToken).ConfigureAwait(false); int statusCode = (int)response.StatusCode; if (statusCode == 0) //Internal Error { if (response.ErrorException.HResult == -2146233079 && retryCount++ < 5) //The request was aborted: Could not create SSL/TLS secure channel. continue; //Seems to work if we immediately retry throw response.ErrorException; } if (statusCode < 200 || statusCode >= 300) //2xx = Success throw new HttpException(response.StatusCode); return response.Content; } } private Method GetMethod(HttpMethod method) { switch (method.Method) { case "DELETE": return Method.DELETE; case "GET": return Method.GET; case "PATCH": return Method.PATCH; case "POST": return Method.POST; case "PUT": return Method.PUT; default: throw new InvalidOperationException($"Unknown HttpMethod: {method}"); } } } } #endif
31.942529
144
0.706729
[ "MIT" ]
jhgg/Discord.Net
src/Discord.Net/Net/Rest/SharpRestEngine.cs
2,781
C#
using System; using System.Collections.Generic; using System.Linq; namespace _02.OddOccurrences { class Program { static void Main(string[] args) //version 2.0 { string[] words = Console.ReadLine() .ToLower() .Split() .ToArray(); Dictionary<string, int> filteredWords = new Dictionary<string, int>(); foreach (var word in words) { if (!filteredWords.ContainsKey(word)) { filteredWords[word] = 0; } filteredWords[word]++; } foreach (var word in filteredWords) { if (word.Value % 2 != 0) { Console.Write($"{word.Key} "); } } } //static void Main(string[] args) //version 1.0 //{ // string[] words = Console.ReadLine().ToLower().Split().ToArray(); // Dictionary<string, int> counts = new Dictionary<string, int>(); // foreach (var word in words) // { // if (!counts.ContainsKey(word)) // { // counts[word] = 0; // } // counts[word]++; // } // foreach (var count in counts) // { // if(count.Value % 2 != 0) // { // Console.Write($"{count.Key} "); // } // } //} } } //2. Odd Occurrences //Write a program that extracts all elements from a given sequence of words that are present in it an odd number of //times(case-insensitive). // Words are given on a single line, space separated. // Print the result elements in lowercase, in their order of appearance. //Examples //Input | Output // | //Java C# PHP PHP JAVA C java | java c# c //3 5 5 hi pi HO Hi 5 ho 3 hi pi | 5 hi //a a A SQL xx a xx a A a XX c | a sql xx c
30.126761
115
0.436653
[ "MIT" ]
FanyaKk/CSharpUniProjects
C#Fundamentals January 2020/AssociativeArrays/02.OddOccurrences/Program.cs
2,145
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; namespace Microsoft.Toolkit.Services { /// <summary> /// This class offers general purpose methods. /// </summary> internal static class ExtensionMethods { /// <summary> /// Converts between enumeration value and string value. /// </summary> /// <param name="value">Enumeration.</param> /// <returns>Returns string value.</returns> private static string GetStringValue(Enum value) { string output = null; Type type = value.GetType(); FieldInfo fi = type.GetRuntimeField(value.ToString()); Parsers.Core.StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(Parsers.Core.StringValueAttribute), false) as Parsers.Core.StringValueAttribute[]; if (attrs != null && attrs.Length > 0) { output = attrs[0].Value; } return output; } } }
33.714286
168
0.620339
[ "MIT" ]
14632791/WindowsCommunityToolkit
Microsoft.Toolkit.Services/Core/ExtensionMethods.cs
1,180
C#
using System; namespace WindowsGrep.Common { public class ConsoleItem { #region Properties.. #region BackgroundColor public ConsoleColor BackgroundColor { get; set; } = Console.BackgroundColor; #endregion BackgroundColor #region ForegroundColor public ConsoleColor ForegroundColor { get; set; } = Console.ForegroundColor; #endregion ForegroundColor #region Value public string Value { get; set; } #endregion Value #endregion Properties.. #region Constructors.. #endregion Constructors.. #region Methods.. #endregion Methods.. } }
24
84
0.627976
[ "MIT" ]
sLill/Windows-BudgetGrep
WindowsGrep/WindowsGrep.Common/ConsoleItem.cs
674
C#
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.IO; using Amazon.AWSSupport.Model; using Amazon.Runtime.Internal.Transform; namespace Amazon.AWSSupport.Model.Internal.MarshallTransformations { /// <summary> /// TrustedAdvisorResourcesSummaryUnmarshaller /// </summary> internal class TrustedAdvisorResourcesSummaryUnmarshaller : IUnmarshaller<TrustedAdvisorResourcesSummary, XmlUnmarshallerContext>, IUnmarshaller<TrustedAdvisorResourcesSummary, JsonUnmarshallerContext> { TrustedAdvisorResourcesSummary IUnmarshaller<TrustedAdvisorResourcesSummary, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } public TrustedAdvisorResourcesSummary Unmarshall(JsonUnmarshallerContext context) { TrustedAdvisorResourcesSummary trustedAdvisorResourcesSummary = new TrustedAdvisorResourcesSummary(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; while (context.Read()) { if ((context.IsKey) && (context.CurrentDepth == targetDepth)) { context.Read(); context.Read(); if (context.TestExpression("ResourcesProcessed", targetDepth)) { trustedAdvisorResourcesSummary.ResourcesProcessed = LongUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ResourcesFlagged", targetDepth)) { trustedAdvisorResourcesSummary.ResourcesFlagged = LongUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ResourcesIgnored", targetDepth)) { trustedAdvisorResourcesSummary.ResourcesIgnored = LongUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ResourcesSuppressed", targetDepth)) { trustedAdvisorResourcesSummary.ResourcesSuppressed = LongUnmarshaller.GetInstance().Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth <= originalDepth) { return trustedAdvisorResourcesSummary; } } return trustedAdvisorResourcesSummary; } private static TrustedAdvisorResourcesSummaryUnmarshaller instance; public static TrustedAdvisorResourcesSummaryUnmarshaller GetInstance() { if (instance == null) instance = new TrustedAdvisorResourcesSummaryUnmarshaller(); return instance; } } }
38.967033
207
0.638748
[ "Apache-2.0" ]
mahanthbeeraka/dataservices-sdk-dotnet
AWSSDK/Amazon.AWSSupport/Model/Internal/MarshallTransformations/TrustedAdvisorResourcesSummaryUnmarshaller.cs
3,546
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace LoRaWan.NetworkServer { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using LoRaTools; using LoRaTools.ADR; using LoRaTools.LoRaMessage; using LoRaTools.LoRaPhysical; using LoRaTools.Utils; using LoRaWan.NetworkServer.ADR; using LoRaWan.Shared; using Microsoft.Azure.Devices.Client; using Microsoft.Azure.Devices.Client.Transport.Mqtt; using Microsoft.Azure.Devices.Shared; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using Newtonsoft.Json; /// <summary> /// Defines udp Server communicating with packet forwarder /// </summary> public class UdpServer : IDisposable, IPacketForwarder { const int PORT = 1680; private readonly NetworkServerConfiguration configuration; private readonly MessageDispatcher messageDispatcher; private readonly LoRaDeviceAPIServiceBase loRaDeviceAPIService; private readonly ILoRaDeviceRegistry loRaDeviceRegistry; readonly SemaphoreSlim randomLock = new SemaphoreSlim(1); readonly Random random = new Random(); private IClassCDeviceMessageSender classCMessageSender; private ModuleClient ioTHubModuleClient; private volatile int pullAckRemoteLoRaAggregatorPort = 0; private volatile string pullAckRemoteLoRaAddress = null; UdpClient udpClient; private async Task<byte[]> GetTokenAsync() { try { await this.randomLock.WaitAsync(); byte[] token = new byte[2]; this.random.NextBytes(token); return token; } finally { this.randomLock.Release(); } } // Creates a new instance of UdpServer public static UdpServer Create() { var configuration = NetworkServerConfiguration.CreateFromEnviromentVariables(); var loRaDeviceAPIService = new LoRaDeviceAPIService(configuration, new ServiceFacadeHttpClientProvider(configuration, ApiVersion.LatestVersion)); var frameCounterStrategyProvider = new LoRaDeviceFrameCounterUpdateStrategyProvider(configuration.GatewayID, loRaDeviceAPIService); var deduplicationStrategyFactory = new DeduplicationStrategyFactory(loRaDeviceAPIService); var adrStrategyProvider = new LoRaADRStrategyProvider(); var cache = new MemoryCache(new MemoryCacheOptions()); var dataHandlerImplementation = new DefaultLoRaDataRequestHandler(configuration, frameCounterStrategyProvider, new LoRaPayloadDecoder(), deduplicationStrategyFactory, adrStrategyProvider, new LoRAADRManagerFactory(loRaDeviceAPIService), new FunctionBundlerProvider(loRaDeviceAPIService)); var connectionManager = new LoRaDeviceClientConnectionManager(cache); var loRaDeviceFactory = new LoRaDeviceFactory(configuration, dataHandlerImplementation, connectionManager); var loRaDeviceRegistry = new LoRaDeviceRegistry(configuration, cache, loRaDeviceAPIService, loRaDeviceFactory); var messageDispatcher = new MessageDispatcher(configuration, loRaDeviceRegistry, frameCounterStrategyProvider); var udpServer = new UdpServer(configuration, messageDispatcher, loRaDeviceAPIService, loRaDeviceRegistry); // TODO: review dependencies var classCMessageSender = new DefaultClassCDevicesMessageSender(configuration, loRaDeviceRegistry, udpServer, frameCounterStrategyProvider); dataHandlerImplementation.SetClassCMessageSender(classCMessageSender); udpServer.SetClassCMessageSender(classCMessageSender); return udpServer; } // Creates a new instance of UdpServer public UdpServer( NetworkServerConfiguration configuration, MessageDispatcher messageDispatcher, LoRaDeviceAPIServiceBase loRaDeviceAPIService, ILoRaDeviceRegistry loRaDeviceRegistry) { this.configuration = configuration; this.messageDispatcher = messageDispatcher; this.loRaDeviceAPIService = loRaDeviceAPIService; this.loRaDeviceRegistry = loRaDeviceRegistry; } public async Task RunServer() { Logger.LogAlways("Starting LoRaWAN Server..."); await this.InitCallBack(); await this.RunUdpListener(); } async Task UdpSendMessageAsync(byte[] messageToSend, string remoteLoRaAggregatorIp, int remoteLoRaAggregatorPort) { if (messageToSend != null && messageToSend.Length != 0) { await this.udpClient.SendAsync(messageToSend, messageToSend.Length, remoteLoRaAggregatorIp, remoteLoRaAggregatorPort); } } async Task RunUdpListener() { IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, PORT); this.udpClient = new UdpClient(endPoint); Logger.LogAlways($"LoRaWAN server started on port {PORT}"); while (true) { UdpReceiveResult receivedResults = await this.udpClient.ReceiveAsync(); var startTimeProcessing = DateTime.UtcNow; switch (PhysicalPayload.GetIdentifierFromPayload(receivedResults.Buffer)) { // In this case we have a keep-alive PULL_DATA packet we don't need to start the engine and can return immediately a response to the challenge case PhysicalIdentifier.PULL_DATA: if (this.pullAckRemoteLoRaAggregatorPort == 0) { this.pullAckRemoteLoRaAggregatorPort = receivedResults.RemoteEndPoint.Port; this.pullAckRemoteLoRaAddress = receivedResults.RemoteEndPoint.Address.ToString(); } this.SendAcknowledgementMessage(receivedResults, (int)PhysicalIdentifier.PULL_ACK, receivedResults.RemoteEndPoint); break; // This is a PUSH_DATA (upstream message). case PhysicalIdentifier.PUSH_DATA: this.SendAcknowledgementMessage(receivedResults, (int)PhysicalIdentifier.PUSH_ACK, receivedResults.RemoteEndPoint); this.DispatchMessages(receivedResults.Buffer, startTimeProcessing); break; // This is a ack to a transmission we did previously case PhysicalIdentifier.TX_ACK: if (receivedResults.Buffer.Length == 12) { Logger.Log( "UDP", $"packet with id {ConversionHelper.ByteArrayToString(receivedResults.Buffer.RangeSubset(1, 2))} successfully transmitted by the aggregator", LogLevel.Debug); } else { var logMsg = string.Format( "packet with id {0} had a problem to be transmitted over the air :{1}", receivedResults.Buffer.Length > 2 ? ConversionHelper.ByteArrayToString(receivedResults.Buffer.RangeSubset(1, 2)) : string.Empty, receivedResults.Buffer.Length > 12 ? Encoding.UTF8.GetString(receivedResults.Buffer.RangeSubset(12, receivedResults.Buffer.Length - 12)) : string.Empty); Logger.Log("UDP", logMsg, LogLevel.Error); } break; default: Logger.Log("UDP", "unknown packet type or length being received", LogLevel.Error); break; } } } private void DispatchMessages(byte[] buffer, DateTime startTimeProcessing) { try { List<Rxpk> messageRxpks = Rxpk.CreateRxpk(buffer); if (messageRxpks != null) { foreach (var rxpk in messageRxpks) { this.messageDispatcher.DispatchRequest(new LoRaRequest(rxpk, this, startTimeProcessing)); } } } catch (Exception ex) { Logger.Log("UDP", $"failed to dispatch messages: {ex.Message}", LogLevel.Error); } } private void SendAcknowledgementMessage(UdpReceiveResult receivedResults, byte messageType, IPEndPoint remoteEndpoint) { byte[] response = new byte[4] { receivedResults.Buffer[0], receivedResults.Buffer[1], receivedResults.Buffer[2], messageType }; _ = this.UdpSendMessageAsync(response, remoteEndpoint.Address.ToString(), remoteEndpoint.Port); } async Task InitCallBack() { try { ITransportSettings transportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { transportSettings }; // if running as Edge module if (this.configuration.RunningAsIoTEdgeModule) { this.ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); Logger.Init(new LoggerConfiguration { ModuleClient = this.ioTHubModuleClient, LogLevel = LoggerConfiguration.InitLogLevel(this.configuration.LogLevel), LogToConsole = this.configuration.LogToConsole, LogToHub = this.configuration.LogToHub, LogToUdp = this.configuration.LogToUdp, LogToUdpPort = this.configuration.LogToUdpPort, LogToUdpAddress = this.configuration.LogToUdpAddress, GatewayId = this.configuration.GatewayID }); if (this.configuration.IoTEdgeTimeout > 0) { this.ioTHubModuleClient.OperationTimeoutInMilliseconds = this.configuration.IoTEdgeTimeout; Logger.Log($"Changing timeout to {this.ioTHubModuleClient.OperationTimeoutInMilliseconds} ms", LogLevel.Debug); } Logger.Log("Getting properties from module twin...", LogLevel.Information); var moduleTwin = await this.ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; try { this.loRaDeviceAPIService.SetURL(moduleTwinCollection["FacadeServerUrl"].Value as string); Logger.LogAlways($"Facade function url: {this.loRaDeviceAPIService.URL}"); } catch (ArgumentOutOfRangeException e) { Logger.Log("Module twin FacadeServerUrl property does not exist", LogLevel.Error); throw e; } try { this.loRaDeviceAPIService.SetAuthCode(moduleTwinCollection["FacadeAuthCode"].Value as string); } catch (ArgumentOutOfRangeException e) { Logger.Log("Module twin FacadeAuthCode does not exist", LogLevel.Error); throw e; } await this.ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(this.OnDesiredPropertiesUpdate, null); await this.ioTHubModuleClient.SetMethodDefaultHandlerAsync(this.OnDirectMethodCalled, null); } // running as non edge module for test and debugging else { Logger.Init(new LoggerConfiguration { ModuleClient = null, LogLevel = LoggerConfiguration.InitLogLevel(this.configuration.LogLevel), LogToConsole = this.configuration.LogToConsole, LogToHub = this.configuration.LogToHub, LogToUdp = this.configuration.LogToUdp, LogToUdpPort = this.configuration.LogToUdpPort, LogToUdpAddress = this.configuration.LogToUdpAddress, GatewayId = this.configuration.GatewayID }); } } catch (Exception ex) { Logger.Log($"Initialization failed with error: {ex.Message}", LogLevel.Error); throw ex; } // Report Log level Logger.LogAlways($"Log Level: {(LogLevel)Logger.LoggerLevel}"); } async Task<MethodResponse> OnDirectMethodCalled(MethodRequest methodRequest, object userContext) { if (string.Equals("clearcache", methodRequest.Name, StringComparison.InvariantCultureIgnoreCase)) { return await this.ClearCache(methodRequest, userContext); } else if (string.Equals(Constants.CLOUD_TO_DEVICE_DECODER_ELEMENT_NAME, methodRequest.Name, StringComparison.InvariantCultureIgnoreCase)) { return await this.SendCloudToDeviceMessageAsync(methodRequest); } Logger.Log($"Unknown direct method called: {methodRequest?.Name}", LogLevel.Error); return new MethodResponse(404); } private async Task<MethodResponse> SendCloudToDeviceMessageAsync(MethodRequest methodRequest) { if (this.classCMessageSender == null) { return new MethodResponse((int)HttpStatusCode.NotFound); } var c2d = JsonConvert.DeserializeObject<ReceivedLoRaCloudToDeviceMessage>(methodRequest.DataAsJson); Logger.Log(c2d.DevEUI, $"received cloud to device message from direct method: {methodRequest.DataAsJson}", LogLevel.Debug); CancellationToken cts = CancellationToken.None; if (methodRequest.ResponseTimeout.HasValue) cts = new CancellationTokenSource(methodRequest.ResponseTimeout.Value).Token; if (await this.classCMessageSender.SendAsync(c2d, cts)) { return new MethodResponse((int)HttpStatusCode.OK); } else { return new MethodResponse((int)HttpStatusCode.BadRequest); } } private Task<MethodResponse> ClearCache(MethodRequest methodRequest, object userContext) { this.loRaDeviceRegistry.ResetDeviceCache(); return Task.FromResult(new MethodResponse(200)); } Task OnDesiredPropertiesUpdate(TwinCollection desiredProperties, object userContext) { try { if (desiredProperties.Contains("FacadeServerUrl")) { this.loRaDeviceAPIService.SetURL((string)desiredProperties["FacadeServerUrl"]); } if (desiredProperties.Contains("FacadeAuthCode")) { this.loRaDeviceAPIService.SetAuthCode((string)desiredProperties["FacadeAuthCode"]); } Logger.Log("Desired property changed", LogLevel.Debug); } catch (AggregateException ex) { foreach (Exception exception in ex.InnerExceptions) { Logger.Log($"Error when receiving desired property: {exception}", LogLevel.Error); } } catch (Exception ex) { Logger.Log($"Error when receiving desired property: {ex.Message}", LogLevel.Error); } return Task.CompletedTask; } async Task IPacketForwarder.SendDownstreamAsync(DownlinkPktFwdMessage downstreamMessage) { try { if (downstreamMessage?.Txpk != null) { var jsonMsg = JsonConvert.SerializeObject(downstreamMessage); var messageByte = Encoding.UTF8.GetBytes(jsonMsg); var token = await this.GetTokenAsync(); PhysicalPayload pyld = new PhysicalPayload(token, PhysicalIdentifier.PULL_RESP, messageByte); if (this.pullAckRemoteLoRaAggregatorPort != 0 && !string.IsNullOrEmpty(this.pullAckRemoteLoRaAddress)) { Logger.Log("UDP", $"sending message with ID {ConversionHelper.ByteArrayToString(token)}, to {this.pullAckRemoteLoRaAddress}:{this.pullAckRemoteLoRaAggregatorPort}", LogLevel.Debug); await this.UdpSendMessageAsync(pyld.GetMessage(), this.pullAckRemoteLoRaAddress, this.pullAckRemoteLoRaAggregatorPort); Logger.Log("UDP", $"message sent with ID {ConversionHelper.ByteArrayToString(token)}", LogLevel.Debug); } else { Logger.Log( "UDP", "waiting for first pull_ack message from the packet forwarder. The received message was discarded as the network server is still starting.", LogLevel.Debug); } } } catch (Exception ex) { Logger.Log("UDP", $"error processing the message {ex.Message}, {ex.StackTrace}", LogLevel.Error); } } private void SetClassCMessageSender(DefaultClassCDevicesMessageSender classCMessageSender) => this.classCMessageSender = classCMessageSender; private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!this.disposedValue) { if (disposing) { this.udpClient?.Dispose(); this.udpClient = null; } this.disposedValue = true; } } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } } }
44.615385
300
0.587252
[ "MIT" ]
MaggieSalak/iotedge-lorawan-starterkit
LoRaEngine/modules/LoRaWanNetworkSrvModule/LoRaWan.NetworkServer/UdpServer.cs
19,142
C#
/* $Id*/ /* * Copyright (C) 2016 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Threading.Tasks; using VoipTasks.BackgroundOperations; using Windows.Foundation.Collections; using Windows.Foundation.Metadata; using VoipBackEnd; namespace VoipUI.Helpers { static class EndpointHelper { public static async Task<OperationResult> StartServiceAsync() { if (!ApiInformation.IsApiContractPresent("Windows.ApplicationModel.Calls.CallsVoipContract", 1)) { return OperationResult.Failed; } AppServiceHelper appServiceHelper = new AppServiceHelper(); ValueSet message = new ValueSet(); message[BackgroundOperation.NewBackgroundRequest] = (int)BackgroundRequest.StartService; ValueSet response = await appServiceHelper.SendMessageAsync(message); if (response != null) { return ((OperationResult)(response[BackgroundOperation.Result])); } return OperationResult.Failed; } public static async Task<OperationResult> GetAccountInfo() { if (!ApiInformation.IsApiContractPresent("Windows.ApplicationModel.Calls.CallsVoipContract", 1)) { return OperationResult.Failed; } AppServiceHelper appServiceHelper = new AppServiceHelper(); ValueSet message = new ValueSet(); message[BackgroundOperation.NewBackgroundRequest] = (int)BackgroundRequest.GetAccountInfo; ValueSet response = await appServiceHelper.SendMessageAsync(message); if (response != null) { return ((OperationResult)(response[BackgroundOperation.Result])); } return OperationResult.Failed; } public static async Task<OperationResult> ModifyAccount(String id, String registrar, String proxy, String username, String password) { if (!ApiInformation.IsApiContractPresent("Windows.ApplicationModel.Calls.CallsVoipContract", 1)) { return OperationResult.Failed; } AppServiceHelper appServiceHelper = new AppServiceHelper(); ValueSet message = new ValueSet(); message[ModifyAccountArguments.id.ToString()] = id; message[ModifyAccountArguments.registrar.ToString()] = registrar; message[ModifyAccountArguments.proxy.ToString()] = proxy; message[ModifyAccountArguments.username.ToString()] = username; message[ModifyAccountArguments.password.ToString()] = password; message[BackgroundOperation.NewBackgroundRequest] = (int)BackgroundRequest.ModifyAccount; ValueSet response = await appServiceHelper.SendMessageAsync(message); if (response != null) { return ((OperationResult)(response[BackgroundOperation.Result])); } return OperationResult.Failed; } } }
37.76
140
0.661017
[ "Apache-2.0" ]
lcmftianci/licodeanalysis
pjproject-2.9/pjsip-apps/src/pjsua/winrt/gui/uwp/Voip/Helpers/EndpointHelper.cs
3,778
C#
/* --------------------------------------- * Author: Martin Pane (martintayx@gmail.com) (@tayx94) * Collaborators: Lars Aalbertsen (@Rockylars) * Project: Graphy - Ultimate Stats Monitor * Date: 05-Mar-18 * Studio: Tayx * * This project is released under the MIT license. * Attribution is not required, but it is always welcomed! * -------------------------------------*/ using UnityEngine; using UnityEngine.UI; using System.Collections; namespace Tayx.Graphy.CustomizationScene { [RequireComponent(typeof(Text))] public class UpdateTextWithSliderValue : MonoBehaviour { /* ----- TODO: ---------------------------- * Check if we can seal this class. * Add summaries to the variables. * Add summaries to the functions. * Check if we can remove "using System.Collections;". * Check if we should add "private" to the Unity Callbacks. * --------------------------------------*/ #region Variables -> Serialized Private [SerializeField] private Slider m_slider; #endregion #region Variables -> Private private Text m_text; #endregion #region Methods -> Unity Callbacks void Start() { m_text = GetComponent<Text>(); m_slider.onValueChanged.AddListener(UpdateText); } #endregion #region Methods -> Private private void UpdateText(float value) { m_text.text = value.ToString(); } #endregion } }
25.774194
68
0.540676
[ "MIT" ]
rawstacktech/unity-lighting-experiments
Assets/Plugins/Graphy/Scene/Customization Scripts/UpdateTextWithSliderValue.cs
1,600
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HallgeirWebApp { 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.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"); // 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.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
28.947368
143
0.618182
[ "MIT" ]
hallgeirl/cloud-demo
app/HallgeirWebApp/HallgeirWebApp/Startup.cs
1,650
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using cilspirv.Spirv; using cilspirv.Spirv.Ops; using Mono.Cecil; namespace cilspirv.Transpiler { internal class TranspilerInternalMethodMapper : ITranspilerLibraryMapper { private readonly TranspilerLibrary library; private readonly Dictionary<string, GenerateCallDelegate> methods = new Dictionary<string, GenerateCallDelegate>(); public TranspilerInternalMethodMapper(TranspilerLibrary library) => this.library = library; public IMappedFromCILType? TryMapType(TypeReference ilTypeRef) => null; public GenerateCallDelegate? TryMapMethod(MethodReference methodRef) { if (methods.TryGetValue(methodRef.FullName, out var mapped)) return mapped; var function = library.TryMapInternalMethod(methodRef.Resolve(), isEntryPoint: false); if (function == null) return null; mapped = GenerateCallFor(function); methods.Add(methodRef.FullName, mapped); return mapped; } private GenerateCallDelegate GenerateCallFor(TranspilerFunction function) => context => new[] { new OpFunctionCall() { Result = context.ResultID, ResultType = context.IDOf(function.ReturnType), Function = context.IDOf(function), Arguments = context.Parameters.Select(p => p.id).ToImmutableArray() } }; } }
34.021277
123
0.659787
[ "MIT" ]
Helco/cilspirv
cilspirv.transpiler/Transpiler/TranspilerInternalMethodMapper.cs
1,601
C#
using Bytes2you.Validation; using Cosmetics.Common; using Cosmetics.Contracts; using System; using System.Text; namespace Cosmetics.Products { public class Shampoo : Product, IProduct, IShampoo { //Class shampoo inherits class Product and extends fields milliliters and usage; //Each Shampoo has name, brand, price, gender, milliliters, usage. private uint milliliters; private UsageType usage; public Shampoo(string name, string brand, decimal price, GenderType gender, uint milliliters, UsageType usage) : base(name, brand, price, gender) { this.Name = name; this.Brand = brand; this.Price = price; this.Gender = gender; } public uint Milliliters { get { return this.milliliters; } set { Guard.WhenArgument((int)value, "Milliliters").IsLessThan(0).Throw(); this.milliliters = value; } } public UsageType Usage { get { return this.usage; } set { Guard.WhenArgument((int)value, "UsageType").IsLessThan(0).IsGreaterThan(1).Throw(); this.usage = value; } } public override string Print() { StringBuilder sb = new StringBuilder(); sb.AppendLine(base.Print()); sb.AppendLine($" #Milliliters: {this.Milliliters}"); sb.AppendLine($" #Usage: {this.Usage}"); sb.AppendLine($" ==="); return sb.ToString(); } } }
25.676471
101
0.514891
[ "MIT" ]
simeonovanton/TelerikALPHA_nov2017
04.OOP/CosmWorkshop_12122017/Cosmetics-Skeleton/Cosmetics/Products/Shampoo.cs
1,748
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Api.Data.Context; using Api.Domain.Entities; using Api.Domain.Interfaces; using Microsoft.EntityFrameworkCore; namespace Api.Data.Repository { public class BaseRepository<T> : IRepository<T> where T : BaseEntity { protected readonly MyContext _context; private DbSet<T> _dataset; public BaseRepository(MyContext context) { _context = context; _dataset = _context.Set<T>(); } public async Task<T> InsertAsync(T item) { try { if (item.Id == Guid.Empty) { item.Id = Guid.NewGuid(); } item.CreateAt = DateTime.UtcNow; _dataset.Add(item); await _context.SaveChangesAsync(); } catch (Exception ex) { throw ex; } return item; } public async Task<T> UpdateAsync(T item) { try { var result = await _dataset.SingleOrDefaultAsync(p => p.Id.Equals(item.Id)); if (result == null) return null; item.UpdateAt = DateTime.UtcNow; item.CreateAt = result.CreateAt; _context.Entry(result).CurrentValues.SetValues(item); await _context.SaveChangesAsync(); } catch (Exception ex) { throw ex; } return item; } public async Task<bool> DeleteAsync(Guid id) { try { var result = await _dataset.SingleOrDefaultAsync(p => p.Id.Equals(id)); if (result == null) return false; _dataset.Remove(result); await _context.SaveChangesAsync(); return true; } catch (Exception ex) { throw ex; } } public async Task<bool> ExistAsync (Guid id) { return await _dataset.AnyAsync(p => p.Id.Equals(id)); } public async Task<T> SelectAsync(Guid id) { try { return await _dataset.SingleOrDefaultAsync(p => p.Id.Equals(id)); } catch (Exception ex) { throw ex; } } public async Task<IEnumerable<T>> SelectAsync() { try { return await _dataset.ToListAsync(); } catch (Exception ex) { throw ex; } } } }
23.85124
92
0.447332
[ "MIT" ]
makampos/api-dotnetcore
src/Api.Data/Repository/BaseRepository.cs
2,886
C#
using UnityEngine; using UnityEngine.Rendering.Universal; namespace UnityEditor.Rendering.Universal { [VolumeComponentEditor(typeof(ChannelMixer))] sealed class ChannelMixerEditor : VolumeComponentEditor { SerializedDataParameter m_RedOutRedIn; SerializedDataParameter m_RedOutGreenIn; SerializedDataParameter m_RedOutBlueIn; SerializedDataParameter m_GreenOutRedIn; SerializedDataParameter m_GreenOutGreenIn; SerializedDataParameter m_GreenOutBlueIn; SerializedDataParameter m_BlueOutRedIn; SerializedDataParameter m_BlueOutGreenIn; SerializedDataParameter m_BlueOutBlueIn; SavedInt m_SelectedChannel; public override void OnEnable() { var o = new PropertyFetcher<ChannelMixer>(serializedObject); m_RedOutRedIn = Unpack(o.Find(x => x.redOutRedIn)); m_RedOutGreenIn = Unpack(o.Find(x => x.redOutGreenIn)); m_RedOutBlueIn = Unpack(o.Find(x => x.redOutBlueIn)); m_GreenOutRedIn = Unpack(o.Find(x => x.greenOutRedIn)); m_GreenOutGreenIn = Unpack(o.Find(x => x.greenOutGreenIn)); m_GreenOutBlueIn = Unpack(o.Find(x => x.greenOutBlueIn)); m_BlueOutRedIn = Unpack(o.Find(x => x.blueOutRedIn)); m_BlueOutGreenIn = Unpack(o.Find(x => x.blueOutGreenIn)); m_BlueOutBlueIn = Unpack(o.Find(x => x.blueOutBlueIn)); m_SelectedChannel = new SavedInt($"{target.GetType()}.SelectedChannel", 0); } public override void OnInspectorGUI() { int currentChannel = m_SelectedChannel.value; EditorGUI.BeginChangeCheck(); { using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Toggle(currentChannel == 0, EditorGUIUtility.TrTextContent("Red", "Red output channel."), EditorStyles.miniButtonLeft)) currentChannel = 0; if (GUILayout.Toggle(currentChannel == 1, EditorGUIUtility.TrTextContent("Green", "Green output channel."), EditorStyles.miniButtonMid)) currentChannel = 1; if (GUILayout.Toggle(currentChannel == 2, EditorGUIUtility.TrTextContent("Blue", "Blue output channel."), EditorStyles.miniButtonRight)) currentChannel = 2; } } if (EditorGUI.EndChangeCheck()) GUI.FocusControl(null); m_SelectedChannel.value = currentChannel; if (currentChannel == 0) { PropertyField(m_RedOutRedIn, EditorGUIUtility.TrTextContent("Red")); PropertyField(m_RedOutGreenIn, EditorGUIUtility.TrTextContent("Green")); PropertyField(m_RedOutBlueIn, EditorGUIUtility.TrTextContent("Blue")); } else if (currentChannel == 1) { PropertyField(m_GreenOutRedIn, EditorGUIUtility.TrTextContent("Red")); PropertyField(m_GreenOutGreenIn, EditorGUIUtility.TrTextContent("Green")); PropertyField(m_GreenOutBlueIn, EditorGUIUtility.TrTextContent("Blue")); } else { PropertyField(m_BlueOutRedIn, EditorGUIUtility.TrTextContent("Red")); PropertyField(m_BlueOutGreenIn, EditorGUIUtility.TrTextContent("Green")); PropertyField(m_BlueOutBlueIn, EditorGUIUtility.TrTextContent("Blue")); } } } }
45.12987
176
0.638849
[ "MIT" ]
Liaoer/ToonShader
Packages/com.unity.render-pipelines.universal@12.1.3/Editor/Overrides/ChannelMixerEditor.cs
3,475
C#
// ----------------------------------------------------------------------- // <copyright file="EndpointReader.cs" company="Asynkron HB"> // Copyright (C) 2015-2018 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System.Linq; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Utils; using Proto.Mailbox; namespace Proto.Remote { public class EndpointReader : Remoting.RemotingBase { private bool _suspended; public override Task<ConnectResponse> Connect(ConnectRequest request, ServerCallContext context) { if (_suspended) { throw new RpcException(Status.DefaultCancelled, "Suspended"); } return Task.FromResult(new ConnectResponse() { DefaultSerializerId = Serialization.DefaultSerializerId }); } public override async Task Receive(IAsyncStreamReader<MessageBatch> requestStream, IServerStreamWriter<Unit> responseStream, ServerCallContext context) { var targets = new PID[100]; await requestStream.ForEachAsync(batch => { if (_suspended) return Actor.Done; //only grow pid lookup if needed if (batch.TargetNames.Count > targets.Length) { targets = new PID[batch.TargetNames.Count]; } for (int i = 0; i < batch.TargetNames.Count; i++) { targets[i] = new PID(ProcessRegistry.Instance.Address, batch.TargetNames[i]); } var typeNames = batch.TypeNames.ToArray(); foreach (var envelope in batch.Envelopes) { var target = targets[envelope.Target]; var typeName = typeNames[envelope.TypeId]; var message = Serialization.Deserialize(typeName, envelope.MessageData, envelope.SerializerId); if (message is Terminated msg) { var rt = new RemoteTerminate(target, msg.Who); EndpointManager.RemoteTerminate(rt); } else if (message is SystemMessage sys) { target.SendSystemMessage(sys); } else { Proto.MessageHeader header = null; if (envelope.MessageHeader != null) { header = new Proto.MessageHeader(envelope.MessageHeader.HeaderData); } var localEnvelope = new Proto.MessageEnvelope(message, envelope.Sender, header); RootContext.Empty.Send(target, localEnvelope); } } return Actor.Done; }); } public void Suspend(bool suspended) { _suspended = suspended; } } }
37.181818
116
0.476467
[ "Apache-2.0" ]
Impetus-Global-Research/protoactor-dotnet
src/Proto.Remote/EndpointReader.cs
3,274
C#
/* * Selling Partner API for Finances * * The Selling Partner API for Finances helps you obtain financial information relevant to a seller's business. You can obtain financial events for a given order, financial event group, or date range without having to wait until a statement period closes. You can also obtain financial event groups for a given date range. * * OpenAPI spec version: v0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using System.Text; namespace AmazonSpApiSDK.Models.Finances { /// <summary> /// A list of financial event group information. /// </summary> [DataContract] public partial class FinancialEventGroupList : List<FinancialEventGroup>, IEquatable<FinancialEventGroupList>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="FinancialEventGroupList" /> class. /// </summary> [JsonConstructorAttribute] public FinancialEventGroupList() : base() { } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class FinancialEventGroupList {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as FinancialEventGroupList); } /// <summary> /// Returns true if FinancialEventGroupList instances are equal /// </summary> /// <param name="input">Instance of FinancialEventGroupList to be compared</param> /// <returns>Boolean</returns> public bool Equals(FinancialEventGroupList input) { if (input == null) return false; return base.Equals(input); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
33.528846
322
0.605391
[ "MIT" ]
KristopherMackowiak/Amazon-SP-API-CSharp
Source/AmazonSpApiSDK/Models/Finances/FinancialEventGroupList.cs
3,487
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== namespace Squidex.Infrastructure.Orleans { public static class JExtensions { public static J<T> AsJ<T>(this T value) { return new J<T>(value); } } }
31.444444
78
0.367491
[ "MIT" ]
jiveabillion/squidex
src/Squidex.Infrastructure/Orleans/JExtensions.cs
568
C#
using System; using Avalonia.Input; using Avalonia.Input.Raw; namespace Avalonia.Input.Raw { public class RawDragEvent : RawInputEventArgs { public IInputElement InputRoot { get; } public Point Location { get; } public IDataObject Data { get; } public DragDropEffects Effects { get; set; } public RawDragEventType Type { get; } public RawDragEvent(IDragDropDevice inputDevice, RawDragEventType type, IInputElement inputRoot, Point location, IDataObject data, DragDropEffects effects) :base(inputDevice, 0) { Type = type; InputRoot = inputRoot; Location = location; Data = data; Effects = effects; } } }
29.461538
95
0.614883
[ "MIT" ]
BOBO41/Avalonia
src/Avalonia.Input/Raw/RawDragEvent.cs
768
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using Splat; namespace ReactiveUI { /// <summary> /// Creates a observable for a property if available that is based on a DependencyProperty. /// </summary> public class DependencyObjectObservableForProperty : ICreatesObservableForProperty { /// <inheritdoc/> public int GetAffinityForObject(Type type, string propertyName, bool beforeChanged = false) { if (!typeof(DependencyObject).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) { return 0; } return GetDependencyProperty(type, propertyName) != null ? 4 : 0; } /// <inheritdoc/> public IObservable<IObservedChange<object, object>> GetNotificationForProperty(object sender, System.Linq.Expressions.Expression expression, string propertyName, bool beforeChanged = false) { var type = sender.GetType(); var dpd = DependencyPropertyDescriptor.FromProperty(GetDependencyProperty(type, propertyName), type); if (dpd == null) { this.Log().Error("Couldn't find dependency property " + propertyName + " on " + type.Name); throw new NullReferenceException("Couldn't find dependency property " + propertyName + " on " + type.Name); } return Observable.Create<IObservedChange<object, object>>(subj => { var handler = new EventHandler((o, e) => { subj.OnNext(new ObservedChange<object, object>(sender, expression)); }); dpd.AddValueChanged(sender, handler); return Disposable.Create(() => dpd.RemoveValueChanged(sender, handler)); }); } private DependencyProperty GetDependencyProperty(Type type, string propertyName) { var fi = type.GetTypeInfo().GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public) .FirstOrDefault(x => x.Name == propertyName + "Property" && x.IsStatic); if (fi != null) { return (DependencyProperty)fi.GetValue(null); } return null; } } }
36.986301
197
0.627778
[ "MIT" ]
Nilox/ReactiveUI
src/ReactiveUI.Wpf/WpfDependencyObjectObservableForProperty.cs
2,702
C#
using System; using System.IO; using libProChic; namespace Notepad { public partial class formnotepad { private string strFile; private MasterClass m = new MasterClass(); public formnotepad(String strFile) { InitializeComponent(); if (System.IO.File.Exists(strFile)) txtNotepad.Text = File.ReadAllText(strFile); else strFile = ""; } private void formnotepad_Load(System.Object sender, System.EventArgs e) { // editTaskbar("95", Me, True) look.Start(); } private void NewToolStripMenuItem1_Click(object sender, EventArgs e) { if ((txtNotepad.Text != null/* TODO Change to default(_) if this is not a reference type */ && strFile == null) || (strFile != null && System.IO.File.ReadAllText(strFile) == txtNotepad.Text)) { //ProjectChicagoObjects.MessageBox c = new ProjectChicagoObjects.MessageBox("The text in this file has changed." + Constants.vbCrLf + "Do you want to save the changes?", "Notepad", false, ProjectChicagoObjects.MessageBox.MsgBoxType.Message_Warning); //var diaResult = c.ShowDialog; //if (diaResult == DialogResult.Yes) //{ // ProjectChicagoObjects.FileDialog fdb = new ProjectChicagoObjects.FileDialog("*.txt", "") { Filter = "Text Documents|*.txt|All Files (*.*)|*.*", Text = "Save As", Directory = "" }; // if (fdb.ShowDialog == DialogResult.OK) // System.IO.File.WriteAllText(fdb.FileName, txtNotepad.Text); //} //else if (diaResult == DialogResult.No) //{ // txtNotepad.ResetText(); // txtNotepad.Focus(); //} } } // CLICK EVENT I ACCIDENTALLY MADE: Private Sub FindToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FindToolStripMenuItem.Click // End Sub // Private Sub ExitToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem1.Click // If txtNotepad.Text <> ReadAllText(strFile) Then // Dim msg = messageBoxGenerate("95", "warning", "The text in this file has changed." & vbCrLf & "Do you want to save the changes?", 1, 0, 1, 1, 0) // If msg.ShowDialog = DialogResult.Yes Then // If sfdNotepad.ShowDialog = DialogResult.OK Then // WriteAllText(sfdNotepad.FileName, txtNotepad.Text) // End If // ElseIf msg.DialogResult = DialogResult.No Then // Close() // End If // End If // End Sub private void look_Tick(System.Object sender, System.EventArgs e) { } } }
44.888889
265
0.583098
[ "BSD-3-Clause" ]
LeMS-Studio5/ProjectChicago-
Applications/Win95/Notepad/Notepad.cs
2,830
C#
using UnityEngine; using System.Collections; public class Cloud : MonoBehaviour { public Vector3 velocity = new Vector3(0.1f, 0, 0); public Vector3 limits = new Vector3(100, 100, 100); // Use this for initialization void Start () { } // Update is called once per frame void Update () { Vector3 pos = transform.position; // Update position based on speed transform.position += velocity; // Reset if gone too far if (pos.x > limits.x) { transform.position = new Vector3(-limits.x, pos.y, pos.z); } if (pos.z > limits.z) { transform.position = new Vector3(pos.x, pos.y, -limits.z); } if (pos.y > limits.y) { transform.position = new Vector3(pos.x, -limits.y, pos.z); } } }
20.542857
61
0.653686
[ "MIT" ]
nickjbenson/Kami
Assets/Scripts/Cloud.cs
721
C#
 namespace LiveSplit.UI.Components { partial class SummaryTrackerSettings { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.topLevelLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.Settings_Groupbox = new System.Windows.Forms.GroupBox(); this.UsernameDesc = new System.Windows.Forms.Label(); this.UsernameTitle = new System.Windows.Forms.Label(); this.UsernameTB = new System.Windows.Forms.TextBox(); this.LiteMode_Desc = new System.Windows.Forms.Label(); this.Checkbox_LiteMode = new System.Windows.Forms.CheckBox(); this.topLevelLayoutPanel.SuspendLayout(); this.Settings_Groupbox.SuspendLayout(); this.SuspendLayout(); // // topLevelLayoutPanel // this.topLevelLayoutPanel.AutoSize = true; this.topLevelLayoutPanel.ColumnCount = 1; this.topLevelLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.topLevelLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.topLevelLayoutPanel.Controls.Add(this.Settings_Groupbox, 0, 0); this.topLevelLayoutPanel.Location = new System.Drawing.Point(0, 0); this.topLevelLayoutPanel.Name = "topLevelLayoutPanel"; this.topLevelLayoutPanel.RowCount = 1; this.topLevelLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.topLevelLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.topLevelLayoutPanel.Size = new System.Drawing.Size(471, 302); this.topLevelLayoutPanel.TabIndex = 0; // // Settings_Groupbox // this.Settings_Groupbox.Controls.Add(this.UsernameDesc); this.Settings_Groupbox.Controls.Add(this.UsernameTitle); this.Settings_Groupbox.Controls.Add(this.UsernameTB); this.Settings_Groupbox.Controls.Add(this.LiteMode_Desc); this.Settings_Groupbox.Controls.Add(this.Checkbox_LiteMode); this.Settings_Groupbox.Location = new System.Drawing.Point(3, 3); this.Settings_Groupbox.Name = "Settings_Groupbox"; this.Settings_Groupbox.Size = new System.Drawing.Size(465, 296); this.Settings_Groupbox.TabIndex = 0; this.Settings_Groupbox.TabStop = false; this.Settings_Groupbox.Text = "Settings"; // // UsernameDesc // this.UsernameDesc.AutoSize = true; this.UsernameDesc.Font = new System.Drawing.Font("Titillium Web", 9.749999F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.UsernameDesc.Location = new System.Drawing.Point(47, 65); this.UsernameDesc.MaximumSize = new System.Drawing.Size(420, 0); this.UsernameDesc.Name = "UsernameDesc"; this.UsernameDesc.Size = new System.Drawing.Size(406, 40); this.UsernameDesc.TabIndex = 6; this.UsernameDesc.Text = "Set your username so the verifiers can easily determine who\'s run they are lookin" + "g at."; // // UsernameTitle // this.UsernameTitle.AutoSize = true; this.UsernameTitle.Font = new System.Drawing.Font("Titillium Web SemiBold", 9.749999F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.UsernameTitle.Location = new System.Drawing.Point(15, 35); this.UsernameTitle.Name = "UsernameTitle"; this.UsernameTitle.Size = new System.Drawing.Size(70, 20); this.UsernameTitle.TabIndex = 5; this.UsernameTitle.Text = "Username:"; // // UsernameTB // this.UsernameTB.Font = new System.Drawing.Font("Titillium Web SemiBold", 9.749999F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.UsernameTB.Location = new System.Drawing.Point(91, 32); this.UsernameTB.MaxLength = 25; this.UsernameTB.Name = "UsernameTB"; this.UsernameTB.Size = new System.Drawing.Size(174, 27); this.UsernameTB.TabIndex = 4; // // LiteMode_Desc // this.LiteMode_Desc.AutoSize = true; this.LiteMode_Desc.Font = new System.Drawing.Font("Titillium Web", 9.749999F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.LiteMode_Desc.Location = new System.Drawing.Point(47, 139); this.LiteMode_Desc.MaximumSize = new System.Drawing.Size(420, 0); this.LiteMode_Desc.Name = "LiteMode_Desc"; this.LiteMode_Desc.Size = new System.Drawing.Size(409, 40); this.LiteMode_Desc.TabIndex = 1; this.LiteMode_Desc.Text = "Lite mode displays minimal information all in 1 row; for those who need as much s" + "pace as possible on their layout."; // // Checkbox_LiteMode // this.Checkbox_LiteMode.AutoSize = true; this.Checkbox_LiteMode.Font = new System.Drawing.Font("Titillium Web SemiBold", 9.749999F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Checkbox_LiteMode.Location = new System.Drawing.Point(15, 116); this.Checkbox_LiteMode.Name = "Checkbox_LiteMode"; this.Checkbox_LiteMode.Size = new System.Drawing.Size(84, 24); this.Checkbox_LiteMode.TabIndex = 0; this.Checkbox_LiteMode.Text = "Lite Mode"; this.Checkbox_LiteMode.UseVisualStyleBackColor = true; // // SummaryTrackerSettings // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.Controls.Add(this.topLevelLayoutPanel); this.Name = "SummaryTrackerSettings"; this.Size = new System.Drawing.Size(474, 305); this.Load += new System.EventHandler(this.QuestTrackerSettings_Load); this.topLevelLayoutPanel.ResumeLayout(false); this.Settings_Groupbox.ResumeLayout(false); this.Settings_Groupbox.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TableLayoutPanel topLevelLayoutPanel; private System.Windows.Forms.GroupBox Settings_Groupbox; private System.Windows.Forms.CheckBox Checkbox_LiteMode; private System.Windows.Forms.Label LiteMode_Desc; private System.Windows.Forms.Label UsernameTitle; private System.Windows.Forms.TextBox UsernameTB; private System.Windows.Forms.Label UsernameDesc; } }
51.941558
182
0.632829
[ "MIT" ]
Shockster218/LiveSplit.AllQuestsTracker
UI/Components/SummaryTrackerSettings.Designer.cs
8,001
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Gooios.EnterprisePortal.Models.AccountViewModels { public class LoginViewModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } }
22.826087
58
0.660952
[ "Apache-2.0" ]
hccoo/gooios
netcoremicroservices/Gooios.EnterprisePortal/Models/AccountViewModels/LoginViewModel.cs
527
C#
namespace MediaShare.Models.TokenAuth { public class ExternalAuthenticateResultModel { public string AccessToken { get; set; } public string EncryptedAccessToken { get; set; } public int ExpireInSeconds { get; set; } public bool WaitingForActivation { get; set; } } }
22.571429
56
0.661392
[ "MIT" ]
tigeryzx/MediaShare
aspnet-core/src/MediaShare.Web.Core/Models/TokenAuth/ExternalAuthenticateResultModel.cs
318
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 06:01:58 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static go.builtin; using context = go.context_package; using json = go.encoding.json_package; using fmt = go.fmt_package; using ast = go.go.ast_package; using parser = go.go.parser_package; using scanner = go.go.scanner_package; using token = go.go.token_package; using types = go.go.types_package; using ioutil = go.io.ioutil_package; using log = go.log_package; using os = go.os_package; using filepath = go.path.filepath_package; using strings = go.strings_package; using sync = go.sync_package; using time = go.time_package; using gcexportdata = go.golang.org.x.tools.go.gcexportdata_package; using gocommand = go.golang.org.x.tools.@internal.gocommand_package; using packagesinternal = go.golang.org.x.tools.@internal.packagesinternal_package; using typesinternal = go.golang.org.x.tools.@internal.typesinternal_package; using go; #nullable enable namespace go { namespace golang.org { namespace x { namespace tools { namespace go { public static partial class packages_package { [GeneratedCode("go2cs", "0.1.0.0")] public partial struct Error { // Constructors public Error(NilType _) { this.Pos = default; this.Msg = default; this.Kind = default; } public Error(@string Pos = default, @string Msg = default, ErrorKind Kind = default) { this.Pos = Pos; this.Msg = Msg; this.Kind = Kind; } // Enable comparisons between nil and Error struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Error value, NilType nil) => value.Equals(default(Error)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Error value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, Error value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, Error value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Error(NilType nil) => default(Error); } [GeneratedCode("go2cs", "0.1.0.0")] public static Error Error_cast(dynamic value) { return new Error(value.Pos, value.Msg, value.Kind); } } }}}}}
34.625
101
0.631441
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/packages_ErrorStruct.cs
3,047
C#
using System; using System.Collections.Generic; using System.Threading; using Machine.Container.Model; using Machine.Container.Plugins; using Machine.Core.Utility; namespace Machine.Container.Services.Impl { public class Memento<K, V> { readonly Dictionary<K, V> _map = new Dictionary<K, V>(); readonly ReaderWriterLock _lock = new ReaderWriterLock(); public V Lookup(K key, Func<K, V> factory) { using (RWLock.AsReader(_lock)) { if (RWLock.UpgradeToWriterIf(_lock, () => !_map.ContainsKey(key))) { _map[key] = factory(key); } return _map[key]; } } } public class ServiceGraph : IServiceGraph { private readonly IListenerInvoker _listenerInvoker; private readonly IDictionary<Type, ServiceEntry> _map = new Dictionary<Type, ServiceEntry>(); #if DEBUGGING_LOCKS private readonly IReaderWriterLock _lock = ReaderWriterLockFactory.CreateLock("ServiceGraph"); #else private readonly ReaderWriterLock _lock = new ReaderWriterLock(); #endif private readonly List<Type> _registrationOrder = new List<Type>(); private readonly Dictionary<string, ServiceEntry> _nameLookupCache = new Dictionary<string, ServiceEntry>(); public ServiceGraph(IListenerInvoker listenerInvoker) { _listenerInvoker = listenerInvoker; } public ServiceEntry Lookup(Type type, LookupFlags flags) { return LookupLazily(type, flags); } public ServiceEntry Lookup(Type type) { return Lookup(type, LookupFlags.Default); } public ServiceEntry Lookup(string name) { List<ServiceEntry> matches = new List<ServiceEntry>(); using (RWLock.AsReader(_lock)) { if (RWLock.UpgradeToWriterIf(_lock, delegate() { return !_nameLookupCache.ContainsKey(name); })) { foreach (KeyValuePair<Type, ServiceEntry> pair in _map) { if (pair.Value.IsNamed(name)) { matches.Add(pair.Value); } } _nameLookupCache[name] = Select(matches, LookupFlags.Default, name); } return _nameLookupCache[name]; } } public void Add(ServiceEntry entry) { using (RWLock.AsWriter(_lock)) { _map[entry.ServiceType] = entry; _registrationOrder.Add(entry.ServiceType); _listenerInvoker.OnRegistration(entry); } } public IEnumerable<ServiceRegistration> RegisteredServices { get { using (RWLock.AsReader(_lock)) { List<ServiceRegistration> registrations = new List<ServiceRegistration>(); foreach (Type serviceType in _registrationOrder) { ServiceEntry serviceEntry = _map[serviceType]; registrations.Add(new ServiceRegistration(serviceEntry.ServiceType)); } return registrations; } } } protected virtual ServiceEntry LookupLazily(Type type, LookupFlags flags) { using (RWLock.AsReader(_lock)) { List<ServiceEntry> matches = new List<ServiceEntry>(); foreach (Type key in _registrationOrder) { ServiceEntry entry = _map[key]; if (type.IsAssignableFrom(entry.ServiceType)) { matches.Add(entry); } } return Select(matches, flags, type.ToString()); } } private static ServiceEntry Select(IList<ServiceEntry> matches, LookupFlags flags, string beingLookedUp) { if (matches.Count == 1) { return matches[0]; } if (matches.Count > 1 && (flags & LookupFlags.ThrowIfAmbiguous) == LookupFlags.ThrowIfAmbiguous) { throw new AmbiguousServicesException(beingLookedUp); } return null; } } }
29.691729
113
0.613067
[ "MIT" ]
benlovell/machine
Source/Container/Machine.Container/Services/Impl/ServiceGraph.cs
3,949
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PSTParse.ListsTablesPropertiesLayer { public class BTHDataRecord { public uint Key; public uint Value; public BTHDataRecord(byte[] bytes, BTHHEADER header) { var keySize = (int)header.KeySize; var dataSize = (int) header.DataSize; this.Key = BitConverter.ToUInt16(bytes.Take(keySize).ToArray(), 0); this.Value = BitConverter.ToUInt32(bytes.Skip(keySize).Take(dataSize).ToArray(), 0); } } }
25.652174
96
0.640678
[ "MIT" ]
Sharpiro/PST-Parser
PSTParse/ListsTablesPropertiesLayer/BTHDataRecord.cs
592
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.DLM")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Data Lifecycle Manager. Amazon Data Lifecycle Manager manages lifecycle of your AWS resources.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Data Lifecycle Manager. Amazon Data Lifecycle Manager manages lifecycle of your AWS resources.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon Data Lifecycle Manager. Amazon Data Lifecycle Manager manages lifecycle of your AWS resources.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon Data Lifecycle Manager. Amazon Data Lifecycle Manager manages lifecycle of your AWS resources.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. 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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.7.1.54")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
45.568627
193
0.768503
[ "Apache-2.0" ]
jamieromanowski/aws-sdk-net
sdk/src/Services/DLM/Properties/AssemblyInfo.cs
2,324
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: mediapipe/calculators/image/scale_image_calculator.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Mediapipe { /// <summary>Holder for reflection information generated from mediapipe/calculators/image/scale_image_calculator.proto</summary> public static partial class ScaleImageCalculatorReflection { #region Descriptor /// <summary>File descriptor for mediapipe/calculators/image/scale_image_calculator.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ScaleImageCalculatorReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjhtZWRpYXBpcGUvY2FsY3VsYXRvcnMvaW1hZ2Uvc2NhbGVfaW1hZ2VfY2Fs", "Y3VsYXRvci5wcm90bxIJbWVkaWFwaXBlGiRtZWRpYXBpcGUvZnJhbWV3b3Jr", "L2NhbGN1bGF0b3IucHJvdG8aLm1lZGlhcGlwZS9mcmFtZXdvcmsvZm9ybWF0", "cy9pbWFnZV9mb3JtYXQucHJvdG8iogYKG1NjYWxlSW1hZ2VDYWxjdWxhdG9y", "T3B0aW9ucxIUCgx0YXJnZXRfd2lkdGgYASABKAUSFQoNdGFyZ2V0X2hlaWdo", "dBgCIAEoBRIXCg90YXJnZXRfbWF4X2FyZWEYDyABKAUSIwoVcHJlc2VydmVf", "YXNwZWN0X3JhdGlvGAMgASgIOgR0cnVlEh4KEG1pbl9hc3BlY3RfcmF0aW8Y", "BCABKAk6BDkvMTYSHgoQbWF4X2FzcGVjdF9yYXRpbxgFIAEoCToEMTYvORI0", "Cg1vdXRwdXRfZm9ybWF0GAYgASgOMh0ubWVkaWFwaXBlLkltYWdlRm9ybWF0", "LkZvcm1hdBJRCglhbGdvcml0aG0YByABKA4yNS5tZWRpYXBpcGUuU2NhbGVJ", "bWFnZUNhbGN1bGF0b3JPcHRpb25zLlNjYWxlQWxnb3JpdGhtOgdERUZBVUxU", "Eh4KEmFsaWdubWVudF9ib3VuZGFyeRgIIAEoBToCMTYSIwoVc2V0X2FsaWdu", "bWVudF9wYWRkaW5nGAkgASgIOgR0cnVlEjIKI09CU09MRVRFX3NraXBfbGlu", "ZWFyX3JnYl9jb252ZXJzaW9uGAogASgIOgVmYWxzZRImChtwb3N0X3NoYXJw", "ZW5pbmdfY29lZmZpY2llbnQYCyABKAI6ATASMwoMaW5wdXRfZm9ybWF0GAwg", "ASgOMh0ubWVkaWFwaXBlLkltYWdlRm9ybWF0LkZvcm1hdBIfChRzY2FsZV90", "b19tdWx0aXBsZV9vZhgNIAEoBToBMhIYCgl1c2VfYnQ3MDkYDiABKAg6BWZh", "bHNlImgKDlNjYWxlQWxnb3JpdGhtEgsKB0RFRkFVTFQQABIKCgZMSU5FQVIQ", "ARIJCgVDVUJJQxACEggKBEFSRUEQAxILCgdMQU5DWk9TEAQSGwoXREVGQVVM", "VF9XSVRIT1VUX1VQU0NBTEUQBTJUCgNleHQSHC5tZWRpYXBpcGUuQ2FsY3Vs", "YXRvck9wdGlvbnMYu+XKHyABKAsyJi5tZWRpYXBpcGUuU2NhbGVJbWFnZUNh", "bGN1bGF0b3JPcHRpb25z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Mediapipe.CalculatorReflection.Descriptor, global::Mediapipe.ImageFormatReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Mediapipe.ScaleImageCalculatorOptions), global::Mediapipe.ScaleImageCalculatorOptions.Parser, new[]{ "TargetWidth", "TargetHeight", "TargetMaxArea", "PreserveAspectRatio", "MinAspectRatio", "MaxAspectRatio", "OutputFormat", "Algorithm", "AlignmentBoundary", "SetAlignmentPadding", "OBSOLETESkipLinearRgbConversion", "PostSharpeningCoefficient", "InputFormat", "ScaleToMultipleOf", "UseBt709" }, null, new[]{ typeof(global::Mediapipe.ScaleImageCalculatorOptions.Types.ScaleAlgorithm) }, new pb::Extension[] { global::Mediapipe.ScaleImageCalculatorOptions.Extensions.Ext }, null) })); } #endregion } #region Messages /// <summary> /// Order of operations. /// 1) Crop the image to fit within min_aspect_ratio and max_aspect_ratio. /// 2) Scale and convert the image to fit inside target_width x target_height /// using the specified scaling algorithm. (maintaining the aspect /// ratio if preserve_aspect_ratio is true). /// The output width and height will be divisible by 2, by default. It is /// possible to output width and height that are odd numbers when the output /// format is SRGB and the aspect ratio is left unpreserved. See /// scale_to_multiple_of for details. /// </summary> public sealed partial class ScaleImageCalculatorOptions : pb::IMessage<ScaleImageCalculatorOptions> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<ScaleImageCalculatorOptions> _parser = new pb::MessageParser<ScaleImageCalculatorOptions>(() => new ScaleImageCalculatorOptions()); private pb::UnknownFieldSet _unknownFields; private int _hasBits0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<ScaleImageCalculatorOptions> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Mediapipe.ScaleImageCalculatorReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ScaleImageCalculatorOptions() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ScaleImageCalculatorOptions(ScaleImageCalculatorOptions other) : this() { _hasBits0 = other._hasBits0; targetWidth_ = other.targetWidth_; targetHeight_ = other.targetHeight_; targetMaxArea_ = other.targetMaxArea_; preserveAspectRatio_ = other.preserveAspectRatio_; minAspectRatio_ = other.minAspectRatio_; maxAspectRatio_ = other.maxAspectRatio_; outputFormat_ = other.outputFormat_; algorithm_ = other.algorithm_; alignmentBoundary_ = other.alignmentBoundary_; setAlignmentPadding_ = other.setAlignmentPadding_; oBSOLETESkipLinearRgbConversion_ = other.oBSOLETESkipLinearRgbConversion_; postSharpeningCoefficient_ = other.postSharpeningCoefficient_; inputFormat_ = other.inputFormat_; scaleToMultipleOf_ = other.scaleToMultipleOf_; useBt709_ = other.useBt709_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ScaleImageCalculatorOptions Clone() { return new ScaleImageCalculatorOptions(this); } /// <summary>Field number for the "target_width" field.</summary> public const int TargetWidthFieldNumber = 1; private readonly static int TargetWidthDefaultValue = 0; private int targetWidth_; /// <summary> /// Target output width and height. The final output's size may vary /// depending on the other options below. If unset, use the same width /// or height as the input. If only one is set then determine the other /// from the aspect ratio (after cropping). The output width and height /// will be divisible by 2, by default. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int TargetWidth { get { if ((_hasBits0 & 1) != 0) { return targetWidth_; } else { return TargetWidthDefaultValue; } } set { _hasBits0 |= 1; targetWidth_ = value; } } /// <summary>Gets whether the "target_width" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasTargetWidth { get { return (_hasBits0 & 1) != 0; } } /// <summary>Clears the value of the "target_width" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearTargetWidth() { _hasBits0 &= ~1; } /// <summary>Field number for the "target_height" field.</summary> public const int TargetHeightFieldNumber = 2; private readonly static int TargetHeightDefaultValue = 0; private int targetHeight_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int TargetHeight { get { if ((_hasBits0 & 2) != 0) { return targetHeight_; } else { return TargetHeightDefaultValue; } } set { _hasBits0 |= 2; targetHeight_ = value; } } /// <summary>Gets whether the "target_height" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasTargetHeight { get { return (_hasBits0 & 2) != 0; } } /// <summary>Clears the value of the "target_height" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearTargetHeight() { _hasBits0 &= ~2; } /// <summary>Field number for the "target_max_area" field.</summary> public const int TargetMaxAreaFieldNumber = 15; private readonly static int TargetMaxAreaDefaultValue = 0; private int targetMaxArea_; /// <summary> /// If set, then automatically calculates a target_width and target_height that /// has an area below the target max area. Aspect ratio preservation cannot be /// disabled. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int TargetMaxArea { get { if ((_hasBits0 & 4096) != 0) { return targetMaxArea_; } else { return TargetMaxAreaDefaultValue; } } set { _hasBits0 |= 4096; targetMaxArea_ = value; } } /// <summary>Gets whether the "target_max_area" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasTargetMaxArea { get { return (_hasBits0 & 4096) != 0; } } /// <summary>Clears the value of the "target_max_area" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearTargetMaxArea() { _hasBits0 &= ~4096; } /// <summary>Field number for the "preserve_aspect_ratio" field.</summary> public const int PreserveAspectRatioFieldNumber = 3; private readonly static bool PreserveAspectRatioDefaultValue = true; private bool preserveAspectRatio_; /// <summary> /// If true, the image is scaled up or down proportionally so that it /// fits inside the box represented by target_width and target_height. /// Otherwise it is scaled to fit target_width and target_height /// completely. In any case, the aspect ratio that is preserved is /// that after cropping to the minimum/maximum aspect ratio. Additionally, if /// true, the output width and height will be divisible by 2. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool PreserveAspectRatio { get { if ((_hasBits0 & 4) != 0) { return preserveAspectRatio_; } else { return PreserveAspectRatioDefaultValue; } } set { _hasBits0 |= 4; preserveAspectRatio_ = value; } } /// <summary>Gets whether the "preserve_aspect_ratio" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasPreserveAspectRatio { get { return (_hasBits0 & 4) != 0; } } /// <summary>Clears the value of the "preserve_aspect_ratio" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearPreserveAspectRatio() { _hasBits0 &= ~4; } /// <summary>Field number for the "min_aspect_ratio" field.</summary> public const int MinAspectRatioFieldNumber = 4; private readonly static string MinAspectRatioDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("OS8xNg=="), 0, 4); private string minAspectRatio_; /// <summary> /// If ratio is positive, crop the image to this minimum and maximum /// aspect ratio (preserving the center of the frame). This is done /// before scaling. The string must contain "/", so to disable cropping, /// set both to "0/1". /// For example, for a min_aspect_ratio of "9/16" and max of "16/9" the /// following cropping will occur: /// 1920x1080 (which is 16:9) is not cropped /// 640x1024 (which is 10:16) is not cropped /// 640x320 (which is 2:1) cropped to 568x320 (just under 16/9) /// 96x480 (which is 1:5), cropped to 96x170 (just over 9/16) /// The resultant frame will always be between (or at) the /// min_aspect_ratio and max_aspect_ratio. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string MinAspectRatio { get { return minAspectRatio_ ?? MinAspectRatioDefaultValue; } set { minAspectRatio_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Gets whether the "min_aspect_ratio" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasMinAspectRatio { get { return minAspectRatio_ != null; } } /// <summary>Clears the value of the "min_aspect_ratio" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearMinAspectRatio() { minAspectRatio_ = null; } /// <summary>Field number for the "max_aspect_ratio" field.</summary> public const int MaxAspectRatioFieldNumber = 5; private readonly static string MaxAspectRatioDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("MTYvOQ=="), 0, 4); private string maxAspectRatio_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string MaxAspectRatio { get { return maxAspectRatio_ ?? MaxAspectRatioDefaultValue; } set { maxAspectRatio_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Gets whether the "max_aspect_ratio" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasMaxAspectRatio { get { return maxAspectRatio_ != null; } } /// <summary>Clears the value of the "max_aspect_ratio" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearMaxAspectRatio() { maxAspectRatio_ = null; } /// <summary>Field number for the "output_format" field.</summary> public const int OutputFormatFieldNumber = 6; private readonly static global::Mediapipe.ImageFormat.Types.Format OutputFormatDefaultValue = global::Mediapipe.ImageFormat.Types.Format.Unknown; private global::Mediapipe.ImageFormat.Types.Format outputFormat_; /// <summary> /// If unset, use the same format as the input. /// NOTE: in the current implementation, the output format (either specified /// in the output_format option or inherited from the input format) must be /// SRGB. It can be YCBCR420P if the input_format is also the same. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Mediapipe.ImageFormat.Types.Format OutputFormat { get { if ((_hasBits0 & 8) != 0) { return outputFormat_; } else { return OutputFormatDefaultValue; } } set { _hasBits0 |= 8; outputFormat_ = value; } } /// <summary>Gets whether the "output_format" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasOutputFormat { get { return (_hasBits0 & 8) != 0; } } /// <summary>Clears the value of the "output_format" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearOutputFormat() { _hasBits0 &= ~8; } /// <summary>Field number for the "algorithm" field.</summary> public const int AlgorithmFieldNumber = 7; private readonly static global::Mediapipe.ScaleImageCalculatorOptions.Types.ScaleAlgorithm AlgorithmDefaultValue = global::Mediapipe.ScaleImageCalculatorOptions.Types.ScaleAlgorithm.Default; private global::Mediapipe.ScaleImageCalculatorOptions.Types.ScaleAlgorithm algorithm_; /// <summary> /// The upscaling algorithm to use. The default is to use CUBIC. Note that /// downscaling unconditionally uses DDA; see image_processing:: /// AffineGammaResizer for documentation. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Mediapipe.ScaleImageCalculatorOptions.Types.ScaleAlgorithm Algorithm { get { if ((_hasBits0 & 16) != 0) { return algorithm_; } else { return AlgorithmDefaultValue; } } set { _hasBits0 |= 16; algorithm_ = value; } } /// <summary>Gets whether the "algorithm" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasAlgorithm { get { return (_hasBits0 & 16) != 0; } } /// <summary>Clears the value of the "algorithm" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearAlgorithm() { _hasBits0 &= ~16; } /// <summary>Field number for the "alignment_boundary" field.</summary> public const int AlignmentBoundaryFieldNumber = 8; private readonly static int AlignmentBoundaryDefaultValue = 16; private int alignmentBoundary_; /// <summary> /// The output image will have this alignment. If set to zero, then /// any alignment could be used. If set to one, the output image will /// be stored contiguously. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int AlignmentBoundary { get { if ((_hasBits0 & 32) != 0) { return alignmentBoundary_; } else { return AlignmentBoundaryDefaultValue; } } set { _hasBits0 |= 32; alignmentBoundary_ = value; } } /// <summary>Gets whether the "alignment_boundary" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasAlignmentBoundary { get { return (_hasBits0 & 32) != 0; } } /// <summary>Clears the value of the "alignment_boundary" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearAlignmentBoundary() { _hasBits0 &= ~32; } /// <summary>Field number for the "set_alignment_padding" field.</summary> public const int SetAlignmentPaddingFieldNumber = 9; private readonly static bool SetAlignmentPaddingDefaultValue = true; private bool setAlignmentPadding_; /// <summary> /// Set the alignment padding area to deterministic values (as opposed /// to possibly leaving it as uninitialized memory). The padding is /// the space between the pixel values in a row and the end of the row /// (which may be different due to alignment requirements on the length /// of a row). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool SetAlignmentPadding { get { if ((_hasBits0 & 64) != 0) { return setAlignmentPadding_; } else { return SetAlignmentPaddingDefaultValue; } } set { _hasBits0 |= 64; setAlignmentPadding_ = value; } } /// <summary>Gets whether the "set_alignment_padding" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasSetAlignmentPadding { get { return (_hasBits0 & 64) != 0; } } /// <summary>Clears the value of the "set_alignment_padding" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearSetAlignmentPadding() { _hasBits0 &= ~64; } /// <summary>Field number for the "OBSOLETE_skip_linear_rgb_conversion" field.</summary> public const int OBSOLETESkipLinearRgbConversionFieldNumber = 10; private readonly static bool OBSOLETESkipLinearRgbConversionDefaultValue = false; private bool oBSOLETESkipLinearRgbConversion_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool OBSOLETESkipLinearRgbConversion { get { if ((_hasBits0 & 128) != 0) { return oBSOLETESkipLinearRgbConversion_; } else { return OBSOLETESkipLinearRgbConversionDefaultValue; } } set { _hasBits0 |= 128; oBSOLETESkipLinearRgbConversion_ = value; } } /// <summary>Gets whether the "OBSOLETE_skip_linear_rgb_conversion" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasOBSOLETESkipLinearRgbConversion { get { return (_hasBits0 & 128) != 0; } } /// <summary>Clears the value of the "OBSOLETE_skip_linear_rgb_conversion" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearOBSOLETESkipLinearRgbConversion() { _hasBits0 &= ~128; } /// <summary>Field number for the "post_sharpening_coefficient" field.</summary> public const int PostSharpeningCoefficientFieldNumber = 11; private readonly static float PostSharpeningCoefficientDefaultValue = 0F; private float postSharpeningCoefficient_; /// <summary> /// Applies sharpening for downscaled images as post-processing. See /// image_processing::AffineGammaResizer for documentation. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public float PostSharpeningCoefficient { get { if ((_hasBits0 & 256) != 0) { return postSharpeningCoefficient_; } else { return PostSharpeningCoefficientDefaultValue; } } set { _hasBits0 |= 256; postSharpeningCoefficient_ = value; } } /// <summary>Gets whether the "post_sharpening_coefficient" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasPostSharpeningCoefficient { get { return (_hasBits0 & 256) != 0; } } /// <summary>Clears the value of the "post_sharpening_coefficient" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearPostSharpeningCoefficient() { _hasBits0 &= ~256; } /// <summary>Field number for the "input_format" field.</summary> public const int InputFormatFieldNumber = 12; private readonly static global::Mediapipe.ImageFormat.Types.Format InputFormatDefaultValue = global::Mediapipe.ImageFormat.Types.Format.Unknown; private global::Mediapipe.ImageFormat.Types.Format inputFormat_; /// <summary> /// If input_format is YCBCR420P, input packets contain a YUVImage. If /// input_format is a format other than YCBCR420P or is unset, input packets /// contain an ImageFrame. /// NOTE: in the current implementation, the input format (either specified /// in the input_format option or inferred from the input packets) must be /// SRGB or YCBCR420P. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Mediapipe.ImageFormat.Types.Format InputFormat { get { if ((_hasBits0 & 512) != 0) { return inputFormat_; } else { return InputFormatDefaultValue; } } set { _hasBits0 |= 512; inputFormat_ = value; } } /// <summary>Gets whether the "input_format" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasInputFormat { get { return (_hasBits0 & 512) != 0; } } /// <summary>Clears the value of the "input_format" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearInputFormat() { _hasBits0 &= ~512; } /// <summary>Field number for the "scale_to_multiple_of" field.</summary> public const int ScaleToMultipleOfFieldNumber = 13; private readonly static int ScaleToMultipleOfDefaultValue = 2; private int scaleToMultipleOf_; /// <summary> /// If set to 2, the target width and height will be rounded-down /// to the nearest even number. If set to any positive value other than 2, /// preserve_aspect_ratio must be false and the target width and height will be /// rounded-down to multiples of the given value. If set to any value less than /// 1, it will be treated like 1. /// NOTE: If set to an odd number, the output format must be SRGB. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int ScaleToMultipleOf { get { if ((_hasBits0 & 1024) != 0) { return scaleToMultipleOf_; } else { return ScaleToMultipleOfDefaultValue; } } set { _hasBits0 |= 1024; scaleToMultipleOf_ = value; } } /// <summary>Gets whether the "scale_to_multiple_of" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasScaleToMultipleOf { get { return (_hasBits0 & 1024) != 0; } } /// <summary>Clears the value of the "scale_to_multiple_of" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearScaleToMultipleOf() { _hasBits0 &= ~1024; } /// <summary>Field number for the "use_bt709" field.</summary> public const int UseBt709FieldNumber = 14; private readonly static bool UseBt709DefaultValue = false; private bool useBt709_; /// <summary> /// If true, assume the input YUV is BT.709 (this is the HDTV standard, so most /// content is likely using it). If false use the previous assumption of BT.601 /// (mid-80s standard). Ideally this information should be contained in the /// input YUV Frame, but as of 02/06/2019, it's not. Once this info is baked /// in, this flag becomes useless. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool UseBt709 { get { if ((_hasBits0 & 2048) != 0) { return useBt709_; } else { return UseBt709DefaultValue; } } set { _hasBits0 |= 2048; useBt709_ = value; } } /// <summary>Gets whether the "use_bt709" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasUseBt709 { get { return (_hasBits0 & 2048) != 0; } } /// <summary>Clears the value of the "use_bt709" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearUseBt709() { _hasBits0 &= ~2048; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as ScaleImageCalculatorOptions); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(ScaleImageCalculatorOptions other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (TargetWidth != other.TargetWidth) return false; if (TargetHeight != other.TargetHeight) return false; if (TargetMaxArea != other.TargetMaxArea) return false; if (PreserveAspectRatio != other.PreserveAspectRatio) return false; if (MinAspectRatio != other.MinAspectRatio) return false; if (MaxAspectRatio != other.MaxAspectRatio) return false; if (OutputFormat != other.OutputFormat) return false; if (Algorithm != other.Algorithm) return false; if (AlignmentBoundary != other.AlignmentBoundary) return false; if (SetAlignmentPadding != other.SetAlignmentPadding) return false; if (OBSOLETESkipLinearRgbConversion != other.OBSOLETESkipLinearRgbConversion) return false; if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(PostSharpeningCoefficient, other.PostSharpeningCoefficient)) return false; if (InputFormat != other.InputFormat) return false; if (ScaleToMultipleOf != other.ScaleToMultipleOf) return false; if (UseBt709 != other.UseBt709) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (HasTargetWidth) hash ^= TargetWidth.GetHashCode(); if (HasTargetHeight) hash ^= TargetHeight.GetHashCode(); if (HasTargetMaxArea) hash ^= TargetMaxArea.GetHashCode(); if (HasPreserveAspectRatio) hash ^= PreserveAspectRatio.GetHashCode(); if (HasMinAspectRatio) hash ^= MinAspectRatio.GetHashCode(); if (HasMaxAspectRatio) hash ^= MaxAspectRatio.GetHashCode(); if (HasOutputFormat) hash ^= OutputFormat.GetHashCode(); if (HasAlgorithm) hash ^= Algorithm.GetHashCode(); if (HasAlignmentBoundary) hash ^= AlignmentBoundary.GetHashCode(); if (HasSetAlignmentPadding) hash ^= SetAlignmentPadding.GetHashCode(); if (HasOBSOLETESkipLinearRgbConversion) hash ^= OBSOLETESkipLinearRgbConversion.GetHashCode(); if (HasPostSharpeningCoefficient) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(PostSharpeningCoefficient); if (HasInputFormat) hash ^= InputFormat.GetHashCode(); if (HasScaleToMultipleOf) hash ^= ScaleToMultipleOf.GetHashCode(); if (HasUseBt709) hash ^= UseBt709.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (HasTargetWidth) { output.WriteRawTag(8); output.WriteInt32(TargetWidth); } if (HasTargetHeight) { output.WriteRawTag(16); output.WriteInt32(TargetHeight); } if (HasPreserveAspectRatio) { output.WriteRawTag(24); output.WriteBool(PreserveAspectRatio); } if (HasMinAspectRatio) { output.WriteRawTag(34); output.WriteString(MinAspectRatio); } if (HasMaxAspectRatio) { output.WriteRawTag(42); output.WriteString(MaxAspectRatio); } if (HasOutputFormat) { output.WriteRawTag(48); output.WriteEnum((int) OutputFormat); } if (HasAlgorithm) { output.WriteRawTag(56); output.WriteEnum((int) Algorithm); } if (HasAlignmentBoundary) { output.WriteRawTag(64); output.WriteInt32(AlignmentBoundary); } if (HasSetAlignmentPadding) { output.WriteRawTag(72); output.WriteBool(SetAlignmentPadding); } if (HasOBSOLETESkipLinearRgbConversion) { output.WriteRawTag(80); output.WriteBool(OBSOLETESkipLinearRgbConversion); } if (HasPostSharpeningCoefficient) { output.WriteRawTag(93); output.WriteFloat(PostSharpeningCoefficient); } if (HasInputFormat) { output.WriteRawTag(96); output.WriteEnum((int) InputFormat); } if (HasScaleToMultipleOf) { output.WriteRawTag(104); output.WriteInt32(ScaleToMultipleOf); } if (HasUseBt709) { output.WriteRawTag(112); output.WriteBool(UseBt709); } if (HasTargetMaxArea) { output.WriteRawTag(120); output.WriteInt32(TargetMaxArea); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (HasTargetWidth) { output.WriteRawTag(8); output.WriteInt32(TargetWidth); } if (HasTargetHeight) { output.WriteRawTag(16); output.WriteInt32(TargetHeight); } if (HasPreserveAspectRatio) { output.WriteRawTag(24); output.WriteBool(PreserveAspectRatio); } if (HasMinAspectRatio) { output.WriteRawTag(34); output.WriteString(MinAspectRatio); } if (HasMaxAspectRatio) { output.WriteRawTag(42); output.WriteString(MaxAspectRatio); } if (HasOutputFormat) { output.WriteRawTag(48); output.WriteEnum((int) OutputFormat); } if (HasAlgorithm) { output.WriteRawTag(56); output.WriteEnum((int) Algorithm); } if (HasAlignmentBoundary) { output.WriteRawTag(64); output.WriteInt32(AlignmentBoundary); } if (HasSetAlignmentPadding) { output.WriteRawTag(72); output.WriteBool(SetAlignmentPadding); } if (HasOBSOLETESkipLinearRgbConversion) { output.WriteRawTag(80); output.WriteBool(OBSOLETESkipLinearRgbConversion); } if (HasPostSharpeningCoefficient) { output.WriteRawTag(93); output.WriteFloat(PostSharpeningCoefficient); } if (HasInputFormat) { output.WriteRawTag(96); output.WriteEnum((int) InputFormat); } if (HasScaleToMultipleOf) { output.WriteRawTag(104); output.WriteInt32(ScaleToMultipleOf); } if (HasUseBt709) { output.WriteRawTag(112); output.WriteBool(UseBt709); } if (HasTargetMaxArea) { output.WriteRawTag(120); output.WriteInt32(TargetMaxArea); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (HasTargetWidth) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(TargetWidth); } if (HasTargetHeight) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(TargetHeight); } if (HasTargetMaxArea) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(TargetMaxArea); } if (HasPreserveAspectRatio) { size += 1 + 1; } if (HasMinAspectRatio) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MinAspectRatio); } if (HasMaxAspectRatio) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MaxAspectRatio); } if (HasOutputFormat) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) OutputFormat); } if (HasAlgorithm) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Algorithm); } if (HasAlignmentBoundary) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(AlignmentBoundary); } if (HasSetAlignmentPadding) { size += 1 + 1; } if (HasOBSOLETESkipLinearRgbConversion) { size += 1 + 1; } if (HasPostSharpeningCoefficient) { size += 1 + 4; } if (HasInputFormat) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) InputFormat); } if (HasScaleToMultipleOf) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(ScaleToMultipleOf); } if (HasUseBt709) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(ScaleImageCalculatorOptions other) { if (other == null) { return; } if (other.HasTargetWidth) { TargetWidth = other.TargetWidth; } if (other.HasTargetHeight) { TargetHeight = other.TargetHeight; } if (other.HasTargetMaxArea) { TargetMaxArea = other.TargetMaxArea; } if (other.HasPreserveAspectRatio) { PreserveAspectRatio = other.PreserveAspectRatio; } if (other.HasMinAspectRatio) { MinAspectRatio = other.MinAspectRatio; } if (other.HasMaxAspectRatio) { MaxAspectRatio = other.MaxAspectRatio; } if (other.HasOutputFormat) { OutputFormat = other.OutputFormat; } if (other.HasAlgorithm) { Algorithm = other.Algorithm; } if (other.HasAlignmentBoundary) { AlignmentBoundary = other.AlignmentBoundary; } if (other.HasSetAlignmentPadding) { SetAlignmentPadding = other.SetAlignmentPadding; } if (other.HasOBSOLETESkipLinearRgbConversion) { OBSOLETESkipLinearRgbConversion = other.OBSOLETESkipLinearRgbConversion; } if (other.HasPostSharpeningCoefficient) { PostSharpeningCoefficient = other.PostSharpeningCoefficient; } if (other.HasInputFormat) { InputFormat = other.InputFormat; } if (other.HasScaleToMultipleOf) { ScaleToMultipleOf = other.ScaleToMultipleOf; } if (other.HasUseBt709) { UseBt709 = other.UseBt709; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { TargetWidth = input.ReadInt32(); break; } case 16: { TargetHeight = input.ReadInt32(); break; } case 24: { PreserveAspectRatio = input.ReadBool(); break; } case 34: { MinAspectRatio = input.ReadString(); break; } case 42: { MaxAspectRatio = input.ReadString(); break; } case 48: { OutputFormat = (global::Mediapipe.ImageFormat.Types.Format) input.ReadEnum(); break; } case 56: { Algorithm = (global::Mediapipe.ScaleImageCalculatorOptions.Types.ScaleAlgorithm) input.ReadEnum(); break; } case 64: { AlignmentBoundary = input.ReadInt32(); break; } case 72: { SetAlignmentPadding = input.ReadBool(); break; } case 80: { OBSOLETESkipLinearRgbConversion = input.ReadBool(); break; } case 93: { PostSharpeningCoefficient = input.ReadFloat(); break; } case 96: { InputFormat = (global::Mediapipe.ImageFormat.Types.Format) input.ReadEnum(); break; } case 104: { ScaleToMultipleOf = input.ReadInt32(); break; } case 112: { UseBt709 = input.ReadBool(); break; } case 120: { TargetMaxArea = input.ReadInt32(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { TargetWidth = input.ReadInt32(); break; } case 16: { TargetHeight = input.ReadInt32(); break; } case 24: { PreserveAspectRatio = input.ReadBool(); break; } case 34: { MinAspectRatio = input.ReadString(); break; } case 42: { MaxAspectRatio = input.ReadString(); break; } case 48: { OutputFormat = (global::Mediapipe.ImageFormat.Types.Format) input.ReadEnum(); break; } case 56: { Algorithm = (global::Mediapipe.ScaleImageCalculatorOptions.Types.ScaleAlgorithm) input.ReadEnum(); break; } case 64: { AlignmentBoundary = input.ReadInt32(); break; } case 72: { SetAlignmentPadding = input.ReadBool(); break; } case 80: { OBSOLETESkipLinearRgbConversion = input.ReadBool(); break; } case 93: { PostSharpeningCoefficient = input.ReadFloat(); break; } case 96: { InputFormat = (global::Mediapipe.ImageFormat.Types.Format) input.ReadEnum(); break; } case 104: { ScaleToMultipleOf = input.ReadInt32(); break; } case 112: { UseBt709 = input.ReadBool(); break; } case 120: { TargetMaxArea = input.ReadInt32(); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the ScaleImageCalculatorOptions message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { public enum ScaleAlgorithm { [pbr::OriginalName("DEFAULT")] Default = 0, [pbr::OriginalName("LINEAR")] Linear = 1, [pbr::OriginalName("CUBIC")] Cubic = 2, [pbr::OriginalName("AREA")] Area = 3, [pbr::OriginalName("LANCZOS")] Lanczos = 4, /// <summary> /// Option to disallow upscaling. /// </summary> [pbr::OriginalName("DEFAULT_WITHOUT_UPSCALE")] DefaultWithoutUpscale = 5, } } #endregion #region Extensions /// <summary>Container for extensions for other messages declared in the ScaleImageCalculatorOptions message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Extensions { public static readonly pb::Extension<global::Mediapipe.CalculatorOptions, global::Mediapipe.ScaleImageCalculatorOptions> Ext = new pb::Extension<global::Mediapipe.CalculatorOptions, global::Mediapipe.ScaleImageCalculatorOptions>(66237115, pb::FieldCodec.ForMessage(529896922, global::Mediapipe.ScaleImageCalculatorOptions.Parser)); } #endregion } #endregion } #endregion Designer generated code
41.950937
634
0.677696
[ "Apache-2.0" ]
SeedV/SeedAvatarStudio
Packages/com.github.homuler.mediapipe/Runtime/Scripts/Protobuf/Calculators/Image/ScaleImageCalculator.cs
47,027
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.Dsa.Tests { public class DSAOpenSslProvider : IDSAProvider { public DSA Create() { return new DSAOpenSsl(); } public DSA Create(int keySize) { return new DSAOpenSsl(keySize); } public bool SupportsFips186_3 => true; public bool SupportsKeyGeneration => true; } public partial class DSAFactory { private static readonly IDSAProvider s_provider = new DSAOpenSslProvider(); } }
25
83
0.64
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Security.Cryptography.OpenSsl/tests/DsaOpenSslProvider.cs
675
C#
namespace TeisterMask.Data { using Microsoft.EntityFrameworkCore; using TeisterMask.Data.Models; public class TeisterMaskContext : DbContext { public TeisterMaskContext() { } public TeisterMaskContext(DbContextOptions options) : base(options) { } public DbSet<Project> Projects { get; set; } public DbSet<Task> Tasks { get; set; } public DbSet<Employee> Employees { get; set; } public DbSet<EmployeeTask> EmployeesTasks { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder .UseSqlServer(Configuration.ConnectionString); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<EmployeeTask>(e => { e.HasKey(et => new { et.EmployeeId, et.TaskId }); }); } } }
27.526316
85
0.587954
[ "MIT" ]
Siafarikas/SoftUni
DB/ExamPrep/TeisterMask/Data/TeisterMaskContext.cs
1,048
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Boss : MonoBehaviour { public BossEye[] eyes = new BossEye[2]; public int currentEye = 0; public Enemy spawnable; public bool active = false; public float timeBetweenSpawns = 5.0f; public float timeSinceLastSpawn = 0.0f; // Use this for initialization public void Start() { } // Update is called once per frame public void Update() { timeSinceLastSpawn += Time.deltaTime; if(timeSinceLastSpawn > timeBetweenSpawns) { timeSinceLastSpawn -= timeBetweenSpawns; Enemy enemy = Instantiate<Enemy>(spawnable); switch(Random.Range(0, 4)) { case 0: enemy.transform.position = transform.position + new Vector3(0.0f, 2.0f, 0.0f); break; case 1: enemy.transform.position = transform.position + new Vector3(0.0f, -2.0f, 0.0f); break; case 2: enemy.transform.position = transform.position + new Vector3(2.0f, 0.0f, 0.0f); break; case 3: enemy.transform.position = transform.position + new Vector3(-2.0f, 0.0f, 0.0f); break; } enemy.currentRoom = eyes[0].currentRoom; } } public void ActivateBoss() { active = true; Game.instance.mainMusic.Stop(); Game.instance.bossMusic.Play(); SwapEyes(); } public void SwapEyes() { eyes[currentEye].Deactivate(); currentEye = 1 - currentEye; if (eyes[currentEye].health > 0) { eyes[currentEye].Activate(); } if (eyes[0].health <= 0 && eyes[1].health <= 0) { OnDeath(); } } public void OnDeath() { if(Game.instance) { Game.instance.StartNextLevel(); } } }
25.87013
106
0.540663
[ "MIT" ]
jamioflan/LD38
Assets/Scripts/Entities/Boss.cs
1,994
C#
// Copyright (c) 2017 Jan Pluskal, Dudek Jindrich // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using Netfox.Framework.Models.Snoopers; namespace Netfox.SnooperXchat.Models { /// <summary> /// Model of snooper export object. /// </summary> public class XChatSnooperExport : SnooperExportBase { public XChatSnooperExport() : base() { } //EF } }
33.884615
74
0.721907
[ "Apache-2.0" ]
mvondracek/NetfoxDetective
Framework/Snoopers/SnooperXchat/Models/XChatSnooperExport.cs
883
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AryuwatSystem.m_DataSet { using System; using System.Collections.Generic; public partial class BookingDoctor { public int ID { get; set; } public string DrID { get; set; } public string RoomID { get; set; } public Nullable<System.DateTime> DateBook { get; set; } public Nullable<System.DateTime> TimeStart { get; set; } public Nullable<System.DateTime> TimeEnd { get; set; } public string Duration { get; set; } public string Note { get; set; } public string BranchID { get; set; } public string ENSave { get; set; } public Nullable<System.DateTime> DateSave { get; set; } public Nullable<int> IDBookLink { get; set; } } }
38
85
0.552632
[ "Unlicense" ]
Krailit/Aryuwat_Nurse
AryuwatSystem/m_DataSet/BookingDoctor.cs
1,178
C#
using System; using System.Collections.Generic; using Comformation.IntrinsicFunctions; namespace Comformation.IoT1Click.Device { /// <summary> /// AWS::IoT1Click::Device /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot1click-device.html /// </summary> public class DeviceResource : ResourceBase { public class DeviceProperties { /// <summary> /// DeviceId /// The ID of the device, such as G030PX0312744DWM. /// Required: Yes /// Type: String /// Update requires: Replacement /// </summary> public Union<string, IntrinsicFunction> DeviceId { get; set; } /// <summary> /// Enabled /// A Boolean value indicating whether the device is enabled (true) or not (false). /// Required: Yes /// Type: Boolean /// Update requires: No interruption /// </summary> public Union<bool, IntrinsicFunction> Enabled { get; set; } } public string Type { get; } = "AWS::IoT1Click::Device"; public DeviceProperties Properties { get; } = new DeviceProperties(); } public static class DeviceAttributes { public static readonly ResourceAttribute<Union<string, IntrinsicFunction>> DeviceId = new ResourceAttribute<Union<string, IntrinsicFunction>>("DeviceId"); public static readonly ResourceAttribute<Union<bool, IntrinsicFunction>> Enabled = new ResourceAttribute<Union<bool, IntrinsicFunction>>("Enabled"); public static readonly ResourceAttribute<Union<string, IntrinsicFunction>> Arn = new ResourceAttribute<Union<string, IntrinsicFunction>>("Arn"); } }
36.916667
162
0.630361
[ "MIT" ]
stanb/Comformation
src/Comformation/Generated/IoT1Click/Device/DeviceResource.cs
1,772
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data; using SchoolProject.Database; namespace SchoolProject { public partial class frmShowLocation : Form { public static string locationId; LocationDAL locdalobj = new LocationDAL(); SqlConnection con = null; SqlCommand cmd = null; int x = 500, y = 600; public frmShowLocation() { InitializeComponent(); } private void frmShowLocation_Load(object sender, EventArgs e) { this.Top = 15; this.Left = 0; frmMainForm fmain = new frmMainForm(); frmAttendaceByLocation faatloc = new frmAttendaceByLocation(); // fmain.MdiChildren = this; // faatloc.MdiParent = fmain; // this.MdiChildren= // ShowLocationImageDataGridView1(); lblCountStudent.Text = Convert.ToString(locdalobj.CountRegistrationType("STUDENT")); lblCountFaculty.Text = Convert.ToString(locdalobj.CountRegistrationType("FACULTY")); lblCountHouseKeeping.Text = Convert.ToString(locdalobj.CountRegistrationType("HOUSE KEEPING")); lblCountGuests.Text = Convert.ToString(locdalobj.CountRegistrationType("GUEST")); ShowLocationImage(); } private void ShowLocationImageDataGridView1() { string cs = ConfigurationManager.ConnectionStrings["conn"].ConnectionString; con = new SqlConnection(cs); con.Open(); int cnt = 0; int countx = 10; int county = 10; int lcountx = 10; int lcounty = 120; cmd = new SqlCommand("Select LocationImage,Location_Id,LocationName from tblLocation", con); DataTable dt = new System.Data.DataTable(); cmd.CommandType = CommandType.Text; SqlDataReader sdr = cmd.ExecuteReader(); if (sdr.HasRows) while (sdr.Read()) { // DataGridView dgview = new DataGridView(); PictureBox eachPictureBox = new PictureBox(); int countp = panelLocation.Controls.OfType<PictureBox>().ToList().Count; //eachPictureBox.Location = new Point((100 * countp),cnt); eachPictureBox.Location = new Point(countx, county); string img = sdr["LocationImage"].ToString(); eachPictureBox.Image = Base64ToImage(img); eachPictureBox.Height = 100; eachPictureBox.Width = 150; eachPictureBox.Name = sdr["Location_Id"].ToString(); eachPictureBox.SizeMode = PictureBoxSizeMode.StretchImage; eachPictureBox.Click += eachPictureBox_Click; // dt.Rows.Add(eachPictureBox); Label lblName = new Label(); lblName.Click += lblName_Click; int countl = panelLocation.Controls.OfType<Label>().ToList().Count; lblName.Location = new Point(lcountx, lcounty); lblName.Text = sdr["LocationName"].ToString(); lblName.Name = sdr["Location_Id"].ToString(); dt.Rows.Add(lblName); cnt++; countx = countx + 50 + 150; lcountx = +lcountx + 50 + 150; if (cnt == 5) { countx = 10; lcountx = 10; lcounty = lcounty + 10 + 150; county = county + 10 + 150; } } // dataGridView1.DataSource = dt; } private void ShowLocationImageDataGridView() { string cs = ConfigurationManager.ConnectionStrings["conn"].ConnectionString; con = new SqlConnection(cs); con.Open(); int cnt = 0; int countx = 10; int county = 10; int lcountx = 10; int lcounty = 120; cmd = new SqlCommand("Select LocationImage,Location_Id,LocationName from tblLocation", con); cmd.CommandType = CommandType.Text; SqlDataReader sdr = cmd.ExecuteReader(); ListBox list = new ListBox(); if (sdr.HasRows) //{ // DataGridView dgview = new DataGridView(); // dgview.Height = 320; // dgview.Width = 970; // dgview.BackgroundColor = Color.WhiteSmoke; while (sdr.Read()) { // DataGridView dgview = new DataGridView(); PictureBox eachPictureBox = new PictureBox(); int countp = panelLocation.Controls.OfType<PictureBox>().ToList().Count; //eachPictureBox.Location = new Point((100 * countp),cnt); eachPictureBox.Location = new Point(countx, county); string img = sdr["LocationImage"].ToString(); eachPictureBox.Image = Base64ToImage(img); eachPictureBox.Height = 100; eachPictureBox.Width = 150; eachPictureBox.Name = sdr["Location_Id"].ToString(); eachPictureBox.SizeMode = PictureBoxSizeMode.StretchImage; eachPictureBox.Click += eachPictureBox_Click; // listBox1.Items.Add(eachPictureBox); Label lblName = new Label(); lblName.Click += lblName_Click; int countl = panelLocation.Controls.OfType<Label>().ToList().Count; lblName.Location = new Point(lcountx, lcounty); lblName.Text = sdr["LocationName"].ToString(); lblName.Name = sdr["Location_Id"].ToString(); // listBox1.Items.Add(lblName); cnt++; countx = countx + 50 + 150; lcountx = +lcountx + 50 + 150; if (cnt == 5) { countx = 10; lcountx = 10; lcounty = lcounty + 10 + 150; county = county + 10 + 150; } } } private void ShowLocationImage() { string cs = ConfigurationManager.ConnectionStrings["conn"].ConnectionString; con = new SqlConnection(cs); con.Open(); int cnt = 0; int countx = 10; int county = 10; int lcountx = 10; int lcounty = 120; cmd = new SqlCommand("Select LocationImage,Location_Id,LocationName from tblLocation", con); cmd.CommandType = CommandType.Text; SqlDataReader sdr = cmd.ExecuteReader(); if (sdr.HasRows) { DataGridView dgview = new DataGridView(); dgview.Height = 320; dgview.Width = 970; dgview.BackgroundColor = Color.WhiteSmoke; //ScrollBar vScrollBar1 = new VScrollBar(); //vScrollBar1.Dock = DockStyle.Right; //vScrollBar1.Scroll += (sender, e) => { panelLocation.VerticalScroll.Value = vScrollBar1.Value; }; //panelLocation.Controls.Add(vScrollBar1); while (sdr.Read()) { // DataGridView dgview = new DataGridView(); //PictureBox eachPictureBox = new PictureBox(); //int countp = panelLocation.Controls.OfType<PictureBox>().ToList().Count; ////eachPictureBox.Location = new Point((100 * countp),cnt); //eachPictureBox.Location = new Point(countx, county); //string img = sdr["LocationImage"].ToString(); //eachPictureBox.Image = Base64ToImage(img); //eachPictureBox.Height = 100; //eachPictureBox.Width = 150; //eachPictureBox.Name = sdr["Location_Id"].ToString(); //eachPictureBox.SizeMode = PictureBoxSizeMode.StretchImage; //eachPictureBox.Click += eachPictureBox_Click; //dgview.Controls.Add(eachPictureBox); //Label lblName = new Label(); //lblName.Click += lblName_Click; //int countl = panelLocation.Controls.OfType<Label>().ToList().Count; //lblName.Location = new Point(lcountx, lcounty); //lblName.Text = sdr["LocationName"].ToString(); //lblName.Name = sdr["Location_Id"].ToString(); //dgview.Controls.Add(lblName); //cnt++; //countx = countx + 50 + 150; //lcountx = +lcountx + 50 + 150; //if (cnt == 5) //{ // countx = 10; // lcountx = 10; // lcounty = lcounty + 10 + 150; // county = county + 10 + 150; //} PictureBox eachPictureBox = new PictureBox(); int countp = panelLocation.Controls.OfType<PictureBox>().ToList().Count; //eachPictureBox.Location = new Point((100 * countp),cnt); eachPictureBox.Location = new Point(countx, county); string img = sdr["LocationImage"].ToString(); eachPictureBox.Image = Base64ToImage(img); eachPictureBox.Height = 100; eachPictureBox.Width = 150; eachPictureBox.Name = sdr["Location_Id"].ToString(); eachPictureBox.SizeMode = PictureBoxSizeMode.StretchImage; eachPictureBox.Click += eachPictureBox_Click; panelLocation.Controls.Add(eachPictureBox); Label lblName = new Label(); lblName.Click += lblName_Click; int countl = panelLocation.Controls.OfType<Label>().ToList().Count; lblName.Location = new Point(lcountx, lcounty); lblName.Text = sdr["LocationName"].ToString(); lblName.Name = sdr["Location_Id"].ToString(); panelLocation.Controls.Add(lblName); cnt++; countx = countx + 50 + 150; lcountx = +lcountx + 50 + 150; if (cnt == 5) { cnt = 0; countx = 10; lcountx = 10; lcounty = lcounty + 10 + 150; county = county + 10 + 150; } } // panelLocation.Height = 800; //ScrollBar vScrollBar1 = new VScrollBar(); //vScrollBar1.Dock = DockStyle.Right; //vScrollBar1.Scroll += (sender, e) => { panelLocation.VerticalScroll.Value = vScrollBar1.Value; }; //panelLocation.Controls.Add(vScrollBar1); // panelLocation.Controls.Add(dgview); panelLocation.AutoScroll = false; panelLocation.HorizontalScroll.Enabled = false; panelLocation.HorizontalScroll.Visible = false; panelLocation.HorizontalScroll.Maximum = 0; panelLocation.AutoScroll = true; } } void eachPictureBox_Click(object sender, EventArgs e) { PictureBox picture = (PictureBox)sender; // MessageBox.Show(picture.Name.ToString()); frmShowLocation.locationId = picture.Name.ToString(); frmMainForm fmain = new frmMainForm(); // this.Hide(); frmAttendaceByLocation fattedance = new frmAttendaceByLocation(); fattedance.Top = 0; fattedance.Left = 0; //fattedance.MdiParent = fmain; fattedance.MdiParent = this.MdiParent; fattedance.Show(); } void lblName_Click(object sender, EventArgs e) { Label lbl = (Label)sender; // MessageBox.Show(lbl.Text.ToString()); // MessageBox.Show(lbl.Name.ToString()); // conn.msgErr(btn.Name.ToString()); frmShowLocation.locationId = lbl.Name.ToString(); frmMainForm fmain = new frmMainForm(); // this.Hide(); frmAttendaceByLocation fattedance = new frmAttendaceByLocation(); this.Top = 0; this.Left = 0; fattedance.MdiParent = this.MdiParent; // fattDeatails.MdiParent = this.MdiParent; fattedance.Show(); } public Image Base64ToImage(string base64String) { // Convert Base64 String to byte[] byte[] imageBytes = Convert.FromBase64String(base64String); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); // Convert byte[] to Image ms.Write(imageBytes, 0, imageBytes.Length); Image image = Image.FromStream(ms, true); return image; } private void btnExit_Click(object sender, EventArgs e) { this.Close(); } } }
42.849231
115
0.513787
[ "MIT" ]
ironboundmanzer/SP1
SchoolProject/frmShowLocation.cs
13,928
C#
//////////////////////////////////////////////////////////////////////////// // // Epoxy template source code. // Write your own copyright and note. // (You can use https://github.com/rubicon-oss/LicenseHeaderManager) // //////////////////////////////////////////////////////////////////////////// using Epoxy; using Epoxy.Synchronized; using System; using System.Collections.ObjectModel; using System.IO; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using EpoxyHello.Models; namespace EpoxyHello.ViewModels { [ViewModel] public sealed class MainWindowViewModel { public MainWindowViewModel() { this.Items = new ObservableCollection<ItemViewModel>(); // A handler for window loaded this.Ready = Command.Factory.CreateSync<RoutedEventArgs>(e => { this.IsEnabled = true; }); // A handler for fetch button this.Fetch = CommandFactory.Create(async () => { this.IsEnabled = false; try { // Uses Reddit API var reddits = await Reddit.FetchNewPostsAsync("r/aww"); this.Items.Clear(); static async ValueTask<ImageSource?> FetchImageAsync(Uri url) { try { var bitmap = new WriteableBitmap( BitmapFrame.Create(new MemoryStream(await Reddit.FetchImageAsync(url)))); bitmap.Freeze(); return bitmap; } // Some images will cause decoding error by WPF's BitmapFrame, so ignoring it. catch (FileFormatException) { return null; } } foreach (var reddit in reddits) { this.Items.Add(new ItemViewModel { Title = reddit.Title, Score = reddit.Score, Image = await FetchImageAsync(reddit.Url) }); } } finally { IsEnabled = true; } }); } public Command? Ready { get; private set; } public bool IsEnabled { get; private set; } public ObservableCollection<ItemViewModel>? Items { get; private set; } public Command? Fetch { get; private set; } } }
30.593407
105
0.446121
[ "Apache-2.0" ]
kekyo/Epoxy
templates/templates/EpoxyHello.Wpf/EpoxyHello/ViewModels/MainWindowViewModel.cs
2,786
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; namespace Sholo.HomeAssistant.Utilities { [PublicAPI] public static class AsyncEnumerableExtensions { public static async IAsyncEnumerable<T> WithEnforcedCancellation<T>( this IAsyncEnumerable<T> source, [EnumeratorCancellation] CancellationToken cancellationToken) { if (source == null) { throw new ArgumentNullException(nameof(source)); } cancellationToken.ThrowIfCancellationRequested(); await foreach (var item in source.WithCancellation(cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); yield return item; } } } }
28.4375
82
0.649451
[ "MIT" ]
scottt732/Sholo.HomeAssistant
Source/Sholo.HomeAssistant.Common/Utilities/AsyncEnumerableExtensions.cs
910
C#
using System.Text; using SAModels; namespace SAWebUI.Models { public class CustomerViewModel { public string Id { get; set; } public string Name { get; set; } public string Address { get; set; } public string Email { get; set; } public string Phone { get; set; } public CustomerViewModel(CustomerUser p_user) { StringBuilder sb = new(); sb.Append(p_user.FirstName ?? ""); sb.AppendFormat(" {0}", p_user.LastName ?? ""); Id = p_user.Id; Name = sb.ToString(); Address = p_user.Address != null ? p_user.Address.ToString() : "None"; Email = p_user.Email ?? "None"; Phone = p_user.PhoneNumber ?? "None"; } } }
31.958333
82
0.548892
[ "MIT" ]
210628-UTA-NET/sean-young-P1
SAWebUI/Models/CustomerViewModel.cs
767
C#
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using ILRuntime.CLR.Method; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Utils; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using LitJson; using SQLite4Unity3d; using UnityEngine; namespace BDFramework.Sql { /// <summary> /// 这里主要是为了和主工程隔离 /// hotfix专用的Sql Helper /// </summary> static public class SqliteHelper { // static private SQLiteService dbservice; //现在是热更层不负责加载,只负责使用 static public SQLiteService DB { get { if (dbservice == null || dbservice.IsClose) { dbservice = new SQLiteService(SqliteLoder.Connection); if (dbservice == null) { BDebug.LogError("Sql加载失败,请检查!"); } } return dbservice; } } /// <summary> /// 设置sql 缓存触发参数 /// </summary> /// <param name="triggerCacheNum"></param> /// <param name="triggerChacheTimer"></param> static public void SetSqlCacheTrigger(int triggerCacheNum = 5, float triggerChacheTimer = 0.05f) { DB.TableRuntime.EnableSqlCahce(triggerCacheNum,triggerChacheTimer); } #region ILRuntime 重定向 /// <summary> /// 注册SqliteHelper的ILR重定向 /// </summary> /// <param name="appdomain"></param> public unsafe static void RegisterCLRRedirection(ILRuntime.Runtime.Enviorment.AppDomain appdomain) { foreach (var mi in typeof(TableQueryForILRuntime).GetMethods()) { if (mi.Name == "FromAll" && mi.IsGenericMethodDefinition) { var param = mi.GetParameters(); if (param[0].ParameterType == typeof(string)) { appdomain.RegisterCLRMethodRedirection(mi, ReDirFromAll); } } } } /// <summary> /// 查询的重定向 /// </summary> /// <param name="intp"></param> /// <param name="esp"></param> /// <param name="mStack"></param> /// <param name="method"></param> /// <param name="isNewObj"></param> /// <returns></returns> public unsafe static StackObject* ReDirFromAll(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(esp, 1); ptr_of_this_method = ILIntepreter.Minus(esp, 1); // System.String selection = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, mStack)); intp.Free(ptr_of_this_method); var generic = method.GenericArguments[0]; //调用 var result_of_this_method = DB.GetTableRuntime().FormAll(generic.ReflectionType, selection); if (generic is CLRType) { // 创建clrTypeInstance var clrType = generic.TypeForCLR; var genericType = typeof(List<>).MakeGenericType(clrType); var retList = (IList)Activator.CreateInstance(genericType); for (int i = 0; i < result_of_this_method.Count; i++) { var obj = result_of_this_method[i]; retList.Add(obj); } return ILIntepreter.PushObject(__ret, mStack, retList); } else { // 转成ilrTypeInstance var retList = new List<ILTypeInstance>(result_of_this_method.Count); for (int i = 0; i < result_of_this_method.Count; i++) { var hotfixObj = result_of_this_method[i] as ILTypeInstance; retList.Add(hotfixObj); } return ILIntepreter.PushObject(__ret, mStack, retList); } } #endregion } }
34.867188
151
0.524087
[ "Apache-2.0" ]
yimengfan/BDFramework
Packages/com.popo.bdframework/Runtime/AssetsManager/Sql/SqliteHelper.cs
4,476
C#
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using BusinessExample.Core.Entities; using BusinessExample.Core.Interfaces; namespace BusinessExample.Infrastructure { public class IdentityService : IIdentityService { public Task<IdentityCheckResult> CheckIdentity(LoanApplication loanApplication) { switch (loanApplication.ApplicantName) { case var name when Regex.IsMatch(name, "unknown", RegexOptions.IgnoreCase): return Task.FromResult(IdentityCheckResult.IdentityNotFound); case var name when Regex.IsMatch(name, "unavailable", RegexOptions.IgnoreCase): return Task.FromResult(IdentityCheckResult.ServiceUnavailable); default: return Task.FromResult(IdentityCheckResult.IdentityFound); } } } }
33.413793
95
0.681115
[ "Apache-2.0" ]
MartinLRodrigues/FlowR
FlowR/Samples/BusinessExample/BusinessExample.Infrastructure/IdentityService.cs
971
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Orleans; namespace Contracts.Articles { public interface IArticleGrain : IGrainWithIntegerCompoundKey { //TODO: create grain implementation Task<Error> CreateArticle(Article article); Task<(Article Article, Error Error)> Get(); Task<Error> UpdateArticle(string title, string body, string description); Task<Error> AddFavorited(string user); Task<Error> RemoveFavorited(string user); } }
26.380952
81
0.712996
[ "MIT" ]
rizaramadan/Coduitorleans
src/Contracts/Articles/IArticleGrain.cs
556
C#
namespace GraphQL.Client.Tests.Common.Chat.Schema { public class ChatSchema : Types.Schema { public ChatSchema(IDependencyResolver resolver) : base(resolver) { Query = resolver.Resolve<ChatQuery>(); Mutation = resolver.Resolve<ChatMutation>(); Subscription = resolver.Resolve<ChatSubscriptions>(); } } }
27.714286
65
0.613402
[ "MIT" ]
Eilon/graphql-client
tests/GraphQL.Client.Tests.Common/Chat/Schema/ChatSchema.cs
388
C#
// <copyright file="PropertyType.cs" company="Fubar Development Junker"> // Copyright (c) 2016 Fubar Development Junker. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> namespace BeanIO.Internal.Parser { /// <summary> /// The property type /// </summary> internal enum PropertyType { /// <summary> /// The simple property type that cannot hold other properties /// </summary> Simple, /// <summary> /// The bean object property type with simple properties and other bean objects for attributes /// </summary> Complex, /// <summary> /// The collection property type used to create a collection of other properties /// </summary> Collection, /// <summary> /// The map property type /// </summary> Map, /// <summary> /// The array property type /// </summary> AggregationArray, /// <summary> /// The collection property type used to aggregate multiple occurrences of a single property /// </summary> AggregationCollection, /// <summary> /// The map property type used to aggregate multiple occurrences of key/value pairs /// </summary> AggregationMap, } }
28.530612
102
0.59299
[ "MIT" ]
FubarDevelopment/beanio-net
src/FubarDev.BeanIO/Internal/Parser/PropertyType.cs
1,398
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using StartFolio.DAL; using System.IO; using Microsoft.AspNetCore.Hosting; using StartFolio.Models; namespace StartFolio.Controllers { [Produces("application/json")] [Route("api/[controller]")] public class PageController : Controller { private readonly IPageRepository pageRepository; IHostingEnvironment appEnvironment; public PageController(IPageRepository repository, IHostingEnvironment environment) { pageRepository = repository; appEnvironment = environment; } // GET: api/Page [HttpGet] public async Task<IEnumerable<Page>> GetAsync() { return await pageRepository.GetPagesAsync(); } // GET: api/Page/5 [HttpGet("{position}")] public async Task<Page> GetPageAsync(int position) { return await pageRepository.GetPage(position); } // POST: api/Page/ [HttpPost] public async Task<IActionResult> UploadMultipart([FromForm]Page page, IFormFileCollection uploads) { if (page == null) { return BadRequest(); } foreach (var uploadedFile in uploads) { string oldFilename = uploadedFile.FileName; string newFilename = Guid.NewGuid().ToString() + "." + uploadedFile.FileName.Split('.').Last(); page.Details = page.Details.Replace(oldFilename, newFilename); // путь к папке Files string path = "/Images/" + newFilename; // сохраняем файл в папку Files в каталоге wwwroot using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create)) { await uploadedFile.CopyToAsync(fileStream); } } await pageRepository.AddPage(page); return Ok("Page succesfully added."); } // PUT: api/Page/Position [HttpPut("{currentPosition}/position")] public async Task<IActionResult> UpdatePositionAsync(int currentPosition, [FromForm]int newPosition ) { Page thisPage = await pageRepository.GetPage(currentPosition); Page swappedWithPage = await pageRepository.GetPage(newPosition); if (thisPage==null || swappedWithPage == null) { return Ok("Cannot move the page this way."); } await pageRepository.UpdatePagePosition(thisPage.Id, newPosition); await pageRepository.UpdatePagePosition(swappedWithPage.Id, currentPosition); return Ok("Page successfully moved."); } // PUT: api/Page/5/Details [HttpPut("{position}/Details")] public async Task<IActionResult> UpdateDetailsAsync(int position, [FromForm] string details, IFormFileCollection uploads) { foreach (var uploadedFile in uploads) { string oldFilename = uploadedFile.FileName; string newFilename = Guid.NewGuid().ToString() + "." + uploadedFile.FileName.Split('.').Last(); details = details.Replace(oldFilename, newFilename); // путь к папке Files string path = "/Images/" + newFilename; // сохраняем файл в папку Files в каталоге wwwroot using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create)) { await uploadedFile.CopyToAsync(fileStream); } } Page page = await pageRepository.GetPage(position); await pageRepository.UpdatePageDetails(page.Id, details); return Ok("Details successfully updated."); } // DELETE: api/Page/5 [HttpDelete("{position}")] public async Task<IActionResult> DeleteAsync(int position) { Page page = await pageRepository.GetPage(position); if (page == null) { return Ok("There is no page with such position."); } await pageRepository.RemovePage(page.Id); return Ok("Page successfully deleted."); } } }
36.795082
129
0.586545
[ "MIT" ]
IlyaSolovyov/angular-startfolio
StartFolio/Controllers/PageController.cs
4,567
C#
using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace Persistence.Migrations { public partial class AddEmailAuthenticator : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "AuthenticatorType", table: "Users", type: "int", nullable: false, defaultValue: 0); migrationBuilder.AlterColumn<DateTime>( name: "CreatedDate", table: "Invoices", type: "datetime2", nullable: false, defaultValue: new DateTime(2022, 2, 18, 13, 23, 42, 625, DateTimeKind.Local).AddTicks(5408), oldClrType: typeof(DateTime), oldType: "datetime2", oldDefaultValue: new DateTime(2022, 2, 16, 22, 46, 47, 552, DateTimeKind.Local).AddTicks(3327)); migrationBuilder.CreateTable( name: "EmailAuthenticators", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserId = table.Column<int>(type: "int", nullable: false), ActivationKey = table.Column<string>(type: "nvarchar(max)", nullable: false), IsVerified = table.Column<bool>(type: "bit", nullable: false) }, constraints: table => { table.PrimaryKey("PK_EmailAuthenticators", x => x.Id); table.ForeignKey( name: "FK_EmailAuthenticators_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.UpdateData( table: "Invoices", keyColumn: "Id", keyValue: 1, columns: new[] { "CreatedDate", "RentalEndDate", "RentalStartDate" }, values: new object[] { new DateTime(2022, 2, 18, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 20, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 18, 0, 0, 0, 0, DateTimeKind.Local) }); migrationBuilder.UpdateData( table: "Invoices", keyColumn: "Id", keyValue: 2, columns: new[] { "CreatedDate", "RentalEndDate", "RentalStartDate" }, values: new object[] { new DateTime(2022, 2, 18, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 20, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 18, 0, 0, 0, 0, DateTimeKind.Local) }); migrationBuilder.UpdateData( table: "Rentals", keyColumn: "Id", keyValue: 1, columns: new[] { "RentEndDate", "RentStartDate" }, values: new object[] { new DateTime(2022, 2, 20, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 18, 0, 0, 0, 0, DateTimeKind.Local) }); migrationBuilder.UpdateData( table: "Rentals", keyColumn: "Id", keyValue: 2, columns: new[] { "RentEndDate", "RentStartDate" }, values: new object[] { new DateTime(2022, 2, 20, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 18, 0, 0, 0, 0, DateTimeKind.Local) }); migrationBuilder.CreateIndex( name: "IX_EmailAuthenticators_UserId", table: "EmailAuthenticators", column: "UserId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "EmailAuthenticators"); migrationBuilder.DropColumn( name: "AuthenticatorType", table: "Users"); migrationBuilder.AlterColumn<DateTime>( name: "CreatedDate", table: "Invoices", type: "datetime2", nullable: false, defaultValue: new DateTime(2022, 2, 16, 22, 46, 47, 552, DateTimeKind.Local).AddTicks(3327), oldClrType: typeof(DateTime), oldType: "datetime2", oldDefaultValue: new DateTime(2022, 2, 18, 13, 23, 42, 625, DateTimeKind.Local).AddTicks(5408)); migrationBuilder.UpdateData( table: "Invoices", keyColumn: "Id", keyValue: 1, columns: new[] { "CreatedDate", "RentalEndDate", "RentalStartDate" }, values: new object[] { new DateTime(2022, 2, 16, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 18, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 16, 0, 0, 0, 0, DateTimeKind.Local) }); migrationBuilder.UpdateData( table: "Invoices", keyColumn: "Id", keyValue: 2, columns: new[] { "CreatedDate", "RentalEndDate", "RentalStartDate" }, values: new object[] { new DateTime(2022, 2, 16, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 18, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 16, 0, 0, 0, 0, DateTimeKind.Local) }); migrationBuilder.UpdateData( table: "Rentals", keyColumn: "Id", keyValue: 1, columns: new[] { "RentEndDate", "RentStartDate" }, values: new object[] { new DateTime(2022, 2, 18, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 16, 0, 0, 0, 0, DateTimeKind.Local) }); migrationBuilder.UpdateData( table: "Rentals", keyColumn: "Id", keyValue: 2, columns: new[] { "RentEndDate", "RentStartDate" }, values: new object[] { new DateTime(2022, 2, 18, 0, 0, 0, 0, DateTimeKind.Local), new DateTime(2022, 2, 16, 0, 0, 0, 0, DateTimeKind.Local) }); } } }
47.098485
218
0.521634
[ "MIT" ]
ahmet-cetinkaya/rentacar-project-backend-dotnet
src/rentACar/Persistence/Migrations/20220218102344_Add-EmailAuthenticator.cs
6,219
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("9.MatrixOfNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("9.MatrixOfNumbers")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("060fbb31-e44e-4ca6-8bc1-68d4e096fe09")] // 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.027027
84
0.745558
[ "MIT" ]
DVidenov/TelerikHomeworks
HomeworkLoops/9.MatrixOfNumbers/Properties/AssemblyInfo.cs
1,410
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: Chat.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; /// <summary>Holder for reflection information generated from Chat.proto</summary> public static partial class ChatReflection { #region Descriptor /// <summary>File descriptor for Chat.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ChatReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CgpDaGF0LnByb3RvGhBQdWJsaWNDaGF0LnByb3RvGhBQdWJsaWNEYXRhLnBy", "b3RvGhBQdWJsaWNIYWhhLnByb3RvIhEKD0NoYXRfcmZkclJSUlJlcSITChFD", "aGF0X3JmZHJSUlJSZXBseWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::PublicChatReflection.Descriptor, global::PublicDataReflection.Descriptor, global::PublicHahaReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Chat_rfdrRRRReq), global::Chat_rfdrRRRReq.Parser, null, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Chat_rfdrRRRReply), global::Chat_rfdrRRRReply.Parser, null, null, null, null, null) })); } #endregion } #region Messages public sealed partial class Chat_rfdrRRRReq : pb::IMessage<Chat_rfdrRRRReq> { private static readonly pb::MessageParser<Chat_rfdrRRRReq> _parser = new pb::MessageParser<Chat_rfdrRRRReq>(() => new Chat_rfdrRRRReq()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Chat_rfdrRRRReq> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::ChatReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Chat_rfdrRRRReq() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Chat_rfdrRRRReq(Chat_rfdrRRRReq other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Chat_rfdrRRRReq Clone() { return new Chat_rfdrRRRReq(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Chat_rfdrRRRReq); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Chat_rfdrRRRReq other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Chat_rfdrRRRReq other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } } } public sealed partial class Chat_rfdrRRRReply : pb::IMessage<Chat_rfdrRRRReply> { private static readonly pb::MessageParser<Chat_rfdrRRRReply> _parser = new pb::MessageParser<Chat_rfdrRRRReply>(() => new Chat_rfdrRRRReply()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Chat_rfdrRRRReply> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::ChatReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Chat_rfdrRRRReply() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Chat_rfdrRRRReply(Chat_rfdrRRRReply other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Chat_rfdrRRRReply Clone() { return new Chat_rfdrRRRReply(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Chat_rfdrRRRReply); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Chat_rfdrRRRReply other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Chat_rfdrRRRReply other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } } } #endregion #endregion Designer generated code
32.146939
161
0.728796
[ "MIT" ]
Addision/ProtoTool
Program/protobuf/Chat/Chat.cs
7,876
C#
using UnityEngine; namespace RTSLockstep { public class GridDebugger : MonoBehaviour { //Show the grid debugging? public bool Show; //type of grid to show... can be changed in runtime. Possibilities: Construct grid, LOS grid public GridType LeGridType; //Height of the grid //Size of each shown grid node public float LeHeight; [Range(.1f, .9f)] public float NodeSize = .4f; public enum GridType { Building, Pathfinding } private Vector3 nodeScale; void OnDrawGizmos() { if (Application.isPlaying && Show) { nodeScale = new Vector3(NodeSize, NodeSize, NodeSize); //Switch for which grid to show switch (this.LeGridType) { case GridType.Pathfinding: DrawPathfinding(); break; case GridType.Building: if (BuildGridAPI.MainBuildGrid.IsNotNull()) { DrawBuilding(); } break; } } } void DrawBuilding() { int length = BuildGridAPI.MainBuildGrid.GridLength; for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { BuildGridNode node = BuildGridAPI.MainBuildGrid.Grid[i, j]; if (node.Occupied) { Gizmos.color = Color.red; } else { Gizmos.color = Color.green; } Gizmos.DrawCube(BuildGridAPI.ToWorldPos(new Coordinate(i, j)).ToVector3(LeHeight), nodeScale); } } } void DrawPathfinding() { for (int i = 0; i < GridManager.GridSize; i++) { //Gets every pathfinding node and shows the draws a cube for the node GridNode node = GridManager.Grid[i]; //Color depends on whether or not the node is walkable //Red = Unwalkable, Green = Walkable if (node.Unwalkable) { Gizmos.color = Color.red; } else { Gizmos.color = Color.green; //I'm part colorblind... grey doesn't work very well with red } Gizmos.DrawCube(node.WorldPos.ToVector3(LeHeight), nodeScale); #if UNITY_EDITOR if (node.ClearanceSource != GridNode.DEFAULT_SOURCE) { UnityEditor.Handles.color = Color.red; UnityEditor.Handles.Label(node.WorldPos.ToVector3(LeHeight), "d" + node.ClearanceDegree.ToString()); } #endif } } } }
31.387755
120
0.454161
[ "MIT" ]
mrdav30/LockstepRTSEngine
Assets/Integration/Test/GridDebugger.cs
3,078
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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Runtime.Serialization; namespace org.apache.plc4net.exceptions { /// <summary> /// Exception raised when the connection to a /// PLC fails /// </summary> [Serializable] public class PlcConnectionException : PlcException { public PlcConnectionException() { } public PlcConnectionException(string message) : base(message) { } public PlcConnectionException(string message, Exception inner) : base(message, inner) { } protected PlcConnectionException( SerializationInfo info, StreamingContext context) : base(info, context) { } } }
30.4
93
0.684211
[ "Apache-2.0" ]
apache/incubator-plc4x
plc4net/api/api/exceptions/PlcConnectionException.cs
1,520
C#
using System; using System.Collections.Generic; using System.Linq; class MinMaxSumAverage { static void Main() { int n = int.Parse(Console.ReadLine()); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = int.Parse(Console.ReadLine()); } Dictionary<string, double> props = new Dictionary<string, double> { { "Sum", nums.Sum() }, { "Min", nums.Min() }, { "Max", nums.Max() }, { "Average", nums.Average() } }; foreach (var prop in props) { Console.WriteLine("{0} = {1}", prop.Key, prop.Value); } } }
22.16129
73
0.473071
[ "MIT" ]
origami99/SoftUni
02. ProgFund/Exercises/08. Dictionaries, Lambda and LINQ - Lab/03. Min, Max, Sum, Average/MinMaxSumAverage.cs
689
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("House")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("House")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("f80506a9-ae15-40e6-92e3-36ccf101f8c4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.243243
84
0.745283
[ "MIT" ]
donded/soft-uni-zadachi
drowingPic/House/Properties/AssemblyInfo.cs
1,381
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.ApplicationModel.Store.Preview.InstallControl { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] #endif public partial class AppInstallItem { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallType InstallType { get { throw new global::System.NotImplementedException("The member AppInstallType AppInstallItem.InstallType is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public bool IsUserInitiated { get { throw new global::System.NotImplementedException("The member bool AppInstallItem.IsUserInitiated is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public string PackageFamilyName { get { throw new global::System.NotImplementedException("The member string AppInstallItem.PackageFamilyName is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public string ProductId { get { throw new global::System.NotImplementedException("The member string AppInstallItem.ProductId is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::System.Collections.Generic.IReadOnlyList<global::Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem> Children { get { throw new global::System.NotImplementedException("The member IReadOnlyList<AppInstallItem> AppInstallItem.Children is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public bool ItemOperationsMightAffectOtherItems { get { throw new global::System.NotImplementedException("The member bool AppInstallItem.ItemOperationsMightAffectOtherItems is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public bool LaunchAfterInstall { get { throw new global::System.NotImplementedException("The member bool AppInstallItem.LaunchAfterInstall is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "bool AppInstallItem.LaunchAfterInstall"); } } #endif // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.ProductId.get // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.PackageFamilyName.get // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.InstallType.get // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.IsUserInitiated.get #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallStatus GetCurrentStatus() { throw new global::System.NotImplementedException("The member AppInstallStatus AppInstallItem.GetCurrentStatus() is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void Cancel() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "void AppInstallItem.Cancel()"); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void Pause() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "void AppInstallItem.Pause()"); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void Restart() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "void AppInstallItem.Restart()"); } #endif // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.Completed.add // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.Completed.remove // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.StatusChanged.add // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.StatusChanged.remove #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void Cancel( string correlationVector) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "void AppInstallItem.Cancel(string correlationVector)"); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void Pause( string correlationVector) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "void AppInstallItem.Pause(string correlationVector)"); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void Restart( string correlationVector) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "void AppInstallItem.Restart(string correlationVector)"); } #endif // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.Children.get // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.ItemOperationsMightAffectOtherItems.get // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.LaunchAfterInstall.get // Forced skipping of method Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem.LaunchAfterInstall.set #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public event global::Windows.Foundation.TypedEventHandler<global::Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem, object> Completed { [global::Uno.NotImplemented] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "event TypedEventHandler<AppInstallItem, object> AppInstallItem.Completed"); } [global::Uno.NotImplemented] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "event TypedEventHandler<AppInstallItem, object> AppInstallItem.Completed"); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public event global::Windows.Foundation.TypedEventHandler<global::Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem, object> StatusChanged { [global::Uno.NotImplemented] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "event TypedEventHandler<AppInstallItem, object> AppInstallItem.StatusChanged"); } [global::Uno.NotImplemented] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Store.Preview.InstallControl.AppInstallItem", "event TypedEventHandler<AppInstallItem, object> AppInstallItem.StatusChanged"); } } #endif } }
45.234637
230
0.78066
[ "Apache-2.0" ]
nv-ksavaria/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Store.Preview.InstallControl/AppInstallItem.cs
8,097
C#
/** * The MIT License * Copyright (c) 2016 Population Register Centre (VRK) * * 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 System; namespace PTV.Domain.Model.Models.Interfaces.OpenApi.V5 { /// <summary> /// OPEN API V5 - View Model of phone channel phone /// </summary> /// <seealso cref="PTV.Domain.Model.Models.Interfaces.OpenApi.IVmOpenApiPhoneSimpleVersionBase" /> public interface IV5VmOpenApiPhoneChannelPhone : IVmOpenApiPhoneSimpleVersionBase { /// <summary> /// Gets or sets the additional information. /// </summary> /// <value> /// The additional information. /// </value> //string AdditionalInformation { get; set; } /// <summary> /// Phone number type (Phone, Sms or Fax). /// </summary> string Type { get; set; } /// <summary> /// Gets or sets the type of the service charge. /// </summary> /// <value> /// The type of the service charge. /// </value> string ServiceChargeType { get; set; } /// <summary> /// Gets or sets the charge description. /// </summary> /// <value> /// The charge description. /// </value> string ChargeDescription { get; set; } } }
36.328125
102
0.660215
[ "MIT" ]
MikkoVirenius/ptv-1.7
src/PTV.Domain.Model/Models/Interfaces/OpenApi/V5/IV5VmOpenApiPhoneChannelPhone.cs
2,327
C#
using System; using System.Runtime.InteropServices; namespace Antijank.Debugging { [StructLayout(LayoutKind.Sequential)] public struct COR_TYPEID : IEquatable<COR_TYPEID> { public ulong token1; public ulong token2; public override int GetHashCode() => (int) token1 + (int) token2; public override bool Equals(object obj) => obj is COR_TYPEID a && Equals(a); public bool Equals(COR_TYPEID other) => token1 == other.token1 && token2 == other.token2; public bool IsMethodTable() => token2 == 0; } }
19.413793
58
0.666075
[ "MIT" ]
JoeFwd/MnB2-Bannerlord-CommunityPatch
tools/Antijank.Debugger/Debugging/CorDebug/COR_TYPEID.cs
563
C#
using Microsoft.AspNetCore.Identity; using Abp.Authorization; using Abp.Authorization.Users; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Zero.Configuration; using TinTucCongNghe.Authorization.Roles; using TinTucCongNghe.Authorization.Users; using TinTucCongNghe.MultiTenancy; namespace TinTucCongNghe.Authorization { public class LogInManager : AbpLogInManager<Tenant, Role, User> { public LogInManager( UserManager userManager, IMultiTenancyConfig multiTenancyConfig, IRepository<Tenant> tenantRepository, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager, IRepository<UserLoginAttempt, long> userLoginAttemptRepository, IUserManagementConfig userManagementConfig, IIocResolver iocResolver, IPasswordHasher<User> passwordHasher, RoleManager roleManager, UserClaimsPrincipalFactory claimsPrincipalFactory) : base( userManager, multiTenancyConfig, tenantRepository, unitOfWorkManager, settingManager, userLoginAttemptRepository, userManagementConfig, iocResolver, passwordHasher, roleManager, claimsPrincipalFactory) { } } }
33.391304
76
0.64388
[ "MIT" ]
nmsdzbmt/TinTucCongNghe-Angular-ABP
aspnet-core/src/TinTucCongNghe.Core/Authorization/LoginManager.cs
1,538
C#
using UnityEngine; /** Shimmy a script to rotate and/or shimmy an object * Matthew Vecchio for VOXON * v 1.0 * */ namespace Voxon.Examples.Animation { public class Shimmy : MonoBehaviour { [Tooltip("The speed of rotation 100 is default. Value are 0 - infinity")] public float speed = 100; public enum Direction { NONE, LEFT, RIGHT, UP, DOWN, FORWARD, BACKWARD, } [Tooltip("The direction you wish the object to rotate")] public Direction directionSelect; [Tooltip("The 2nd direction you wish the object to rotate")] public Direction directionSelectSub; [Tooltip("Enable this to have the object reverse its direction after a set point")] public bool directionSwitch; [Tooltip("The first point to switch the direction of the object. Value is between 0 and 1")] public float changeThreshold1 = 0.5f; [Tooltip("The second point to switch the direction of the object. Value is between 0 and 1")] public float changeThreshold2 = 0.5f; // Update is called once per frame void Update() { if (directionSwitch) { switch (directionSelect) { case Direction.RIGHT: if (transform.rotation.x > changeThreshold1) { directionSelect = Direction.LEFT; } break; case Direction.LEFT: if (transform.rotation.x < -changeThreshold2) { directionSelect = Direction.RIGHT; } break; case Direction.UP: if (transform.rotation.y > changeThreshold1) { directionSelect = Direction.DOWN; } break; case Direction.DOWN: if (transform.rotation.y < -changeThreshold2) { directionSelect = Direction.UP; } break; case Direction.FORWARD: if (transform.rotation.z > changeThreshold1) { directionSelect = Direction.BACKWARD; } break; case Direction.BACKWARD: if (transform.rotation.z < -changeThreshold2) { directionSelect = Direction.FORWARD; } break; } switch (directionSelectSub) { case Direction.RIGHT: if (transform.rotation.x > changeThreshold1) { directionSelectSub = Direction.LEFT; } break; case Direction.LEFT: if (transform.rotation.x < -changeThreshold2) { directionSelectSub = Direction.RIGHT; } break; case Direction.UP: if (transform.rotation.y > changeThreshold1) { directionSelectSub = Direction.DOWN; } break; case Direction.DOWN: if (transform.rotation.y < -changeThreshold2) { directionSelectSub = Direction.UP; } break; case Direction.FORWARD: if (transform.rotation.z > changeThreshold1) { directionSelectSub = Direction.BACKWARD; } break; case Direction.BACKWARD: if (transform.rotation.z < -changeThreshold2) { directionSelectSub = Direction.FORWARD; } break; } } switch (directionSelect) { case Direction.RIGHT: transform.Rotate(speed * Time.deltaTime * Vector3.right); break; case Direction.LEFT: transform.Rotate(speed * Time.deltaTime * Vector3.left); break; case Direction.UP: transform.Rotate(speed * Time.deltaTime * Vector3.up); break; case Direction.DOWN: transform.Rotate(speed * Time.deltaTime * Vector3.down); break; case Direction.FORWARD: transform.Rotate(speed * Time.deltaTime * Vector3.forward); break; case Direction.BACKWARD: transform.Rotate(speed * Time.deltaTime * Vector3.back); break; } switch (directionSelectSub) { case Direction.RIGHT: transform.Rotate(speed * Time.deltaTime * Vector3.right); break; case Direction.LEFT: transform.Rotate(speed * Time.deltaTime * Vector3.left); break; case Direction.UP: transform.Rotate(speed * Time.deltaTime * Vector3.up); break; case Direction.DOWN: transform.Rotate(speed * Time.deltaTime * Vector3.down); break; case Direction.FORWARD: transform.Rotate(speed * Time.deltaTime * Vector3.forward); break; case Direction.BACKWARD: transform.Rotate(speed * Time.deltaTime * Vector3.back); break; } } } }
34.392473
101
0.4277
[ "MIT" ]
lee1761/3D-avatar
3D chatbot/Assets/Voxon/Examples/Scripts/Animation/Shimmy.cs
6,399
C#
using System; using EditorUtils; using Microsoft.VisualStudio.Text.Editor; using Vim.Extensions; using Xunit; using Microsoft.VisualStudio.Text; namespace Vim.UnitTest { public abstract class MacroIntegrationTest : VimTestBase { protected IVimBuffer _vimBuffer; protected ITextBuffer _textBuffer; protected ITextView _textView; protected IVimGlobalSettings _globalSettings; internal char TestRegisterChar { get { return 'c'; } } internal Register TestRegister { get { return _vimBuffer.RegisterMap.GetRegister(TestRegisterChar); } } protected void Create(params string[] lines) { _textView = CreateTextView(lines); _textBuffer = _textView.TextBuffer; _vimBuffer = Vim.CreateVimBuffer(_textView); _vimBuffer.SwitchMode(ModeKind.Normal, ModeArgument.None); _globalSettings = _vimBuffer.LocalSettings.GlobalSettings; VimHost.FocusedTextView = _textView; } /// <summary> /// Make sure that on tear down we don't have a current transaction. Having one indicates /// we didn't close it and hence are killing undo in the ITextBuffer /// </summary> public override void Dispose() { base.Dispose(); var history = TextBufferUndoManagerProvider.GetTextBufferUndoManager(_textView.TextBuffer).TextBufferUndoHistory; Assert.Null(history.CurrentTransaction); } public sealed class RunMacroTest : MacroIntegrationTest { /// <summary> /// RunMacro a text insert back from a particular register /// </summary> [Fact] public void InsertText() { Create("world"); TestRegister.UpdateValue("ihello "); _vimBuffer.Process("@c"); Assert.Equal(ModeKind.Insert, _vimBuffer.ModeKind); Assert.Equal("hello world", _textView.GetLine(0).GetText()); } /// <summary> /// Replay a text insert back from a particular register which also contains an Escape key /// </summary> [Fact] public void InsertTextWithEsacpe() { Create("world"); TestRegister.UpdateValue("ihello ", VimKey.Escape); _vimBuffer.Process("@c"); Assert.Equal(ModeKind.Normal, _vimBuffer.ModeKind); Assert.Equal("hello world", _textView.GetLine(0).GetText()); } /// <summary> /// When running a macro make sure that we properly repeat the last command /// </summary> [Fact] public void RepeatLastCommand_DeleteWord() { Create("hello world again"); TestRegister.UpdateValue("."); _vimBuffer.Process("dw@c"); Assert.Equal("again", _textView.GetLine(0).GetText()); Assert.True(_vimBuffer.VimData.LastMacroRun.IsSome('c')); } /// <summary> /// When running the last macro with a count it should do the macro 'count' times /// </summary> [Fact] public void WithCount() { Create("cat", "dog", "bear"); TestRegister.UpdateValue("~", VimKey.Left, VimKey.Down); _vimBuffer.Process("2@c"); Assert.Equal("Cat", _textView.GetLine(0).GetText()); Assert.Equal("Dog", _textView.GetLine(1).GetText()); } /// <summary> /// This is actually a macro scenario called out in the Vim documentation. Namely the ability /// to build a numbered list by using a macro /// </summary> [Fact] public void NumberedList() { Create("1. Heading"); _vimBuffer.Process("qaYp"); _vimBuffer.Process(KeyNotationUtil.StringToKeyInput("<C-a>")); _vimBuffer.Process("q3@a"); for (var i = 0; i < 5; i++) { var line = String.Format("{0}. Heading", i + 1); Assert.Equal(line, _textView.GetLine(i).GetText()); } } /// <summary> /// If there is no focussed IVimBuffer then the macro playback should use the original IVimBuffer /// </summary> [Fact] public void NoFocusedView() { Create("world"); VimHost.FocusedTextView = null; TestRegister.UpdateValue("ihello "); _vimBuffer.Process("@c"); Assert.Equal(ModeKind.Insert, _vimBuffer.ModeKind); Assert.Equal("hello world", _textView.GetLine(0).GetText()); } /// <summary> /// Record a a text insert sequence followed by escape and play it back /// </summary> [Fact] public void InsertTextAndEscape() { Create(""); _vimBuffer.Process("qcidog"); _vimBuffer.Process(VimKey.Escape); _vimBuffer.Process("q"); Assert.Equal(ModeKind.Normal, _vimBuffer.ModeKind); _textView.MoveCaretTo(0); _vimBuffer.Process("@c"); Assert.Equal("dogdog", _textView.GetLine(0).GetText()); Assert.Equal(ModeKind.Normal, _vimBuffer.ModeKind); Assert.Equal(2, _textView.GetCaretPoint().Position); } /// <summary> /// When using an upper case register notation make sure the information is appended to /// the existing value. This can and will cause different behavior to occur /// </summary> [Fact] public void AppendValues() { Create(""); TestRegister.UpdateValue("iw"); _vimBuffer.Process("qCin"); _vimBuffer.Process(VimKey.Escape); _vimBuffer.Process("q"); Assert.Equal(ModeKind.Normal, _vimBuffer.ModeKind); _textView.SetText(""); _textView.MoveCaretTo(0); _vimBuffer.Process("@c"); Assert.Equal("win", _textView.GetLine(0).GetText()); Assert.Equal(ModeKind.Normal, _vimBuffer.ModeKind); Assert.Equal(2, _textView.GetCaretPoint().Position); } /// <summary> /// The ^ motion shouldn't register as an error at the start of the line and hence shouldn't /// cancel macro playback /// </summary> [Fact] public void StartOfLineAndChange() { Create(" cat dog"); _textView.MoveCaretTo(2); TestRegister.UpdateValue("^cwfish"); _vimBuffer.Process("@c"); Assert.Equal(0, VimHost.BeepCount); Assert.Equal(" fish dog", _textBuffer.GetLine(0).GetText()); Assert.Equal(6, _textView.GetCaretPoint()); } } public sealed class RunLastMacroTest : MacroIntegrationTest { /// <summary> /// When the word completion command is run and there are no completions this shouldn't /// register as an error and macro processing should continue /// </summary> [Fact] public void WordCompletionWithNoCompletion() { Create("z "); _textView.MoveCaretTo(1); TestRegister.UpdateValue( KeyNotationUtil.StringToKeyInput("i"), KeyNotationUtil.StringToKeyInput("<C-n>"), KeyNotationUtil.StringToKeyInput("s")); _vimBuffer.Process("@c"); Assert.Equal("zs ", _textView.GetLine(0).GetText()); } /// <summary> /// The @@ command should just read the char on the LastMacroRun value and replay /// that macro /// </summary> [Fact] public void ReadTheRegister() { Create(""); TestRegister.UpdateValue("iwin"); _vimBuffer.VimData.LastMacroRun = FSharpOption.Create('c'); _vimBuffer.Process("@@"); Assert.Equal("win", _textView.GetLine(0).GetText()); } } public sealed class ErrorTest : MacroIntegrationTest { /// <summary> /// Any command which produces an error should cause the macro to stop playback. One /// such command is trying to move right past the end of a line in insert mode /// </summary> [Fact] public void RightMove() { Create("cat", "cat"); _globalSettings.VirtualEdit = string.Empty; // ensure not 've=onemore' TestRegister.UpdateValue("llidone", VimKey.Escape); // Works because 'll' can get to the end of the line _vimBuffer.Process("@c"); Assert.Equal("cadonet", _textView.GetLine(0).GetText()); // Fails since the second 'l' fails _textView.MoveCaretToLine(1, 2); _vimBuffer.Process("@c"); Assert.Equal("cat", _textView.GetLine(1).GetText()); } /// <summary> /// Recursive macros which move to the end of the line shouldn't recurse infinitely /// </summary> [Fact] public void RecursiveRightMove() { Create("cat", "dog"); _globalSettings.VirtualEdit = string.Empty; // Ensure not 've=onemore' TestRegister.UpdateValue("l@c"); _vimBuffer.Process("@c"); Assert.Equal(2, _textView.GetCaretPoint().Position); } /// <summary> /// An up move at the start of the ITextBuffer should be an error and hence break /// a macro execution. But the results of the macro before the error should be /// still visible /// </summary> [Fact] public void UpMove() { Create("dog cat tree", "dog cat tree"); TestRegister.UpdateValue("lkdw"); _vimBuffer.Process("@c"); Assert.Equal("dog cat tree", _textView.GetLine(0).GetText()); Assert.Equal(1, _textView.GetCaretPoint().Position); } /// <summary> /// Attempting to move left before the beginining of the line should register as an error /// and hence kill macro playbakc /// </summary> [Fact] public void LeftMoveBeforeLine() { Create("dog cat tree"); _textView.MoveCaretTo(1); TestRegister.UpdateValue("hhhhdw"); _vimBuffer.Process("@c"); Assert.Equal(1, VimHost.BeepCount); Assert.Equal("dog cat tree", _textBuffer.GetLine(0).GetText()); Assert.Equal(0, _textView.GetCaretPoint()); } /// <summary> /// Attempting to move right after the end of the line should register as an error and /// hence kill macro playback /// </summary> [Fact] public void RightMoveAfterLine() { Create("dog cat"); _textView.MoveCaretTo(4); TestRegister.UpdateValue("lllllD"); _vimBuffer.Process("@c"); Assert.Equal(1, VimHost.BeepCount); Assert.Equal("dog cat", _textBuffer.GetLine(0).GetText()); Assert.Equal(6, _textView.GetCaretPoint()); } } public sealed class KeyMappingTest : MacroIntegrationTest { /// <summary> /// During macro evaluation what is typed is what should be recorded, not what is actually /// processed by the buffer. If the user types 'h' but it is mapped to 'u' then 'h' should /// be recorded /// </summary> [Fact] public void RecordTyped() { Create("cat dog"); _textView.MoveCaretTo(4); _vimBuffer.Process(":noremap l h", enter: true); _vimBuffer.Process("qfllq"); Assert.Equal(2, _textView.GetCaretPoint().Position); Assert.Equal("ll", _vimBuffer.GetRegister('f').StringValue); } /// <summary> /// The macro replay should consider mappings as they exist during the replay. If the mappings /// change after a record occurs then the behavior of the replay should demonstrate that /// change /// </summary> [Fact] public void ConsiderMappingDuringReplay() { Create("cat"); _vimBuffer.GetRegister('c').UpdateValue("ibig "); _vimBuffer.Process("@c"); Assert.Equal("big cat", _textBuffer.GetLine(0).GetText()); } [Fact] public void Issue1117() { Create("cat", "dog", "fish", "hello", "world", "ok"); _vimBuffer.Process(":noremap h k", enter: true); _vimBuffer.Process(":noremap k j", enter: true); _textView.MoveCaretToLine(5); _vimBuffer.Process("qfhhq@f"); Assert.Equal(1, _textView.GetCaretPoint().GetContainingLine().LineNumber); } } public sealed class MiscTest : MacroIntegrationTest { /// <summary> /// Running a macro which consists of several commands should cause only the last /// command to be the last command for the purpose of a 'repeat' operation /// </summary> [Fact] public void RepeatCommandAfterRunMacro() { Create("hello world", "kick tree"); TestRegister.UpdateValue("dwra"); _vimBuffer.Process("@c"); Assert.Equal("aorld", _textView.GetLine(0).GetText()); _textView.MoveCaretToLine(1); _vimBuffer.Process("."); Assert.Equal("aick tree", _textView.GetLine(1).GetText()); } /// <summary> /// A macro run with a count should execute as a single action. This includes undo behavior /// </summary> [Fact] public void UndoMacroWithCount() { Create("cat", "dog", "bear"); TestRegister.UpdateValue("~", VimKey.Left, VimKey.Down); _vimBuffer.Process("2@c"); _vimBuffer.Process("u"); Assert.Equal(0, _textView.GetCaretPoint().Position); Assert.Equal("cat", _textView.GetLine(0).GetText()); Assert.Equal("dog", _textView.GetLine(1).GetText()); } [Fact] public void RepeatLinked() { Create("cat", "dog", "bear"); _vimBuffer.ProcessNotation(@"qccwbat<Esc>q"); _textView.MoveCaretToLine(1); _vimBuffer.ProcessNotation(@"@c"); Assert.Equal("bat", _textBuffer.GetLine(1).GetText()); } } } }
40.929648
126
0.505034
[ "Apache-2.0" ]
L1031353632/VsVim
Test/VimCoreTest/MacroIntegrationTest.cs
16,292
C#
// // RuntimeBinderContext.cs // // Authors: // Marek Safar <marek.safar@gmail.com> // // Copyright (C) 2009 Novell, Inc (http://www.novell.com) // // 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. // #if DYNAMIC_SUPPORT using System; using System.Collections.Generic; using Compiler = Mono.CSharp; namespace PlayScript.RuntimeBinder { sealed class RuntimeBinderContext : Compiler.IMemberContext { readonly Compiler.ModuleContainer module; readonly Type callingType; readonly DynamicContext ctx; Compiler.TypeSpec callingTypeImported; public RuntimeBinderContext (DynamicContext ctx, Compiler.TypeSpec callingType) { this.ctx = ctx; this.module = ctx.Module; this.callingTypeImported = callingType; } public RuntimeBinderContext (DynamicContext ctx, Type callingType) { this.ctx = ctx; this.module = ctx.Module; this.callingType = callingType; } #region IMemberContext Members public Compiler.TypeSpec CurrentType { get { // // Delay importing of calling type to be compatible with .net // Some libraries are setting it to null which is invalid // but the NullReferenceException is thrown only when the context // is used and not during initialization // if (callingTypeImported == null && callingType != null) callingTypeImported = ctx.ImportType (callingType); return callingTypeImported; } } public Compiler.TypeParameters CurrentTypeParameters { get { throw new NotImplementedException (); } } public Compiler.MemberCore CurrentMemberDefinition { get { return null; } } public bool IsObsolete { get { // Always true to ignore obsolete attribute checks return true; } } public bool IsUnsafe { get { // Dynamic cannot be used with pointers return false; } } public bool IsStatic { get { throw new NotImplementedException (); } } public Compiler.ModuleContainer Module { get { return module; } } public string GetSignatureForError () { throw new NotImplementedException (); } public Compiler.ExtensionMethodCandidates LookupExtensionMethod (string name, int arity) { // No extension method lookup in this context return null; } public Compiler.FullNamedExpression LookupNamespaceOrType (string name, int arity, Mono.CSharp.LookupMode mode, Mono.CSharp.Location loc) { throw new NotImplementedException (); } public Compiler.FullNamedExpression LookupNamespaceAlias (string name) { // No namespace aliases in this context return null; } #endregion } } #endif
26.26087
139
0.727925
[ "Apache-2.0" ]
PlayScriptRedux/playscript
mcs/class/PlayScript.Dynamic/PlayScript/RuntimeBinder/RuntimeBinderContext.cs
3,624
C#
using System; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; #pragma warning disable 1591 namespace Nano.Demo.Mvc4 { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : HttpApplication { public override void Init() { NanoWebStartup.Start( this ); base.Init(); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register( GlobalConfiguration.Configuration ); FilterConfig.RegisterGlobalFilters( GlobalFilters.Filters ); RouteConfig.RegisterRoutes( RouteTable.Routes ); } protected void Application_BeginRequest( object sender, EventArgs e ) { } } }
27.30303
77
0.63485
[ "MIT" ]
revnique/Nano
src/Nano.Demo.Mvc4/Global.asax.cs
903
C#
using McMaster.Extensions.CommandLineUtils; using System; using System.IO; namespace dotnet_fs { [Command(Description = "Lists files and folders.")] class List { [Option(Description = "Folder path.")] public string Path { get; } = "."; public void OnExecute(IConsole console) { try { var dir = new DirectoryInfo(Path); foreach (var subdir in dir.GetDirectories()) { console.WriteLine($"{subdir.Name} (DIR)"); } foreach (var file in dir.GetFiles()) { console.WriteLine($"{file.Name}"); } } catch (Exception e) { console.WriteLine(e.Message); } } } }
23.611111
62
0.46
[ "MIT" ]
damirarh/dotnet-fs
dotnet-fs/List.cs
852
C#
using System; using CamundaClient; using CamundaClient.Dto; using CamundaClient.Services; namespace CamundaClientDemo { public class ChargeCardSubscriptionWorker : SubscriptionWorker { public string WorkderId { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override void ExecuteTask<T>(T task, IExternalTaskService externalTaskService) { var t = task as ExternalTask; Console.WriteLine("Processing task Id: " + t.Id); Console.WriteLine("Charging card"); externalTaskService.Complete(t.WorkerId, t.Id, null); } } }
30.045455
123
0.680787
[ "MIT" ]
nextgenadarsh/Camunda-Client-CSharp
CamundaClientDemo/ChargeCardTopicSubscriptionHandler.cs
663
C#
namespace FSH.WebApi.Domain.Lookup; public class InActiveReason : AuditableLookupEntity, IAggregateRoot { public string Name { get; set; } public string? Description { get; set; } public string InActiveStatusId { get; private set; } public virtual InActiveStatus InActiveStatus { get; private set; } = default!; public InActiveReason(string name, string? description, string inActiveStatusId) { Name = name; Description = description; InActiveStatusId = inActiveStatusId; } public InActiveReason Update(string name, string? description, string inActiveStatusId) { if (name is not null && Name?.Equals(name) is not true) Name = name; if (description is not null && Description?.Equals(description) is not true) Description = description; if (inActiveStatusId is not null && InActiveStatusId?.Equals(inActiveStatusId) is not true) InActiveStatusId = inActiveStatusId; return this; } }
42.652174
136
0.705403
[ "MIT" ]
SyahidahSuhaili/dotnet-webapi-boilerplate
src/Core/Domain/Lookup/InActiveReason.cs
983
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Septem.Notifications.Jobs.Config; namespace Septem.Notifications.Jobs.JobExecution; internal class ConcurrentQueueDispatcherJobStrategyHandler : ITaskExecuteStrategyHandler { private readonly ConcurrentQueueDispatcher _concurrentQueueDispatcher; public ConcurrentQueueDispatcherJobStrategyHandler(ConcurrentQueueDispatcher concurrentQueueDispatcher) { _concurrentQueueDispatcher = concurrentQueueDispatcher; } public bool CanHandle => _concurrentQueueDispatcher.CanAdd; public Task Handle(IEnumerable<Func<IServiceProvider, Task>> tasks) { _concurrentQueueDispatcher.Add(tasks); return Task.CompletedTask; } }
31.458333
107
0.802649
[ "MIT" ]
rasimismatulin/Septem.Utils
src/Septem.Notifications.Jobs/JobExecution/ConcurrentQueueDispatcherJobStrategyHandler.cs
757
C#
using CodeHub.Core.ViewModels.Repositories; namespace CodeHub.iOS.Views.Repositories { public class RepositoryForksView : BaseRepositoriesView<RepositoryForksViewModel> { public RepositoryForksView() { Title = "Forks"; } } }
19.714286
85
0.663043
[ "Apache-2.0" ]
gitter-badger/CodeHub
CodeHub.iOS/Views/Repositories/RepositoryForksView.cs
278
C#
namespace Walpy.VacancyApp.Server.Models.Web.Vacancy { public class IndexPageStatus { public bool Success { get; set; } public string Message { get; set; } } }
23.375
52
0.641711
[ "MIT" ]
allan-walpy/01-19-vacancy-task-1
src/Models/Web/Vacancy/IndexPageStatus.cs
187
C#
/* This file is a part of JustLogic product which is distributed under the BSD 3-clause "New" or "Revised" License Copyright (c) 2015. All rights reserved. Authors: Vladyslav Taranov. 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. * Neither the name of JustLogic 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 JustLogic.Core; using System.Collections.Generic; using UnityEngine; [UnitMenu("GUILayout/MinHeight")] [UnitFriendlyName("GUILayout.MinHeight")] [UnitUsage(typeof(GUILayoutOption), HideExpressionInActionsList = true)] public class JLGuiLayoutMinHeight : JLExpression { [Parameter(ExpressionType = typeof(System.Single))] public JLExpression MinHeight; public override object GetAnyResult(IExecutionContext context) { return GUILayout.MinHeight(MinHeight.GetResult<System.Single>(context)); } }
41.169811
80
0.784601
[ "BSD-3-Clause" ]
AqlaSolutions/JustLogic
Assets/JustLogicUnits/Generated/GUILayout/JLGuiLayoutMinHeight.cs
2,182
C#
using System.Collections.Generic; using Unity.NetCode; using Unity.NetCode.Editor; using static Unity.NetCode.Editor.GhostAuthoringComponentEditor; public class GhostOverrides : IGhostDefaultOverridesModifier { public void Modify(Dictionary<string, GhostAuthoringComponentEditor.GhostComponent> overrides) { overrides["Unity.Transforms.NonUniformScale"] = new GhostAuthoringComponentEditor.GhostComponent { name = "Unity.Transforms.NonUniformScale", attribute = new GhostComponentAttribute { PrefabType = GhostPrefabType.All, OwnerPredictedSendType = GhostSendType.All, SendDataForChildEntity = false }, fields = new GhostComponentField[] { new GhostComponentField { name = "Value", attribute = new GhostFieldAttribute{Quantization = 100, Interpolate = true} } }, entityIndex = 0 }; } public void ModifyAlwaysIncludedAssembly(HashSet<string> alwaysIncludedAssemblies) { alwaysIncludedAssemblies.Add("Unity.Transforms.NonUniformScale"); } public void ModifyTypeRegistry(TypeRegistry typeRegistry, string netCodeGenAssemblyPath) { } }
40.25
159
0.760426
[ "MIT" ]
mpcomplete/frenzy
Assets/Scripts/GhostOverrides/GhostOverrides.cs
1,129
C#
//----------------------------------------------------------------------- // <copyright file="PersistentFSMSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using Akka.Actor; using Akka.Persistence.Fsm; using FluentAssertions; using System; using System.Collections.Generic; using System.Threading.Tasks; using Hocon; using Xunit; using static Akka.Actor.FSMBase; namespace Akka.Persistence.Tests.Fsm { public class PersistentFSMSpec : PersistenceSpec { public PersistentFSMSpec() : base(Configuration("PersistentFSMSpec")) { } [Fact] public void PersistentFSM_must_has_function_as_regular_fsm() { var dummyReportActorRef = CreateTestProbe().Ref; var fsmRef = Sys.ActorOf(WebStoreCustomerFSM.Props(Name, dummyReportActorRef)); Watch(fsmRef); fsmRef.Tell(new SubscribeTransitionCallBack(TestActor)); var shirt = new Item("1", "Shirt", 59.99F); var shoes = new Item("2", "Shoes", 89.99F); var coat = new Item("3", "Coat", 119.99F); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(shirt)); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(shoes)); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(coat)); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new Buy()); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new Leave()); var userState = ExpectMsg<CurrentState<IUserState>>(); userState.FsmRef.Should().Be(fsmRef); userState.State.Should().Be(LookingAround.Instance); ExpectMsg<EmptyShoppingCart>(); var transition1 = ExpectMsg<Transition<IUserState>>(); transition1.FsmRef.Should().Be(fsmRef); transition1.From.Should().Be(LookingAround.Instance); transition1.To.Should().Be(Shopping.Instance); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes, coat); var transition2 = ExpectMsg<Transition<IUserState>>(); transition2.FsmRef.Should().Be(fsmRef); transition2.From.Should().Be(Shopping.Instance); transition2.To.Should().Be(Paid.Instance); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes, coat); ExpectTerminated(fsmRef); } [Fact] public void PersistentFSM_must_has_function_as_regular_fsm_on_state_timeout() { var dummyReportActorRef = CreateTestProbe().Ref; var fsmRef = Sys.ActorOf(WebStoreCustomerFSM.Props(Name, dummyReportActorRef)); Watch(fsmRef); fsmRef.Tell(new SubscribeTransitionCallBack(TestActor)); var shirt = new Item("1", "Shirt", 59.99F); fsmRef.Tell(new AddItem(shirt)); var userState = ExpectMsg<CurrentState<IUserState>>(); userState.FsmRef.Should().Be(fsmRef); userState.State.Should().Be(LookingAround.Instance); var transition1 = ExpectMsg<Transition<IUserState>>(); transition1.FsmRef.Should().Be(fsmRef); transition1.From.Should().Be(LookingAround.Instance); transition1.To.Should().Be(Shopping.Instance); Within(TimeSpan.FromSeconds(0.9), RemainingOrDefault, () => { var transition2 = ExpectMsg<Transition<IUserState>>(); transition2.FsmRef.Should().Be(fsmRef); transition2.From.Should().Be(Shopping.Instance); transition2.To.Should().Be(Inactive.Instance); }); ExpectTerminated(fsmRef); } [Fact] public void PersistentFSM_must_recover_successfully_with_correct_state_data() { var dummyReportActorRef = CreateTestProbe().Ref; var fsmRef = Sys.ActorOf(WebStoreCustomerFSM.Props(Name, dummyReportActorRef)); Watch(fsmRef); fsmRef.Tell(new SubscribeTransitionCallBack(TestActor)); var shirt = new Item("1", "Shirt", 59.99F); var shoes = new Item("2", "Shoes", 89.99F); var coat = new Item("3", "Coat", 119.99F); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(shirt)); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(shoes)); fsmRef.Tell(new GetCurrentCart()); var userState1 = ExpectMsg<CurrentState<IUserState>>(); userState1.FsmRef.Should().Be(fsmRef); userState1.State.Should().Be(LookingAround.Instance); ExpectMsg<EmptyShoppingCart>(); var transition1 = ExpectMsg<Transition<IUserState>>(); transition1.FsmRef.Should().Be(fsmRef); transition1.From.Should().Be(LookingAround.Instance); transition1.To.Should().Be(Shopping.Instance); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes); fsmRef.Tell(PoisonPill.Instance); ExpectTerminated(fsmRef); var recoveredFsmRef = Sys.ActorOf(Props.Create(() => new WebStoreCustomerFSM(Name, dummyReportActorRef))); Watch(recoveredFsmRef); recoveredFsmRef.Tell(new SubscribeTransitionCallBack(TestActor)); recoveredFsmRef.Tell(new GetCurrentCart()); recoveredFsmRef.Tell(new AddItem(coat)); recoveredFsmRef.Tell(new GetCurrentCart()); recoveredFsmRef.Tell(new Buy()); recoveredFsmRef.Tell(new GetCurrentCart()); recoveredFsmRef.Tell(new Leave()); var userState2 = ExpectMsg<CurrentState<IUserState>>(); userState2.FsmRef.Should().Be(recoveredFsmRef); userState2.State.Should().Be(Shopping.Instance); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes, coat); var transition2 = ExpectMsg<Transition<IUserState>>(); transition2.FsmRef.Should().Be(recoveredFsmRef); transition2.From.Should().Be(Shopping.Instance); transition2.To.Should().Be(Paid.Instance); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes, coat); ExpectTerminated(recoveredFsmRef); } [Fact] public void PersistentFSM_must_execute_the_defined_actions_following_successful_persistence_of_state_change() { var reportActorProbe = CreateTestProbe(Sys); var fsmRef = Sys.ActorOf(WebStoreCustomerFSM.Props(Name, reportActorProbe.Ref)); Watch(fsmRef); fsmRef.Tell(new SubscribeTransitionCallBack(TestActor)); var shirt = new Item("1", "Shirt", 59.99F); var shoes = new Item("2", "Shoes", 89.99F); var coat = new Item("3", "Coat", 119.99F); fsmRef.Tell(new AddItem(shirt)); fsmRef.Tell(new AddItem(shoes)); fsmRef.Tell(new AddItem(coat)); fsmRef.Tell(new Buy()); fsmRef.Tell(new Leave()); var userState = ExpectMsg<CurrentState<IUserState>>(); userState.FsmRef.Should().Be(fsmRef); userState.State.Should().Be(LookingAround.Instance); var transition1 = ExpectMsg<Transition<IUserState>>(); transition1.FsmRef.Should().Be(fsmRef); transition1.From.Should().Be(LookingAround.Instance); transition1.To.Should().Be(Shopping.Instance); var transition2 = ExpectMsg<Transition<IUserState>>(); transition2.FsmRef.Should().Be(fsmRef); transition2.From.Should().Be(Shopping.Instance); transition2.To.Should().Be(Paid.Instance); reportActorProbe.ExpectMsg<PurchaseWasMade>().Items.Should().ContainInOrder(shirt, shoes, coat); ExpectTerminated(fsmRef); } [Fact] public void PersistentFSM_must_execute_the_defined_actions_following_successful_persistence_of_FSM_stop() { var reportActorProbe = CreateTestProbe(Sys); var fsmRef = Sys.ActorOf(WebStoreCustomerFSM.Props(Name, reportActorProbe.Ref)); Watch(fsmRef); fsmRef.Tell(new SubscribeTransitionCallBack(TestActor)); var shirt = new Item("1", "Shirt", 59.99F); var shoes = new Item("2", "Shoes", 89.99F); var coat = new Item("3", "Coat", 119.99F); fsmRef.Tell(new AddItem(shirt)); fsmRef.Tell(new AddItem(shoes)); fsmRef.Tell(new AddItem(coat)); fsmRef.Tell(new Leave()); var userState = ExpectMsg<CurrentState<IUserState>>(); userState.FsmRef.Should().Be(fsmRef); userState.State.Should().Be(LookingAround.Instance); var transition = ExpectMsg<Transition<IUserState>>(); transition.FsmRef.Should().Be(fsmRef); transition.From.Should().Be(LookingAround.Instance); transition.To.Should().Be(Shopping.Instance); reportActorProbe.ExpectMsg<ShoppingCardDiscarded>(); ExpectTerminated(fsmRef); } [Fact] public void PersistentFSM_must_recover_successfully_with_correct_state_timeout() { var dummyReportActorRef = CreateTestProbe().Ref; var fsmRef = Sys.ActorOf(WebStoreCustomerFSM.Props(Name, dummyReportActorRef)); Watch(fsmRef); fsmRef.Tell(new SubscribeTransitionCallBack(TestActor)); var shirt = new Item("1", "Shirt", 59.99F); fsmRef.Tell(new AddItem(shirt)); var userState1 = ExpectMsg<CurrentState<IUserState>>(); userState1.FsmRef.Should().Be(fsmRef); userState1.State.Should().Be(LookingAround.Instance); var transition1 = ExpectMsg<Transition<IUserState>>(); transition1.FsmRef.Should().Be(fsmRef); transition1.From.Should().Be(LookingAround.Instance); transition1.To.Should().Be(Shopping.Instance); ExpectNoMsg(TimeSpan.FromSeconds(0.6)); // arbitrarily chosen delay, less than the timeout, before stopping the FSM fsmRef.Tell(PoisonPill.Instance); ExpectTerminated(fsmRef); var recoveredFsmRef = Sys.ActorOf(Props.Create(() => new WebStoreCustomerFSM(Name, dummyReportActorRef))); Watch(recoveredFsmRef); recoveredFsmRef.Tell(new SubscribeTransitionCallBack(TestActor)); var userState2 = ExpectMsg<CurrentState<IUserState>>(); userState2.FsmRef.Should().Be(recoveredFsmRef); userState2.State.Should().Be(Shopping.Instance); Within(TimeSpan.FromSeconds(0.9), RemainingOrDefault, () => { var transition2 = ExpectMsg<Transition<IUserState>>(); transition2.FsmRef.Should().Be(recoveredFsmRef); transition2.From.Should().Be(Shopping.Instance); transition2.To.Should().Be(Inactive.Instance); }); ExpectNoMsg(TimeSpan.FromSeconds(0.6)); // arbitrarily chosen delay, less than the timeout, before stopping the FSM recoveredFsmRef.Tell(PoisonPill.Instance); ExpectTerminated(recoveredFsmRef); var recoveredFsmRef2 = Sys.ActorOf(Props.Create(() => new WebStoreCustomerFSM(Name, dummyReportActorRef))); Watch(recoveredFsmRef2); recoveredFsmRef2.Tell(new SubscribeTransitionCallBack(TestActor)); var userState3 = ExpectMsg<CurrentState<IUserState>>(); userState3.FsmRef.Should().Be(recoveredFsmRef2); userState3.State.Should().Be(Inactive.Instance); ExpectTerminated(recoveredFsmRef2); } [Fact] public void PersistentFSM_must_not_trigger_onTransition_for_stay() { var probe = CreateTestProbe(Sys); var fsmRef = Sys.ActorOf(SimpleTransitionFSM.Props(Name, probe.Ref)); probe.ExpectMsg("LookingAround -> LookingAround", 3.Seconds()); // caused by initialize(), OK fsmRef.Tell("goto(the same state)"); // causes goto() probe.ExpectMsg("LookingAround -> LookingAround", 3.Seconds()); fsmRef.Tell("stay"); probe.ExpectNoMsg(3.Seconds()); } [Fact] public void PersistentFSM_must_not_persist_state_change_event_when_staying_in_the_same_state() { var dummyReportActorRef = CreateTestProbe().Ref; var fsmRef = Sys.ActorOf(WebStoreCustomerFSM.Props(Name, dummyReportActorRef)); Watch(fsmRef); var shirt = new Item("1", "Shirt", 59.99F); var shoes = new Item("2", "Shoes", 89.99F); var coat = new Item("3", "Coat", 119.99F); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(shirt)); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(shoes)); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(coat)); fsmRef.Tell(new GetCurrentCart()); ExpectMsg<EmptyShoppingCart>(); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes, coat); fsmRef.Tell(PoisonPill.Instance); ExpectTerminated(fsmRef); var persistentEventsStreamer = Sys.ActorOf(PersistentEventsStreamer.Props(Name, TestActor)); ExpectMsg<ItemAdded>().Item.Should().Be(shirt); ExpectMsg<PersistentFSM.StateChangeEvent>(); ExpectMsg<ItemAdded>().Item.Should().Be(shoes); ExpectMsg<PersistentFSM.StateChangeEvent>(); ExpectMsg<ItemAdded>().Item.Should().Be(coat); ExpectMsg<PersistentFSM.StateChangeEvent>(); Watch(persistentEventsStreamer); persistentEventsStreamer.Tell(PoisonPill.Instance); ExpectTerminated(persistentEventsStreamer); } [Fact] public void PersistentFSM_must_persist_snapshot() { var dummyReportActorRef = CreateTestProbe().Ref; var fsmRef = Sys.ActorOf(WebStoreCustomerFSM.Props(Name, dummyReportActorRef)); Watch(fsmRef); var shirt = new Item("1", "Shirt", 59.99F); var shoes = new Item("2", "Shoes", 89.99F); var coat = new Item("3", "Coat", 119.99F); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(shirt)); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(shoes)); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new AddItem(coat)); fsmRef.Tell(new GetCurrentCart()); fsmRef.Tell(new Buy()); fsmRef.Tell(new GetCurrentCart()); ExpectMsg<EmptyShoppingCart>(); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes, coat); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes, coat); ExpectNoMsg(1.Seconds()); fsmRef.Tell(PoisonPill.Instance); ExpectTerminated(fsmRef); var recoveredFsmRef = Sys.ActorOf(WebStoreCustomerFSM.Props(Name, dummyReportActorRef)); recoveredFsmRef.Tell(new GetCurrentCart()); ExpectMsg<NonEmptyShoppingCart>().Items.Should().ContainInOrder(shirt, shoes, coat); Watch(recoveredFsmRef); recoveredFsmRef.Tell(PoisonPill.Instance); ExpectTerminated(recoveredFsmRef); var persistentEventsStreamer = Sys.ActorOf(PersistentEventsStreamer.Props(Name, TestActor)); ExpectMsg<SnapshotOffer>(); Watch(persistentEventsStreamer); persistentEventsStreamer.Tell(PoisonPill.Instance); ExpectTerminated(persistentEventsStreamer); } [Fact] public void PersistentFSM_must_allow_cancelling_stateTimeout_by_issuing_forMax_null() { var probe = CreateTestProbe(); var fsm = Sys.ActorOf(TimeoutFsm.Props(probe.Ref)); probe.ExpectMsg<StateTimeout>(); fsm.Tell(TimeoutFsm.OverrideTimeoutToInf.Instance); probe.ExpectMsg<TimeoutFsm.OverrideTimeoutToInf>(); probe.ExpectNoMsg(1.Seconds()); } [Fact] public void PersistentFSM_must_save_periodical_snapshots_if_enablesnapshotafter() { var sys2 = ActorSystem.Create("PersistentFsmSpec2", ConfigurationFactory.ParseString(@" akka.persistence.fsm.snapshot-after = 3 ").WithFallback(Configuration("PersistentFSMSpec"))); try { var probe = CreateTestProbe(); var fsmRef = sys2.ActorOf(SnapshotFSM.Props(probe.Ref)); fsmRef.Tell(1); fsmRef.Tell(2); fsmRef.Tell(3); // Needs to wait with expectMsg, before sending the next message to fsmRef. // Otherwise, stateData sent to this probe is already updated probe.ExpectMsg("SeqNo=3, StateData=List(3, 2, 1)"); fsmRef.Tell("4x"); //changes the state to Persist4xAtOnce, also updates SeqNo although nothing is persisted fsmRef.Tell(10); //Persist4xAtOnce = persist 10, 4x times // snapshot-after = 3, but the SeqNo is not multiple of 3, // as saveStateSnapshot() is called at the end of persistent event "batch" = 4x of 10's. probe.ExpectMsg("SeqNo=8, StateData=List(10, 10, 10, 10, 3, 2, 1)"); } finally { Shutdown(sys2); } } [Fact] public async Task PersistentFSM_must_pass_latest_statedata_to_AndThen() { var actor = Sys.ActorOf(Props.Create(() => new AndThenTestActor())); var response1 = await actor.Ask<AndThenTestActor.Data>(new AndThenTestActor.Command("Message 1")).ConfigureAwait(true); var response2 = await actor.Ask<AndThenTestActor.Data>(new AndThenTestActor.Command("Message 2")).ConfigureAwait(true); Assert.Equal("Message 1", response1.Value); Assert.Equal("Message 2", response2.Value); } internal class WebStoreCustomerFSM : PersistentFSM<IUserState, IShoppingCart, IDomainEvent> { public WebStoreCustomerFSM(string persistenceId, IActorRef reportActor) { PersistenceId = persistenceId; StartWith(LookingAround.Instance, new EmptyShoppingCart()); When(LookingAround.Instance, (evt, state) => { if (evt.FsmEvent is AddItem addItem) { return GoTo(Shopping.Instance) .Applying(new ItemAdded(addItem.Item)) .ForMax(TimeSpan.FromSeconds(1)); } if (evt.FsmEvent is GetCurrentCart) { return Stay().Replying(evt.StateData); } return state; }); When(Shopping.Instance, (evt, state) => { if (evt.FsmEvent is AddItem addItem) { return Stay().Applying(new ItemAdded(addItem.Item)).ForMax(TimeSpan.FromSeconds(1)); } if (evt.FsmEvent is Buy) { return GoTo(Paid.Instance) .Applying(new OrderExecuted()) .AndThen(cart => { if (cart is NonEmptyShoppingCart nonShoppingCart) { reportActor.Tell(new PurchaseWasMade(nonShoppingCart.Items)); SaveStateSnapshot(); } else if (cart is EmptyShoppingCart) { SaveStateSnapshot(); } }); } if (evt.FsmEvent is Leave) { return Stop() .Applying(new OrderDiscarded()) .AndThen(cart => { reportActor.Tell(new ShoppingCardDiscarded()); SaveStateSnapshot(); }); } if (evt.FsmEvent is GetCurrentCart) { return Stay().Replying(evt.StateData); } if (evt.FsmEvent is StateTimeout) { return GoTo(Inactive.Instance).ForMax(TimeSpan.FromSeconds(2)); } return state; }); When(Inactive.Instance, (evt, state) => { if (evt.FsmEvent is AddItem addItem) { return GoTo(Shopping.Instance) .Applying(new ItemAdded(addItem.Item)) .ForMax(TimeSpan.FromSeconds(1)); } if (evt.FsmEvent is StateTimeout) { return Stop() .Applying(new OrderDiscarded()) .AndThen(cart => reportActor.Tell(new ShoppingCardDiscarded())); } return state; }); When(Paid.Instance, (evt, state) => { if (evt.FsmEvent is Leave) { return Stop(); } if (evt.FsmEvent is GetCurrentCart) { return Stay().Replying(evt.StateData); } return state; }); } public override string PersistenceId { get; } internal static Props Props(string name, IActorRef dummyReportActorRef) { return Actor.Props.Create(() => new WebStoreCustomerFSM(name, dummyReportActorRef)); } protected override IShoppingCart ApplyEvent(IDomainEvent evt, IShoppingCart cartBeforeEvent) { if (evt is ItemAdded itemAdded) { return cartBeforeEvent.AddItem(itemAdded.Item); } if (evt is OrderExecuted) { return cartBeforeEvent; } if (evt is OrderDiscarded) { return cartBeforeEvent.Empty(); } return cartBeforeEvent; } } } public class TimeoutFsm : PersistentFSM<TimeoutFsm.ITimeoutState, string, string> { public interface ITimeoutState: PersistentFSM.IFsmState { } public class Init : ITimeoutState { public static Init Instance { get; } = new Init(); private Init() { } public override bool Equals(object obj) => !ReferenceEquals(obj, null) && obj is Init; public override int GetHashCode() => nameof(Init).GetHashCode(); public string Identifier => "Init"; } public class OverrideTimeoutToInf { public static readonly OverrideTimeoutToInf Instance = new OverrideTimeoutToInf(); private OverrideTimeoutToInf() { } } public TimeoutFsm(IActorRef probe) { StartWith(Init.Instance, ""); When(Init.Instance, (evt, state) => { if (evt.FsmEvent is StateTimeout) { probe.Tell(StateTimeout.Instance); return Stay(); } else if (evt.FsmEvent is OverrideTimeoutToInf) { probe.Tell(OverrideTimeoutToInf.Instance); return Stay().ForMax(TimeSpan.MaxValue); } return null; }, TimeSpan.FromMilliseconds(300)); } public override string PersistenceId { get; } = "timeout-test"; protected override string ApplyEvent(string e, string data) { return "whatever"; } public static Props Props(IActorRef probe) { return Actor.Props.Create(() => new TimeoutFsm(probe)); } } internal class SimpleTransitionFSM : PersistentFSM<IUserState, IShoppingCart, IDomainEvent> { public SimpleTransitionFSM(string persistenceId, IActorRef reportActor) { PersistenceId = persistenceId; StartWith(LookingAround.Instance, new EmptyShoppingCart()); When(LookingAround.Instance, (evt, state) => { if (evt.FsmEvent.Equals("stay")) { return Stay(); } return GoTo(LookingAround.Instance); }); OnTransition((state, nextState) => { reportActor.Tell($"{state} -> {nextState}"); }); } public override string PersistenceId { get; } protected override IShoppingCart ApplyEvent(IDomainEvent domainEvent, IShoppingCart currentData) { return currentData; } public static Props Props(string persistenceId, IActorRef reportActor) { return Actor.Props.Create(() => new SimpleTransitionFSM(persistenceId, reportActor)); } } internal class PersistentEventsStreamer : PersistentActor { private readonly IActorRef _client; public PersistentEventsStreamer(string persistenceId, IActorRef client) { PersistenceId = persistenceId; _client = client; } public override string PersistenceId { get; } protected override bool ReceiveRecover(object message) { if (!(message is RecoveryCompleted)) { _client.Tell(message); } return true; } protected override bool ReceiveCommand(object message) { return true; } public static Props Props(string persistenceId, IActorRef client) { return Actor.Props.Create(() => new PersistentEventsStreamer(persistenceId, client)); } } #region Custome States public interface IUserState : PersistentFSM.IFsmState { } public class Shopping : IUserState { public static Shopping Instance { get; } = new Shopping(); private Shopping() { } public override bool Equals(object obj) => !ReferenceEquals(obj, null) && obj is Shopping; public override int GetHashCode() => nameof(Shopping).GetHashCode(); public override string ToString() => nameof(Shopping); public string Identifier => "Shopping"; } public class Inactive : IUserState { public static Inactive Instance { get; } = new Inactive(); private Inactive() { } public override bool Equals(object obj) => !ReferenceEquals(obj, null) && obj is Inactive; public override int GetHashCode() => nameof(Inactive).GetHashCode(); public override string ToString() => nameof(Inactive); public string Identifier => "Inactive"; } public class Paid : IUserState { public static Paid Instance { get; } = new Paid(); private Paid() { } public override bool Equals(object obj) => !ReferenceEquals(obj, null) && obj is Paid; public override int GetHashCode() => nameof(Paid).GetHashCode(); public override string ToString() => nameof(Paid); public string Identifier => "Paid"; } public class LookingAround : IUserState { public static LookingAround Instance { get; } = new LookingAround(); private LookingAround() { } public override bool Equals(object obj) => !ReferenceEquals(obj, null) && obj is LookingAround; public override int GetHashCode() => nameof(LookingAround).GetHashCode(); public override string ToString() => nameof(LookingAround); public string Identifier => "Looking Around"; } #endregion #region Customer states data internal class Item { public Item(string id, string name, float price) { Id = id; Name = name; Price = price; } public string Id { get; } public string Name { get; } public float Price { get; } #region Equals protected bool Equals(Item other) { return string.Equals(Id, other.Id) && string.Equals(Name, other.Name) && Price.Equals(other.Price); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Item)obj); } public override int GetHashCode() { unchecked { var hashCode = (Id != null ? Id.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Price.GetHashCode(); return hashCode; } } #endregion } internal interface IShoppingCart { ICollection<Item> Items { get; set; } IShoppingCart AddItem(Item item); IShoppingCart Empty(); } internal class EmptyShoppingCart : IShoppingCart { public IShoppingCart AddItem(Item item) { return new NonEmptyShoppingCart(item); } public IShoppingCart Empty() { return this; } public ICollection<Item> Items { get; set; } } internal class NonEmptyShoppingCart : IShoppingCart { public NonEmptyShoppingCart(Item item) { Items = new List<Item>(); Items.Add(item); } public IShoppingCart AddItem(Item item) { Items.Add(item); return this; } public IShoppingCart Empty() { return new EmptyShoppingCart(); } public ICollection<Item> Items { get; set; } } #endregion #region Customer commands internal interface ICommand { } internal class AddItem : ICommand { public AddItem(Item item) { Item = item; } public Item Item { get; private set; } } internal class Buy { } internal class Leave { } internal class GetCurrentCart : ICommand { } #endregion #region Customer domain events internal interface IDomainEvent { } internal class ItemAdded : IDomainEvent { public ItemAdded(Item item) { Item = item; } public Item Item { get; private set; } } internal class OrderExecuted : IDomainEvent { } internal class OrderDiscarded : IDomainEvent { } #endregion #region Side effects - report events to be sent to some internal interface IReportEvent { } internal class PurchaseWasMade : IReportEvent { public PurchaseWasMade(IEnumerable<Item> items) { Items = items; } public IEnumerable<Item> Items { get; } } internal class ShoppingCardDiscarded : IReportEvent { } #endregion public interface ISnapshotFSMState : PersistentFSM.IFsmState { } public class PersistSingleAtOnce : ISnapshotFSMState { public static PersistSingleAtOnce Instance { get; } = new PersistSingleAtOnce(); private PersistSingleAtOnce() { } public string Identifier => "PersistSingleAtOnce"; } public class Persist4xAtOnce : ISnapshotFSMState { public static Persist4xAtOnce Instance { get; } = new Persist4xAtOnce(); private Persist4xAtOnce() { } public string Identifier => "Persist4xAtOnce"; } public interface ISnapshotFSMEvent { } public class IntAdded : ISnapshotFSMEvent { public IntAdded(int i) { I = i; } public int I { get; } } internal class SnapshotFSM : PersistentFSM<ISnapshotFSMState, List<int>, ISnapshotFSMEvent> { public SnapshotFSM(IActorRef probe) { StartWith(PersistSingleAtOnce.Instance, null); When(PersistSingleAtOnce.Instance, (evt, state) => { if (evt.FsmEvent is int i) { return Stay().Applying(new IntAdded(i)); } else if (evt.FsmEvent.Equals("4x")) { return GoTo(Persist4xAtOnce.Instance); } else if (evt.FsmEvent is SaveSnapshotSuccess snap) { probe.Tell($"SeqNo={snap.Metadata.SequenceNr}, StateData=List({string.Join(", ", StateData)})"); return Stay(); } return Stay(); }); When(Persist4xAtOnce.Instance, (evt, state) => { if (evt.FsmEvent is int i) { return Stay().Applying(new IntAdded(i), new IntAdded(i), new IntAdded(i), new IntAdded(i)); } else if (evt.FsmEvent is SaveSnapshotSuccess snap) { probe.Tell($"SeqNo={snap.Metadata.SequenceNr}, StateData=List({string.Join(", ", StateData)})"); return Stay(); } return Stay(); }); } public override string PersistenceId { get; } = "snapshot-fsm-test"; protected override List<int> ApplyEvent(ISnapshotFSMEvent domainEvent, List<int> currentData) { if (domainEvent is IntAdded intAdded) { var list = new List<int>(); list.Add(intAdded.I); if (currentData != null) list.AddRange(currentData); return list; } return currentData; } public static Props Props(IActorRef probe) { return Actor.Props.Create(() => new SnapshotFSM(probe)); } } #region AndThen receiving latest data public class AndThenTestActor : PersistentFSM<AndThenTestActor.IState, AndThenTestActor.Data, AndThenTestActor.IEvent> { public override string PersistenceId => "PersistentFSMSpec.AndThenTestActor"; public AndThenTestActor() { StartWith(Init.Instance, new Data()); When(Init.Instance, (evt, state) => { switch (evt.FsmEvent) { case Command cmd: return Stay() .Applying(new CommandReceived(cmd.Value)) .AndThen(data => { // NOTE At this point, I'd expect data to be the value returned by Apply Sender.Tell(data, Self); }); default: return Stay(); } }); } protected override Data ApplyEvent(IEvent domainEvent, Data currentData) { switch (domainEvent) { case CommandReceived cmd: return new Data(cmd.Value); default: return currentData; } } public interface IState : PersistentFSM.IFsmState { } public class Init : IState { public static readonly Init Instance = new Init(); public string Identifier => "Init"; } public class Data { public Data() { } public Data(string value) { Value = value; } public string Value { get; } } public interface IEvent { } public class CommandReceived : IEvent { public CommandReceived(string value) { Value = value; } public string Value { get; } } public class Command { public Command(string value) { Value = value; } public string Value { get; } } } #endregion }
34.417857
131
0.556112
[ "Apache-2.0" ]
hueifeng/akka.net
src/core/Akka.Persistence.Tests/Fsm/PersistentFSMSpec.cs
38,550
C#
namespace WebPlex.Core.Builders { public class FlatConstant : Constant { private readonly string _key; public FlatConstant(string key) { _key = key; } protected override string BuildKey() { return _key; } } }
17.615385
40
0.694323
[ "MIT" ]
m-sadegh-sh/WebPlex
src/WebPlex.Core/Builders/FlatConstant.cs
231
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Assets.Scripts.Input; using UnityEngine; namespace Assets.Scripts.Tutorial { /// <summary> /// Class that can play the tutorial for this game. /// </summary> class TutorialController: MonoBehaviour { /// <summary> /// The sequence of tutorial steps that should be executed. /// </summary> public List<TutorialStep> AllTutorialSteps; /// <summary> /// Left click controller, we keep a reference to it as we will disable it during the tutorial and we will need to find it again to reenable it. /// </summary> [HideInInspector] public LeftClickController LeftClickController; /// <summary> /// Right click controller, we keep a reference to it as we will disable it during the tutorial and we will need to find it again to reenable it. /// </summary> [HideInInspector] public RightClickController RightClickController; /// <summary> /// Pause click controller, we keep a reference to it as we will disable it during the tutorial and we will need to find it again to reenable it. /// </summary> [HideInInspector] public PauseManager PauseManager; /// <summary> /// If true, we should start the tutorial automatically on level load. Mainly used for testing. /// </summary> public bool AutoStart; /// <summary> /// The index of the currently executed tutorial step. /// </summary> private int currentTutorialStep = 0; /// <summary> /// If true, the tutorial is currently playing. /// </summary> private bool isTutorialActive; /// <summary> /// Called before the first Update, starts the tutorial if <see cref="AutoStart"/> is true. /// </summary> private void Start() { if (AutoStart) { StartTutorial(); } } /// <summary> /// Called every frame. Checks whether the tutorial steps is over. /// If it is, move to the next step, ending the tutorial if we reached the end. /// </summary> private void Update() { if (isTutorialActive && AllTutorialSteps[currentTutorialStep].IsTutorialStepOver()) { AllTutorialSteps[currentTutorialStep].gameObject.SetActive(false); ++currentTutorialStep; ExecuteCurrentTutorialStep(); } } /// <summary> /// Plays the tutorial. /// </summary> public void StartTutorial() { LeftClickController = FindObjectOfType<LeftClickController>(); RightClickController = FindObjectOfType<RightClickController>(); PauseManager = FindObjectOfType<PauseManager>(); LeftClickController.enabled = false; RightClickController.enabled = false; PauseManager.enabled = false; isTutorialActive = true; currentTutorialStep = 0; ExecuteCurrentTutorialStep(); } /// <summary> /// Call when the tutorial ends to reenable everything that was disabled. /// </summary> private void EndTutorial() { LeftClickController.enabled = true; RightClickController.enabled = true; PauseManager.enabled = true; isTutorialActive = false; foreach (var interactableObject in FindObjectsOfType<InteractableObject>()) { interactableObject.IsInteractionDisabledByTutorial = false; } } /// <summary> /// Plays the tutorial step we are executing right now. /// </summary> private void ExecuteCurrentTutorialStep() { if (AllTutorialSteps == null || currentTutorialStep >= AllTutorialSteps.Count) { EndTutorial(); return; } AllTutorialSteps[currentTutorialStep].gameObject.SetActive(true); } } }
36.852174
153
0.589901
[ "MIT" ]
MatousK/EncounterGenerationRPG
Assets/Scripts/Tutorial/TutorialController.cs
4,240
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("Preserver")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Preserver")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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")] [assembly: ComVisible(false)]
35.689655
84
0.740097
[ "MIT" ]
Advik-B/Preserver
src/Properties/AssemblyInfo.cs
1,038
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class UnityEngine_UI_Toggle_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; FieldInfo field; Type[] args; Type type = typeof(UnityEngine.UI.Toggle); args = new Type[]{}; method = type.GetMethod("get_isOn", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_isOn_0); args = new Type[]{typeof(System.Boolean)}; method = type.GetMethod("set_isOn", flag, null, args, null); app.RegisterCLRMethodRedirection(method, set_isOn_1); field = type.GetField("onValueChanged", flag); app.RegisterCLRFieldGetter(field, get_onValueChanged_0); app.RegisterCLRFieldSetter(field, set_onValueChanged_0); app.RegisterCLRFieldBinding(field, CopyToStack_onValueChanged_0, AssignFromStack_onValueChanged_0); } static StackObject* get_isOn_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); UnityEngine.UI.Toggle instance_of_this_method = (UnityEngine.UI.Toggle)typeof(UnityEngine.UI.Toggle).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.isOn; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* set_isOn_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Boolean @value = ptr_of_this_method->Value == 1; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); UnityEngine.UI.Toggle instance_of_this_method = (UnityEngine.UI.Toggle)typeof(UnityEngine.UI.Toggle).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0); __intp.Free(ptr_of_this_method); instance_of_this_method.isOn = value; return __ret; } static object get_onValueChanged_0(ref object o) { return ((UnityEngine.UI.Toggle)o).onValueChanged; } static StackObject* CopyToStack_onValueChanged_0(ref object o, ILIntepreter __intp, StackObject* __ret, IList<object> __mStack) { var result_of_this_method = ((UnityEngine.UI.Toggle)o).onValueChanged; return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static void set_onValueChanged_0(ref object o, object v) { ((UnityEngine.UI.Toggle)o).onValueChanged = (UnityEngine.UI.Toggle.ToggleEvent)v; } static StackObject* AssignFromStack_onValueChanged_0(ref object o, ILIntepreter __intp, StackObject* ptr_of_this_method, IList<object> __mStack) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; UnityEngine.UI.Toggle.ToggleEvent @onValueChanged = (UnityEngine.UI.Toggle.ToggleEvent)typeof(UnityEngine.UI.Toggle.ToggleEvent).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0); ((UnityEngine.UI.Toggle)o).onValueChanged = @onValueChanged; return ptr_of_this_method; } } }
42.933962
252
0.691496
[ "MIT" ]
752636090/ET
Unity/Assets/Mono/ILRuntime/Generate/UnityEngine_UI_Toggle_Binding.cs
4,551
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. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Amazon.Runtime; using Amazon.S3Control.Model; using System.IO; using Amazon.Runtime.Internal; using Amazon.S3Control; using System.Text.RegularExpressions; using Amazon.Util; using System.Globalization; #pragma warning disable 1591 namespace Amazon.S3Control.Internal { public class AmazonS3ControlPostMarshallHandler : PipelineHandler { /// <summary> /// Calls pre invoke logic before calling the next handler /// in the pipeline. /// </summary> /// <param name="executionContext">The execution context which contains both the /// requests and response context.</param> public override void InvokeSync(IExecutionContext executionContext) { PreInvoke(executionContext); base.InvokeSync(executionContext); } #if AWS_ASYNC_API /// <summary> /// Calls pre invoke logic before calling the next handler /// in the pipeline. /// </summary> /// <typeparam name="T">The response type for the current request.</typeparam> /// <param name="executionContext">The execution context, it contains the /// request and response context.</param> /// <returns>A task that represents the asynchronous operation.</returns> public override System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext) { PreInvoke(executionContext); return base.InvokeAsync<T>(executionContext); } #elif AWS_APM_API /// <summary> /// Calls pre invoke logic before calling the next handler /// in the pipeline. /// </summary> /// <param name="executionContext">The execution context which contains both the /// requests and response context.</param> /// <returns>IAsyncResult which represent an async operation.</returns> public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext) { PreInvoke(ExecutionContext.CreateFromAsyncContext(executionContext)); return base.InvokeAsync(executionContext); } #endif protected virtual void PreInvoke(IExecutionContext executionContext) { ProcessRequestHandlers(executionContext); } public static void ProcessRequestHandlers(IExecutionContext executionContext) { var request = executionContext.RequestContext.Request; var config = executionContext.RequestContext.ClientConfig; //If a ServiceURL is set the config ClientRegion should be null. Under this case //the region needs to be determined from the ServiceURL. RegionEndpoint useRegion = config.RegionEndpoint; if (useRegion == null && !string.IsNullOrEmpty(config.ServiceURL)) { var regionName = AWSSDKUtils.DetermineRegion(config.ServiceURL); useRegion = RegionEndpoint.GetBySystemName(regionName); } string nonArnOutpostId; Arn s3Arn; if (S3ArnUtils.RequestContainsArn(request, out s3Arn)) { IS3Resource s3Resource = null; if (!s3Arn.HasValidAccountId()) { throw new AmazonAccountIdException(); } if (s3Arn.IsOutpostArn()) { if (!s3Arn.IsValidService()) { throw new AmazonClientException($"Invalid ARN: {s3Arn.ToString()}, not S3 Outposts ARN"); } s3Resource = s3Arn.ParseOutpost(); request.Headers[HeaderKeys.XAmzOutpostId] = ((S3OutpostResource) s3Resource).OutpostId; } if (s3Resource != null) { s3Resource.ValidateArnWithClientConfig(config, useRegion); if (string.IsNullOrEmpty(config.ServiceURL)) { request.Endpoint = s3Resource.GetEndpoint(config); } else { request.Endpoint = new Uri(config.ServiceURL); } request.SignatureVersion = SignatureVersion.SigV4; request.CanonicalResourcePrefix = string.Concat("/", s3Resource.FullResourceName); request.OverrideSigningServiceName = s3Arn.Service; // The access point arn can be using a region different from the configured region for the service client. // If so be sure to set the authentication region so the signer will use the correct region. request.AuthenticationRegion = s3Arn.Region; request.Headers[HeaderKeys.XAmzAccountId] = s3Arn.AccountId; // replace the ARNs in the resource path or query params with the extracted name of the resource // These methods assume that there is max 1 Arn in the PathResources or Parameters S3ArnUtils.ReplacePathResourceArns(request.PathResources, s3Resource.Name); S3ArnUtils.ReplacePathResourceArns(request.Parameters, s3Resource.Name); } } else if (S3ArnUtils.DoesRequestHaveOutpostId(request.OriginalRequest, out nonArnOutpostId)) { if (!S3ArnUtils.IsValidOutpostId(nonArnOutpostId)) { throw new AmazonClientException($"Invalid outpost ID. ID must contain only alphanumeric characters and dashes"); } request.OverrideSigningServiceName = S3ArnUtils.S3OutpostsService; if (string.IsNullOrEmpty(config.ServiceURL)) { request.Endpoint = S3ArnUtils.GetNonStandardOutpostIdEndpoint(config); } else { request.Endpoint = new Uri(config.ServiceURL); } request.Headers[HeaderKeys.XAmzOutpostId] = nonArnOutpostId; } } } }
43.459119
132
0.606512
[ "Apache-2.0" ]
MDanialSaleem/aws-sdk-net
sdk/src/Services/S3Control/Custom/Internal/AmazonS3ControlPostMarshallHandler.cs
6,912
C#
#region MigraDoc - Creating Documents on the Fly // // Authors: // Klaus Potzesny // // Copyright (c) 2001-2017 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // 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. #endregion using PdfSharp.Drawing; using MigraDoc.DocumentObjectModel.Shapes; namespace MigraDoc.Rendering { /// <summary> /// Renders fill formats. /// </summary> internal class FillFormatRenderer { public FillFormatRenderer(FillFormat fillFormat, XGraphics gfx) { _gfx = gfx; _fillFormat = fillFormat; } internal void Render(XUnit x, XUnit y, XUnit width, XUnit height) { XBrush brush = GetBrush(); if (brush == null) return; _gfx.DrawRectangle(brush, x.Point, y.Point, width.Point, height.Point); } private bool IsVisible() { if (!_fillFormat._visible.IsNull) return _fillFormat.Visible; return !_fillFormat._color.IsNull; } private XBrush GetBrush() { if (_fillFormat == null || !IsVisible()) return null; #if noCMYK return new XSolidBrush(XColor.FromArgb(_fillFormat.Color.Argb)); #else return new XSolidBrush(ColorHelper.ToXColor(_fillFormat.Color, _fillFormat.Document.UseCmykColor)); #endif } readonly XGraphics _gfx; readonly FillFormat _fillFormat; } }
32.575
111
0.673446
[ "MIT" ]
AVPolyakov/MigraDoc
MigraDoc/src/MigraDoc.Rendering/Rendering/FillFormatRenderer.cs
2,606
C#
using Dynamo.Core; using Dynamo.Graph.Nodes; using Dynamo.ViewModels; using Dynamo.Wpf.Extensions; using System; using System.Collections.ObjectModel; using System.Linq; namespace SpeckleDynamoExtension.ViewModels { public class NodeManagerViewModel : NotificationObject, IDisposable { private ViewLoadedParams viewLoadedParams; private ObservableCollection<NodeModel> _speckleNodes = new ObservableCollection<NodeModel>(); public ObservableCollection<NodeModel> SpeckleNodes { get { return _speckleNodes; } set { _speckleNodes = value; RaisePropertyChanged("SpeckleNodes"); } } public NodeManagerViewModel(ViewLoadedParams p) { viewLoadedParams = p; //subscribing to dynamo events viewLoadedParams.CurrentWorkspaceModel.NodeAdded += CurrentWorkspaceModel_NodeAdded; viewLoadedParams.CurrentWorkspaceModel.NodeRemoved += CurrentWorkspaceModel_NodeRemoved; } private void CurrentWorkspaceModel_NodeRemoved(NodeModel obj) { var type = obj.GetType().ToString(); if (type == "SpeckleDynamo.Sender" || type == "SpeckleDynamo.Receiver") { SpeckleNodes.Remove(obj); } } private void CurrentWorkspaceModel_NodeAdded(NodeModel obj) { var type = obj.GetType().ToString(); if (type == "SpeckleDynamo.Sender" || type == "SpeckleDynamo.Receiver") { SpeckleNodes.Add(obj); } } public void ZoomToFitNodes() { //IsSelected on the NodeModel is not enough, need to call AddToSelectionCommand var dynViewModel = viewLoadedParams.DynamoWindow.DataContext as DynamoViewModel; var selectedNodes = SpeckleNodes.Where(x => x.IsSelected).ToList(); Utilities.ClearSelection(); foreach (var node in selectedNodes) dynViewModel.AddToSelectionCommand.Execute(node); dynViewModel.FitViewCommand.Execute(null); } public void DeleteNodes() { //IsSelected on the NodeModel is not enough, need to call AddToSelectionCommand var dynViewModel = viewLoadedParams.DynamoWindow.DataContext as DynamoViewModel; var selectedNodes = SpeckleNodes.Where(x => x.IsSelected).ToList(); Utilities.ClearSelection(); foreach(var node in selectedNodes) dynViewModel.AddToSelectionCommand.Execute(node); dynViewModel.DeleteCommand.Execute(null); } public void Dispose() { //unsubscribing from events viewLoadedParams.CurrentWorkspaceModel.NodeAdded -= CurrentWorkspaceModel_NodeAdded; viewLoadedParams.CurrentWorkspaceModel.NodeRemoved -= CurrentWorkspaceModel_NodeRemoved; } } }
34.077922
158
0.727515
[ "MIT" ]
arup-group/SpeckleDynamo
SpeckleDynamoExtension/ViewModels/NodeManagerViewModel.cs
2,626
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Contoso.GameNetCore.Testing.xunit; using Xunit; [assembly: OSSkipCondition(OperatingSystems.MacOSX)] [assembly: OSSkipCondition(OperatingSystems.Linux)] [assembly: CollectionBehavior(DisableTestParallelization = true)]
44.666667
112
0.791045
[ "Apache-2.0" ]
bclnet/GameNetCore
src/Servers/HttpSys/test/FunctionalTests/Properties/AssemblyInfo.cs
404
C#
namespace Cachet.NET.Responses { public class PingResponse { /// <summary> /// Gets or sets the data. /// </summary> public string Data { get; set; } /// <summary> /// Returns true if the ping is valid. /// </summary> public bool IsValid { get { return Data?.StartsWith("Pong") ?? false; } } } }
18.538462
57
0.400415
[ "MIT" ]
BerkanYildiz/Cachet.NET
Cachet.NET/Responses/PingResponse.cs
484
C#
using HarmonyLib; using UnityEngine; namespace MappingExtensions.HarmonyPatches { [HarmonyPatch(typeof(BeatmapObjectSpawnMovementData), nameof(BeatmapObjectSpawnMovementData.GetNoteOffset))] internal class BeatmapObjectSpawnMovementDataGetNoteOffset { private static void Postfix(int noteLineIndex, NoteLineLayer noteLineLayer, ref Vector3 __result, int ____noteLinesCount, Vector3 ____rightVec) { if (!Plugin.active) return; if (noteLineIndex is >= 1000 or <= -1000) { if (noteLineIndex <= -1000) noteLineIndex += 2000; float num = -(____noteLinesCount - 1f) * 0.5f; num += noteLineIndex * (StaticBeatmapObjectSpawnMovementData.kNoteLinesDistance / 1000); __result = ____rightVec * num + new Vector3(0f, StaticBeatmapObjectSpawnMovementData.LineYPosForLineLayer(noteLineLayer), 0f); } } } [HarmonyPatch(typeof(BeatmapObjectSpawnMovementData), nameof(BeatmapObjectSpawnMovementData.Get2DNoteOffset))] internal class BeatmapObjectSpawnMovementDataGet2DNoteOffset { private static void Postfix(int noteLineIndex, NoteLineLayer noteLineLayer, ref Vector2 __result, int ____noteLinesCount) { if (!Plugin.active) return; if (noteLineIndex is >= 1000 or <= -1000) { if (noteLineIndex <= -1000) noteLineIndex += 2000; float num = -(____noteLinesCount - 1f) * 0.5f; float x = num + noteLineIndex * (StaticBeatmapObjectSpawnMovementData.kNoteLinesDistance / 1000); float y = StaticBeatmapObjectSpawnMovementData.LineYPosForLineLayer(noteLineLayer); __result = new Vector2(x, y); } } } [HarmonyPatch(typeof(BeatmapObjectSpawnMovementData), nameof(BeatmapObjectSpawnMovementData.GetObstacleOffset))] internal class BeatmapObjectSpawnControllerGetObstacleOffset { private static void Postfix(int noteLineIndex, NoteLineLayer noteLineLayer, ref Vector3 __result, int ____noteLinesCount, Vector3 ____rightVec) { if (!Plugin.active) return; if (noteLineIndex >= 1000 || noteLineIndex <= -1000) { if (noteLineIndex <= -1000) noteLineIndex += 2000; float num = -(____noteLinesCount - 1f) * 0.5f; num += noteLineIndex * (StaticBeatmapObjectSpawnMovementData.kNoteLinesDistance / 1000); __result = ____rightVec * num + new Vector3(0f, StaticBeatmapObjectSpawnMovementData.LineYPosForLineLayer(noteLineLayer) + StaticBeatmapObjectSpawnMovementData.kObstacleVerticalOffset, 0f); } } } [HarmonyPatch(typeof(BeatmapObjectSpawnMovementData), nameof(BeatmapObjectSpawnMovementData.HighestJumpPosYForLineLayer))] internal class BeatmapObjectSpawnMovementDataHighestJumpPosYForLineLayer { private static void Postfix(NoteLineLayer lineLayer, ref float __result, float ____upperLinesHighestJumpPosY, float ____topLinesHighestJumpPosY, IJumpOffsetYProvider ____jumpOffsetYProvider) { if (!Plugin.active) return; float delta = ____topLinesHighestJumpPosY - ____upperLinesHighestJumpPosY; switch ((int)lineLayer) { case >= 1000 or <= -1000: __result = ____upperLinesHighestJumpPosY - delta - delta + ____jumpOffsetYProvider.jumpOffsetY + (int)lineLayer * (delta / 1000); break; case > 2 or < 0: __result = ____upperLinesHighestJumpPosY - delta + ____jumpOffsetYProvider.jumpOffsetY + (int)lineLayer * delta; break; } } } }
49.896104
205
0.656169
[ "MIT" ]
Meivyn/MappingExtensions
MappingExtensions/HarmonyPatches/BeatmapObjectSpawnMovementData.cs
3,844
C#
using System.Collections.Generic; using Infrastructure; using Moq; using Shouldly; using Vertical.Tools.TemplateCopy.Core; using Xunit; namespace Vertical.Tools.TemplateCopy.Providers { public class ContentResolverTests { private readonly IContentResolver _subject = new ContentResolver(TestObjects.Logger , new ISymbolStore[] {new OptionsSymbolStore(new OptionsProvider(new Options { Properties = {["Color"] = "blue"} }) , TestObjects.Logger)}, new OptionsProvider(new Options())); [Theory, MemberData(nameof(Theories))] public void ReplaceSymbols_Returns_Expected_Values(string content, string expected) { _subject.ReplaceSymbols(content).ShouldBe(expected); } public static IEnumerable<object[]> Theories => new[] { new object[]{ "", "" }, new object[]{ "I have no symbols", "I have no symbols" }, new object[]{ "I have a ${non-matching} symbol", "I have a ${non-matching} symbol" }, new object[]{ "I have one symbol, value=${Color}", "I have one symbol, value=blue" }, new object[]{ "I have one symbol, value=${Color}, then other content", "I have one symbol, value=blue, then other content" }, new object[]{ "I have two symbols, value=${Color} and ${Color}", "I have two symbols, value=blue and blue"} }; [Fact] public void LoadSymbols_Invokes_SymbolStores() { var symbolStoreMock = new Mock<ISymbolStore>(); var subject = new ContentResolver(TestObjects.Logger , new[]{symbolStoreMock.Object} , new Mock<IOptionsProvider>().Object); symbolStoreMock.Setup(m => m.Build()).Verifiable(); subject.LoadSymbols(); symbolStoreMock.Verify(m => m.Build()); } } }
39.16
137
0.592952
[ "MIT" ]
verticalsoftware/vertical-templatecopy
test/Vertical/Tools/TemplateCopy/Providers/ContentResolverTests.cs
1,958
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 _Marker_Plot { public partial class Form2 : Form { public Form2() { InitializeComponent(); button1.DialogResult = DialogResult.Retry; button2.DialogResult = DialogResult.Yes; button3.DialogResult = DialogResult.Cancel; button4.DialogResult = DialogResult.No; } } }
24.44
56
0.644845
[ "MIT" ]
aaiijmrtt/MARKERPLOT
Marker Plot/Form2.cs
613
C#
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Devices.Portable; using Windows.Storage; using Windows.Storage.Search; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; namespace Microsoft.Samples.Devices.Portable.RemovableStorageSample { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class S3_GetFromStorage : SDKTemplate.Common.LayoutAwarePage { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() MainPage rootPage = MainPage.Current; // Contains the device information used for populating the device selection list private DeviceInformationCollection _deviceInfoCollection = null; public S3_GetFromStorage() { this.InitializeComponent(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { DeviceSelector.Visibility = Visibility.Collapsed; } /// <summary> /// This is the click handler for the 'Get Image' button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> async private void GetImage_Click(object sender, RoutedEventArgs e) { await ShowDeviceSelectorAsync(); } /// <summary> /// Enumerates all storages and populates the device selection list. /// </summary> async private Task ShowDeviceSelectorAsync() { _deviceInfoCollection = null; // Find all storage devices using Windows.Devices.Enumeration _deviceInfoCollection = await DeviceInformation.FindAllAsync(StorageDevice.GetDeviceSelector()); if (_deviceInfoCollection.Count > 0) { var items = new List<object>(); foreach (DeviceInformation deviceInfo in _deviceInfoCollection) { items.Add(new { Name = deviceInfo.Name, }); } DeviceList.ItemsSource = items; DeviceSelector.Visibility = Visibility.Visible; } else { rootPage.NotifyUser("No removable storages were found. Please attach a removable storage to the system (e.g. a camera or camera memory)", NotifyType.StatusMessage); } } /// <summary> /// This is the tapped handler for the device selection list. It runs the scenario /// for the selected storage. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> async private void DeviceList_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { DeviceSelector.Visibility = Visibility.Collapsed; if (_deviceInfoCollection == null) { return; // not yet populated } var deviceInfo = _deviceInfoCollection[DeviceList.SelectedIndex]; await GetFirstImageFromStorageAsync(deviceInfo); } /// <summary> /// Finds and displays the first image file on the storage referenced by the device information element. /// </summary> /// <param name="deviceInfoElement">Contains information about a selected device.</param> async private Task GetFirstImageFromStorageAsync(DeviceInformation deviceInfoElement) { // Convert the selected device information element to a StorageFolder var storage = StorageDevice.FromId(deviceInfoElement.Id); var storageName = deviceInfoElement.Name; // Construct the query for image files var queryOptions = new QueryOptions(CommonFileQuery.OrderByName, new List<string> { ".jpg", ".png", ".gif" }); var imageFileQuery = storage.CreateFileQueryWithOptions(queryOptions); // Run the query for image files rootPage.NotifyUser("Looking for images on " + storageName + " ...", NotifyType.StatusMessage); var imageFiles = await imageFileQuery.GetFilesAsync(); if (imageFiles.Count > 0) { var imageFile = imageFiles[0]; rootPage.NotifyUser("Found " + imageFile.Name + " on " + storageName, NotifyType.StatusMessage); await DisplayImageAsync(imageFile); } else { rootPage.NotifyUser("No images were found on " + storageName + ". You can use scenario 2 to transfer an image to it", NotifyType.StatusMessage); } } /// <summary> /// Displays an image file in the 'ScenarioOutputImage' element. /// </summary> /// <param name="imageFile">The image file to display.</param> async private Task DisplayImageAsync(StorageFile imageFile) { var imageProperties = await imageFile.GetBasicPropertiesAsync(); if (imageProperties.Size > 0) { rootPage.NotifyUser("Displaying: " + imageFile.Name + ", date modified: " + imageProperties.DateModified + ", size: " + imageProperties.Size + " bytes", NotifyType.StatusMessage); var stream = await imageFile.OpenAsync(FileAccessMode.Read); // BitmapImage.SetSource needs to be called in the UI thread await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var bitmap = new BitmapImage(); bitmap.SetSource(stream); ScenarioOutputImage.SetValue(Image.SourceProperty, bitmap); }); } else { rootPage.NotifyUser("Cannot display " + imageFile.Name + " because its size is 0", NotifyType.ErrorMessage); } } } }
42.313253
196
0.585279
[ "MIT" ]
mfloresn90/CSharpSources
Removable storage sample/C#/S3_GetFromStorage.xaml.cs
7,026
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 ebs-2019-11-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.EBS.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.EBS.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for GetSnapshotBlock operation /// </summary> public class GetSnapshotBlockResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { GetSnapshotBlockResponse response = new GetSnapshotBlockResponse(); response.BlockData = context.Stream; if (context.ResponseData.IsHeaderPresent("x-amz-Checksum")) response.Checksum = context.ResponseData.GetHeaderValue("x-amz-Checksum"); if (context.ResponseData.IsHeaderPresent("x-amz-Checksum-Algorithm")) response.ChecksumAlgorithm = context.ResponseData.GetHeaderValue("x-amz-Checksum-Algorithm"); if (context.ResponseData.IsHeaderPresent("x-amz-Data-Length")) response.DataLength = int.Parse(context.ResponseData.GetHeaderValue("x-amz-Data-Length"), CultureInfo.InvariantCulture); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException")) { return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("RequestThrottledException")) { return RequestThrottledExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceQuotaExceededException")) { return ServiceQuotaExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException")) { return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonEBSException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } /// <summary> /// Overriden to return true indicating the response contains streaming data. /// </summary> public override bool HasStreamingProperty { get { return true; } } private static GetSnapshotBlockResponseUnmarshaller _instance = new GetSnapshotBlockResponseUnmarshaller(); internal static GetSnapshotBlockResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetSnapshotBlockResponseUnmarshaller Instance { get { return _instance; } } } }
42.80292
187
0.632333
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/EBS/Generated/Model/Internal/MarshallTransformations/GetSnapshotBlockResponseUnmarshaller.cs
5,864
C#
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved using System; using System.Diagnostics; using System.Threading; using Windows.ApplicationModel.Background; using Windows.Foundation; using Windows.Storage; using Windows.System.Threading; // // The namespace for the background tasks. // namespace Tasks { // // A background task always implements the IBackgroundTask interface. // public sealed class SampleBackgroundTask : IBackgroundTask { BackgroundTaskCancellationReason _cancelReason = BackgroundTaskCancellationReason.Abort; volatile bool _cancelRequested = false; BackgroundTaskDeferral _deferral = null; ThreadPoolTimer _periodicTimer = null; uint _progress = 0; IBackgroundTaskInstance _taskInstance = null; // // The Run method is the entry point of a background task. // public void Run(IBackgroundTaskInstance taskInstance) { Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting..."); // // Query BackgroundWorkCost // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount // of work in the background task and return immediately. // var cost = BackgroundWorkCost.CurrentBackgroundWorkCost; var settings = ApplicationData.Current.LocalSettings; settings.Values["BackgroundWorkCost"] = cost.ToString(); // // Associate a cancellation handler with the background task. // taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); // // Get the deferral object from the task instance, and take a reference to the taskInstance; // _deferral = taskInstance.GetDeferral(); _taskInstance = taskInstance; _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1)); } // // Handles background task cancellation. // private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { // // Indicate that the background task is canceled. // _cancelRequested = true; _cancelReason = reason; Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested..."); } // // Simulate the background task activity. // private void PeriodicTimerCallback(ThreadPoolTimer timer) { if ((_cancelRequested == false) && (_progress < 100)) { _progress += 10; _taskInstance.Progress = _progress; } else { _periodicTimer.Cancel(); var settings = ApplicationData.Current.LocalSettings; var key = _taskInstance.Task.Name; // // Write to LocalSettings to indicate that this background task ran. // settings.Values[key] = (_progress < 100) ? "Canceled with reason: " + _cancelReason.ToString() : "Completed"; Debug.WriteLine("Background " + _taskInstance.Task.Name + settings.Values[key]); // // Indicate that the background task has completed. // _deferral.Complete(); } } } }
36.055556
139
0.594504
[ "MIT" ]
mfloresn90/CSharpSources
Background task sample/C# and JavaScript/Tasks/SampleBackgroundTask.cs
3,896
C#
using System.Collections.Generic; using System.Threading.Tasks; using Convey.CQRS.Events; namespace AAS.Architecture.Services { public interface IMessageBroker { Task PublishAsync(params IEvent[] events); Task PublishAsync(IEnumerable<IEvent> events); } }
23.666667
54
0.735915
[ "Apache-2.0" ]
aarn94/AAS.Architecture
AAS.Architecture/Services/IMessageBroker.cs
284
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Xml; using System.Xml.Serialization; namespace SG.Checkouts_Overview.Test { [TestClass] public class TestEntryListIO { [TestMethod] public void Serialize() { Dictionary<string, string> paths = new Dictionary<string, string>(); paths["Name 1"] = @"C:\somewhere\here"; paths["Name 2"] = @"C:\somewhere\there"; paths["Name 3"] = @"D:\else\where"; Dictionary<string, string> types = new Dictionary<string, string>(); types["Name 1"] = @"git"; types["Name 2"] = @"gut"; types["Name 3"] = @"good"; ObservableCollection<Entry> entries = new ObservableCollection<Entry>(); entries.Add( new Entry() { Name = "Name 1", Path = paths["Name 1"], Type = types["Name 1"] }); entries.Add( new Entry() { Name = "Name 2", Path = paths["Name 2"], Type = types["Name 2"] }); entries.Add( new Entry() { Name = "Name 3", Path = paths["Name 3"], Type = types["Name 3"] }); string serialized = null; using (StringWriter wrtr = new StringWriter()) { XmlSerializer ser = new XmlSerializer(typeof(Entry[])); ser.Serialize(wrtr, entries.ToArray()); serialized = wrtr.ToString(); } Assert.IsFalse(string.IsNullOrWhiteSpace(serialized)); XmlDocument doc = new XmlDocument(); doc.LoadXml(serialized); Assert.AreEqual(doc.DocumentElement.LocalName, "ArrayOfEntry"); XmlNodeList entryNodes = doc.SelectNodes("//Entry"); Assert.AreEqual(3, entryNodes.Count); Assert.AreEqual(3, doc.DocumentElement.ChildNodes.Count); foreach (XmlNode entryNode in entryNodes) { Assert.AreEqual(3, entryNode.ChildNodes.Count); string name = entryNode.SelectSingleNode("./Name").InnerText; Assert.IsFalse(string.IsNullOrWhiteSpace(name)); string path = entryNode.SelectSingleNode("./Path").InnerText; Assert.IsFalse(string.IsNullOrWhiteSpace(path)); string type = entryNode.SelectSingleNode("./Type").InnerText; Assert.IsFalse(string.IsNullOrWhiteSpace(type)); Assert.IsTrue(paths.ContainsKey(name)); Assert.AreEqual(paths[name], path); paths.Remove(name); Assert.IsTrue(types.ContainsKey(name)); Assert.AreEqual(types[name], type); types.Remove(name); } } [TestMethod] public void Deserialize() { string xml = @"<?xml version=""1.0"" encoding=""utf-16""?> <ArrayOfEntry xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <Entry> <Name>Name 1</Name> <Path>C:\somewhere\here</Path> <Type>git</Type> </Entry> <Entry> <Name>Name 2</Name> <Path>C:\somewhere\there</Path> <Type>gut</Type> </Entry> <Entry> <Name>Name 3</Name> <Path>D:\else\where</Path> <Type>good</Type> </Entry> </ArrayOfEntry>"; Dictionary<string, string> paths = new Dictionary<string, string>(); paths["Name 1"] = @"C:\somewhere\here"; paths["Name 2"] = @"C:\somewhere\there"; paths["Name 3"] = @"D:\else\where"; Dictionary<string, string> types = new Dictionary<string, string>(); types["Name 1"] = @"git"; types["Name 2"] = @"gut"; types["Name 3"] = @"good"; using (StringReader rdr = new StringReader(xml)) { XmlSerializer ser = new XmlSerializer(typeof(Entry[])); Entry[] es = ser.Deserialize(rdr) as Entry[]; Assert.AreEqual(3, es.Length); foreach (Entry e in es) { Assert.IsTrue(paths.ContainsKey(e.Name)); Assert.AreEqual(paths[e.Name], e.Path); paths.Remove(e.Name); Assert.IsTrue(types.ContainsKey(e.Name)); Assert.AreEqual(types[e.Name], e.Type); types.Remove(e.Name); } } } [TestMethod] public void RoundTrip() { Dictionary<string, string> paths = new Dictionary<string, string>(); paths["Name 1"] = @"C:\somewhere\here"; paths["Name 2"] = @"C:\somewhere\there"; paths["Name 3"] = @"D:\else\where"; Dictionary<string, string> types = new Dictionary<string, string>(); types["Name 1"] = @"git"; types["Name 2"] = @"gut"; types["Name 3"] = @"good"; ObservableCollection<Entry> entries = new ObservableCollection<Entry>(); entries.Add( new Entry() { Name = "Name 1", Path = paths["Name 1"], Type = types["Name 1"] }); entries.Add( new Entry() { Name = "Name 2", Path = paths["Name 2"], Type = types["Name 2"] }); entries.Add( new Entry() { Name = "Name 3", Path = paths["Name 3"], Type = types["Name 3"] }); string serialized = null; using (StringWriter wrtr = new StringWriter()) { XmlSerializer ser = new XmlSerializer(typeof(Entry[])); ser.Serialize(wrtr, entries.ToArray()); serialized = wrtr.ToString(); } Assert.IsFalse(string.IsNullOrWhiteSpace(serialized)); XmlDocument doc = new XmlDocument(); doc.LoadXml(serialized); Assert.AreEqual(doc.DocumentElement.LocalName, "ArrayOfEntry"); XmlNodeList entryNodes = doc.SelectNodes("//Entry"); Assert.AreEqual(3, entryNodes.Count); Assert.AreEqual(3, doc.DocumentElement.ChildNodes.Count); using (StringReader rdr = new StringReader(serialized)) { XmlSerializer ser = new XmlSerializer(typeof(Entry[])); Entry[] es = ser.Deserialize(rdr) as Entry[]; Assert.AreEqual(3, es.Length); foreach (Entry e in es) { Assert.IsTrue(paths.ContainsKey(e.Name)); Assert.AreEqual(paths[e.Name], e.Path); paths.Remove(e.Name); Assert.IsTrue(types.ContainsKey(e.Name)); Assert.AreEqual(types[e.Name], e.Type); types.Remove(e.Name); } } } [TestMethod] public void RoundTripOneEntry() { Dictionary<string, string> paths = new Dictionary<string, string>(); paths["Name 2"] = @"C:\somewhere\there"; Dictionary<string, string> types = new Dictionary<string, string>(); types["Name 2"] = @"gut"; ObservableCollection<Entry> entries = new ObservableCollection<Entry>(); entries.Add( new Entry() { Name = "Name 2", Path = paths["Name 2"], Type = types["Name 2"] }); string serialized = null; using (StringWriter wrtr = new StringWriter()) { XmlSerializer ser = new XmlSerializer(typeof(Entry[])); ser.Serialize(wrtr, entries.ToArray()); serialized = wrtr.ToString(); } Assert.IsFalse(string.IsNullOrWhiteSpace(serialized)); XmlDocument doc = new XmlDocument(); doc.LoadXml(serialized); Assert.AreEqual(doc.DocumentElement.LocalName, "ArrayOfEntry"); XmlNodeList entryNodes = doc.SelectNodes("//Entry"); Assert.AreEqual(1, entryNodes.Count); Assert.AreEqual(1, doc.DocumentElement.ChildNodes.Count); using (StringReader rdr = new StringReader(serialized)) { XmlSerializer ser = new XmlSerializer(typeof(Entry[])); Entry[] es = ser.Deserialize(rdr) as Entry[]; Assert.AreEqual(1, es.Length); foreach (Entry e in es) { Assert.IsTrue(paths.ContainsKey(e.Name)); Assert.AreEqual(paths[e.Name], e.Path); paths.Remove(e.Name); Assert.IsTrue(types.ContainsKey(e.Name)); Assert.AreEqual(types[e.Name], e.Type); types.Remove(e.Name); } } } [TestMethod] public void RoundTripEmpty() { ObservableCollection<Entry> entries = new ObservableCollection<Entry>(); string serialized = null; using (StringWriter wrtr = new StringWriter()) { XmlSerializer ser = new XmlSerializer(typeof(Entry[])); ser.Serialize(wrtr, entries.ToArray()); serialized = wrtr.ToString(); } Assert.IsFalse(string.IsNullOrWhiteSpace(serialized)); XmlDocument doc = new XmlDocument(); doc.LoadXml(serialized); Assert.AreEqual(doc.DocumentElement.LocalName, "ArrayOfEntry"); Assert.AreEqual(0, doc.DocumentElement.ChildNodes.Count); using (StringReader rdr = new StringReader(serialized)) { XmlSerializer ser = new XmlSerializer(typeof(Entry[])); Entry[] es = ser.Deserialize(rdr) as Entry[]; Assert.IsNotNull(es); Assert.AreEqual(0, es.Length); } } } }
27.488673
118
0.623146
[ "Apache-2.0" ]
sgrottel/checkouts-overview
Test/TestEntryListIO.cs
8,494
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace Chronokeep.Updates { public class Version { public int major; public int minor; public int patch; public Version() { major = 0; minor = 0; patch = 0; } public bool Equal(Version other) { return this.major == other.major && this.minor == other.minor && this.patch == other.patch; } public bool Newer(Version other) { if ((this.major > other.major) || (this.major == other.major && this.minor > other.minor) || (this.major == other.major && this.minor == other.minor && this.patch > other.patch)) { return true; } return false; } public void Set(Version other) { this.major = other.major; this.minor = other.minor; this.patch = other.patch; } public override string ToString() { return string.Format("v{0}.{1}.{2}", major, minor, patch); } } public class Check { private static string RepoURL = "https://api.github.com/repos/grecaun/chronokeep-windows/releases"; public static async void Do() { string curVersion; using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Chronokeep." + "version.txt")) { using (StreamReader reader = new StreamReader(stream)) { curVersion = reader.ReadToEnd(); } } Version current = new Version(); string[] version = curVersion.Split('.'); if (version.Length >= 3) { current.major = int.Parse(version[0].Replace("v", "")); current.minor = int.Parse(version[1]); current.patch = int.Parse(version[2].Split('-')[0]); } Log.D("Updates.Check", string.Format("Current version found {0}", current.ToString())); List<GithubRelease> releases = null; try { releases = await GetReleases(); } catch (Exception ex) { Log.E("Updates.Check", ex.Message); MessageBox.Show("Unable to check for update.", "Error"); return; } GithubRelease latestRelease = null; Version latestVersion = new Version(); foreach (GithubRelease release in releases) { Version releaseVersion = new Version(); version = release.Name.Split('.'); if (version.Length >= 3) { releaseVersion.major = int.Parse(version[0].Replace("v", "")); releaseVersion.minor = int.Parse(version[1]); releaseVersion.patch = int.Parse(version[2].Split('-')[0]); } // Check for major version updates // Then minor version updates // patches if (releaseVersion.Newer(latestVersion)) { latestRelease = release; latestVersion.Set(releaseVersion); } } Log.D("Updates.Check", string.Format("Latest version is {0}", latestVersion.ToString())); if (latestVersion.Newer(current)) { Log.D("Updates.Check", "Newer version found."); DownloadWindow downloadWindow = new DownloadWindow(latestRelease, latestVersion); downloadWindow.ShowDialog(); } } private static async Task<List<GithubRelease>> GetReleases() { Log.D("Updates.Check", "Getting releases."); string content = ""; try { using (var client = GetHttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, RepoURL); HttpResponseMessage response = await client.SendAsync(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { Log.D("Updates.Check", "Status Code OK"); var json = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<List<GithubRelease>>(json); return result; } Log.D("Updates.Check", "Status Code not OK"); content = await response.Content.ReadAsStringAsync(); } } catch (Exception ex) { throw new Exception("Exception thrown getting releases: " + ex.Message + " - " + ex.InnerException); } throw new Exception(string.Format("Unable to get releases. {0}", content)); } private static HttpClient GetHttpClient() { var handler = new WinHttpHandler(); var client = new HttpClient(handler); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.UserAgent.TryParseAdd("Chronokeep Desktop Application"); return client; } } }
35.888199
124
0.518865
[ "MIT" ]
grecaun/chronokeep-windows
ChronoKeep/Updates/Check.cs
5,780
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("ECE2310_HW01_01")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("ECE2310_HW01_01")] [assembly: System.Reflection.AssemblyTitleAttribute("ECE2310_HW01_01")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.458333
80
0.652261
[ "MIT" ]
ariyonaty/ECE2310
HW01/ECE2310_HW01_01/obj/Debug/netcoreapp3.1/ECE2310_HW01_01.AssemblyInfo.cs
995
C#
using System; using System.Windows; using System.Data.SQLite; using System.Data; namespace Bancofinal { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { PaginaConta pagConta; public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Persistencia per = new Persistencia(); try { int j = Convert.ToInt32(numconta.Text); Conta c = per.AchaConta(j); if (c != null) { pagConta = new PaginaConta(); pagConta.SetConta(c); pagConta.Transf.Click += Button_Click_2; pagConta.Saq.Click += Button_Click_0; pagConta.Dep.Click += Button_Click_1; this.Content = pagConta; } else error.Text = "Conta inválida"; } catch { error.Text = "Informe um valor"; } } private void Button_Click_0(object sender, RoutedEventArgs e) { Saque x = new Saque(); x.oksaq.Click += OKsaq; x.sairsaq.Click += Sairsaq; this.Content = x; } private void Button_Click_1(object sender, RoutedEventArgs e) { Deposito k = new Deposito(); k.Okdep.Click += Okdep; k.Sairdep.Click += Sairdep; this.Content = k; } private void Button_Click_2(object sender, RoutedEventArgs e) { Transferencia y = new Transferencia(); y.oktransf.Click += OKtransf; y.sairtrans.Click += Sairtransf; this.Content = y; } private void Okdep(object sender, RoutedEventArgs e) { //double valor = Convert.ToDouble(deposito.Text); //Conta.Dep(valor); confirmadeposito c = new confirmadeposito(); c.acceptdep.Click += Accept_Click_dep; c.Canceldep.Click += Cancelar_Click_dep; this.Content = c; } private void Sairdep(object sender, RoutedEventArgs e) { this.Content = pagConta; } private void OKsaq(object sender, RoutedEventArgs e) { //double valor = Convert.ToDouble(saque.Text); //Conta.Saca(valor); confirmasaque j = new confirmasaque(); j.Confsaq.Click += Confsaq_Click; j.Cancsaque.Click += Cancelarsaq_Click; this.Content = j; } private void Sairsaq(object sender, RoutedEventArgs e) { this.Content = pagConta; } private void OKtransf(object sender, RoutedEventArgs e) { confirmartransf l = new confirmartransf(); l.conftransf.Click += Conftransf; l.Canctransf.Click += Canctransf; this.Content = l; } private void Sairtransf(object sender, RoutedEventArgs e) { this.Content = pagConta; } private void Cancelar_Click_dep(object sender, RoutedEventArgs e) { Deposito k = new Deposito(); this.Content = k; } private void Accept_Click_dep(object sender, RoutedEventArgs e) { } private void Cancelarsaq_Click(object sender, RoutedEventArgs e) { Saque x = new Saque(); this.Content = x; } private void Confsaq_Click(object sender, RoutedEventArgs e) { } private void Canctransf(object sender, RoutedEventArgs e) { Transferencia y = new Transferencia(); this.Content = y; } private void Conftransf(object sender, RoutedEventArgs e) { } } }
27.424837
74
0.501192
[ "MIT" ]
chipana/ChipanaBank
Bancofinal/MainWindow.xaml.cs
4,199
C#
using Domain.Aggregates; using EventSourcing.Sample.Clients.Contracts.Clients.DTOs; using System; namespace EventSourcing.Sample.Clients.Domain.Clients { public class Client : IAggregate { public Guid Id { get; private set; } public string Name { get; private set; } public string Email { get; private set; } public Client() { } public Client(Guid id, string name, string email) { Id = id; Name = name; Email = email; } public void Update(ClientInfo clientInfo) { Name = clientInfo.Name; Email = clientInfo.Email; } } }
20.5
58
0.558106
[ "MIT" ]
BienioM/EventSourcing.NetCore
Sample/EventSourcing.Sample.Clients/Domain/Clients/Client.cs
699
C#
using System.Collections.Generic; using UnityEngine; using CommonCore.World; namespace CommonCore.State { //EDIT THIS FILE AND PUT YOUR GAME DATA HERE public sealed partial class MetaState { //PUT ANY STATE VARIABLES YOU WANT HERE } }
19.5
55
0.684982
[ "MIT" ]
XCVG/californium_dr
Assets/CommonCoreGame/RPGGame/State/MetaState.cs
275
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.PowerShell.Cmdlets.Websites.Helper.Network.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Parameters that define the retention policy for flow log. /// </summary> public partial class RetentionPolicyParameters { /// <summary> /// Initializes a new instance of the RetentionPolicyParameters class. /// </summary> public RetentionPolicyParameters() { CustomInit(); } /// <summary> /// Initializes a new instance of the RetentionPolicyParameters class. /// </summary> /// <param name="days">Number of days to retain flow log /// records.</param> /// <param name="enabled">Flag to enable/disable retention.</param> public RetentionPolicyParameters(int? days = default(int?), bool? enabled = default(bool?)) { Days = days; Enabled = enabled; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets number of days to retain flow log records. /// </summary> [JsonProperty(PropertyName = "days")] public int? Days { get; set; } /// <summary> /// Gets or sets flag to enable/disable retention. /// </summary> [JsonProperty(PropertyName = "enabled")] public bool? Enabled { get; set; } } }
32.606557
100
0.588738
[ "MIT" ]
Agazoth/azure-powershell
src/Websites/Websites.Helper/Network/Models/RetentionPolicyParameters.cs
1,929
C#
using System; using System.Text; using System.Net; using System.Net.Sockets; using Z.Tools; namespace Z { public class TcpClient { #region Elements protected Socket dasSocket; protected byte[] buffer = new byte[1024]; //for receive protected int BufferSize = 1024; protected byte[] sendDataBuffer; //for send protected bool isSpitePackage ; protected int restPackage = -1; protected int bufferIndex ; protected int maxSinglePackageSize = 1024; public Func<byte[],byte[]> OnReceived; #endregion public TcpClient(string _ServerIpAddr, int _ServerPort, Func<byte[],byte[]> OnReceived, IPType ipType = IPType.IPv4) { if(ipType == IPType.IPv6) dasSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); else dasSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipa = IPAddress.Parse(_ServerIpAddr); IPEndPoint ipe = new IPEndPoint(ipa, _ServerPort); this.OnReceived = OnReceived; dasSocket.BeginConnect(ipe, new AsyncCallback(ConnectAsynCallBack), dasSocket); } #region CallBack Stuff void ConnectAsynCallBack(IAsyncResult ar) { Socket socketHandler = (Socket)ar.AsyncState; try { socketHandler.EndConnect(ar); socketHandler.BeginReceive( buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(ReceivedAsynCallBack), socketHandler ); } catch (Exception e) { Logger.LogError("[TcpClient] Remote computer reject this request" + e.Message + "\n"); } } void ReceivedAsynCallBack(IAsyncResult ar) { Socket socketHandler = (Socket)ar.AsyncState; int byteLength = socketHandler.EndReceive(ar); if (byteLength > 0) { if (OnReceived != null) { byte[] result = OnReceived(buffer); if (result != null && result.Length > 0) SendDataToServer(result); } } socketHandler.BeginReceive( buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(ReceivedAsynCallBack), socketHandler ); } void SendAsynCallBack(IAsyncResult ar) { try { Socket socketHandler = (Socket)ar.AsyncState; socketHandler.EndSend(ar); } catch (Exception e) { Logger.LogError(e.Message); } } #endregion #region Facade Zone public void SendDataToServer(byte[] msg) { if (!dasSocket.Connected) { Logger.LogError("TcpClient has not Connected"); return; } dasSocket.BeginSend( msg, 0, msg.Length, 0, new AsyncCallback(SendAsynCallBack), dasSocket ); } #endregion } }
25.957143
125
0.491194
[ "MIT" ]
DASTUDIO/EZServer
System/Tcp/TcpClient.cs
3,636
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; namespace Taitans.Owin.Security.QQ.FrameworkExample.Models { public class IndexViewModel { public bool HasPassword { get; set; } public IList<UserLoginInfo> Logins { get; set; } public string PhoneNumber { get; set; } public bool TwoFactor { get; set; } public bool BrowserRemembered { get; set; } } public class ManageLoginsViewModel { public IList<UserLoginInfo> CurrentLogins { get; set; } public IList<AuthenticationDescription> OtherLogins { get; set; } } public class FactorViewModel { public string Purpose { get; set; } } public class SetPasswordViewModel { [Required] [StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "新密码")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "确认新密码")] [Compare("NewPassword", ErrorMessage = "新密码和确认密码不匹配。")] public string ConfirmPassword { get; set; } } public class ChangePasswordViewModel { [Required] [DataType(DataType.Password)] [Display(Name = "当前密码")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "新密码")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "确认新密码")] [Compare("NewPassword", ErrorMessage = "新密码和确认密码不匹配。")] public string ConfirmPassword { get; set; } } public class AddPhoneNumberViewModel { [Required] [Phone] [Display(Name = "电话号码")] public string Number { get; set; } } public class VerifyPhoneNumberViewModel { [Required] [Display(Name = "代码")] public string Code { get; set; } [Required] [Phone] [Display(Name = "电话号码")] public string PhoneNumber { get; set; } } public class ConfigureTwoFactorViewModel { public string SelectedProvider { get; set; } public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; } } }
28.686047
84
0.610053
[ "MIT" ]
taitans/Security
samples/Taitans.Owin.Security.QQ.FrameworkExample/Models/ManageViewModels.cs
2,617
C#
/* selfgenerated from version 0.0.0.1 28/08/2018 10:05:16 */ using System; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; using ContactHubSdkLibrary.Events; using ContactHubSdkLibrary; using Newtonsoft.Json.Linq; namespace ContactHubSdkLibrary.Events { //context class 'CONTACT_CENTER': CONTACT_CENTER public class EventContextPropertyCONTACT_CENTER: EventBaseProperty { public Client client {get;set;} public User user {get;set;} } public class Client { public string userAgent {get;set;} //format: ipv4 public string ip {get;set;} public Localization localization {get;set;} } public class Localization { public string city {get;set;} public string country {get;set;} public string region {get;set;} public string province {get;set;} public string zip {get;set;} public Geo geo {get;set;} } public class User { [Display(Name="The identifier of the user")] public string id {get;set;} [Display(Name="The external identifier of the user")] public string externalId {get;set;} [Display(Name="The username of the user")] public string username {get;set;} [Display(Name="The first name of the user")] public string firstName {get;set;} [Display(Name="The last name of the user")] public string lastName {get;set;} public Contacts contacts {get;set;} } //context class 'WEB': WEB public class EventContextPropertyWEB: EventBaseProperty { public Client client {get;set;} public User user {get;set;} } //context class 'MOBILE': MOBILE public class EventContextPropertyMOBILE: EventBaseProperty { public Client client {get;set;} public Device device {get;set;} public User user {get;set;} } public class Device { public string bundleIdentifier {get;set;} public string versionNumber {get;set;} public string buildNumber {get;set;} public string identifierForVendor {get;set;} public string systemVersion {get;set;} public string model {get;set;} public string deviceVendor {get;set;} public string locale {get;set;} public string language {get;set;} } //context class 'ECOMMERCE': ECOMMERCE public class EventContextPropertyECOMMERCE: EventBaseProperty { public Client client {get;set;} public Store store {get;set;} public User user {get;set;} } public class Store { public string id {get;set;} public string name {get;set;} [JsonProperty("type")]public string _type {get;set;} [JsonProperty("hidden_type")][JsonIgnore] public StoreTypeEnum type { get { StoreTypeEnum enumValue =ContactHubSdkLibrary.EnumHelper<StoreTypeEnum>.GetValueFromDisplayName(_type); return enumValue; } set { var displayValue = ContactHubSdkLibrary.EnumHelper<StoreTypeEnum>.GetDisplayValue(value); _type = (displayValue=="NoValue"? null : displayValue); } } public string street {get;set;} public string city {get;set;} public string country {get;set;} public string province {get;set;} public string region {get;set;} public string zip {get;set;} public Geo geo {get;set;} public string website {get;set;} } public enum StoreTypeEnum { NoValue, [Display(Name="AIRPORT")] AIRPORT, [Display(Name="ECOMMERCE")] ECOMMERCE, [Display(Name="FLAGSHIP")] FLAGSHIP, [Display(Name="FREE-STANDING")] FREEMinusSTANDING, [Display(Name="MALL")] MALL, [Display(Name="OUTLET")] OUTLET, [Display(Name="RESORT")] RESORT, [Display(Name="SIS")] SIS, [Display(Name="WAREHOUSE")] WAREHOUSE, [Display(Name="NOT-DEFINED")] NOTMinusDEFINED } //context class 'RETAIL': RETAIL public class EventContextPropertyRETAIL: EventBaseProperty { public Client client {get;set;} public SalesAssistant salesAssistant {get;set;} public Store store {get;set;} public User user {get;set;} } public class SalesAssistant { [Display(Name="The identifier of the sales assistant")] public string id {get;set;} [Display(Name="The first name of the sales assistant")] public string firstName {get;set;} [Display(Name="The last name of the sales assistant")] public string lastName {get;set;} public Contacts contacts {get;set;} } //context class 'IOT': IOT public class EventContextPropertyIOT: EventBaseProperty { public Client client {get;set;} public User user {get;set;} } //context class 'SOCIAL': SOCIAL public class EventContextPropertySOCIAL: EventBaseProperty { public Client client {get;set;} public User user {get;set;} } //context class 'DIGITAL_CAMPAIGN': DIGITAL_CAMPAIGN public class EventContextPropertyDIGITAL_CAMPAIGN: EventBaseProperty { public Client client {get;set;} public User user {get;set;} } //context class 'OTHER': OTHER public class EventContextPropertyOTHER: EventBaseProperty { public Client client {get;set;} public User user {get;set;} } } public enum EventContextEnum { NoValue, [Display(Name="CONTACT_CENTER")] CONTACTCENTER, [Display(Name="WEB")] WEB, [Display(Name="MOBILE")] MOBILE, [Display(Name="ECOMMERCE")] ECOMMERCE, [Display(Name="RETAIL")] RETAIL, [Display(Name="IOT")] IOT, [Display(Name="SOCIAL")] SOCIAL, [Display(Name="DIGITAL_CAMPAIGN")] DIGITALCAMPAIGN, [Display(Name="OTHER")] OTHER } public static class EventPropertiesContextUtil { /// <summary> /// Return events context properties with right cast, event type based /// </summary> public static object GetEventContext(JObject jo, JsonSerializer serializer) { var typeName = jo["context"].ToString().ToLowerInvariant(); switch (typeName) { case "contact_center": return jo["contextInfo"].ToObject<EventContextPropertyCONTACT_CENTER > (serializer);break; case "web": return jo["contextInfo"].ToObject<EventContextPropertyWEB > (serializer);break; case "mobile": return jo["contextInfo"].ToObject<EventContextPropertyMOBILE > (serializer);break; case "ecommerce": return jo["contextInfo"].ToObject<EventContextPropertyECOMMERCE > (serializer);break; case "retail": return jo["contextInfo"].ToObject<EventContextPropertyRETAIL > (serializer);break; case "iot": return jo["contextInfo"].ToObject<EventContextPropertyIOT > (serializer);break; case "social": return jo["contextInfo"].ToObject<EventContextPropertySOCIAL > (serializer);break; case "digital_campaign": return jo["contextInfo"].ToObject<EventContextPropertyDIGITAL_CAMPAIGN > (serializer);break; case "other": return jo["contextInfo"].ToObject<EventContextPropertyOTHER > (serializer);break; } return null; } }
27.007722
134
0.683202
[ "Apache-2.0" ]
contactlab/contacthub-sdk-dotnet
ContactHubSdkLibrary/ContactHubSdkLibrary/PropertiesClasses/20180903eventContextClass.cs
6,995
C#
namespace Coimbra { /// <summary> /// Define where to keep the available instances. /// </summary> public enum PoolContainerMode { /// <summary> /// Let the <see cref="Pool"/> create a container for it's objects. /// </summary> Automatic, /// <summary> /// Manually choose a parent to be the <see cref="Pool"/>'s container. /// </summary> Manual } }
24.388889
78
0.530752
[ "MIT" ]
coimbrastudios/object-pool
Runtime/Coimbra.Pooling/Enums/PoolContainerMode.cs
441
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DeusClientCore.Events { /// <summary> /// Args for the socket's events /// </summary> public class SocketEventArgs : EventArgs { /// <summary> /// Unique identifier of the source of the event /// </summary> private int m_idSource; /// <summary> /// Get the unique identifier of the source of the event /// </summary> public int IdSource { get { return m_idSource; } } /// <summary> /// Init new instance of <see cref="SocketEventArgs"/> /// </summary> /// <param name="idSource">Unique identifier of the source of the event</param> public SocketEventArgs(int idSource) { m_idSource = idSource; } } }
27.029412
88
0.568009
[ "MIT" ]
Suliac/ProjectDeusClient
DeusClientCore/DeusClientCore/Events/SocketEventArgs.cs
921
C#
using System; using System.Globalization; using System.Text.RegularExpressions; class DatesFromTextInCanada { static void Main() { string randomText = Console.ReadLine(); foreach (Match item in Regex.Matches(randomText, @"\b[0-9]{1,2}.[0-9]{1,2}.[0-9]{2,4}")) { DateTime date; if (DateTime.TryParseExact(item.Value, "d.M.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { Console.WriteLine(date.ToString(CultureInfo.GetCultureInfo("en-CA").DateTimeFormat.ShortDatePattern)); } } Console.WriteLine(); } }
26.44
118
0.600605
[ "MIT" ]
iliyaST/TelericAcademy
C#2/6-Strings-And-Text-Processing/19.DatesFromTextInCanada/Program.cs
663
C#