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
// 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.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Loader; using System.Threading.Tasks; using Microsoft.Build.Construction; using Microsoft.Build.Definition; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Locator; using Microsoft.Build.Logging; using Semver; namespace Microsoft.Tye { public static class ProjectReader { private static object @lock = new object(); private static bool registered; public static IEnumerable<FileInfo> EnumerateProjects(FileInfo solutionFile) { EnsureMSBuildRegistered(null, solutionFile); return EnumerateProjectsCore(solutionFile); } // Do not load MSBuild types before using EnsureMSBuildRegistered. [MethodImpl(MethodImplOptions.NoInlining)] private static IEnumerable<FileInfo> EnumerateProjectsCore(FileInfo solutionFile) { var solution = SolutionFile.Parse(solutionFile.FullName); foreach (var project in solution.ProjectsInOrder) { if (project.ProjectType != SolutionProjectType.KnownToBeMSBuildFormat) { continue; } var extension = Path.GetExtension(project.AbsolutePath).ToLower(); switch (extension) { case ".csproj": case ".fsproj": break; default: continue; } yield return new FileInfo(project.AbsolutePath.Replace('\\', '/')); } } public static Task ReadProjectDetailsAsync(OutputContext output, ProjectServiceBuilder project) { if (output is null) { throw new ArgumentNullException(nameof(output)); } if (project is null) { throw new ArgumentNullException(nameof(project)); } EnsureMSBuildRegistered(output, project.ProjectFile); EvaluateProject(output, project); if (!SemVersion.TryParse(project.Version, out var version)) { output.WriteInfoLine($"No version or invalid version '{project.Version}' found, using default."); version = new SemVersion(0, 1, 0); project.Version = version.ToString(); } return Task.CompletedTask; } private static void EnsureMSBuildRegistered(OutputContext? output, FileInfo projectFile) { if (!registered) { lock (@lock) { output?.WriteDebugLine("Locating .NET SDK..."); // It says VisualStudio - but we'll just use .NET SDK var instances = MSBuildLocator.QueryVisualStudioInstances(new VisualStudioInstanceQueryOptions() { DiscoveryTypes = DiscoveryType.DotNetSdk, // Using the project as the working directory. We're making the assumption that // all of the projects want to use the same SDK version. This library is going // load a single version of the SDK's assemblies into our process, so we can't // use support SDKs at once without getting really tricky. // // The .NET SDK-based discovery uses `dotnet --info` and returns the SDK // in use for the directory. // // https://github.com/microsoft/MSBuildLocator/blob/master/src/MSBuildLocator/MSBuildLocator.cs#L320 WorkingDirectory = projectFile.DirectoryName, }); var instance = instances.SingleOrDefault(); if (instance == null) { throw new CommandException("Failed to find dotnet. Make sure the .NET SDK is installed and on the PATH."); } output?.WriteDebugLine("Found .NET SDK at: " + instance.MSBuildPath); try { MSBuildLocator.RegisterInstance(instance); output?.WriteDebug("Registered .NET SDK."); } finally { registered = true; } } } } [MethodImpl(MethodImplOptions.NoInlining)] private static void LogIt(OutputContext output) { output.WriteDebugLine("Loaded: " + typeof(ProjectInstance).Assembly.FullName); output.WriteDebugLine("Loaded From: " + typeof(ProjectInstance).Assembly.Location); } // Do not load MSBuild types before using EnsureMSBuildRegistered. [MethodImpl(MethodImplOptions.NoInlining)] private static void EvaluateProject(OutputContext output, ProjectServiceBuilder project) { var sw = Stopwatch.StartNew(); // Currently we only log at debug level. var logger = new ConsoleLogger( verbosity: LoggerVerbosity.Normal, write: message => output.WriteDebug(message), colorSet: null, colorReset: null); // We need to isolate projects from each other for testing. MSBuild does not support // loading the same project twice in the same collection. var projectCollection = new ProjectCollection(); ProjectInstance projectInstance; Microsoft.Build.Evaluation.Project msbuildProject; try { output.WriteDebugLine($"Loading project '{project.ProjectFile.FullName}'."); msbuildProject = Microsoft.Build.Evaluation.Project.FromFile(project.ProjectFile.FullName, new ProjectOptions() { ProjectCollection = projectCollection, GlobalProperties = project.BuildProperties }); projectInstance = msbuildProject.CreateProjectInstance(); output.WriteDebugLine($"Loaded project '{project.ProjectFile.FullName}'."); } catch (Exception ex) { throw new CommandException($"Failed to load project: '{project.ProjectFile.FullName}'.", ex); } try { AssemblyLoadContext.Default.Resolving += ResolveAssembly; output.WriteDebugLine($"Restoring project '{project.ProjectFile.FullName}'."); // Similar to what MSBuild does for restore: // https://github.com/microsoft/msbuild/blob/3453beee039fb6f5ccc54ac783ebeced31fec472/src/MSBuild/XMake.cs#L1417 // // We need to do restore as a separate operation var restoreRequest = new BuildRequestData( projectInstance, targetsToBuild: new[] { "Restore" }, hostServices: null, flags: BuildRequestDataFlags.ClearCachesAfterBuild | BuildRequestDataFlags.SkipNonexistentTargets | BuildRequestDataFlags.IgnoreMissingEmptyAndInvalidImports); var parameters = new BuildParameters(projectCollection) { Loggers = new[] { logger, }, }; // We don't really look at the result, because it's not clear we should halt totally // if restore fails. var restoreResult = BuildManager.DefaultBuildManager.Build(parameters, restoreRequest); output.WriteDebugLine($"Restored project '{project.ProjectFile.FullName}'."); msbuildProject.MarkDirty(); projectInstance = msbuildProject.CreateProjectInstance(); var targets = new List<string>() { "ResolveReferences", "ResolvePackageDependenciesDesignTime", "PrepareResources", "GetAssemblyAttributes", }; var result = projectInstance.Build( targets: targets.ToArray(), loggers: new[] { logger, }); // If the build fails, we're not really blocked from doing our work. // For now we just log the output to debug. There are errors that occur during // running these targets we don't really care as long as we get the data. } finally { AssemblyLoadContext.Default.Resolving -= ResolveAssembly; } // Reading a few different version properties to be more resilient. var version = projectInstance.GetProperty("AssemblyInformationalVersion")?.EvaluatedValue ?? projectInstance.GetProperty("InformationalVersion")?.EvaluatedValue ?? projectInstance.GetProperty("Version").EvaluatedValue; project.Version = version; output.WriteDebugLine($"Found application version: {version}"); var targetFrameworks = projectInstance.GetPropertyValue("TargetFrameworks"); project.TargetFrameworks = targetFrameworks.Split(';', StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>(); project.RunCommand = projectInstance.GetPropertyValue("RunCommand"); project.RunArguments = projectInstance.GetPropertyValue("RunArguments"); project.TargetPath = projectInstance.GetPropertyValue("TargetPath"); project.PublishDir = projectInstance.GetPropertyValue("PublishDir"); project.AssemblyName = projectInstance.GetPropertyValue("AssemblyName"); project.IntermediateOutputPath = projectInstance.GetPropertyValue("IntermediateOutputPath"); output.WriteDebugLine($"RunCommand={project.RunCommand}"); output.WriteDebugLine($"RunArguments={project.RunArguments}"); output.WriteDebugLine($"TargetPath={project.TargetPath}"); output.WriteDebugLine($"PublishDir={project.PublishDir}"); output.WriteDebugLine($"AssemblyName={project.AssemblyName}"); output.WriteDebugLine($"IntermediateOutputPath={project.IntermediateOutputPath}"); // Normalize directories to their absolute paths project.IntermediateOutputPath = Path.Combine(project.ProjectFile.DirectoryName, NormalizePath(project.IntermediateOutputPath)); project.TargetPath = Path.Combine(project.ProjectFile.DirectoryName, NormalizePath(project.TargetPath)); project.PublishDir = Path.Combine(project.ProjectFile.DirectoryName, NormalizePath(project.PublishDir)); var targetFramework = projectInstance.GetPropertyValue("TargetFramework"); project.TargetFramework = targetFramework; output.WriteDebugLine($"Found target framework: {targetFramework}"); // TODO: Parse the name and version manually out of the TargetFramework field if it's non-null project.TargetFrameworkName = projectInstance.GetPropertyValue("_ShortFrameworkIdentifier"); project.TargetFrameworkVersion = projectInstance.GetPropertyValue("_ShortFrameworkVersion") ?? projectInstance.GetPropertyValue("_TargetFrameworkVersionWithoutV"); var sharedFrameworks = projectInstance.GetItems("FrameworkReference").Select(i => i.EvaluatedInclude).ToList(); project.Frameworks.AddRange(sharedFrameworks.Select(s => new Framework(s))); output.WriteDebugLine($"Found shared frameworks: {string.Join(", ", sharedFrameworks)}"); bool PropertyIsTrue(string property) { return projectInstance.GetPropertyValue(property) is string s && !string.IsNullOrEmpty(s) && bool.Parse(s); } project.IsAspNet = project.Frameworks.Any(f => f.Name == "Microsoft.AspNetCore.App") || projectInstance.GetPropertyValue("MicrosoftNETPlatformLibrary") == "Microsoft.AspNetCore.App" || PropertyIsTrue("_AspNetCoreAppSharedFxIsEnabled") || PropertyIsTrue("UsingMicrosoftNETSdkWeb"); output.WriteDebugLine($"IsAspNet={project.IsAspNet}"); output.WriteDebugLine($"Evaluation Took: {sw.Elapsed.TotalMilliseconds}ms"); // The Microsoft.Build.Locator doesn't handle the loading of other assemblies // that are shipped with MSBuild (ex NuGet). // // This means that the set of assemblies that need special handling depends on the targets // that we run :( // // This is workaround for this limitation based on the targets we need to run // to resolve references and versions. // // See: https://github.com/microsoft/MSBuildLocator/issues/86 Assembly? ResolveAssembly(AssemblyLoadContext context, AssemblyName assemblyName) { if (assemblyName.Name is object) { var msbuildDirectory = Environment.GetEnvironmentVariable("MSBuildExtensionsPath")!; var assemblyFilePath = Path.Combine(msbuildDirectory, assemblyName.Name + ".dll"); if (File.Exists(assemblyFilePath)) { return context.LoadFromAssemblyPath(assemblyFilePath); } } return default; } } private static string NormalizePath(string path) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return path.Replace('/', '\\'); } return path.Replace('\\', '/'); } } }
45.218069
179
0.596073
[ "MIT" ]
ArieJones/tye
src/Microsoft.Tye.Core/ProjectReader.cs
14,517
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ds-2015-04-16.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DirectoryService.Model { /// <summary> /// This is the response object from the ListIpRoutes operation. /// </summary> public partial class ListIpRoutesResponse : AmazonWebServiceResponse { private List<IpRouteInfo> _ipRoutesInfo = new List<IpRouteInfo>(); private string _nextToken; /// <summary> /// Gets and sets the property IpRoutesInfo. /// <para> /// A list of <a>IpRoute</a>s. /// </para> /// </summary> public List<IpRouteInfo> IpRoutesInfo { get { return this._ipRoutesInfo; } set { this._ipRoutesInfo = value; } } // Check to see if IpRoutesInfo property is set internal bool IsSetIpRoutesInfo() { return this._ipRoutesInfo != null && this._ipRoutesInfo.Count > 0; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// If not null, more results are available. Pass this value for the <i>NextToken</i> /// parameter in a subsequent call to <a>ListIpRoutes</a> to retrieve the next set of /// items. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
31.064935
100
0.623328
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/DirectoryService/Generated/Model/ListIpRoutesResponse.cs
2,392
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace YS.Knife.Data.FilterExpressions.Converters { [FilterConverter(FilterType.Exists)] internal class ExistsExpressionConverter : OpenExpressionConverter { private static readonly MethodInfo AnyMethod0 = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).First(p => p.Name == nameof(Enumerable.Any) && p.GetParameters().Length == 1); private static readonly MethodInfo AnyMethod1 = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).First(p => p.Name == nameof(Enumerable.Any) && p.GetParameters().Length == 2); public override Expression ConvertValue(Expression p, PropertyInfo propInfo, object value, List<FilterInfo> subFilters) { var trimFilters = subFilters.TrimNotNull().ToList(); if (trimFilters.Count == 0) { var (_, propType) = propInfo.PropertyType.GetUnderlyingTypeTypeInfo(); var subType = propType.GetEnumerableSubType(); return Expression.Call(AnyMethod0.MakeGenericMethod(subType), Expression.Property(p, propInfo)); } if (trimFilters.Count == 1) { return CreateAnyMethod1Expression(p, propInfo, trimFilters.First()); } else { return CreateAnyMethod1Expression(p, propInfo, FilterInfo.CreateAnd(trimFilters.ToArray())); } } private static Expression CreateAnyMethod1Expression(Expression p, PropertyInfo propInfo, FilterInfo filterInfo) { var (_, propType) = propInfo.PropertyType.GetUnderlyingTypeTypeInfo(); var subType = propType.GetEnumerableSubType(); var innerExpression = filterInfo.CreatePredicate(subType); var propExpression = Expression.Property(p, propInfo); return Expression.Call(AnyMethod1.MakeGenericMethod(subType), propExpression, innerExpression); } } }
43.714286
163
0.661531
[ "MIT" ]
obpt123/ys.knife
src/YS.Knife.Data/Data/FilterExpressions/Converters/ExistsExpressionConverter.cs
2,144
C#
using Demo.Scaffold.Tool.Changes; using Demo.Scaffold.Tool.Interfaces; using Demo.Scaffold.Tool.Scaffolders.OutputCollectors.Endpoint.InputCollectors; using Demo.Scaffold.Tool.Scaffolders.OutputCollectors.Endpoint.OutputCollectors; using System.Collections.Generic; using System.Linq; namespace Demo.Scaffold.Tool.Scaffolders.OutputCollectors.Endpoint { internal class EndpointOutputCollector : IOutputCollector { private List<IInputCollector> _inputCollectors = new List<IInputCollector>() { new CommandOrQueryInputCollector(), new ControllerNameInputCollector() }; private List<IOutputCollector> _outputCollectors = new List<IOutputCollector>() { new EndpointTypeOutputCollector(), }; public IEnumerable<IChange> CollectChanges(ScaffolderContext context) { foreach (var inputCollector in _inputCollectors) { inputCollector.CollectInput(context); } var changes = _outputCollectors .Select(x => x.CollectChanges(context)) .SelectMany(x => x) .Where(x => x != null) .ToList(); return changes; } } }
31.6
87
0.64557
[ "MIT" ]
nvdvlies/aspnet-core-api-demo
tools/Demo.Scaffold.Tool/Scaffolders/OutputCollectors/Endpoint/EndpointOutputCollector.cs
1,266
C#
namespace grate.Infrastructure { public class MariaDbSyntax : ISyntax { public string StatementSeparatorRegex { get { const string strings = @"(?<KEEP1>'[^']*')"; const string dashComments = @"(?<KEEP1>--.*$)"; const string starComments = @"(?<KEEP1>/\*[\S\s]*?\*/)"; const string separator = @"(?<KEEP1>^|\s)(?<BATCHSPLITTER>GO)(?<KEEP2>\s|;|$)"; return strings + "|" + dashComments + "|" + starComments + "|" + separator; } } public string CurrentDatabase => "SELECT DATABASE()"; public string ListDatabases => "SHOW DATABASES"; public string VarcharType => "varchar"; public string TextType => "text"; public string BooleanType => "boolean"; public string PrimaryKeyColumn(string columnName) => $"{columnName} bigint NOT NULL AUTO_INCREMENT"; public string CreateSchema(string schemaName) => @$"CREATE SCHEMA {schemaName}"; public string CreateDatabase(string databaseName) => @$"CREATE DATABASE {databaseName}"; public string DropDatabase(string databaseName) => @$"DROP DATABASE IF EXISTS `{databaseName}`;"; public string TableWithSchema(string schemaName, string tableName) => $"{schemaName}_{tableName}"; public string ReturnId => ";SELECT LAST_INSERT_ID();"; public string TimestampType => "timestamp"; public string Quote(string text) => $"`{text}`"; public string PrimaryKeyConstraint(string tableName, string column) => $",\nCONSTRAINT PK_{tableName}_{column} PRIMARY KEY ({column})"; public string LimitN(string sql, int n) => sql + "\nLIMIT 1"; } }
51.088235
143
0.604491
[ "MIT" ]
OzBob/grate
grate/Infrastructure/MariaDbSyntax.cs
1,739
C#
// ******************************************************* // // Copyright (C) Microsoft. All rights reserved. // // ******************************************************* [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Zentity.Services", Justification="Suppressed as per design")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Zentity.Services.HttpAuthentication")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Zentity.Services.ServiceHandler.#ProcessRequest(System.Web.HttpContext)", Justification="Catch exception to avoid crashing the application")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorIdAsRss(System.String,System.String,System.String)", Justification = "Supressed because it is giving spelling mistake for word 'Zentity', 'Rss'")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorNameAsRss(System.String,System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByCategoryIdAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByCategoryNameAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorEmailAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorIdAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorNameAsRss(System.String,System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByDateAddedAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByDateModifiedAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByTagIdAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByTagLabelAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Zentity")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Zentity", Scope = "namespace", Target = "Zentity.Services")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Zentity", Scope = "namespace", Target = "Zentity.Services.HttpAuthentication")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", Scope = "member", Target = "Zentity.Services.HttpAuthentication.HttpAuthenticationProvider.#OnAuthenticateRequest(System.Object,System.EventArgs)", Justification = @"This is not an event handler, actual event handler is in Global.asax which calls this method. It needs to have same parameters as the event handler, since this method actually processes the request. The processing is done in this method so that Global.asax event handlers for all services can call this method.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA2210:AssembliesShouldHaveValidStrongNames", Justification="Assemblies are delay signed")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorNameInDefaultFormat(System.String,System.String,System.String,System.String)", Justification = "Ignoring this warning.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorNameAsAtom(System.String,System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorNameAsRss(System.String,System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorEmailInDefaultFormat(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorEmailAsAtom(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorEmailAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorIdInDefaultFormat(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorIdAsAtom(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorIdAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByCategoryNameInDefaultFormat(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByCategoryNameAsAtom(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByCategoryNameAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByCategoryIdInDefaultFormat(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByCategoryIdAsAtom(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByCategoryIdAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorNameInDefaultFormat(System.String,System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorNameAsAtom(System.String,System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorNameAsRss(System.String,System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorEmailInDefaultFormat(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorEmailAsAtom(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorEmailAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorIdInDefaultFormat(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorIdAsAtom(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByContributorIdAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByDateAddedInDefaultFormat(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByDateAddedAsAtom(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByDateAddedAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByDateModifiedInDefaultFormat(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByDateModifiedAsAtom(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByDateModifiedAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByTagLabelInDefaultFormat(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByTagLabelAsAtom(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByTagLabelAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByTagIdInDefaultFormat(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByTagIdAsAtom(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByTagIdAsRss(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss", Scope = "member", Target = "Zentity.Services.IRepositoryFeed.#GetFeedByAuthorEmailAsRss(System.String,System.String,System.String)")]
236.5
330
0.818566
[ "MIT" ]
intj-t/Zenity
Product/Zentity.Services/Zentity.Services/GlobalSuppressions.cs
15,609
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class Engine { private RaceTower raceTower; public Engine(RaceTower raceTower) { this.raceTower = raceTower; } public void Run() { StringBuilder sb = new StringBuilder(); string output = ""; while (!raceTower.RaceOver()) { output = ""; string[] command = Console.ReadLine().Split(); string type = command[0]; List<string> commandArgs = command.Skip(1).ToList(); switch (type) { case "RegisterDriver": raceTower.RegisterDriver(commandArgs); break; case "Leaderboard": output = raceTower.GetLeaderboard(); break; case "CompleteLaps": output = raceTower.CompleteLaps(commandArgs); break; case "Box": raceTower.DriverBoxes(commandArgs); break; case "ChangeWeather": raceTower.ChangeWeather(commandArgs); break; default: Console.WriteLine("Invalid command"); break; } if (!string.IsNullOrEmpty(output)) { sb.AppendLine(output); } } sb.AppendLine(raceTower.GetWinner()); Console.WriteLine(sb.ToString().TrimEnd()); } }
26.032787
65
0.479219
[ "MIT" ]
NaskoVasilev/CSharp-OOP-Basics
RetakeExam-5 September 2017/GrandPrix/GrandPrix/Core/Engine.cs
1,590
C#
using System.Runtime.Serialization; namespace Shoko.Server.API.v2.Models { [DataContract] public class Sizes { [DataMember(IsRequired = false, EmitDefaultValue = false)] public int Episodes { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public int Specials { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public int Credits { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public int Trailers { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public int Parodies { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public int Others { get; set; } } }
30.307692
66
0.635787
[ "MIT" ]
EraYaN/ShokoServer
Shoko.Server/API/v2/Models/common/Sizes.cs
790
C#
/* * Your rights to use code governed by this license http://o-s-a.net/doc/license_simple_engine.pdf *Ваши права на использование кода регулируются данной лицензией http://o-s-a.net/doc/license_simple_engine.pdf */ using System; using System.Collections.Generic; using System.Drawing; using System.IO; using OsEngine.Entity; namespace OsEngine.Charts.CandleChart.Indicators { /// <summary> /// RSI indicator /// RSI. Relative Strength Index. Индикатор /// </summary> public class Rsi:IIndicatorCandle { /// <summary> /// constructor with parameters. Indicator will be saved /// конструктор с параметрами. Индикатор будет сохраняться /// </summary> /// <param name="uniqName">unique name/уникальное имя</param> /// <param name="canDelete">whether user can remove indicator from chart manually/можно ли пользователю удалить индикатор с графика вручную</param> public Rsi(string uniqName,bool canDelete) { Name = uniqName; TypeIndicator = IndicatorOneCandleChartType.Line; Lenght = 5; ColorBase = Color.Green; PaintOn = true; CanDelete = canDelete; Load(); } /// <summary> /// constructor without parameters.Indicator will not saved/конструктор без параметров. Индикатор не будет сохраняться /// used ONLY to create composite indicators/используется ТОЛЬКО для создания составных индикаторов /// Don't use it from robot creation layer/не используйте его из слоя создания роботов! /// </summary> /// <param name="canDelete">whether user can remove indicator from chart manually/можно ли пользователю удалить индикатор с графика вручную</param> public Rsi(bool canDelete) { Name = Guid.NewGuid().ToString(); TypeIndicator = IndicatorOneCandleChartType.Line; Lenght = 5; ColorBase = Color.Green; PaintOn = true; CanDelete = canDelete; } /// <summary> /// all indicator values /// все значения индикатора /// </summary> List<List<decimal>> IIndicatorCandle.ValuesToChart { get { List<List<decimal>> list = new List<List<decimal>>(); list.Add(Values); return list; } } /// <summary> /// indicator colors /// цвета для индикатора /// </summary> List<Color> IIndicatorCandle.Colors { get { List<Color> colors = new List<Color>(); colors.Add(ColorBase); return colors; } } /// <summary> /// whether indicator can be removed from chart. This is necessary so that robots can't be removed /можно ли удалить индикатор с графика. Это нужно для того чтобы у роботов нельзя было удалить /// indicators he needs in trading/индикаторы которые ему нужны в торговле /// </summary> public bool CanDelete { get; set; } /// <summary> /// indicator drawing type /// тип индикатора /// </summary> public IndicatorOneCandleChartType TypeIndicator { get; set; } /// <summary> /// unique indicator name /// уникальное имя индикатор /// </summary> public string Name { get; set; } /// <summary> /// name of data series on which indicator will be drawn /// имя серии данных на которой индикатор прорисовывается /// </summary> public string NameSeries { get; set; } /// <summary> /// name of data area where indicator will be drawn /// имя области данных на которой индикатор прорисовывается /// </summary> public string NameArea { get; set; } /// <summary> /// indicator calculation length /// длинна расчёта индикатора /// </summary> public int Lenght { get; set; } /// <summary> /// indicator color /// цвет индикатора /// </summary> public Color ColorBase { get; set; } /// <summary> /// is indicator tracing enabled /// включена ли прорисовка индикатора /// </summary> public bool PaintOn { get; set; } /// <summary> /// upload settings from file /// загрузить настройки из файла /// </summary> public void Load() { if (!File.Exists(@"Engine\" + Name + @".txt")) { return; } try { using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt")) { ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine())); Lenght = Convert.ToInt32(reader.ReadLine()); reader.Close(); } } catch (Exception) { // send to log // отправить в лог } } /// <summary> /// save settings to file /// сохранить настройки в файл /// </summary> public void Save() { try { if (string.IsNullOrWhiteSpace(Name)) { return; } using (StreamWriter writer = new StreamWriter(@"Engine\" + Name + @".txt", false)) { writer.WriteLine(ColorBase.ToArgb()); writer.WriteLine(Lenght); writer.Close(); } } catch (Exception) { // send to log // отправить в лог } } /// <summary> /// delete file with settings /// удалить файл с настройками /// </summary> public void Delete() { if (File.Exists(@"Engine\" + Name + @".txt")) { File.Delete(@"Engine\" + Name + @".txt"); } } /// <summary> /// delete data /// удалить данные /// </summary> public void Clear() { if (Values != null) { Values.Clear(); } _myCandles = null; } /// <summary> /// display settings window /// показать окно настроек /// </summary> public void ShowDialog() { RsiUi ui = new RsiUi(this); ui.ShowDialog(); if (ui.IsChange && _myCandles != null) { Reload(); } } /// <summary> /// reload indicator /// перезагрузить индикатор /// </summary> public void Reload() { if (_myCandles == null) { return; } ProcessAll(_myCandles); if (NeadToReloadEvent != null) { NeadToReloadEvent(this); } } /// <summary> /// indicator values /// данные индикатора /// </summary> public List<decimal> Values { get; set; } /// <summary> /// candles to calculate indicator /// свечи по которым строиться индикатор /// </summary> private List<Candle> _myCandles; /// <summary> /// indicator needs to be redrawn /// требуется перерисовать индикатор /// </summary> public event Action<IIndicatorCandle> NeadToReloadEvent; // calculation // вычисления /// <summary> /// to upload new candles /// прогрузить новыми свечками /// </summary> public void Process(List<Candle> candles) { if (candles == null) { return; } _myCandles = candles; if (Values != null && Values.Count + 1 == candles.Count) { ProcessOne(candles); } else if (Values != null && Values.Count == candles.Count) { ProcessLast(candles); } else { ProcessAll(candles); } } /// <summary> /// load only last candle /// прогрузить только последнюю свечку /// </summary> private void ProcessOne(List<Candle> candles) { if (candles == null) { return; } if (Values == null) { Values = new List<decimal>(); Values.Add(GetValue(candles, candles.Count - 1)); } else { Values.Add(GetValue(candles, candles.Count - 1)); } } /// <summary> /// to upload from the beginning /// прогрузить с самого начала /// </summary> private void ProcessAll(List<Candle> candles) { if (candles == null) { return; } Values = new List<decimal>(); for (int i = 0; i < candles.Count; i++) { Values.Add(GetValue(candles, i)); } } /// <summary> /// overload last value /// перегрузить последнее значение /// </summary> private void ProcessLast(List<Candle> candles) { if (candles == null) { return; } Values[Values.Count - 1] = GetValue(candles, candles.Count - 1); } /// <summary> /// take indicator value by index /// взять значение индикаторм по индексу /// </summary> private decimal GetValue(List<Candle> candles, int index) { if (index - Lenght - 1 <= 0) { return 0; } int startIndex = 1; if (index > 150) { startIndex = index - 150; } decimal[] priceChangeHigh = new decimal[candles.Count]; decimal[] priceChangeLow = new decimal[candles.Count]; decimal[] priceChangeHighAverage = new decimal[candles.Count]; decimal[] priceChangeLowAverage = new decimal[candles.Count]; for (int i = startIndex; i < candles.Count; i++) { if (candles[i].Close - candles[i - 1].Close > 0) { priceChangeHigh[i] = candles[i].Close - candles[i - 1].Close; priceChangeLow[i] = 0; } else { priceChangeLow[i] = candles[i - 1].Close - candles[i].Close; priceChangeHigh[i] = 0; } MovingAverageHard(priceChangeHigh, priceChangeHighAverage, Lenght, i); MovingAverageHard(priceChangeLow, priceChangeLowAverage, Lenght, i); } decimal averageHigh = priceChangeHighAverage[index]; decimal averageLow = priceChangeLowAverage[index]; decimal rsi; if (averageHigh != 0 && averageLow != 0) { rsi = 100 * (1 - averageLow / (averageLow + averageHigh)); //rsi = 100 - 100 / (1 + averageHigh / averageLow); } else { rsi = 100; } return Math.Round(rsi, 2); } /// <summary> /// take exponential average by index /// взять экспоненциальную среднюю по индексу /// </summary> /// <param name="valuesSeries">index data series/серия данных для расчета индекса</param> /// <param name="moving">previous average values/предыдущие значения средней</param> /// <param name="length">length of ma/длинна машки</param> /// <param name="index">index/индекс</param> private void MovingAverageHard(decimal[] valuesSeries, decimal[] moving, int length, int index) { if (index == length) { // it's first value. Calculate as simple ma // это первое значение. Рассчитываем как простую машку decimal lastMoving = 0; for (int i = index; i > index - 1 - length; i--) { lastMoving += valuesSeries[i]; } lastMoving = lastMoving / length; moving[index] = lastMoving; } else if (index > length) { // decimal a = 2.0m / (length * 2 - 0.15m); decimal a = Math.Round(2.0m / (length * 2), 7); decimal lastValueMoving = moving[index - 1]; decimal lastValueSeries = Math.Round(valuesSeries[index], 7); decimal nowValueMoving; //if (lastValueSeries != 0) // { nowValueMoving = Math.Round(lastValueMoving + a * (lastValueSeries - lastValueMoving), 7); // } // else // { // nowValueMoving = lastValueMoving; // } moving[index] = nowValueMoving; } } } }
29.934211
201
0.48022
[ "Apache-2.0" ]
22825usd/OsEngine
project/OsEngine/Charts/CandleChart/Indicators/Rsi.cs
14,890
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace LeagueDatabase.Models { public class Tournament { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ID { get; set; } public string Title { get; set; } public int Reward { get; set; } public int PlayerID { get; set; } public ICollection<Enrollment> Enrollments { get; set; } } }
27.9375
64
0.66443
[ "MIT" ]
BaseDorp/LeagueDatabaseRazorPages
LeagueDatabase/LeagueDatabase/Models/Tournament.cs
449
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace ResourceManagement.Data.Migrations { public partial class AddProperties : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Name", table: "ScheduleItem", nullable: true); migrationBuilder.AddColumn<TimeSpan>( name: "Duration", table: "RecurringSchedule", nullable: false, defaultValue: new TimeSpan(0, 0, 0, 0, 0)); migrationBuilder.AddColumn<string>( name: "Name", table: "RecurringSchedule", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Name", table: "ScheduleItem"); migrationBuilder.DropColumn( name: "Duration", table: "RecurringSchedule"); migrationBuilder.DropColumn( name: "Name", table: "RecurringSchedule"); } } }
28.744186
71
0.536408
[ "MIT" ]
stoyanov7/ResourceManagement
src/ResourceManagement.Data/Migrations/20190930074642_AddProperties.cs
1,238
C#
using System; using Andreys.Services; using Andreys.ViewModels.Products; using SUS.HTTP; using SUS.MvcFramework; namespace Andreys.Controllers { public class ProductsController : Controller { private readonly IProductsService productsService; public ProductsController(IProductsService productsService) { this.productsService = productsService; } public HttpResponse Add() { if (!this.IsUserSignedIn()) { return this.Redirect("/Home/Index"); } return this.View(); } [HttpPost] public HttpResponse Add(AddProductInputModel model) { if (!this.IsUserSignedIn()) { return this.Redirect("/"); } if (String.IsNullOrEmpty(model.Name) || model.Name.Length< 4 || model.Name.Length> 20) { return this.Redirect("/Products/Add"); //return this.Error("Name of the product should be between [4-20] characters."); } if (!String.IsNullOrEmpty(model.Description) && model.Description.Length>10) { return this.Redirect("/Products/Add"); //return this.Error("Description cannot exceed 10 characters."); } if (model.Price<=0M) { return this.Redirect("/Products/Add"); //return this.Error("Price cannot be zero or negative number."); } if (String.IsNullOrEmpty(model.Category)) { return this.Redirect("/Products/Add"); //return this.Error("Category cannot be empty."); } if (String.IsNullOrEmpty(model.Gender)) { return this.Redirect("/Products/Add"); //return this.Error("Gender cannot be empty."); } this.productsService.Create(model.Name, model.Description, model.ImageUrl,model.Category, model.Gender, model.Price); return this.Redirect("/"); } public HttpResponse Details(int id) { if (!this.IsUserSignedIn()) { return this.Redirect("/Home/Index"); } var viewModel = this.productsService.GetDetails(id); return this.View(viewModel); } public HttpResponse Delete(int id) { if (!this.IsUserSignedIn()) { return this.Redirect("/Home/Index"); } this.productsService.DeleteProduct(id); return this.Redirect("/"); } } }
28.505263
129
0.528065
[ "MIT" ]
tonchevaAleksandra/C-Sharp-Web-Development-SoftUni-Problems
C# Web Basic/SUS September 2020 Session/Andreys/Controllers/ProductsController.cs
2,710
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Maintenance.V20210501 { public static class GetMaintenanceConfiguration { /// <summary> /// Maintenance configuration record type /// </summary> public static Task<GetMaintenanceConfigurationResult> InvokeAsync(GetMaintenanceConfigurationArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetMaintenanceConfigurationResult>("azure-native:maintenance/v20210501:getMaintenanceConfiguration", args ?? new GetMaintenanceConfigurationArgs(), options.WithVersion()); } public sealed class GetMaintenanceConfigurationArgs : Pulumi.InvokeArgs { /// <summary> /// Resource Group Name /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// Maintenance Configuration Name /// </summary> [Input("resourceName", required: true)] public string ResourceName { get; set; } = null!; public GetMaintenanceConfigurationArgs() { } } [OutputType] public sealed class GetMaintenanceConfigurationResult { /// <summary> /// Duration of the maintenance window in HH:mm format. If not provided, default value will be used based on maintenance scope provided. Example: 05:00. /// </summary> public readonly string? Duration; /// <summary> /// Effective expiration date of the maintenance window in YYYY-MM-DD hh:mm format. The window will be created in the time zone provided and adjusted to daylight savings according to that time zone. Expiration date must be set to a future date. If not provided, it will be set to the maximum datetime 9999-12-31 23:59:59. /// </summary> public readonly string? ExpirationDateTime; /// <summary> /// Gets or sets extensionProperties of the maintenanceConfiguration /// </summary> public readonly ImmutableDictionary<string, string>? ExtensionProperties; /// <summary> /// Fully qualified identifier of the resource /// </summary> public readonly string Id; /// <summary> /// Gets or sets location of the resource /// </summary> public readonly string? Location; /// <summary> /// Gets or sets maintenanceScope of the configuration /// </summary> public readonly string? MaintenanceScope; /// <summary> /// Name of the resource /// </summary> public readonly string Name; /// <summary> /// Gets or sets namespace of the resource /// </summary> public readonly string? Namespace; /// <summary> /// Rate at which a Maintenance window is expected to recur. The rate can be expressed as daily, weekly, or monthly schedules. Daily schedule are formatted as recurEvery: [Frequency as integer]['Day(s)']. If no frequency is provided, the default frequency is 1. Daily schedule examples are recurEvery: Day, recurEvery: 3Days. Weekly schedule are formatted as recurEvery: [Frequency as integer]['Week(s)'] [Optional comma separated list of weekdays Monday-Sunday]. Weekly schedule examples are recurEvery: 3Weeks, recurEvery: Week Saturday,Sunday. Monthly schedules are formatted as [Frequency as integer]['Month(s)'] [Comma separated list of month days] or [Frequency as integer]['Month(s)'] [Week of Month (First, Second, Third, Fourth, Last)] [Weekday Monday-Sunday]. Monthly schedule examples are recurEvery: Month, recurEvery: 2Months, recurEvery: Month day23,day24, recurEvery: Month Last Sunday, recurEvery: Month Fourth Monday. /// </summary> public readonly string? RecurEvery; /// <summary> /// Effective start date of the maintenance window in YYYY-MM-DD hh:mm format. The start date can be set to either the current date or future date. The window will be created in the time zone provided and adjusted to daylight savings according to that time zone. /// </summary> public readonly string? StartDateTime; /// <summary> /// Azure Resource Manager metadata containing createdBy and modifiedBy information. /// </summary> public readonly Outputs.SystemDataResponse SystemData; /// <summary> /// Gets or sets tags of the resource /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Name of the timezone. List of timezones can be obtained by executing [System.TimeZoneInfo]::GetSystemTimeZones() in PowerShell. Example: Pacific Standard Time, UTC, W. Europe Standard Time, Korea Standard Time, Cen. Australia Standard Time. /// </summary> public readonly string? TimeZone; /// <summary> /// Type of the resource /// </summary> public readonly string Type; /// <summary> /// Gets or sets the visibility of the configuration. The default value is 'Custom' /// </summary> public readonly string? Visibility; [OutputConstructor] private GetMaintenanceConfigurationResult( string? duration, string? expirationDateTime, ImmutableDictionary<string, string>? extensionProperties, string id, string? location, string? maintenanceScope, string name, string? @namespace, string? recurEvery, string? startDateTime, Outputs.SystemDataResponse systemData, ImmutableDictionary<string, string>? tags, string? timeZone, string type, string? visibility) { Duration = duration; ExpirationDateTime = expirationDateTime; ExtensionProperties = extensionProperties; Id = id; Location = location; MaintenanceScope = maintenanceScope; Name = name; Namespace = @namespace; RecurEvery = recurEvery; StartDateTime = startDateTime; SystemData = systemData; Tags = tags; TimeZone = timeZone; Type = type; Visibility = visibility; } } }
42.801282
943
0.644601
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Maintenance/V20210501/GetMaintenanceConfiguration.cs
6,677
C#
using System; using System.Collections.Generic; using System.Linq; using CommandLine; using CommandLine.Text; namespace ChatopsBot.Commands { public class Command { public bool ParsingSuccess { get; set; } = true; public bool ExecutingSuccess { get; set; } = false; public IEnumerable<string> Args { get; set; } public string Input { get; set; } public List<string> Output { get; set; } = new List<string>(); public string Title { get; set; } public bool IsHelp { get; set; } = false; public virtual bool Validate() { return false; } } public class BotCommand : Command { } public class VstsCommand : Command { } [Verb("build", HelpText = "Start or Cancel a build. List all available builds. Type 'help build' for more info.")] public class BuildCommand : VstsCommand { [Option("id", Required = false, HelpText = "the build id or name")] public string BuildId { get; set; } [Option("config", Required = false, HelpText = "override the default build configuration")] public string Config { get; set; } [Value(0, HelpText = "pass the build id or name as the first parameter")] public string BuildIdPos { get; set; } [Option("start", Required = false, HelpText = "start a build (the default switch if none is specified)")] public bool Start { get; set; } [Option("list", Required = false, HelpText = "list all builds for a project")] public bool List { get; set; } [Option("cancel", Required = false, HelpText = "cancel all builds")] public bool Cancel { get; set; } [Option("queue", Required = false, HelpText = "show all builds in the queue (inprogress or notstarted)")] public bool Queue { get; set; } [Option("project", Required = false, HelpText = "the project id or name")] public string ProjectId { get; set; } [Usage] public static IEnumerable<Example> Examples { get { yield return new Example("Build project with id=42 with projectid", new BuildCommand {Start = true, BuildId = "42", ProjectId = Guid.NewGuid().ToString("N") }); yield return new Example("Build project with id=42 with projectid", new BuildCommand { Start = true, BuildIdPos = "42", ProjectId = Guid.NewGuid().ToString("N") }); yield return new Example("Build project with id=42 using projectid from state", new BuildCommand { Start = true, BuildIdPos = "42" }); yield return new Example("Build project with id=42 using projectid from state", new BuildCommand { BuildId = "42" }); yield return new Example("Build project with id=42 with BuildConfiguration=Debug", new BuildCommand { BuildId = "42", Config = "Debug"}); yield return new Example("List all knpwn builds using projectid from state", new BuildCommand {List = true, }); yield return new Example("Cancel all builds with id=42 using projectid from state", new BuildCommand { Cancel = true, BuildId = "42" }); yield return new Example("Cancel all builds with id=42 using projectid from state", new BuildCommand { Cancel = true, BuildIdPos = "42" }); yield return new Example("List all builds with projectid", new BuildCommand { List = true, ProjectId = Guid.NewGuid().ToString("N") }); yield return new Example("List all builds using projectid from state", new BuildCommand { List = true }); yield return new Example("Show all running and queued builds using projectid from state", new BuildCommand { Queue = true }); } } public override bool Validate() { var result = true; var all = new[] {Start, Cancel, List, Queue}; //start = default if (!all.Any(b => b)) Start = true; if (all.Count(b => b) > 1) { Output.Add($"you cannot choose more than one from [Start({Start}), Cancel({Cancel}), List({List})]"); result = false; } var buildIdString = BuildIdPos ?? BuildId; if (String.IsNullOrWhiteSpace(buildIdString) && (Start || Cancel)) { Output.Add("could not get build id or name"); result = false; } return result; } } [Verb("state", HelpText = "list all the state settings in the current conversation")] public class StateCommand : BotCommand { public StateCommand() { Title = "conversation state for {0}"; } [Option("clear", Required = false, HelpText = "clear state settings")] public bool Clear { get; set; } [Usage] public static IEnumerable<Example> Examples { get { yield return new Example("Show all your state settings", new StateCommand() { }); yield return new Example("Clear all your state settings", new StateCommand() {Clear = true }); } } public override bool Validate() { return true; } } [Verb("set", HelpText = "add state settings in the current conversation")] public class SetCommand : VstsCommand { [Option("tfsuser", Required = false, HelpText = "set your tfs username")] public string TfsUser { get; set; } [Option("project", Required = false, HelpText = "set your default tfs project")] public string Project { get; set; } [Usage] public static IEnumerable<Example> Examples { get { yield return new Example("Set your tfs user name", new SetCommand() { TfsUser = "me@my.com"}); yield return new Example("Set your default project", new SetCommand() { Project = Guid.NewGuid().ToString("N")}); } } public override bool Validate() { return true; } } [Verb("project", HelpText = "List all available projects. Type 'project help' for more info.")] public class ProjectCommand : VstsCommand { [Option("list", Required = false, HelpText = "list available projects (the default switch if none is specified)")] public bool List { get; set; } [Usage] public static IEnumerable<Example> Examples { get { yield return new Example("List available projects", new ProjectCommand() {List = true }); yield return new Example("List available projects (--list is default)", new ProjectCommand() { }); } } public override bool Validate() { var result = true; var all = new[] { List }; //list is default if (!all.Any(b => b)) List = true; if (all.Count(b => b) > 1) { Output.Add($"you cannot choose more than one from [List({List})]"); result = false; } return result; } } [Verb("alias", HelpText = "Create an alias for another command. Run an aliased command. List all known aliases. Type 'help alias' for more info.")] public class AliasCommand : Command { [Option("name", Required = false, HelpText = "the name of the alias")] public string Name { get; set; } [Option("command", Required = false, HelpText = "the aliased command")] public string Command { get; set; } [Value(0, HelpText = "the aliased command can also be passed without the --command switch")] public IEnumerable<string> CommandSeq { get; set; } [Option("create", Required = false, HelpText = "create a new alias or update an existing one (this is the default switch if none is specified). Requires you to also specify a name and command")] public bool Create { get; set; } [Option("run", Required = false, HelpText = "run an aliased command. You can also run the alias by just passing the alias without 'alias --run'. The command 'alias --run <aliasName>' is equivalent with the command '<aliasName>'")] public bool Run { get; set; } [Option("list", Required = false, HelpText = "list all known aliases")] public bool List { get; set; } [Option("clear", Required = false, HelpText = "clear all known aliases")] public bool Clear { get; set; } [Usage] public static IEnumerable<Example> Examples { get { yield return new Example("Create or update an alias with the --command switch", new AliasCommand() { Name = "lp", Command = "project --list" }); yield return new Example("Create or update an alias. Everything after the name of the alias is the command", new AliasCommand() { Name = "qb2", CommandSeq = new[] { "build --start 42" } }); yield return new Example("Create or update an alias", new AliasCommand() { Name = "qb2", CommandSeq = new [] { "build 42"} }); yield return new Example("Run an alias. This is equivalent to simply typing 'my-alias'", new AliasCommand() { Run = true, Name = "my-alias" }); yield return new Example("List all known aliases", new AliasCommand() { List = true }); } } public override bool Validate() { var result = true; var all = new[] {Create, Run, List, Clear}; //create is default if (!all.Any(b => b)) Create = true; if (all.Count(b => b) > 1) { Output.Add($"you cannot choose more than one from [Create({Create}), Run({Run}), List({List}), Clear({Clear})]"); result = false; } //if create and no name or no command if (Create && (String.IsNullOrWhiteSpace(Name) || (String.IsNullOrWhiteSpace(Command) && (CommandSeq == null || !CommandSeq.Any())))) { Output.Add("--create was specified but either a name or a command was not given"); result = false; } //if run and no name if (Run && String.IsNullOrWhiteSpace(Name)) { Output.Add("--run was specified but a name was not given"); result = false; } return result; } } }
40.576208
239
0.55749
[ "MIT" ]
stombeur/chatopsbot
src/ChatopsBot.Commands/Commands.cs
10,917
C#
namespace OurUmbraco.Community.Nuget { using System; using Newtonsoft.Json; public class NugetRegistrationCatalogEntry { [JsonProperty("published")] public DateTime PublishedDate { get; set; } } }
18.153846
51
0.665254
[ "MIT" ]
AaronSadlerUK/OurUmbraco
OurUmbraco/Community/Nuget/NugetRegistrationCatalogEntry.cs
238
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// KoubeiAdvertCommissionCascademissionCreateResponse. /// </summary> public class KoubeiAdvertCommissionCascademissionCreateResponse : AopResponse { } }
20.692308
81
0.732342
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Response/KoubeiAdvertCommissionCascademissionCreateResponse.cs
269
C#
using System; using Windows.UI.Xaml.Controls; using Uno.UI.Samples.Controls; using Windows.Storage.Pickers; using Uno.UI.Samples.UITests.Helpers; using Windows.UI.Core; using Windows.Storage; using System.Linq; using System.Collections.ObjectModel; using Uno.Extensions; namespace UITests.Shared.Windows_Storage.Pickers { [Sample("Windows.Storage", ViewModelType = typeof(FileOpenPickerTestsViewModel))] public sealed partial class FileOpenPickerTests : Page { public FileOpenPickerTests() { this.InitializeComponent(); this.DataContextChanged += FolderPickerTests_DataContextChanged; } private void FolderPickerTests_DataContextChanged(Windows.UI.Xaml.DependencyObject sender, Windows.UI.Xaml.DataContextChangedEventArgs args) { ViewModel = args.NewValue as FileOpenPickerTestsViewModel; } public FileOpenPickerTestsViewModel ViewModel { get; private set; } } public class FileOpenPickerTestsViewModel : ViewModelBase { private string _fileType = string.Empty; private string _errorMessage = string.Empty; private string _statusMessage = string.Empty; private StorageFile[] _pickedFiles = null; public FileOpenPickerTestsViewModel(CoreDispatcher dispatcher) : base(dispatcher) { } public PickerLocationId[] SuggestedStartLocations { get; } = Enum.GetValues(typeof(PickerLocationId)).OfType<PickerLocationId>().ToArray(); public PickerLocationId SuggestedStartLocation { get; set; } = PickerLocationId.ComputerFolder; public string SettingsIdentifier { get; set; } = string.Empty; public string CommitButtonText { get; set; } = string.Empty; public PickerViewMode[] ViewModes { get; } = Enum.GetValues(typeof(PickerViewMode)).OfType<PickerViewMode>().ToArray(); public PickerViewMode ViewMode { get; set; } = PickerViewMode.List; public string FileType { get => _fileType; set { _fileType = value; RaisePropertyChanged(); } } public ObservableCollection<string> FileTypeFilter { get; } = new ObservableCollection<string>(); public string ErrorMessage { get => _errorMessage; set { _errorMessage = value; RaisePropertyChanged(); } } public string StatusMessage { get => _statusMessage; set { _statusMessage = value; RaisePropertyChanged(); } } public void AddFileType() { if (!string.IsNullOrEmpty(FileType)) { FileTypeFilter.Add(FileType); FileType = string.Empty; } } public void ClearFileTypes() => FileTypeFilter.Clear(); public StorageFile[] PickedFiles { get => _pickedFiles; set { _pickedFiles = value; RaisePropertyChanged(); } } public async void PickSingleFile() { ErrorMessage = string.Empty; StatusMessage = string.Empty; try { var filePicker = new FileOpenPicker { SuggestedStartLocation = SuggestedStartLocation, ViewMode = ViewMode, }; if (!string.IsNullOrEmpty(SettingsIdentifier)) { filePicker.SettingsIdentifier = SettingsIdentifier; } if (!string.IsNullOrEmpty(CommitButtonText)) { filePicker.CommitButtonText = CommitButtonText; } filePicker.FileTypeFilter.AddRange(FileTypeFilter); var pickedFile = await filePicker.PickSingleFileAsync(); if (pickedFile != null) { StatusMessage = "File picked successfully."; PickedFiles = new[] { pickedFile }; } else { StatusMessage = "No file picked"; PickedFiles = Array.Empty<StorageFile>(); } } catch (Exception ex) { ErrorMessage = $"Exception occurred: {ex}."; } } public async void PickMultipleFiles() { ErrorMessage = string.Empty; StatusMessage = string.Empty; try { var filePicker = new FileOpenPicker { SuggestedStartLocation = SuggestedStartLocation, ViewMode = ViewMode, }; if (!string.IsNullOrEmpty(SettingsIdentifier)) { filePicker.SettingsIdentifier = SettingsIdentifier; } if (!string.IsNullOrEmpty(CommitButtonText)) { filePicker.CommitButtonText = CommitButtonText; } filePicker.FileTypeFilter.AddRange(FileTypeFilter); var pickedFiles = await filePicker.PickMultipleFilesAsync(); if (pickedFiles.Any()) { StatusMessage = $"{pickedFiles.Count} files picked successfully."; PickedFiles = pickedFiles.ToArray(); } else { StatusMessage = "No files picked."; PickedFiles = Array.Empty<StorageFile>(); } } catch (Exception ex) { ErrorMessage = $"Exception occurred: {ex}."; } } } }
24.578378
142
0.702221
[ "Apache-2.0" ]
NateTheGreat714/uno
src/SamplesApp/UITests.Shared/Windows_Storage/Pickers/FileOpenPickerTests.xaml.cs
4,549
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using com.rfilkov.components; public class MocapDistributor : MonoBehaviour { public MocapPlayer leftPlayer; public MocapPlayer rightPlayer; bool isLeft; public void SetPlayerAnimation(AnimationClip animClip) { animClip.wrapMode = WrapMode.Loop; if(isLeft) { leftPlayer.PlayAnimationClip(animClip); } else { rightPlayer.PlayAnimationClip(animClip); } isLeft = !isLeft; } }
20.428571
58
0.645105
[ "Unlicense" ]
albertobonanni/unity-installation
Assets/MocapDistributor.cs
574
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Chalmers.ILL.Models.PartialPage { public class ChalmersILLActionProviderReturnDateModel : OrderItemPageModelBase { public ChalmersILLActionProviderReturnDateModel(OrderItemModel orderItemModel) : base(orderItemModel) { } } }
28.416667
113
0.794721
[ "MIT" ]
ChalmersLibrary/Chillin
Chalmers.ILL/Models/PartialPage/ChalmersILLActionProviderReturnDateModel.cs
343
C#
using System; #if SUPPORTS_SERIALIZATION using System.Runtime.Serialization; #endif namespace Here { /// <summary> /// Exception thrown when getting a null result where it's not authorized. /// </summary> #if SUPPORTS_SERIALIZATION [Serializable] #endif public sealed class NullResultException : Exception { /// <summary> /// Constructor. /// </summary> public NullResultException() : base("Result is null where it is forbidden.") { } #if SUPPORTS_SERIALIZATION /// <summary> /// Serialization constructor. /// </summary> private NullResultException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }
23.117647
85
0.608142
[ "MIT" ]
KeRNeLith/Here
src/Here/Exceptions/NullResultException.cs
786
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Motor : MonoBehaviour { public float moveSpeed = 10f; public Vector2 Input { get; set; } private void Update() { Move(Input); } private void Move(Vector2 input) { var move = transform.TransformDirection(input.x, 0, input.y); transform.localPosition += move * moveSpeed * Time.deltaTime; } }
20.772727
69
0.660832
[ "Apache-2.0" ]
YunShangAR/AR-Housing
Assets/_App/Scripts/Movement/Motor.cs
459
C#
/// <summary> /// /// </summary> /// <remarks> /// Price Elasticity must be negative /// </remarks> public class Iron : Resources { public override Curve demand { get; protected set; } public Iron(float initialAmount, float equilibrium_price, float equilibrium_qty, float price_elasticity, float demand_shift, float price_shift) : base(initialAmount, equilibrium_price, equilibrium_qty, price_elasticity, demand_shift, price_shift) { float x_displacement = 0; demand = Curve.createCurveByName("XSquareCurve", price_elasticity, x_displacement, equilibrium_price, equilibrium_qty); } public Iron(params float[] initialValues) : this(initialValues[0], initialValues[1], initialValues[2], initialValues[3], initialValues[4], initialValues[5]) { } public override float calculatePrice() { float price = demand.calculateY(getState()); return (price > 0) ? price : 1; } public override float calculateTotalPrice(int quantity) { int quantityLeftAfterPurchase = state - quantity; return demand.calculateAreaUnderCurve(state, quantityLeftAfterPurchase); } }
34.382353
250
0.698888
[ "MIT" ]
simplygamedev/trading_game
Trading Game/Assets/Scripts/Resources/Iron.cs
1,171
C#
using Microsoft.AspNetCore.Blazor.Hosting; namespace WordDaze.Client { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IWebAssemblyHostBuilder CreateHostBuilder(string[] args) => BlazorWebAssemblyHost.CreateDefaultBuilder() .UseBlazorStartup<Startup>(); } }
25.411765
82
0.608796
[ "MIT" ]
chrissainty/worddaze
src/WordDaze.Client/Program.cs
434
C#
using System; using System.Collections.Generic; namespace SRF { public static class SRFIListExtensions { public static T Random<T>(this IList<T> list) { if(list.Count == 0) throw new IndexOutOfRangeException("List needs at least one entry to call Random()"); if (list.Count == 1) return list[0]; return list[UnityEngine.Random.Range(0, list.Count)]; } public static T RandomOrDefault<T>(this IList<T> list) { if (list.Count == 0) return default(T); return list.Random(); } public static T PopLast<T>(this IList<T> list) { if (list.Count == 0) throw new InvalidOperationException(); var t = list[list.Count - 1]; list.RemoveAt(list.Count-1); return t; } } }
14.88
89
0.642473
[ "MIT" ]
StompyRobot/SRF
Scripts/Extensions/IListExtensions.cs
746
C#
// Copyright 2018 (c) Nutanix. All rights reserved. // Licensed under the MIT License. See LICENSE file in the repository root for full license information. // Purpose: Subnets (virtual networks / vlans) source for 'Nutanix.PowerShell.SDK' // Author: Nutanix // Copyright: Nutanix, 2018 // Owner: PowerShell@nutanix.com // Maintainer(s): // Jon Kohler (Nutanix, JonKohler) // Alex Guo (Nutanix, mallochine) using System; using System.Management.Automation; using Newtonsoft.Json; namespace Nutanix.PowerShell.SDK { public class Subnet { public string Name { get; set; } public string Id { get; set; } // 'Uid' is VMware's equivalent field for Nutanix's Uuid. public string Uid { get; set; } public string Uuid { get; set; } public dynamic Json { get; set; } // TODO Mtu, NumPorts, ExtensionData, NumPortsAvailable, Key, Nic, VMHostId, // VMHost, VMHostUid, Nic public Subnet(dynamic json) { // Special property 'json' stores the original json. this.Json = json; this.Json.Property("status").Remove(); this.Json.api_version = "3.1"; Name = json.spec.name; Id = json.spec.resources.vlan_id; Uuid = json.metadata.uuid; Uid = Uuid; } } [CmdletAttribute(VerbsCommon.New, "VirtualSwitch")] public class NewSubnetCmdlet : Cmdlet { [Parameter] public string Name { get; set; } [Parameter] public string VlanId { get; set; } [Parameter] public string Description { get; set; } [Parameter] public Cluster Cluster { get; set; } protected override void ProcessRecord() { var url = "subnets"; var method = "POST"; var str = @"{ ""api_version"": ""3.1"", ""metadata"": { ""kind"": ""subnet"", ""name"": """ + Name + @""" }, ""spec"": { ""description"": """ + Description + @""", ""name"": """ + Name + @""", ""resources"": { ""subnet_type"": ""VLAN"", ""vlan_id"": " + VlanId + @", } } }"; dynamic json = JsonConvert.DeserializeObject(str); if (Cluster != null) { json.spec.cluster_reference = new Newtonsoft.Json.Linq.JObject(); json.spec.cluster_reference.kind = "cluster"; json.spec.cluster_reference.uuid = Cluster.Uuid; json.spec.cluster_reference.name = Cluster.Name; } // TODO: should use Task. WriteObject( Task.FromUuidInJson(NtnxUtil.RestCall(url, method, json.ToString()))); } } [CmdletAttribute(VerbsCommon.Get, "VirtualSwitch")] public class GetSubnetCmdlet : Cmdlet { // TODO: Name parameter to specify the names of subnets to retrieve. [Parameter] public string Uuid { get; set; } [Parameter] public string Name { get; set; } [Parameter] public int? Max { get; set; } protected override void ProcessRecord() { if (NtnxUtil.PassThroughNonNull(Uuid)) { WriteObject(GetSubnetByUuid(Uuid)); return; } var subnets = GetAllSubnets(BuildRequestBody()); WriteObject(subnets); } // Given the parameters, build request body for '/subnets/list'. public dynamic BuildRequestBody() { dynamic json = JsonConvert.DeserializeObject("{}"); if (Max != null) { json.length = Max; } if (NtnxUtil.PassThroughNonNull(Name)) { json.filter = "name==" + Name; } return json; } public static Subnet GetSubnetByUuid(string uuid) { // TODO: validate using UUID regexes that 'uuid' is in correct format. var json = NtnxUtil.RestCall("subnets/" + uuid, "GET", string.Empty /* requestBody */); return new Subnet(json); } public static Subnet[] GetSubnetsByName(string name) { return GetAllSubnets("{\"filter\": \"name==" + name + "\"}"); } public static Subnet[] GetAllSubnets(dynamic jsonReqBody) { return GetAllSubnets(jsonReqBody.ToString()); } public static Subnet[] GetAllSubnets(string reqBody) { return NtnxUtil.FromJson<Subnet>( NtnxUtil.RestCall("subnets/list", "POST", reqBody), (Func<dynamic, Subnet>)(j => new Subnet(j))); } } [CmdletAttribute(VerbsCommon.Remove, "VirtualSwitch")] public class DeleteSubnetCmdlet : Cmdlet { [Parameter] public string Uuid { get; set; } // TODO: Confirm, WhatIf params. // https://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Remove-VirtualSwitch.html protected override void ProcessRecord() { if (NtnxUtil.PassThroughNonNull(Uuid)) { // TODO: WriteObject Task DeleteSubnetByUuid(Uuid); } } public static void DeleteSubnetByUuid(string uuid) { // TODO: validate using UUID regexes that 'uuid' is in correct format. NtnxUtil.RestCall("subnets/" + uuid, "DELETE", string.Empty /* requestBody */); } } [CmdletAttribute(VerbsCommon.Set, "VirtualSwitch")] public class SetSubnetCmdlet : Cmdlet { [Parameter(Mandatory = true)] public Subnet Subnet { get; set; } [Parameter] public string Name { get; set; } [Parameter] public string VlanId { get; set; } protected override void ProcessRecord() { if (Name != null) { Subnet.Json.spec.name = Name; } if (VlanId != null) { Subnet.Json.spec.resources.vlan_id = VlanId; } Subnet.Json.api_version = "3.1"; NtnxUtil.RestCall("subnets/" + Subnet.Uuid, "PUT", Subnet.Json.ToString()); } } }
26.027778
104
0.608502
[ "MIT" ]
coderGo93/PowerShell
src/Nutanix.PowerShell.SDK/Subnet.cs
5,622
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 Gamma.Entities { using System; using System.Collections.Generic; public partial class DocRepack { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public DocRepack() { this.DocRepackProducts = new HashSet<DocRepackProducts>(); } public System.Guid DocID { get; set; } public Nullable<System.Guid> ProductionTaskID { get; set; } public virtual Docs Docs { get; set; } public virtual ProductionTasks ProductionTasks { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<DocRepackProducts> DocRepackProducts { get; set; } } }
39.34375
128
0.601271
[ "Unlicense" ]
Polimat/Gamma
Entities/DocRepack.cs
1,259
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Elasticsearch.Net; using FluentAssertions; using Tests.Framework.MockResponses; using System.Net; namespace Tests.Framework { public class VirtualClusterConnection : InMemoryConnection { private static readonly object _lock = new object(); private class State { public int Pinged = 0; public int Sniffed = 0; public int Called = 0; public int Successes = 0; public int Failures = 0; } private IDictionary<int, State> Calls = new Dictionary<int, State> { }; private VirtualCluster _cluster; private TestableDateTimeProvider _dateTimeProvider; public VirtualClusterConnection(VirtualCluster cluster, TestableDateTimeProvider dateTimeProvider) { this.UpdateCluster(cluster); this._dateTimeProvider = dateTimeProvider; } public void UpdateCluster(VirtualCluster cluster) { if (cluster == null) return; lock (_lock) { this._cluster = cluster; this.Calls = cluster.Nodes.ToDictionary(n => n.Uri.Port, v => new State()); } } public bool IsSniffRequest(RequestData requestData) => requestData.Path.StartsWith("_nodes/_all/settings", StringComparison.Ordinal); public bool IsPingRequest(RequestData requestData) => requestData.Path == "/" && requestData.Method == HttpMethod.HEAD; public override ElasticsearchResponse<TReturn> Request<TReturn>(RequestData requestData) { this.Calls.Should().ContainKey(requestData.Uri.Port); try { var state = this.Calls[requestData.Uri.Port]; if (IsSniffRequest(requestData)) { var sniffed = Interlocked.Increment(ref state.Sniffed); return HandleRules<TReturn, ISniffRule>( requestData, this._cluster.SniffingRules, requestData.RequestTimeout, (r) => this.UpdateCluster(r.NewClusterState), (r) => SniffResponse.Create(this._cluster.Nodes, this._cluster.SniffShouldReturnFqnd) ); } if (IsPingRequest(requestData)) { var pinged = Interlocked.Increment(ref state.Pinged); return HandleRules<TReturn, IRule>( requestData, this._cluster.PingingRules, requestData.PingTimeout, (r) => { }, (r) => null //HEAD request ); } var called = Interlocked.Increment(ref state.Called); return HandleRules<TReturn, IClientCallRule>( requestData, this._cluster.ClientCallRules, requestData.RequestTimeout, (r) => { }, CallResponse ); } #if DOTNETCORE catch (System.Net.Http.HttpRequestException e) #else catch (WebException e) #endif { var builder = new ResponseBuilder<TReturn>(requestData); builder.Exception = e; return builder.ToResponse(); } } private ElasticsearchResponse<TReturn> HandleRules<TReturn, TRule>( RequestData requestData, IEnumerable<TRule> rules, TimeSpan timeout, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse ) where TReturn : class where TRule : IRule { var state = this.Calls[requestData.Uri.Port]; foreach (var rule in rules.Where(s => s.OnPort.HasValue)) { var always = rule.Times.Match(t => true, t => false); var times = rule.Times.Match(t => -1, t => t); if (rule.OnPort.Value == requestData.Uri.Port) { if (always) return Always<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, rule); return Sometimes<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, state, rule, times); } } foreach (var rule in rules.Where(s => !s.OnPort.HasValue)) { var always = rule.Times.Match(t => true, t => false); var times = rule.Times.Match(t => -1, t => t); if (always) return Always<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, rule); return Sometimes<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, state, rule, times); } return this.ReturnConnectionStatus<TReturn>(requestData, successResponse(default(TRule))); } private ElasticsearchResponse<TReturn> Always<TReturn, TRule>(RequestData requestData, TimeSpan timeout, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse, TRule rule) where TReturn : class where TRule : IRule { if (rule.Takes.HasValue) { var time = timeout < rule.Takes.Value ? timeout: rule.Takes.Value; this._dateTimeProvider.ChangeTime(d=> d.Add(time)); if (rule.Takes.Value > requestData.RequestTimeout) #if DOTNETCORE throw new System.Net.Http.HttpRequestException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #else throw new WebException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #endif } return rule.Succeeds ? Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule) : Fail<TReturn, TRule>(requestData, rule); } private ElasticsearchResponse<TReturn> Sometimes<TReturn, TRule>(RequestData requestData, TimeSpan timeout, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse, State state, TRule rule, int times) where TReturn : class where TRule : IRule { if (rule.Takes.HasValue) { var time = timeout < rule.Takes.Value ? timeout : rule.Takes.Value; this._dateTimeProvider.ChangeTime(d=> d.Add(time)); if (rule.Takes.Value > requestData.RequestTimeout) #if DOTNETCORE throw new System.Net.Http.HttpRequestException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #else throw new WebException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #endif } if (rule.Succeeds && times >= state.Successes) return Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule); else if (rule.Succeeds) return Fail<TReturn, TRule>(requestData, rule); if (!rule.Succeeds && times >= state.Failures) return Fail<TReturn, TRule>(requestData, rule); return Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule); } private ElasticsearchResponse<TReturn> Fail<TReturn, TRule>(RequestData requestData, TRule rule) where TReturn : class where TRule : IRule { var state = this.Calls[requestData.Uri.Port]; var failed = Interlocked.Increment(ref state.Failures); if (rule.Return == null) #if DOTNETCORE throw new System.Net.Http.HttpRequestException(); #else throw new WebException(); #endif return rule.Return.Match( (e) => { throw e; }, (statusCode) => this.ReturnConnectionStatus<TReturn>(requestData, CallResponse(rule), statusCode) ); } private ElasticsearchResponse<TReturn> Success<TReturn, TRule>(RequestData requestData, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse, TRule rule) where TReturn : class where TRule : IRule { var state = this.Calls[requestData.Uri.Port]; var succeeded = Interlocked.Increment(ref state.Successes); beforeReturn?.Invoke(rule); return this.ReturnConnectionStatus<TReturn>(requestData, successResponse(rule)); } private byte[] CallResponse<TRule>(TRule rule) where TRule : IRule { if (rule?.ReturnResponse != null) return rule.ReturnResponse; var response = DefaultResponse; using (var ms = new MemoryStream()) { new ElasticsearchDefaultSerializer().Serialize(response, ms); return ms.ToArray(); } } private static object DefaultResponse { get { var response = new { name = "Razor Fist", cluster_name = "elasticsearch-test-cluster", version = new { number = "2.0.0", build_hash = "af1dc6d8099487755c3143c931665b709de3c764", build_timestamp = "2015-07-07T11:28:47Z", build_snapshot = true, lucene_version = "5.2.1" }, tagline = "You Know, for Search" }; return response; } } public override Task<ElasticsearchResponse<TReturn>> RequestAsync<TReturn>(RequestData requestData) { return Task.FromResult(this.Request<TReturn>(requestData)); } } }
34.288066
210
0.698512
[ "Apache-2.0" ]
RossLieberman/NEST
src/Tests/Framework/VirtualClustering/VirtualClusterConnection.cs
8,332
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 Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test.Reaqtive.Operators { [TestClass] public partial class DistinctUntilChanged : OperatorTestBase { } }
27.785714
71
0.758355
[ "MIT" ]
Botcoin-com/reaqtor
Reaqtor/Samples/Remoting/Tests.Reaqtor.Remoting.Glitching/Operators/DistinctUntilChanged.cs
391
C#
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public static double[,] Values(dmat2 m) => m.Values; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public static double[] Values1D(dmat2 m) => m.Values1D; /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public static IEnumerator<double> GetEnumerator(dmat2 m) => m.GetEnumerator(); } }
27.333333
86
0.626016
[ "MIT" ]
BitquakeProgramming/GlmSharp
GlmSharp/GlmSharpCompat/Mat2x2/dmat2.glm.cs
984
C#
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Lob.Net { public interface ILobCommunicator { Task<T> GetAsync<T>(string url, CancellationToken cancellationToken = default); Task<T> DeleteAsync<T>(string url, CancellationToken cancellationToken = default); Task<T> PostAsync<T>(string url, object body, CancellationToken cancellationToken = default); Task<T> PostAsync<T>(string url, object body, string idempotencyKey = default, CancellationToken cancellationToken = default); Task<T> PostAsync<T>(string url, object body, IDictionary<string, string> extraHeaders = null, CancellationToken cancellationToken = default); } }
45.5625
150
0.743484
[ "MIT" ]
adamreed90/lob.net
src/Lob.Net/Interfaces/ILobCommunicator.cs
731
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json; using NodaTime; using NUnit.Framework; using QuantConnect.Securities; using QuantConnect.Util; namespace QuantConnect.Tests.Common.Util { [TestFixture] public class MarketHoursDatabaseJsonConverterTests { [Test] public void HandlesRoundTrip() { var database = MarketHoursDatabase.FromDataFolder(); var result = JsonConvert.SerializeObject(database, Formatting.Indented); var deserializedDatabase = JsonConvert.DeserializeObject<MarketHoursDatabase>(result); var originalListing = database.ExchangeHoursListing.ToDictionary(); foreach (var kvp in deserializedDatabase.ExchangeHoursListing) { var original = originalListing[kvp.Key]; Assert.AreEqual(original.DataTimeZone, kvp.Value.DataTimeZone); CollectionAssert.AreEqual(original.ExchangeHours.Holidays, kvp.Value.ExchangeHours.Holidays); foreach (var value in Enum.GetValues(typeof(DayOfWeek))) { var day = (DayOfWeek) value; var o = original.ExchangeHours.MarketHours[day]; var d = kvp.Value.ExchangeHours.MarketHours[day]; foreach (var pair in o.Segments.Zip(d.Segments, Tuple.Create)) { Assert.AreEqual(pair.Item1.State, pair.Item2.State); Assert.AreEqual(pair.Item1.Start, pair.Item2.Start); Assert.AreEqual(pair.Item1.End, pair.Item2.End); } } } } [Test, Ignore("This is provided to make it easier to convert your own market-hours-database.csv to the new format")] public void ConvertMarketHoursDatabaseCsvToJson() { var directory = Path.Combine(Globals.DataFolder, "market-hours"); var input = Path.Combine(directory, "market-hours-database.csv"); var output = Path.Combine(directory, Path.GetFileNameWithoutExtension(input) + ".json"); var allHolidays = Directory.EnumerateFiles(Path.Combine(Globals.DataFolder, "market-hours"), "holidays-*.csv").Select(x => { var dates = new HashSet<DateTime>(); var market = Path.GetFileNameWithoutExtension(x).Replace("holidays-", string.Empty); foreach (var line in File.ReadAllLines(x).Skip(1).Where(l => !l.StartsWith("#"))) { var csv = line.ToCsv(); dates.Add(new DateTime( Parse.Int(csv[0]), Parse.Int(csv[1]), Parse.Int(csv[2]) )); } return new KeyValuePair<string, IEnumerable<DateTime>>(market, dates); }).ToDictionary(); var database = FromCsvFile(input, allHolidays); File.WriteAllText(output, JsonConvert.SerializeObject(database, Formatting.Indented)); } #region These methods represent the old way of reading MarketHoursDatabase from csv and are left here to allow users to convert /// <summary> /// Creates a new instance of the <see cref="MarketHoursDatabase"/> class by reading the specified csv file /// </summary> /// <param name="file">The csv file to be read</param> /// <param name="holidaysByMarket">The holidays for each market in the file, if no holiday is present then none is used</param> /// <returns>A new instance of the <see cref="MarketHoursDatabase"/> class representing the data in the specified file</returns> public static MarketHoursDatabase FromCsvFile(string file, IReadOnlyDictionary<string, IEnumerable<DateTime>> holidaysByMarket) { var exchangeHours = new Dictionary<SecurityDatabaseKey, MarketHoursDatabase.Entry>(); if (!File.Exists(file)) { throw new FileNotFoundException("Unable to locate market hours file: " + file); } // skip the first header line, also skip #'s as these are comment lines foreach (var line in File.ReadLines(file).Where(x => !x.StartsWith("#")).Skip(1)) { SecurityDatabaseKey key; var hours = FromCsvLine(line, holidaysByMarket, out key); if (exchangeHours.ContainsKey(key)) { throw new Exception($"Encountered duplicate key while processing file: {file}. Key: {key}"); } exchangeHours[key] = hours; } return new MarketHoursDatabase(exchangeHours); } /// <summary> /// Creates a new instance of <see cref="SecurityExchangeHours"/> from the specified csv line and holiday set /// </summary> /// <param name="line">The csv line to be parsed</param> /// <param name="holidaysByMarket">The holidays this exchange isn't open for trading by market</param> /// <param name="key">The key used to uniquely identify these market hours</param> /// <returns>A new <see cref="SecurityExchangeHours"/> for the specified csv line and holidays</returns> private static MarketHoursDatabase.Entry FromCsvLine(string line, IReadOnlyDictionary<string, IEnumerable<DateTime>> holidaysByMarket, out SecurityDatabaseKey key) { var csv = line.Split(','); var marketHours = new List<LocalMarketHours>(7); // timezones can be specified using Tzdb names (America/New_York) or they can // be specified using offsets, UTC-5 var dataTimeZone = ParseTimeZone(csv[0]); var exchangeTimeZone = ParseTimeZone(csv[1]); //var market = csv[2]; //var symbol = csv[3]; //var type = csv[4]; var symbol = string.IsNullOrEmpty(csv[3]) ? null : csv[3]; key = new SecurityDatabaseKey(csv[2], symbol, (SecurityType)Enum.Parse(typeof(SecurityType), csv[4], true)); int csvLength = csv.Length; for (int i = 1; i < 8; i++) // 7 days, so < 8 { // the 4 here is because 4 times per day, ex_open,open,close,ex_close if (4*i + 4 > csvLength - 1) { break; } var hours = ReadCsvHours(csv, 4*i + 1, (DayOfWeek) (i - 1)); marketHours.Add(hours); } IEnumerable<DateTime> holidays; if (!holidaysByMarket.TryGetValue(key.Market, out holidays)) { holidays = Enumerable.Empty<DateTime>(); } var earlyCloses = new Dictionary<DateTime, TimeSpan>(); var lateOpens = new Dictionary<DateTime, TimeSpan>(); var exchangeHours = new SecurityExchangeHours(exchangeTimeZone, holidays, marketHours.ToDictionary(x => x.DayOfWeek), earlyCloses, lateOpens); return new MarketHoursDatabase.Entry(dataTimeZone, exchangeHours); } private static DateTimeZone ParseTimeZone(string tz) { // handle UTC directly if (tz == "UTC") return TimeZones.Utc; // if it doesn't start with UTC then it's a name, like America/New_York if (!tz.StartsWith("UTC")) return DateTimeZoneProviders.Tzdb[tz]; // it must be a UTC offset, parse the offset as hours // define the time zone as a constant offset time zone in the form: 'UTC-3.5' or 'UTC+10' var millisecondsOffset = (int) TimeSpan.FromHours( Parse.Double(tz.Replace("UTC", string.Empty)) ).TotalMilliseconds; return DateTimeZone.ForOffset(Offset.FromMilliseconds(millisecondsOffset)); } private static LocalMarketHours ReadCsvHours(string[] csv, int startIndex, DayOfWeek dayOfWeek) { var ex_open = csv[startIndex]; if (ex_open == "-") { return LocalMarketHours.ClosedAllDay(dayOfWeek); } if (ex_open == "+") { return LocalMarketHours.OpenAllDay(dayOfWeek); } var open = csv[startIndex + 1]; var close = csv[startIndex + 2]; var ex_close = csv[startIndex + 3]; var ex_open_time = ParseHoursToTimeSpan(ex_open); var open_time = ParseHoursToTimeSpan(open); var close_time = ParseHoursToTimeSpan(close); var ex_close_time = ParseHoursToTimeSpan(ex_close); if (ex_open_time == TimeSpan.Zero && open_time == TimeSpan.Zero && close_time == TimeSpan.Zero && ex_close_time == TimeSpan.Zero) { return LocalMarketHours.ClosedAllDay(dayOfWeek); } return new LocalMarketHours(dayOfWeek, ex_open_time, open_time, close_time, ex_close_time); } private static TimeSpan ParseHoursToTimeSpan(string ex_open) { return TimeSpan.FromHours(Parse.Double(ex_open)); } #endregion } }
44.90625
154
0.600855
[ "Apache-2.0" ]
AENotFound/Lean
Tests/Common/Util/MarketHoursDatabaseJsonConverterTests.cs
10,059
C#
//Apache2, 2017, WinterDev //Apache2, 2009, griffm, FO.NET namespace Fonet.Fo.Properties { enum BaselineShift : byte { BASELINE = Constants.BASELINE, SUB = Constants.SUB, SUPER = Constants.SUPER } }
21.363636
38
0.629787
[ "Apache-2.0" ]
PaintLab/SaveAsPdf
src/FoDom/Fo/Properties/BaselineShift.cs
237
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SpeedrunComApi.Interfaces { public interface IRateLimitedRequester { /// <summary> /// Create a get request and send it asynchronously to the server. /// </summary> /// <param name="relativeUrl"></param> /// <param name="queryParameters"></param> /// <returns>The content of the response.</returns> /// <exception cref="SpeedrunComApiException"> /// Thrown if an Http error occurs. /// Contains the Http error code and error message. /// </exception> Task<string> CreateGetRequestAsync(string relativeUrl, List<string> queryParameters = null); /// <summary> /// Create a post request and send it asynchronously to the server. /// </summary> /// <param name="relativeUrl"></param> /// <param name="body"></param> /// <param name="queryParameters"></param> /// <returns>The content of the response.</returns> /// <exception cref="SpeedrunComApiException"> /// Thrown if an Http error occurs. /// Contains the Http error code and error message. /// </exception> Task<string> CreatePostRequestAsync(string relativeUrl, string body, List<string> queryParameters = null); /// <summary> /// Create a post request and send it asynchronously to the server. /// </summary> /// <param name="relativeUrl"></param> /// <param name="body"></param> /// <param name="queryParameters"></param> /// <returns>The content of the response.</returns> /// <exception cref="SpeedrunComApiException"> /// Thrown if an Http error occurs. /// Contains the Http error code and error message. /// </exception> Task<bool> CreatePutRequestAsync(string relativeUrl, string body, List<string> queryParameters = null); } }
39.529412
114
0.618552
[ "MIT" ]
Failcookie/SpeedrunComApi
SpeedrunComApi/Interfaces/IRateLimitedRequester.cs
2,018
C#
using System.Threading; using Cysharp.Threading.Tasks; using MessagePipe; namespace TebakAngka.Gameplay { public class UserInputState : IGameState { private readonly GameModel _gameModel; private readonly IAsyncRequestHandler<GameStateEnum, int> _answerRequestHandler; public UserInputState( GameModel gameModel, IAsyncRequestHandler<GameStateEnum, int> answerRequestHandler) { _gameModel = gameModel; _answerRequestHandler = answerRequestHandler; } public async UniTask OnStateBegan(CancellationToken token) { using var cts = new CancellationTokenSource(); var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, cts.Token); _gameModel.userAnswer = await _answerRequestHandler.InvokeAsync(GameStateEnum.UserInput, linkedTokenSource.Token); } public GameStateEnum OnStateEnded() { return GameStateEnum.CheckAnswer; } } }
32.59375
126
0.684564
[ "MIT" ]
laicasaane/TebakAngka
Assets/_Contents/Gameplay/GameStates/UserInputState.cs
1,043
C#
using Sample.Views; using Prism.Ioc; using Prism.Modularity; using Prism.Regions; namespace Sample { public class SampleModule : IModule { public void OnInitialized(IContainerProvider containerProvider) { var regionManager = containerProvider.Resolve<IRegionManager>(); // Simple registration for regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA)); // Register inside internal MainView regionManager.RegisterViewWithRegion("SimpleContentRegion", typeof(ViewA)); } public void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterForNavigation<MainView>("SimpleMainView"); // Custom name! containerRegistry.RegisterForNavigation<ViewA>("ViewA"); containerRegistry.RegisterForNavigation<ViewB>("ViewB"); } } }
32.642857
96
0.680525
[ "MIT" ]
sequws/MyStarterProjects
PrismMultiModule/Sample/SampleModule.cs
916
C#
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.Project { /// <summary> /// Defines abstract package. /// </summary> [ComVisible(true)] public abstract class ProjectPackage : Microsoft.VisualStudio.Shell.Package { #region fields /// <summary> /// This is the place to register all the solution listeners. /// </summary> private List<SolutionListener> solutionListeners = new List<SolutionListener>(); #endregion #region properties /// <summary> /// Add your listener to this list. They should be added in the overridden Initialize befaore calling the base. /// </summary> protected internal IList<SolutionListener> SolutionListeners { get { return this.solutionListeners; } } public abstract string ProductUserContext { get; } #endregion #region methods protected override void Initialize() { base.Initialize(); // Subscribe to the solution events this.solutionListeners.Add(new SolutionListenerForProjectReferenceUpdate(this)); this.solutionListeners.Add(new SolutionListenerForProjectOpen(this)); this.solutionListeners.Add(new SolutionListenerForBuildDependencyUpdate(this)); this.solutionListeners.Add(new SolutionListenerForProjectEvents(this)); foreach(SolutionListener solutionListener in this.solutionListeners) { solutionListener.Init(); } } protected override void Dispose(bool disposing) { // Unadvise solution listeners. try { if(disposing) { foreach(SolutionListener solutionListener in this.solutionListeners) { solutionListener.Dispose(); } // Dispose the UIThread singleton. UIThread.Instance.Dispose(); } } finally { base.Dispose(disposing); } } #endregion } }
40.885496
119
0.665795
[ "BSD-3-Clause" ]
Dark-Tater/Cosmos
source/Archive/MPF/12.0/ProjectPackage.cs
5,356
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. internal static partial class Interop { internal static partial class ComCtl32 { [Flags] public enum LVCF : uint { /// <summary> /// The <c>fmt</c> member is valid. /// </summary> FMT = 0x0001, /// <summary> /// The <c>cx</c> member is valid. /// </summary> WIDTH = 0x0002, /// <summary> /// The <c>pszText</c> member is valid. /// </summary> TEXT = 0x0004, /// <summary> /// The <c>iSubItem</c> member is valid. /// </summary> SUBITEM = 0x0008, /// <summary> /// The <c>iImage</c> member is valid. /// </summary> IMAGE = 0x0010, /// <summary> /// The <c>iOrder </c> member is valid. /// </summary> ORDER = 0x0020, /// <summary> /// The <c>cxMin</c> member is valid. /// </summary> MINWIDTH = 0x0040, /// <summary> /// The <c>cxDefault</c> member is valid. /// </summary> DEFAULTWIDTH = 0x0080, /// <summary> /// The <c>cxIdeal</c> member is valid. /// </summary> IDEALWIDTH = 0x0100, } } }
26.779661
71
0.443038
[ "MIT" ]
AndreRRR/winforms
src/System.Windows.Forms.Primitives/src/Interop/ComCtl32/Interop.LVCF.cs
1,582
C#
using Microsoft.EntityFrameworkCore; using PaymentGateway.Application.Interfaces.Storage.Write; using PaymentGateway.Domain.Common; using PaymentGateway.Persistence.InMemory.Context; using PaymentGateway.Persistence.InMemory.DataEntities; using System.Threading.Tasks; namespace PaymentGateway.Persistence.InMemory.Repositories { /// <summary> /// Provided basic write functionality (for DRY reasons) /// </summary> public abstract class BaseWriteRepository<T, DBEntity> : IWriteRepository<T> where T : Entity where DBEntity : DataEntity<T>, new() { protected readonly PaymentGatewayContext _db; protected BaseWriteRepository(PaymentGatewayContext context) { _db = context; } public async Task SaveAsync(T entity) { DBEntity dbEntity = new DBEntity(); dbEntity.LoadDomainObject(entity); _db.Entry(dbEntity).State = entity.Id == 0 ? EntityState.Added : EntityState.Modified; await _db.SaveChangesAsync(); } } }
31.05
97
0.591787
[ "Unlicense" ]
marnezos/PaymentGateway
PaymentGateway.Persistence.InMemory/Repositories/BaseWriteRepository.cs
1,244
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200601 { /// <summary> /// A common class for general resource information. /// </summary> [AzureNativeResourceType("azure-native:network/v20200601:LocalNetworkGateway")] public partial class LocalNetworkGateway : Pulumi.CustomResource { /// <summary> /// Local network gateway's BGP speaker settings. /// </summary> [Output("bgpSettings")] public Output<Outputs.BgpSettingsResponse?> BgpSettings { get; private set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// FQDN of local network gateway. /// </summary> [Output("fqdn")] public Output<string?> Fqdn { get; private set; } = null!; /// <summary> /// IP address of local network gateway. /// </summary> [Output("gatewayIpAddress")] public Output<string?> GatewayIpAddress { get; private set; } = null!; /// <summary> /// Local network site address space. /// </summary> [Output("localNetworkAddressSpace")] public Output<Outputs.AddressSpaceResponse?> LocalNetworkAddressSpace { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The provisioning state of the local network gateway resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The resource GUID property of the local network gateway resource. /// </summary> [Output("resourceGuid")] public Output<string> ResourceGuid { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a LocalNetworkGateway resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public LocalNetworkGateway(string name, LocalNetworkGatewayArgs args, CustomResourceOptions? options = null) : base("azure-native:network/v20200601:LocalNetworkGateway", name, args ?? new LocalNetworkGatewayArgs(), MakeResourceOptions(options, "")) { } private LocalNetworkGateway(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:network/v20200601:LocalNetworkGateway", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20150615:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20150615:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20160330:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160330:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20160601:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160601:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20160901:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20161201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20170301:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20170601:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20170801:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20170901:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170901:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20171001:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20171101:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20180101:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20180201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20180401:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20180601:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20180701:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20180801:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20181001:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20181101:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20181201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20190201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20190401:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20190601:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20190701:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20190801:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20190901:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20191101:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20191201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20200301:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20200401:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20200501:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20200701:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20200801:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20201101:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20201101:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20210201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20210201:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-native:network/v20210301:LocalNetworkGateway"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20210301:LocalNetworkGateway"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing LocalNetworkGateway resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static LocalNetworkGateway Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new LocalNetworkGateway(name, id, options); } } public sealed class LocalNetworkGatewayArgs : Pulumi.ResourceArgs { /// <summary> /// Local network gateway's BGP speaker settings. /// </summary> [Input("bgpSettings")] public Input<Inputs.BgpSettingsArgs>? BgpSettings { get; set; } /// <summary> /// FQDN of local network gateway. /// </summary> [Input("fqdn")] public Input<string>? Fqdn { get; set; } /// <summary> /// IP address of local network gateway. /// </summary> [Input("gatewayIpAddress")] public Input<string>? GatewayIpAddress { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Local network site address space. /// </summary> [Input("localNetworkAddressSpace")] public Input<Inputs.AddressSpaceArgs>? LocalNetworkAddressSpace { get; set; } /// <summary> /// The name of the local network gateway. /// </summary> [Input("localNetworkGatewayName")] public Input<string>? LocalNetworkGatewayName { get; set; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public LocalNetworkGatewayArgs() { } } }
53.727941
151
0.608321
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20200601/LocalNetworkGateway.cs
14,614
C#
namespace OpenGLBindings { /// <summary> /// Not used directly. /// </summary> public enum LightEnvParameterSgix { /// <summary> /// Original was GL_LIGHT_ENV_MODE_SGIX = 0x8407 /// </summary> LightEnvModeSgix = 33799 } }
21.307692
56
0.566787
[ "MIT" ]
DeKaDeNcE/WoWDatabaseEditor
Rendering/OpenGLBindings/LightEnvParameterSgix.cs
277
C#
using System.Threading.Tasks; using Abp.Domain.Entities; using Abp.DynamicEntityParameters; using Shouldly; using Xunit; namespace Abp.Zero.SampleApp.Tests.DynamicEntityParameters { public class DynamicParameterValueManager_Tests : DynamicEntityParametersTestBase { private readonly IDynamicParameterValueManager _dynamicParameterValueManager; public DynamicParameterValueManager_Tests() { _dynamicParameterValueManager = Resolve<IDynamicParameterValueManager>(); } private void CheckEquality(DynamicParameterValue v1, DynamicParameterValue v2) { v1.ShouldNotBeNull(); v2.ShouldNotBeNull(); v1.DynamicParameterId.ShouldBe(v2.DynamicParameterId); v1.Value.ShouldBe(v2.Value); } [Fact] public void Should_Get_Value() { var dynamicParameter = CreateAndGetDynamicParameterWithTestPermission(); var dynamicParameterValue = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test", TenantId = AbpSession.TenantId }; WithUnitOfWork(() => { var d = DynamicParameterStore.Get(dynamicParameter.Id); _dynamicParameterValueManager.Add(dynamicParameterValue); }); RunAndCheckIfPermissionControlled(() => { var entity = _dynamicParameterValueManager.Get(dynamicParameterValue.Id); CheckEquality(entity, dynamicParameterValue); }); } [Fact] public void Should_Add_Value() { var dynamicParameter = CreateAndGetDynamicParameterWithTestPermission(); var dynamicParameterValue = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test", TenantId = AbpSession.TenantId }; RunAndCheckIfPermissionControlled(() => { _dynamicParameterValueManager.Add(dynamicParameterValue); }); WithUnitOfWork(() => { var entity = _dynamicParameterValueManager.Get(dynamicParameterValue.Id); CheckEquality(entity, dynamicParameterValue); }); } [Fact] public void Should_Update_Value() { var dynamicParameter = CreateAndGetDynamicParameterWithTestPermission(); var dynamicParameterValue = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test", TenantId = AbpSession.TenantId }; WithUnitOfWork(() => { _dynamicParameterValueManager.Add(dynamicParameterValue); }); WithUnitOfWork(() => { dynamicParameterValue = _dynamicParameterValueManager.Get(dynamicParameterValue.Id); dynamicParameterValue.ShouldNotBeNull(); }); dynamicParameterValue.Value = "Test2"; RunAndCheckIfPermissionControlled(() => { _dynamicParameterValueManager.Update(dynamicParameterValue); }); WithUnitOfWork(() => { var entity = _dynamicParameterValueManager.Get(dynamicParameterValue.Id); entity.Value.ShouldBe("Test2"); entity.DynamicParameterId.ShouldBe(dynamicParameter.Id); }); } [Fact] public void Should_Delete_Value() { var dynamicParameter = CreateAndGetDynamicParameterWithTestPermission(); var dynamicParameterValue = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test", TenantId = AbpSession.TenantId }; WithUnitOfWork(() => { _dynamicParameterValueManager.Add(dynamicParameterValue); }); RunAndCheckIfPermissionControlled(() => { _dynamicParameterValueManager.Delete(dynamicParameterValue.Id); }); WithUnitOfWork(() => { try { var entity = _dynamicParameterValueManager.Get(dynamicParameterValue.Id); entity.ShouldBeNull(); } catch (EntityNotFoundException) { } }); } [Fact] public void Should_Clean_Value() { var dynamicParameter = CreateAndGetDynamicParameterWithTestPermission(); var dynamicParameterValue = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test", TenantId = AbpSession.TenantId }; var dynamicParameterValue2 = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test2", TenantId = AbpSession.TenantId }; WithUnitOfWork(() => { _dynamicParameterValueManager.Add(dynamicParameterValue); _dynamicParameterValueManager.Add(dynamicParameterValue2); }); RunAndCheckIfPermissionControlled(() => { _dynamicParameterValueManager.CleanValues(dynamicParameter.Id); }); WithUnitOfWork(() => { var entity = _dynamicParameterValueManager.GetAllValuesOfDynamicParameter(dynamicParameter.Id); entity.ShouldBeEmpty(); }); } [Fact] public async Task Should_Get_Value_Async() { var dynamicParameter = CreateAndGetDynamicParameterWithTestPermission(); var dynamicParameterValue = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test", TenantId = AbpSession.TenantId }; await WithUnitOfWorkAsync(async () => { await _dynamicParameterValueManager.AddAsync(dynamicParameterValue); }); await RunAndCheckIfPermissionControlledAsync(async () => { var entity = await _dynamicParameterValueManager.GetAsync(dynamicParameterValue.Id); CheckEquality(entity, dynamicParameterValue); }); } [Fact] public async Task Should_Add_Value_Async() { var dynamicParameter = CreateAndGetDynamicParameterWithTestPermission(); var dynamicParameterValue = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test", TenantId = AbpSession.TenantId }; await RunAndCheckIfPermissionControlledAsync(async () => { await _dynamicParameterValueManager.AddAsync(dynamicParameterValue); }); await WithUnitOfWorkAsync(async () => { var entity = await _dynamicParameterValueManager.GetAsync(dynamicParameterValue.Id); CheckEquality(entity, dynamicParameterValue); }); } [Fact] public async Task Should_Update_Value_Async() { var dynamicParameter = CreateAndGetDynamicParameterWithTestPermission(); var dynamicParameterValue = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test", TenantId = AbpSession.TenantId }; await WithUnitOfWorkAsync(async () => { await _dynamicParameterValueManager.AddAsync(dynamicParameterValue); }); await WithUnitOfWorkAsync(async () => { dynamicParameterValue = await _dynamicParameterValueManager.GetAsync(dynamicParameterValue.Id); dynamicParameterValue.ShouldNotBeNull(); }); dynamicParameterValue.Value = "Test2"; await RunAndCheckIfPermissionControlledAsync(async () => { await _dynamicParameterValueManager.UpdateAsync(dynamicParameterValue); }); await WithUnitOfWorkAsync(async () => { var entity = await _dynamicParameterValueManager.GetAsync(dynamicParameterValue.Id); entity.Value.ShouldBe("Test2"); entity.DynamicParameterId.ShouldBe(dynamicParameter.Id); }); } [Fact] public async Task Should_Delete_Value_Async() { var dynamicParameter = CreateAndGetDynamicParameterWithTestPermission(); var dynamicParameterValue = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test", TenantId = AbpSession.TenantId }; await WithUnitOfWorkAsync(async () => { await _dynamicParameterValueManager.AddAsync(dynamicParameterValue); }); await RunAndCheckIfPermissionControlledAsync(async () => { await _dynamicParameterValueManager.DeleteAsync(dynamicParameterValue.Id); }); await WithUnitOfWorkAsync(async () => { try { var entity = await _dynamicParameterValueManager.GetAsync(dynamicParameterValue.Id); entity.ShouldBeNull(); } catch (EntityNotFoundException) { } }); } [Fact] public async Task Should_Clean_Value_Async() { var dynamicParameter = CreateAndGetDynamicParameterWithTestPermission(); var dynamicParameterValue = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test", TenantId = AbpSession.TenantId }; var dynamicParameterValue2 = new DynamicParameterValue() { DynamicParameterId = dynamicParameter.Id, Value = "Test2", TenantId = AbpSession.TenantId }; await WithUnitOfWorkAsync(async () => { await _dynamicParameterValueManager.AddAsync(dynamicParameterValue); await _dynamicParameterValueManager.AddAsync(dynamicParameterValue2); }); await RunAndCheckIfPermissionControlledAsync(async () => { await _dynamicParameterValueManager.CleanValuesAsync(dynamicParameter.Id); }); await WithUnitOfWorkAsync(async () => { var entity = await _dynamicParameterValueManager.GetAllValuesOfDynamicParameterAsync(dynamicParameter.Id); entity.ShouldBeEmpty(); }); } } }
33.263768
122
0.559341
[ "MIT" ]
Aytekin/aspnetboilerplate
test/Abp.Zero.SampleApp.Tests/DynamicEntityParameters/DynamicParameterValueManager_Tests.cs
11,478
C#
using System.Linq; using NeoSharp.Application.Client; using NeoSharp.Core; using NeoSharp.Core.DI; using NeoSharp.Core.Extensions; namespace NeoSharp.Application.DI { public class ClientModule : IModule { public void Register(IContainerBuilder containerBuilder) { containerBuilder.Register<IBootstrapper, Bootstrapper>(); containerBuilder.RegisterSingleton<IPrompt, Prompt>(); containerBuilder.RegisterSingleton<IPromptUserVariables, PromptUserVariables>(); containerBuilder.RegisterSingleton<IConsoleReader, ConsoleReader>(); containerBuilder.RegisterSingleton<IConsoleWriter, ConsoleWriter>(); // Get prompt controllers var promptHandlerTypes = typeof(IPromptController).Assembly .GetExportedTypes() .Where(t => t.IsClass && !t.IsInterface && !t.IsAbstract && typeof(IPromptController).IsAssignableFrom(t)) .ToArray(); containerBuilder.RegisterCollection(typeof(IPromptController), promptHandlerTypes); } } }
37.655172
121
0.68956
[ "MIT" ]
wy/neo-sharp
src/NeoSharp.Application/DI/ClientModule.cs
1,094
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace LogicMonitor.Api.Data { /// <summary> /// Raw LogicMonitor Data /// </summary> [DataContract] public class Data { /// <summary> /// Data Values /// </summary> [DataMember(Name = "values")] public Dictionary<string, object[][]> DataValues { get; set; } /// <summary> /// Data Points /// </summary> [DataMember(Name = "dataPoints")] public string[] DataPoints { get; set; } /// <summary> /// Data Points /// </summary> [DataMember(Name = "tzoffset")] public int TimeZoneOffsetMilliseconds { get; set; } } }
20.8
64
0.639423
[ "MIT" ]
tdicks/LogicMonitor.Api
LogicMonitor.Api/Data/Data.cs
624
C#
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TicketOffice.Models; public class RouteCity { [Key] public int Id { get; set; } [MaxLength(24, ErrorMessage = "Назва міста не може бути більше 24 символів"), MinLength(2, ErrorMessage = "Назва міста не може бути менше 2 символів")] [Display(Name = "Назва міста")] [Required(ErrorMessage = "Поле має бути заповненим")] public string Name { get; set; } = null!; [Display(Name = "Дата відправлення")] [DataType(DataType.Date)] public DateTime? ArrivalTime { get; set; } [Display(Name = "Дата прибуття")] [DataType(DataType.Date)] public DateTime? DepartureTime { get; set; } [Display(Name = "Ціна подорожі з попереднього міста")] [DataType(DataType.Currency)] public double? CostFromPreviousCity { get; set; } [ForeignKey("Route")] public int RouteId { get; set; } public Route Route { get; set; } = null!; }
31.625
81
0.667984
[ "MIT" ]
cuqmbr/ticket-office
TicketOffice/Models/RouteCity.cs
1,168
C#
using System; using System.IO; using System.Data.SQLite; using System.Data.SqlClient; namespace MemeTeamPro { internal class Program { static void Main(string[] args) { UserInterface UI = new UserInterface(); UI.Start(); // /*Database databaseObject = new Database(); // Console.ReadKey();*/ // SQLiteConnection.CreateFile("MyDatabase.sqlite"); // Console.WriteLine("Created a database!"); // // Open a database connection // SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;"); // m_dbConnection.Open(); // // Create a table // string sql = "CREATE TABLE Highscores (name TEXT, score INTEGER)"; // SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection); // command.ExecuteNonQuery(); // // Create a table for CRUD // string sql1 = "CREATE TABLE User(Id INTEGER PRIMARY KEY AUTOINCREMENT, " + // "FirstName TEXT NOT NULL, LastName TEXT NOT NULL)"; // SQLiteCommand command1 = new SQLiteCommand(sql1, m_dbConnection); // command1.ExecuteNonQuery(); // // Insert dummy data into table scores // sql = "INSERT INTO Highscores (name, score) VALUES ('Me', 9001)"; // command = new SQLiteCommand(sql, m_dbConnection); // command.ExecuteNonQuery(); // sql = "INSERT INTO Highscores (name, score) VALUES ('Myself', 6000)"; // command = new SQLiteCommand(sql, m_dbConnection); // command.ExecuteNonQuery(); // sql = "INSERT INTO Highscores (name, score) VALUES ('And I', 9001)"; // command = new SQLiteCommand(sql, m_dbConnection); // command.ExecuteNonQuery(); // // Read the data from the database // sql = "SELECT * FROM User ORDER BY Id DESC"; // command1 = new SQLiteCommand(sql, m_dbConnection); // SQLiteDataReader reader1 = command1.ExecuteReader(); // while (reader1.Read()) // { // Console.WriteLine("Id: " + reader1["Id"] + "\tFirstName: " + reader1["FirstName"] + "\tLastName: " + reader1["LastName"]); // } // // Read the data from the database // sql = "SELECT * FROM Highscores ORDER BY score DESC"; // command = new SQLiteCommand(sql, m_dbConnection); // SQLiteDataReader reader = command.ExecuteReader(); // while (reader.Read()) // { // Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["score"]); // } // // Close the connection // m_dbConnection.Close(); } } }
39.621622
142
0.538881
[ "MIT" ]
Antenni/memeteam
src/AgileGroupwork/Program.cs
2,934
C#
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Service { using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Text; using Apache.Ignite.Config; using Apache.Ignite.Core; using Apache.Ignite.Core.Common; /// <summary> /// Ignite windows service. /// </summary> internal class IgniteService : ServiceBase { /** Service name. */ internal static readonly string SvcName = "Apache Ignite.NET"; /** Service display name. */ internal static readonly string SvcDisplayName = "Apache Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version.ToString(4); /** Service description. */ internal static readonly string SvcDesc = "Apache Ignite.NET Service."; /** Current executable name. */ internal static readonly string ExeName = new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath).FullName; /** Current executable fully qualified name. */ internal static readonly string FullExeName = Path.GetFileName(FullExeName); /** Ignite configuration to start with. */ private readonly IgniteConfiguration _cfg; /// <summary> /// Constructor. /// </summary> public IgniteService(IgniteConfiguration cfg) { AutoLog = true; CanStop = true; ServiceName = SvcName; _cfg = cfg; } /** <inheritDoc /> */ protected override void OnStart(string[] args) { Ignition.Start(_cfg); } /** <inheritDoc /> */ protected override void OnStop() { Ignition.StopAll(true); } /// <summary> /// Install service programmatically. /// </summary> /// <param name="cfg">Ignite configuration.</param> internal static void DoInstall(IgniteConfiguration cfg) { // 1. Check if already defined. if (ServiceController.GetServices().Any(svc => SvcName.Equals(svc.ServiceName))) { throw new IgniteException("Ignite service is already installed (uninstall it using \"" + ExeName + " " + IgniteRunner.SvcUninstall + "\" first)"); } // 2. Create startup arguments. var args = ArgsConfigurator.ToArgs(cfg); if (args.Length > 0) { Console.WriteLine("Installing \"" + SvcName + "\" service with the following startup " + "arguments:"); foreach (var arg in args) Console.WriteLine("\t" + arg); } else Console.WriteLine("Installing \"" + SvcName + "\" service ..."); // 3. Actual installation. Install0(args); Console.WriteLine("\"" + SvcName + "\" service installed successfully."); } /// <summary> /// Uninstall service programmatically. /// </summary> internal static void Uninstall() { var svc = ServiceController.GetServices().FirstOrDefault(x => SvcName == x.ServiceName); if (svc == null) { Console.WriteLine("\"" + SvcName + "\" service is not installed."); } else if (svc.Status != ServiceControllerStatus.Stopped) { throw new IgniteException("Ignite service is running, please stop it first."); } else { Console.WriteLine("Uninstalling \"" + SvcName + "\" service ..."); Uninstall0(); Console.WriteLine("\"" + SvcName + "\" service uninstalled successfully."); } } /// <summary> /// Native service installation. /// </summary> /// <param name="args">Arguments.</param> private static void Install0(string[] args) { // 1. Prepare arguments. var binPath = new StringBuilder(FullExeName).Append(" ").Append(IgniteRunner.Svc); foreach (var arg in args) binPath.Append(" ").Append(arg); // 2. Get SC manager. var scMgr = OpenServiceControlManager(); // 3. Create service. var svc = NativeMethods.CreateService( scMgr, SvcName, SvcDisplayName, 983551, // Access constant. 0x10, // Service type SERVICE_WIN32_OWN_PROCESS. 0x2, // Start type SERVICE_AUTO_START. 0x2, // Error control SERVICE_ERROR_SEVERE. binPath.ToString(), null, IntPtr.Zero, null, null, // Use priviliged LocalSystem account. null ); if (svc == IntPtr.Zero) throw new IgniteException("Failed to create the service.", new Win32Exception()); // 4. Set description. var desc = new ServiceDescription {desc = Marshal.StringToHGlobalUni(SvcDesc)}; try { if (!NativeMethods.ChangeServiceConfig2(svc, 1u, ref desc)) throw new IgniteException("Failed to set service description.", new Win32Exception()); } finally { Marshal.FreeHGlobal(desc.desc); } } /// <summary> /// Native service uninstallation. /// </summary> private static void Uninstall0() { var scMgr = OpenServiceControlManager(); var svc = NativeMethods.OpenService(scMgr, SvcName, 65536); if (svc == IntPtr.Zero) throw new IgniteException("Failed to uninstall the service.", new Win32Exception()); NativeMethods.DeleteService(svc); } /// <summary> /// Opens SC manager. /// </summary> /// <returns>SC manager pointer.</returns> private static IntPtr OpenServiceControlManager() { var ptr = NativeMethods.OpenSCManager(null, null, 983103); if (ptr == IntPtr.Zero) throw new IgniteException("Failed to initialize Service Control manager " + "(did you run the command as administrator?)", new Win32Exception()); return ptr; } } }
33.972727
111
0.555526
[ "CC0-1.0" ]
anton-vinogradov/ignite
modules/platforms/dotnet/Apache.Ignite/Service/IgniteService.cs
7,474
C#
using EmbeddedMvc.IdentityServer; using Microsoft.IdentityModel.Protocols; using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Google; using Microsoft.Owin.Security.OpenIdConnect; using Owin; using System; using System.Collections.Generic; using System.IdentityModel.Tokens; using System.Security.Claims; using System.Security.Cryptography.X509Certificates; using System.Linq; using System.Web.Helpers; using IdentityServer3.Core; using IdentityServer3.Core.Configuration; using IdentityModel.Client; using System.Threading.Tasks; [assembly: OwinStartup(typeof(EmbeddedMvc.Startup))] namespace EmbeddedMvc { public class Startup { public void Configuration(IAppBuilder app) { // todo: replace with serilog //LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider()); AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); app.Map("/identity", idsrvApp => { idsrvApp.UseIdentityServer(new IdentityServerOptions { SiteName = "Embedded IdentityServer", SigningCertificate = LoadCertificate(), Factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()), AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions { EnablePostSignOutAutoRedirect = true, IdentityProviders = ConfigureIdentityProviders } }); }); app.UseResourceAuthorization(new AuthorizationManager()); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { Authority = "https://localhost:44319/identity", ClientId = "mvc", Scope = "openid profile roles sampleApi", ResponseType = "id_token token", RedirectUri = "https://localhost:44319/", SignInAsAuthenticationType = "Cookies", UseTokenLifetime = false, Notifications = new OpenIdConnectAuthenticationNotifications { SecurityTokenValidated = async n => { var nid = new ClaimsIdentity( n.AuthenticationTicket.Identity.AuthenticationType, Constants.ClaimTypes.GivenName, Constants.ClaimTypes.Role); // get userinfo data var userInfoClient = new UserInfoClient( new Uri(n.Options.Authority + "/connect/userinfo"), n.ProtocolMessage.AccessToken); var userInfo = await userInfoClient.GetAsync(); userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2))); // keep the id_token for logout nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); // add access token for sample API nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken)); // keep track of access token expiration nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString())); // add some other app specific claim nid.AddClaim(new Claim("app_specific", "some data")); n.AuthenticationTicket = new AuthenticationTicket( nid, n.AuthenticationTicket.Properties); }, RedirectToIdentityProvider = n => { if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token"); if (idTokenHint != null) { n.ProtocolMessage.IdTokenHint = idTokenHint.Value; } } return Task.FromResult(0); } } }); } private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType) { app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions { AuthenticationType = "Google", Caption = "Sign-in with Google", SignInAsAuthenticationType = signInAsType, ClientId = "701386055558-9epl93fgsjfmdn14frqvaq2r9i44qgaa.apps.googleusercontent.com", ClientSecret = "3pyawKDWaXwsPuRDL7LtKm_o" }); } X509Certificate2 LoadCertificate() { return new X509Certificate2( string.Format(@"{0}\bin\identityServer\idsrv3test.pfx", AppDomain.CurrentDomain.BaseDirectory), "idsrv3test"); } } }
42.575342
152
0.514479
[ "Apache-2.0" ]
AkhilNaidu09/IdentityServer3.Samples
source/MVC Authentication/EmbeddedMvc/Startup.cs
6,218
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 getCardUid { public partial class ventanaCara : Form { public ventanaCara() { InitializeComponent(); } } }
18.142857
43
0.692913
[ "MIT" ]
3dangs28/bioLector
getCardUid/ventanaCara.cs
383
C#
#if MIXTURE_SHADERGRAPH using UnityEngine; using UnityEditor.ShaderGraph; using UnityEditor.Graphing; namespace Mixture { [Title("Custom Texture", "Size")] class CustomTextureSize : AbstractMaterialNode, IGeneratesFunction { private const string kOutputSlotWidthName = "Texture Width"; private const string kOutputSlotHeightName = "Texture Height"; private const string kOutputSlotDepthName = "Texture Depth"; public const int OutputSlotWidthId = 0; public const int OutputSlotHeightId = 1; public const int OutputSlotDepthId = 2; public CustomTextureSize() { name = "Custom Texture Size"; UpdateNodeAfterDeserialization(); } protected int[] validSlots => new[] { OutputSlotWidthId, OutputSlotHeightId, OutputSlotDepthId }; public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(OutputSlotWidthId, kOutputSlotWidthName, kOutputSlotWidthName, SlotType.Output, 0)); AddSlot(new Vector1MaterialSlot(OutputSlotHeightId, kOutputSlotHeightName, kOutputSlotHeightName, SlotType.Output, 0)); AddSlot(new Vector1MaterialSlot(OutputSlotDepthId, kOutputSlotDepthName, kOutputSlotDepthName, SlotType.Output, 0)); RemoveSlotsNameNotMatching(validSlots); } public override string GetVariableNameForSlot(int slotId) { switch (slotId) { case OutputSlotHeightId: return "_CustomRenderTextureHeight"; case OutputSlotDepthId: return "_CustomRenderTextureDepth"; default: return "_CustomRenderTextureWidth"; } } public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { // For preview only we declare CRT defines if (generationMode == GenerationMode.Preview) { registry.builder.AppendLine("#define _CustomRenderTextureHeight 0.0"); registry.builder.AppendLine("#define _CustomRenderTextureWidth 0.0"); registry.builder.AppendLine("#define _CustomRenderTextureDepth 0.0"); } } } [Title("Custom Texture", "Slice / Face")] class CustomTextureSlice : AbstractMaterialNode, IGeneratesFunction { private const string kOutputSlotCubeFaceName = "Texture Cube Face"; private const string kOutputSlot3DSliceName = "Texture 3D Slice"; public const int OutputSlotCubeFaceId = 3; public const int OutputSlot3DSliceId = 4; public CustomTextureSlice() { name = "Custom Texture Size"; UpdateNodeAfterDeserialization(); } protected int[] validSlots => new[] { OutputSlotCubeFaceId, OutputSlot3DSliceId }; public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(OutputSlotCubeFaceId, kOutputSlotCubeFaceName, kOutputSlotCubeFaceName, SlotType.Output, 0)); AddSlot(new Vector1MaterialSlot(OutputSlot3DSliceId, kOutputSlot3DSliceName, kOutputSlot3DSliceName, SlotType.Output, 0)); RemoveSlotsNameNotMatching(validSlots); } public override string GetVariableNameForSlot(int slotId) { switch (slotId) { case OutputSlotCubeFaceId: return "_CustomRenderTextureCubeFace"; case OutputSlot3DSliceId: return "_CustomRenderTexture3DSlice"; default: return "_CustomRenderTextureWidth"; } } public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { // For preview only we declare CRT defines if (generationMode == GenerationMode.Preview) { registry.builder.AppendLine("#define _CustomRenderTextureCubeFace 0.0"); registry.builder.AppendLine("#define _CustomRenderTexture3DSlice 0.0"); } } } [Title("Custom Texture", "Self")] class CustomTextureSelf : AbstractMaterialNode, IGeneratesFunction { private const string kOutputSlotSelf2DName = "Self Texture 2D"; private const string kOutputSlotSelfCubeName = "Self Texture Cube"; private const string kOutputSlotSelf3DName = "Self Texture 3D"; public const int OutputSlotSelf2DId = 5; public const int OutputSlotSelfCubeId = 6; public const int OutputSlotSelf3DId = 7; public CustomTextureSelf() { name = "Custom Texture Self"; UpdateNodeAfterDeserialization(); } protected int[] validSlots => new[] { OutputSlotSelf2DId, OutputSlotSelfCubeId, OutputSlotSelf3DId }; public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Texture2DMaterialSlot(OutputSlotSelf2DId, kOutputSlotSelf2DName, kOutputSlotSelf2DName, SlotType.Output, ShaderStageCapability.Fragment, false)); AddSlot(new CubemapMaterialSlot(OutputSlotSelfCubeId, kOutputSlotSelfCubeName, kOutputSlotSelfCubeName, SlotType.Output, ShaderStageCapability.Fragment, false)); AddSlot(new Texture2DMaterialSlot(OutputSlotSelf3DId, kOutputSlotSelf3DName, kOutputSlotSelf3DName, SlotType.Output, ShaderStageCapability.Fragment, false)); RemoveSlotsNameNotMatching(validSlots); } public override string GetVariableNameForSlot(int slotId) { switch (slotId) { case OutputSlotSelf2DId: return "_SelfTexture2D"; case OutputSlotSelfCubeId: return "_SelfTextureCube"; default: return "_SelfTexture3D"; } } public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { // For preview only we declare CRT defines if (generationMode == GenerationMode.Preview) { registry.builder.AppendLine("TEXTURE2D(_SelfTexture2D);"); registry.builder.AppendLine("SAMPLER(sampler_SelfTexture2D);"); registry.builder.AppendLine("TEXTURE2D(_SelfTextureCube);"); registry.builder.AppendLine("SAMPLER(sampler_SelfTextureCube);"); registry.builder.AppendLine("TEXTURE2D(_SelfTexture3D);"); registry.builder.AppendLine("SAMPLER(sampler_SelfTexture3D);"); } } } } #endif
41.147239
173
0.65126
[ "MIT" ]
IxxyXR/PolyGraph
Packages/com.alelievr.mixture/Editor/CustomTextureShaderGraph/CustomTextureNodes.cs
6,707
C#
#region LICENSE /* MIT License Copyright (c) 2018 bugbit 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 System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MiniCAS.Core.Extensions { public static class TimeSpanExtensions { public static string ToShortString(this TimeSpan t) { var strs = new List<string>(); if (t.Hours == 1) strs.Add(string.Format(Properties.Resources.TimespanHour, t.Hours)); else if (t.Hours > 1) strs.Add(string.Format(Properties.Resources.TimespanHours, t.Hours)); if (t.Minutes == 1) strs.Add(string.Format(Properties.Resources.TimespanMinute, t.Minutes)); else if (t.Minutes > 1) strs.Add(string.Format(Properties.Resources.TimespanMinutes, t.Minutes)); if (t.Seconds == 1) strs.Add(string.Format(Properties.Resources.TimespanSecond, t.Seconds)); else if (t.Seconds > 1) strs.Add(string.Format(Properties.Resources.TimespanSeconds, t.Seconds)); if (t.Milliseconds > 0) strs.Add(string.Format(Properties.Resources.TimespanMiliSeconds, t.Milliseconds)); return string.Join(' ', strs); } } }
38.393443
98
0.698975
[ "MIT" ]
bugbit/MiniCAS
MiniCAS.Core/Extensions/TimeSpanExtensions.cs
2,344
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Website_RegLog { public partial class Home : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
18.470588
60
0.687898
[ "MIT" ]
HeshamFawzy/Website-RegLog
Website-RegLog/Website-RegLog/Home.aspx.cs
316
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DataMigration.V20180331Preview.Inputs { /// <summary> /// Blob container storage information. /// </summary> public sealed class BlobShareArgs : Pulumi.ResourceArgs { /// <summary> /// SAS URI of Azure Storage Account Container. /// </summary> [Input("sasUri", required: true)] public Input<string> SasUri { get; set; } = null!; public BlobShareArgs() { } } }
26.827586
81
0.647815
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DataMigration/V20180331Preview/Inputs/BlobShareArgs.cs
778
C#
// Licensed under the BSD license // See the LICENSE file in the project root for more information using System.Collections.Generic; using NLog.Targets.Syslog.Settings; namespace NLog.Targets.Syslog.MessageCreation { internal class LogLevelSeverityMapping { private readonly IDictionary<LogLevel, Severity> logLevelSeverityMapping; public LogLevelSeverityMapping(LogLevelSeverityConfig logLevelSeverityConfig) { logLevelSeverityMapping = new Dictionary<LogLevel, Severity> { { LogLevel.Fatal, logLevelSeverityConfig.Fatal }, { LogLevel.Error, logLevelSeverityConfig.Error }, { LogLevel.Warn, logLevelSeverityConfig.Warn }, { LogLevel.Info, logLevelSeverityConfig.Info }, { LogLevel.Debug, logLevelSeverityConfig.Debug }, { LogLevel.Trace, logLevelSeverityConfig.Trace } }; } public Severity this[LogLevel logLevel] => logLevelSeverityMapping[logLevel]; } }
38.285714
87
0.656716
[ "BSD-3-Clause" ]
JTOne123/NLog.Targets.Syslog
src/NLog.Targets.Syslog/MessageCreation/LogLevelSeverityMapping.cs
1,045
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace Multilinks.Core.Services.Migrations { public partial class AddNotificationsTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Notifications", columns: table => new { NotificationId = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), RecipientEndpointId = table.Column<Guid>(nullable: false), NotificationType = table.Column<int>(nullable: false), Message = table.Column<string>(maxLength: 256, nullable: false), Hidden = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Notifications", x => x.NotificationId); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Notifications"); } } }
37.342857
122
0.58378
[ "MIT" ]
andym-2iV/MultilinksCore
Multilinks.Core/Services/Migrations/20190609101402_AddNotificationsTable.cs
1,309
C#
using Newtonsoft.Json; using RestSharp; using System; using System.Net; namespace gpayments.Utils { public static class ProcessResponse { public static T Process<T>(IRestResponse response) where T : class { if(IsError(response.StatusCode)) { throw new Exception($"4Geeks payments returns an error. HttpCode: {response.StatusCode}, Message: {response.StatusDescription}, Content: {response.Content}"); } return JsonConvert.DeserializeObject<T>(response.Content); } public static bool Process(IRestResponse response, HttpStatusCode expectedHttpStatusCode) { if (IsError(response.StatusCode)) { throw new Exception($"4Geeks payments returns an error. HttpCode: {response.StatusCode}, Message: {response.StatusDescription}, Content: {response.Content}"); } return response.StatusCode == expectedHttpStatusCode; } private static bool IsError(HttpStatusCode statusCode) { return statusCode == HttpStatusCode.BadRequest || statusCode == HttpStatusCode.MethodNotAllowed || statusCode == HttpStatusCode.InternalServerError || statusCode == HttpStatusCode.Unauthorized || statusCode == HttpStatusCode.Forbidden || statusCode == HttpStatusCode.NotFound || statusCode == HttpStatusCode.ServiceUnavailable; } } }
36.333333
174
0.629096
[ "MIT" ]
djhvscf/gpayments-dotnet
gpayments-dotnet/Utils/ProcessResponse.cs
1,528
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Toggl.DataObjects; using Toggl.QueryObjects; namespace Toggl.Interfaces { public interface IReportServiceAsync { IApiServiceAsync ToggleSrv { get; set; } Task<DetailedReport> Detailed(DetailedReportParams requestParameters); } }
21.222222
78
0.759162
[ "MIT" ]
DannyRusnok/TogglAPI.Net
TogglAPI.NetStandard/Interfaces/IReportServiceAsync.cs
384
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlgoTest.LeetCode.Custom_Sort_String { [TestClass] public class Custom_Sort_String { [TestMethod] public void Test() { Assert.AreEqual("cbad" , CustomSortString("cba", "abcd")); } public string CustomSortString(string order, string str) { var dic = new Dictionary<char, int>(); for (var i = 0; i < str.Length; i++) { var key = str[i]; if (!dic.TryAdd(key, 1)) dic[key] += 1; } var ret = new StringBuilder(str.Length); for (var i = 0; i < order.Length; i++) { var key = order[i]; if (dic.ContainsKey(key)) { ret.Append(new string(order[i], dic[key])); dic.Remove(key); } } foreach (var dicKey in dic.Keys) { ret.Append(new string(dicKey, dic[dicKey])); } return ret.ToString(); } } }
25.510638
70
0.477064
[ "MIT" ]
sagasu/Algo-DataStructures
AlgoTest/LeetCode/Custom Sort String/Custom Sort String.cs
1,201
C#
namespace Nzy3d.Maths { public enum PlaneAxis { X, Y, Z } }
6.9
22
0.594203
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
BobLd/Nzy3d
Nzy3d/Maths/PlaneAxis.cs
69
C#
using System; using System.IO; namespace PdfToolConsole.Tests { namespace PdfToolConsoleTest { public abstract class PdfToolConsoleTestBase : IDisposable { protected const string _testDataDir = "../../../TestData"; protected const string _existFileName = "PdfRotateTest.pdf"; protected string _existFilePath; protected const string _outputFileName = "output.pdf"; protected string _outputFilePath; public void Dispose() { if (File.Exists(_outputFilePath)) { try { File.Delete(_outputFilePath); } catch { // } } } } } }
26.363636
72
0.46092
[ "MIT" ]
shuheydev/PdfTool
src/PdfToolConsole.Tests/PdfToolConsoleTestBase.cs
872
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.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace System.Threading { // // Windows-specific implementation of Timer // internal partial class TimerQueue { private IntPtr _nativeTimer; [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static void TimerCallback(IntPtr instance, IntPtr context, IntPtr timer) { var wrapper = ThreadPoolCallbackWrapper.Enter(); Instance.FireNextTimers(); wrapper.Exit(); } private unsafe void SetTimer(uint actualDuration) { if (_nativeTimer == IntPtr.Zero) { IntPtr nativeCallback = AddrofIntrinsics.AddrOf<Interop.mincore.TimerCallback>(TimerCallback); _nativeTimer = Interop.mincore.CreateThreadpoolTimer(nativeCallback, IntPtr.Zero, IntPtr.Zero); if (_nativeTimer == IntPtr.Zero) throw new OutOfMemoryException(); } // Negative time indicates the amount of time to wait relative to the current time, in 100 nanosecond units long dueTime = -10000 * (long)actualDuration; Interop.mincore.SetThreadpoolTimer(_nativeTimer, &dueTime, 0, 0); } // // We need to keep our notion of time synchronized with the calls to SleepEx that drive // the underlying native timer. In Win8, SleepEx does not count the time the machine spends // sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time, // so we will get out of sync with SleepEx if we use that method. // // So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent // in sleep/hibernate mode. // private static int TickCount { get { ulong time100ns; bool result = Interop.mincore.QueryUnbiasedInterruptTime(out time100ns); Debug.Assert(result); // convert to 100ns to milliseconds, and truncate to 32 bits. return (int)(uint)(time100ns / 10000); } } } internal sealed partial class TimerQueueTimer { private void SignalNoCallbacksRunning() { object toSignal = _notifyWhenNoCallbacksRunning; Debug.Assert(toSignal is WaitHandle || toSignal is Task<bool>); if (toSignal is WaitHandle wh) { Interop.Kernel32.SetEvent(wh.SafeWaitHandle); } else { ((Task<bool>)toSignal).TrySetResult(true); } } } }
35.25
119
0.611955
[ "MIT" ]
Dotnet-GitSync-Bot/corert
src/System.Private.CoreLib/src/System/Threading/Timer.Windows.cs
2,961
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the athena-2017-05-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Athena.Model { /// <summary> /// This is the response object from the ListWorkGroups operation. /// </summary> public partial class ListWorkGroupsResponse : AmazonWebServiceResponse { private string _nextToken; private List<WorkGroupSummary> _workGroups = new List<WorkGroupSummary>(); /// <summary> /// Gets and sets the property NextToken. /// <para> /// A token to be used by the next request if this request is truncated. /// </para> /// </summary> [AWSProperty(Min=1, Max=1024)] public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } /// <summary> /// Gets and sets the property WorkGroups. /// <para> /// The list of workgroups, including their names, descriptions, creation times, and states. /// </para> /// </summary> [AWSProperty(Min=0, Max=50)] public List<WorkGroupSummary> WorkGroups { get { return this._workGroups; } set { this._workGroups = value; } } // Check to see if WorkGroups property is set internal bool IsSetWorkGroups() { return this._workGroups != null && this._workGroups.Count > 0; } } }
30.987179
104
0.628879
[ "Apache-2.0" ]
Melvinerall/aws-sdk-net
sdk/src/Services/Athena/Generated/Model/ListWorkGroupsResponse.cs
2,417
C#
using Imagini.Drawing; using Imagini.Fonts; using Imagini.Fonts.Renderers; namespace Imagini.Fonts { /// <summary> /// Contains Graphics class related extension methods. /// </summary> public static class GraphicsExtensions { /// <summary> /// Creates a text renderer for the specified font. /// </summary> public static ITextRenderer CreateTextRenderer( this Graphics graphics, SpriteFont font, TextureScalingQuality quality = TextureScalingQuality.Linear) => new GraphicsTextRenderer(graphics, font, quality); } }
30.45
76
0.661741
[ "MIT" ]
project-grove/imagini
Imagini.Fonts/GraphicsExtensions.cs
609
C#
namespace GigHub.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddingUserNotificationTable : DbMigration { public override void Up() { CreateTable( "dbo.UserNotifications", c => new { UserId = c.String(nullable: false, maxLength: 128), NotificationId = c.Int(nullable: false), IsRead = c.Boolean(nullable: false), }) .PrimaryKey(t => new { t.UserId, t.NotificationId }) .ForeignKey("dbo.Notifications", t => t.NotificationId) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.UserId) .Index(t => t.NotificationId); } public override void Down() { DropForeignKey("dbo.UserNotifications", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.UserNotifications", "NotificationId", "dbo.Notifications"); DropIndex("dbo.UserNotifications", new[] { "NotificationId" }); DropIndex("dbo.UserNotifications", new[] { "UserId" }); DropTable("dbo.UserNotifications"); } } }
36.083333
91
0.516551
[ "MIT" ]
HalfBlood-Prince/GigHub
GigHub/Persistence/Migrations/201806061814009_AddingUserNotificationTable.cs
1,299
C#
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. #if STRIDE_UI_SDL using System; using System.Collections.Generic; using Stride.Core.Mathematics; namespace Stride.Graphics.SDL { using System.Diagnostics; // Using is here otherwise it would conflict with the current namespace that also defines SDL. using SDL2; public static class Application { /// <summary> /// Initialize Application for handling events and available windows. /// </summary> static Application() { InternalWindows = new Dictionary<IntPtr, WeakReference<Window>>(10); } /// <summary> /// Register <paramref name="c"/> to the list of available windows. /// </summary> /// <param name="c">Window to register</param> public static void RegisterWindow(Window c) { lock (InternalWindows) { InternalWindows.Add(c.SdlHandle, new WeakReference<Window>(c)); } } /// <summary> /// Unregister <paramref name="c"/> from the list of available windows. /// </summary> /// <param name="c">Window to unregister</param> public static void UnregisterWindow(Window c) { lock (InternalWindows) { InternalWindows.Remove(c.SdlHandle); } } /// <summary> /// Window that currently has the focus. /// </summary> public static Window WindowWithFocus { get; private set; } /// <summary> /// Screen coordinate of the mouse. /// </summary> public static Point MousePosition { get { int x, y; SDL.SDL_GetGlobalMouseState(out x, out y); return new Point(x, y); } set { int err = SDL.SDL_WarpMouseGlobal(value.X, value.Y); if (err != 0) throw new NotSupportedException("Current platform doesn't let you set the position of the mouse cursor."); } } /// <summary> /// List of windows managed by the application. /// </summary> public static List<Window> Windows { get { lock (InternalWindows) { var res = new List<Window>(InternalWindows.Count); List<IntPtr> toRemove = null; foreach (var weakRef in InternalWindows) { Window ctrl; if (weakRef.Value.TryGetTarget(out ctrl)) { res.Add(ctrl); } else { // Window was reclaimed without being unregistered first. // We add it to `toRemove' to remove it from InternalWindows later. if (toRemove == null) { toRemove = new List<IntPtr>(5); } toRemove.Add(weakRef.Key); } } // Clean InternalWindows from windows that have been collected. if (toRemove != null) { foreach (var w in toRemove) { InternalWindows.Remove(w); } } return res; } } } /// <summary> /// Process all available events. /// </summary> public static void ProcessEvents() { SDL.SDL_Event e; while (SDL.SDL_PollEvent(out e) > 0) { // Handy for debugging //if (e.type == SDL.SDL_EventType.SDL_WINDOWEVENT) // Debug.WriteLine(e.window.windowEvent); Application.ProcessEvent(e); } } /// <summary> /// Process a single event and dispatch it to the right window. /// </summary> public static void ProcessEvent(SDL.SDL_Event e) { Window ctrl = null; // Code below is to extract the associated `Window' instance and to find out the window // with focus. In the future, we could even add events handled at the application level. switch (e.type) { case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN: case SDL.SDL_EventType.SDL_MOUSEBUTTONUP: ctrl = WindowFromSdlHandle(SDL.SDL_GetWindowFromID(e.button.windowID)); break; case SDL.SDL_EventType.SDL_MOUSEMOTION: ctrl = WindowFromSdlHandle(SDL.SDL_GetWindowFromID(e.motion.windowID)); break; case SDL.SDL_EventType.SDL_MOUSEWHEEL: ctrl = WindowFromSdlHandle(SDL.SDL_GetWindowFromID(e.wheel.windowID)); break; case SDL.SDL_EventType.SDL_KEYDOWN: case SDL.SDL_EventType.SDL_KEYUP: ctrl = WindowFromSdlHandle(SDL.SDL_GetWindowFromID(e.key.windowID)); break; case SDL.SDL_EventType.SDL_TEXTEDITING: ctrl = WindowFromSdlHandle(SDL.SDL_GetWindowFromID(e.edit.windowID)); break; case SDL.SDL_EventType.SDL_TEXTINPUT: ctrl = WindowFromSdlHandle(SDL.SDL_GetWindowFromID(e.text.windowID)); break; case SDL.SDL_EventType.SDL_FINGERMOTION: case SDL.SDL_EventType.SDL_FINGERDOWN: case SDL.SDL_EventType.SDL_FINGERUP: ctrl = WindowWithFocus; break; case SDL.SDL_EventType.SDL_WINDOWEVENT: { ctrl = WindowFromSdlHandle(SDL.SDL_GetWindowFromID(e.window.windowID)); switch (e.window.windowEvent) { case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_GAINED: WindowWithFocus = ctrl; break; case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_LOST: WindowWithFocus = null; break; } break; } case SDL.SDL_EventType.SDL_JOYDEVICEADDED: case SDL.SDL_EventType.SDL_JOYDEVICEREMOVED: // Send these events to all the windows Windows.ForEach(x => x.ProcessEvent(e)); break; } ctrl?.ProcessEvent(e); } /// <summary> /// Given a SDL Handle of a SDL window, retrieve the corresponding managed object. If object /// was already garbage collected, we will also clean up <see cref="InternalWindows"/>. /// </summary> /// <param name="w">SDL Handle of the window we are looking for</param> /// <returns></returns> private static Window WindowFromSdlHandle(IntPtr w) { lock (InternalWindows) { WeakReference<Window> weakRef; if (InternalWindows.TryGetValue(w, out weakRef)) { Window ctrl; if (weakRef.TryGetTarget(out ctrl)) { return ctrl; } else { // Window does not exist anymore in our code. Clean `InternalWindows'. InternalWindows.Remove(w); return null; } } else { return null; } } } /// <summary> /// Backup storage for windows of current application. /// </summary> private static readonly Dictionary<IntPtr, WeakReference<Window>> InternalWindows; } } #endif
36.206751
126
0.483394
[ "MIT" ]
Aggror/Stride
sources/engine/Stride.Graphics/SDL/Application.cs
8,581
C#
#region License // Copyright (c) 2014 The Sentry Team and individual contributors. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // 3. Neither the name of the Sentry 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. #endregion namespace SharpRaven.Logging { /// <summary> /// Interface for plugging into RavenClient to provide methods to filter logs. /// </summary> public interface IScrubber { /// <summary> /// The main interface for scrubbing a JSON packet, /// called before compression (if enabled) /// </summary> /// <param name="input">The serialized JSON packet is given here.</param> /// <returns>Scrubbed JSON packet.</returns> string Scrub(string input); } }
48.347826
101
0.706385
[ "BSD-3-Clause" ]
SPARTAN563/raven-csharp
src/app/SharpRaven/Logging/IScrubber.cs
2,226
C#
using Liversage.Primitives; using System; using System.Text.Json.Serialization; namespace SystemTextJson { [Primitive] [JsonConverter(typeof(TimestampConverter))] public readonly partial struct Timestamp { readonly DateTimeOffset timestamp; public static Timestamp Now => DateTimeOffset.Now; public static Timestamp UtcNow => DateTimeOffset.UtcNow; public Timestamp ToLocalTime() => timestamp.ToLocalTime(); public Timestamp ToUniversalTime() => timestamp.ToUniversalTime(); } }
25.904762
74
0.71875
[ "MIT" ]
Liversage/Primitives
Samples/SystemTextJson/Timestamp.cs
546
C#
using System; using EventStoreBasics.Tests.Tools; using FluentAssertions; using Npgsql; using Xunit; namespace EventStoreBasics.Tests { public class Exercise05StreamAggregation { class User { public Guid Id { get; private set; } public string Name { get; private set; } public long Version { get; private set; } public User(Guid id, string name) { Id = id; Name = name; } // For deserialization private User() { } private void Apply(UserCreated @event) { Id = @event.UserId; Name = @event.UserName; } private void Apply(UserNameUpdated @event) { Name = @event.UserName; } } class UserCreated { public Guid UserId { get; } public string UserName { get; } public UserCreated(Guid userId, string userName) { UserId = userId; UserName = userName; } } class UserNameUpdated { public Guid UserId { get; } public string UserName { get; } public UserNameUpdated(Guid userId, string userName) { UserId = userId; UserName = userName; } } private readonly NpgsqlConnection databaseConnection; private readonly EventStore eventStore; /// <summary> /// Inits Event Store /// </summary> public Exercise05StreamAggregation() { databaseConnection = PostgresDbConnectionProvider.GetFreshDbConnection(); // Create Event Store eventStore = new EventStore(databaseConnection); // Initialize Event Store eventStore.Init(); } [Fact] public void AggregateStream_ShouldReturnObjectWithStateBasedOnEvents() { var streamId = Guid.NewGuid(); var userCreated = new UserCreated(streamId, "John Doe"); var userNameUpdated = new UserNameUpdated(streamId, "Adam Smith"); eventStore.AppendEvent<User>(streamId, userCreated); eventStore.AppendEvent<User>(streamId, userNameUpdated); var aggregate = eventStore.AggregateStream<User>(streamId); aggregate.Id.Should().Be(streamId); aggregate.Name.Should().Be(userNameUpdated.UserName); aggregate.Version.Should().Be(2); } } }
27.636364
86
0.517909
[ "MIT" ]
WaleedMKasem/EventSourcing.NetCore
Workshop/01-EventStoreBasics/EventStoreBasics.Tests/Exercise05StreamAggregation.cs
2,736
C#
namespace Atc.Rest.Tests.Extensions; public class ApplicationInsightsExtensionsTests { [Fact] public void GetApiName() { // Arrange var serviceCollection = new ServiceCollection(); // Act var actual = serviceCollection.AddCallingIdentityTelemetryInitializer(); // Assert Assert.NotNull(actual); Assert.True(actual.Count == 2); } }
22.5
80
0.644444
[ "MIT" ]
atc-net/atc-common
test/Atc.Rest.Tests/Extensions/ApplicationInsightsExtensionsTests.cs
405
C#
using BuildingBlocks.Web; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; namespace Reservation.Reservations.Features.CreateReservation; [Route(BaseApiPath + "/reservation")] public class CreateReservationEndpoint : BaseController { [HttpPost] [Authorize] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [SwaggerOperation(Summary = "Create new Reservation", Description = "Create new Reservation")] public async Task<ActionResult> CreateReservation([FromBody] CreateReservationCommand command, CancellationToken cancellationToken) { var result = await Mediator.Send(command, cancellationToken); return Ok(result); } }
33.56
98
0.779499
[ "MIT" ]
xpertdev/Airline-Microservices
src/Services/Airline.Reservation/src/Reservation/Reservations/Features/CreateReservation/CreateReservationEndpoint.cs
839
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Dingtalkrobot_1_0.Models { public class BatchRecallGroupRequest : TeaModel { /// <summary> /// 机器人的robotCode /// </summary> [NameInMap("chatbotId")] [Validation(Required=false)] public string ChatbotId { get; set; } /// <summary> /// 开放的群id /// </summary> [NameInMap("openConversationId")] [Validation(Required=false)] public string OpenConversationId { get; set; } /// <summary> /// 消息id /// </summary> [NameInMap("processQueryKeys")] [Validation(Required=false)] public List<string> ProcessQueryKeys { get; set; } } }
23.25
58
0.590203
[ "Apache-2.0" ]
aliyun/dingtalk-sdk
dingtalk/csharp/core/robot_1_0/Models/BatchRecallGroupRequest.cs
857
C#
using System; using System.Collections.Generic; namespace DotNetReleaser.Changelog; public class ChangelogCollection { public ChangelogCollection() { Version = ChangelogVersionModel.Empty; PreviousVersion = ChangelogVersionModel.Empty; CompareUrl = string.Empty; CommitChanges = new List<ChangelogCommitChangeModel>(); PullRequestChanges = new List<ChangelogPullRequestChangeModel>(); } public ChangelogVersionModel Version { get; set; } public ChangelogVersionModel PreviousVersion { get; set; } public string CompareUrl { get; set; } public List<ChangelogCommitChangeModel> CommitChanges { get; } public List<ChangelogPullRequestChangeModel> PullRequestChanges { get; } public void AddCommitChange(string title, string body, string author, string sha) { CommitChanges.Add(new ChangelogCommitChangeModel(title, body, author, sha)); } public void AddPullRequestChange(int prNumber, string branch, string title, string body, string author, string[] labels, string[] files) { PullRequestChanges.Add(new ChangelogPullRequestChangeModel(prNumber, branch, title, body, author, labels, files)); } }
34.055556
140
0.724307
[ "BSD-2-Clause" ]
xoofx/dotnet-releaser
src/dotnet-releaser/Changelog/ChangelogCollection.cs
1,228
C#
using System; using System.Runtime.InteropServices; namespace Swift.Interop { //https://github.com/apple/swift/blob/852585e491e929d1d0da115f92626dd5aa1f871b/include/swift/Reflection/Records.h#L126 public enum FieldDescriptorKind : short { // Swift nominal types. Struct, Class, Enum, // Fixed-size multi-payload enums have a special descriptor format that // encodes spare bits. // // FIXME: Actually implement this. For now, a descriptor with this kind // just means we also have a builtin descriptor from which we get the // size and alignment. MultiPayloadEnum, // A Swift opaque protocol. There are no fields, just a record for the // type itself. Protocol, // A Swift class-bound protocol. ClassProtocol, // An Objective-C protocol, which may be imported or defined in Swift. ObjCProtocol, // An Objective-C class, which may be imported or defined in Swift. // In the former case, field type metadata is not emitted, and // must be obtained from the Objective-C runtime. ObjCClass }; [StructLayout (LayoutKind.Sequential)] public unsafe ref struct FieldDescriptor { internal RelativePointer MangledTypeNamePtr; internal RelativePointer SuperclassPtr; public FieldDescriptorKind Kind; public ushort FieldRecordSize; public uint NumFields; // Vector of NumFields FieldRecords follows... // maybe don't expose this.. a lot of the time it's a symbolic ref //public string MangledTypeName => Marshal.PtrToStringAnsi ((IntPtr)MangledTypeNamePtr.Target); } [Flags] public enum FieldRecordFlags { // Is this an indirect enum case? IsIndirectCase = 0x1, // Is this a mutable `var` property? IsVar = 0x2, } [StructLayout (LayoutKind.Sequential)] public unsafe ref struct FieldRecord { public FieldRecordFlags Flags; internal RelativePointer MangledTypeNamePtr; internal RelativePointer FieldNamePtr; public string FieldName => Marshal.PtrToStringAnsi ((IntPtr)FieldNamePtr.Target); } }
27.232877
119
0.748491
[ "MIT" ]
CartBlanche/Xamarin.SwiftUI
src/SwiftUI/Swift/Interop/FieldDescriptor.cs
1,990
C#
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using UnityEngine.Serialization; using System.Collections; namespace Fungus { /// <summary> /// Rotates a game object to the specified angles over time. /// </summary> [CommandInfo("iTween", "[Dep]Rotate To", "Rotates a game object to the specified angles over time.")] [AddComponentMenu("")] [ExecuteInEditMode] public class RotateTo : iTweenCommand { [Tooltip("Target transform that the GameObject will rotate to")] [SerializeField] protected TransformData _toTransform; [Tooltip("Target rotation that the GameObject will rotate to, if no To Transform is set")] [SerializeField] protected Vector3Data _toRotation; [Tooltip("Whether to animate in world space or relative to the parent. False by default.")] [SerializeField] protected bool isLocal; #region Public members public override void DoTween() { Hashtable tweenParams = new Hashtable(); tweenParams.Add("name", _tweenName.Value); if (_toTransform.Value == null) { tweenParams.Add("rotation", _toRotation.Value); } else { tweenParams.Add("rotation", _toTransform.Value); } tweenParams.Add("time", _duration.Value); tweenParams.Add("easetype", easeType); tweenParams.Add("looptype", loopType); tweenParams.Add("isLocal", isLocal); tweenParams.Add("oncomplete", "OniTweenComplete"); tweenParams.Add("oncompletetarget", gameObject); tweenParams.Add("oncompleteparams", this); iTween.RotateTo(_targetObject.Value, tweenParams); } #endregion #region Backwards compatibility [HideInInspector] [FormerlySerializedAs("toTransform")] public Transform toTransformOLD; [HideInInspector] [FormerlySerializedAs("toRotation")] public Vector3 toRotationOLD; protected override void OnEnable() { base.OnEnable(); if (toTransformOLD != null) { _toTransform.Value = toTransformOLD; toTransformOLD = null; } if (toRotationOLD != default(Vector3)) { _toRotation.Value = toRotationOLD; toRotationOLD = default(Vector3); } } #endregion } }
34.658228
125
0.607012
[ "MIT" ]
stevehalliwell/fungus
Assets/Fungus/Thirdparty/iTween/Commands/RotateTo.cs
2,738
C#
using System.Threading.Tasks; using AppInsights.EnterpriseTelemetry; using Microsoft.AspNetCore.Http; using Microsoft.FeatureManagement; using Microsoft.Extensions.Configuration; using Microsoft.FeatureFlighting.Core.Spec; using static Microsoft.FeatureFlighting.Common.Constants; namespace Microsoft.FeatureFlighting.Core.FeatureFilters { [FilterAlias(FilterKeys.Region)] public class RegionFilter: BaseFilter, IFeatureFilter { protected override string FilterType => FilterKeys.Region; public RegionFilter(IConfiguration configuration, IHttpContextAccessor httpContextAccessor, ILogger logger, IOperatorStrategy evaluatorStrategy) : base(configuration, httpContextAccessor, logger, evaluatorStrategy) { } public Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context) { return EvaluateFlightingContextAsync(context, FlightingContextParams.Region); } } }
36.384615
222
0.786469
[ "MIT" ]
microsoft/FeatureFlightingManagement
src/service/Domain/FeatureFilters/RegionFilter.cs
948
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using StardewValley; using StardewValley.Characters; namespace StardustCore.Utilities { public class JunimoAdvanceMoveData { public string junimoActorID; public int maxFrames; public int tickSpeed; public bool loop; public List<Point> points; private int currentIndex; private int currentFrameAmount; private bool finished; public JunimoAdvanceMoveData() { } public JunimoAdvanceMoveData(string Actor, List<Point> Points, int FramesToPoint, int tickSpeed = 1,bool Loop=false) { this.junimoActorID = Actor; this.points = Points; this.maxFrames = FramesToPoint; this.tickSpeed = tickSpeed; this.currentFrameAmount = 0; this.currentIndex = 0; this.loop = Loop; } public void update() { if (Game1.CurrentEvent == null) return; else { if (this.finished) return; Junimo junimo=(Junimo)Game1.CurrentEvent.actors.Find(i => i.Name.Equals(this.junimoActorID)); if (junimo == null) return; Point nextPoint = this.getNextPoint(); if (this.finished) return; if (nextPoint.X > this.getCurrentPoint().X) { junimo.flip = false; //junimo.Sprite.Animate(Game1.currentGameTime, 0, 8, 50f); if (junimo.Sprite.CurrentAnimation==null) { junimo.Sprite.Animate(Game1.currentGameTime, 16, 8, 50f); } } if (nextPoint.X < this.getCurrentPoint().X) { junimo.flip = true; //junimo.Sprite.Animate(Game1.currentGameTime, 0, 8, 50f); if (junimo.Sprite.CurrentAnimation== null) { junimo.Sprite.Animate(Game1.currentGameTime, 16, 8, 50f); } } if (nextPoint.Y < this.getCurrentPoint().Y) { junimo.flip = false; //junimo.Sprite.Animate(Game1.currentGameTime, 0, 8, 50f); if (junimo.Sprite.CurrentAnimation == null) { junimo.Sprite.Animate(Game1.currentGameTime, 32, 8, 50f); } } if(nextPoint.Y > this.getCurrentPoint().Y) { junimo.flip = false; if (junimo.Sprite.CurrentAnimation==null) { junimo.Sprite.Animate(Game1.currentGameTime, 0, 8, 50f); } } junimo.Position= Vector2.Lerp(new Vector2(this.getCurrentPoint().X,this.getCurrentPoint().Y),new Vector2(nextPoint.X,nextPoint.Y),(float)((float)this.currentFrameAmount/(float)this.maxFrames)); ++this.currentFrameAmount; if (this.currentFrameAmount >= this.maxFrames) { this.currentFrameAmount = 0; this.currentIndex++; junimo.Sprite.StopAnimation(); if (this.currentIndex >= this.points.Count) { if (this.loop == false) { this.finished = true; } else { this.currentIndex = 0; } } } } } Point getNextPoint() { if (this.currentIndex+1 >= this.points.Count) { if (this.loop == false) { this.finished=true; return new Point(0, 0); } return this.points[0]; } else { return this.points[this.currentIndex+1]; } } Point getCurrentPoint() { if (this.currentIndex >= this.points.Count) { return this.points[0]; } else { return this.points[this.currentIndex]; } } } }
30.335526
209
0.45977
[ "MIT" ]
JitterDev/Stardew_Valley_Mods
GeneralMods/StardustCore/Utilities/JunimoAdvanceMoveData.cs
4,611
C#
using System; using System.Threading.Tasks; using Jasper.Messaging.Sagas; using Shouldly; using Xunit; namespace IntegrationTests.Persistence.Marten.Persistence.Sagas { public class GuidBasicWorkflow : BasicWorkflow<GuidWorkflowState, GuidStart, GuidCompleteThree, Guid> { public GuidWorkflowState Starts(WildcardStart start) { var sagaId = Guid.Parse(start.Id); return new GuidWorkflowState { Id = sagaId, Name = start.Name }; } public void Handles(GuidDoThree message, GuidWorkflowState state) { state.ThreeCompleted = true; } } public class GuidDoThree { [SagaIdentity] public Guid TheSagaId { get; set; } } public class basic_mechanics_with_guid : SagaTestHarness<GuidBasicWorkflow, GuidWorkflowState> { private readonly Guid stateId = Guid.NewGuid(); [Fact] public async Task complete() { await send(new GuidStart { Id = stateId, Name = "Croaker" }); await send(new FinishItAll(), stateId); (await LoadState(stateId)).ShouldBeNull(); } [Fact] public async Task handle_a_saga_message_with_cascading_messages_passes_along_the_saga_id_in_header() { await send(new GuidStart { Id = stateId, Name = "Croaker" }); await send(new CompleteOne(), stateId); var state = await LoadState(stateId); state.OneCompleted.ShouldBeTrue(); state.TwoCompleted.ShouldBeTrue(); } [Fact] public async Task start_1() { await send(new GuidStart { Id = stateId, Name = "Croaker" }); var state = await LoadState(stateId); state.ShouldNotBeNull(); state.Name.ShouldBe("Croaker"); } [Fact] public async Task start_2() { var code = codeFor<WildcardStart>(); //throw new Exception(code); await send(new WildcardStart { Id = stateId.ToString(), Name = "One Eye" }); var state = await LoadState(stateId); state.ShouldNotBeNull(); state.Name.ShouldBe("One Eye"); } [Fact] public async Task straight_up_update_with_the_saga_id_on_the_message() { await send(new GuidStart { Id = stateId, Name = "Croaker" }); var message = new GuidCompleteThree { SagaId = stateId }; await send(message); var state = await LoadState(stateId); state.ThreeCompleted.ShouldBeTrue(); } [Fact] public async Task update_expecting_the_saga_id_to_be_on_the_envelope() { await send(new GuidStart { Id = stateId, Name = "Croaker" }); await send(new CompleteFour(), stateId); var state = await LoadState(stateId); state.FourCompleted.ShouldBeTrue(); } [Fact] public async Task update_with_message_that_uses_saga_identity_attributed_property() { await send(new GuidStart { Id = stateId, Name = "Croaker" }); var message = new GuidDoThree { TheSagaId = stateId }; await send(message); var state = await LoadState(stateId); state.ThreeCompleted.ShouldBeTrue(); } } }
25.2
108
0.513057
[ "MIT" ]
SVemulapalli/jasper
src/IntegrationTests/Persistence/Marten/Persistence/Sagas/basic_mechanics_with_guid.cs
3,908
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("SpiderManCommon")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SpiderManCommon")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("6572ab5a-f733-49fe-929e-0fe043aaafac")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.702703
56
0.716088
[ "MIT" ]
daohunliwei/spider-csharp
SpiderMan/SpiderManCommon/Properties/AssemblyInfo.cs
1,302
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TransactSqlAnalyzer.Gui.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.774194
151
0.585343
[ "MIT" ]
ifbeginend/TransactSqlAnalyzer
Source/TransactSqlAnalyzer.Gui/Properties/Settings.Designer.cs
1,080
C#
using System.Collections.Generic; namespace Greg.Xrm.EnvironmentSolutionsComparer.Views.Solutions.ComponentResolution { public interface IResolver { void Resolve(SolutionComponentGrid grid, IReadOnlyCollection<ConnectionModel> connections); } }
25.2
93
0.837302
[ "MIT" ]
neronotte/Greg.Xrm
src/Greg.Xrm.EnvironmentSolutionsComparer/Views/Solutions/ComponentResolution/IResolver.cs
254
C#
namespace CadAlunos { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.Edit = new System.Windows.Forms.DataGridViewButtonColumn(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // button1 // this.button1.BackColor = System.Drawing.Color.Transparent; this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.ForeColor = System.Drawing.Color.White; this.button1.Location = new System.Drawing.Point(49, 47); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(228, 117); this.button1.TabIndex = 0; this.button1.Text = "Cadastrar Aluno"; this.button1.UseVisualStyleBackColor = false; this.button1.Click += new System.EventHandler(this.Button1_Click); // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToOrderColumns = true; this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.ActiveCaptionText; this.dataGridView1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.dataGridView1.ColumnHeadersHeight = 29; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.Edit}); this.dataGridView1.GridColor = System.Drawing.SystemColors.ButtonFace; this.dataGridView1.Location = new System.Drawing.Point(410, 343); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowHeadersWidth = 51; this.dataGridView1.RowTemplate.Height = 24; this.dataGridView1.Size = new System.Drawing.Size(432, 223); this.dataGridView1.TabIndex = 1; // // Edit // this.Edit.HeaderText = "Edit"; this.Edit.MinimumWidth = 6; this.Edit.Name = "Edit"; this.Edit.Width = 125; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = global::CadAlunos.Properties.Resources.banco_imagens_gratis; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(854, 578); this.Controls.Add(this.dataGridView1); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Form1"; ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.DataGridViewButtonColumn Edit; } }
42.919192
167
0.604613
[ "MIT" ]
brunovolz/WindowsForms
CadAlunos/Form1.Designer.cs
4,251
C#
using System; using System.Collections.Generic; using System.Text; /////////////////////////////////// // JHUNELL BARCENAS // /////////////////////////////////// namespace GDC.PH.AIDE.BusinessLayer { public class clsWorkplaceAudit : BusinessObjectBase { #region InnerClass public enum clsWorkplaceAuditFields { AUDIT_DAILY_ID, AUDIT_QUESTIONS_ID, EMP_ID, FY_WEEK, STATUS, DT_CHECKED, AUDIT_QUESTIONS, OWNER, AUDIT_QUESTIONS_GROUP } #endregion #region Data Members int _auditDailyID; int _auditQuestionsID; int _empID; int _fyWeek; int _status; DateTime _dtChecked; string _auditQuestions; string _owner; string _auditQuestionsGroup; #endregion #region Properties public int AUDIT_DAILY_ID { get { return _auditDailyID; } set { if (_auditDailyID != value) { _auditDailyID = value; PropertyHasChanged("AUDIT_DAILY_ID"); } } } public int AUDIT_QUESTIONS_ID { get { return _auditQuestionsID; } set { if (_auditQuestionsID != value) { _auditQuestionsID = value; PropertyHasChanged("AUDIT_QUESTIONS_ID"); } } } public int EMP_ID { get { return _empID; } set { if (_empID != value) { _empID = value; PropertyHasChanged("EMP_ID"); } } } public int FY_WEEK { get { return _fyWeek; } set { if (_fyWeek != value) { _fyWeek = value; PropertyHasChanged("FY_WEEK"); } } } public int STATUS { get { return _status; } set { if (_status != value) { _status = value; PropertyHasChanged("STATUS"); } } } public DateTime DT_CHECKED { get { return _dtChecked; } set { if (_dtChecked != value) { _dtChecked = value; PropertyHasChanged("DT_CHECKED"); } } } public String AUDIT_QUESTIONS { get { return _auditQuestions; } set { if (_auditQuestions != value) { _auditQuestions = value; PropertyHasChanged("AUDIT_QUESTIONS"); } } } public String OWNER { get { return _owner; } set { if (_owner != value) { _owner = value; PropertyHasChanged("OWNER"); } } } public String AUDIT_QUESTIONS_GROUP { get { return _auditQuestionsGroup; } set { if (_auditQuestionsGroup != value) { _auditQuestionsGroup = value; PropertyHasChanged("AUDIT_QUESTIONS_GROUP"); } } } #endregion #region Validation internal override void AddValidationRules() { ValidationRules.AddRules(new Validation.ValidateRuleNotNull("AUDIT_DAILY_ID", "AUDIT_DAILY_ID")); ValidationRules.AddRules(new Validation.ValidateRuleNotNull("AUDIT_QUESTIONS_ID", "AUDIT_QUESTIONS_ID")); ValidationRules.AddRules(new Validation.ValidateRuleNotNull("EMP_ID", "EMP_ID")); ValidationRules.AddRules(new Validation.ValidateRuleNotNull("FY_WEEK", "FY_WEEK")); ValidationRules.AddRules(new Validation.ValidateRuleNotNull("STATUS", "STATUS")); ValidationRules.AddRules(new Validation.ValidateRuleNotNull("DT_CHECKED", "DT_CHECKED")); ValidationRules.AddRules(new Validation.ValidateRuleNotNull("AUDIT_QUESTIONS", "AUDIT_QUESTIONS")); ValidationRules.AddRules(new Validation.ValidateRuleNotNull("OWNER", "OWNER")); ValidationRules.AddRules(new Validation.ValidateRuleNotNull("AUDIT_QUESTIONS_GROUP", "AUDIT_QUESTIONS_GROUP")); } #endregion } } /////////////////////////////////// // JHUNELL BARCENAS // ///////////////////////////////////
26.945652
123
0.455224
[ "BSD-3-Clause" ]
chriscg/aide-backend
AIDEBackendMaster/GDC.PH.AIDE.BusinessLayer/clsWorkplaceAudit.cs
4,958
C#
using System; using System.Diagnostics; using System.Linq; using Get_Interfaces.Utils; namespace Get_Interfaces { internal static class Program { #region Fields private static readonly string[] Modules = {"client.dll", "engine2.dll", "vstdlib.dll", "vgui2.dll", "gameui2.dll", "vguirendersurface.dll"}; #endregion #region Static Methods private static void Main(string[] args) { Process processApp = Process.GetProcesses().FirstOrDefault(x => x.ProcessName == "dota2"); if (processApp != default(Process)) foreach (string module in Modules) { Console.WriteLine($"----------------------------"); Console.WriteLine($"-----Module {module}-----"); Console.WriteLine($"----------------------------"); Interface.GetInterface(processApp, module); } Console.WriteLine($"Press key to exit console."); Console.ReadLine(); } #endregion } }
28.973684
110
0.520436
[ "MIT" ]
Vacko/Source-Engine-2-Interfaces
Source-Engine-2-Interfaces/Program.cs
1,103
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using lm.Comol.Core.DomainModel; namespace lm.Comol.Modules.Standard.Menu { [Serializable] public class ModuleMenu { public const String UniqueCode = "SRVmenu"; public virtual Boolean ManagePortalMenubar {get;set;} public virtual Boolean ManageAdministrationMenubar { get; set; } public virtual Boolean ManageCommunitiesMenubar { get; set; } public virtual Boolean SetActivePortalMenubar { get; set; } public virtual Boolean SetActiveAdministrationMenubar { get; set; } public virtual Boolean SetActiveCommunitiesMenubar { get; set; } public ModuleMenu() { } public static ModuleMenu CreatePortalmodule(int UserTypeID) { ModuleMenu module = new ModuleMenu(); module.ManagePortalMenubar = (UserTypeID == (int)UserTypeStandard.SysAdmin || UserTypeID == (int)UserTypeStandard.Administrator || UserTypeID == (int)UserTypeStandard.Administrative ); module.ManageAdministrationMenubar = (UserTypeID == (int)UserTypeStandard.SysAdmin || UserTypeID == (int)UserTypeStandard.Administrator); module.ManageCommunitiesMenubar = (UserTypeID == (int)UserTypeStandard.SysAdmin || UserTypeID == (int)UserTypeStandard.Administrator || UserTypeID == (int)UserTypeStandard.Administrative); module.SetActivePortalMenubar = (UserTypeID == (int)UserTypeStandard.SysAdmin || UserTypeID == (int)UserTypeStandard.Administrator); module.SetActiveAdministrationMenubar = (UserTypeID == (int)UserTypeStandard.SysAdmin || UserTypeID == (int)UserTypeStandard.Administrator); module.SetActiveCommunitiesMenubar = (UserTypeID == (int)UserTypeStandard.SysAdmin || UserTypeID == (int)UserTypeStandard.Administrator || UserTypeID == (int)UserTypeStandard.Administrative); return module; } public ModuleMenu(long permission) { //AddPersonal = PermissionHelper.CheckPermissionSoft((long)Base2Permission.AddPersonal, permission); //AddSubmission = PermissionHelper.CheckPermissionSoft((long)Base2Permission.AddSubmission, permission); //CreateCallForPaper = PermissionHelper.CheckPermissionSoft((long)Base2Permission.AddCall, permission); //EditCallForPaper = PermissionHelper.CheckPermissionSoft((long)Base2Permission.EditCall, permission); //Administration = PermissionHelper.CheckPermissionSoft((long)Base2Permission.Admin, permission); //ManageCallForPapers = PermissionHelper.CheckPermissionSoft((long)Base2Permission.ManageCalls, permission); //DeleteOwnCallForPaper = PermissionHelper.CheckPermissionSoft((long)Base2Permission.DeleteCall, permission); } [Flags,Serializable] public enum Base2Permission{ View = 1, Manage = 2 , Edit = 4, Delete = 8, AddPersonal = 16 } [Serializable] public enum ActionType{ //None = 87000, //NoPermission = 87001, //GenericError = 87002, //AddSticky = 87003, //EditSticky = 87004, //VirtualDeleteSticky = 87005, //VirtualUndeleteSticky = 87006, //DeleteSticky = 87007, //HideSticky = 87008, //ShowSticky = 87009, //AddStickyToUser = 87010, //AddStickyToCommunity = 87011, //AddStickyFromService = 87012 } [Serializable] public enum ObjectType{ None = 0, MenuBar = 1, TopMenuItem = 2, ColumnItem = 3, MenuItem = 4 } } }
45.166667
203
0.654718
[ "MIT" ]
EdutechSRL/Adevico
3-Business/3-Modules/lm.Comol.Modules.Standard/Menu/Domain/ModuleMenu.cs
3,796
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 System.Diagnostics; using System.IO; using System.Threading.Tasks; using NuGet.Configuration; using NuGet.Protocol.Core.Types; using NuGet.Test.Utility; using Xunit; namespace NuGet.Commands.Test { public class RequestFactoryTests { [Fact] public void RequestFactory_RestorePackagesArgRelativeToCwd() { // If a packages argument is provided, GetEffectiveGlobalPackagesFolder() should ignore // the provided root path and any configuration information and resolve relative to the // current working directory. // Arrange var globalPackagesFolder = "MyPackages"; var restoreArgs = new RestoreArgs() { GlobalPackagesFolder = globalPackagesFolder }; // Act var resolvedGlobalPackagesFolder = restoreArgs.GetEffectiveGlobalPackagesFolder("C:\\Dummy", null); // Assert var expectedResolvedGlobalPackagesFolder = Path.GetFullPath(globalPackagesFolder); Assert.Equal(expectedResolvedGlobalPackagesFolder, resolvedGlobalPackagesFolder); } [Fact] public async Task RequestFactory_ReadDGSpec() { // Arrange var cache = new RestoreCommandProvidersCache(); var provider = new DependencyGraphFileRequestProvider(cache); using (var workingDir = TestDirectory.Create()) { var dgSpec = Path.Combine(workingDir, "project.dg"); Directory.CreateDirectory(Path.GetDirectoryName(dgSpec)); File.WriteAllText(dgSpec, DGSpec); var context = new RestoreArgs(); using (var cacheContext = new SourceCacheContext()) { context.CacheContext = cacheContext; context.Log = new TestLogger(); // Act var supports = await provider.Supports(dgSpec); Assert.Equal(true, supports); var requests = await provider.CreateRequests(dgSpec, context); Assert.Equal(1, requests.Count); } } } private static string DGSpec = @" { ""format"": 1, ""restore"": { ""C:\\Users\\ConsoleApp1\\ConsoleApp1.csproj"": {} }, ""projects"": { ""C:\\Users\\ConsoleApp1\\ConsoleApp1.csproj"": { ""version"": ""1.0.0"", ""restore"": { ""projectUniqueName"": ""C:\\Users\\ConsoleApp1\\ConsoleApp1.csproj"", ""projectName"": ""ConsoleApp1"", ""projectPath"": ""C:\\Users\\ConsoleApp1\\ConsoleApp1.csproj"", ""packagesPath"": ""C:\\Users\\.nuget\\packages\\"", ""outputPath"": ""C:\\Users\\Documents\\Visual Studio 2017\\Projects\\ConsoleApp7\\ConsoleApp1\\obj\\"", ""projectStyle"": ""PackageReference"", ""configFilePaths"": [ ], ""fallbackFolders"": [ ""C:\\Users\\.dotnet\\NuGetFallbackFolder"" ], ""originalTargetFrameworks"": [ ""netcoreapp1.1"" ], ""sources"": { ""https://api.nuget.org/v3/index.json"": {}, ""C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\"": {} }, ""frameworks"": { ""netcoreapp1.1"": { ""projectReferences"": {} } } }, ""frameworks"": { ""netcoreapp1.1"": { ""dependencies"": { ""Microsoft.NETCore.App"": { ""target"": ""Package"", ""version"": ""1.1.1"" }, ""jQuery"": { ""target"": ""Package"", ""version"": ""3.1.1"" } } } } } } }"; } }
32.508197
112
0.544377
[ "Apache-2.0" ]
0xced/NuGet.Client
test/NuGet.Core.Tests/NuGet.Commands.Test/RequestFactoryTests.cs
3,966
C#
using System; using System.Collections.Generic; using Android.Runtime; using Java.Interop; namespace Com.Payment.Paymentsdk.Sharedclasses.Model.Request { // Metadata.xml XPath class reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']" [global::Android.Runtime.Register ("com/payment/paymentsdk/sharedclasses/model/request/CardDetails", DoNotGenerateAcw=true)] public sealed partial class CardDetails : global::Java.Lang.Object { static readonly JniPeerMembers _members = new XAPeerMembers ("com/payment/paymentsdk/sharedclasses/model/request/CardDetails", typeof (CardDetails)); internal static IntPtr class_ref { get { return _members.JniPeerType.PeerReference.Handle; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] protected override IntPtr ThresholdClass { get { return _members.JniPeerType.PeerReference.Handle; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } internal CardDetails (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) { } // Metadata.xml XPath constructor reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']/constructor[@name='CardDetails' and count(parameter)=4 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.Integer'] and parameter[3][@type='java.lang.Integer'] and parameter[4][@type='java.lang.String']]" [Register (".ctor", "(Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/String;)V", "")] public unsafe CardDetails (string cvv, global::Java.Lang.Integer expiryMonth, global::Java.Lang.Integer expiryYear, string pan) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/String;)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_cvv = JNIEnv.NewString (cvv); IntPtr native_pan = JNIEnv.NewString (pan); try { JniArgumentValue* __args = stackalloc JniArgumentValue [4]; __args [0] = new JniArgumentValue (native_cvv); __args [1] = new JniArgumentValue ((expiryMonth == null) ? IntPtr.Zero : ((global::Java.Lang.Object) expiryMonth).Handle); __args [2] = new JniArgumentValue ((expiryYear == null) ? IntPtr.Zero : ((global::Java.Lang.Object) expiryYear).Handle); __args [3] = new JniArgumentValue (native_pan); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { JNIEnv.DeleteLocalRef (native_cvv); JNIEnv.DeleteLocalRef (native_pan); global::System.GC.KeepAlive (expiryMonth); global::System.GC.KeepAlive (expiryYear); } } public unsafe string Cvv { // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']/method[@name='getCvv' and count(parameter)=0]" [Register ("getCvv", "()Ljava/lang/String;", "")] get { const string __id = "getCvv.()Ljava/lang/String;"; try { var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null); return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } } public unsafe global::Java.Lang.Integer ExpiryMonth { // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']/method[@name='getExpiryMonth' and count(parameter)=0]" [Register ("getExpiryMonth", "()Ljava/lang/Integer;", "")] get { const string __id = "getExpiryMonth.()Ljava/lang/Integer;"; try { var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null); return global::Java.Lang.Object.GetObject<global::Java.Lang.Integer> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } } public unsafe global::Java.Lang.Integer ExpiryYear { // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']/method[@name='getExpiryYear' and count(parameter)=0]" [Register ("getExpiryYear", "()Ljava/lang/Integer;", "")] get { const string __id = "getExpiryYear.()Ljava/lang/Integer;"; try { var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null); return global::Java.Lang.Object.GetObject<global::Java.Lang.Integer> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } } public unsafe string Pan { // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']/method[@name='getPan' and count(parameter)=0]" [Register ("getPan", "()Ljava/lang/String;", "")] get { const string __id = "getPan.()Ljava/lang/String;"; try { var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null); return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } } // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']/method[@name='component1' and count(parameter)=0]" [Register ("component1", "()Ljava/lang/String;", "")] public unsafe string Component1 () { const string __id = "component1.()Ljava/lang/String;"; try { var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null); return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']/method[@name='component2' and count(parameter)=0]" [Register ("component2", "()Ljava/lang/Integer;", "")] public unsafe global::Java.Lang.Integer Component2 () { const string __id = "component2.()Ljava/lang/Integer;"; try { var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null); return global::Java.Lang.Object.GetObject<global::Java.Lang.Integer> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']/method[@name='component3' and count(parameter)=0]" [Register ("component3", "()Ljava/lang/Integer;", "")] public unsafe global::Java.Lang.Integer Component3 () { const string __id = "component3.()Ljava/lang/Integer;"; try { var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null); return global::Java.Lang.Object.GetObject<global::Java.Lang.Integer> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']/method[@name='component4' and count(parameter)=0]" [Register ("component4", "()Ljava/lang/String;", "")] public unsafe string Component4 () { const string __id = "component4.()Ljava/lang/String;"; try { var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null); return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.sharedclasses.model.request']/class[@name='CardDetails']/method[@name='copy' and count(parameter)=4 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.Integer'] and parameter[3][@type='java.lang.Integer'] and parameter[4][@type='java.lang.String']]" [Register ("copy", "(Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/String;)Lcom/payment/paymentsdk/sharedclasses/model/request/CardDetails;", "")] public unsafe global::Com.Payment.Paymentsdk.Sharedclasses.Model.Request.CardDetails Copy (string cvv, global::Java.Lang.Integer expiryMonth, global::Java.Lang.Integer expiryYear, string pan) { const string __id = "copy.(Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/String;)Lcom/payment/paymentsdk/sharedclasses/model/request/CardDetails;"; IntPtr native_cvv = JNIEnv.NewString (cvv); IntPtr native_pan = JNIEnv.NewString (pan); try { JniArgumentValue* __args = stackalloc JniArgumentValue [4]; __args [0] = new JniArgumentValue (native_cvv); __args [1] = new JniArgumentValue ((expiryMonth == null) ? IntPtr.Zero : ((global::Java.Lang.Object) expiryMonth).Handle); __args [2] = new JniArgumentValue ((expiryYear == null) ? IntPtr.Zero : ((global::Java.Lang.Object) expiryYear).Handle); __args [3] = new JniArgumentValue (native_pan); var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, __args); return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Sharedclasses.Model.Request.CardDetails> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { JNIEnv.DeleteLocalRef (native_cvv); JNIEnv.DeleteLocalRef (native_pan); global::System.GC.KeepAlive (expiryMonth); global::System.GC.KeepAlive (expiryYear); } } } }
53.807292
383
0.735553
[ "MIT" ]
amr-Magdy-PT/xamarin-paytabs-binding
android/PaymentSDK.Binding/obj/Debug/generated/src/Com.Payment.Paymentsdk.Sharedclasses.Model.Request.CardDetails.cs
10,331
C#
using Newtonsoft.Json.UnityConverters.Helpers; using UnityEngine; namespace Newtonsoft.Json.UnityConverters { /// <summary> /// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for a type containing only Unitys integer version of the Vector3 type <see cref="Vector3Int"/>, /// </summary> public abstract class PartialVector3IntConverter<T> : PartialConverter<T, Vector3Int> { protected PartialVector3IntConverter(string[] propertyNames) : base(propertyNames) { } protected override Vector3Int ReadValue(JsonReader reader, int index, JsonSerializer serializer) { return reader.ReadViaSerializer<Vector3Int>(serializer); } protected override void WriteValue(JsonWriter writer, Vector3Int value, JsonSerializer serializer) { serializer.Serialize(writer, value, typeof(Vector3Int)); } } }
35.423077
164
0.697068
[ "MIT" ]
Adsolution/Ray1Map
Assets/Scripts/Libraries/UnityConverters/PartialVector3IntConverter.cs
923
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class EntityBase : MonoBehaviour { public event Action<EntityBase> OnDeath = (entity) => { }; public bool movedThisTurn { get; set; } public EntityBase InteractingWith { get; set; } public int X { get; set; } public int Y { get; set; } public EntityType EntityType; public EntityType? morphingInto; public Vector3 HUDPoint => transform.position + Vector3.up; public virtual void Init() { } public virtual string GetDebugEntityInfo() { return string.Empty; } public virtual void Die() { OnDeath(this); ObjectPool.Despawn(this); } }
19.225
63
0.63199
[ "MIT" ]
saint-angels/Silkworms
Assets/Scripts/Entities/EntityBase.cs
771
C#
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using OptionsPatternMvc.Example.Settings; using OptionsPatternValidation; namespace OptionsPatternMvc.Example { 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.AddValidatedSettings<ExampleAppSettings>(Configuration); var directExampleAppSettings = Configuration.GetValidatedConfigurationSection<ExampleAppSettings>(); Console.WriteLine($"Name={directExampleAppSettings.Name}"); services.AddControllers(); } // 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(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
29.924528
112
0.652585
[ "MIT" ]
tgharold/OptionsPatternValidation
examples/OptionsPatternMvc.Example/Startup.cs
1,586
C#
using Cosmos.Business.Extensions.Holiday.Configuration; // ReSharper disable once CheckNamespace namespace Cosmos.Business.Extensions.Holiday { /// <summary> /// United States Holiday Provider Extensions /// </summary> public static class UnitedStatesHolidayProviderExtensions { /// <summary> /// Use United States holiday provider /// </summary> /// <param name="options"></param> /// <param name="holidayTypes"></param> /// <typeparam name="TOptions"></typeparam> /// <returns></returns> public static TOptions UseUnitedStates<TOptions>(this HolidayOptions<TOptions> options, params HolidayType[] holidayTypes) where TOptions : HolidayOptions<TOptions> { return options.Use<UnitedStatesHolidayProvider>(holidayTypes); } } }
36.608696
172
0.662708
[ "Apache-2.0" ]
cosmos-open/Holiday
src/Cosmos.Business.Extensions.Holiday/Cosmos/Business/Extensions/Holiday/Definitions/NorthAmerica/UnitedStates/UnitedStatesHolidayProviderExtensions.cs
842
C#
using System; using System.Collections; using Zyan.Communication.ChannelSinks.Compression; using Zyan.Communication.ChannelSinks.Encryption; using Zyan.Communication.Transport; namespace Zyan.Communication.Protocols { /// <summary> /// Base client protocol setup with support for user-defined authentication, security and traffic compression. /// </summary> public class CustomClientProtocolSetup : ClientProtocolSetup { private bool _encryption = true; private string _algorithm = "3DES"; private bool _oaep = false; private int _maxAttempts = 2; private int _compressionThreshold = 1 << 16; private CompressionMethod _compressionMethod = CompressionMethod.Default; /// <summary> /// Creates a new instance of the CustomClientProtocolSetup class. /// </summary> protected CustomClientProtocolSetup() : base() { } /// <summary> /// Creates a new instance of the CustomClientProtocolSetup class. /// </summary> /// <param name="channelFactory">Delegate to channel factory method</param> public CustomClientProtocolSetup(Func<IDictionary, IClientTransportAdapter> channelFactory) : base(channelFactory) { } /// <summary> /// Gets or sets a value indicating whether the encryption is enabled. /// </summary> public bool Encryption { get { return _encryption; } set { _encryption = value; } } /// <summary> /// Gets or sets the name of the symmetric encryption algorithm. /// </summary> public string Algorithm { get { return _algorithm; } set { _algorithm = value; } } /// <summary> /// Gets or sets, if OAEP padding should be activated. /// </summary> public bool Oaep { get { return _oaep; } set { _oaep = value; } } /// <summary> /// Gets or sets the maximum number of attempts when trying to establish a encrypted conection. /// </summary> public int MaxAttempts { get { return _maxAttempts; } set { _maxAttempts = value; } } /// <summary> /// Gets or sets the compression threshold. /// </summary> public int CompressionThreshold { get { return _compressionThreshold; } set { _compressionThreshold = value; } } /// <summary> /// Gets or sets the compression method. /// </summary> public CompressionMethod CompressionMethod { get { return _compressionMethod; } set { _compressionMethod = value; } } private bool _encryptionConfigured = false; /// <summary> /// Configures encrpytion sinks, if encryption is enabled. /// </summary> protected void ConfigureEncryption() { if (_encryption) { if (_encryptionConfigured) return; _encryptionConfigured = true; //TODO: Implement encryption as pipeline stages first. //this.AddClientSinkAfterFormatter(new CryptoClientChannelSinkProvider() //{ // Algorithm = _algorithm, // MaxAttempts = _maxAttempts, // Oaep = _oaep //}); //this.AddServerSinkBeforeFormatter(new CryptoServerChannelSinkProvider() //{ // Algorithm = _algorithm, // RequireCryptoClient = true, // Oaep = _oaep //}); } } private bool _compressionConfigured = false; /// <summary> /// Configures the compression sinks. /// </summary> protected void ConfigureCompression() { if (_compressionConfigured) { return; } _compressionConfigured = true; //TODO: Implement compression as pipeline stages first. //this.AddClientSinkAfterFormatter(new CompressionClientChannelSinkProvider(_compressionThreshold, _compressionMethod)); //this.AddServerSinkBeforeFormatter(new CompressionServerChannelSinkProvider(_compressionThreshold, _compressionMethod)); } } }
28.048951
134
0.6365
[ "MIT" ]
ErrCode/Zyan.Core.LocalIPC
branches/withoutremoting/Zyan.Communication/Protocols/CustomClientProtocolSetup.cs
4,013
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("HKH.Linq.SqlServer")] [assembly: AssemblyDescription("Execute Linq via Dapper for MS SqlServer")] [assembly: AssemblyConfiguration("")] //[assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HKH.Linq.SqlServer")] //[assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0788b3be-1af9-4b9a-8c81-9290e0b379e2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] //[assembly: AssemblyVersion("1.0.0.0")] //[assembly: AssemblyFileVersion("1.0.0.0")]
39.378378
84
0.743308
[ "Apache-2.0" ]
JackyLi918/HKH
HKHProjects/DataProvider/DapperLinq/HKH.Linq.SqlServer/Properties/AssemblyInfo.cs
1,460
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QuieroPizza.BL { public class Categoria { public int Id { get; set; } public string Descripcion { get; set; } } }
18
47
0.677778
[ "MIT" ]
cfreyes/quieropizza
QuieroPizza/QuieroPizza.BL/Categoria.cs
272
C#
using System; using LanguageBasics.Common; using Xunit; namespace LanguageBasics { public class ArrayOperations { [Fact] public void should_access_certain_element_by_position() { var array = new[] {'a', 'e', 'i', 'o', 'u'}; char elementAtIndex2 = array[2]; // change "default(char)" to correct value. const char expectedResult = default (char); Assert.Equal(expectedResult, elementAtIndex2); } [Fact] public void should_throw_if_index_is_out_of_range() { var array = new[] { 'a', 'e', 'i', 'o', 'u' }; // change "typeof(FormatException)" to correct value. Type expectedExceptionType = typeof(FormatException); Assert.NotEqual(typeof(ArgumentException), expectedExceptionType); Assert.NotEqual(typeof(SystemException), expectedExceptionType); Assert.NotEqual(typeof(Exception), expectedExceptionType); Assert.Throws(expectedExceptionType, () => array[99]); } [Fact] public void should_return_index_number_if_found() { var array = new[] { 'a', 'e', 'i', 'o', 'u' }; int indexOfCharacterO = Array.IndexOf(array, 'o'); // change "default(char)" to correct value. const int expectedResult = default(char); Assert.Equal(expectedResult, indexOfCharacterO); } [Fact] public void should_initialize_to_default_value() { var arrayWithValueType = new int[10]; var arrayWithRefType = new string[10]; // change the variable values in the following 2 lines to correct value. const int intAtPostion3 = 1; const string stringAtPosition3 = ""; Assert.Equal(intAtPostion3, arrayWithValueType[3]); Assert.Equal(stringAtPosition3, arrayWithRefType[3]); } [Fact] public void should_return_shallow_copy_of_an_array_using_clone() { var array = new[] {new RefTypeClass(1)}; var cloned = (RefTypeClass[])array.Clone(); array[0].Value = 5; // change the variable value to correct one. const int expectedResult = 1; Assert.Equal(expectedResult, cloned[0].Value); } } }
32.592105
85
0.562374
[ "MIT" ]
WorkSharp/01_NewbieVillage
src/LanguageBasics/03_ArrayOperations.cs
2,479
C#
using Newtonsoft.Json; namespace Common.DTOs.SlackAppDTOs { public class ReactionEventDto { [JsonProperty("type")] public string Type { get; set; } [JsonProperty("user")] public string User { get; set; } [JsonProperty("reaction")] public string Reaction { get; set; } [JsonProperty("item_user")] public string ItemUser { get; set; } [JsonProperty("item")] public Item Item { get; set; } [JsonProperty("event_ts")] public string EventTs { get; set; } } }
22.68
44
0.57672
[ "MIT" ]
projectunic0rn/pub-api
src/Pub/Common/DTOs/SlackAppDtos/ReactionEventDto.cs
567
C#
using EasyEPlanner.PxcIolinkConfiguration.Interfaces; using EasyEPlanner.PxcIolinkConfiguration.Models; using System.IO; using System.Xml.Serialization; namespace EasyEPlanner.PxcIolinkConfiguration { public class XmlSensorSerializer : IXmlSensorSerializer { public LinerecorderSensor Deserialize(string xml) { var serializer = new XmlSerializer(typeof(LinerecorderSensor)); using (var reader = new StringReader(xml)) { var info = (LinerecorderSensor)serializer.Deserialize(reader); return info; } } public void Serialize(LinerecorderMultiSensor template, string path) { var serializer = new XmlSerializer(typeof(LinerecorderMultiSensor)); using (var fs = new FileStream(path, FileMode.Create)) { serializer.Serialize(fs, template); } } } }
31.6
80
0.639241
[ "MIT" ]
KirillGutyrchik/EasyEPLANner
src/PxcIolinkConfiguration/XmlSensorSerializer.cs
950
C#
using Sharp.Redux.Playground.Engine.States; using System.Threading.Tasks; namespace Sharp.Redux.Playground.Engine { public class PlaygroundReduxDispatcher: ReduxDispatcher<RootState, IReduxReducer<RootState>>, IPlaygroundReduxDispatcher { public PlaygroundReduxDispatcher(RootState initialState, IReduxReducer<RootState> reducer) : base(initialState, reducer, TaskScheduler.FromCurrentSynchronizationContext()) { } } }
31.333333
124
0.755319
[ "MIT" ]
JTOne123/sharp-redux
playground/Sharp.Redux.Playground.Engine/WpfReduxDispatcher.cs
472
C#
// // Copyright (c) Leif Erik Bjoerkli, Norwegian University of Science and Technology, 2015. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Kinect; namespace Kinect2TrackingTopView { class HeatMap { private readonly Dictionary<int, int>[] _map; private int _maxIntensity; public HeatMap() { _map = new Dictionary<int, int>[GlobVar.ScaledFrameLength]; for (int i = 0; i < _map.Length; i++) { _map[i] = new Dictionary<int, int>(); } _maxIntensity = 0; } public void AddFrame(int[] heatFrame) { for (int i = 0; i < heatFrame.Length; i++) { int pixelBodyId = heatFrame[i]; if (pixelBodyId != 0) { if (_map[i].ContainsKey(pixelBodyId)) { _map[i][pixelBodyId]++; if (_map[i][pixelBodyId] > _maxIntensity) { _maxIntensity = _map[i][pixelBodyId]; } } else { _map[i].Add(pixelBodyId,1); } } } ClearHeatCanvas(); } private static void ClearHeatCanvas() { GlobVar.HeatCanvas = new int[GlobVar.ScaledFrameLength]; } public byte[] Get() { var filteredHeatMap = FilterMostTrackedBodyId(_map); var normalizedHeatMap = NormalizeIntensitiesInHeatMap(filteredHeatMap); var bgraMap = CreateBgraMapFromHeatMap(normalizedHeatMap); return bgraMap; } private Dictionary<int, int>[] NormalizeIntensitiesInHeatMap(Dictionary<int, int>[] filteredHeatMap) { var normalizedHeatMap = new Dictionary<int, int>[filteredHeatMap.Length]; for (int i = 0; i < filteredHeatMap.Length; i++) { var newHeatFrame = new Dictionary<int, int>(); foreach (var element in filteredHeatMap[i]) { newHeatFrame.Add(element.Key, (int)(((double)element.Value / (double)_maxIntensity) * 255)); } normalizedHeatMap[i] = newHeatFrame; } return normalizedHeatMap; } public static byte[] CreateBgraMapFromHeatMap(Dictionary<int, int>[] normalizedHeatMap) { var bgraMap = new byte[GlobVar.ScaledFrameLength * 4]; for (int i = 0; i < normalizedHeatMap.Length; i++) { int rgbaHeatMapIndex = i * 4; var color = GetColorFromHeatData(normalizedHeatMap[i], i); double totalIntensity = 0; foreach (var element in normalizedHeatMap[i]) { totalIntensity += element.Value; } bgraMap[rgbaHeatMapIndex] = color[0]; bgraMap[rgbaHeatMapIndex + 1] = color[1]; bgraMap[rgbaHeatMapIndex + 2] = color[2]; bgraMap[rgbaHeatMapIndex + 3] = color[3]; } return bgraMap; } private static byte[] GetColorFromHeatData(Dictionary<int,int> heatDictionary,int i) { int totalIntensity = 0; foreach (var element in heatDictionary) { totalIntensity += element.Value; } var color = new byte[4]; foreach (var element in heatDictionary) { var idColor = GraphicsUtils.GetBgrColorFromBodyId(element.Key); var weight = (double)element.Value / (double)totalIntensity; color[0] += (byte)(idColor[0] * weight); color[1] += (byte)(idColor[1] * weight); color[2] += (byte)(idColor[2] * weight); } color[3] = (byte) totalIntensity; return color; } /// <summary> /// If only one body is supposed to be tracked, this method filters away all other bodies than the one that is tracked the most. /// </summary> private Dictionary<int, int>[] FilterMostTrackedBodyId(Dictionary<int, int>[] heatMap) { var filteredHeatMap = new Dictionary<int, int>[heatMap.Length]; int mostTrackedBodyId = GetMostTrackedBodyIdFromHeatHistory(); for (int i = 0; i < heatMap.Length; i++) { var newHeatFrame = new Dictionary<int, int>(); foreach (var element in heatMap[i]) { if (element.Key == mostTrackedBodyId) { newHeatFrame.Add(1,element.Value); } } filteredHeatMap[i] = newHeatFrame; } return filteredHeatMap; } private int GetMostTrackedBodyIdFromHeatHistory() { var bodyIdCount = new Dictionary<int,int>(); for (int i = 1; i <= GlobVar.MaxBodyCount; i++) { bodyIdCount.Add(i,0); } foreach (var index in _map) { foreach (var heat in index) { bodyIdCount[heat.Key] += heat.Value; } } var sortedCount = bodyIdCount.OrderByDescending(kvp => kvp.Value); return sortedCount.ElementAt(0).Key; } } }
31.88587
136
0.502983
[ "MIT" ]
leiferikbjorkli/Kinect2TrackingTopView
PostProcessing/HeatMap.cs
5,869
C#
using System; using System.Collections.Generic; using System.Xml.Serialization; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// KoubeiMarketingCampaignIntelligentPromoConsultModel Data Structure. /// </summary> [Serializable] public class KoubeiMarketingCampaignIntelligentPromoConsultModel : AlipayObject { /// <summary> /// 扩展信息,以key-value的形式传递 /// </summary> [JsonProperty("ext_info")] [XmlElement("ext_info")] public string ExtInfo { get; set; } /// <summary> /// 操作人信息 /// </summary> [JsonProperty("operator_context")] [XmlElement("operator_context")] public PromoOperatorInfo OperatorContext { get; set; } /// <summary> /// 外部业务id,尽量保持该字段足够复杂 /// </summary> [JsonProperty("out_request_no")] [XmlElement("out_request_no")] public string OutRequestNo { get; set; } /// <summary> /// 原智能方案id /// </summary> [JsonProperty("parent_promo_id")] [XmlElement("parent_promo_id")] public string ParentPromoId { get; set; } /// <summary> /// 商户和支付宝交互时,用于代表支付宝分配给商户ID /// </summary> [JsonProperty("partner_id")] [XmlElement("partner_id")] public string PartnerId { get; set; } /// <summary> /// 当全场普通和单品普通方案时必传,体验方案不用传 /// </summary> [JsonProperty("shop_ids")] [XmlArray("shop_ids")] [XmlArrayItem("string")] public List<string> ShopIds { get; set; } /// <summary> /// 营销模板的编号,GENERAL_EXPERIENCE:全场体验;GENERAL_NORMAL:全场普通;ITEM_EXPERIENCE:单品体验;ITEM_NORMAL:单品普通 /// </summary> [JsonProperty("template_code")] [XmlElement("template_code")] public string TemplateCode { get; set; } } }
29.246154
101
0.590216
[ "MIT" ]
AkonCoder/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiMarketingCampaignIntelligentPromoConsultModel.cs
2,127
C#
using System; using NUnit.Framework; namespace MPT.PropertyChanger.UnitTests { [TestFixture] public class ChildChangedListenerTests { [Test] public void TestMethod1() { } } }
14.125
42
0.610619
[ "MIT" ]
MarkPThomas/MPT.Net
MPT/PropertyChanger/MPT.PropertyChanger.UnitTests/ChangedListener/ChildChangedListenerTests.cs
228
C#
using System.ComponentModel.DataAnnotations; using Abp.Organizations; namespace GSoft.AbpZeroTemplate.Organizations.Dto { public class CreateOrganizationUnitInput { public long? ParentId { get; set; } [Required] [StringLength(OrganizationUnit.MaxDisplayNameLength)] public string DisplayName { get; set; } } }
25.5
61
0.708683
[ "Apache-2.0" ]
NTD98/ASP_ANGULAR
asset-management-api/src/GSoft.AbpZeroTemplate.Application.Shared/Organizations/Dto/CreateOrganizationUnitInput.cs
359
C#