content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Horeb.Presentation")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Horeb.Presentation")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
42.571429
98
0.710151
[ "Apache-2.0" ]
AsimKhan2019/Horeb-Financial-Management
Horeb.Presentation/Properties/AssemblyInfo.cs
2,387
C#
namespace ClearHl7.Codes.V290 { /// <summary> /// HL7 Version 2 Table 0175 - Master File Identifier Code. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0175</remarks> public enum CodeMasterFileIdentifierCode { /// <summary> /// CDM - Charge description master file. /// </summary> ChargeDescriptionMasterFile, /// <summary> /// CLN - Clinic master file. /// </summary> ClinicMasterFile, /// <summary> /// CMA - Clinical study with phases and scheduled master file. /// </summary> ClinicalStudyWithPhasesAndScheduledMasterFile, /// <summary> /// CMB - Clinical study without phases but with scheduled master file. /// </summary> ClinicalStudyWithoutPhasesButWithScheduledMasterFile, /// <summary> /// INV - Inventory master file. /// </summary> InventoryMasterFile, /// <summary> /// LOC - Location master file. /// </summary> LocationMasterFile, /// <summary> /// MACP - Medicare Approved Coverage Process. /// </summary> MedicareApprovedCoverageProcess, /// <summary> /// MLCP - Medicare Limited Coverage Process. /// </summary> MedicareLimitedCoverageProcess, /// <summary> /// OMA - Numerical observation master file. /// </summary> NumericalObservationMasterFile, /// <summary> /// OMB - Categorical observation master file. /// </summary> CategoricalObservationMasterFile, /// <summary> /// OMC - Observation batteries master file. /// </summary> ObservationBatteriesMasterFile, /// <summary> /// OMD - Calculated observations master file. /// </summary> CalculatedObservationsMasterFile, /// <summary> /// OME - Other Observation/Service Item master file. /// </summary> OtherObservationServiceItemMasterFile, /// <summary> /// OMM - Mixed type observation master file. /// </summary> MixedTypeObservationMasterFile, /// <summary> /// PRA - Practitioner master file. /// </summary> PractitionerMasterFile, /// <summary> /// STF - Staff master file. /// </summary> StaffMasterFile } }
27.944444
80
0.543141
[ "MIT" ]
kamlesh-microsoft/clear-hl7-net
src/ClearHl7.Codes/V290/CodeMasterFileIdentifierCode.cs
2,517
C#
using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using RobsonROX.Util.MVC.RouteDebug; namespace Agenda.Web { public class MvcApplication : HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); //RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); ModelConfig.AssociateMetadata(); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
29.409091
72
0.692427
[ "MIT" ]
RobsonRochaBR/Cursos
ASP.NET MVC/Aula 5/Demo 1/Agenda.Web/Global.asax.cs
649
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using Mono.Cecil; using Clang.Ast; namespace Extrospection { public enum Platforms { macOS, iOS, watchOS, tvOS, } public static partial class Helpers { // the original name can be lost and, if not registered (e.g. enums), might not be available static Dictionary<string,string> map = new Dictionary<string, string> () { { "AudioChannelBitmap", "AudioChannelBit" }, { "EABluetoothAccessoryPickerErrorCode", "EABluetoothAccessoryPickerError" }, { "EKCalendarEventAvailabilityMask", "EKCalendarEventAvailability" }, { "GKErrorCode", "GKError" }, { "HMCharacteristicValueAirParticulateSize", "HMCharacteristicValueAirParticulate" }, { "HMCharacteristicValueLockMechanismLastKnownAction", "HMCharacteristicValueLockMechanism" }, { "HMErrorCode", "HMError" }, { "LAError", "LAStatus" }, { "MCErrorCode", "MCError" }, { "MPMovieMediaTypeMask", "MPMovieMediaType" }, { "NEVPNIKEv2CertificateType", "NEVpnIke2CertificateType" }, { "NEVPNIKEv2DeadPeerDetectionRate", "NEVpnIke2DeadPeerDetectionRate" }, { "NEVPNIKEv2DiffieHellmanGroup", "NEVpnIke2DiffieHellman" }, { "NEVPNIKEv2EncryptionAlgorithm", "NEVpnIke2EncryptionAlgorithm" }, { "NEVPNIKEv2IntegrityAlgorithm", "NEVpnIke2IntegrityAlgorithm" }, { "NEDNSProtocol", "NEDnsProtocol"}, { "NEDNSSettingsManagerError", "NEDnsSettingsManagerError"}, { "NSAttributedStringEnumerationOptions", "NSAttributedStringEnumeration" }, { "NSFileProviderErrorCode", "NSFileProviderError" }, { "NSUbiquitousKeyValueStoreChangeReason", "NSUbiquitousKeyValueStore" }, { "PHLivePhotoEditingErrorCode", "PHLivePhotoEditingError" }, { "RPRecordingErrorCode", "RPRecordingError" }, { "SecTrustResultType", "SecTrustResult" }, { "SKErrorCode", "SKError" }, { "SSReadingListErrorCode", "SSReadingListError" }, { "tls_ciphersuite_group_t", "TlsCipherSuiteGroup" }, { "tls_ciphersuite_t", "TlsCipherSuite" }, { "tls_protocol_version_t", "TlsProtocolVersion" }, { "UIDataDetectorTypes", "UIDataDetectorType" }, { "UIControlEvents", "UIControlEvent" }, { "UIKeyboardHIDUsage", "UIKeyboardHidUsage" }, { "UITableViewCellAccessoryType", "UITableViewCellAccessory" }, { "UITableViewCellStateMask", "UITableViewCellState" }, { "WatchKitErrorCode", "WKErrorCode" }, // WebKit already had that name { "MIDIProtocolID", "MidiProtocolId" }, { "MIDICVStatus", "MidiCVStatus" }, { "MIDIMessageType", "MidiMessageType" }, { "MIDISysExStatus", "MidiSysExStatus" }, { "MIDISystemStatus", "MidiSystemStatus" }, { "NFCFeliCaEncryptionId", "EncryptionId" }, { "NFCFeliCaPollingRequestCode", "PollingRequestCode" }, { "NFCFeliCaPollingTimeSlot", "PollingTimeSlot" }, { "NFCVASErrorCode", "VasErrorCode" }, { "NFCVASMode", "VasMode" }, { "NFCISO15693RequestFlag", "RequestFlag" }, // not enums }; public static string GetManagedName (string nativeName) { map.TryGetValue (nativeName, out var result); return result ?? nativeName; } public static string ReplaceFirstInstance (this string source, string find, string replace) { int index = source.IndexOf (find, StringComparison.Ordinal); return index < 0 ? source : source.Substring (0, index) + replace + source.Substring (index + find.Length); } public static Platforms Platform { get; set; } public static int GetPlatformManagedValue (Platforms platform) { // None, MacOSX, iOS, WatchOS, TvOS switch (platform) { case Platforms.macOS: return 1; case Platforms.iOS: return 2; case Platforms.watchOS: return 3; case Platforms.tvOS: return 4; default: throw new InvalidOperationException ($"Unexpected Platform {Platform} in GetPlatformManagedValue"); } } // Clang.Ast.AvailabilityAttr.Platform.Name public static string ClangPlatformName { get { switch (Helpers.Platform) { case Platforms.macOS: return "macos"; case Platforms.iOS: return "ios"; case Platforms.watchOS: return "watchos"; case Platforms.tvOS: return "tvos"; default: throw new InvalidOperationException ($"Unexpected Platform {Platform} in ClangPlatformName"); } } } public static bool IsAvailable (this ICustomAttributeProvider cap) { if (!cap.HasCustomAttributes) return true; foreach (var ca in cap.CustomAttributes) { switch (ca.Constructor.DeclaringType.Name) { case "UnavailableAttribute": if (GetPlatformManagedValue (Platform) == (byte) ca.ConstructorArguments [0].Value) return false; break; case "NoiOSAttribute": if (Platform == Platforms.iOS) return false; break; case "NoTVAttribute": if (Platform == Platforms.tvOS) return false; break; case "NoWatchAttribute": if (Platform == Platforms.watchOS) return false; break; case "NoMacAttribute": if (Platform == Platforms.macOS) return false; break; } } return true; } public static bool IsAvailable (this Decl decl) { // there's no doubt we need to ask for the current platform var result = decl.IsAvailable (Platform); // some categories are not decorated (as not available) but they extend types that are if (!result.HasValue) { // first check if we're checking the category itself var category = decl as ObjCCategoryDecl; if (category != null) result = category.ClassInterface.IsAvailable (Platform); if (!result.HasValue) { // then check if we're a method inside a category category = (decl.DeclContext as ObjCCategoryDecl); if (category != null) result = category.ClassInterface.IsAvailable (Platform); } } // but right now most frameworks consider tvOS and watchOS like iOS unless // decorated otherwise so we must check again if we do not get a definitve answer if ((result == null) && ((Platform == Platforms.tvOS) || (Platform == Platforms.watchOS))) result = decl.IsAvailable (Platforms.iOS); return !result.HasValue ? true : result.Value; } static bool? IsAvailable (this Decl decl, Platforms platform_value) { var platform = platform_value.ToString ().ToLowerInvariant (); bool? result = null; foreach (var attr in decl.Attrs) { // NS_UNAVAILABLE if (attr is UnavailableAttr) return false; var avail = (attr as AvailabilityAttr); if (avail == null) continue; // if the headers says it's not available then we won't report it as missing if (avail.Unavailable && (avail.Platform.Name == platform)) return false; // for iOS we won't report missing members that were deprecated before 5.0 if (!avail.Deprecated.IsEmpty && avail.Platform.Name == "ios" && avail.Deprecated.Major < 5) return false; // can't return true right away as it can be deprecated too if (!avail.Introduced.IsEmpty && (avail.Platform.Name == platform)) result = true; } return result; } public static bool IsDesignatedInitializer (this MethodDefinition self) { return self.HasAttribute ("DesignatedInitializerAttribute"); } public static bool IsProtocol (this TypeDefinition self) { return self.HasAttribute ("ProtocolAttribute"); } public static bool RequiresSuper (this MethodDefinition self) { return self.HasAttribute ("RequiresSuperAttribute"); } static bool HasAttribute (this ICustomAttributeProvider self, string attributeName) { if (!self.HasCustomAttributes) return false; foreach (var ca in self.CustomAttributes) { if (ca.Constructor.DeclaringType.Name == attributeName) return true; } return false; } static bool IsStatic (this TypeDefinition self) { return (self.IsSealed && self.IsAbstract); } public static string GetName (this ObjCMethodDecl self) { if (self == null) return null; var sb = new StringBuilder (); if (self.IsClassMethod) sb.Append ('+'); if (self.DeclContext is ObjCCategoryDecl category) { sb.Append (category.ClassInterface.Name); } else { sb.Append ((self.DeclContext as NamedDecl).Name); } sb.Append ("::"); var sel = self.Selector.ToString (); sb.Append (string.IsNullOrEmpty (sel) ? self.Name : sel); return sb.ToString (); } public static string GetName (this TypeDefinition self) { if ((self == null) || !self.HasCustomAttributes) return null; if (self.IsStatic ()) { // static types, e.g. categories, won't have a [Register] attribute foreach (var ca in self.CustomAttributes) { if (ca.Constructor.DeclaringType.Name == "CategoryAttribute") { if (ca.HasProperties) return (ca.Properties [0].Argument.Value as string); return self.Name; } } } else { foreach (var ca in self.CustomAttributes) { if (ca.Constructor.DeclaringType.Name == "RegisterAttribute") { if (ca.HasConstructorArguments) return (ca.ConstructorArguments [0].Value as string); return self.Name; } else if (ca.Constructor.DeclaringType.Name == "ProtocolAttribute") { if (ca.HasConstructorArguments) return (ca.ConstructorArguments [0].Value as string); return self.Name; } } } return null; } public static string GetName (this MethodDefinition self) { if (self == null) return null; var type = self.DeclaringType; string tname = self.DeclaringType.GetName (); // a static type is not used for static selectors bool is_static = !type.IsStatic () && self.IsStatic; // static types, e.g. categories, won't have a [Register] attribute if (type.IsStatic ()) { if (self.HasParameters) tname = self.Parameters [0].ParameterType.Resolve ().GetName (); // extension method } if (tname == null) return null; var selector = self.GetSelector (); if (selector == null) return null; var sb = new StringBuilder (); if (is_static) sb.Append ('+'); sb.Append (tname); sb.Append ("::"); sb.Append (selector); return sb.ToString (); } public static string GetSelector (this MethodDefinition self) { if ((self == null) || !self.HasCustomAttributes) return null; foreach (var ca in self.CustomAttributes) { if (ca.Constructor.DeclaringType.Name == "ExportAttribute") return ca.ConstructorArguments [0].Value as string; } return null; } public static string GetSelector (this ObjCMethodDecl self) { return self.Selector.ToString () ?? self.Name; } public static bool IsObsolete (this ICustomAttributeProvider provider) { if (provider.HasCustomAttributes) { foreach (var attrib in provider.CustomAttributes) { var attribType = attrib.Constructor.DeclaringType; if (attribType.Namespace == "System" && attribType.Name == "ObsoleteAttribute") return true; } } // If we're a property accessor, check the property as well. var prop = FindProperty (provider as MethodReference); if (prop != null) return IsObsolete (prop); return false; } public static PropertyDefinition FindProperty (this MethodReference method) { var def = method?.Resolve (); if (def == null) return null; if (!def.IsSpecialName) return null; if (!def.DeclaringType.HasProperties) return null; if (!method.Name.StartsWith ("get_", StringComparison.Ordinal) && !method.Name.StartsWith ("set_", StringComparison.Ordinal)) return null; var propName = method.Name.Substring (4); foreach (var prop in def.DeclaringType.Properties) { if (prop.Name == propName) return prop; } return null; } public static string GetFramework (TypeReference type) { var framework = type.Namespace; if (String.IsNullOrEmpty (framework) && type.IsNested) framework = type.DeclaringType.Namespace; return MapFramework (framework); } public static string GetFramework (MethodDefinition method) { string framework = null; if (method.HasPInvokeInfo) framework = Path.GetFileNameWithoutExtension (method.PInvokeInfo.Module.Name); else framework = GetFramework (method.DeclaringType); return MapFramework (framework); } public static string GetFramework (MemberReference member) { string framework = GetFramework (member.DeclaringType); return MapFramework (framework); } public static string GetFramework (Decl decl) { var header_file = decl.PresumedLoc.FileName; var fxh = header_file.IndexOf (".framework/Headers/", StringComparison.Ordinal); if (fxh <= 0) return null; var start = header_file.LastIndexOf ('/', fxh) + 1; return MapFramework (header_file.Substring (start, fxh - start)); } public static string MapFramework (string candidate) { switch (candidate) { case "AVFAudio": return "AVFoundation"; case "libc": // dispatch_* return "CoreFoundation"; case "libobjc": case "libSystem": // dlopen, dlerror, dlsym, dlclose return "ObjCRuntime"; case "libsystem_kernel": // getxattr, removexattr and setxattr return "Foundation"; case "MPSCore": case "MPSImage": case "MPSMatrix": case "MPSNDArray": case "MPSNeuralNetwork": case "MPSRayIntersector": return "MetalPerformanceShaders"; case "QuartzCore": return "CoreAnimation"; case "OpenAL": case "OpenGL": case "OpenGLES": case "OpenTK.Platform.iPhoneOS": return "OpenGL[ES]"; case "vImage": return "Accelerate"; default: return candidate; } } public static (T, T) Sort<T> (T o1, T o2) { if (StringComparer.Ordinal.Compare (o1.ToString (), o2.ToString ()) < 0) return (o2, o1); else return (o1, o2); } public enum ArgumentSemantic { None = -1, Assign = 0, Copy = 1, Retain = 2, Weak = 3, Strong = Retain, UnsafeUnretained = Assign, } public static ArgumentSemantic ToArgumentSemantic (this ObjCPropertyAttributeKind attr) { if ((attr & ObjCPropertyAttributeKind.Retain) != 0) return ArgumentSemantic.Retain; else if ((attr & ObjCPropertyAttributeKind.Copy) != 0) return ArgumentSemantic.Copy; else if ((attr & ObjCPropertyAttributeKind.Assign) != 0) return ArgumentSemantic.Assign; else if ((attr & ObjCPropertyAttributeKind.Weak) != 0) return ArgumentSemantic.Weak; else if ((attr & ObjCPropertyAttributeKind.Strong) != 0) return ArgumentSemantic.Strong; else if ((attr & ObjCPropertyAttributeKind.UnsafeUnretained) != 0) return ArgumentSemantic.UnsafeUnretained; else return ArgumentSemantic.Assign; // Default } public static string ToUsableString (this ArgumentSemantic argSem) { if (argSem == ArgumentSemantic.Retain) return "Strong|Retain"; if (argSem == ArgumentSemantic.Assign) return "UnsafeUnretained|Assign"; return argSem.ToString (); } } }
30.440816
128
0.686444
[ "BSD-3-Clause" ]
tondat/xamarin-macios
tests/xtro-sharpie/Helpers.cs
14,918
C#
//==================================================================================================================== // Copyright (c) 2012 IdeaBlade //==================================================================================================================== // 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. //==================================================================================================================== // USE OF THIS SOFTWARE IS GOVERENED BY THE LICENSING TERMS WHICH CAN BE FOUND AT // http://cocktail.ideablade.com/licensing //==================================================================================================================== namespace Common.Messages { public class EntityChangedMessage { public EntityChangedMessage(object entity) { Entity = entity; } public object Entity { get; private set; } } }
55.916667
120
0.467213
[ "MIT" ]
jkattestaart/AccoBooking
Common.SL/Messages/EntityChangedMessage.cs
1,342
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { [Export(typeof(VisualStudioProjectFactory))] internal sealed class VisualStudioProjectFactory { private const string SolutionContextName = "Solution"; private const string SolutionSessionIdPropertyName = "SolutionSessionID"; private readonly VisualStudioWorkspaceImpl _visualStudioWorkspaceImpl; private readonly HostDiagnosticUpdateSource _hostDiagnosticUpdateSource; private readonly ImmutableArray<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> _dynamicFileInfoProviders; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioProjectFactory( VisualStudioWorkspaceImpl visualStudioWorkspaceImpl, [ImportMany] IEnumerable<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> fileInfoProviders, HostDiagnosticUpdateSource hostDiagnosticUpdateSource) { _visualStudioWorkspaceImpl = visualStudioWorkspaceImpl; _dynamicFileInfoProviders = fileInfoProviders.AsImmutableOrEmpty(); _hostDiagnosticUpdateSource = hostDiagnosticUpdateSource; } public VisualStudioProject CreateAndAddToWorkspace(string projectSystemName, string language) => CreateAndAddToWorkspace(projectSystemName, language, new VisualStudioProjectCreationInfo()); public VisualStudioProject CreateAndAddToWorkspace(string projectSystemName, string language, VisualStudioProjectCreationInfo creationInfo) { // HACK: Fetch this service to ensure it's still created on the UI thread; once this is moved off we'll need to fix up it's constructor to be free-threaded. _visualStudioWorkspaceImpl.Services.GetRequiredService<VisualStudioMetadataReferenceManager>(); // HACK: since we're on the UI thread, ensure we initialize our options provider which depends on a UI-affinitized experimentation service _visualStudioWorkspaceImpl.EnsureDocumentOptionProvidersInitialized(); var id = ProjectId.CreateNewId(projectSystemName); var assemblyName = creationInfo.AssemblyName ?? projectSystemName; // We will use the project system name as the default display name of the project var project = new VisualStudioProject( _visualStudioWorkspaceImpl, _dynamicFileInfoProviders, _hostDiagnosticUpdateSource, id, displayName: projectSystemName, language, assemblyName: assemblyName, compilationOptions: creationInfo.CompilationOptions, filePath: creationInfo.FilePath, parseOptions: creationInfo.ParseOptions); var versionStamp = creationInfo.FilePath != null ? VersionStamp.Create(File.GetLastWriteTimeUtc(creationInfo.FilePath)) : VersionStamp.Create(); _visualStudioWorkspaceImpl.AddProjectToInternalMaps(project, creationInfo.Hierarchy, creationInfo.ProjectGuid, projectSystemName); _visualStudioWorkspaceImpl.ApplyChangeToWorkspace(w => { var projectInfo = ProjectInfo.Create( id, versionStamp, name: projectSystemName, assemblyName: assemblyName, language: language, filePath: creationInfo.FilePath, compilationOptions: creationInfo.CompilationOptions, parseOptions: creationInfo.ParseOptions) .WithTelemetryId(creationInfo.ProjectGuid); // If we don't have any projects and this is our first project being added, then we'll create a new SolutionId if (w.CurrentSolution.ProjectIds.Count == 0) { // Fetch the current solution path. Since we're on the UI thread right now, we can do that. string? solutionFilePath = null; var solution = (IVsSolution)Shell.ServiceProvider.GlobalProvider.GetService(typeof(SVsSolution)); if (solution != null) { if (ErrorHandler.Failed(solution.GetSolutionInfo(out _, out solutionFilePath, out _))) { // Paranoia: if the call failed, we definitely don't want to use any stuff that was set solutionFilePath = null; } } var solutionSessionId = GetSolutionSessionId(); w.OnSolutionAdded( SolutionInfo.Create( SolutionId.CreateNewId(solutionFilePath), VersionStamp.Create(), solutionFilePath, projects: new[] { projectInfo }, analyzerReferences: w.CurrentSolution.AnalyzerReferences) .WithTelemetryId(solutionSessionId)); } else { w.OnProjectAdded(projectInfo); } _visualStudioWorkspaceImpl.RefreshProjectExistsUIContextForLanguage(language); }); return project; static Guid GetSolutionSessionId() { var dataModelTelemetrySession = TelemetryService.DefaultSession; var solutionContext = dataModelTelemetrySession.GetContext(SolutionContextName); var sessionIdProperty = solutionContext is object ? (string)solutionContext.SharedProperties[SolutionSessionIdPropertyName] : ""; _ = Guid.TryParse(sessionIdProperty, out var solutionSessionId); return solutionSessionId; } } } }
49.888889
168
0.640831
[ "MIT" ]
HurricanKai/roslyn
src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectFactory.cs
6,737
C#
using System; using System.ComponentModel.DataAnnotations; using McMaster.Extensions.CommandLineUtils; using McMaster.Extensions.CommandLineUtils.Validation; namespace DnsPush.Core.OptionValidators { public class TtlRangeValidator : IOptionValidator { public ValidationResult GetValidationResult(CommandOption option, ValidationContext context) { // This validator only runs if there is a value if (!option.HasValue()) return ValidationResult.Success; int val = ((CommandOption<int>)option).ParsedValue; if (val < 60 || val > 60000) { return new ValidationResult($"The value for --{option.LongName} must be at least 60 and no greater than 60000"); } return ValidationResult.Success; } } }
34.458333
128
0.668682
[ "MIT" ]
x3haloed/dnspush
src/DnsPush.Core/OptionValidators/TtlRangeValidator.cs
827
C#
namespace Matrix.Handlers { public interface IMatrixHandler { Matrix For(Matrix matrix); } }
14.25
35
0.640351
[ "Unlicense" ]
interreto/www.metlinskyi.com
csharp/tasks/moneyveo/Matrix/Handlers/IMatrixHandler.cs
116
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Ecs.Model.V20140526 { public class ResetDisksResponse : AcsResponse { private string requestId; private List<ResetDisks_OperationProgress> operationProgressSet; public string RequestId { get { return requestId; } set { requestId = value; } } public List<ResetDisks_OperationProgress> OperationProgressSet { get { return operationProgressSet; } set { operationProgressSet = value; } } public class ResetDisks_OperationProgress { private string operationStatus; private string errorCode; private string errorMsg; private List<ResetDisks_RelatedItem> relatedItemSet; public string OperationStatus { get { return operationStatus; } set { operationStatus = value; } } public string ErrorCode { get { return errorCode; } set { errorCode = value; } } public string ErrorMsg { get { return errorMsg; } set { errorMsg = value; } } public List<ResetDisks_RelatedItem> RelatedItemSet { get { return relatedItemSet; } set { relatedItemSet = value; } } public class ResetDisks_RelatedItem { private string name; private string _value; public string Name { get { return name; } set { name = value; } } public string _Value { get { return _value; } set { _value = value; } } } } } }
17.395973
67
0.605324
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-ecs/Ecs/Model/V20140526/ResetDisksResponse.cs
2,592
C#
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Threading; using System.Threading.Tasks; namespace LionFire.Data.Connections { public interface IConnection : IHostedService { //ILogger Logger { set; } //string ConnectionString { get; set; } string ConnectionString { get; } // will all connections have this? new Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)); new Task StopAsync(CancellationToken cancellationToken = default(CancellationToken)); } }
30.526316
94
0.72931
[ "MIT" ]
LionFire/Core
src/LionFire.Data.Connections/Conections/IConnection.cs
582
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the devops-guru-2020-12-01.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.DevOpsGuru { /// <summary> /// Configuration for accessing Amazon DevOpsGuru service /// </summary> public partial class AmazonDevOpsGuruConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.7.3.8"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonDevOpsGuruConfig() { this.AuthenticationServiceName = "devops-guru"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "devops-guru"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2020-12-01"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.175
109
0.587393
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/DevOpsGuru/Generated/AmazonDevOpsGuruConfig.cs
2,094
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using StarkPlatform.CodeAnalysis.Stark.Extensions.ContextQuery; using StarkPlatform.CodeAnalysis.Stark.Syntax; namespace StarkPlatform.CodeAnalysis.Stark.Completion.KeywordRecommenders { internal class RemoveKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public RemoveKeywordRecommender() : base(SyntaxKind.RemoveKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.TargetToken.IsAccessorDeclarationContext<EventDeclarationSyntax>(position, SyntaxKind.RemoveKeyword); } } }
39.136364
161
0.761905
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/Features/Stark/Portable/Completion/KeywordRecommenders/RemoveKeywordRecommender.cs
863
C#
//////////////////////////////////////////////////////////////////////////////// //EF Core Provider for LCPI OLE DB. // IBProvider and Contributors. 04.09.2021. using System; using System.Diagnostics; using System.Linq.Expressions; namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Methods.Translators{ //////////////////////////////////////////////////////////////////////////////// //using using Structure_TypeCache =Structure.Structure_TypeCache; using Structure_MethodIdCache =Structure.Structure_MethodIdCache; using Structure_MethodInfoCache =Structure.Structure_MethodInfoCache; //////////////////////////////////////////////////////////////////////////////// //class ETranslator__TimeOnly__std__IsBetween sealed class ETranslator__TimeOnly__std__IsBetween :Root.Query.Local.LcpiOleDb__LocalEval_MethodCallTranslator { public static readonly Root.Query.Local.LcpiOleDb__LocalEval_MethodCallTranslator Instance =new ETranslator__TimeOnly__std__IsBetween(); //----------------------------------------------------------------------- private ETranslator__TimeOnly__std__IsBetween() :base(Structure_MethodIdCache.MethodIdOf__TimeOnly__std__IsBetween) { }//ETranslator__TimeOnly__std__IsBetween //interface ------------------------------------------------------------- public override Expression Translate(in tagOpData opData) { Debug.Assert(!Object.ReferenceEquals(opData.MethodId,null)); Debug.Assert(opData.MethodId==Structure_MethodInfoCache.MethodInfoOf__TimeOnly__std__IsBetween); //---------------------------------------- Debug.Assert(!Object.ReferenceEquals(opData.CallObject,null)); Debug.Assert(!Object.ReferenceEquals(opData.Arguments,null)); Debug.Assert(opData.Arguments.Count==2); //---------------------------------------- var node_Source =opData.CallObject; Debug.Assert(!Object.ReferenceEquals(node_Source,null)); Debug.Assert(!Object.ReferenceEquals(node_Source.Type,null)); Debug.Assert(node_Source.Type==Structure_TypeCache.TypeOf__System_TimeOnly); //---------------------------------------- var node_Start =opData.Arguments[0]; Debug.Assert(!Object.ReferenceEquals(node_Start,null)); Debug.Assert(!Object.ReferenceEquals(node_Start.Type,null)); Debug.Assert(node_Start.Type==Structure_TypeCache.TypeOf__System_TimeOnly); //---------------------------------------- var node_End =opData.Arguments[1]; Debug.Assert(!Object.ReferenceEquals(node_End,null)); Debug.Assert(!Object.ReferenceEquals(node_End.Type,null)); Debug.Assert(node_End.Type==Structure_TypeCache.TypeOf__System_TimeOnly); //---------------------------------------- var r =Expression.Call (Code.Method_Code__TimeOnly__IsBetween.MethodInfo, node_Source, node_Start, node_End); Debug.Assert(!Object.ReferenceEquals(r,null)); return r; }//Translate };//class ETranslator__TimeOnly__std__IsBetween //////////////////////////////////////////////////////////////////////////////// }//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Methods.Translators
34.408602
121
0.629688
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Code/Provider/Source/Basement/EF/Root/Query/Local/Expressions/Methods/Translators/TimeOnly/ETranslator__TimeOnly__std__IsBetween.cs
3,202
C#
using CSharpBinairoSolver; using CSharpBinairoSolver.ValidityCheckers; using NUnit.Framework; namespace SolverTests { [TestFixture] public class OnlyTwoSameNumbersCheckerTests { private OnlyTwoSameNumbersChecker _validator; [SetUp] public void Setup() { _validator = new OnlyTwoSameNumbersChecker(); } [Test] public void TestIsValidReturnsFalseIfThereAreThreeAdjacentZeroSlots() { var field = new[,] { {SlotStatus.Zero, SlotStatus.Zero, SlotStatus.Zero, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty} }; Assert.IsFalse(_validator.IsValid(new Playfield(field))); } [Test] public void TestIsValidReturnsFalseIfThereAreThreeAdjacentOneSlots() { var field = new[,] { {SlotStatus.One, SlotStatus.One, SlotStatus.One, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty} }; Assert.IsFalse(_validator.IsValid(new Playfield(field))); } [Test] public void TestIsValidReturnsTrueIfFieldIsEmpty() { var field = new[,] { {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty} }; Assert.IsTrue(_validator.IsValid(new Playfield(field))); } [Test] public void TestIsValidReturnsFalseIfColumnHasThreeAdjacentZeroSlots() { var field = new[,] { {SlotStatus.Zero, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Zero, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Zero, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty} }; Assert.IsFalse(_validator.IsValid(new Playfield(field))); } [Test] public void TestIsValidReturnsFalseIfColumnHasThreeAdjacentOneSlots() { var field = new[,] { {SlotStatus.Zero, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.One, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Zero, SlotStatus.Empty, SlotStatus.One, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.One, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty}, {SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty, SlotStatus.Empty} }; Assert.IsFalse(_validator.IsValid(new Playfield(field))); } } }
56.723404
125
0.665791
[ "MIT" ]
Hekku2/csharp-binairo-solver
CSharpBinairoSolver/SolverTests/OnlyTwoSameNumbersCheckerTests.cs
5,334
C#
using Tanks.Enemy; using UnityEngine; namespace Tanks.States { [RequireComponent(typeof(EnemyBehaviour))] public class TankState : MonoBehaviour { [HideInInspector] public EnemyBehaviour enemyBehaviour; public virtual void Awake() { enemyBehaviour = GetComponent<EnemyBehaviour>(); } public virtual void OnEnterState() { this.enabled = true; } public virtual void OnExitState() { this.enabled = false; } protected virtual void tick() { } } }
19.545455
61
0.531783
[ "MIT" ]
vijit101/BattleTankGame
Assets/Scripts/States/TankState.cs
647
C#
// Copyright 2020 New Relic, Inc. All rights reserved. // SPDX-License-Identifier: Apache-2.0 using System.Linq; using NewRelic.Agent.IntegrationTestHelpers; using NewRelic.Agent.IntegrationTestHelpers.RemoteServiceFixtures; using NewRelic.Testing.Assertions; using Xunit; using Xunit.Abstractions; namespace NewRelic.Agent.IntegrationTests.RequestHandling { [NetFrameworkTest] public abstract class NotFoundAndOptionsTests<T> : NewRelicIntegrationTest<T> where T : RemoteApplicationFixture { protected readonly T _fixture; public NotFoundAndOptionsTests(T fixture, ITestOutputHelper output) : base(fixture) { _fixture = fixture; _fixture.TestLogger = output; _fixture.Actions ( setupConfiguration: SetupApplication, exerciseApplication: ExerciseApplication ); _fixture.Initialize(); } protected virtual void SetupApplication() { } protected abstract void ExerciseApplication(); [Fact] public void Test() { var expectedTransaction = @"WebTransaction/StatusCode/404"; var unexpectedTransactions = new[] { @"WebTransaction/MVC/DefaultController/MissingAction", @"WebTransaction/MVC/MissingController", @"WebTransaction/ASP/{controller}/{action}/{id}" }; var metrics = _fixture.AgentLog.GetMetrics(); NrAssert.Multiple ( () => Assertions.MetricExists(new Assertions.ExpectedMetric { metricName = expectedTransaction, callCount = 2 }, metrics), () => Assertions.MetricsDoNotExist(unexpectedTransactions.Select(t => new Assertions.ExpectedMetric { metricName = t }), metrics) ); var badTransactionSamples = _fixture.AgentLog.GetTransactionSamples() .Where(sample => sample.Path != expectedTransaction); var badTransactionEvents = _fixture.AgentLog.GetTransactionEvents() .Where(te => !te.IntrinsicAttributes["name"].Equals(expectedTransaction)); NrAssert.Multiple ( () => Assert.Empty(badTransactionSamples), () => Assert.Empty(badTransactionEvents) ); } } }
33.985714
145
0.624632
[ "Apache-2.0" ]
SergeyKanzhelev/newrelic-dotnet-agent
tests/Agent/IntegrationTests/IntegrationTests/RequestHandling/BaseTests.cs
2,379
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x1017_d1fa-b0687082")] public void /* sys */ Method_1017_d1fa() { ii(0x1017_d1fa, 1); push(ecx); /* push ecx */ ii(0x1017_d1fb, 1); push(esi); /* push esi */ ii(0x1017_d1fc, 1); push(edi); /* push edi */ ii(0x1017_d1fd, 1); push(ebp); /* push ebp */ ii(0x1017_d1fe, 3); sub(esp, 0x10); /* sub esp, 0x10 */ ii(0x1017_d201, 1); push(eax); /* push eax */ ii(0x1017_d202, 2); mov(ebp, edx); /* mov ebp, edx */ ii(0x1017_d204, 5); call(/* sys */ 0x1019_46a5, 0x1_749c);/* call 0x101946a5 */ ii(0x1017_d209, 4); mov(memd[ss, esp + 8], eax); /* mov [esp+0x8], eax */ ii(0x1017_d20d, 2); test(eax, eax); /* test eax, eax */ ii(0x1017_d20f, 2); if(jnz(0x1017_d225, 0x14)) goto l_0x1017_d225;/* jnz 0x1017d225 */ ii(0x1017_d211, 5); mov(eax, 4); /* mov eax, 0x4 */ l_0x1017_d216: ii(0x1017_d216, 5); call(/* sys */ 0x1018_d3bf, 0x1_01a4);/* call 0x1018d3bf */ ii(0x1017_d21b, 5); mov(eax, 0xffff_ffff); /* mov eax, 0xffffffff */ ii(0x1017_d220, 5); jmp(0x1017_d2ed, 0xc8); goto l_0x1017_d2ed;/* jmp 0x1017d2ed */ l_0x1017_d225: ii(0x1017_d225, 2); test(al, 1); /* test al, 0x1 */ ii(0x1017_d227, 2); if(jnz(0x1017_d230, 7)) goto l_0x1017_d230;/* jnz 0x1017d230 */ ii(0x1017_d229, 5); mov(eax, 6); /* mov eax, 0x6 */ ii(0x1017_d22e, 2); jmp(0x1017_d216, -0x1a); goto l_0x1017_d216;/* jmp 0x1017d216 */ l_0x1017_d230: ii(0x1017_d230, 2); test(al, 0x40); /* test al, 0x40 */ ii(0x1017_d232, 2); if(jz(0x1017_d25c, 0x28)) goto l_0x1017_d25c;/* jz 0x1017d25c */ ii(0x1017_d234, 2); mov(ecx, ebx); /* mov ecx, ebx */ ii(0x1017_d236, 3); mov(ebx, memd[ss, esp]); /* mov ebx, [esp] */ ii(0x1017_d239, 2); mov(ah, 0x3f); /* mov ah, 0x3f */ ii(0x1017_d23b, 2); @int(0x21); /* int 0x21 */ ii(0x1017_d23d, 2); rcl(eax, 1); /* rcl eax, 1 */ ii(0x1017_d23f, 2); ror(eax, 1); /* ror eax, 1 */ ii(0x1017_d241, 2); mov(edi, eax); /* mov edi, eax */ ii(0x1017_d243, 2); mov(esi, eax); /* mov esi, eax */ ii(0x1017_d245, 2); test(eax, eax); /* test eax, eax */ ii(0x1017_d247, 6); if(jge(0x1017_d2eb, 0x9e)) goto l_0x1017_d2eb;/* jge 0x1017d2eb */ ii(0x1017_d24d, 2); xor(eax, eax); /* xor eax, eax */ ii(0x1017_d24f, 3); mov(ax, di); /* mov ax, di */ l_0x1017_d252: ii(0x1017_d252, 5); call(/* sys */ 0x1018_dbb7, 0x1_0960);/* call 0x1018dbb7 */ ii(0x1017_d257, 5); jmp(0x1017_d2ed, 0x91); goto l_0x1017_d2ed;/* jmp 0x1017d2ed */ l_0x1017_d25c: ii(0x1017_d25c, 4); mov(memd[ss, esp + 12], ebx); /* mov [esp+0xc], ebx */ ii(0x1017_d260, 2); xor(esi, esi); /* xor esi, esi */ l_0x1017_d262: ii(0x1017_d262, 4); mov(ecx, memd[ss, esp + 12]); /* mov ecx, [esp+0xc] */ ii(0x1017_d266, 3); mov(ebx, memd[ss, esp]); /* mov ebx, [esp] */ ii(0x1017_d269, 2); mov(edx, ebp); /* mov edx, ebp */ ii(0x1017_d26b, 2); mov(ah, 0x3f); /* mov ah, 0x3f */ ii(0x1017_d26d, 2); @int(0x21); /* int 0x21 */ ii(0x1017_d26f, 2); rcl(eax, 1); /* rcl eax, 1 */ ii(0x1017_d271, 2); ror(eax, 1); /* ror eax, 1 */ ii(0x1017_d273, 2); mov(ebx, eax); /* mov ebx, eax */ ii(0x1017_d275, 2); mov(edi, eax); /* mov edi, eax */ ii(0x1017_d277, 4); mov(memd[ss, esp + 4], eax); /* mov [esp+0x4], eax */ ii(0x1017_d27b, 2); test(eax, eax); /* test eax, eax */ ii(0x1017_d27d, 2); if(jge(0x1017_d286, 7)) goto l_0x1017_d286;/* jge 0x1017d286 */ ii(0x1017_d27f, 2); xor(eax, eax); /* xor eax, eax */ ii(0x1017_d281, 3); mov(ax, bx); /* mov ax, bx */ ii(0x1017_d284, 2); jmp(0x1017_d252, -0x34); goto l_0x1017_d252;/* jmp 0x1017d252 */ l_0x1017_d286: ii(0x1017_d286, 2); if(jz(0x1017_d2eb, 0x63)) goto l_0x1017_d2eb;/* jz 0x1017d2eb */ ii(0x1017_d288, 2); xor(edi, eax); /* xor edi, eax */ ii(0x1017_d28a, 2); mov(eax, ebp); /* mov eax, ebp */ ii(0x1017_d28c, 3); lea(ecx, memd[ds, ebx + ebp]); /* lea ecx, [ebx+ebp] */ ii(0x1017_d28f, 2); xor(edx, edx); /* xor edx, edx */ ii(0x1017_d291, 4); mov(memd[ss, esp + 16], ecx); /* mov [esp+0x10], ecx */ ii(0x1017_d295, 2); jmp(0x1017_d2c8, 0x31); goto l_0x1017_d2c8;/* jmp 0x1017d2c8 */ l_0x1017_d297: ii(0x1017_d297, 2); xor(ebx, ebx); /* xor ebx, ebx */ ii(0x1017_d299, 2); mov(bl, memb[ds, eax]); /* mov bl, [eax] */ ii(0x1017_d29b, 3); cmp(ebx, 0x1a); /* cmp ebx, 0x1a */ ii(0x1017_d29e, 2); if(jnz(0x1017_d2b8, 0x18)) goto l_0x1017_d2b8;/* jnz 0x1017d2b8 */ ii(0x1017_d2a0, 4); mov(ebp, memd[ss, esp + 4]); /* mov ebp, [esp+0x4] */ ii(0x1017_d2a4, 2); mov(edx, edi); /* mov edx, edi */ ii(0x1017_d2a6, 5); mov(ebx, 1); /* mov ebx, 0x1 */ ii(0x1017_d2ab, 2); sub(edx, ebp); /* sub edx, ebp */ ii(0x1017_d2ad, 3); mov(eax, memd[ss, esp]); /* mov eax, [esp] */ ii(0x1017_d2b0, 1); inc(edx); /* inc edx */ ii(0x1017_d2b1, 5); call(Definitions.sys_lseek, -0x11f); /* call 0x1017d197 */ ii(0x1017_d2b6, 2); jmp(0x1017_d2eb, 0x33); goto l_0x1017_d2eb;/* jmp 0x1017d2eb */ l_0x1017_d2b8: ii(0x1017_d2b8, 3); cmp(ebx, 0xd); /* cmp ebx, 0xd */ ii(0x1017_d2bb, 2); if(jz(0x1017_d2c6, 9)) goto l_0x1017_d2c6;/* jz 0x1017d2c6 */ ii(0x1017_d2bd, 2); mov(ebx, edx); /* mov ebx, edx */ ii(0x1017_d2bf, 1); inc(esi); /* inc esi */ ii(0x1017_d2c0, 2); mov(cl, memb[ds, eax]); /* mov cl, [eax] */ ii(0x1017_d2c2, 1); inc(edx); /* inc edx */ ii(0x1017_d2c3, 3); mov(memb[ds, ebx + ebp], cl); /* mov [ebx+ebp], cl */ l_0x1017_d2c6: ii(0x1017_d2c6, 1); inc(eax); /* inc eax */ ii(0x1017_d2c7, 1); inc(edi); /* inc edi */ l_0x1017_d2c8: ii(0x1017_d2c8, 4); cmp(eax, memd[ss, esp + 16]); /* cmp eax, [esp+0x10] */ ii(0x1017_d2cc, 2); if(jb(0x1017_d297, -0x37)) goto l_0x1017_d297;/* jb 0x1017d297 */ ii(0x1017_d2ce, 4); mov(ecx, memd[ss, esp + 12]); /* mov ecx, [esp+0xc] */ ii(0x1017_d2d2, 4); mov(ah, memb[ss, esp + 9]); /* mov ah, [esp+0x9] */ ii(0x1017_d2d6, 2); sub(ecx, edx); /* sub ecx, edx */ ii(0x1017_d2d8, 2); add(ebp, edx); /* add ebp, edx */ ii(0x1017_d2da, 4); mov(memd[ss, esp + 12], ecx); /* mov [esp+0xc], ecx */ ii(0x1017_d2de, 3); test(ah, 0x20); /* test ah, 0x20 */ ii(0x1017_d2e1, 2); if(jnz(0x1017_d2eb, 8)) goto l_0x1017_d2eb;/* jnz 0x1017d2eb */ ii(0x1017_d2e3, 2); test(ecx, ecx); /* test ecx, ecx */ ii(0x1017_d2e5, 6); if(jnz(0x1017_d262, -0x89)) goto l_0x1017_d262;/* jnz 0x1017d262 */ l_0x1017_d2eb: ii(0x1017_d2eb, 2); mov(eax, esi); /* mov eax, esi */ l_0x1017_d2ed: ii(0x1017_d2ed, 3); add(esp, 0x14); /* add esp, 0x14 */ ii(0x1017_d2f0, 1); pop(ebp); /* pop ebp */ ii(0x1017_d2f1, 1); pop(edi); /* pop edi */ ii(0x1017_d2f2, 1); pop(esi); /* pop esi */ ii(0x1017_d2f3, 1); pop(ecx); /* pop ecx */ ii(0x1017_d2f4, 1); ret(); /* ret */ } } }
77.288
101
0.428838
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-1017-d1fa-sys.cs
9,661
C#
using System; using UnityEngine; public class ShakeCamera : MonoBehaviour { public float Magnitude = 1f; public float Duration = 1f; public static ShakeCamera Shake(float magnitude, float duration) { OrbitGameObject orbitGameObject = (OrbitGameObject)UnityEngine.Object.FindObjectOfType(typeof(OrbitGameObject)); ShakeCamera shakeCamera = orbitGameObject.gameObject.AddComponent<ShakeCamera>(); shakeCamera.Magnitude = magnitude; shakeCamera.Duration = duration; return shakeCamera; } private void Update() { this.Duration -= Time.deltaTime; if (this.Duration < 0f) { UnityEngine.Object.Destroy(this); } OrbitGameObject component = base.gameObject.GetComponent<OrbitGameObject>(); if (component) { component.ShakeVal.y = Mathf.Sin(1000f * Time.time) * this.Duration * this.Magnitude; } } }
26.242424
115
0.725173
[ "MIT" ]
corefan/mobahero_src
ShakeCamera.cs
866
C#
using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; public class DialogSequence : EventManager { [SerializeField] private bool hasOnceOnlyDialog; [SerializeField] private bool EndsWithUI; [SerializeField] private bool InitiateOnTrigger; [SerializeField] private bool Triggerable; [SerializeField] private bool onceOnly; [SerializeField] private bool doesNotManipulatePauseState; private bool noLongerTriggerable = false; public bool NoLongerTriggerable { get { return noLongerTriggerable; } } public List<Dialog> dialogs; [SerializeField] private List<EventSelector> events; [Header("If does not have once only dialog")] public List<Dialog> newDialogs; [SerializeField] private List<EventSelector> newEvents; private Queue<Dialog> dialogQueue; private Queue<EventSelector> eventQueue; public enum Actions { doNothing }; void Start() { dialogQueue = new Queue<Dialog>(); eventQueue = new Queue<EventSelector>(); QueueOriginal(); } public static DialogSequence Default() { DialogSequence dialogSeqeuence = new DialogSequence(); dialogSeqeuence.SetEventSelector(EventSelector.doNothing); return dialogSeqeuence; } public void InitiateDialog() { DialogManager.Instance.InitiateDialog(dialogQueue.Dequeue(), this); // GameManager.Instance.PauseGame(true); GameManager.Instance.PausePlayerInput(true); if(transform.parent.GetComponent<Animator>()) transform.parent.GetComponent<Animator>().SetBool("Talk", true); if(GetComponent<Shop>() != null) { GameManager.Instance.currentShopItems = GetComponent<Shop>().shopItems; } if(onceOnly) noLongerTriggerable = true; } void OnTriggerEnter(Collider other) { if(!InitiateOnTrigger) return; if (other.gameObject.tag == Tags.PLAYER && !DialogManager.Instance.isDialogRunning) { if(!GameManager.Instance.PlayerInGameInputDisabled) { InitiateDialog(); DialogManager.Instance.UnloadDialog(); UIManager.Instance.DisableInteractionText(); } } } void OnTriggerStay(Collider other) { if(noLongerTriggerable) return; if(InitiateOnTrigger) return; if (other.gameObject.tag == Tags.PLAYER && !DialogManager.Instance.isDialogRunning) { if(!GameManager.Instance.PlayerInGameInputDisabled) { if (Input.GetKeyDown(KeyCode.E) && Triggerable) { InitiateDialog(); AudioManager.Instance.access.Play(); UIManager.Instance.DisableInteractionText(); } } } } public void SetEventSelector(EventSelector select) { eventQueue = new Queue<EventSelector>(); eventQueue.Enqueue(select); } public void DoAfterDialogEvent() { EventManager.GetDelegate(eventQueue.Dequeue())(); if(transform.parent.GetComponent<Animator>()) transform.parent.GetComponent<Animator>().SetBool("Talk", false); if(dialogQueue.Count > 0) { InitiateDialog(); DialogManager.Instance.UnloadDialog(); } else { if(!doesNotManipulatePauseState) { GameManager.Instance.PausePlayerInput(EndsWithUI); GameManager.Instance.PauseUIInputs(false); GameManager.Instance.PauseEnemies(false); GameManager.Instance.MouseMovementActive = true; if(!EndsWithUI) { GameManager.Instance.PauseGame(false); UIManager.Instance.Blur(false); if(EventManager.currentSpellCraftArea) EventManager.currentSpellCraftArea = null; } else { UIManager.Instance.ToggleMainUI(false); } } UIManager.Instance.Blur(false); ReQueueDialog(); } } private void ReQueueDialog() { if(hasOnceOnlyDialog) { foreach(Dialog dialog in newDialogs) dialogQueue.Enqueue(dialog); foreach (EventSelector e in newEvents) eventQueue.Enqueue(e); } else { QueueOriginal(); } } private void QueueOriginal() { foreach(Dialog dialog in dialogs) dialogQueue.Enqueue(dialog); foreach (EventSelector e in events) eventQueue.Enqueue(e); } }
27.342541
91
0.584158
[ "MIT" ]
TheRayOfSeasons/The-Adventures-of-Inday-Scripts
Dialogue/DialogSequence.cs
4,951
C#
using System.Linq; using NUnit.Framework; using SIL.Extensions; namespace SIL.WritingSystems.Tests { [TestFixture] public class LanguageLookupTests { [Test] public void SuggestLanguages_EmptyString_ReturnsNothing() { var lookup = new LanguageLookup(); Assert.That(lookup.SuggestLanguages("").Count(), Is.EqualTo(0)); } [Test] public void SuggestLanguages_Asterisk_ReturnsEverything() { var lookup = new LanguageLookup(); Assert.Greater(lookup.SuggestLanguages("*").Count(), 1000); } [Test] public void SuggestLanguages_LargeMispelling_StillFinds() { var lookup = new LanguageLookup(); Assert.That(lookup.SuggestLanguages("angrish").Any(), Is.True); } [Test] public void SuggestLanguages_Thai_ReturnsLocalizedNameAsFirstChoiceLanguage() { /* tha KH D Thai Koh Kong tha KH D Thai Norkor Raja tha KH DA Siam Nokor tha KH DA Siam Trang tha KH L Thai tha TH D Khorat Thai tha TH DA Korat tha TH DA Thaikorat tha TH L Thai tha TH LA Central Tai tha TH LA Siamese tha TH LA Standard Thai tha TH LA Thaiklang */ var lookup = new LanguageLookup(); LanguageInfo thai = lookup.SuggestLanguages("thai").First(); Assert.That(thai.Names[0], Is.EqualTo("Thai")); Assert.That(thai.Names[1], Is.EqualTo("ไทย")); } [Test] [Ignore("This test is not longer valid because additional regions come from CLDR and there are many for Thailand")] // 2018-11-01 public void SuggestLanguages_Thai_TwoCountries() { /* tha KH D Thai Koh Kong tha KH D Thai Norkor Raja tha KH DA Siam Nokor tha KH DA Siam Trang tha KH L Thai tha TH D Khorat Thai tha TH DA Korat tha TH DA Thaikorat tha TH L Thai tha TH LA Central Tai tha TH LA Siamese tha TH LA Standard Thai tha TH LA Thaiklang */ var lookup = new LanguageLookup(); LanguageInfo languageInfo = lookup.SuggestLanguages("thai").First(); Assert.That(languageInfo.LanguageTag, Is.EqualTo("th")); Assert.That(languageInfo.Countries, Is.EqualTo(new[] {"Cambodia", "Thailand"})); } /// <summary> /// test that we're delivering 2 letter codes when available /// </summary> [Test] public void SuggestLanguages_Thai_CodeIsJustTwoLetters() { var lookup = new LanguageLookup(); var selection = lookup.SuggestLanguages("thai"); LanguageInfo languageInfo = selection.First(); Assert.That(languageInfo.LanguageTag, Is.EqualTo("th")); } /// <summary> /// languages are entered once for every country, so we need to be careful not to list "English, English, English" in the names /// </summary> [Test] public void SuggestLanguages_English_EnglishNotInTheAlternativeNames() { var lookup = new LanguageLookup(); //messed up case is intentional var search = lookup.SuggestLanguages("english"); Assert.That(search.First().Names.Count(s => s == "English"), Is.EqualTo(1)); } [TestCase("en", "United States")] // a typical result [TestCase("ro", "Romania")] // even more typical (and different from langInfo.Countries.First()). [TestCase("zrp", "France")] // a three-letter code that has a region [TestCase("xak", "Venezuela")] // two special cases, the countries currently without regions and with >1 country [TestCase("itd", "Indonesia")] [TestCase("fuv-Arab", "Nigeria")] // language code with script with country [TestCase("zh-Hans", "China")] // TODO want an example language code with script without country [TestCase("qaa", "")] // unknown language, no country [TestCase("bua", "Russian Federation")] // no region, but does have a unique country public void FindsCorrectPrimaryCountry(string code, string primaryCountry) { var lookup = new LanguageLookup(); var lang = lookup.GetLanguageFromCode(code); Assert.That(lang.PrimaryCountry, Is.EqualTo(primaryCountry)); } /// <summary> /// JT: At the time I wrote these tests, only the indicated two languages had more than one /// country and lacked a region specification to disambigute the primary country. /// This test is designed to catch a change in that situation when the language data /// tables are updated. /// /// DG: LanguageData.exe will say which languages don't have a unique primary country /// see LanguageDataIndex() /// </summary> [Test] public void AllExpectedLanguagesHaveUniquePrimaryCountries() { var languagesWithoutRegions = new LanguageLookup().LanguagesWithoutRegions(); var languagesWithAmbiguousPrimaryCountry = languagesWithoutRegions.Where(l => l.Countries.Count() > 1); Assert.IsEmpty(languagesWithAmbiguousPrimaryCountry); } [Test] public void SuggestLanguages_GivenUnambigous3LetterCode_ReturnsLanguage() { var lookup = new LanguageLookup(); //messed up case is intentional Assert.That(lookup.SuggestLanguages("eTR").First().Names.First().Contains("Edolo"), Is.True); } [Test] public void SuggestLanguages_GivenPNGLanguage_ReturnsPNGCountryName() { var lookup = new LanguageLookup(); //messed up case is intentional Assert.That(lookup.SuggestLanguages("eTR").First().Countries, Is.EqualTo(new[] {"Papua New Guinea"})); } [Test] public void SuggestLanguages_StartOfName_ReturnsManyLanguages() { var lookup = new LanguageLookup(); //messed up case is intentional Assert.Greater(1000, lookup.SuggestLanguages("eastern").Count()); } [Test] public void SuggestLanguages_3LetterCode_ResultIncludesAlternateLanguageNames() { var lookup = new LanguageLookup(); LanguageInfo[] languages = lookup.SuggestLanguages("ana").ToArray(); Assert.True(languages.Any(l => l.LanguageTag == "ana")); Assert.True(languages.Any(l => l.Names.Contains("Aguanunga"))); Assert.True(languages.Any(l => l.Names.Contains("Andaki"))); Assert.True(languages.Any(l => l.Names.Contains("Churuba"))); } [Test] public void SuggestLanguages_NonPrimary_ResultIncludesAlternateLanguageNames() { var lookup = new LanguageLookup(); //messed up case and extra spaces are is intentional LanguageInfo[] languages = lookup.SuggestLanguages(" ChuRUba ").ToArray(); Assert.True(languages.Any(l => l.LanguageTag == "ana")); Assert.True(languages.Any(l => l.Names.Contains("Aguanunga"))); Assert.True(languages.Any(l => l.Names.Contains("Andaki"))); Assert.True(languages.Any(l => l.Names.Contains("Churuba"))); } [Test] // Akan is a macrolanguage so make sure we know that public void SuggestLanguages_Akan_DoesnotCrash() { var lookup = new LanguageLookup(); LanguageInfo[] languages = lookup.SuggestLanguages("a").ToArray(); Assert.True(languages.Any(l => l.LanguageTag == "ak")); Assert.True(languages.Any(l => l.LanguageTag == "akq")); //Assert.True(languages.Any(l => l.Names.Contains("Akuapem"))); // 2018-10-26 Dialect name so not found any more Assert.True(languages.Any(l => l.Names.Contains("Ak"))); Assert.True(languages.Any(l => l.Names.Contains("Akan"))); // Assert.True(languages.Any(l => l.Names.Contains("Fanti"))); // 2018-10-26 Dialect name so not found any more languages = lookup.SuggestLanguages("ak").ToArray(); Assert.True(languages.Any(l => l.LanguageTag == "ak")); Assert.True(languages.Any(l => l.LanguageTag == "akq")); //Assert.True(languages.Any(l => l.Names.Contains("Asante"))); // 2018-10-26 Dialect name so not found any more Assert.True(languages.Any(l => l.Names.Contains("Ak"))); Assert.True(languages.Any(l => l.Names.Contains("Akan"))); //Assert.True(languages.Any(l => l.Names.Contains("Fanti"))); // 2018-10-26 Dialect name so not found any more } [Test] public void SuggestLanguages_ByCountry_Matches() { var lookup = new LanguageLookup(); var languages = lookup.SuggestLanguages("United States"); Assert.That(languages, Has.Member(lookup.GetLanguageFromCode("en"))); Assert.That(languages, Has.Member(lookup.GetLanguageFromCode("es"))); languages = lookup.SuggestLanguages("Fran"); // prefix of 'France' Assert.That(languages, Has.Member(lookup.GetLanguageFromCode("fr"))); languages = lookup.SuggestLanguages("Russian"); Assert.That(languages, Has.Member(lookup.GetLanguageFromCode("bua"))); // macro-language in Russian Federation languages = lookup.SuggestLanguages("?"); Assert.That(languages, Has.No.Member(lookup.GetLanguageFromCode("qaa"))); Assert.That(languages, Has.No.Member(lookup.GetLanguageFromCode("mn-Mong"))); } [Test] public void SuggestLanguages_LanguageHasPejorativeAlternativeNames_FilteredOut() { var lookup = new LanguageLookup(); var languages = lookup.SuggestLanguages("Degexit’an").ToArray(); Assert.AreEqual("ing", languages[0].LanguageTag); Assert.True(languages.Any(l => l.Names.Contains("Degexit’an"))); Assert.True(languages.Any(l => l.Names.Contains("Deg Xinag"))); Assert.True(languages.Any(l => l.Names.Contains("Deg Xit’an"))); Assert.AreEqual(3, languages[0].Names.Count, "2 of the 5 names are pejorative and should not be listed"); } /// <summary> /// This is a result of finding that some of the alternative names, in Nov 2016, were *not* marked as pejorative but actually were. /// These may be fixed in the Ethnologue over time, but it was requested that we just remove all alternative names for now. /// </summary> [Test] public void SuggestLanguages_LanguageIsInEthiopia_ShowOnlyOfficialNames() { var lookup = new LanguageLookup(); var languages = lookup.SuggestLanguages("Wolaytta").ToArray(); Assert.True(languages.Any(l => l.Names.Contains("ወላይታቱ"))); Assert.True(languages.Any(l => l.Names.Contains("Wolaytta"))); Assert.AreEqual(2, languages[0].Names.Count, "Should list only the first name in the IANA subtag registry for Ethiopian languages, plus local name."); languages = lookup.SuggestLanguages("Qimant").ToArray(); Assert.True(languages.Any(l => l.Names.Contains("Qimant"))); Assert.AreEqual(1, languages[0].Names.Count, "Should only list the first name in the IANA subtag registry for Ethiopian languages."); } /// <summary> /// We have been asked to temporarily suppress these three codes for Ethiopia, until the Ethnologue is changed. /// </summary> [Test] public void SuggestLanguages_LanguageIsOromo_DoNotShowRelatedLanguages() { var lookup = new LanguageLookup(); var languages = lookup.SuggestLanguages("Oromo").ToArray(); Assert.True(languages.All(l => l.DesiredName == "Oromo")); Assert.True(languages.All(l => l.LanguageTag.StartsWith("om")), "We should be suppressing gax, hae, gaz"); languages = lookup.SuggestLanguages("gax").ToArray(); Assert.False(languages.Any(l => l.LanguageTag == "gax")); languages = lookup.SuggestLanguages("gaz").ToArray(); Assert.False(languages.Any(l => l.LanguageTag == "gaz")); languages = lookup.SuggestLanguages("hae").ToArray(); Assert.False(languages.Any(l => l.LanguageTag == "hae")); } /// <summary> /// We should not find old code for Kataang (deprecated Jan 2017) /// but find new ones instead /// </summary> [Test] public void SuggestLanguages_KataangNewCodes() { var lookup = new LanguageLookup(); var languages = lookup.SuggestLanguages("Kataang").ToArray(); Assert.True(languages.Any(l => l.LanguageTag == "ncq")); Assert.True(languages.Any(l => l.LanguageTag == "sct")); Assert.False(languages.Any(l => l.LanguageTag == "kgd")); } /// <summary> /// We should not suggest macro languages unless they are marked as such so that they can be filtered out. /// </summary> [Test] [Ignore("Macrolanguages not used now")] // 2018-10-26 public void SuggestLanguages_CanFilterMacroLanguages() { var lookup = new LanguageLookup(); Assert.That(lookup.SuggestLanguages("macrolanguage").Count(), Is.EqualTo(0)); var languages = lookup.SuggestLanguages("zza").ToArray(); Assert.True(languages.Any(l => l.LanguageTag == "zza" && l.IsMacroLanguage)); } /// <summary> /// We should not suggest deprecated tags for languages. /// </summary> [Test] public void SuggestLanguages_DoesNotSuggestDeprecatedTags() { var lookup = new LanguageLookup(); var languages = lookup.SuggestLanguages("dzd").ToArray(); Assert.False(languages.Any(l => l.LanguageTag == "dzd")); languages = lookup.SuggestLanguages("yiy").ToArray(); Assert.False(languages.Any(l => l.LanguageTag == "yiy")); languages = lookup.SuggestLanguages("jeg").ToArray(); Assert.False(languages.Any(l => l.LanguageTag == "jeg")); } /// <summary> /// We should not suggest language collections. /// </summary> [Test] public void SuggestLanguages_DoesNotSuggestLanguageCollections() { var lookup = new LanguageLookup(); var languages = lookup.SuggestLanguages("urj").ToArray(); Assert.False(languages.Any(l => l.LanguageTag == "urj")); languages = lookup.SuggestLanguages("aav").ToArray(); Assert.False(languages.Any(l => l.LanguageTag == "aav")); } /// <summary> /// We should now be able to search for 3 letter codes e.g. nld for languages that have 2 letter codes e.g. nl /// </summary> [Test] public void SuggestLanguages_CanFind3LetterCodesForLanguagesWith2LetterCodes() { var lookup = new LanguageLookup(); var languages = lookup.SuggestLanguages("nld").ToArray(); Assert.True(languages.Any(l => l.DesiredName == "Dutch")); } /// <summary> /// We should now be able to find codes that are in iana registry but not Ethnologue /// </summary> [Test] [Ignore("Dialects are not included in the language data any more so this will not work until they are included again")] // 2018-10-26 public void SuggestLanguages_CanFindValidTagsThatAreNotInEthnologue() { var lookup = new LanguageLookup(); var languages = lookup.SuggestLanguages("fat").ToArray(); Assert.True(languages.Any(l => l.DesiredName == "Fanti")); languages = lookup.SuggestLanguages("twi").ToArray(); Assert.True(languages.Any(l => l.DesiredName == "Twi")); } [Test] public void GetLanguageFromCode_CodeNotFound_ReturnsNull() { var lookup = new LanguageLookup(); Assert.IsNull(lookup.GetLanguageFromCode("foobar")); } [Test] public void GetLanguageFromCode_CodeFound_ReturnsMatchingLanguageInfo() { var lookup = new LanguageLookup(); Assert.AreEqual("etr", lookup.GetLanguageFromCode("etr").LanguageTag); Assert.AreEqual("English", lookup.GetLanguageFromCode("en").DesiredName); } [Test] public void SuggestLanguages_HandlesApostrophe() { var lookup = new LanguageLookup(); var languages = lookup.SuggestLanguages("K\u2019i").ToArray(); Assert.True(languages.Any(l => l.DesiredName == "K\u2019iche\u2019")); languages = lookup.SuggestLanguages("K'i").ToArray(); Assert.True(languages.Any(l => l.DesiredName == "K\u2019iche\u2019")); } /// <summary> /// We have a special case where we want to return all sign languages when you type "sign", or something like that. /// </summary> [Test] public void SuggestLanguages_SearchingForSign_ReturnsSignLanguages() { var lookup = new LanguageLookup(); foreach (var wayToSaySign in new[] {"SiGn", "SIGNES ", "señas", "sign language " }) { var languages = lookup.SuggestLanguages(wayToSaySign).ToArray(); var countOfPossibleSignLangsYouWouldGetWithThatSearchTerm = languages.Select(li => li.Names.AsQueryable().Any(n => n.ToLowerInvariant().Contains("sign")) ).Count(); Assert.GreaterOrEqual(countOfPossibleSignLangsYouWouldGetWithThatSearchTerm, 140); // was 145 in October 2018. So if it's giving us at least 140, it's probably doing the right thing } } } }
39.655696
153
0.703971
[ "MIT" ]
JamesPrabu/libpalaso
SIL.WritingSystems.Tests/LanguageLookupTests.cs
15,687
C#
using System.Collections; using System.Collections.Generic; using Assets.Scripts.Game.GangWu.Mgr; using com.yxixia.utile.YxDebug; using Sfs2X.Entities.Data; using UnityEngine; using YxFramwork.Common; using YxFramwork.ConstDefine; using YxFramwork.Framework.Core; using YxFramwork.Manager; namespace Assets.Scripts.Game.GangWu.Main { public class GangWuGameManager : YxGameManager { public ResultMgr ResultMgr; /// <summary> /// 公共牌 /// </summary> [HideInInspector] public List<PokerCard> PublicPokers = new List<PokerCard>(); public RModelMgr RModelMgr; public HistoryResultMgr HistoryResultMgr; public BetMgr BetMgr; public SpeakMgr SpeakMgr; public MenuMgr MenuMgr; public EffectsMgr EffectsMgr; public DealerMgr DealerMgr; protected override void OnStart() { base.OnStart(); GetComponent<UIRoot>().scalingStyle = Application.platform == RuntimePlatform.WindowsPlayer ? UIRoot.Scaling.Constrained : UIRoot.Scaling.ConstrainedOnMobiles; } public override void OnGetGameInfo(ISFSObject gameInfo) { var gdata = App.GetGameData<GangwuGameData>(); Reset(); //初始化玩家信息 InitUser(gameInfo); //初始化房间信息 InitRoom(gameInfo); gdata.IsGameInfo = true; YxWindowManager.HideWaitFor(); } /// <summary> /// 初始化用户信息 /// </summary> /// <param name="gameInfo"></param> public void InitUser(ISFSObject gameInfo) { var gdata = App.GetGameData<GangwuGameData>(); List<int> betList = new List<int>(); ISFSObject selfSfs = gameInfo.GetSFSObject(RequestKey.KeyUser); InitSomeOne(selfSfs); //初始化部分数据 //初始化个人手牌 var selfPanel = gdata.GetPlayer<PlayerPanel>(); if (selfSfs.ContainsKey("cards")) { int[] selfCards = selfSfs.GetIntArray("cards"); if (selfCards.Length > 0) { selfPanel.UserBetPoker.LeftCardValue = selfCards[0]; selfPanel.UserBetPoker.RightCardValue = selfCards[1]; } } //初始化下注信息 if (selfSfs.ContainsKey("curRoundBet")) { var selfBet = selfSfs.GetInt("curRoundBet"); betList.Add(selfBet); } ISFSArray users = gameInfo.GetSFSArray(RequestKey.KeyUserList); foreach (ISFSObject user in users) { InitSomeOne(user); if (!user.ContainsKey("curRoundBet")) continue; int bet = user.GetInt("curRoundBet"); betList.Add(bet); } if (!gameInfo.ContainsKey("totalBet")) return; int ttBet = gameInfo.GetInt("totalBet"); foreach (var oneBet in betList) { ttBet -= oneBet; } BetMgr.BigBetStack.SetBet(ttBet); } public void InitSomeOne(ISFSObject info) { var gdata = App.GetGameData<GangwuGameData>(); int userSeat = info.GetInt(RequestKey.KeySeat); PlayerPanel onePanel = gdata.GetPlayer<PlayerPanel>(userSeat, true); onePanel.SetPlayerReadyState(info.GetBool(RequestKey.KeyState)); foreach (Transform tran in onePanel.PokersTrans) { tran.DestroyChildren(); } if (info.ContainsKey("cards")) { int[] selfCards = info.GetIntArray("cards"); if (selfCards.Length > 0) { onePanel.UserBetPoker.LeftCardValue = selfCards[0]; onePanel.UserBetPoker.RightCardValue = selfCards[1]; DealerMgr.DealOnesPokers(selfCards, onePanel.PokersTrans, gdata.SelfSeat); } } if (info.ContainsKey("curRoundBet")) { var selfBet = info.GetInt("curRoundBet"); onePanel.BetMoney = selfBet; } } /// <summary> /// 初始化 房间 /// </summary> public void InitRoom(ISFSObject gameInfo) { if (gameInfo.ContainsKey("rid") && RModelMgr != null) { RModelMgr.ShowRoomInfo(gameInfo); } var gdata = App.GetGameData<GangwuGameData>(); if (gdata.IsGameStart) { //当前谁说话 if (gameInfo.ContainsKey("current")) { App.GetGameManager<GangWuGameManager>().Speaker(gameInfo.GetInt("current")); } //下过的筹码 除当前轮 int allBetV = 0; foreach (ISFSObject user in gameInfo.GetSFSArray("users")) { PlayerPanel player = gdata.GetPlayer<PlayerPanel>(user.GetInt("seat"), true); int xz = user.GetInt("ttxz") - user.GetInt("rndGold"); allBetV += xz; if (user.GetLong("ttgold") <= 0 && player.ReadyState) { player.CurGameType = PlayerGameType.AllIn; } //服务器给的的棋牌 if (user.GetInt("txstate") == 2) { player.CurGameType = PlayerGameType.Fold; } player.PlayerBet(user.GetInt("rndGold"), false); } //下过筹码才有收 if (allBetV > 0) { BetMgr.CollectBetValue(); } if (gameInfo.ContainsKey("opData")) { var sfs = gameInfo.GetSFSObject("opData"); var type = sfs.GetInt(RequestKey.KeyType); App.GetGameManager<GangWuGameManager>().GameResponseStatus(type, sfs); } } BetMgr.SetChipsTime(); //设置筹码倍数 } public override void OnGetRejoinInfo(ISFSObject gameInfo) { } public override void GameStatus(int status, ISFSObject info) { } public override void GameResponseStatus(int type, ISFSObject response) { var gdata = App.GetGameData<GangwuGameData>(); if (!gdata.IsGameInfo) { YxDebug.LogError("GameInfo还没有初始化!!"); return; } switch ((GameRequestType)type) { case GameRequestType.Bet: if (response.ContainsKey("seat")) { int bseat = response.GetInt("seat"); int bgold = response.GetInt("gold"); PlayerPanel onePanel = gdata.GetPlayer<PlayerPanel>(bseat, true); if (bgold > 0) { if (bgold + onePanel.BetMoney == SpeakMgr.MaxBetNum) { onePanel.ShowGameType("call"); } else if (onePanel.Info != null && bgold == onePanel.Coin) { onePanel.CurGameType = PlayerGameType.AllIn; onePanel.ShowGameType("allIn"); } else { onePanel.ShowGameType(""); } } else { onePanel.ShowGameType("seePoker"); } onePanel.PlayerBet(bgold); if (onePanel.CurGameType != PlayerGameType.AllIn && onePanel.BetMoney > SpeakMgr.MaxBetNum) { Facade.Instance<MusicManager>().Play("addBet"); onePanel.ShowGameType(string.Empty); } else if (onePanel.CurGameType != PlayerGameType.AllIn && onePanel.BetMoney == SpeakMgr.MaxBetNum) { Facade.Instance<MusicManager>().Play(bgold > 0 ? "call" : "seePoker"); } //设置最大下注 SpeakMgr.MaxBetNum = onePanel.BetMoney > SpeakMgr.MaxBetNum ? onePanel.BetMoney : SpeakMgr.MaxBetNum; if (bseat == gdata.SelfSeat) { SpeakMgr.ShowAuto(); SpeakMgr.AddBetSum = 0; } } //包含users说明游戏开始 else if (response.ContainsKey("users")) { ++gdata.CurRound; int[] beginSeats = response.GetIntArray("users"); int beginBetGold = response.GetInt("guoBet"); gdata.Ante = response.GetInt("curante"); gdata.IsGameStart = true; gdata.IsPlayed = true; foreach (int seat in beginSeats) { PlayerPanel panel = gdata.GetPlayer<PlayerPanel>(seat, true); if (panel.Info != null) { panel.SetPlayerReadyState(true); panel.PlayerBet(beginBetGold); } } HistoryResultMgr.CreateHistoryItem(beginSeats); //隐藏准备按钮 gdata.GetPlayer<SelfPlayerPanel>().OnGameStart(); } break; case GameRequestType.Fold: int fseat = response.GetInt("seat"); PlayerPanel foldPanel = gdata.GetPlayer<PlayerPanel>(fseat, true); foldPanel.CurGameType = PlayerGameType.Fold; foldPanel.Mask.SetActive(true); foldPanel.BetLabel.gameObject.SetActive(foldPanel.BetMoney > 0); foldPanel.ShowGameType("fold"); if (fseat == gdata.SelfSeat) { SpeakMgr.ShowNothing(); } break; case GameRequestType.Card: if (response.ContainsKey("selfCard")) { int[] selfCards = response.GetIntArray("selfCard"); if (selfCards.Length > 0) { gdata.GetPlayer<PlayerPanel>().UserBetPoker.LeftCardValue = selfCards[0]; } } if (response.ContainsKey("cards")) { int[] cardSeats = response.GetIntArray("seats"); int[] cards = response.GetIntArray("cards"); int cardCount = response.GetInt("cardCount"); gdata.CardCount = cardCount; //如果为cardCount是2,则是第一轮发牌,需要先发一轮暗牌 if (cardCount <= 2) { int[] tempCards = new int[cardSeats.Length]; for (int i = 0; i < cardSeats.Length; i++) { if (cardSeats[i] == gdata.SelfSeat) { tempCards[i] = gdata.GetPlayer<PlayerPanel>().UserBetPoker.LeftCardValue; } } DealerMgr.BeginBigDeal(tempCards, cardSeats, 0); } DealerMgr.BeginBigDeal(cards, cardSeats, cardCount - 1); //初始化玩家当前状态信息 foreach (int seat in cardSeats) { gdata.GetPlayer<PlayerPanel>(seat, true).ShowGameType(string.Empty); } } //每轮开始清除最大下注 SpeakMgr.MaxBetNum = 0; SpeakMgr.AddBetSum = 0; BetMgr.CollectBet(); foreach (var yxBaseGamePlayer in gdata.PlayerList) { var panel = (PlayerPanel)yxBaseGamePlayer; panel.BetMoney = 0; panel.BetLabel.text = panel.BetMoney.ToString(); } SpeakMgr.BetRemenber.Clear(); break; case GameRequestType.Result: gdata.AllocateFour = false; //当接到结算时,由于要排除由于手机卡顿或者由于有玩家手上筹码过少,引起的直接结算,这里将手牌取消动画显示 DealerMgr.OnResult(); ResultMgr.OnGameResult(response.GetSFSArray("result")); StartCoroutine(ShowResultView()); DoResult(response); HistoryResultMgr.GetHistoryInfo(response); YxClockManager.StopWaitPlayer(); break; case GameRequestType.BetSpeak: int betSpeakSeat = response.GetInt("seat"); var betSpeaker = gdata.GetPlayer<PlayerPanel>(betSpeakSeat, true); if (!betSpeaker.ReadyState) return; gdata.AllocateFour = response.ContainsKey("allocateFour") && response.GetBool("allocateFour"); gdata.SpeakCd = response.GetInt("cd"); betSpeaker.ShowGameType(string.Empty); Speaker(betSpeakSeat, response.GetInt("cd")); if (betSpeakSeat == gdata.SelfSeat) { betSpeaker.BetLabel.gameObject.SetActive(true); SpeakMgr.ShowSpeak(); } break; case GameRequestType.FollowSpeak: int followSpeakSeat = response.GetInt("seat"); var followSpeaker = gdata.GetPlayer<PlayerPanel>(followSpeakSeat, true); if (!followSpeaker.ReadyState) return; gdata.SpeakCd = response.GetInt("cd"); gdata.AllocateFour = response.GetBool("allocateFour"); followSpeaker.ShowGameType(string.Empty); Speaker(followSpeakSeat, response.GetInt("cd")); if (followSpeakSeat == gdata.SelfSeat) { followSpeaker.BetLabel.gameObject.SetActive(true); SpeakMgr.ShowSpeak(); } break; case GameRequestType.AllowReady: gdata.AllocateFour = false; gdata.IsGameStart = false; _waitResult = false; //允许显示结算 YxClockManager.StopWaitPlayer(); break; default: YxDebug.Log("不存在的服务器交互!"); break; } } private bool _waitResult = true; IEnumerator ShowResultView() { yield return new WaitForSeconds(1.5f); while (_waitResult) { yield return new WaitForFixedUpdate(); } _waitResult = true; ResultMgr.ShowResultView(); Reset(); } /// <summary> /// 港式五张的结算方法 /// </summary> public void DoResult(ISFSObject data) { var gdata = App.GetGameData<GangwuGameData>(); ISFSArray isfsArr = data.GetSFSArray("result"); List<Transform> wheres = new List<Transform>(); foreach (ISFSObject isfsObj in isfsArr) { int win = isfsObj.GetInt("win"); int seat = isfsObj.GetInt("seat"); PlayerPanel panel = gdata.GetPlayer<PlayerPanel>(seat, true); //标记赢家的位置信息 if (panel.Info != null) { panel.Coin = isfsObj.GetLong("ttgold"); panel.RefreshPanel(); } if (panel.PokersTrans[0].childCount > 0) { int[] cards = isfsObj.GetIntArray("cards"); PokerCard poker = panel.PokersTrans[0].GetChild(0).GetComponent<PokerCard>(); poker.SetCardId(cards[0]); poker.SetCardFront(); } if (win > 0) { var resultSeat = seat; var pokerType = panel.UserBetPoker.PokerType; if (panel.PokersTrans[panel.PokersTrans.Length - 1].childCount > 0) { pokerType.spriteName = "ct_" + isfsObj.GetUtfString("cardsName"); pokerType.MakePixelPerfect(); pokerType.transform.localScale = resultSeat == gdata.SelfSeat ? Vector3.one : new Vector3(1.5f, 1.5f, 1.5f); pokerType.gameObject.SetActive(true); } panel.WinEffect.SetActive(true); //如果是特殊牌型,需要播放牌型特效 if (EffectsMgr.NeedShowEffect(isfsObj.GetUtfString("cardsName"))) EffectsMgr.PlayParticleEffect("ct_" + isfsObj.GetUtfString("cardsName"), 2f, true); if (resultSeat == gdata.SelfSeat) { Facade.Instance<MusicManager>().Play("win"); EffectsMgr.PlayYouWin(); } wheres.Add(panel.UserIcon.transform); } } if (wheres.Count > 0) { BetMgr.BigBetStack.SendBetToSomewhere(wheres); } } /// <summary> /// 显示指定玩家说话 /// </summary> /// <param name="speaker"></param> /// <param name="cd"></param> public void Speaker(int speaker, float cd = -1) { var speakerPanel = App.GameData.GetPlayer<PlayerPanel>(speaker, true); if (speakerPanel.Info == null) { YxDebug.Log("座位上没有玩家!"); return; } YxClockManager.BeginWaitPlayer(speaker, cd <= 0 ? App.GetGameData<GangwuGameData>().SpeakCd : cd); } public override void OnOtherPlayerJoinRoom(ISFSObject sfsObject) { var gdata = App.GetGameData<GangwuGameData>(); if (!gdata.IsGameInfo) { YxDebug.LogError("GameInfo还没有初始化!!"); return; } base.OnOtherPlayerJoinRoom(sfsObject); var data = sfsObject.GetSFSObject(RequestKey.KeyUser); int seat = data.GetInt(RequestKey.KeySeat); var panel = gdata.GetPlayer<PlayerPanel>(seat, true); panel.SetPlayerReadyState(false); } public override void BeginReady() { base.BeginReady(); var playerList = App.GetGameData<GangwuGameData>().PlayerList; foreach (var play in playerList) { var panel = (PlayerPanel)play; panel.SetPlayerReadyState(false); } } public override int OnChangeRoom() { var gdata = App.GetGameData<GangwuGameData>(); var playerList = gdata.PlayerList; gdata.IsGameInfo = false; BetMgr.Reset(); Reset(); gdata.CurRound = 0; foreach (var yxBaseGamePlayer in playerList) { var player = (PlayerPanel)yxBaseGamePlayer; player.Reset(); player.Info = null; player.RefreshPanel(); player.gameObject.SetActive(false); } HistoryResultMgr.Reset(); return base.OnChangeRoom(); } public override void UserReady(int localSeat, ISFSObject responseData) { base.UserReady(localSeat, responseData); var gdata = App.GetGameData<GangwuGameData>(); if (gdata.IsGameStart) { return; } YxDebug.Log("Seat " + responseData.GetInt("seat") + " is ready!"); PlayerPanel panel = gdata.GetPlayer<PlayerPanel>(responseData.GetInt("seat"), true); panel.SetPlayerReadyState(true); } /// <summary> /// 重置 /// </summary> public void Reset() { if (PublicPokers.Count > 0) { foreach (PokerCard publicPoker in PublicPokers) { if (publicPoker != null && publicPoker.gameObject != null) Destroy(publicPoker.gameObject); } } YxClockManager.StopWaitPlayer(); PublicPokers.Clear(); SpeakMgr.Reset(); DealerMgr.Rest(); var playerList = App.GetGameData<GangwuGameData>().PlayerList; foreach (var yxBaseGamePlayer in playerList) { var player = (PlayerPanel)yxBaseGamePlayer; player.Reset(); } StopAllCoroutines(); } } // ReSharper disable InconsistentNaming public enum PokerType { ct_GaoPai = 0, //高牌 ct_YiDui, //一对 ct_LiangDui, //两对 ct_SanTiao, //三条 ct_ShunZi, //顺子 ct_TongHua, //同花 ct_Hulu, //葫芦 ct_SiTiao, //四条 ct_TongHuaShun, //同花顺 ct_HJTongHuaShun, //皇家同花顺 //ct_WuTiao //测试特殊牌型动画使用 } }
34.399698
132
0.45736
[ "MIT" ]
GEngine-JP/chessgame
Assets/Scripts/Game/GangWu/Main/GangWuGameManager.cs
23,417
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ScreenshotCamera : MonoBehaviour { public Camera cam; public RenderTexture renderTexture; public bool isTimePaused = false; public bool isTrackingMouse = false; [Range(0f, 5f)] public float turnSpeed; [Range(0f, 20f)] public float defaultSpeed, fastSpeed; [Range(0f, 5f)] public float slowSpeed; private void Update() { if (Input.GetKeyDown(KeyCode.Mouse0)) { isTrackingMouse = true; } if (Input.GetKeyDown(KeyCode.P)) { ToggleTimeStop(); } if (Input.GetKeyDown(KeyCode.Escape)) { isTrackingMouse = !isTrackingMouse; } if (Input.GetKeyDown(KeyCode.Space)) { StartCoroutine(Screenshot()); } if (isTrackingMouse) { Rotate(); Move(); } } private void ToggleTimeStop() { isTimePaused = !isTimePaused; if (isTimePaused) { Time.timeScale = 0f; } else { Time.timeScale = 1f; } } private IEnumerator Screenshot() { yield return new WaitForEndOfFrame(); cam.targetTexture = renderTexture; cam.Render(); cam.targetTexture = null; DateTime dt = DateTime.Now; String filename = $"{dt.Year}-{dt.Month}-{dt.Day}_{dt.Hour}-{dt.Minute}-{dt.Second}-{dt.Millisecond}.png"; Debug.Log($"Saving screenshot as ./{filename}"); Texture2D tex = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, false); tex.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); byte[] bytes; bytes = tex.EncodeToPNG(); System.IO.File.WriteAllBytes(filename, bytes); // This is rendering to a black image for some reason //ScreenCapture.CaptureScreenshot(filename, 1); } private void Rotate() { float h = Input.GetAxis("Mouse X"); float v = -Input.GetAxis("Mouse Y"); //transform.Rotate(v, h, 0); Quaternion r1 = Quaternion.AngleAxis(h * turnSpeed, Vector3.up); Quaternion r2 = Quaternion.AngleAxis(v * turnSpeed, Vector3.right); transform.localRotation = transform.localRotation * r1 * r2; Vector3 euler = transform.rotation.eulerAngles; euler.z = 0f; transform.localRotation = Quaternion.Euler(euler); } private void Move() { // Delegate between sprint/ float moveSpeed = defaultSpeed; if (Input.GetKey(KeyCode.LeftShift)) { moveSpeed = fastSpeed; } else if (Input.GetKey(KeyCode.LeftControl)) { moveSpeed = slowSpeed; } // I should really learn the new input system things at some point if (Input.GetKey(KeyCode.A)) { transform.position -= transform.right * moveSpeed * Time.unscaledDeltaTime; } if (Input.GetKey(KeyCode.D)) { transform.position += transform.right * moveSpeed * Time.unscaledDeltaTime; } if (Input.GetKey(KeyCode.W)) { transform.position += transform.forward * moveSpeed * Time.unscaledDeltaTime; } if (Input.GetKey(KeyCode.S)) { transform.position -= transform.forward * moveSpeed * Time.unscaledDeltaTime; } if (Input.GetKey(KeyCode.E)) { transform.position += transform.up * moveSpeed * Time.unscaledDeltaTime; } if (Input.GetKey(KeyCode.Q)) { transform.position -= transform.up * moveSpeed * Time.unscaledDeltaTime; } } }
31.056911
115
0.582723
[ "MIT" ]
iamrequest/shattered-skies
Assets/Scripts/Cameras/ScreenshotCamera.cs
3,822
C#
using System; namespace SamplePrism.Infrastructure.Cron { [Serializable] public class CronEntryException : Exception { public CronEntryException(string message) : base(message) { } } }
14.642857
47
0.717073
[ "Apache-2.0" ]
XYRYTeam/SimplePrism
SamplePrism.Infrastructure/Cron/CronEntryException.cs
205
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using System; internal class NullableTest1 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((char?)o) == null; } public static void Run() { char? s = null; Console.WriteLine("char"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest2 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((bool?)o) == null; } public static void Run() { bool? s = null; Console.WriteLine("bool"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest3 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((byte?)o) == null; } public static void Run() { byte? s = null; Console.WriteLine("byte"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest4 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((sbyte?)o) == null; } public static void Run() { sbyte? s = null; Console.WriteLine("sbyte"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest5 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((short?)o) == null; } public static void Run() { short? s = null; Console.WriteLine("short"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest6 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((ushort?)o) == null; } public static void Run() { ushort? s = null; Console.WriteLine("ushort"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest7 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((int?)o) == null; } public static void Run() { int? s = null; Console.WriteLine("int"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest8 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((uint?)o) == null; } public static void Run() { uint? s = null; Console.WriteLine("uint"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest9 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((long?)o) == null; } public static void Run() { long? s = null; Console.WriteLine("long"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest10 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((ulong?)o) == null; } public static void Run() { ulong? s = null; Console.WriteLine("ulong"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest11 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((float?)o) == null; } public static void Run() { float? s = null; Console.WriteLine("float"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest12 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((double?)o) == null; } public static void Run() { double? s = null; Console.WriteLine("double"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest13 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((decimal?)o) == null; } public static void Run() { decimal? s = null; Console.WriteLine("decimal"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest14 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((IntPtr?)o) == null; } public static void Run() { IntPtr? s = null; Console.WriteLine("IntPtr"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest15 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((UIntPtr?)o) == null; } public static void Run() { UIntPtr? s = null; Console.WriteLine("UIntPtr"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest16 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((Guid?)o) == null; } public static void Run() { Guid? s = null; Console.WriteLine("Guid"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest17 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((GCHandle?)o) == null; } public static void Run() { GCHandle? s = null; Console.WriteLine("GCHandle"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest18 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((ByteE?)o) == null; } public static void Run() { ByteE? s = null; Console.WriteLine("ByteE"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest19 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((IntE?)o) == null; } public static void Run() { IntE? s = null; Console.WriteLine("IntE"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest20 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((LongE?)o) == null; } public static void Run() { LongE? s = null; Console.WriteLine("LongE"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest21 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((EmptyStruct?)o) == null; } public static void Run() { EmptyStruct? s = null; Console.WriteLine("EmptyStruct"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest22 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStruct?)o) == null; } public static void Run() { NotEmptyStruct? s = null; Console.WriteLine("NotEmptyStruct"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest23 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStructQ?)o) == null; } public static void Run() { NotEmptyStructQ? s = null; Console.WriteLine("NotEmptyStructQ"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest24 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStructA?)o) == null; } public static void Run() { NotEmptyStructA? s = null; Console.WriteLine("NotEmptyStructA"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest25 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStructQA?)o) == null; } public static void Run() { NotEmptyStructQA? s = null; Console.WriteLine("NotEmptyStructQA"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest26 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((EmptyStructGen<int>?)o) == null; } public static void Run() { EmptyStructGen<int>? s = null; Console.WriteLine("EmptyStructGen<int>"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest27 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStructGen<int>?)o) == null; } public static void Run() { NotEmptyStructGen<int>? s = null; Console.WriteLine("NotEmptyStructGen<int>"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest28 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStructConstrainedGen<int>?)o) == null; } public static void Run() { NotEmptyStructConstrainedGen<int>? s = null; Console.WriteLine("NotEmptyStructConstrainedGen<int>"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest29 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStructConstrainedGenA<int>?)o) == null; } public static void Run() { NotEmptyStructConstrainedGenA<int>? s = null; Console.WriteLine("NotEmptyStructConstrainedGenA<int>"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest30 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStructConstrainedGenQ<int>?)o) == null; } public static void Run() { NotEmptyStructConstrainedGenQ<int>? s = null; Console.WriteLine("NotEmptyStructConstrainedGenQ<int>"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest31 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStructConstrainedGenQA<int>?)o) == null; } public static void Run() { NotEmptyStructConstrainedGenQA<int>? s = null; Console.WriteLine("NotEmptyStructConstrainedGenQA<int>"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest32 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NestedStruct?)o) == null; } public static void Run() { NestedStruct? s = null; Console.WriteLine("NestedStruct"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest33 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NestedStructGen<int>?)o) == null; } public static void Run() { NestedStructGen<int>? s = null; Console.WriteLine("NestedStructGen<int>"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest34 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((ExplicitFieldOffsetStruct?)o) == null; } public static void Run() { ExplicitFieldOffsetStruct? s = null; Console.WriteLine("ExplicitFieldOffsetStruct"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest37 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((MarshalAsStruct?)o) == null; } public static void Run() { MarshalAsStruct? s = null; Console.WriteLine("MarshalAsStruct"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest38 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((ImplementOneInterface?)o) == null; } public static void Run() { ImplementOneInterface? s = null; Console.WriteLine("ImplementOneInterface"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest39 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((ImplementTwoInterface?)o) == null; } public static void Run() { ImplementTwoInterface? s = null; Console.WriteLine("ImplementTwoInterface"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest40 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((ImplementOneInterfaceGen<int>?)o) == null; } public static void Run() { ImplementOneInterfaceGen<int>? s = null; Console.WriteLine("ImplementOneInterfaceGen<int>"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest41 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((ImplementTwoInterfaceGen<int>?)o) == null; } public static void Run() { ImplementTwoInterfaceGen<int>? s = null; Console.WriteLine("ImplementTwoInterfaceGen<int>"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest42 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((ImplementAllInterface<int>?)o) == null; } public static void Run() { ImplementAllInterface<int>? s = null; Console.WriteLine("ImplementAllInterface<int>"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest43 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((WithMultipleGCHandleStruct?)o) == null; } public static void Run() { WithMultipleGCHandleStruct? s = null; Console.WriteLine("WithMultipleGCHandleStruct"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest44 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((WithOnlyFXTypeStruct?)o) == null; } public static void Run() { WithOnlyFXTypeStruct? s = null; Console.WriteLine("WithOnlyFXTypeStruct"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class NullableTest45 { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((MixedAllStruct?)o) == null; } public static void Run() { MixedAllStruct? s = null; Console.WriteLine("MixedAllStruct"); Assert.IsTrue(BoxUnboxToNQ(s)); Assert.IsTrue(BoxUnboxToQ(s)); Assert.IsTrue(BoxUnboxToNQGen(s)); Assert.IsTrue(BoxUnboxToQGen(s)); } } internal class Test { private static int Main() { try { NullableTest1.Run(); NullableTest2.Run(); NullableTest3.Run(); NullableTest4.Run(); NullableTest5.Run(); NullableTest6.Run(); NullableTest7.Run(); NullableTest8.Run(); NullableTest9.Run(); NullableTest10.Run(); NullableTest11.Run(); NullableTest12.Run(); NullableTest13.Run(); NullableTest14.Run(); NullableTest15.Run(); NullableTest16.Run(); NullableTest17.Run(); NullableTest18.Run(); NullableTest19.Run(); NullableTest20.Run(); NullableTest21.Run(); NullableTest22.Run(); NullableTest23.Run(); NullableTest24.Run(); NullableTest25.Run(); NullableTest26.Run(); NullableTest27.Run(); NullableTest28.Run(); NullableTest29.Run(); NullableTest30.Run(); NullableTest31.Run(); NullableTest32.Run(); NullableTest33.Run(); NullableTest34.Run(); NullableTest37.Run(); NullableTest38.Run(); NullableTest39.Run(); NullableTest40.Run(); NullableTest41.Run(); NullableTest42.Run(); NullableTest43.Run(); NullableTest44.Run(); NullableTest45.Run(); } catch (Exception ex) { Console.WriteLine("Test FAILED"); Console.WriteLine(ex); return 666; } Console.WriteLine("Test SUCCESS"); return 100; } }
21.449313
71
0.574765
[ "MIT" ]
belav/runtime
src/tests/JIT/Directed/nullabletypes/Desktop/nullcomparaison.cs
32,796
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AquaShop.Models.Aquariums.Contracts; using AquaShop.Models.Decorations.Contracts; using AquaShop.Models.Fish.Contracts; using AquaShop.Utilities.Messages; namespace AquaShop.Models.Aquariums { public abstract class Aquarium : IAquarium { private string name; private List<IDecoration> decorations; private List<IFish> fish; protected Aquarium(string name, int capacity) { this.Name = name; this.Capacity = capacity; this.decorations = new List<IDecoration>(); this.fish = new List<IFish>(); } public string Name { get => this.name; private set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException(ExceptionMessages.InvalidAquariumName); } this.name = value; } } public int Capacity { get; } public int Comfort => this.Decorations.Sum(x => x.Comfort); //public ICollection<IDecoration> Decorations { get; } public ICollection<IDecoration> Decorations => this.decorations; //public ICollection<IFish> Fish { get; private set; } public ICollection<IFish> Fish => this.fish; public void AddFish(IFish fish) { if (this.Fish.Count == this.Capacity) { throw new InvalidOperationException(ExceptionMessages.NotEnoughCapacity); } this.Fish.Add(fish); } public bool RemoveFish(IFish fish) => this.Fish.Remove(fish); public void AddDecoration(IDecoration decoration) => this.Decorations.Add(decoration); public void Feed() => this.fish.ForEach(x => x.Eat()); //{ // foreach (IFish fish in this.Fish) // { // fish.Eat(); // } //} public string GetInfo() { StringBuilder sb = new StringBuilder(); sb.AppendLine($"{Name} ({GetType().Name}):"); sb.AppendLine($"Fish: {(Fish.Any() ? string.Join(", ", GetFishNames()) : "none")}"); sb.AppendLine($"Decorations: {Decorations.Count}"); sb.AppendLine($"Comfort: {Comfort}"); return sb.ToString().TrimEnd(); } private List<string> GetFishNames() { List<string> list = new List<string>(); foreach (var fish in Fish) { list.Add(fish.Name); } return list; } //public string GetInfo() //{ // StringBuilder sb = new StringBuilder(); // sb.AppendLine($"{this.Name} ({this.GetType().Name}):"); // sb.AppendLine($"Fish: {(this.Fish.Any() ? string.Join(", ", this.Fish.Select(x => x.Name)) : "none")}"); // sb.AppendLine($"Decorations: {this.Decorations.Count}"); // sb.AppendLine($"Comfort: {this.Comfort}"); // return sb.ToString().TrimEnd(); //} } }
29.425926
118
0.541536
[ "MIT" ]
NeSh74/CSharp-OOP-June-2021
Exam/CSharp OOP Exam - 10 April 2021/01. Structure & 02. Business Logic/AquaShop/Models/Aquariums/Aquarium.cs
3,180
C#
using CacheManager.Core; using Hangfire; using Masuit.MyBlogs.Core.Common; using Masuit.MyBlogs.Core.Configs; using Masuit.MyBlogs.Core.Extensions.Firewall; using Masuit.MyBlogs.Core.Extensions.Hangfire; using Masuit.MyBlogs.Core.Infrastructure.Services.Interface; using Masuit.MyBlogs.Core.Models.DTO; using Masuit.MyBlogs.Core.Models.Enum; using Masuit.MyBlogs.Core.Models.ViewModel; using Masuit.Tools; using Masuit.Tools.AspNetCore.Mime; using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions; using Masuit.Tools.Core.Net; using Masuit.Tools.Logging; using Masuit.Tools.Security; using Masuit.Tools.Strings; using Microsoft.AspNetCore.Mvc; using System.Net; using System.Web; namespace Masuit.MyBlogs.Core.Controllers { /// <summary> /// 登录授权 /// </summary> [ApiExplorerSettings(IgnoreApi = true), ServiceFilter(typeof(FirewallAttribute))] public class PassportController : Controller { /// <summary> /// 用户 /// </summary> public IUserInfoService UserInfoService { get; set; } public IFirewallRepoter FirewallRepoter { get; set; } /// <summary> /// 客户端的真实IP /// </summary> public string ClientIP => HttpContext.Connection.RemoteIpAddress.ToString(); /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="isTrue"></param> /// <param name="message"></param> /// <returns></returns> public ActionResult ResultData(object data, bool isTrue = true, string message = "") { return Json(new { Success = isTrue, Message = message, Data = data }); } /// <summary> /// 登录页 /// </summary> /// <returns></returns> public ActionResult Login() { var keys = RsaCrypt.GenerateRsaKeys(RsaKeyType.PKCS1); Response.Cookies.Append(nameof(keys.PublicKey), keys.PublicKey, new CookieOptions() { SameSite = SameSiteMode.Lax }); HttpContext.Session.Set(nameof(keys.PrivateKey), keys.PrivateKey); string from = Request.Query["from"]; if (!string.IsNullOrEmpty(from)) { from = HttpUtility.UrlDecode(from); Response.Cookies.Append("refer", from, new CookieOptions() { SameSite = SameSiteMode.Lax }); } if (HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo) != null) { if (string.IsNullOrEmpty(from)) { return RedirectToAction("Index", "Home"); } return LocalRedirect(from); } if (Request.Cookies.Count > 2) { string name = Request.Cookies["username"]; string pwd = Request.Cookies["password"]?.DesDecrypt(AppConfig.BaiduAK); var userInfo = UserInfoService.Login(name, pwd); if (userInfo != null) { Response.Cookies.Append("username", name, new CookieOptions() { Expires = DateTime.Now.AddYears(1), SameSite = SameSiteMode.Lax }); Response.Cookies.Append("password", Request.Cookies["password"], new CookieOptions() { Expires = DateTime.Now.AddYears(1), SameSite = SameSiteMode.Lax }); HttpContext.Session.Set(SessionKey.UserInfo, userInfo); BackgroundJob.Enqueue<IHangfireBackJob>(job => job.LoginRecord(userInfo, ClientIP, LoginType.Default)); if (string.IsNullOrEmpty(from)) { return RedirectToAction("Index", "Home"); } return LocalRedirect(from); } } return View(); } /// <summary> /// 登陆检查 /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="valid"></param> /// <param name="remem"></param> /// <returns></returns> [HttpPost, ValidateAntiForgeryToken] public ActionResult Login([FromServices] ICacheManager<int> cacheManager, string username, string password, string valid, string remem) { string validSession = HttpContext.Session.Get<string>("valid") ?? string.Empty; //将验证码从Session中取出来,用于登录验证比较 if (string.IsNullOrEmpty(validSession) || !valid.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase)) { return ResultData(null, false, "验证码错误"); } HttpContext.Session.Remove("valid"); //验证成功就销毁验证码Session,非常重要 if (string.IsNullOrEmpty(username.Trim()) || string.IsNullOrEmpty(password.Trim())) { return ResultData(null, false, "用户名或密码不能为空"); } try { var privateKey = HttpContext.Session.Get<string>(nameof(RsaKey.PrivateKey)); password = password.RSADecrypt(privateKey); } catch (Exception e) { LogManager.Info("登录失败,私钥:" + HttpContext.Session.Get<string>(nameof(RsaKey.PrivateKey))); throw; } var userInfo = UserInfoService.Login(username, password); if (userInfo == null) { var times = cacheManager.AddOrUpdate("LoginError:" + ClientIP, 1, i => i + 1, 5); if (times > 30) { FirewallRepoter.ReportAsync(IPAddress.Parse(ClientIP)).ContinueWith(_ => LogManager.Info($"多次登录用户名或密码错误,疑似爆破行为,已上报IP{ClientIP}至:" + FirewallRepoter.ReporterName)); } return ResultData(null, false, "用户名或密码错误"); } HttpContext.Session.Set(SessionKey.UserInfo, userInfo); if (remem.Trim().Contains(new[] { "on", "true" })) //是否记住登录 { Response.Cookies.Append("username", HttpUtility.UrlEncode(username.Trim()), new CookieOptions() { Expires = DateTime.Now.AddYears(1), SameSite = SameSiteMode.Lax }); Response.Cookies.Append("password", password.Trim().DesEncrypt(AppConfig.BaiduAK), new CookieOptions() { Expires = DateTime.Now.AddYears(1), SameSite = SameSiteMode.Lax }); } BackgroundJob.Enqueue<IHangfireBackJob>(job => job.LoginRecord(userInfo, ClientIP, LoginType.Default)); string refer = Request.Cookies["refer"]; Response.Cookies.Delete(nameof(RsaKey.PublicKey), new CookieOptions() { SameSite = SameSiteMode.Lax }); Response.Cookies.Delete("refer", new CookieOptions() { SameSite = SameSiteMode.Lax }); HttpContext.Session.Remove(nameof(RsaKey.PrivateKey)); return ResultData(null, true, string.IsNullOrEmpty(refer) ? "/" : refer); } /// <summary> /// 生成验证码 /// </summary> /// <returns></returns> public ActionResult ValidateCode() { string code = Tools.Strings.ValidateCode.CreateValidateCode(6); HttpContext.Session.Set("valid", code); //将验证码生成到Session中 var buffer = HttpContext.CreateValidateGraphic(code); return this.ResumeFile(buffer, ContentType.Jpeg, "验证码.jpg"); } /// <summary> /// 检查验证码 /// </summary> /// <param name="code"></param> /// <returns></returns> [HttpPost] public ActionResult CheckValidateCode(string code) { string validSession = HttpContext.Session.Get<string>("valid"); if (string.IsNullOrEmpty(validSession) || !code.Trim().Equals(validSession, StringComparison.InvariantCultureIgnoreCase)) { return ResultData(null, false, "验证码错误"); } return ResultData(null, false, "验证码正确"); } /// <summary> /// 获取用户信息 /// </summary> /// <returns></returns> public ActionResult GetUserInfo() { var user = HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo); #if DEBUG user = UserInfoService.GetByUsername("masuit").Mapper<UserInfoDto>(); #endif return ResultData(user); } /// <summary> /// 注销登录 /// </summary> /// <returns></returns> public ActionResult Logout() { HttpContext.Session.Remove(SessionKey.UserInfo); Response.Cookies.Delete("username", new CookieOptions() { SameSite = SameSiteMode.Lax }); Response.Cookies.Delete("password", new CookieOptions() { SameSite = SameSiteMode.Lax }); HttpContext.Session.Clear(); return Request.Method.Equals(HttpMethods.Get) ? RedirectToAction("Index", "Home") : ResultData(null, message: "注销成功!"); } } }
36.818533
183
0.542995
[ "MIT" ]
Muzsor/Masuit.MyBlogs
src/Masuit.MyBlogs.Core/Controllers/PassportController.cs
9,858
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 ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.EC2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.EC2.Model.Internal.MarshallTransformations { /// <summary> /// CreateVpcEndpointServiceConfiguration Request Marshaller /// </summary> public class CreateVpcEndpointServiceConfigurationRequestMarshaller : IMarshaller<IRequest, CreateVpcEndpointServiceConfigurationRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreateVpcEndpointServiceConfigurationRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateVpcEndpointServiceConfigurationRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.EC2"); request.Parameters.Add("Action", "CreateVpcEndpointServiceConfiguration"); request.Parameters.Add("Version", "2016-11-15"); if(publicRequest != null) { if(publicRequest.IsSetAcceptanceRequired()) { request.Parameters.Add("AcceptanceRequired", StringUtils.FromBool(publicRequest.AcceptanceRequired)); } if(publicRequest.IsSetClientToken()) { request.Parameters.Add("ClientToken", StringUtils.FromString(publicRequest.ClientToken)); } if(publicRequest.IsSetNetworkLoadBalancerArns()) { int publicRequestlistValueIndex = 1; foreach(var publicRequestlistValue in publicRequest.NetworkLoadBalancerArns) { request.Parameters.Add("NetworkLoadBalancerArn" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue)); publicRequestlistValueIndex++; } } if(publicRequest.IsSetPrivateDnsName()) { request.Parameters.Add("PrivateDnsName", StringUtils.FromString(publicRequest.PrivateDnsName)); } if(publicRequest.IsSetTagSpecifications()) { int publicRequestlistValueIndex = 1; foreach(var publicRequestlistValue in publicRequest.TagSpecifications) { if(publicRequestlistValue.IsSetResourceType()) { request.Parameters.Add("TagSpecification" + "." + publicRequestlistValueIndex + "." + "ResourceType", StringUtils.FromString(publicRequestlistValue.ResourceType)); } if(publicRequestlistValue.IsSetTags()) { int publicRequestlistValuelistValueIndex = 1; foreach(var publicRequestlistValuelistValue in publicRequestlistValue.Tags) { if(publicRequestlistValuelistValue.IsSetKey()) { request.Parameters.Add("TagSpecification" + "." + publicRequestlistValueIndex + "." + "Tag" + "." + publicRequestlistValuelistValueIndex + "." + "Key", StringUtils.FromString(publicRequestlistValuelistValue.Key)); } if(publicRequestlistValuelistValue.IsSetValue()) { request.Parameters.Add("TagSpecification" + "." + publicRequestlistValueIndex + "." + "Tag" + "." + publicRequestlistValuelistValueIndex + "." + "Value", StringUtils.FromString(publicRequestlistValuelistValue.Value)); } publicRequestlistValuelistValueIndex++; } } publicRequestlistValueIndex++; } } } return request; } private static CreateVpcEndpointServiceConfigurationRequestMarshaller _instance = new CreateVpcEndpointServiceConfigurationRequestMarshaller(); internal static CreateVpcEndpointServiceConfigurationRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateVpcEndpointServiceConfigurationRequestMarshaller Instance { get { return _instance; } } } }
45.128788
253
0.589055
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/CreateVpcEndpointServiceConfigurationRequestMarshaller.cs
5,957
C#
namespace ThreeJs4Net.Materials { public interface IMorphTargets { bool MorphTargets { get; set; } } }
15.5
39
0.637097
[ "MIT" ]
threejs4net/threejs4net
ThreeJs4Net/Materials/IMorphTargets.cs
126
C#
namespace Azure.Data.AppConfiguration { public partial class ConfigurationClient { protected ConfigurationClient() { } public ConfigurationClient(string connectionString) { } public ConfigurationClient(string connectionString, Azure.Data.AppConfiguration.ConfigurationClientOptions options) { } public ConfigurationClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { } public ConfigurationClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Data.AppConfiguration.ConfigurationClientOptions options) { } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> AddConfigurationSetting(Azure.Data.AppConfiguration.ConfigurationSetting setting, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> AddConfigurationSetting(string key, string value, string label = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> AddConfigurationSettingAsync(Azure.Data.AppConfiguration.ConfigurationSetting setting, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> AddConfigurationSettingAsync(string key, string value, string label = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DeleteConfigurationSetting(Azure.Data.AppConfiguration.ConfigurationSetting setting, bool onlyIfUnchanged = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DeleteConfigurationSetting(string key, string label = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteConfigurationSettingAsync(Azure.Data.AppConfiguration.ConfigurationSetting setting, bool onlyIfUnchanged = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteConfigurationSettingAsync(string key, string label = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> GetConfigurationSetting(Azure.Data.AppConfiguration.ConfigurationSetting setting, bool onlyIfChanged = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> GetConfigurationSetting(Azure.Data.AppConfiguration.ConfigurationSetting setting, System.DateTimeOffset acceptDateTime, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> GetConfigurationSetting(string key, string label, System.DateTimeOffset? acceptDateTime, Azure.MatchConditions conditions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> GetConfigurationSetting(string key, string label = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> GetConfigurationSettingAsync(Azure.Data.AppConfiguration.ConfigurationSetting setting, bool onlyIfChanged = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> GetConfigurationSettingAsync(Azure.Data.AppConfiguration.ConfigurationSetting setting, System.DateTimeOffset acceptDateTime, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> GetConfigurationSettingAsync(string key, string label, System.DateTimeOffset? acceptDateTime, Azure.MatchConditions conditions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> GetConfigurationSettingAsync(string key, string label = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.Data.AppConfiguration.ConfigurationSetting> GetConfigurationSettings(Azure.Data.AppConfiguration.SettingSelector selector, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Data.AppConfiguration.ConfigurationSetting> GetConfigurationSettingsAsync(Azure.Data.AppConfiguration.SettingSelector selector, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual Azure.Pageable<Azure.Data.AppConfiguration.ConfigurationSetting> GetRevisions(Azure.Data.AppConfiguration.SettingSelector selector, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.Data.AppConfiguration.ConfigurationSetting> GetRevisions(string keyFilter, string labelFilter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Data.AppConfiguration.ConfigurationSetting> GetRevisionsAsync(Azure.Data.AppConfiguration.SettingSelector selector, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Data.AppConfiguration.ConfigurationSetting> GetRevisionsAsync(string keyFilter, string labelFilter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> SetConfigurationSetting(Azure.Data.AppConfiguration.ConfigurationSetting setting, bool onlyIfUnchanged = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> SetConfigurationSetting(string key, string value, string label = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> SetConfigurationSettingAsync(Azure.Data.AppConfiguration.ConfigurationSetting setting, bool onlyIfUnchanged = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> SetConfigurationSettingAsync(string key, string value, string label = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> SetReadOnly(Azure.Data.AppConfiguration.ConfigurationSetting setting, bool isReadOnly, bool onlyIfUnchanged = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> SetReadOnly(string key, bool isReadOnly, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting> SetReadOnly(string key, string label, bool isReadOnly, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> SetReadOnlyAsync(Azure.Data.AppConfiguration.ConfigurationSetting setting, bool isReadOnly, bool onlyIfUnchanged = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> SetReadOnlyAsync(string key, bool isReadOnly, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.AppConfiguration.ConfigurationSetting>> SetReadOnlyAsync(string key, string label, bool isReadOnly, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } public virtual void UpdateSyncToken(string token) { } } public partial class ConfigurationClientOptions : Azure.Core.ClientOptions { public ConfigurationClientOptions(Azure.Data.AppConfiguration.ConfigurationClientOptions.ServiceVersion version = Azure.Data.AppConfiguration.ConfigurationClientOptions.ServiceVersion.V1_0) { } public enum ServiceVersion { V1_0 = 0, } } public static partial class ConfigurationModelFactory { public static Azure.Data.AppConfiguration.ConfigurationSetting ConfigurationSetting(string key, string value, string label = null, string contentType = null, Azure.ETag eTag = default(Azure.ETag), System.DateTimeOffset? lastModified = default(System.DateTimeOffset?), bool? isReadOnly = default(bool?)) { throw null; } } public partial class ConfigurationSetting { public ConfigurationSetting(string key, string value, string label = null) { } public string ContentType { get { throw null; } set { } } public Azure.ETag ETag { get { throw null; } } public bool? IsReadOnly { get { throw null; } } public string Key { get { throw null; } set { } } public string Label { get { throw null; } set { } } public System.DateTimeOffset? LastModified { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } } public string Value { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class FeatureFlagConfigurationSetting : Azure.Data.AppConfiguration.ConfigurationSetting { public FeatureFlagConfigurationSetting(string featureId, bool isEnabled, string label = null) : base (default(string), default(string), default(string)) { } public System.Collections.Generic.IList<Azure.Data.AppConfiguration.FeatureFlagFilter> ClientFilters { get { throw null; } } public string Description { get { throw null; } set { } } public string DisplayName { get { throw null; } set { } } public string FeatureId { get { throw null; } set { } } public bool IsEnabled { get { throw null; } set { } } public static string KeyPrefix { get { throw null; } } } public partial class FeatureFlagFilter { public FeatureFlagFilter(string name) { } public FeatureFlagFilter(string name, System.Collections.Generic.IDictionary<string, object> parameters) { } public string Name { get { throw null; } } public System.Collections.Generic.IDictionary<string, object> Parameters { get { throw null; } } } public partial class SecretReferenceConfigurationSetting : Azure.Data.AppConfiguration.ConfigurationSetting { public SecretReferenceConfigurationSetting(string key, System.Uri secretId, string label = null) : base (default(string), default(string), default(string)) { } public System.Uri SecretId { get { throw null; } set { } } } [System.FlagsAttribute] public enum SettingFields : uint { Key = (uint)1, Label = (uint)2, Value = (uint)4, ContentType = (uint)8, ETag = (uint)16, LastModified = (uint)32, IsReadOnly = (uint)64, Tags = (uint)128, All = (uint)4294967295, } public partial class SettingSelector { public static readonly string Any; public SettingSelector() { } public System.DateTimeOffset? AcceptDateTime { get { throw null; } set { } } public Azure.Data.AppConfiguration.SettingFields Fields { get { throw null; } set { } } public string KeyFilter { get { throw null; } set { } } public string LabelFilter { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Microsoft.Extensions.Azure { public static partial class ConfigurationClientBuilderExtensions { public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Data.AppConfiguration.ConfigurationClient, Azure.Data.AppConfiguration.ConfigurationClientOptions> AddConfigurationClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Data.AppConfiguration.ConfigurationClient, Azure.Data.AppConfiguration.ConfigurationClientOptions> AddConfigurationClient<TBuilder>(this TBuilder builder, System.Uri configurationUri) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Data.AppConfiguration.ConfigurationClient, Azure.Data.AppConfiguration.ConfigurationClientOptions> AddConfigurationClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } } }
117.978571
385
0.78949
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/appconfiguration/Azure.Data.AppConfiguration/api/Azure.Data.AppConfiguration.netstandard2.0.cs
16,517
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request the Call Me Now permissions for Pinhole digit patterns for a group default and its departments. /// The response is either a GroupOutgoingCallingPlanPinholeDigitPlanCallMeNowGetListResponse or an ErrorResponse. /// <see cref="GroupOutgoingCallingPlanPinholeDigitPlanCallMeNowGetListResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""6f793dfca9bd3d121bb35e0f9cf1cb2e:564""}]")] public class GroupOutgoingCallingPlanPinholeDigitPlanCallMeNowGetListRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _serviceProviderId; [XmlElement(ElementName = "serviceProviderId", IsNullable = false, Namespace = "")] [Group(@"6f793dfca9bd3d121bb35e0f9cf1cb2e:564")] [MinLength(1)] [MaxLength(30)] public string ServiceProviderId { get => _serviceProviderId; set { ServiceProviderIdSpecified = true; _serviceProviderId = value; } } [XmlIgnore] protected bool ServiceProviderIdSpecified { get; set; } private string _groupId; [XmlElement(ElementName = "groupId", IsNullable = false, Namespace = "")] [Group(@"6f793dfca9bd3d121bb35e0f9cf1cb2e:564")] [MinLength(1)] [MaxLength(30)] public string GroupId { get => _groupId; set { GroupIdSpecified = true; _groupId = value; } } [XmlIgnore] protected bool GroupIdSpecified { get; set; } } }
32.016129
129
0.63728
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/GroupOutgoingCallingPlanPinholeDigitPlanCallMeNowGetListRequest.cs
1,985
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codeartifact-2018-09-22.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.CodeArtifact.Model { /// <summary> /// The operation did not succeed because of an unauthorized access attempt. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class AccessDeniedException : AmazonCodeArtifactException { /// <summary> /// Constructs a new AccessDeniedException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public AccessDeniedException(string message) : base(message) {} /// <summary> /// Construct instance of AccessDeniedException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public AccessDeniedException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of AccessDeniedException /// </summary> /// <param name="innerException"></param> public AccessDeniedException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of AccessDeniedException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public AccessDeniedException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of AccessDeniedException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public AccessDeniedException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the AccessDeniedException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected AccessDeniedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
46.951613
178
0.678976
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CodeArtifact/Generated/Model/AccessDeniedException.cs
5,822
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Network.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Describes the storage location for a packet capture session. /// </summary> public partial class PacketCaptureStorageLocation { /// <summary> /// Initializes a new instance of the PacketCaptureStorageLocation /// class. /// </summary> public PacketCaptureStorageLocation() { CustomInit(); } /// <summary> /// Initializes a new instance of the PacketCaptureStorageLocation /// class. /// </summary> /// <param name="storageId">The ID of the storage account to save the /// packet capture session. Required if no local file path is /// provided.</param> /// <param name="storagePath">The URI of the storage path to save the /// packet capture. Must be a well-formed URI describing the location /// to save the packet capture.</param> /// <param name="filePath">A valid local path on the targeting VM. Must /// include the name of the capture file (*.cap). For linux virtual /// machine it must start with /var/captures. Required if no storage ID /// is provided, otherwise optional.</param> public PacketCaptureStorageLocation(string storageId = default(string), string storagePath = default(string), string filePath = default(string)) { StorageId = storageId; StoragePath = storagePath; FilePath = filePath; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the ID of the storage account to save the packet /// capture session. Required if no local file path is provided. /// </summary> [JsonProperty(PropertyName = "storageId")] public string StorageId { get; set; } /// <summary> /// Gets or sets the URI of the storage path to save the packet /// capture. Must be a well-formed URI describing the location to save /// the packet capture. /// </summary> [JsonProperty(PropertyName = "storagePath")] public string StoragePath { get; set; } /// <summary> /// Gets or sets a valid local path on the targeting VM. Must include /// the name of the capture file (*.cap). For linux virtual machine it /// must start with /var/captures. Required if no storage ID is /// provided, otherwise optional. /// </summary> [JsonProperty(PropertyName = "filePath")] public string FilePath { get; set; } } }
38.373494
152
0.621036
[ "MIT" ]
0xced/azure-sdk-for-net
src/SDKs/Network/Management.Network/Generated/Models/PacketCaptureStorageLocation.cs
3,185
C#
using HotChocolate; using HotChocolate.Types; using Snowflake.Remoting.GraphQL; using Snowflake.Support.GraphQL.FrameworkQueries.Mutations.Orchestration; using System; using System.Collections.Generic; using System.Text; namespace Snowflake.Support.GraphQL.FrameworkQueries.Subscriptions.Orchestration { public sealed class OrchestrationSubscriptions : ObjectTypeExtension { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.ExtendSubscription(); descriptor.Field("onEmulationCleanup") .Description("A subscription for the cleanupEmulation mutation.") .Type<NonNullType<EmulationInstancePayloadType>>() .Argument("instanceId", arg => arg.Type<NonNullType<UuidType>>()) .SubscribeToTopic<Guid, OnEmulationCleanupMessage>("instanceId") .Resolve(ctx => ctx.GetEventMessage<EmulationInstancePayload>()); descriptor.Field("onEmulationStart") .Description("A subscription for the startEmulation mutation.") .Type<NonNullType<EmulationInstancePayloadType>>() .Argument("instanceId", arg => arg.Type<NonNullType<UuidType>>()) .SubscribeToTopic<Guid, OnEmulationStartMessage>("instanceId") .Resolve(ctx => ctx.GetEventMessage<EmulationInstancePayload>()); descriptor.Field("onEmulationStop") .Description("A subscription for when an emulation ends. The payload will be the same as in the corresponding `onEmulationStart` subscription.") .Type<NonNullType<EmulationInstancePayloadType>>() .Argument("instanceId", arg => arg.Type<NonNullType<UuidType>>()) .SubscribeToTopic<Guid, OnEmulationStopMessage>("instanceId") .Resolve(ctx => ctx.GetEventMessage<EmulationInstancePayload>()); descriptor.Field("onEmulationSetupEnvironment") .Description("A subscription for the setupEmulationEnvironment mutation.") .Type<NonNullType<EmulationInstancePayloadType>>() .Argument("instanceId", arg => arg.Type<NonNullType<UuidType>>()) .SubscribeToTopic<Guid, OnEmulationSetupEnvironmentMessage>("instanceId") .Resolve(ctx => ctx.GetEventMessage<EmulationInstancePayload>()); descriptor.Field("onEmulationCompileConfiguration") .Description("A subscription for the compileEmulationConfiguration mutation.") .Type<NonNullType<EmulationInstancePayloadType>>() .Argument("instanceId", arg => arg.Type<NonNullType<UuidType>>()) .SubscribeToTopic<Guid, OnEmulationCompileConfigurationMessage>("instanceId") .Resolve(ctx => ctx.GetEventMessage<EmulationInstancePayload>()); descriptor.Field("onEmulationRestoreSave") .Description("A subscription for the restoreEmulationSave mutation.") .Type<NonNullType<EmulationInstancePayloadType>>() .Argument("instanceId", arg => arg.Type<NonNullType<UuidType>>()) .SubscribeToTopic<Guid, OnEmulationRestoreSaveMessage>("instanceId") .Resolve(ctx => ctx.GetEventMessage<EmulationInstancePayload>()); descriptor.Field("onEmulationPersistSave") .Description("A subscription for the persistEmulationSave mutation.") .Type<NonNullType<PersistEmulationSavePayloadType>>() .Argument("instanceId", arg => arg.Type<NonNullType<UuidType>>()) .SubscribeToTopic<Guid, OnEmulationPersistSaveMessage>("instanceId") .Resolve(ctx => ctx.GetEventMessage<PersistEmulationSavePayload>()); } } }
56.426471
160
0.664321
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
SnowflakePowered/snowflake
src/Snowflake.Support.GraphQL.FrameworkQueries/Subscriptions/Orchestration/OrchestrationSubscriptions.cs
3,839
C#
using System; namespace ModelUpgrade.Store { /// <summary> /// Data for saving /// </summary> public sealed class DataModel { public DataModel() { } /// <summary> /// Initializes a new instance of the <see cref="DataModel"/> class. /// </summary> /// <param name="model">The model.</param> /// <param name="parseFunc">The parse function.</param> public DataModel(IVersionModel model, Func<IVersionModel, string> parseFunc) { Id = model.GetId(); Data = parseFunc(model); ModelName = model.GetModelName(); } public string Id { get; set; } public string Data { get; set; } public string ModelName { get; set; } } }
24.967742
84
0.547804
[ "MIT" ]
davidyujia/ModelUpgrade.Store
ModelUpgrade.Store/DataModel.cs
776
C#
using System; using System.Collections; namespace Serpentine.IISModule { internal interface IApplicationStorage { void Set<T>(string key, T value); T Get<T>(string key); } //Singleton because multiple httpapplications can exist per worker process internal class ApplicationStorage : IApplicationStorage { private static readonly Lazy<ApplicationStorage> LazyInstance = new Lazy<ApplicationStorage>(() => new ApplicationStorage()); public static ApplicationStorage Instance => LazyInstance.Value; private readonly Hashtable _hashtable; private ApplicationStorage() { _hashtable = new Hashtable(); } public void Set<T>(string key, T value) { _hashtable[key] = value; } public T Get<T>(string key) { if (!_hashtable.ContainsKey(key)) { return default(T); } return (T) _hashtable[key]; } } }
24.666667
78
0.590734
[ "MIT" ]
gamingrobot/Serpentine
src/Serpentine.IISModule/ApplicationStorage.cs
1,038
C#
namespace Microsoft.HockeyApp.Channel { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Extensibility.Implementation.Platform; using TestFramework; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TaskEx = System.Threading.Tasks.Task; using Services; public class PersistenceChannelTest : AsyncTest { private readonly TelemetryConfiguration configuration; public PersistenceChannelTest() { this.configuration = new TelemetryConfiguration(); } protected override void Dispose(bool disposing) { this.configuration.Dispose(); PlatformSingleton.Current = null; } [TestClass] public class DeveloperMode : PersistenceChannelTest { [TestMethod] public void DeveloperModeIsFalseByDefault() { ServiceLocator.AddService<BaseStorageService>(new StorageService()); var channel = new PersistenceChannel(); Assert.IsFalse(channel.DeveloperMode.Value); } [TestMethod] public void DeveloperModeCanBeModifiedByConfiguration() { ServiceLocator.AddService<BaseStorageService>(new StorageService()); var channel = new PersistenceChannel(); channel.DeveloperMode = true; Assert.IsTrue(channel.DeveloperMode.Value); } [TestMethod] public void WhenSetToTrueChangesTelemetryBufferCapacityToOneForImmediateTransmission() { ServiceLocator.AddService<BaseStorageService>(new StorageService()); var channel = new PersistenceChannel(); channel.DeveloperMode = true; Assert.AreEqual(1, channel.TelemetryBuffer.Capacity); } [TestMethod] public void WhenSetToFalseChangesTelemetryBufferCapacityToOriginalValueForBufferedTransmission() { ServiceLocator.AddService<BaseStorageService>(new StorageService()); var channel = new PersistenceChannel(); int originalTelemetryBufferSize = channel.TelemetryBuffer.Capacity; channel.DeveloperMode = true; channel.DeveloperMode = false; Assert.AreEqual(originalTelemetryBufferSize, channel.TelemetryBuffer.Capacity); } } [TestClass] public class EndpointAddress : PersistenceChannelTest { [TestMethod] public void EndpointAddressCanBeModifiedByConfiguration() { ServiceLocator.AddService<BaseStorageService>(new StorageService()); var channel = new PersistenceChannel(); Uri expectedEndpoint = new Uri("http://abc.com"); channel.EndpointAddress = expectedEndpoint.AbsoluteUri; Assert.AreEqual(expectedEndpoint, new Uri(channel.EndpointAddress)); } } [TestClass] public class MaxTelemetryBufferCapacity : PersistenceChannelTest { [TestMethod] public void GetterReturnsTelemetryBufferCapacity() { ServiceLocator.AddService<BaseStorageService>(new StorageService()); var channel = new PersistenceChannel(); channel.TelemetryBuffer.Capacity = 42; Assert.AreEqual(42, channel.MaxTelemetryBufferCapacity); } [TestMethod] public void SetterChangesTelemetryBufferCapacity() { ServiceLocator.AddService<BaseStorageService>(new StorageService()); var channel = new PersistenceChannel(); channel.MaxTelemetryBufferCapacity = 42; Assert.AreEqual(42, channel.TelemetryBuffer.Capacity); } } [TestClass] public class Send : PersistenceChannelTest { [TestMethod] public void PassesTelemetryToMemoryBufferChannel() { ServiceLocator.AddService<BaseStorageService>(new StorageService()); var channel = new PersistenceChannel(); var telemetry = new StubTelemetry(); channel.Send(telemetry); IEnumerable<ITelemetry> actual = channel.TelemetryBuffer.Dequeue(); Assert.AreEqual(telemetry, actual.First()); } } [TestClass] public class ConstructorTest : PersistenceChannelTest { /// <summary> /// Testing that creating multiple instances of PersistenceChannel and Disposing them is not causing a deadlock. /// </summary> [Owner("mihailsm")] [TestMethod] public void TestPersistenceChannelConstructorAndDisposeOnDeadlock() { ServiceLocator.AddService<BaseStorageService>(new StorageService()); List<Task> taskList = new List<Task>(); for (int i = 0; i < 500; i++) { var task = new Task(Action); task.Start(); taskList.Add(task); } var completed = Task.WaitAll(taskList.ToArray(), 5000); Assert.IsTrue(completed, "tasks did not finish. Potential deadlock problem."); } private void Action() { var channel = new PersistenceChannel(); channel.Dispose(); } } } }
36.853503
125
0.580712
[ "MIT" ]
bitstadium/HockeySDK-Windows
Src/Kit.UWP.Tests/Channel/Persistence/PersistenceChannelTest.cs
5,788
C#
using System; using AM; using AM.Json; using AM.Runtime; using AM.Xml; using ManagedIrbis.Quality; using ManagedIrbis.Quality.Rules; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTests.ManagedIrbis.Quality.Rules { [TestClass] public class Require461Test : RuleTest { [TestMethod] public void Require416_Construction_1() { Require461 check = new Require461(); Assert.IsNotNull(check); } [TestMethod] public void Require461_FieldSpec_1() { Require461 check = new Require461(); Assert.AreEqual("461", check.FieldSpec); } [TestMethod] //[ExpectedException(typeof(VerificationException))] public void Require461_CheckRecord_1() { RuleContext context = GetContext(); Require461 check = new Require461(); RuleReport report = check.CheckRecord(context); Assert.IsNotNull(report); } } }
23.386364
60
0.616132
[ "MIT" ]
amironov73/ManagedClient.45
Source/UnitTests/ManagedIrbis/Quality/Rules/Require461Test.cs
1,031
C#
// ReSharper disable RedundantUsingDirective // ReSharper disable DoNotCallOverridableMethodsInConstructor // ReSharper disable InconsistentNaming // ReSharper disable PartialTypeWithSinglePart // ReSharper disable PartialMethodWithSinglePart // ReSharper disable RedundantNameQualifier // ReSharper disable UnusedMember.Global #pragma warning disable 1591 // Ignore "Missing XML Comment" warning using System; using System.CodeDom.Compiler; using System.Collections.Generic; using Microsoft.Extensions.Configuration; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; namespace Geco.Tests.Database.Model { [GeneratedCode("Geco", "1.0.5.0")] public partial class AddressType { // Key Properties public int AddressTypeID { get; set; } // Scalar Properties public string Name { get; set; } public Guid Rowguid { get; set; } public DateTime ModifiedDate { get; set; } // Reverse navigation public List<BusinessEntityAddress> BusinessEntityAddresses { get; set; } public AddressType() { BusinessEntityAddresses = new List<BusinessEntityAddress>(); } } }
31.815789
80
0.727047
[ "Apache-2.0" ]
raminrahimzada/Geco
Test/Geco.Tests/Database/Model/AddressType.cs
1,209
C#
using System.ComponentModel; using System.ComponentModel.Composition; namespace Beeffective.Presentation.Main { [Export(typeof(IMainView))] public partial class MainWindow : IMainView { public MainWindow() { InitializeComponent(); } protected override void OnClosing(CancelEventArgs e) { if (DataContext is MainViewModel viewModel) { viewModel.Close(); } base.OnClosing(e); } } }
21.791667
60
0.575526
[ "MIT" ]
PeterMilovcik/Beeffective
Beeffective.Presentation/Main/MainWindow.xaml.cs
525
C#
#if (OBI_BURST && OBI_MATHEMATICS && OBI_COLLECTIONS) using UnityEngine; using Unity.Jobs; using Unity.Mathematics; using Unity.Collections; using System.Collections; using System.Collections.Generic; namespace Obi { public class BurstSolverImpl : ISolverImpl { ObiSolver m_Solver; public ObiSolver abstraction { get { return m_Solver; } } public int particleCount { get { return m_Solver.positions.count; } } public int activeParticleCount { get { return activeParticles.Length; } } public BurstInertialFrame inertialFrame { get { return m_InertialFrame; } } public BurstAffineTransform solverToWorld { get { return m_InertialFrame.frame; } } public BurstAffineTransform worldToSolver { get { return m_InertialFrame.frame.Inverse(); } } private const int maxBatches = 17; private ConstraintBatcher constraintBatcher; // Per-type constraints array: IBurstConstraintsImpl[] constraints; // particle contact generation: public ParticleGrid particleGrid; public NativeArray<BurstContact> particleContacts; public NativeArray<BatchData> particleBatchData; // fluid interaction generation: public NativeArray<FluidInteraction> fluidInteractions; public NativeArray<BatchData> fluidBatchData; // collider contact generation: private BurstColliderWorld colliderGrid; public NativeArray<BurstContact> colliderContacts; // misc data: public NativeList<int> activeParticles; private NativeList<int> deformableTriangles; public NativeList<int> simplices; public SimplexCounts simplexCounts; private BurstInertialFrame m_InertialFrame; // local to world inertial frame. private int scheduledJobCounter = 0; // cached particle data arrays (just wrappers over raw unmanaged data held by the abstract solver) public NativeArray<float4> positions; public NativeArray<float4> restPositions; public NativeArray<float4> prevPositions; public NativeArray<float4> renderablePositions; public NativeArray<quaternion> orientations; public NativeArray<quaternion> restOrientations; public NativeArray<quaternion> prevOrientations; public NativeArray<quaternion> renderableOrientations; public NativeArray<float4> velocities; public NativeArray<float4> angularVelocities; public NativeArray<float> invMasses; public NativeArray<float> invRotationalMasses; public NativeArray<float4> invInertiaTensors; public NativeArray<float4> externalForces; public NativeArray<float4> externalTorques; public NativeArray<float4> wind; public NativeArray<float4> positionDeltas; public NativeArray<quaternion> orientationDeltas; public NativeArray<int> positionConstraintCounts; public NativeArray<int> orientationConstraintCounts; public NativeArray<int> collisionMaterials; public NativeArray<int> phases; public NativeArray<float4> anisotropies; public NativeArray<float4> principalRadii; public NativeArray<float4> normals; public NativeArray<float4> vorticities; public NativeArray<float4> fluidData; public NativeArray<float4> userData; public NativeArray<float> smoothingRadii; public NativeArray<float> buoyancies; public NativeArray<float> restDensities; public NativeArray<float> viscosities; public NativeArray<float> surfaceTension; public NativeArray<float> vortConfinement; public NativeArray<float> athmosphericDrag; public NativeArray<float> athmosphericPressure; public NativeArray<float> diffusion; public NativeArray<int4> cellCoords; public NativeArray<BurstAabb> simplexBounds; public BurstSolverImpl(ObiSolver solver) { this.m_Solver = solver; // Initialize collision world: GetOrCreateColliderWorld(); colliderGrid.IncreaseReferenceCount(); activeParticles = new NativeList<int>(64, Allocator.Persistent); deformableTriangles = new NativeList<int>(64, Allocator.Persistent); simplices = new NativeList<int>(64, Allocator.Persistent); // Initialize contact generation acceleration structure: particleGrid = new ParticleGrid(); // Initialize constraint batcher: constraintBatcher = new ConstraintBatcher(maxBatches); // Initialize constraint arrays: constraints = new IBurstConstraintsImpl[Oni.ConstraintTypeCount]; constraints[(int)Oni.ConstraintType.Tether] = new BurstTetherConstraints(this); constraints[(int)Oni.ConstraintType.Volume] = new BurstVolumeConstraints(this); constraints[(int)Oni.ConstraintType.Chain] = new BurstChainConstraints(this); constraints[(int)Oni.ConstraintType.Bending] = new BurstBendConstraints(this); constraints[(int)Oni.ConstraintType.Distance] = new BurstDistanceConstraints(this); constraints[(int)Oni.ConstraintType.ShapeMatching] = new BurstShapeMatchingConstraints(this); constraints[(int)Oni.ConstraintType.BendTwist] = new BurstBendTwistConstraints(this); constraints[(int)Oni.ConstraintType.StretchShear] = new BurstStretchShearConstraints(this); constraints[(int)Oni.ConstraintType.Pin] = new BurstPinConstraints(this); constraints[(int)Oni.ConstraintType.ParticleCollision] = new BurstParticleCollisionConstraints(this); constraints[(int)Oni.ConstraintType.Density] = new BurstDensityConstraints(this); constraints[(int)Oni.ConstraintType.Collision] = new BurstColliderCollisionConstraints(this); constraints[(int)Oni.ConstraintType.Skin] = new BurstSkinConstraints(this); constraints[(int)Oni.ConstraintType.Aerodynamics] = new BurstAerodynamicConstraints(this); constraints[(int)Oni.ConstraintType.Stitch] = new BurstStitchConstraints(this); constraints[(int)Oni.ConstraintType.ParticleFriction] = new BurstParticleFrictionConstraints(this); constraints[(int)Oni.ConstraintType.Friction] = new BurstColliderFrictionConstraints(this); var c = constraints[(int)Oni.ConstraintType.Collision] as BurstColliderCollisionConstraints; c.CreateConstraintsBatch(); var f = constraints[(int)Oni.ConstraintType.Friction] as BurstColliderFrictionConstraints; f.CreateConstraintsBatch(); } public void Destroy() { for (int i = 0; i < constraints.Length; ++i) if (constraints[i] != null) constraints[i].Dispose(); // Get rid of particle and collider grids: particleGrid.Dispose(); if (colliderGrid != null) colliderGrid.DecreaseReferenceCount(); constraintBatcher.Dispose(); if (activeParticles.IsCreated) activeParticles.Dispose(); if (deformableTriangles.IsCreated) deformableTriangles.Dispose(); if (simplices.IsCreated) simplices.Dispose(); if (simplexBounds.IsCreated) simplexBounds.Dispose(); if (particleContacts.IsCreated) particleContacts.Dispose(); if (particleBatchData.IsCreated) particleBatchData.Dispose(); if (fluidInteractions.IsCreated) fluidInteractions.Dispose(); if (fluidBatchData.IsCreated) fluidBatchData.Dispose(); if (colliderContacts.IsCreated) colliderContacts.Dispose(); } // Utility function to count scheduled jobs. Call it once per job. // Will JobHandle.ScheduleBatchedJobs once there's a good bunch of scheduled jobs. public void ScheduleBatchedJobsIfNeeded() { if (scheduledJobCounter++ > 16) { scheduledJobCounter = 0; JobHandle.ScheduleBatchedJobs(); } } private void GetOrCreateColliderWorld() { colliderGrid = GameObject.FindObjectOfType<BurstColliderWorld>(); if (colliderGrid == null) { var world = new GameObject("BurstCollisionWorld", typeof(BurstColliderWorld)); colliderGrid = world.GetComponent<BurstColliderWorld>(); } } public void InitializeFrame(Vector4 translation, Vector4 scale, Quaternion rotation) { m_InertialFrame = new BurstInertialFrame(translation, scale, rotation); } public void UpdateFrame(Vector4 translation, Vector4 scale, Quaternion rotation, float deltaTime) { m_InertialFrame.Update(translation, scale, rotation, deltaTime); } public void ApplyFrame(float worldLinearInertiaScale, float worldAngularInertiaScale, float deltaTime) { // inverse linear part: float4x4 linear = float4x4.TRS(float3.zero, inertialFrame.frame.rotation, math.rcp(inertialFrame.frame.scale.xyz)); float4x4 linearInv = math.transpose(linear); // non-inertial frame accelerations: float4 angularVel = math.mul(linearInv, math.mul(float4x4.Scale(inertialFrame.angularVelocity.xyz), linear)).diagonal(); float4 eulerAccel = math.mul(linearInv, math.mul(float4x4.Scale(inertialFrame.angularAcceleration.xyz), linear)).diagonal(); float4 inertialAccel = math.mul(linearInv, inertialFrame.acceleration); var applyInertialForces = new ApplyInertialForcesJob() { activeParticles = activeParticles, positions = positions, velocities = velocities, invMasses = invMasses, angularVel = angularVel, inertialAccel = inertialAccel, eulerAccel = eulerAccel, worldLinearInertiaScale = worldLinearInertiaScale, worldAngularInertiaScale = worldAngularInertiaScale, deltaTime = deltaTime, }; applyInertialForces.Schedule(activeParticleCount, 64).Complete(); } public int GetDeformableTriangleCount() { return deformableTriangles.Length / 3; } public void SetDeformableTriangles(int[] indices, int num, int destOffset) { if (destOffset + num >= deformableTriangles.Length / 3) deformableTriangles.ResizeUninitialized((destOffset + num) * 3); for (int i = 0; i < num * 3; ++i) deformableTriangles[i + destOffset * 3] = indices[i]; } public int RemoveDeformableTriangles(int num, int sourceOffset) { if (deformableTriangles.IsCreated) { int amount = deformableTriangles.Length / 3; if (num < 0) { deformableTriangles.Clear(); return amount; } int set = ClampArrayAccess(amount, num, sourceOffset); int end = sourceOffset + set; for (int i = end * 3 - 1; i >= sourceOffset * 3; --i) deformableTriangles.RemoveAtSwapBack(i); return set; } return 0; } public void SetSimplices(int[] simplices, SimplexCounts counts) { this.simplices.CopyFrom(simplices); this.simplexCounts = counts; if (simplexBounds.IsCreated) simplexBounds.Dispose(); simplexBounds = new NativeArray<BurstAabb>(counts.simplexCount, Allocator.Persistent); cellCoords = abstraction.cellCoords.AsNativeArray<int4>(); } public void SetActiveParticles(int[] indices, int num) { int set = ClampArrayAccess(particleCount, num, 0); activeParticles.ResizeUninitialized(set); for (int i = 0; i < num; ++i) activeParticles[i] = indices[i]; activeParticles.Sort(); } int ClampArrayAccess(int size, int num, int offset) { return math.min(num, math.max(0, size - offset)); } public JobHandle RecalculateInertiaTensors(JobHandle inputDeps) { var updateInertiaTensors = new UpdateInertiaTensorsJob() { activeParticles = activeParticles, inverseMasses = abstraction.invMasses.AsNativeArray<float>(), inverseRotationalMasses = abstraction.invRotationalMasses.AsNativeArray<float>(), principalRadii = abstraction.principalRadii.AsNativeArray<float4>(), inverseInertiaTensors = abstraction.invInertiaTensors.AsNativeArray<float4>(), }; return updateInertiaTensors.Schedule(activeParticles.Length, 128, inputDeps); } public void GetBounds(ref Vector3 min, ref Vector3 max) { if (!activeParticles.IsCreated) return; int chunkSize = 4; NativeArray<BurstAabb> bounds = new NativeArray<BurstAabb>(activeParticles.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); var particleBoundsJob = new ParticleToBoundsJob() { activeParticles = activeParticles, positions = positions, radii = principalRadii, bounds = bounds }; JobHandle reduction = particleBoundsJob.Schedule(activeParticles.Length, 64); // parallel reduction: int chunks = bounds.Length; int stride = 1; while (chunks > 1) { var reductionJob = new BoundsReductionJob() { bounds = bounds, stride = stride, size = chunkSize, }; reduction = reductionJob.Schedule(chunks, 1, reduction); chunks = (int)math.ceil(chunks / (float)chunkSize); stride *= chunkSize; } reduction.Complete(); // the parallel reduction leaves the final bounds in the first entry: if (bounds.Length > 0) { min = bounds[0].min.xyz; max = bounds[0].max.xyz; } bounds.Dispose(); } public void ResetForces() { abstraction.externalForces.WipeToZero(); abstraction.externalTorques.WipeToZero(); abstraction.wind.WipeToZero(); // We're at the end of a whole step (not a substep), so dispose of contact buffers: if (particleContacts.IsCreated) particleContacts.Dispose(); if (particleBatchData.IsCreated) particleBatchData.Dispose(); if (colliderContacts.IsCreated) colliderContacts.Dispose(); } public int GetConstraintCount(Oni.ConstraintType type) { if ((int)type > 0 && (int)type < constraints.Length) return constraints[(int)type].GetConstraintCount(); return 0; } public void GetCollisionContacts(Oni.Contact[] contacts, int count) { NativeArray<Oni.Contact>.Copy(colliderContacts.Reinterpret<Oni.Contact>(),0, contacts,0,count); } public void GetParticleCollisionContacts(Oni.Contact[] contacts, int count) { NativeArray<Oni.Contact>.Copy(particleContacts.Reinterpret<Oni.Contact>(),0, contacts,0,count); } public void SetParameters(Oni.SolverParameters parameters) { // No need to implement. This backend grabs parameters from the abstraction when it needs them. } public void SetConstraintGroupParameters(Oni.ConstraintType type, ref Oni.ConstraintParameters parameters) { // No need to implement. This backend grabs parameters from the abstraction when it needs them. } public void ParticleCountChanged(ObiSolver solver) { positions = abstraction.positions.AsNativeArray<float4>(); restPositions = abstraction.restPositions.AsNativeArray<float4>(); prevPositions = abstraction.prevPositions.AsNativeArray<float4>(); renderablePositions = abstraction.renderablePositions.AsNativeArray<float4>(); orientations = abstraction.orientations.AsNativeArray<quaternion>(); restOrientations = abstraction.restOrientations.AsNativeArray<quaternion>(); prevOrientations = abstraction.prevOrientations.AsNativeArray<quaternion>(); renderableOrientations = abstraction.renderableOrientations.AsNativeArray<quaternion>(); velocities = abstraction.velocities.AsNativeArray<float4>(); angularVelocities = abstraction.angularVelocities.AsNativeArray<float4>(); invMasses = abstraction.invMasses.AsNativeArray<float>(); invRotationalMasses = abstraction.invRotationalMasses.AsNativeArray<float>(); invInertiaTensors = abstraction.invInertiaTensors.AsNativeArray<float4>(); externalForces = abstraction.externalForces.AsNativeArray<float4>(); externalTorques = abstraction.externalTorques.AsNativeArray<float4>(); wind = abstraction.wind.AsNativeArray<float4>(); positionDeltas = abstraction.positionDeltas.AsNativeArray<float4>(); orientationDeltas = abstraction.orientationDeltas.AsNativeArray<quaternion>(); positionConstraintCounts = abstraction.positionConstraintCounts.AsNativeArray<int>(); orientationConstraintCounts = abstraction.orientationConstraintCounts.AsNativeArray<int>(); collisionMaterials = abstraction.collisionMaterials.AsNativeArray<int>(); phases = abstraction.phases.AsNativeArray<int>(); anisotropies = abstraction.anisotropies.AsNativeArray<float4>(); principalRadii = abstraction.principalRadii.AsNativeArray<float4>(); normals = abstraction.normals.AsNativeArray<float4>(); vorticities = abstraction.vorticities.AsNativeArray<float4>(); fluidData = abstraction.fluidData.AsNativeArray<float4>(); userData = abstraction.userData.AsNativeArray<float4>(); smoothingRadii = abstraction.smoothingRadii.AsNativeArray<float>(); buoyancies = abstraction.buoyancies.AsNativeArray<float>(); restDensities = abstraction.restDensities.AsNativeArray<float>(); viscosities = abstraction.viscosities.AsNativeArray<float>(); surfaceTension = abstraction.surfaceTension.AsNativeArray<float>(); vortConfinement = abstraction.vortConfinement.AsNativeArray<float>(); athmosphericDrag = abstraction.atmosphericDrag.AsNativeArray<float>(); athmosphericPressure = abstraction.atmosphericPressure.AsNativeArray<float>(); diffusion = abstraction.diffusion.AsNativeArray<float>(); } public void SetRigidbodyArrays(ObiSolver solver) { // No need to implement. This backend grabs arrays from the abstraction when it needs them. } public IConstraintsBatchImpl CreateConstraintsBatch(Oni.ConstraintType type) { return constraints[(int)type].CreateConstraintsBatch(); } public void DestroyConstraintsBatch(IConstraintsBatchImpl batch) { if (batch != null) constraints[(int)batch.constraintType].RemoveBatch(batch); } public IObiJobHandle CollisionDetection(float stepTime) { var fluidHandle = FindFluidParticles(); var inertiaUpdate = RecalculateInertiaTensors(fluidHandle); return new BurstJobHandle(GenerateContacts(inertiaUpdate, stepTime)); } protected JobHandle FindFluidParticles() { var d = constraints[(int)Oni.ConstraintType.Density] as BurstDensityConstraints; // Update positions: var findFluidJob = new FindFluidParticlesJob() { activeParticles = activeParticles, phases = m_Solver.phases.AsNativeArray<int>(), fluidParticles = d.fluidParticles, }; return findFluidJob.Schedule(); } protected JobHandle UpdateSimplexBounds(JobHandle inputDeps, float deltaTime) { var buildAabbs = new BuildSimplexAabbs { radii = principalRadii, fluidRadii = smoothingRadii, positions = positions, velocities = velocities, simplices = simplices, simplexCounts = simplexCounts, simplexBounds = simplexBounds, particleMaterialIndices = abstraction.collisionMaterials.AsNativeArray<int>(), collisionMaterials = ObiColliderWorld.GetInstance().collisionMaterials.AsNativeArray<BurstCollisionMaterial>(), collisionMargin = abstraction.parameters.collisionMargin, continuousCollisionDetection = abstraction.parameters.continuousCollisionDetection, dt = deltaTime, }; return buildAabbs.Schedule(simplexCounts.simplexCount, 32, inputDeps); } protected JobHandle GenerateContacts(JobHandle inputDeps, float deltaTime) { // Dispose of previous fluid interactions. // We need fluid data during interpolation, for anisotropic fluid particles. For this reason, // we can't dispose of these arrays in ResetForces() at the end of each full step. They must use persistent allocation. if (fluidInteractions.IsCreated) fluidInteractions.Dispose(); if (fluidBatchData.IsCreated) fluidBatchData.Dispose(); // get constraint parameters for constraint types that depend on broadphases: var collisionParameters = m_Solver.GetConstraintParameters(Oni.ConstraintType.Collision); var particleCollisionParameters = m_Solver.GetConstraintParameters(Oni.ConstraintType.ParticleCollision); var densityParameters = m_Solver.GetConstraintParameters(Oni.ConstraintType.Density); // if no enabled constraints that require broadphase info, skip it entirely. if (collisionParameters.enabled || particleCollisionParameters.enabled || densityParameters.enabled) { // update the bounding box of each simplex: inputDeps = UpdateSimplexBounds(inputDeps, deltaTime); // generate particle-particle and particle-collider interactions in parallel: JobHandle generateParticleInteractionsHandle = inputDeps, generateContactsHandle = inputDeps; // particle-particle interactions (contacts, fluids) if (particleCollisionParameters.enabled || densityParameters.enabled) { particleGrid.Update(this, deltaTime, inputDeps); generateParticleInteractionsHandle = particleGrid.GenerateContacts(this, deltaTime); } // particle-collider interactions (contacts) if (collisionParameters.enabled) { generateContactsHandle = colliderGrid.GenerateContacts(this, deltaTime, inputDeps); } JobHandle.CombineDependencies(generateParticleInteractionsHandle, generateContactsHandle).Complete(); // allocate arrays for interactions and batch data: particleContacts = new NativeArray<BurstContact>(particleGrid.particleContactQueue.Count, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); particleBatchData = new NativeArray<BatchData>(maxBatches, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); fluidInteractions = new NativeArray<FluidInteraction>(particleGrid.fluidInteractionQueue.Count, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); fluidBatchData = new NativeArray<BatchData>(maxBatches, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); colliderContacts = new NativeArray<BurstContact>(colliderGrid.colliderContactQueue.Count, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); // dequeue contacts/interactions into temporary arrays: var rawParticleContacts = new NativeArray<BurstContact>(particleGrid.particleContactQueue.Count, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var sortedParticleContacts = new NativeArray<BurstContact>(particleGrid.particleContactQueue.Count, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var rawFluidInteractions = new NativeArray<FluidInteraction>(particleGrid.fluidInteractionQueue.Count, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); DequeueIntoArrayJob<BurstContact> dequeueParticleContacts = new DequeueIntoArrayJob<BurstContact>() { InputQueue = particleGrid.particleContactQueue, OutputArray = rawParticleContacts }; DequeueIntoArrayJob<FluidInteraction> dequeueFluidInteractions = new DequeueIntoArrayJob<FluidInteraction>() { InputQueue = particleGrid.fluidInteractionQueue, OutputArray = rawFluidInteractions }; DequeueIntoArrayJob<BurstContact> dequeueColliderContacts = new DequeueIntoArrayJob<BurstContact>() { InputQueue = colliderGrid.colliderContactQueue, OutputArray = colliderContacts }; var dequeueHandle = JobHandle.CombineDependencies(dequeueParticleContacts.Schedule(), dequeueFluidInteractions.Schedule(), dequeueColliderContacts.Schedule()); // Sort contacts for jitter-free gauss-seidel (sequential) solving: dequeueHandle = ConstraintSorter.SortConstraints<BurstContact>(simplexCounts.simplexCount, rawParticleContacts, ref sortedParticleContacts, dequeueHandle); ContactProvider contactProvider = new ContactProvider() { contacts = sortedParticleContacts, sortedContacts = particleContacts, simplices = simplices, simplexCounts = simplexCounts }; FluidInteractionProvider fluidProvider = new FluidInteractionProvider() { interactions = rawFluidInteractions, sortedInteractions = fluidInteractions, }; // batch particle contacts: var activeParticleBatchCount = new NativeArray<int>(1, Allocator.TempJob); var particleBatchHandle = constraintBatcher.BatchConstraints(ref contactProvider, particleCount, ref particleBatchData, ref activeParticleBatchCount, dequeueHandle); // batch fluid interactions: var activeFluidBatchCount = new NativeArray<int>(1, Allocator.TempJob); var fluidBatchHandle = constraintBatcher.BatchConstraints(ref fluidProvider, particleCount, ref fluidBatchData, ref activeFluidBatchCount, dequeueHandle); JobHandle.CombineDependencies(particleBatchHandle, fluidBatchHandle).Complete(); // Generate particle contact/friction batches: var pc = constraints[(int)Oni.ConstraintType.ParticleCollision] as BurstParticleCollisionConstraints; pc.batches.Clear(); var pf = constraints[(int)Oni.ConstraintType.ParticleFriction] as BurstParticleFrictionConstraints; pf.batches.Clear(); for (int i = 0; i < activeParticleBatchCount[0]; ++i) { var cbatch = pc.CreateConstraintsBatch() as BurstParticleCollisionConstraintsBatch; cbatch.batchData = particleBatchData[i]; var fbatch = pf.CreateConstraintsBatch() as BurstParticleFrictionConstraintsBatch; fbatch.batchData = particleBatchData[i]; } // Generate fluid interaction batches: var dc = constraints[(int)Oni.ConstraintType.Density] as BurstDensityConstraints; dc.batches.Clear(); for (int i = 0; i < activeFluidBatchCount[0]; ++i) { var batch = dc.CreateConstraintsBatch() as BurstDensityConstraintsBatch; batch.batchData = fluidBatchData[i]; } // dispose of temporary buffers: rawParticleContacts.Dispose(); rawFluidInteractions.Dispose(); sortedParticleContacts.Dispose(); activeParticleBatchCount.Dispose(); activeFluidBatchCount.Dispose(); } return inputDeps; } public IObiJobHandle Substep(float stepTime, float substepTime, int substeps) { // Apply aerodynamics JobHandle aerodynamicsHandle = constraints[(int)Oni.ConstraintType.Aerodynamics].Project(new JobHandle(), stepTime, substepTime, substeps); // Predict positions: var predictPositions = new PredictPositionsJob() { activeParticles = activeParticles, phases = phases, buoyancies = buoyancies, externalForces = externalForces, inverseMasses = invMasses, positions = positions, previousPositions = prevPositions, velocities = velocities, externalTorques = externalTorques, inverseRotationalMasses = invRotationalMasses, orientations = orientations, previousOrientations = prevOrientations, angularVelocities = angularVelocities, gravity = new float4(m_Solver.parameters.gravity, 0), deltaTime = substepTime, is2D = abstraction.parameters.mode == Oni.SolverParameters.Mode.Mode2D }; JobHandle predictPositionsHandle = predictPositions.Schedule(activeParticles.Length, 128, aerodynamicsHandle); // Project position constraints: JobHandle projectionHandle = ApplyConstraints(predictPositionsHandle, stepTime, substepTime, substeps); // Update velocities: var updateVelocitiesJob = new UpdateVelocitiesJob() { activeParticles = activeParticles, inverseMasses = invMasses, previousPositions = prevPositions, positions = positions, velocities = velocities, inverseRotationalMasses = invRotationalMasses, previousOrientations = prevOrientations, orientations = orientations, angularVelocities = angularVelocities, deltaTime = substepTime, is2D = abstraction.parameters.mode == Oni.SolverParameters.Mode.Mode2D }; JobHandle updateVelocitiesHandle = updateVelocitiesJob.Schedule(activeParticles.Length, 128, projectionHandle); // velocity constraints: JobHandle velocityCorrectionsHandle = ApplyVelocityCorrections(updateVelocitiesHandle, substepTime); // Update positions: var updatePositionsJob = new UpdatePositionsJob() { activeParticles = activeParticles, positions = positions, previousPositions = prevPositions, velocities = velocities, orientations = orientations, previousOrientations = prevOrientations, angularVelocities = angularVelocities, velocityScale = math.pow(1 - math.clamp(m_Solver.parameters.damping, 0, 1), substepTime), sleepThreshold = m_Solver.parameters.sleepThreshold }; JobHandle updatePositionsHandle = updatePositionsJob.Schedule(activeParticles.Length, 128, velocityCorrectionsHandle); return new BurstJobHandle(updatePositionsHandle); } private JobHandle ApplyVelocityCorrections(JobHandle inputDeps, float deltaTime) { var densityParameters = m_Solver.GetConstraintParameters(Oni.ConstraintType.Density); if (densityParameters.enabled) { var d = constraints[(int)Oni.ConstraintType.Density] as BurstDensityConstraints; if (d != null) { return d.ApplyVelocityCorrections(inputDeps, deltaTime); } } return inputDeps; } private JobHandle ApplyConstraints(JobHandle inputDeps, float stepTime, float substepTime, int substeps) { // calculate max amount of iterations required, and initialize constraints.. int maxIterations = 0; for (int i = 0; i < Oni.ConstraintTypeCount; ++i) { var parameters = m_Solver.GetConstraintParameters((Oni.ConstraintType)i); if (parameters.enabled) { maxIterations = math.max(maxIterations, parameters.iterations); inputDeps = constraints[i].Initialize(inputDeps, substepTime); } } // calculate iteration paddings: int[] padding = new int[Oni.ConstraintTypeCount]; for (int i = 0; i < Oni.ConstraintTypeCount; ++i) { var parameters = m_Solver.GetConstraintParameters((Oni.ConstraintType)i); if (parameters.enabled && parameters.iterations > 0) padding[i] = (int)math.ceil(maxIterations / (float)parameters.iterations); else padding[i] = maxIterations; } // perform projection iterations: for (int i = 1; i < maxIterations; ++i) { for (int j = 0; j < Oni.ConstraintTypeCount; ++j) { if (j != (int)Oni.ConstraintType.Aerodynamics) { var parameters = m_Solver.GetConstraintParameters((Oni.ConstraintType)j); if (parameters.enabled && i % padding[j] == 0) inputDeps = constraints[j].Project(inputDeps, stepTime, substepTime, substeps); } } } // final iteration, all groups together: for (int i = 0; i < Oni.ConstraintTypeCount; ++i) { if (i != (int)Oni.ConstraintType.Aerodynamics) { var parameters = m_Solver.GetConstraintParameters((Oni.ConstraintType)i); if (parameters.enabled && parameters.iterations > 0) inputDeps = constraints[i].Project(inputDeps, stepTime, substepTime, substeps); } } // Despite friction constraints being applied after collision (since coulomb friction depends on normal impulse) // we perform a collision iteration right at the end to ensure the final state meets the Signorini-Fichera conditions. var param = m_Solver.GetConstraintParameters(Oni.ConstraintType.ParticleCollision); if (param.enabled && param.iterations > 0) inputDeps = constraints[(int)Oni.ConstraintType.ParticleCollision].Project(inputDeps, stepTime, substepTime, substeps); param = m_Solver.GetConstraintParameters(Oni.ConstraintType.Collision); if (param.enabled && param.iterations > 0) inputDeps = constraints[(int)Oni.ConstraintType.Collision].Project(inputDeps, stepTime, substepTime, substeps); return inputDeps; } public void ApplyInterpolation(ObiNativeVector4List startPositions, ObiNativeQuaternionList startOrientations, float stepTime, float unsimulatedTime) { // Interpolate particle positions and orientations. var interpolate = new InterpolationJob() { positions = positions, startPositions = startPositions.AsNativeArray<float4>(), renderablePositions = renderablePositions, orientations = orientations, startOrientations = startOrientations.AsNativeArray<quaternion>(), renderableOrientations = renderableOrientations, deltaTime = stepTime, unsimulatedTime = unsimulatedTime, interpolationMode = m_Solver.parameters.interpolation }; JobHandle jobHandle = interpolate.Schedule(m_Solver.positions.count, 128); // Update deformable triangle normals var updateNormals = new UpdateNormalsJob() { renderPositions = renderablePositions, deformableTriangles = deformableTriangles, normals = normals }; jobHandle = updateNormals.Schedule(jobHandle); // fluid laplacian/anisotropy: var d = constraints[(int)Oni.ConstraintType.Density] as BurstDensityConstraints; if (d != null) jobHandle = d.CalculateAnisotropyLaplacianSmoothing(jobHandle); // update axis: var updatePrincipalAxis = new UpdatePrincipalAxisJob() { activeParticles = activeParticles, renderableOrientations = renderableOrientations, phases = phases, principalRadii = principalRadii, principalAxis = anisotropies, }; jobHandle = updatePrincipalAxis.Schedule(activeParticles.Length, 128, jobHandle); jobHandle.Complete(); } public void InterpolateDiffuseProperties(ObiNativeVector4List properties, ObiNativeVector4List diffusePositions, ObiNativeVector4List diffuseProperties, ObiNativeIntList neighbourCount, int diffuseCount) { particleGrid.InterpolateDiffuseProperties(this, properties.AsNativeArray<float4>(), diffusePositions.AsNativeArray<float4>(), diffuseProperties.AsNativeArray<float4>(), neighbourCount.AsNativeArray<int>(), diffuseCount).Complete(); } public int GetParticleGridSize() { return particleGrid.grid.usedCells.Length; } public void GetParticleGrid(ObiNativeAabbList cells) { particleGrid.GetCells(cells); } } } #endif
44.191209
181
0.622345
[ "MIT" ]
Xuzefan-Create/Unity3d-PhysicsGun
Unity3d-PhysicsGun/Assets/Obi/Scripts/Common/Backends/Burst/Solver/BurstSolverImpl.cs
40,216
C#
using ProtoBuf; namespace ETHotfix { public interface IMessage { } public interface IRequest: IMessage { int RpcId { get; set; } } public interface IResponse : IMessage { int Error { get; set; } string Message { get; set; } int RpcId { get; set; } } public class ResponseMessage : IResponse { public int Error { get; set; } public string Message { get; set; } public int RpcId { get; set; } } }
15.777778
41
0.650235
[ "MIT" ]
AlunWorker/ET-
Unity/Hotfix/Module/Message/IMessage.cs
428
C#
namespace DFC.App.JobProfiles.HowToBecome.Data.Enums { public enum MessageContentType { JobProfile, ApprenticeshipLink, UniversityLink, CollegeLink, ApprenticeshipRequirement, UniversityRequirement, CollegeRequirement, ApprenticeshipEntryRequirements, UniversityEntryRequirements, CollegeEntryRequirements, Registration, } }
25
53
0.670588
[ "MIT" ]
SkillsFundingAgency/dfc-app-howtobecome
DFC.App.JobProfiles.HowToBecome.Data/Enums/MessageContentType.cs
427
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Charlotte.Commons; namespace Charlotte.Games { /// <summary> /// ゲームの状態を保持する。 /// プレイヤーのレベルとか保有アイテムといった概念が入ってくることを想定して、独立したクラスとする。 /// </summary> public class GameStatus { // (テスト時など)特にフィールドを設定せずにインスタンスを生成する使い方を想定して、 // 全てのパラメータはデフォルト値で初期化すること。 private const int MAX_HP = 10; /// <summary> /// プレイヤーの最大HP /// </summary> public int MaxHP = MAX_HP; /// <summary> /// (マップ入場時の)プレイヤーのHP /// </summary> public int StartHP = MAX_HP; /// <summary> /// スタート地点の Direction 値 /// 5 == 中央(デフォルト) == ゲームスタート時 /// 2 == 下から入場 /// 4 == 左から入場 /// 6 == 右から入場 /// 8 == 上から入場 /// 101 == ロード地点 /// </summary> public int StartPointDirection = 5; /// <summary> /// (マップ入場時に)プレイヤーが左を向いているか /// </summary> public bool StartFacingLeft = false; /// <summary> /// 最後のマップを退場した方向 /// 5 == 中央(デフォルト) == 死亡・ゲーム終了時 /// 2 == 下から退場 /// 4 == 左から退場 /// 6 == 右から退場 /// 8 == 上から退場 /// </summary> public int ExitDirection = 5; /// <summary> /// (マップ入場時に)プレイヤーが装備している武器 /// </summary> public Player.武器_e Start_武器 = Player.武器_e.NORMAL; // ---- game_進行・インベントリ ---- public bool 神奈子を倒した = false; // ---- // <---- prm public string Serialize() { List<string> dest = new List<string>(); // ★★★ シリアライズ_ここから ★★★ dest.Add("" + this.MaxHP); dest.Add("" + this.StartHP); dest.Add("" + this.StartPointDirection); dest.Add("" + (this.StartFacingLeft ? 1 : 0)); dest.Add("" + this.ExitDirection); dest.Add("" + (int)this.Start_武器); dest.Add("" + (this.神奈子を倒した ? 1 : 0)); // ★★★ シリアライズ_ここまで ★★★ return AttachString.I.Untokenize(dest); } private void S_Deserialize(string value) { string[] lines = AttachString.I.Tokenize(value); int c = 0; // ★★★ デシリアライズ_ここから ★★★ this.MaxHP = int.Parse(lines[c++]); this.StartHP = int.Parse(lines[c++]); this.StartPointDirection = int.Parse(lines[c++]); this.StartFacingLeft = int.Parse(lines[c++]) != 0; this.ExitDirection = int.Parse(lines[c++]); this.Start_武器 = (Player.武器_e)int.Parse(lines[c++]); this.神奈子を倒した = int.Parse(lines[c++]) != 0; // ★★★ デシリアライズ_ここまで ★★★ } public static GameStatus Deserialize(string value) { GameStatus gameStatus = new GameStatus(); gameStatus.S_Deserialize(value); return gameStatus; } public GameStatus GetClone() { return Deserialize(this.Serialize()); } } }
20.848739
54
0.608626
[ "MIT" ]
soleil-taruto/Elsa
e20201210_YokoActTM_Demo2_old/Elsa20200001/Elsa20200001/Games/GameStatus.cs
3,265
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 Util.Var.Events { using UnityEngine; public sealed class Vector2GameEventListenerBehaviour : GameEventListenerBehaviour<Vector2, Vector2EventReference> { } }
30.842105
118
0.508532
[ "MIT" ]
chris-m-cann/LDJam48
Assets/_Project/Scripts/Game/Util/Var/Events/Vector2GameEventListenerBehaviour.cs
586
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 guardduty-2017-11-28.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.GuardDuty.Model { /// <summary> /// Container for the parameters to the ListThreatIntelSets operation. /// Lists the ThreatIntelSets of the GuardDuty service specified by the detector ID. /// </summary> public partial class ListThreatIntelSetsRequest : AmazonGuardDutyRequest { private string _detectorId; private int? _maxResults; private string _nextToken; /// <summary> /// Gets and sets the property DetectorId. The detectorID that specifies the GuardDuty /// service whose ThreatIntelSets you want to list. /// </summary> [AWSProperty(Required=true)] public string DetectorId { get { return this._detectorId; } set { this._detectorId = value; } } // Check to see if DetectorId property is set internal bool IsSetDetectorId() { return this._detectorId != null; } /// <summary> /// Gets and sets the property MaxResults. You can use this parameter to indicate the /// maximum number of items that you want in the response. The default value is 7. The /// maximum value is 7. /// </summary> [AWSProperty(Min=1, Max=50)] public int MaxResults { get { return this._maxResults.GetValueOrDefault(); } set { this._maxResults = value; } } // Check to see if MaxResults property is set internal bool IsSetMaxResults() { return this._maxResults.HasValue; } /// <summary> /// Gets and sets the property NextToken. Pagination token to start retrieving threat /// intel sets from. /// </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.98913
107
0.631668
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/GuardDuty/Generated/Model/ListThreatIntelSetsRequest.cs
2,943
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Fluid.Values; namespace Fluid.Filters { public static class ArrayFilters { public static FilterCollection WithArrayFilters(this FilterCollection filters) { filters.AddFilter("join", Join); filters.AddFilter("first", First); filters.AddFilter("last", Last); filters.AddFilter("concat", Concat); filters.AddAsyncFilter("map", Map); filters.AddFilter("reverse", Reverse); filters.AddAsyncFilter("size", Size); filters.AddAsyncFilter("sort", Sort); filters.AddAsyncFilter("sort_natural", SortNatural); filters.AddFilter("uniq", Uniq); filters.AddAsyncFilter("where", Where); return filters; } public static FluidValue Join(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return input; } return new StringValue(String.Join(arguments.At(0).ToStringValue(), input.Enumerate().Select(x => x.ToStringValue()).ToArray())); } public static FluidValue First(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return input; } return input.Enumerate().FirstOrDefault() ?? NilValue.Instance; } public static FluidValue Last(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return input; } return input.Enumerate().LastOrDefault() ?? NilValue.Instance; } public static FluidValue Concat(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return input; } if (arguments.At(0).Type != FluidValues.Array) { return input; } var concat = new List<FluidValue>(); foreach(var item in input.Enumerate()) { concat.Add(item); } foreach (var item in arguments.At(0).Enumerate()) { concat.Add(item); } return new ArrayValue(concat); } public static async ValueTask<FluidValue> Map(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return input; } var member = arguments.At(0).ToStringValue(); var list = new List<FluidValue>(); foreach(var item in input.Enumerate()) { list.Add(await item.GetValueAsync(member, context)); } return new ArrayValue(list); } // https://github.com/Shopify/liquid/commit/842986a9721de11e71387732be51951285225977 public static async ValueTask<FluidValue> Where(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return input; } // First argument is the property name to match var member = arguments.At(0).ToStringValue(); // Second argument is the value to match, or 'true' if none is defined var targetValue = arguments.At(1).Or(BooleanValue.True); var list = new List<FluidValue>(); foreach (var item in input.Enumerate()) { var itemValue = await item.GetValueAsync(member, context); if (itemValue.Equals(targetValue)) { list.Add(item); } } return new ArrayValue(list); } public static FluidValue Reverse(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type != FluidValues.Array) { return input; } return new ArrayValue(input.Enumerate().Reverse()); } public static async ValueTask<FluidValue> Size(FluidValue input, FilterArguments arguments, TemplateContext context) { if (input.Type == FluidValues.Array) { return await ((ArrayValue)input).GetValueAsync("size", context); } if (input.Type == FluidValues.String) { return await ((StringValue)input).GetValueAsync("size", context); } return NilValue.Instance; } public static async ValueTask<FluidValue> Sort(FluidValue input, FilterArguments arguments, TemplateContext context) { if (arguments.Count > 0) { var member = arguments.At(0).ToStringValue(); var values = new List<KeyValuePair<FluidValue, object>>(); foreach (var item in input.Enumerate()) { values.Add(new KeyValuePair<FluidValue, object>(item, (await item.GetValueAsync(member, context)).ToObjectValue())); } var orderedValues = values.OrderBy(x => x.Value).Select(x => x.Key).ToList(); return new ArrayValue(orderedValues); } else { return new ArrayValue(input.Enumerate().OrderBy(x => { return x.ToStringValue(); }, StringComparer.Ordinal).ToArray()); } } public static async ValueTask<FluidValue> SortNatural(FluidValue input, FilterArguments arguments, TemplateContext context) { if (arguments.Count > 0) { var member = arguments.At(0).ToStringValue(); var values = new List<KeyValuePair<FluidValue, object>>(); foreach (var item in input.Enumerate()) { values.Add(new KeyValuePair<FluidValue, object>(item, (await item.GetValueAsync(member, context)).ToObjectValue())); } var orderedValues = values.OrderBy(x => x.Value).Select(x => x.Key).ToList(); return new ArrayValue(orderedValues); } else { return new ArrayValue(input.Enumerate().OrderBy(x => { return x.ToStringValue(); }, StringComparer.OrdinalIgnoreCase)); } } public static FluidValue Uniq(FluidValue input, FilterArguments arguments, TemplateContext context) { return new ArrayValue(input.Enumerate().Distinct().ToArray()); } } }
33.106977
141
0.541163
[ "MIT" ]
CharlotteA44/fluid
Fluid/Filters/ArrayFilters.cs
7,120
C#
namespace Smart.Resolver { using Smart.Navigation.Components; using Smart.Resolver.Configs; using Smart.Resolver.Scopes; public static class ResolverConfigExtensions { public static ResolverConfig UsePageContextScope(this ResolverConfig config) { config.Bind<PageContextStorage>().ToSelf().InSingletonScope(); config.Bind<PageContextKeyManager>().ToSelf().InSingletonScope(); return config; } public static IBindingNamedWithSyntax InPageContextScope(this IBindingInSyntax syntax, string name) { return syntax.InScope(_ => new PageContextScope(name)); } } }
29.565217
107
0.673529
[ "MIT" ]
usausa/Smart-Net-Navigation
Smart.Navigation.Resolver/Resolver/ResolverConfigExtensions.cs
680
C#
// ReSharper disable All // Expected number of suggestions: 2 using System.Collections.Generic; using System.Threading; using static System.Threading.Thread; namespace CSharp50.VS2019.AsyncAwait.AwaitTaskDelayInsteadOfCallingThreadSleep { class TaskDelayCanBeAwaitedInsteadOfCallingThreadSleepAndCallerYieldsIAsyncEnumerable { async IAsyncEnumerable<int> CanBeAwaited() { Thread.Sleep(0); Sleep(0); yield return 0; } } }
23.666667
89
0.708249
[ "MIT" ]
afrlan/Sharpen
tests/smoke/CSharp50.VS2019/AsyncAwait/AwaitTaskDelayInsteadOfCallingThreadSleep/TaskDelayCanBeAwaitedInsteadOfCallingThreadSleepAndCallerYieldsIAsyncEnumerable.cs
499
C#
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MetroFramework.Controls; using Guna.UI.WinForms; using Bunifu.Framework.UI; namespace Login.Classes { public static class InventoryMethods { public static void LoadProductInformation(MetroComboBox cmbProductName, GunaTextBox txtItemNumber, GunaTextBox txtStocks, BunifuDatepicker dtpDateCreation, MetroComboBox cmbCategory) { try { using (var connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["POS_SYSTEM"].ConnectionString)) { connection.Open(); string query = "SELECT product_item_code, product_stocks, product_category FROM tbl_products WHERE product_id = @product_id;"; using (var command = new MySqlCommand(query, connection)) { command.Parameters.Add("product_id", MySqlDbType.Int32).Value = cmbProductName.SelectedValue; MySqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { txtItemNumber.Text = reader["product_item_code"].ToString(); txtStocks.Text = reader["product_stocks"].ToString(); dtpDateCreation.Value = DateTime.Today; cmbCategory.Text = reader["product_category"].ToString(); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } public static void LoadComboBoxProducts(ComboBox comboBox) { try { using (var connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["POS_SYSTEM"].ConnectionString)) { connection.Open(); string query = "SELECT product_id, product_name FROM tbl_products ORDER BY product_name ASC;"; using (var command = new MySqlCommand(query, connection)) { var da = new MySqlDataAdapter { SelectCommand = command }; var dt = new DataTable(); da.Fill(dt); comboBox.DataSource = dt; comboBox.DisplayMember = "product_name"; comboBox.ValueMember = "product_id"; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } public static void LoadComboBoxSupplier(ComboBox comboBox) { try { using (var connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["POS_SYSTEM"].ConnectionString)) { connection.Open(); string query = "SELECT supplier_id, supplier_name FROM tbl_suppliers ORDER BY supplier_name ASC;"; using (var command = new MySqlCommand(query, connection)) { var da = new MySqlDataAdapter { SelectCommand = command }; var dt = new DataTable(); da.Fill(dt); comboBox.DataSource = dt; comboBox.DisplayMember = "supplier_name"; comboBox.ValueMember = "supplier_id"; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } public static void LoadGridViewProductStocksIn(DataGridView gridView) { try { using (var connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["POS_SYSTEM"].ConnectionString)) { connection.Open(); string query = "SELECT prodin.stockin_id, prod.product_name, prod.product_srp, prod.product_cost, prod.product_item_code, prod.product_stocks, prod.date_creation, prod.product_category FROM tbl_product_stockin prodin INNER JOIN tbl_products prod ON prodin.product_id = prod.product_id ORDER BY prod.product_name ASC;"; using (var command = new MySqlCommand(query, connection)) { var da = new MySqlDataAdapter { SelectCommand = command }; var dt = new DataTable(); da.Fill(dt); gridView.AutoGenerateColumns = false; gridView.DataSource = dt; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } public static void LoadGridViewProductCreation(DataGridView gridView) { try { using (var connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["POS_SYSTEM"].ConnectionString)) { connection.Open(); string query = @"SELECT prod.product_id, prod.product_name, CONCAT('₱',prod.product_srp) product_srp, CONCAT('₱', prod.product_cost) product_cost, prod.product_item_code, prod.product_stocks, date_format(prod.date_creation, '%M %d, %Y') AS date_creation, prod.product_category, supp.supplier_name FROM tbl_products prod INNER JOIN tbl_suppliers supp ON prod.supplier_id = supp.supplier_id ORDER BY prod.product_name ASC;"; using (var command = new MySqlCommand(query, connection)) { var da = new MySqlDataAdapter { SelectCommand = command }; var dt = new DataTable(); da.Fill(dt); gridView.AutoGenerateColumns = false; gridView.DataSource = dt; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
42.843137
442
0.523265
[ "Apache-2.0" ]
agurokeendavid/windows-form-pos
Login/Classes/InventoryMethods.cs
6,561
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the secretsmanager-2017-10-17.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SecretsManager.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SecretsManager.Model.Internal.MarshallTransformations { /// <summary> /// RotationRulesType Marshaller /// </summary> public class RotationRulesTypeMarshaller : IRequestMarshaller<RotationRulesType, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(RotationRulesType requestObject, JsonMarshallerContext context) { if(requestObject.IsSetAutomaticallyAfterDays()) { context.Writer.WritePropertyName("AutomaticallyAfterDays"); context.Writer.Write(requestObject.AutomaticallyAfterDays); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static RotationRulesTypeMarshaller Instance = new RotationRulesTypeMarshaller(); } }
34
112
0.695446
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SecretsManager/Generated/Model/Internal/MarshallTransformations/RotationRulesTypeMarshaller.cs
2,108
C#
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Running; using BenchmarkDotNet.Validators; using DirectionalPathingLayers; using NUnit.Framework; namespace PathfindingDirectionalLayers.Tests.Benchmark_ { [ShortRunJob] [HtmlExporter] [MarkdownExporterAttribute.GitHub] public class TestClass { private const int N = 10; int mapWidth = 25; int mapHeight = 250; MapDirectionalLayer map_250; MapDirectionalLayer map_250_complex; public TestClass() { this.map_250 = new MapDirectionalLayer(this.mapWidth, this.mapHeight, new DirectionalNode(1, 1, 1, 1, 0, 0)); this.map_250_complex = new MapDirectionalLayer(this.mapWidth, this.mapHeight, new DirectionalNode(1, 1, 1, 1, 0, 0)); DirectionalLayer horizontalWall = new DirectionalLayer(this.mapWidth - 1, 0); horizontalWall.Set(1); for (int i = -this.mapHeight + 5; i < this.mapHeight - 5; i += 6) { if (i / 2 % 2 == 0) { this.map_250_complex.AddDirectionalLayerAtPoint(horizontalWall, -2, i); } else { this.map_250_complex.AddDirectionalLayerAtPoint(horizontalWall, 2, i); } } } [Params(1, 5, 10, 20, 30, 40, 50, 100, 150, 200)] public static int pathIterations; [Benchmark] public void profile_SimpleStraightPath() { MapDirectionalLayer mapLayer = this.map_250; PathfindSettings pathfindSettings = new PathfindSettings() { }; //Create our pathfinder. Pathfinder pathFinderMap = new Pathfinder(this.mapWidth, 0, this.mapWidth, this.mapHeight * 2, mapLayer, pathfindSettings); //Run until all options are completed. int earlyExititer = 0; while (pathFinderMap.Iterate() == false && earlyExititer++ < pathIterations) { ; } } //[Benchmark] //public void profile_ComplexPath() //{ // MapDirectionalLayer mapLayer = this.map_250_complex; // PathfindSettings pathfindSettings = new PathfindSettings() { }; // //Create our pathfinder. // Pathfinder pathFinderMap = new Pathfinder(this.mapWidth, 0, this.mapWidth, startPosition, mapLayer, pathfindSettings); // //Run until all options are completed. // int earlyExititer = 0; // while (pathFinderMap.Iterate() == false && earlyExititer++ < 1000000) // { // ; // } //} //[Test] //public void SimpleVisualize_ComplexPath() //{ // MapDirectionalLayer mapLayer = this.map_250_complex; // PathfindSettings pathfindSettings = new PathfindSettings() { }; // //Create our pathfinder. // Pathfinder pathFinderMap = new Pathfinder(this.mapWidth, 2, this.mapWidth, this.mapHeight * 2 - 2, mapLayer, pathfindSettings); // //Run until all options are completed. // int earlyExititer = 0; // while (pathFinderMap.Iterate() == false && earlyExititer++ < 10000000) // { // ; // } // PathfinderVisualizer.SaveAsPng(pathFinderMap, "complexPath.png", 6); //} #if RELEASE [Test] public void ProfilePaths() { ManualConfig config = new ManualConfig() .WithOptions(ConfigOptions.DisableOptimizationsValidator) .AddValidator(JitOptimizationsValidator.DontFailOnError) .AddLogger(ConsoleLogger.Default) .AddColumnProvider(DefaultColumnProviders.Instance); BenchmarkDotNet.Reports.Summary summary = BenchmarkRunner.Run<TestClass>(config); } #endif //[Benchmark] //public void path_100() //{ // MapDirectionalLayer mapLayer = this.map_500; // PathfindSettings pathfindSettings = new PathfindSettings() { }; // //Create our pathfinder. // Pathfinder pathFinderMap = new Pathfinder(100, 0, 0, 0, mapLayer, pathfindSettings); // //Run until all options are completed. // int earlyExititer = 0; // while (pathFinderMap.Iterate() == false && earlyExititer++ < 10000) // { // ; // } //} //[Benchmark] //public void path_500() //{ // MapDirectionalLayer mapLayer = this.map_500; // PathfindSettings pathfindSettings = new PathfindSettings() { }; // //Create our pathfinder. // Pathfinder pathFinderMap = new Pathfinder(500, 0, 0, 0, mapLayer, pathfindSettings); // //Run until all options are completed. // int earlyExititer = 0; // while (pathFinderMap.Iterate() == false && earlyExititer++ < 10000) // { // ; // } //} } }
33.837662
141
0.570716
[ "MIT" ]
GrahamMueller1992/Pathfinding-DirectionalPathingLayer
Tests/Benchmark~/Benchmark_SimplePath.cs
5,213
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace PlacesApp.Mobile.iOS; public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, typeof(AppDelegate)); } }
21.571429
87
0.697572
[ "MIT" ]
WELL1NGTON/Introducao-Xamarin.Forms-2020
aula-07/PlacesApp/PlacesApp.Mobile.iOS/Main.cs
455
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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities; using Microsoft.AspNetCore.Server.IntegrationTesting; using Microsoft.AspNetCore.Server.IntegrationTesting.IIS; using Microsoft.AspNetCore.Testing.xunit; using Microsoft.Win32; using Xunit; namespace Microsoft.AspNetCore.Server.IISIntegration.FunctionalTests { [Collection(PublishedSitesCollection.Name)] public class StartupTests : IISFunctionalTestBase { private readonly PublishedSitesFixture _fixture; public StartupTests(PublishedSitesFixture fixture) { _fixture = fixture; } private readonly string _dotnetLocation = DotNetCommands.GetDotNetExecutable(RuntimeArchitecture.x64); [ConditionalFact] [RequiresIIS(IISCapability.PoolEnvironmentVariables)] public async Task ExpandEnvironmentVariableInWebConfig() { // Point to dotnet installed in user profile. var deploymentParameters = _fixture.GetBaseDeploymentParameters(); deploymentParameters.EnvironmentVariables["DotnetPath"] = _dotnetLocation; deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("processPath", "%DotnetPath%")); await StartAsync(deploymentParameters); } [ConditionalTheory] [InlineData("bogus", "", @"Executable was not found at '.*?\\bogus.exe")] [InlineData("c:\\random files\\dotnet.exe", "something.dll", @"Could not find dotnet.exe at '.*?\\dotnet.exe'")] [InlineData(".\\dotnet.exe", "something.dll", @"Could not find dotnet.exe at '.*?\\.\\dotnet.exe'")] [InlineData("dotnet.exe", "", @"Application arguments are empty.")] [InlineData("dotnet.zip", "", @"Process path 'dotnet.zip' doesn't have '.exe' extension.")] public async Task InvalidProcessPath_ExpectServerError(string path, string arguments, string subError) { var deploymentParameters = _fixture.GetBaseDeploymentParameters(); deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("processPath", path)); deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("arguments", arguments)); var deploymentResult = await DeployAsync(deploymentParameters); var response = await deploymentResult.HttpClient.GetAsync("HelloWorld"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); StopServer(); EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.UnableToStart(deploymentResult, subError)); Assert.Contains("HTTP Error 500.0 - ANCM In-Process Handler Load Failure", await response.Content.ReadAsStringAsync()); } [ConditionalFact] public async Task StartsWithDotnetLocationWithoutExe() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(); var dotnetLocationWithoutExtension = _dotnetLocation.Substring(0, _dotnetLocation.LastIndexOf(".")); deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("processPath", dotnetLocationWithoutExtension)); await StartAsync(deploymentParameters); } [ConditionalFact] public async Task StartsWithDotnetLocationUppercase() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(); var dotnetLocationWithoutExtension = _dotnetLocation.Substring(0, _dotnetLocation.LastIndexOf(".")).ToUpperInvariant(); deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("processPath", dotnetLocationWithoutExtension)); await StartAsync(deploymentParameters); } [ConditionalTheory] [InlineData("dotnet")] [InlineData("dotnet.EXE")] [RequiresIIS(IISCapability.PoolEnvironmentVariables)] public async Task StartsWithDotnetOnThePath(string path) { var deploymentParameters = _fixture.GetBaseDeploymentParameters(); deploymentParameters.EnvironmentVariables["PATH"] = Path.GetDirectoryName(_dotnetLocation); deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("processPath", path)); var deploymentResult = await DeployAsync(deploymentParameters); await deploymentResult.AssertStarts(); StopServer(); // Verify that in this scenario where.exe was invoked only once by shim and request handler uses cached value Assert.Equal(1, TestSink.Writes.Count(w => w.Message.Contains("Invoking where.exe to find dotnet.exe"))); } [SkipOnHelix] // https://github.com/aspnet/AspNetCore/issues/7972 [ConditionalTheory] [InlineData(RuntimeArchitecture.x64)] [InlineData(RuntimeArchitecture.x86)] [SkipIfNotAdmin] [RequiresNewShim] [RequiresIIS(IISCapability.PoolEnvironmentVariables)] public async Task StartsWithDotnetInstallLocation(RuntimeArchitecture runtimeArchitecture) { var deploymentParameters = _fixture.GetBaseDeploymentParameters(); deploymentParameters.RuntimeArchitecture = runtimeArchitecture; // IIS doesn't allow empty PATH deploymentParameters.EnvironmentVariables["PATH"] = "."; deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("processPath", "dotnet")); // Key is always in 32bit view using (var localMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) { var installDir = DotNetCommands.GetDotNetInstallDir(runtimeArchitecture); using (new TestRegistryKey( localMachine, "SOFTWARE\\dotnet\\Setup\\InstalledVersions\\" + runtimeArchitecture, "InstallLocation", installDir)) { var deploymentResult = await DeployAsync(deploymentParameters); await deploymentResult.AssertStarts(); StopServer(); // Verify that in this scenario dotnet.exe was found using InstallLocation lookup // I would've liked to make a copy of dotnet directory in this test and use it for verification // but dotnet roots are usually very large on dev machines so this test would take disproportionally long time and disk space Assert.Equal(1, TestSink.Writes.Count(w => w.Message.Contains($"Found dotnet.exe in InstallLocation at '{installDir}\\dotnet.exe'"))); } } } [ConditionalFact] [RequiresIIS(IISCapability.PoolEnvironmentVariables)] public async Task DoesNotStartIfDisabled() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(); using (new TestRegistryKey( Registry.LocalMachine, "SOFTWARE\\Microsoft\\IIS Extensions\\IIS AspNetCore Module V2\\Parameters", "DisableANCM", 1)) { var deploymentResult = await DeployAsync(deploymentParameters); // Disabling ANCM produces no log files deploymentResult.AllowNoLogs(); var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld"); Assert.False(response.IsSuccessStatusCode); StopServer(); EventLogHelpers.VerifyEventLogEvent(deploymentResult, "AspNetCore Module is disabled"); } } public static TestMatrix TestVariants => TestMatrix.ForServers(DeployerSelector.ServerType) .WithTfms(Tfm.NetCoreApp30) .WithAllApplicationTypes() .WithAncmV2InProcess(); [ConditionalTheory] [MemberData(nameof(TestVariants))] public async Task HelloWorld(TestVariant variant) { var deploymentParameters = _fixture.GetBaseDeploymentParameters(variant); await StartAsync(deploymentParameters); } [SkipOnHelix] // https://github.com/aspnet/AspNetCore/issues/7972 [ConditionalFact] [RequiresIIS(IISCapability.PoolEnvironmentVariables)] public async Task StartsWithPortableAndBootstraperExe() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(_fixture.InProcessTestSite); // We need the right dotnet on the path in IIS deploymentParameters.EnvironmentVariables["PATH"] = Path.GetDirectoryName(DotNetCommands.GetDotNetExecutable(deploymentParameters.RuntimeArchitecture)); // ReferenceTestTasks is workaround for https://github.com/dotnet/sdk/issues/2482 deploymentParameters.AdditionalPublishParameters = "AppHost"; var deploymentResult = await DeployAsync(deploymentParameters); Assert.True(File.Exists(Path.Combine(deploymentResult.ContentRoot, "InProcessWebSite.exe"))); Assert.False(File.Exists(Path.Combine(deploymentResult.ContentRoot, "hostfxr.dll"))); Assert.Contains("InProcessWebSite.exe", Helpers.ReadAllTextFromFile(Path.Combine(deploymentResult.ContentRoot, "web.config"), Logger)); await deploymentResult.AssertStarts(); } [ConditionalFact] public async Task DetectsOverriddenServer() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(_fixture.InProcessTestSite); deploymentParameters.TransformArguments((a, _) => $"{a} OverriddenServer"); var deploymentResult = await DeployAsync(deploymentParameters); var response = await deploymentResult.HttpClient.GetAsync("/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); StopServer(); EventLogHelpers.VerifyEventLogEvents(deploymentResult, EventLogHelpers.InProcessFailedToStart(deploymentResult, "CLR worker thread exited prematurely"), EventLogHelpers.InProcessThreadException(deploymentResult, ".*?Application is running inside IIS process but is not configured to use IIS server")); } [ConditionalFact] public async Task LogsStartupExceptionExitError() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(_fixture.InProcessTestSite); deploymentParameters.TransformArguments((a, _) => $"{a} Throw"); var deploymentResult = await DeployAsync(deploymentParameters); var response = await deploymentResult.HttpClient.GetAsync("/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); StopServer(); EventLogHelpers.VerifyEventLogEvents(deploymentResult, EventLogHelpers.InProcessFailedToStart(deploymentResult, "CLR worker thread exited prematurely"), EventLogHelpers.InProcessThreadException(deploymentResult, ", exception code = '0xe0434352'")); } [ConditionalFact] public async Task LogsUnexpectedThreadExitError() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(_fixture.InProcessTestSite); deploymentParameters.TransformArguments((a, _) => $"{a} EarlyReturn"); var deploymentResult = await DeployAsync(deploymentParameters); var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); StopServer(); EventLogHelpers.VerifyEventLogEvents(deploymentResult, EventLogHelpers.InProcessFailedToStart(deploymentResult, "CLR worker thread exited prematurely"), EventLogHelpers.InProcessThreadExit(deploymentResult, "12")); } [ConditionalFact] public async Task RemoveHostfxrFromApp_InProcessHostfxrAPIAbsent() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(_fixture.InProcessTestSite); deploymentParameters.ApplicationType = ApplicationType.Standalone; var deploymentResult = await DeployAsync(deploymentParameters); File.Copy( Path.Combine(deploymentResult.ContentRoot, "aspnetcorev2_inprocess.dll"), Path.Combine(deploymentResult.ContentRoot, "hostfxr.dll"), true); await AssertSiteFailsToStartWithInProcessStaticContent(deploymentResult); EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.InProcessHostfxrInvalid(deploymentResult), Logger); } [ConditionalFact] [RequiresNewShim] public async Task RemoveHostfxrFromApp_InProcessHostfxrLoadFailure() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(_fixture.InProcessTestSite); deploymentParameters.ApplicationType = ApplicationType.Standalone; var deploymentResult = await DeployAsync(deploymentParameters); // We don't distinguish between load failure types so making dll empty should be enough File.WriteAllText(Path.Combine(deploymentResult.ContentRoot, "hostfxr.dll"), ""); await AssertSiteFailsToStartWithInProcessStaticContent(deploymentResult); EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.InProcessHostfxrUnableToLoad(deploymentResult), Logger); } [ConditionalFact] public async Task TargedDifferenceSharedFramework_FailedToFindNativeDependencies() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(_fixture.InProcessTestSite); var deploymentResult = await DeployAsync(deploymentParameters); Helpers.ModifyFrameworkVersionInRuntimeConfig(deploymentResult); await AssertSiteFailsToStartWithInProcessStaticContent(deploymentResult); EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.InProcessFailedToFindNativeDependencies(deploymentResult), Logger); } [ConditionalFact] public async Task RemoveInProcessReference_FailedToFindRequestHandler() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(_fixture.InProcessTestSite); deploymentParameters.ApplicationType = ApplicationType.Standalone; var deploymentResult = await DeployAsync(deploymentParameters); File.Delete(Path.Combine(deploymentResult.ContentRoot, "aspnetcorev2_inprocess.dll")); await AssertSiteFailsToStartWithInProcessStaticContent(deploymentResult); if (DeployerSelector.IsForwardsCompatibilityTest) { EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.InProcessFailedToFindNativeDependencies(deploymentResult), Logger); } else { EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.InProcessFailedToFindRequestHandler(deploymentResult), Logger); } } [ConditionalFact] public async Task StartupTimeoutIsApplied() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(_fixture.InProcessTestSite); deploymentParameters.TransformArguments((a, _) => $"{a} Hang"); deploymentParameters.WebConfigActionList.Add( WebConfigHelpers.AddOrModifyAspNetCoreSection("startupTimeLimit", "1")); var deploymentResult = await DeployAsync(deploymentParameters); var response = await deploymentResult.HttpClient.GetAsync("/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); StopServer(); EventLogHelpers.VerifyEventLogEvents(deploymentResult, EventLogHelpers.InProcessFailedToStart(deploymentResult, "Managed server didn't initialize after 1000 ms.") ); } [ConditionalFact] public async Task CheckInvalidHostingModelParameter() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(); deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("hostingModel", "bogus")); var deploymentResult = await DeployAsync(deploymentParameters); var response = await deploymentResult.HttpClient.GetAsync("HelloWorld"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); StopServer(); EventLogHelpers.VerifyEventLogEvents(deploymentResult, EventLogHelpers.ConfigurationLoadError(deploymentResult, "Unknown hosting model 'bogus'. Please specify either hostingModel=\"inprocess\" or hostingModel=\"outofprocess\" in the web.config file.") ); } private static Dictionary<string, (string, Action<XElement>)> InvalidConfigTransformations = InitInvalidConfigTransformations(); public static IEnumerable<object[]> InvalidConfigTransformationsScenarios => InvalidConfigTransformations.ToTheoryData(); [ConditionalTheory] [MemberData(nameof(InvalidConfigTransformationsScenarios))] public async Task ReportsWebConfigAuthoringErrors(string scenario) { var (expectedError, action) = InvalidConfigTransformations[scenario]; var iisDeploymentParameters = _fixture.GetBaseDeploymentParameters(); iisDeploymentParameters.WebConfigActionList.Add((element, _) => action(element)); var deploymentResult = await DeployAsync(iisDeploymentParameters); var result = await deploymentResult.HttpClient.GetAsync("/HelloWorld"); Assert.Equal(HttpStatusCode.InternalServerError, result.StatusCode); // Config load errors might not allow us to initialize log file deploymentResult.AllowNoLogs(); StopServer(); EventLogHelpers.VerifyEventLogEvents(deploymentResult, EventLogHelpers.ConfigurationLoadError(deploymentResult, expectedError) ); } public static Dictionary<string, (string, Action<XElement>)> InitInvalidConfigTransformations() { var dictionary = new Dictionary<string, (string, Action<XElement>)>(); dictionary.Add("Empty process path", ( "Attribute 'processPath' is required.", element => element.Descendants("aspNetCore").Single().SetAttributeValue("processPath", "") )); dictionary.Add("Unknown hostingModel", ( "Unknown hosting model 'asdf'.", element => element.Descendants("aspNetCore").Single().SetAttributeValue("hostingModel", "asdf") )); dictionary.Add("environmentVariables with add", ( "Unable to get required configuration section 'system.webServer/aspNetCore'. Possible reason is web.config authoring error.", element => element.Descendants("aspNetCore").Single().GetOrAdd("environmentVariables").GetOrAdd("add") )); return dictionary; } private static Dictionary<string, Func<IISDeploymentParameters, string>> PortableConfigTransformations = InitPortableWebConfigTransformations(); public static IEnumerable<object[]> PortableConfigTransformationsScenarios => PortableConfigTransformations.ToTheoryData(); [ConditionalTheory] [MemberData(nameof(PortableConfigTransformationsScenarios))] public async Task StartsWithWebConfigVariationsPortable(string scenario) { var action = PortableConfigTransformations[scenario]; var iisDeploymentParameters = _fixture.GetBaseDeploymentParameters(); var expectedArguments = action(iisDeploymentParameters); var result = await DeployAsync(iisDeploymentParameters); Assert.Equal(expectedArguments, await result.HttpClient.GetStringAsync("/CommandLineArgs")); } public static Dictionary<string, Func<IISDeploymentParameters, string>> InitPortableWebConfigTransformations() { var dictionary = new Dictionary<string, Func<IISDeploymentParameters, string>>(); var pathWithSpace = "\u03c0 \u2260 3\u00b714"; dictionary.Add("App in bin subdirectory full path to dll using exec and quotes", parameters => { MoveApplication(parameters, "bin"); parameters.TransformArguments((arguments, root) => "exec " + Path.Combine(root, "bin", arguments)); return ""; }); dictionary.Add("App in subdirectory with space", parameters => { MoveApplication(parameters, pathWithSpace); parameters.TransformArguments((arguments, root) => Path.Combine(pathWithSpace, arguments)); return ""; }); dictionary.Add("App in subdirectory with space and full path to dll", parameters => { MoveApplication(parameters, pathWithSpace); parameters.TransformArguments((arguments, root) => Path.Combine(root, pathWithSpace, arguments)); return ""; }); dictionary.Add("App in bin subdirectory with space full path to dll using exec and quotes", parameters => { MoveApplication(parameters, pathWithSpace); parameters.TransformArguments((arguments, root) => "exec \"" + Path.Combine(root, pathWithSpace, arguments) + "\" extra arguments"); return "extra|arguments"; }); dictionary.Add("App in bin subdirectory and quoted argument", parameters => { MoveApplication(parameters, "bin"); parameters.TransformArguments((arguments, root) => Path.Combine("bin", arguments) + " \"extra argument\""); return "extra argument"; }); dictionary.Add("App in bin subdirectory full path to dll", parameters => { MoveApplication(parameters, "bin"); parameters.TransformArguments((arguments, root) => Path.Combine(root, "bin", arguments) + " extra arguments"); return "extra|arguments"; }); return dictionary; } private static Dictionary<string, Func<IISDeploymentParameters, string>> StandaloneConfigTransformations = InitStandaloneConfigTransformations(); public static IEnumerable<object[]> StandaloneConfigTransformationsScenarios => StandaloneConfigTransformations.ToTheoryData(); [ConditionalTheory] [MemberData(nameof(StandaloneConfigTransformationsScenarios))] public async Task StartsWithWebConfigVariationsStandalone(string scenario) { var action = StandaloneConfigTransformations[scenario]; var iisDeploymentParameters = _fixture.GetBaseDeploymentParameters(); iisDeploymentParameters.ApplicationType = ApplicationType.Standalone; var expectedArguments = action(iisDeploymentParameters); var result = await DeployAsync(iisDeploymentParameters); Assert.Equal(expectedArguments, await result.HttpClient.GetStringAsync("/CommandLineArgs")); } public static Dictionary<string, Func<IISDeploymentParameters, string>> InitStandaloneConfigTransformations() { var dictionary = new Dictionary<string, Func<IISDeploymentParameters, string>>(); var pathWithSpace = "\u03c0 \u2260 3\u00b714"; dictionary.Add("App in subdirectory", parameters => { MoveApplication(parameters, pathWithSpace); parameters.TransformPath((path, root) => Path.Combine(pathWithSpace, path)); parameters.TransformArguments((arguments, root) => "\"additional argument\""); return "additional argument"; }); dictionary.Add("App in bin subdirectory full path", parameters => { MoveApplication(parameters, pathWithSpace); parameters.TransformPath((path, root) => Path.Combine(root, pathWithSpace, path)); parameters.TransformArguments((arguments, root) => "additional arguments"); return "additional|arguments"; }); return dictionary; } [ConditionalFact] [RequiresNewHandler] public async Task SetCurrentDirectoryHandlerSettingWorks() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(); deploymentParameters.HandlerSettings["SetCurrentDirectory"] = "false"; var deploymentResult = await DeployAsync(deploymentParameters); Assert.Equal(deploymentResult.ContentRoot, await deploymentResult.HttpClient.GetStringAsync("/ContentRootPath")); Assert.Equal(deploymentResult.ContentRoot + "\\wwwroot", await deploymentResult.HttpClient.GetStringAsync("/WebRootPath")); Assert.Equal(Path.GetDirectoryName(deploymentResult.HostProcess.MainModule.FileName), await deploymentResult.HttpClient.GetStringAsync("/CurrentDirectory")); Assert.Equal(deploymentResult.ContentRoot + "\\", await deploymentResult.HttpClient.GetStringAsync("/BaseDirectory")); Assert.Equal(deploymentResult.ContentRoot + "\\", await deploymentResult.HttpClient.GetStringAsync("/ASPNETCORE_IIS_PHYSICAL_PATH")); } [ConditionalFact] [RequiresNewShim] [RequiresIIS(IISCapability.PoolEnvironmentVariables)] public async Task StartupIsSuspendedWhenEventIsUsed() { var deploymentParameters = _fixture.GetBaseDeploymentParameters(); deploymentParameters.ApplicationType = ApplicationType.Standalone; deploymentParameters.EnvironmentVariables["ASPNETCORE_STARTUP_SUSPEND_EVENT"] = "ANCM_TestEvent"; var eventPrefix = deploymentParameters.ServerType == ServerType.IISExpress ? "" : "Global\\"; var startWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, eventPrefix + "ANCM_TestEvent"); var suspendedWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, eventPrefix + "ANCM_TestEvent_suspended"); var deploymentResult = await DeployAsync(deploymentParameters); var request = deploymentResult.AssertStarts(); Assert.True(suspendedWaitHandle.WaitOne(TimeoutExtensions.DefaultTimeoutValue)); // didn't figure out a better way to check that ANCM is waiting to start var applicationDll = Path.Combine(deploymentResult.ContentRoot, "InProcessWebSite.dll"); var handlerDll = Path.Combine(deploymentResult.ContentRoot, "aspnetcorev2_inprocess.dll"); // Make sure application dll is not locked File.WriteAllBytes(applicationDll, File.ReadAllBytes(applicationDll)); // Make sure handler dll is not locked File.WriteAllBytes(handlerDll, File.ReadAllBytes(handlerDll)); // Make sure request is not completed Assert.False(request.IsCompleted); startWaitHandle.Set(); await request; } private static void MoveApplication( IISDeploymentParameters parameters, string subdirectory) { parameters.WebConfigActionList.Add((config, contentRoot) => { var source = new DirectoryInfo(contentRoot); var subDirectoryPath = source.CreateSubdirectory(subdirectory); // Copy everything into a subfolder Helpers.CopyFiles(source, subDirectoryPath, null); // Cleanup files foreach (var fileSystemInfo in source.GetFiles()) { fileSystemInfo.Delete(); } }); } private async Task AssertSiteFailsToStartWithInProcessStaticContent(IISDeploymentResult deploymentResult) { var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Contains("HTTP Error 500.0 - ANCM In-Process Handler Load Failure", await response.Content.ReadAsStringAsync()); StopServer(); } } }
50.105085
212
0.67262
[ "Apache-2.0" ]
Taturevich/AspNetCore
src/Servers/IIS/IIS/test/Common.FunctionalTests/Inprocess/StartupTests.cs
29,562
C#
using NuGet.Protocol.Core.Types; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PackageManager.Services { public interface INuGetPackageFilter { NuGetPackageFilterResult IsPassed(IPackageSearchMetadata package); } }
22.066667
75
0.749245
[ "MIT" ]
RussKie/gitextensions.pluginmanager
src/PackageManager.NuGet/Services/INuGetPackageFilter.cs
333
C#
using System; using TrueCraft.API.Logging; using System.IO; namespace TrueCraft.Core.Logging { public class FileLogProvider : ILogProvider { public StreamWriter Stream { get; set; } public LogCategory EnabledCategories { get; set; } public FileLogProvider(StreamWriter stream, LogCategory enabledCategories = LogCategory.Notice | LogCategory.Warning | LogCategory.Error) { Stream = stream; EnabledCategories = enabledCategories; } public void Log(LogCategory category, string text, params object[] parameters) { if ((EnabledCategories & category) != 0) { Stream.WriteLine(text, parameters); } } } }
29
145
0.623342
[ "MIT" ]
BinaryGears/TrueCraft
TrueCraft.Core/Logging/FileLogProvider.cs
756
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ShutDown")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ShutDown")] [assembly: AssemblyCopyright("Copyright © 2016")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
42.357143
98
0.706155
[ "MIT" ]
stanac/ShutDown
ShutDown/Properties/AssemblyInfo.cs
2,375
C#
#region File Description //----------------------------------------------------------------------------- // GameSettings.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using directives using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; using RacingGame.Helpers; using System.Threading; #endregion namespace RacingGame.Properties { /// <summary> /// Game settings, stored in a custom xml file. The reason for this is /// we want to be able to store our game data on the Xbox360 too. /// On the PC we could just use a Settings/config file and have all the /// code autogenerated for us, but this way it works both on PC and Xbox. /// Note: The default instance for the game settings is in this class, /// this way we get the same behaviour as for normal Settings files! /// </summary> [Serializable] public class GameSettings { #region Default /// <summary> /// Filename for our game settings file. /// </summary> const string SettingsFilename = "RacingGameSettings.xml"; /// <summary> /// Default instance for our game settings. /// </summary> private static GameSettings defaultInstance = new GameSettings(); /// <summary> /// Need saving the game settings file? Only set to true if /// we really changed some game setting here. /// </summary> private static bool needSave = false; /// <summary> /// Default /// </summary> /// <returns>Game settings</returns> public static GameSettings Default { get { return defaultInstance; } } #endregion #region Constructor /// <summary> /// Create game settings, don't allow public constructor! /// </summary> private GameSettings() { } /// <summary> /// Create game settings. This constructor helps us to only load the /// GameSettings once, not again if GameSettings is recreated by /// the Deserialization process. /// </summary> /// <param name="loadSettings">Load settings</param> public static void Initialize() { Load(); } #endregion #region Load /// <summary> /// Load /// </summary> public static void Load() { bool saveImmediately = false; needSave = false; FileHelper.StorageContainerMRE.WaitOne(); FileHelper.StorageContainerMRE.Reset(); try { //TODO: Use Nick Gravlyn's easy storage? StorageDevice storageDevice = FileHelper.XnaUserDevice; if ((storageDevice != null) && storageDevice.IsConnected) { IAsyncResult async = storageDevice.BeginOpenContainer("RacingGame", null, null); async.AsyncWaitHandle.WaitOne(); using (StorageContainer container = storageDevice.EndOpenContainer(async)) { async.AsyncWaitHandle.Close(); if (container.FileExists(SettingsFilename)) { using (Stream file = container.OpenFile(SettingsFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { if (file.Length > 0) { GameSettings loadedGameSettings = (GameSettings)new XmlSerializer( typeof(GameSettings)).Deserialize(file); if (loadedGameSettings != null) defaultInstance = loadedGameSettings; } else { // If the file is empty, just create a new file with the // default settings. needSave = true; saveImmediately = true; } } } else { // Create new file after exiting needSave = true; } } } } catch (Exception exc) { System.Diagnostics.Debug.WriteLine("Settings Load Failure: " + exc.ToString()); } FileHelper.StorageContainerMRE.Set(); if (saveImmediately) { Save(); } } #endregion #region Save /// <summary> /// Save /// </summary> public static void Save() { // No need to save if everything is up to date. if (needSave == false) return; needSave = false; FileHelper.StorageContainerMRE.WaitOne(); FileHelper.StorageContainerMRE.Reset(); // Open a storage container try { StorageDevice storageDevice = FileHelper.XnaUserDevice; if ((storageDevice != null) && storageDevice.IsConnected) { IAsyncResult async = storageDevice.BeginOpenContainer("RacingGame", null, null); async.AsyncWaitHandle.WaitOne(); using (StorageContainer container = storageDevice.EndOpenContainer(async)) { async.AsyncWaitHandle.Close(); using (Stream file = container.CreateFile(SettingsFilename)) { // Save everything in this class with help of the XmlSerializer. new XmlSerializer(typeof(GameSettings)). Serialize(file, defaultInstance); } } } } catch (Exception exc) { System.Diagnostics.Trace.WriteLine("Settings Load Failure: " + exc.ToString()); } FileHelper.StorageContainerMRE.Set(); } /// <summary> /// Sets all of the graphical settings to their minimum possible /// values and saves the changes. /// </summary> public static void SetMinimumGraphics() { GameSettings.Default.ResolutionWidth = GameSettings.MinimumResolutionWidth; GameSettings.Default.ResolutionHeight = GameSettings.MinimumResolutionHeight; GameSettings.Default.ShadowMapping = false; GameSettings.Default.HighDetail = false; GameSettings.Default.PostScreenEffects = false; GameSettings.Save(); } #endregion #region Setting variables with properties /// <summary> /// Highscores /// </summary> string highscores = ""; /// <summary> /// Highscores /// </summary> /// <returns>String</returns> public string Highscores { get { return highscores; } set { if (highscores != value) needSave = true; highscores = value; } } /// <summary> /// Player name /// </summary> string playerName = "Player"; /// <summary> /// Player name /// </summary> /// <returns>String</returns> public string PlayerName { get { return playerName; } set { if (playerName != value) needSave = true; playerName = value; } } public const int MinimumResolutionWidth = 640; /// <summary> /// Resolution width /// </summary> int resolutionWidth = 0; /// <summary> /// Resolution width /// </summary> /// <returns>Int</returns> public int ResolutionWidth { get { return resolutionWidth; } set { if (resolutionWidth != value) needSave = true; resolutionWidth = value; } } public const int MinimumResolutionHeight = 480; /// <summary> /// Resolution height /// </summary> int resolutionHeight = 0; /// <summary> /// Resolution height /// </summary> /// <returns>Int</returns> public int ResolutionHeight { get { return resolutionHeight; } set { if (resolutionHeight != value) needSave = true; resolutionHeight = value; } } /// <summary> /// Fullscreen /// </summary> bool fullscreen = true; /// <summary> /// Fullscreen /// </summary> /// <returns>Bool</returns> public bool Fullscreen { get { return fullscreen; } set { if (fullscreen != value) needSave = true; fullscreen = value; } } bool postScreenEffects = true; /// <summary> /// Post screen effects /// </summary> /// <returns>Bool</returns> public bool PostScreenEffects { get { return postScreenEffects; } set { if (postScreenEffects != value) needSave = true; postScreenEffects = value; } } bool shadowMapping = true; /// <summary> /// ShadowMapping /// </summary> /// <returns>Bool</returns> public bool ShadowMapping { get { return shadowMapping; } set { if (shadowMapping != value) needSave = true; shadowMapping = value; } } bool highDetail = true; /// <summary> /// HighDetail /// </summary> /// <returns>Bool</returns> public bool HighDetail { get { return highDetail; } set { if (highDetail != value) needSave = true; highDetail = value; } } /// <summary> /// Sound volume /// </summary> float soundVolume = 0.8f; /// <summary> /// Sound volume /// </summary> /// <returns>Float</returns> public float SoundVolume { get { return soundVolume; } set { if (soundVolume != value) needSave = true; soundVolume = value; } } /// <summary> /// Music volume /// </summary> float musicVolume = 0.6f; /// <summary> /// Music volume /// </summary> /// <returns>Float</returns> public float MusicVolume { get { return musicVolume; } set { if (musicVolume != value) needSave = true; musicVolume = value; } } /// <summary> /// Controller sensitivity /// </summary> float controllerSensitivity = 0.5f; /// <summary> /// Controller sensitivity /// </summary> /// <returns>Float</returns> public float ControllerSensitivity { get { return controllerSensitivity; } set { if (controllerSensitivity != value) needSave = true; controllerSensitivity = value; } } #endregion } }
29
100
0.444344
[ "MIT" ]
SimonDarksideJ/XNAGameStudio
Samples/XNA-4-Racing-Game-Kit-master/RacingGameWindows1/RacingGame/RacingGame/GameSettings.cs
13,224
C#
//------------------------------------ using UnityEngine; using UnityEngine.UI; using UnityStandardAssets.CrossPlatformInput; using System.Collections; using UnityEngine.EventSystems; using UnityEngine.Events; //------------------------------------ public class Typer : MonoBehaviour { //Reference to typed word public static string TypedWord = string.Empty; //Reference to all enemies in level private AIEnemy[] Enemies; //Text object for showing type private Text TyperText = null; //Reference to audio source component private AudioSource ThisAS = null; //Typing changed event public UnityEvent OnTypingChanged; //Time elapsed since last reset public static float ElapsedTime = 0.0f; //Record words per second public static float RecordLettersPerSecond = 2f; //------------------------------------ //Collection of combat sounds public AudioClip[] CombatSounds; // Use this for initialization void Awake () { //Get all enemies Enemies = Object.FindObjectsOfType<AIEnemy>(); //Get audio source ThisAS = GetComponent<AudioSource>(); ThisAS.clip = CombatSounds[0]; TyperText = GetComponentInChildren<Text>(); } //------------------------------------ // Update is called once per frame void Update () { //Update time ElapsedTime += Time.deltaTime; //Update types string if (Input.inputString.Length > 0) { TypedWord += Input.inputString.ToLower(); UpdateTyping (); } } //------------------------------------ //Update enemy type event private void UpdateTyping() { //Invoke typing events for enemies foreach (AIEnemy E in Enemies) { E.OnTypingChanged.Invoke (); } //Update GUI Typer OnTypingChanged.Invoke(); //Check for entry reset (are there no possible matches?) foreach (AIEnemy E in Enemies) { if (TypedWord.Length-E.MatchedWord.Length <= 0) return; } Reset (); } //------------------------------------ public void Reset() { //Reset typing TypedWord = string.Empty; //Reset time ElapsedTime = 0.0f; //Invoke typing events for enemies foreach (AIEnemy E in Enemies) { E.OnTypingChanged.Invoke (); } } //------------------------------------ // Update is called once per frame public void UpdateTyperText() { TyperText.text = Input.inputString; ThisAS.clip = CombatSounds [Random.Range (0, CombatSounds.Length)]; } //------------------------------------ } //------------------------------------
22.990566
69
0.610997
[ "MIT" ]
PacktPublishing/Mastering-Unity-2017-Game-Development
Chapter03/Start/FirstPersonAttack/Assets/scripts/Typer.cs
2,439
C#
using System.Threading; using System.Threading.Tasks; namespace BeeBus { /// <summary> /// Simple handler for a basic message without response. /// </summary> /// <typeparam name="TMessage">The type of the message to handle.</typeparam> public interface IMessageHandler<TMessage> : IHandler<TMessage> where TMessage : IMessage { /// <summary> /// Handles the message. /// </summary> /// <param name="message">The message to handle.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns></returns> Task HandleAsync(TMessage message, CancellationToken cancellationToken); } /// <summary> /// Handler dedicated to a message associated with a spectific response. /// </summary> /// <typeparam name="TMessage">The type of the message to handle.</typeparam> /// <typeparam name="TResponse">The type of the response awaited.</typeparam> public interface IMessageHandler<TMessage, TResponse> : IHandler<TMessage> where TMessage : IMessage<TResponse> { /// <summary> /// Handles the message and return a response. /// </summary> /// <param name="message">The message to handle.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns></returns> Task<TResponse> HandleAsync(TMessage message, CancellationToken cancellationToken); } }
40.945946
115
0.656766
[ "MIT" ]
FrederickRies/BeeBus
src/BeeBus.Core/IMessageHandler.cs
1,517
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; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.WebHooks.Filters; using Microsoft.AspNetCore.WebHooks.Metadata; using Microsoft.AspNetCore.WebHooks.Properties; namespace Microsoft.AspNetCore.WebHooks { /// <summary> /// <para> /// An <see cref="Attribute"/> indicating the associated action is a GitHub WebHook endpoint. Specifies the /// optional <see cref="EventName"/> and <see cref="WebHookAttribute.Id"/>. Also adds a /// <see cref="WebHookReceiverExistsFilter"/> and a <see cref="ModelStateInvalidFilter"/> (unless /// <see cref="ApiBehaviorOptions.SuppressModelStateInvalidFilter"/> is <see langword="true"/>) for the action. /// </para> /// <para> /// The signature of the action should be: /// <code> /// Task{IActionResult} ActionName(string id, string @event, TData data) /// </code> /// or include the subset of parameters required. <c>TData</c> must be compatible with expected requests e.g. /// <see cref="Newtonsoft.Json.Linq.JObject"/>. /// </para> /// <para> /// An example GitHub WebHook URI is '<c>https://{host}/api/webhooks/incoming/github/{id}</c>'. See /// <see href="https://developer.github.com/webhooks/"/> for additional details about GitHub WebHook requests. /// </para> /// </summary> /// <remarks> /// <para> /// If the application enables CORS in general (see the <c>Microsoft.AspNetCore.Cors</c> package), apply /// <c>DisableCorsAttribute</c> to this action. If the application depends on the /// <c>Microsoft.AspNetCore.Mvc.ViewFeatures</c> package, apply <c>IgnoreAntiforgeryTokenAttribute</c> to this /// action. /// </para> /// <para> /// <see cref="GitHubWebHookAttribute"/> should be used at most once per <see cref="WebHookAttribute.Id"/> and /// <see cref="EventName"/> in a WebHook application. /// </para> /// </remarks> public class GitHubWebHookAttribute : WebHookAttribute, IWebHookEventSelectorMetadata { private string _eventName; /// <summary> /// Instantiates a new <see cref="GitHubWebHookAttribute"/> instance indicating the associated action is a /// GitHub WebHook endpoint. /// </summary> public GitHubWebHookAttribute() : base(GitHubConstants.ReceiverName) { } /// <summary> /// Gets or sets the name of the event the associated controller action accepts. /// </summary> /// <value>Default value is <see langword="null"/>, indicating this action accepts all events.</value> public string EventName { get { return _eventName; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(Resources.General_ArgumentCannotBeNullOrEmpty, nameof(value)); } _eventName = value; } } } }
40.4125
115
0.632539
[ "Apache-2.0" ]
AhmadShabbir3518/WebHooks
src/Microsoft.AspNetCore.WebHooks.Receivers.GitHub/GitHubWebHookAttribute.cs
3,233
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class ExampleArmy : MonoBehaviour { private FormationBase _formation; public FormationBase Formation { get { if (_formation == null) _formation = GetComponent<FormationBase>(); return _formation; } set => _formation = value; } [SerializeField] private GameObject _unitPrefab; [SerializeField] private float _unitSpeed = 2; private readonly List<GameObject> _spawnedUnits = new List<GameObject>(); private List<Vector3> _points = new List<Vector3>(); private Transform _parent; private void Awake() { _parent = new GameObject("Unit Parent").transform; } private void Update() { SetFormation(); } private void SetFormation() { _points = Formation.EvaluatePoints().ToList(); if (_points.Count > _spawnedUnits.Count) { var remainingPoints = _points.Skip(_spawnedUnits.Count); Spawn(remainingPoints); } else if (_points.Count < _spawnedUnits.Count) { Kill(_spawnedUnits.Count - _points.Count); } for (var i = 0; i < _spawnedUnits.Count; i++) { _spawnedUnits[i].transform.position = Vector3.MoveTowards(_spawnedUnits[i].transform.position, transform.position + _points[i], _unitSpeed * Time.deltaTime); } } private void Spawn(IEnumerable<Vector3> points) { foreach (var pos in points) { var unit = Instantiate(_unitPrefab, transform.position + pos, Quaternion.identity, _parent); _spawnedUnits.Add(unit); } } private void Kill(int num) { for (var i = 0; i < num; i++) { var unit = _spawnedUnits.Last(); _spawnedUnits.Remove(unit); Destroy(unit.gameObject); } } }
30.709677
169
0.62395
[ "MIT" ]
Dehaku/Zenthium-Heroes
Assets/Imports/Formations/Scripts/ExampleArmy.cs
1,904
C#
using System; using Orchard.AuditTrail.Helpers; using Orchard.AuditTrail.Providers.AuditTrail; using Orchard.AuditTrail.Services.Models; namespace Orchard.AuditTrail.ViewModels { public class AuditTrailEventDescriptorSettingViewModel { public AuditTrailEventDescriptor Descriptor { get; set; } public AuditTrailEventSettingEventData Setting { get; set; } public string EventDisplayName { get { return !String.IsNullOrWhiteSpace(Setting.EventDisplayName) ? Setting.EventDisplayName : Descriptor != null ? Descriptor.Name.Text : EventNameExtensions.GetShortEventName(Setting.EventName); } } public string EventCategory { get { return !String.IsNullOrWhiteSpace(Setting.EventCategory) ? Setting.EventCategory : Descriptor != null ? Descriptor.CategoryDescriptor.Name.Text : Setting.EventCategory; } } } }
36.0625
80
0.57279
[ "BSD-3-Clause" ]
Lombiq/Associativy
src/Orchard.Web/Modules/Orchard.AuditTrail/ViewModels/AuditTrailEventDescriptorSettingViewModel.cs
1,154
C#
using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; using System; using System.Threading.Tasks; namespace BIADTemplate.Dialogs { //All IDialog implementations and all their member variables must be marked as serializable. //This is because BotBuilder V3 uses binary serialization to maintain the state of the conversation //inbetween API calls. You can omit member variables with the [NonSerialized] attribute [Serializable] public class EchoDialog : IDialog<object> { //StartAsync is the only interface method that all dialogs must implement //This is invoked by the bot framework when a dialog is added to the conversation stack. //Note: we might not even have a message from the user yet! public Task StartAsync(IDialogContext context) { //This conversation is now at the top of the dialog stack. //Wait for input from the user before continuing. context.Wait(MessageReceivedAsync); return Task.CompletedTask; } private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result) { //The bot builder SDK V3 relies heavily on callbacks. In this case, //"result" in this case holds what we received from the user //And in this case, we will just parrot it back to the user. var activity = await result as IMessageActivity; // calculate something for us to return int length = (activity.Text ?? string.Empty).Length; // return our reply to the user await context.PostAsync($"You sent {activity.Text} which was {length} characters long."); //This is essentially a loop. The next time the user sends a message to the same context, //we will process using this same callback. context.Wait(MessageReceivedAsync); } } }
44.090909
103
0.673711
[ "MIT" ]
JIoffe/BotExamples
CSharp/BIAD/BIADTemplate/BIADTemplate/Dialogs/EchoDialog.cs
1,942
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServer.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace IdentityServer { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(config => { config.UseInMemoryDatabase("memory"); }); services.AddIdentity<IdentityUser, IdentityRole>(config => { config.Password.RequiredLength = 4; config.Password.RequireDigit = false; config.Password.RequireNonAlphanumeric = false; config.Password.RequireUppercase = false; }) .AddEntityFrameworkStores<AppDbContext>() .AddDefaultTokenProviders(); services.ConfigureApplicationCookie(config => { config.Cookie.Name = "identityserver.cookie"; config.LoginPath = "/Auth/Login"; }); services.AddIdentityServer() .AddAspNetIdentity<IdentityUser>() .AddInMemoryApiResources(DataStore.GetApis()) .AddInMemoryClients(DataStore.GetClients()) .AddInMemoryIdentityResources(DataStore.GetIdentityResources()) .AddDeveloperSigningCredential(); services.AddControllersWithViews(); } // 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.UseIdentityServer(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } } }
31.77381
106
0.62308
[ "Apache-2.0" ]
NisalUdara/encode-identity
src/IdentityServer/Startup.cs
2,669
C#
/* The MIT License (MIT) Copyright 2021 Adam Reilly, Call to Action Software LLC 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. */ namespace Cta.Gameplay { public enum TimeOfDayType { Morning, Midday, Afternoon, Night }; /// <summary> /// System for controlling the time of day in the simulation /// </summary> public interface ITimeOfDaySystem : IBaseSystem { /// <summary> /// Set the time of day /// </summary> /// <param name="timeOfDayType">The general time of day</param> void SetTimeOfDay(TimeOfDayType timeOfDayType); /// <summary> /// Set the exact time of day /// </summary> /// <param name="dateTime">The exact time of day. Only time units hours and below are used</param> void SetTimeOfDay(DateTime dateTime); /// <summary> /// Set the hour of the time of day /// </summary> /// <param name="hour">The hour. Should be between 0 (12 am) and 23 (11pm)</param> void SetTimeOfDay(int hour); /// <summary> /// Get the current time of day /// </summary> DateTime currentTime { get; } /// <summary> /// Gets/Sets the time zone (should be between -12 and 14 if based off UTC) /// </summary> float timeZone { get; set; } } }
42.196429
460
0.666949
[ "MIT" ]
areilly711/CtaApi
Unity/CtaApi/Packages/com.calltoaction.ctaapi/CtaApi/Runtime/Scripts/Gameplay/ITimeOfDaySystem.cs
2,363
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; namespace Microsoft.SqlTools.ServiceLayer.Scripting.Contracts { /// <summary> /// Class to represent a database object that can be scripted. /// </summary> public sealed class ScriptingObject : IEquatable<ScriptingObject> { /// <summary> /// Gets or sets the database object type. /// </summary> /// <remarks> /// This underlying values are determined by the SqlScriptPublishModel.GetDatabaseObjectTypes() and /// can change depending on the version of SMO used by the tools service. Values can be: /// Table, /// View, /// StoredProcedure, /// UserDefinedFunction, /// UserDefinedDataType, /// User, /// Default, /// Rule, /// DatabaseRole, /// ApplicationRole, /// SqlAssembly, /// DdlTrigger, /// Synonym, /// XmlSchemaCollection, /// Schema, /// PlanGuide, /// UserDefinedType, /// UserDefinedAggregate, /// FullTextCatalog, /// UserDefinedTableType /// </remarks> public string Type { get; set; } /// <summary> /// Gets or sets the schema of the database object. /// </summary> public string Schema { get; set; } /// <summary> /// Gets or sets the database object name. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the parent object name /// </summary> public string ParentName { get; set; } /// <summary> /// Gets or sets the parent object type name, such as Table, View, etc. /// </summary> public string ParentTypeName { get; set; } public override string ToString() { string objectName = string.Empty; if (!string.IsNullOrEmpty(this.Schema)) { objectName += this.Schema + "."; } if (!string.IsNullOrEmpty(this.ParentName)) { objectName += this.ParentName + "."; } return objectName + this.Name; } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(this.Type ?? string.Empty) ^ StringComparer.OrdinalIgnoreCase.GetHashCode(this.Schema ?? string.Empty) ^ StringComparer.OrdinalIgnoreCase.GetHashCode(this.ParentName ?? string.Empty) ^ StringComparer.OrdinalIgnoreCase.GetHashCode(this.ParentTypeName ?? string.Empty) ^ StringComparer.OrdinalIgnoreCase.GetHashCode(this.Name ?? string.Empty); } public override bool Equals(object obj) { return obj != null && this.GetType() == obj.GetType() && this.Equals((ScriptingObject)obj); } public bool Equals(ScriptingObject other) { if (other == null) { return false; } return string.Equals(this.Type, other.Type, StringComparison.OrdinalIgnoreCase) && string.Equals(this.Schema, other.Schema, StringComparison.OrdinalIgnoreCase) && string.Equals(this.ParentName, other.ParentName, StringComparison.OrdinalIgnoreCase) && string.Equals(this.ParentTypeName, other.ParentTypeName, StringComparison.OrdinalIgnoreCase) && string.Equals(this.ParentTypeName, other.ParentTypeName, StringComparison.OrdinalIgnoreCase) && string.Equals(this.Name, other.Name, StringComparison.OrdinalIgnoreCase); } } }
35.336283
111
0.554721
[ "MIT" ]
JPaja/sqltoolsservice
src/Microsoft.SqlTools.ServiceLayer/Scripting/Contracts/ScriptingObject.cs
3,995
C#
using System.Runtime.Serialization; namespace Microsoft.Xrm.Sdk.Metadata { /// <summary>Contains the data for an attribute that provides options.</summary> [KnownType(typeof(EntityNameAttributeMetadata))] [KnownType(typeof(PicklistAttributeMetadata))] [KnownType(typeof(StateAttributeMetadata))] [KnownType(typeof(StatusAttributeMetadata))] [DataContract(Name = "EnumAttributeMetadata", Namespace = "http://schemas.microsoft.com/xrm/2011/Metadata")] public abstract class EnumAttributeMetadata : AttributeMetadata { private OptionSetMetadata _optionSetMetadata; private int? _defaultValue; /// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Metadata.EnumAttributeMetadata"></see> class.</summary> protected EnumAttributeMetadata() { } /// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Metadata.EnumAttributeMetadata"></see> class.</summary> /// <param name="attributeType">Type: <see cref="T:Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode"></see> The attribute type code.</param> /// <param name="schemaName">Type: Returns_String /// The schema name for the attribute.</param> protected EnumAttributeMetadata(AttributeTypeCode attributeType, string schemaName) : base(attributeType, schemaName) { } /// <summary>Gets or sets the default form value for the attribute.</summary> /// <returns>Type: Returns_Nullable&lt;Returns_Int32&gt; /// The default form value for the attribute..</returns> [DataMember] public int? DefaultFormValue { get { return this._defaultValue; } set { this._defaultValue = value; } } /// <summary>Gets or sets the available options for the attribute.</summary> /// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata"></see>The available options for the attribute.</returns> [DataMember] public OptionSetMetadata OptionSet { get { return this._optionSetMetadata; } set { this._optionSetMetadata = value; } } } }
38.387097
144
0.62605
[ "MIT" ]
develmax/Crm.Sdk.Core
Microsoft.Xrm.Sdk/Metadata/EnumAttributeMetadata.cs
2,382
C#
namespace VeldridGen.Example.Engine { // Some of these interfaces are checked for extremely frequently and the performance cost of using attributes instead would be excessive. #pragma warning disable CA1040 // Avoid empty interfaces public interface IEvent { } public interface IVerboseEvent : IEvent { } #pragma warning restore 1040 // Avoid empty interfaces }
41.666667
141
0.776
[ "MIT" ]
csinkers/VeldridCodeGen
Example/Engine/EventInterfaces.cs
377
C#
namespace BlazorApp { public class Sample2 { public int Value { get; set; } } public class Sample1 { public static string Test() => "aaa"; public static int Test2() => 100; public static int Test3 { get; set; } = 1000; public static Sample2 Sample2 => new Sample2(); } }
22.4
55
0.559524
[ "MIT" ]
Codeer-Software/Selenium.Friendly.Blazor
Project/BlazorApp/BlazorApp/Sample1.cs
338
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Network.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Outbound pool of the load balancer. /// </summary> [Rest.Serialization.JsonTransformation] public partial class OutboundRule : SubResource { /// <summary> /// Initializes a new instance of the OutboundRule class. /// </summary> public OutboundRule() { CustomInit(); } /// <summary> /// Initializes a new instance of the OutboundRule class. /// </summary> /// <param name="frontendIPConfigurations">The Frontend IP addresses of /// the load balancer.</param> /// <param name="backendAddressPool">A reference to a pool of DIPs. /// Outbound traffic is randomly load balanced across IPs in the /// backend IPs.</param> /// <param name="protocol">The protocol for the outbound rule in load /// balancer. Possible values include: 'Tcp', 'Udp', 'All'</param> /// <param name="id">Resource ID.</param> /// <param name="allocatedOutboundPorts">The number of outbound ports /// to be used for NAT.</param> /// <param name="provisioningState">Gets the provisioning state of the /// PublicIP resource. Possible values are: 'Updating', 'Deleting', and /// 'Failed'.</param> /// <param name="enableTcpReset">Receive bidirectional TCP Reset on TCP /// flow idle timeout or unexpected connection termination. This /// element is only used when the protocol is set to TCP.</param> /// <param name="idleTimeoutInMinutes">The timeout for the TCP idle /// connection.</param> /// <param name="name">The name of the resource that is unique within a /// resource group. This name can be used to access the /// resource.</param> /// <param name="etag">A unique read-only string that changes whenever /// the resource is updated.</param> public OutboundRule(IList<SubResource> frontendIPConfigurations, SubResource backendAddressPool, string protocol, string id = default(string), int? allocatedOutboundPorts = default(int?), string provisioningState = default(string), bool? enableTcpReset = default(bool?), int? idleTimeoutInMinutes = default(int?), string name = default(string), string etag = default(string)) : base(id) { AllocatedOutboundPorts = allocatedOutboundPorts; FrontendIPConfigurations = frontendIPConfigurations; BackendAddressPool = backendAddressPool; ProvisioningState = provisioningState; Protocol = protocol; EnableTcpReset = enableTcpReset; IdleTimeoutInMinutes = idleTimeoutInMinutes; Name = name; Etag = etag; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the number of outbound ports to be used for NAT. /// </summary> [JsonProperty(PropertyName = "properties.allocatedOutboundPorts")] public int? AllocatedOutboundPorts { get; set; } /// <summary> /// Gets or sets the Frontend IP addresses of the load balancer. /// </summary> [JsonProperty(PropertyName = "properties.frontendIPConfigurations")] public IList<SubResource> FrontendIPConfigurations { get; set; } /// <summary> /// Gets or sets a reference to a pool of DIPs. Outbound traffic is /// randomly load balanced across IPs in the backend IPs. /// </summary> [JsonProperty(PropertyName = "properties.backendAddressPool")] public SubResource BackendAddressPool { get; set; } /// <summary> /// Gets the provisioning state of the PublicIP resource. Possible /// values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; set; } /// <summary> /// Gets or sets the protocol for the outbound rule in load balancer. /// Possible values include: 'Tcp', 'Udp', 'All' /// </summary> [JsonProperty(PropertyName = "properties.protocol")] public string Protocol { get; set; } /// <summary> /// Gets or sets receive bidirectional TCP Reset on TCP flow idle /// timeout or unexpected connection termination. This element is only /// used when the protocol is set to TCP. /// </summary> [JsonProperty(PropertyName = "properties.enableTcpReset")] public bool? EnableTcpReset { get; set; } /// <summary> /// Gets or sets the timeout for the TCP idle connection. /// </summary> [JsonProperty(PropertyName = "properties.idleTimeoutInMinutes")] public int? IdleTimeoutInMinutes { get; set; } /// <summary> /// Gets or sets the name of the resource that is unique within a /// resource group. This name can be used to access the resource. /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Gets or sets a unique read-only string that changes whenever the /// resource is updated. /// </summary> [JsonProperty(PropertyName = "etag")] public string Etag { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (FrontendIPConfigurations == null) { throw new ValidationException(ValidationRules.CannotBeNull, "FrontendIPConfigurations"); } if (BackendAddressPool == null) { throw new ValidationException(ValidationRules.CannotBeNull, "BackendAddressPool"); } if (Protocol == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Protocol"); } } } }
42
383
0.617596
[ "MIT" ]
AzureMentor/azure-sdk-for-net
sdk/network/Microsoft.Azure.Management.Network/src/Generated/Models/OutboundRule.cs
6,888
C#
using System; using System.Runtime.InteropServices; using System.Numerics; using LiteNetLib.Utils; namespace LibreLancer { public class BitWriter { private const int GROWTH_AMOUNT = 4; private byte[] buffer; private int bitOffset; public BitWriter(int initialCapacity = 64) { buffer = new byte [(initialCapacity + 7) >> 3]; bitOffset = 0; } public void PutInt(int i) => PutUInt((uint) i, 32); public void PutByte(byte b) => PutUInt( b, 8); [StructLayout(LayoutKind.Explicit)] struct F2I { [FieldOffset(0)] public float f; [FieldOffset(0)] public uint i; } public void PutFloat(float f) { var c = new F2I() {f = f}; PutUInt(c.i, 32); } public void PutVector3(Vector3 vec) { PutFloat(vec.X); PutFloat(vec.Y); PutFloat(vec.Z); } static float WrapMinMax(float x, float min, float max) { var m = max - min; var y = (x - min); return min + (m + y % m) % m; } public void PutRadiansQuantized(float angle) { var wrapped = WrapMinMax(angle, NetPacking.ANGLE_MIN, NetPacking.ANGLE_MAX); PutRangedFloat(angle, NetPacking.ANGLE_MIN, NetPacking.ANGLE_MAX, 16); } public void PutQuaternion(Quaternion q) { var maxIndex = 0; var maxValue = float.MinValue; var sign = 1f; maxValue = Math.Abs(q.X); sign = q.X < 0 ? -1 : 1; if (Math.Abs(q.Y) > maxValue) { maxValue = Math.Abs(q.Y); maxIndex = 1; sign = q.Y < 0 ? -1 : 1; } if (Math.Abs(q.Z) > maxValue) { maxValue = Math.Abs(q.Z); maxIndex = 2; sign = q.Z < 0 ? -1 : 1; } if (Math.Abs(q.W) > maxValue) { maxIndex = 3; sign = q.W < 0 ? -1 : 1; } PutUInt((uint)maxIndex, 2); if (maxIndex == 0) { PutRangedFloat(q.Y * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); PutRangedFloat(q.Z * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); PutRangedFloat(q.W * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); } else if (maxIndex == 1) { PutRangedFloat(q.X * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); PutRangedFloat(q.Z * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); PutRangedFloat(q.W * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); } else if (maxIndex == 2) { PutRangedFloat(q.X * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); PutRangedFloat(q.Y * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); PutRangedFloat(q.W * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); } else { PutRangedFloat(q.X * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); PutRangedFloat(q.Y * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); PutRangedFloat(q.Z * sign, NetPacking.UNIT_MIN, NetPacking.UNIT_MAX, NetPacking.BITS_COMPONENT); } } public void PutBool(bool b) { CheckSize(bitOffset + 1); PackBits(b ? (byte) 1 : (byte) 0, 1, buffer, bitOffset++); } public void PutUInt(uint u, int bits) { CheckSize(bitOffset + bits); PackUInt(u, bits, buffer, bitOffset); bitOffset += bits; } public void PutRangedFloat(float f, float min, float max, int bits) { var intMax = (1 << bits) - 1; float unit = ((f - min) / (max - min)); PutUInt((uint)(intMax * unit), bits); } static void PackUInt(uint src, int nBits, Span<byte> dest, int destOffset) { if (nBits <= 8) { PackBits((byte) src, nBits, dest, destOffset); return; } PackBits((byte) src, 8, dest, destOffset); destOffset += 8; nBits -= 8; if (nBits <= 8) { PackBits((byte) (src >> 8), nBits, dest, destOffset); return; } PackBits((byte) (src >> 8), 8, dest, destOffset); destOffset += 8; nBits -= 8; if (nBits <= 8) { PackBits((byte) (src >> 16), nBits, dest, destOffset); return; } PackBits((byte) (src >> 16), 8, dest, destOffset); destOffset += 8; nBits -= 8; PackBits((byte) (src >> 24), nBits, dest, destOffset); } static void PackBits(byte src, int nBits, Span<byte> dest, int destOffset) { src = (byte)(src & (0xFF >> (8 - nBits))); int p = destOffset >> 3; int bitsUsed = destOffset & 0x7; int bitsFree = 8 - bitsUsed; int bitsLeft = bitsFree - nBits; if (bitsLeft >= 0) { int mask = (0xFF >> bitsFree) | (0xFF << (8 - bitsLeft)); dest[p] = (byte)( (dest[p] & mask) | (src << bitsUsed)); return; } dest[p] = (byte) ( (dest[p] & (0xFF >> bitsFree)) | (src << bitsUsed) ); p++; dest[p] = (byte)( (dest[p] & (0xFF << (nBits - bitsFree))) | (src >> bitsFree) ); } void CheckSize(int nBits) { int byteLen = (nBits + 7) >> 3; if (buffer.Length < byteLen) Array.Resize(ref buffer, byteLen + GROWTH_AMOUNT); } public int ByteLength => (bitOffset + 7) >> 3; public void WriteToPacket(NetDataWriter dw) { dw.Put(buffer, 0, (bitOffset + 7) >> 3); } } }
35.292553
112
0.483949
[ "MIT" ]
HaydnTrigg/Librelancer
src/LibreLancer/Net/Protocol/BitWriter.cs
6,635
C#
// Copyright 2014 Serilog Contributors // // 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.Text; using System.Text.RegularExpressions; using Elasticsearch.Net; using Serilog.Debugging; using Serilog.Events; using Serilog.Formatting; namespace Serilog.Sinks.Elasticsearch { internal class ElasticsearchSinkState { public static ElasticsearchSinkState Create(ElasticsearchSinkOptions options) { if (options == null) throw new ArgumentNullException(nameof(options)); return new ElasticsearchSinkState(options); } private readonly ElasticsearchSinkOptions _options; readonly Func<LogEvent, DateTimeOffset, string> _indexDecider; private readonly ITextFormatter _formatter; private readonly ITextFormatter _durableFormatter; private readonly ElasticLowLevelClient _client; private readonly bool _registerTemplateOnStartup; private readonly string _templateName; private readonly string _templateMatchString; private static readonly Regex IndexFormatRegex = new Regex(@"^(.*)(?:\{0\:.+\})(.*)$"); public ElasticsearchSinkOptions Options => _options; public IElasticLowLevelClient Client => _client; public ITextFormatter Formatter => _formatter; public ITextFormatter DurableFormatter => _durableFormatter; public bool TemplateRegistrationSuccess { get; private set; } private ElasticsearchSinkState(ElasticsearchSinkOptions options) { if (string.IsNullOrWhiteSpace(options.IndexFormat)) throw new ArgumentException("options.IndexFormat"); if (string.IsNullOrWhiteSpace(options.TypeName)) throw new ArgumentException("options.TypeName"); if (string.IsNullOrWhiteSpace(options.TemplateName)) throw new ArgumentException("options.TemplateName"); _templateName = options.TemplateName; _templateMatchString = IndexFormatRegex.Replace(options.IndexFormat, @"$1*$2"); _indexDecider = options.IndexDecider ?? ((@event, offset) => string.Format(options.IndexFormat, offset)); _options = options; var configuration = new ConnectionConfiguration(options.ConnectionPool, options.Connection, options.Serializer) .RequestTimeout(options.ConnectionTimeout); if (options.ModifyConnectionSettings != null) configuration = options.ModifyConnectionSettings(configuration); configuration.ThrowExceptions(); _client = new ElasticLowLevelClient(configuration); _formatter = options.CustomFormatter ?? new ElasticsearchJsonFormatter( formatProvider: options.FormatProvider, renderMessage: true, closingDelimiter: string.Empty, serializer: options.Serializer, inlineFields: options.InlineFields ); _durableFormatter = options.CustomDurableFormatter ?? new ElasticsearchJsonFormatter( formatProvider: options.FormatProvider, renderMessage: true, closingDelimiter: Environment.NewLine, serializer: options.Serializer, inlineFields: options.InlineFields ); _registerTemplateOnStartup = options.AutoRegisterTemplate; TemplateRegistrationSuccess = !_registerTemplateOnStartup; } public string Serialize(object o) { return _client.Serializer.SerializeToString(o, SerializationFormatting.None); } public string GetIndexForEvent(LogEvent e, DateTimeOffset offset) { if (!TemplateRegistrationSuccess && _options.RegisterTemplateFailure == RegisterTemplateRecovery.IndexToDeadletterIndex) return string.Format(_options.DeadLetterIndexName, offset); return _indexDecider(e, offset); } /// <summary> /// Register the elasticsearch index template if the provided options mandate it. /// </summary> public void RegisterTemplateIfNeeded() { if (!_registerTemplateOnStartup) return; try { if (!_options.OverwriteTemplate) { var templateExistsResponse = _client.IndicesExistsTemplateForAll<DynamicResponse>(_templateName); if (templateExistsResponse.HttpStatusCode == 200) { TemplateRegistrationSuccess = true; return; } } var result = _client.IndicesPutTemplateForAll<DynamicResponse>(_templateName, GetTempatePostData()); if (!result.Success) { ((IElasticsearchResponse)result).TryGetServerErrorReason(out var serverError); SelfLog.WriteLine("Unable to create the template. {0}", serverError); if (_options.RegisterTemplateFailure == RegisterTemplateRecovery.FailSink) throw new Exception($"Unable to create the template named {_templateName}.", result.OriginalException); TemplateRegistrationSuccess = false; } else TemplateRegistrationSuccess = true; } catch (Exception ex) { TemplateRegistrationSuccess = false; SelfLog.WriteLine("Failed to create the template. {0}", ex); if (_options.RegisterTemplateFailure == RegisterTemplateRecovery.FailSink) throw; } } private PostData GetTempatePostData() { //PostData no longer exposes an implict cast from object. Previously it supported that and would inspect the object Type to //determine if it it was a litteral string to write directly or if it was an object that it needed to serialse. Now the onus is //on us to tell it what type we are passing otherwise if the user specified the template as a json string it would be serialised again. var template = GetTemplateData(); if (template is string) { return PostData.String((string)template); } else { return PostData.Serializable(template); } } private object GetTemplateData() { if (_options.GetTemplateContent != null) return _options.GetTemplateContent(); var settings = new Dictionary<string, string> { {"index.refresh_interval", "5s"} }; if (_options.NumberOfShards.HasValue) settings.Add("number_of_shards", _options.NumberOfShards.Value.ToString()); if (_options.NumberOfReplicas.HasValue) settings.Add("number_of_replicas", _options.NumberOfReplicas.Value.ToString()); return ElasticsearchTemplateProvider.GetTemplate( settings, _templateMatchString, _options.AutoRegisterTemplateVersion); } } }
39.25
147
0.636433
[ "Apache-2.0" ]
reedz/serilog-sinks-elasticsearch
src/Serilog.Sinks.Elasticsearch/Sinks/ElasticSearch/ElasticsearchSinkState.cs
7,852
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; namespace ClientSideBlazor { public class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("app"); builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); builder.Services.AddSingleton(typeof(IStringLocalizer), typeof(StringLocalizer<SharedLocalization.SharedResources>)); await builder.Build().RunAsync(); } } }
32.454545
129
0.710084
[ "MIT" ]
Blazored/FormExtensions
samples/ClientSideBlazor/Program.cs
714
C#
using System.ComponentModel.DataAnnotations.Schema; namespace Pims.Dal.Entities { /// <summary> /// PimsPropertyRoadType class, provides an entity for the datamodel to manage a list of property road types. /// </summary> public partial class PimsPropertyRoadType : ITypeEntity<string> { #region Properties /// <summary> /// get/set - Primary key to identify a road type. /// </summary> [NotMapped] public string Id { get => PropertyRoadTypeCode; set => PropertyRoadTypeCode = value; } #endregion #region Constructors /// <summary> /// Create a new instance of a PimsPropertyRoadType class. /// </summary> /// <param name="id"></param> public PimsPropertyRoadType(string id) : this() { Id = id; } #endregion } }
30.206897
113
0.593607
[ "Apache-2.0" ]
FuriousLlama/PSP
backend/entities/PropertyRoadType.cs
876
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace cloudscribe.Core.IdentityServer.EFCore.Entities { public class ClientIdPRestriction { public int Id { get; set; } public string Provider { get; set; } public Client Client { get; set; } } }
31.846154
107
0.688406
[ "Apache-2.0" ]
4L4M1N/cloudscribe
src/cloudscribe.Core.IdentityServer.EFCore.Common/Entities/ClientIdPRestriction.cs
416
C#
using System.IO; namespace Unity.VisualScripting { [Plugin(BoltCore.ID)] public class BoltCorePaths : PluginPaths { public BoltCorePaths(Plugin plugin) : base(plugin) { } public string variableResources => Path.Combine(persistentGenerated, "Variables/Resources"); public string propertyProviders => Path.Combine(transientGenerated, "Property Providers"); public string propertyProvidersEditor => Path.Combine(propertyProviders, "Editor"); public string assemblyDocumentations => Path.Combine(transientGenerated, "Documentation"); public string dotNetDocumentation => Path.Combine(package, "DotNetDocumentation"); } }
40.176471
100
0.7306
[ "MIT" ]
2PUEG-VRIK/UnityEscapeGame
2P-UnityEscapeGame/Library/PackageCache/com.unity.visualscripting@1.6.1/Editor/VisualScripting.Core/Plugin/BoltCorePaths.cs
683
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.Drawing; using System.Windows.Forms; namespace WinformsControlsTest { public partial class ListViewTest : Form { public ListViewTest() { InitializeComponent(); CreateMyListView(); listView1.LabelEdit = true; listView1.View = View.Tile; var random = new Random(); int i = random.Next(100, 300); listView1.TileSize = new Size(200, 50); listView1.Items[0].ImageIndex = 0; listView1.Items[1].ImageIndex = 1; listView1.Items[2].ImageIndex = 2; listView1.Click += (s, e) => { //listView1.TileSize = new Size(random.Next(100, 300), random.Next(25, 50)); Point pos = Cursor.Position; pos = PointToClient(pos); var index = listView1.InsertionMark.NearestIndex(pos); Console.WriteLine($"nearest index: {index}"); }; AddCollapsibleGroupToListView(); AddGroupTasks(); } private void CreateMyListView() { // Create a new ListView control. ListView listView2 = new ListView { Bounds = new Rectangle(new Point(0, 0), new Size(400, 200)), // Set the view to show details. View = View.Details, // Allow the user to edit item text. LabelEdit = true, // Allow the user to rearrange columns. AllowColumnReorder = true, // Display check boxes. CheckBoxes = true, // Select the item and subitems when selection is made. FullRowSelect = true, // Display grid lines. GridLines = true, // Sort the items in the list in ascending order. Sorting = SortOrder.Ascending, VirtualMode = true, VirtualListSize = 3, }; listView2.SelectedIndexChanged += listView2_SelectedIndexChanged; listView2.Click += listView2_Click; // Create three items and three sets of subitems for each item. ListViewItem item1 = new("item1", 0) { // Place a check mark next to the item. Checked = true }; item1.SubItems.Add("1"); item1.SubItems.Add("2"); item1.SubItems.Add("3"); ListViewItem item2 = new("item2", 1); item2.SubItems.Add("4"); item2.SubItems.Add("5"); item2.SubItems.Add("6"); ListViewItem item3 = new("item3", 0) { // Place a check mark next to the item. Checked = true }; item3.SubItems.Add("7"); item3.SubItems.Add("8"); item3.SubItems.Add("9"); // Add the items to the ListView, but because the listview is in Virtual Mode, we have to manage items ourselves // and thus, we can't call the following: // listView2.Items.AddRange(new ListViewItem[] { item1, item2, item3 }); listView2.RetrieveVirtualItem += (s, e) => { e.Item = e.ItemIndex switch { 0 => item1, 1 => item2, 2 => item3, _ => throw new IndexOutOfRangeException(), }; }; // Create columns for the items and subitems. // Width of -2 indicates auto-size. listView2.Columns.Add("column1", "Item Column", -2, HorizontalAlignment.Left, 0); listView2.Columns.Add("Column 2", -2, HorizontalAlignment.Left); listView2.Columns.Add("Column 3", -2, HorizontalAlignment.Left); listView2.Columns.Add("Column 4", -2, HorizontalAlignment.Center); listView2.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); // Create two ImageList objects. ImageList imageListSmall = new(components); ImageList imageListLarge = new(components); // Initialize the ImageList objects with bitmaps. imageListSmall.Images.Add(Bitmap.FromFile("Images\\SmallA.bmp")); imageListSmall.Images.Add(Bitmap.FromFile("Images\\SmallABlue.bmp")); imageListLarge.Images.Add(Bitmap.FromFile("Images\\LargeA.bmp")); imageListLarge.Images.Add(Bitmap.FromFile("Images\\LargeABlue.bmp")); // Assign the ImageList objects to the ListView. listView2.LargeImageList = imageListLarge; listView2.SmallImageList = imageListSmall; // Add the ListView to the control collection. Controls.Add(listView2); listView2.Dock = DockStyle.Bottom; } private void AddCollapsibleGroupToListView() { var lvgroup1 = new ListViewGroup { Header = "CollapsibleGroup1", CollapsedState = ListViewGroupCollapsedState.Expanded }; listView1.Groups.Add(lvgroup1); listView1.Items.Add(new ListViewItem { Text = "Item", Group = lvgroup1 }); var lvgroup2 = new ListViewGroup { Header = "CollapsibleGroup2", CollapsedState = ListViewGroupCollapsedState.Collapsed }; listView1.Groups.Add(lvgroup2); listView1.Items.Add(new ListViewItem { Text = "Item", Group = lvgroup2 }); listView1.GroupCollapsedStateChanged += listView1_GroupCollapsedStateChanged; } private void listView1_GroupCollapsedStateChanged(object sender, ListViewGroupEventArgs e) { MessageBox.Show("CollapsedState changed at group with index " + e.GroupIndex); } private void AddGroupTasks() { listView1.Groups[0].TaskLink = "Task"; listView1.GroupTaskLinkClick += listView1_GroupTaskLinkClick; var lvgroup1 = new ListViewGroup { Header = "TaskGroup", TaskLink = "Task2" }; listView1.Groups.Add(lvgroup1); listView1.Items.Add(new ListViewItem { Text = "Item", Group = lvgroup1 }); } private void listView1_GroupTaskLinkClick(object sender, ListViewGroupEventArgs e) { MessageBox.Show(this, "Task at group index " + e.GroupIndex + " was clicked", "GroupClick Event"); } private void listView2_Click(object sender, System.EventArgs e) { Debug.WriteLine(listView1.TileSize); MessageBox.Show(this, "listView2_Click", "event"); } private void listView2_SelectedIndexChanged(object sender, System.EventArgs e) { // MessageBox.Show(this, "listView2_SelectedIndexChanged", "event"); var listView2 = sender as ListView; if (listView2 is null) { return; } var random = new Random(); listView2.Columns[random.Next(0, listView2.Columns.Count)].ImageIndex = random.Next(0, 2); } private void btnClearListView1_Click(object sender, EventArgs e) { listView1.Clear(); LargeImageList.Images.Clear(); listView1.LargeImageList = LargeImageList; listView1.View = View.LargeIcon; } private void btnLoadImagesListView1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() != DialogResult.OK) { return; } foreach (string file in openFileDialog1.FileNames) { Bitmap bitmap = (Bitmap)Bitmap.FromFile(file); LargeImageList.Images.Add(file, bitmap); ListViewItem item = new ListViewItem { Text = Path.GetFileName(file), Name = file, ImageKey = file, Checked = true }; listView1.Items.Add(item); } } private void btnReplaceImageListView1_Click(object sender, EventArgs e) { if (listView1.SelectedIndices.Count != 1) { return; } openFileDialog1.Multiselect = false; DialogResult result = openFileDialog1.ShowDialog(); openFileDialog1.Multiselect = true; if (result != DialogResult.OK) { return; } string file = openFileDialog1.FileName; Bitmap bitmap = (Bitmap)Bitmap.FromFile(file); LargeImageList.Images[listView1.SelectedIndices[0]] = bitmap; listView1.Refresh(); } } }
34.774074
124
0.538183
[ "MIT" ]
AndreRRR/winforms
src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/ListViewTest.cs
9,391
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.17929 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace JumpListApplicationTask.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("JumpListApplicationTask.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.890625
189
0.61659
[ "MIT" ]
DiogoBarbosaSilvaSousa/apress
pro-wpf-4.5-in-csharp/Pro WPF 4.5 in C#/Chapter23/JumpListApplicationTask/Properties/Resources.Designer.cs
2,811
C#
using NUnit.Framework; using System; using System.IO; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; using ICSharpCode.SharpZipLib.Tests.TestSupport; namespace ICSharpCode.SharpZipLib.Tests.Tar { /// <summary> /// This class contains test cases for Tar archive handling. /// </summary> [TestFixture] public class TarTestSuite { private int entryCount; private void EntryCounter(TarArchive archive, TarEntry entry, string message) { entryCount++; } /// <summary> /// Test that an empty archive can be created and when read has 0 entries in it /// </summary> [Test] [Category("Tar")] public void EmptyTar() { var ms = new MemoryStream(); int recordSize = 0; using (TarArchive tarOut = TarArchive.CreateOutputTarArchive(ms)) { recordSize = tarOut.RecordSize; } Assert.IsTrue(ms.GetBuffer().Length > 0, "Archive size must be > zero"); Assert.AreEqual(ms.GetBuffer().Length % recordSize, 0, "Archive size must be a multiple of record size"); var ms2 = new MemoryStream(); ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms2.Seek(0, SeekOrigin.Begin); using (TarArchive tarIn = TarArchive.CreateInputTarArchive(ms2)) { entryCount = 0; tarIn.ProgressMessageEvent += EntryCounter; tarIn.ListContents(); Assert.AreEqual(0, entryCount, "Expected 0 tar entries"); } } /// <summary> /// Check that the tar block factor can be varied successfully. /// </summary> [Test] [Category("Tar")] public void BlockFactorHandling() { const int MinimumBlockFactor = 1; const int MaximumBlockFactor = 64; const int FillFactor = 2; for (int factor = MinimumBlockFactor; factor < MaximumBlockFactor; ++factor) { var ms = new MemoryStream(); using (TarOutputStream tarOut = new TarOutputStream(ms, factor)) { TarEntry entry = TarEntry.CreateTarEntry("TestEntry"); entry.Size = (TarBuffer.BlockSize * factor * FillFactor); tarOut.PutNextEntry(entry); byte[] buffer = new byte[TarBuffer.BlockSize]; var r = new Random(); r.NextBytes(buffer); // Last block is a partial one for (int i = 0; i < factor * FillFactor; ++i) { tarOut.Write(buffer, 0, buffer.Length); } } byte[] tarData = ms.ToArray(); Assert.IsNotNull(tarData, "Data written is null"); // Blocks = Header + Data Blocks + Zero block + Record trailer int usedBlocks = 1 + (factor * FillFactor) + 2; int totalBlocks = usedBlocks + (factor - 1); totalBlocks /= factor; totalBlocks *= factor; Assert.AreEqual(TarBuffer.BlockSize * totalBlocks, tarData.Length, "Tar file should contain {0} blocks in length", totalBlocks); if (usedBlocks < totalBlocks) { // Start at first byte after header. int byteIndex = TarBuffer.BlockSize * ((factor * FillFactor) + 1); while (byteIndex < tarData.Length) { int blockNumber = byteIndex / TarBuffer.BlockSize; int offset = blockNumber % TarBuffer.BlockSize; Assert.AreEqual(0, tarData[byteIndex], string.Format("Trailing block data should be null iteration {0} block {1} offset {2} index {3}", factor, blockNumber, offset, byteIndex)); byteIndex += 1; } } } } /// <summary> /// Check that the tar trailer only contains nulls. /// </summary> [Test] [Category("Tar")] public void TrailerContainsNulls() { const int TestBlockFactor = 3; for (int iteration = 0; iteration < TestBlockFactor * 2; ++iteration) { var ms = new MemoryStream(); using (TarOutputStream tarOut = new TarOutputStream(ms, TestBlockFactor)) { TarEntry entry = TarEntry.CreateTarEntry("TestEntry"); if (iteration > 0) { entry.Size = (TarBuffer.BlockSize * (iteration - 1)) + 9; } tarOut.PutNextEntry(entry); byte[] buffer = new byte[TarBuffer.BlockSize]; var r = new Random(); r.NextBytes(buffer); if (iteration > 0) { for (int i = 0; i < iteration - 1; ++i) { tarOut.Write(buffer, 0, buffer.Length); } // Last block is a partial one for (int i = 1; i < 10; ++i) { tarOut.WriteByte((byte)i); } } } byte[] tarData = ms.ToArray(); Assert.IsNotNull(tarData, "Data written is null"); // Blocks = Header + Data Blocks + Zero block + Record trailer int usedBlocks = 1 + iteration + 2; int totalBlocks = usedBlocks + (TestBlockFactor - 1); totalBlocks /= TestBlockFactor; totalBlocks *= TestBlockFactor; Assert.AreEqual(TarBuffer.BlockSize * totalBlocks, tarData.Length, string.Format("Tar file should be {0} blocks in length", totalBlocks)); if (usedBlocks < totalBlocks) { // Start at first byte after header. int byteIndex = TarBuffer.BlockSize * (iteration + 1); while (byteIndex < tarData.Length) { int blockNumber = byteIndex / TarBuffer.BlockSize; int offset = blockNumber % TarBuffer.BlockSize; Assert.AreEqual(0, tarData[byteIndex], string.Format("Trailing block data should be null iteration {0} block {1} offset {2} index {3}", iteration, blockNumber, offset, byteIndex)); byteIndex += 1; } } } } private void TryLongName(string name) { var ms = new MemoryStream(); using (TarOutputStream tarOut = new TarOutputStream(ms)) { DateTime modTime = DateTime.Now; TarEntry entry = TarEntry.CreateTarEntry(name); tarOut.PutNextEntry(entry); } var ms2 = new MemoryStream(); ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms2.Seek(0, SeekOrigin.Begin); using (TarInputStream tarIn = new TarInputStream(ms2)) { TarEntry nextEntry = tarIn.GetNextEntry(); Assert.AreEqual(nextEntry.Name, name, "Name match failure"); } } /// <summary> /// Check that long names are handled correctly for reading and writing. /// </summary> [Test] [Category("Tar")] public void LongNames() { TryLongName("11111111112222222222333333333344444444445555555555" + "6666666666777777777788888888889999999999000000000"); TryLongName("11111111112222222222333333333344444444445555555555" + "66666666667777777777888888888899999999990000000000"); TryLongName("11111111112222222222333333333344444444445555555555" + "66666666667777777777888888888899999999990000000000" + "1"); TryLongName("11111111112222222222333333333344444444445555555555" + "66666666667777777777888888888899999999990000000000" + "11111111112222222222333333333344444444445555555555" + "66666666667777777777888888888899999999990000000000"); TryLongName("11111111112222222222333333333344444444445555555555" + "66666666667777777777888888888899999999990000000000" + "11111111112222222222333333333344444444445555555555" + "66666666667777777777888888888899999999990000000000" + "11111111112222222222333333333344444444445555555555" + "66666666667777777777888888888899999999990000000000" + "11111111112222222222333333333344444444445555555555" + "66666666667777777777888888888899999999990000000000" + "11111111112222222222333333333344444444445555555555" + "66666666667777777777888888888899999999990000000000"); for (int n = 1; n < 1024; ++n) { string format = "{0," + n + "}"; string formatted = string.Format(format, "A"); TryLongName(formatted); } } [Test] [Category("Tar")] public void ExtendedHeaderLongName() { string expectedName = "lftest-0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999"; var input64 = @"Li9QYXhIZWFkZXJzLjExOTY5L2xmdGVzdC0wMDAwMDAwMDAwMTExMTExMTExMTIyMjIyMjIyMjIz MzMzMzMzMzMzNDQ0NDQ0NDQ0NDU1NTU1NTU1NTU2NjY2NjY2NjY2Nzc3NzAwMDA2NDQAMDAwMDAw MAAwMDAwMDAwADAwMDAwMDAwMzE3ADEzMzE2MTYyMzMzADAyMTYwNgAgeAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB1c3RhcgAwMAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAx MTcgcGF0aD1sZnRlc3QtMDAwMDAwMDAwMDExMTExMTExMTEyMjIyMjIyMjIyMzMzMzMzMzMzMzQ0 NDQ0NDQ0NDQ1NTU1NTU1NTU1NjY2NjY2NjY2Njc3Nzc3Nzc3Nzc4ODg4ODg4ODg4OTk5OTk5OTk5 OQozMCBtdGltZT0xNTMwNDU1MjU5LjcwNjU0ODg4OAozMCBhdGltZT0xNTMwNDU1MjU5LjcwNjU0 ODg4OAozMCBjdGltZT0xNTMwNDU1MjU5LjcwNjU0ODg4OAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGxm dGVzdC0wMDAwMDAwMDAwMTExMTExMTExMTIyMjIyMjIyMjIzMzMzMzMzMzMzNDQ0NDQ0NDQ0NDU1 NTU1NTU1NTU2NjY2NjY2NjY2Nzc3Nzc3Nzc3Nzg4ODg4ODg4ODg5OTkwMDAwNjY0ADAwMDE3NTAA MDAwMTc1MAAwMDAwMDAwMDAwMAAxMzMxNjE2MjMzMwAwMjM3MjcAIDAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAdXN0YXIAMDBuaWxzAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAG5pbHMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMDAwMDAwMAAwMDAwMDAw"; var buffer = new byte[2560]; var truncated = Convert.FromBase64String(input64); Array.Copy(truncated, buffer, truncated.Length); truncated = null; using (var ms = new MemoryStream(buffer)) using (var tis = new TarInputStream(ms)) { var entry = tis.GetNextEntry(); Assert.IsNotNull(entry, "Entry is null"); Assert.IsNotNull(entry.Name, "Entry name is null"); Assert.AreEqual(expectedName.Length, entry.Name.Length, $"Entry name is truncated to {entry.Name.Length} bytes."); Assert.AreEqual(expectedName, entry.Name, "Entry name does not match expected value"); } } /// <summary> /// Test equals function for tar headers. /// </summary> [Test] [Category("Tar")] public void HeaderEquality() { var h1 = new TarHeader(); var h2 = new TarHeader(); Assert.IsTrue(h1.Equals(h2)); h1.Name = "ABCDEFG"; Assert.IsFalse(h1.Equals(h2)); h2.Name = h1.Name; Assert.IsTrue(h1.Equals(h2)); h1.Mode = 33188; Assert.IsFalse(h1.Equals(h2)); h2.Mode = h1.Mode; Assert.IsTrue(h1.Equals(h2)); h1.UserId = 654; Assert.IsFalse(h1.Equals(h2)); h2.UserId = h1.UserId; Assert.IsTrue(h1.Equals(h2)); h1.GroupId = 654; Assert.IsFalse(h1.Equals(h2)); h2.GroupId = h1.GroupId; Assert.IsTrue(h1.Equals(h2)); h1.Size = 654; Assert.IsFalse(h1.Equals(h2)); h2.Size = h1.Size; Assert.IsTrue(h1.Equals(h2)); h1.ModTime = DateTime.Now; Assert.IsFalse(h1.Equals(h2)); h2.ModTime = h1.ModTime; Assert.IsTrue(h1.Equals(h2)); h1.TypeFlag = 165; Assert.IsFalse(h1.Equals(h2)); h2.TypeFlag = h1.TypeFlag; Assert.IsTrue(h1.Equals(h2)); h1.LinkName = "link"; Assert.IsFalse(h1.Equals(h2)); h2.LinkName = h1.LinkName; Assert.IsTrue(h1.Equals(h2)); h1.Magic = "other"; Assert.IsFalse(h1.Equals(h2)); h2.Magic = h1.Magic; Assert.IsTrue(h1.Equals(h2)); h1.Version = "1"; Assert.IsFalse(h1.Equals(h2)); h2.Version = h1.Version; Assert.IsTrue(h1.Equals(h2)); h1.UserName = "nuser"; Assert.IsFalse(h1.Equals(h2)); h2.UserName = h1.UserName; Assert.IsTrue(h1.Equals(h2)); h1.GroupName = "group"; Assert.IsFalse(h1.Equals(h2)); h2.GroupName = h1.GroupName; Assert.IsTrue(h1.Equals(h2)); h1.DevMajor = 165; Assert.IsFalse(h1.Equals(h2)); h2.DevMajor = h1.DevMajor; Assert.IsTrue(h1.Equals(h2)); h1.DevMinor = 164; Assert.IsFalse(h1.Equals(h2)); h2.DevMinor = h1.DevMinor; Assert.IsTrue(h1.Equals(h2)); } [Test] [Category("Tar")] public void Checksum() { var ms = new MemoryStream(); using (TarOutputStream tarOut = new TarOutputStream(ms)) { DateTime modTime = DateTime.Now; TarEntry entry = TarEntry.CreateTarEntry("TestEntry"); entry.TarHeader.Mode = 12345; tarOut.PutNextEntry(entry); } var ms2 = new MemoryStream(); ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms2.Seek(0, SeekOrigin.Begin); TarEntry nextEntry; using (TarInputStream tarIn = new TarInputStream(ms2)) { nextEntry = tarIn.GetNextEntry(); Assert.IsTrue(nextEntry.TarHeader.IsChecksumValid, "Checksum should be valid"); } var ms3 = new MemoryStream(); ms3.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms3.Seek(0, SeekOrigin.Begin); ms3.Write(new byte[] { 34 }, 0, 1); ms3.Seek(0, SeekOrigin.Begin); using (TarInputStream tarIn = new TarInputStream(ms3)) { bool trapped = false; try { nextEntry = tarIn.GetNextEntry(); } catch (TarException) { trapped = true; } Assert.IsTrue(trapped, "Checksum should be invalid"); } } /// <summary> /// Check that values set are preserved when writing and reading archives. /// </summary> [Test] [Category("Tar")] public void ValuesPreserved() { var ms = new MemoryStream(); TarEntry entry; DateTime modTime = DateTime.Now; using (TarOutputStream tarOut = new TarOutputStream(ms)) { entry = TarEntry.CreateTarEntry("TestEntry"); entry.GroupId = 12; entry.UserId = 14; entry.ModTime = modTime; entry.UserName = "UserName"; entry.GroupName = "GroupName"; entry.TarHeader.Mode = 12345; tarOut.PutNextEntry(entry); } var ms2 = new MemoryStream(); ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms2.Seek(0, SeekOrigin.Begin); using (TarInputStream tarIn = new TarInputStream(ms2)) { TarEntry nextEntry = tarIn.GetNextEntry(); Assert.AreEqual(entry.TarHeader.Checksum, nextEntry.TarHeader.Checksum, "Checksum"); Assert.IsTrue(nextEntry.Equals(entry), "Entries should be equal"); Assert.IsTrue(nextEntry.TarHeader.Equals(entry.TarHeader), "Headers should match"); // Tar only stores seconds var truncatedTime = new DateTime(modTime.Year, modTime.Month, modTime.Day, modTime.Hour, modTime.Minute, modTime.Second); Assert.AreEqual(truncatedTime, nextEntry.ModTime, "Modtimes should match"); entryCount = 0; while (nextEntry != null) { ++entryCount; nextEntry = tarIn.GetNextEntry(); } Assert.AreEqual(1, entryCount, "Expected 1 entry"); } } /// <summary> /// Check invalid mod times are detected /// </summary> [Test] [Category("Tar")] //[ExpectedException(typeof(ArgumentOutOfRangeException))] public void InvalidModTime() { TarEntry e = TarEntry.CreateTarEntry("test"); //e.ModTime = DateTime.MinValue; Assert.That(() => e.ModTime = DateTime.MinValue, Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Check invalid sizes are detected /// </summary> [Test] [Category("Tar")] //[ExpectedException(typeof(ArgumentOutOfRangeException))] public void InvalidSize() { TarEntry e = TarEntry.CreateTarEntry("test"); //e.Size = -6; Assert.That(() => e.Size = -6, Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Check invalid names are detected /// </summary> [Test] [Category("Tar")] //[ExpectedException(typeof(ArgumentNullException))] public void InvalidName() { TarEntry e = TarEntry.CreateTarEntry("test"); //e.Name = null; Assert.That(() => e.Name = null, Throws.TypeOf<ArgumentNullException>()); } /// <summary> /// Check setting user and group names. /// </summary> [Test] [Category("Tar")] public void UserAndGroupNames() { TarEntry e = TarEntry.CreateTarEntry("test"); e.UserName = null; Assert.IsNotNull(e.UserName, "Name set to OS default"); e.UserName = ""; Assert.AreEqual(0, e.UserName.Length, "Empty name allowed"); e.GroupName = null; Assert.AreEqual("None", e.GroupName, "default group name is None"); } /// <summary> /// Check invalid magic values are detected /// </summary> [Test] [Category("Tar")] //[ExpectedException(typeof(ArgumentNullException))] public void InvalidMagic() { TarEntry e = TarEntry.CreateTarEntry("test"); //e.TarHeader.Magic = null; Assert.That(() => e.TarHeader.Magic = null, Throws.TypeOf<ArgumentNullException>()); } /// <summary> /// Check invalid link names are detected /// </summary> [Test] [Category("Tar")] //[ExpectedException(typeof(ArgumentNullException))] public void InvalidLinkName() { TarEntry e = TarEntry.CreateTarEntry("test"); //e.TarHeader.LinkName = null; Assert.That(() => e.TarHeader.LinkName = null, Throws.TypeOf<ArgumentNullException>()); } /// <summary> /// Check invalid version names are detected /// </summary> [Test] [Category("Tar")] //[ExpectedException(typeof(ArgumentNullException))] public void InvalidVersionName() { TarEntry e = TarEntry.CreateTarEntry("test"); //e.TarHeader.Version = null; Assert.That(() => e.TarHeader.Version = null, Throws.TypeOf<ArgumentNullException>()); } [Test] [Category("Tar")] public void CloningAndUniqueness() { // Partial test of cloning for TarHeader and TarEntry TarEntry e = TarEntry.CreateTarEntry("ohsogood"); e.GroupId = 47; e.GroupName = "GroupName"; e.ModTime = DateTime.Now; e.Size = 123234; TarHeader headerE = e.TarHeader; headerE.DevMajor = 99; headerE.DevMinor = 98; headerE.LinkName = "LanceLink"; var d = (TarEntry)e.Clone(); Assert.AreEqual(d.File, e.File); Assert.AreEqual(d.GroupId, e.GroupId); Assert.AreEqual(d.GroupName, e.GroupName); Assert.AreEqual(d.IsDirectory, e.IsDirectory); Assert.AreEqual(d.ModTime, e.ModTime); Assert.AreEqual(d.Size, e.Size); TarHeader headerD = d.TarHeader; Assert.AreEqual(headerE.Checksum, headerD.Checksum); Assert.AreEqual(headerE.LinkName, headerD.LinkName); Assert.AreEqual(99, headerD.DevMajor); Assert.AreEqual(98, headerD.DevMinor); Assert.AreEqual("LanceLink", headerD.LinkName); var entryf = new TarEntry(headerD); headerD.LinkName = "Something different"; Assert.AreNotEqual(headerD.LinkName, entryf.TarHeader.LinkName, "Entry headers should be unique"); } [Test] [Category("Tar")] public void OutputStreamOwnership() { var memStream = new TrackedMemoryStream(); var s = new TarOutputStream(memStream); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); s.Close(); Assert.IsTrue(memStream.IsClosed, "Should be closed after parent owner close"); Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close"); memStream = new TrackedMemoryStream(); s = new TarOutputStream(memStream); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); s.IsStreamOwner = false; s.Close(); Assert.IsFalse(memStream.IsClosed, "Should not be closed after parent owner close"); Assert.IsFalse(memStream.IsDisposed, "Should not be disposed after parent owner close"); } [Test] [Category("Tar")] public void InputStreamOwnership() { var memStream = new TrackedMemoryStream(); var s = new TarInputStream(memStream); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); s.Close(); Assert.IsTrue(memStream.IsClosed, "Should be closed after parent owner close"); Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close"); memStream = new TrackedMemoryStream(); s = new TarInputStream(memStream); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); s.IsStreamOwner = false; s.Close(); Assert.IsFalse(memStream.IsClosed, "Should not be closed after parent owner close"); Assert.IsFalse(memStream.IsDisposed, "Should not be disposed after parent owner close"); } [Test] [Category("Tar")] public void EndBlockHandling() { int dummySize = 70145; long outCount, inCount; using (var ms = new MemoryStream()) { using (var tarOut = TarArchive.CreateOutputTarArchive(ms)) using (var dummyFile = Utils.GetDummyFile(dummySize)) { tarOut.IsStreamOwner = false; tarOut.WriteEntry(TarEntry.CreateEntryFromFile(dummyFile.Filename), false); } outCount = ms.Position; ms.Seek(0, SeekOrigin.Begin); using (var tarIn = TarArchive.CreateInputTarArchive(ms)) using (var tempDir = new Utils.TempDir()) { tarIn.IsStreamOwner = false; tarIn.ExtractContents(tempDir.Fullpath); foreach (var file in Directory.GetFiles(tempDir.Fullpath, "*", SearchOption.AllDirectories)) { Console.WriteLine($"Extracted \"{file}\""); } } inCount = ms.Position; Console.WriteLine($"Output count: {outCount}"); Console.WriteLine($"Input count: {inCount}"); Assert.AreEqual(inCount, outCount, "Bytes read and bytes written should be equal"); } } [Test] [Category("Tar")] [Category("Performance")] [Explicit("Long Running")] public void WriteThroughput() { const string EntryName = "LargeTarEntry"; PerformanceTesting.TestWrite(TestDataSize.Large, bs => { var tos = new TarOutputStream(bs); tos.PutNextEntry(new TarEntry(new TarHeader() { Name = EntryName, Size = (int)TestDataSize.Large, })); return tos; }, stream => { ((TarOutputStream)stream).CloseEntry(); }); } [Test] [Category("Tar")] [Category("Performance")] [Explicit("Long Running")] public void SingleLargeEntry() { const string EntryName = "LargeTarEntry"; const TestDataSize dataSize = TestDataSize.Large; PerformanceTesting.TestReadWrite( size: dataSize, input: bs => { var tis = new TarInputStream(bs); var entry = tis.GetNextEntry(); Assert.AreEqual(entry.Name, EntryName); return tis; }, output: bs => { var tos = new TarOutputStream(bs); tos.PutNextEntry(new TarEntry(new TarHeader() { Name = EntryName, Size = (int)dataSize, })); return tos; }, outputClose: stream => { ((TarOutputStream)stream).CloseEntry(); } ); } // Test for corruption issue described @ https://github.com/icsharpcode/SharpZipLib/issues/321 [Test] [Category("Tar")] public void ExtractingCorruptTarShouldntLeakFiles() { using (var memoryStream = new MemoryStream()) { //Create a tar.gz in the output stream using (var gzipStream = new GZipOutputStream(memoryStream)) { gzipStream.IsStreamOwner = false; using (var tarOut = TarArchive.CreateOutputTarArchive(gzipStream)) using (var dummyFile = Utils.GetDummyFile(32000)) { tarOut.IsStreamOwner = false; tarOut.WriteEntry(TarEntry.CreateEntryFromFile(dummyFile.Filename), false); } } // corrupt archive - make sure the file still has more than one block memoryStream.SetLength(16000); memoryStream.Seek(0, SeekOrigin.Begin); // try to extract using (var gzipStream = new GZipInputStream(memoryStream)) { string tempDirName; gzipStream.IsStreamOwner = false; using (var tempDir = new Utils.TempDir()) { tempDirName = tempDir.Fullpath; using (var tarIn = TarArchive.CreateInputTarArchive(gzipStream)) { tarIn.IsStreamOwner = false; Assert.Throws<SharpZipBaseException>(() => tarIn.ExtractContents(tempDir.Fullpath)); } } Assert.That(Directory.Exists(tempDirName), Is.False, "Temporary folder should have been removed"); } } } } }
29.017878
135
0.690791
[ "MIT" ]
Mefodei/UniModules
UniGame.Zip/com.unity.sharp-zip-lib/Tests/Runtime/Tar/TarTests.cs
24,346
C#
using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; namespace Discord.Commands { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)] public abstract class ParameterPreconditionAttribute : Attribute { public abstract Task<PreconditionResult> CheckPermissions(ICommandContext context, ParameterInfo parameter, object value, IServiceProvider services); } }
37.583333
157
0.800443
[ "MIT" ]
TekMotion/Discord.Net
src/Discord.Net.Commands/Attributes/ParameterPreconditionAttribute.cs
451
C#
using System; namespace Accountant.Util; public static class Helpers { public static bool DateTimeClose(DateTime lhs, DateTime rhs) => (lhs - rhs).Duration() < TimeSpan.FromMinutes(1); // cf https://stackoverflow.com/questions/36845430/persistent-hashcode-for-strings public static int GetStableHashCode(string str) { unchecked { var hash1 = 5381; var hash2 = hash1; for (var i = 0; i < str.Length && str[i] != '\0'; i += 2) { hash1 = ((hash1 << 5) + hash1) ^ str[i]; if (i == str.Length - 1 || str[i + 1] == '\0') break; hash2 = ((hash2 << 5) + hash2) ^ str[i + 1]; } return hash1 + hash2 * 1566083941; } } // cf https://stackoverflow.com/questions/1646807/quick-and-simple-hash-code-combinations public static int CombineHashCodes(params int[] hashCodes) { var hash1 = (5381 << 16) + 5381; var hash2 = hash1; var i = 0; foreach (var hashCode in hashCodes) { if (i % 2 == 0) hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ hashCode; else hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ hashCode; ++i; } return hash1 + hash2 * 1566083941; } }
27.673077
94
0.477415
[ "Apache-2.0" ]
Ottermandias/Accountant
Accountant/Util/Helpers.cs
1,439
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lecture3 { public class Cube { // 3----------2 // /| /| // / | / | z // / 7-------/--6 | // 4--/-------1 / ----x // | / | / / // |/ |/ y // 8----------5 private const int size = 1; public List<Vector> vertexbuffer = new List<Vector> { new Vector( 1.0f, 1.0f, 1.0f), //1 new Vector( 1.0f, -1.0f, 1.0f), //2 new Vector(-1.0f, -1.0f, 1.0f), //3 new Vector(-1.0f, 1.0f, 1.0f), //4 new Vector( 1.0f, 1.0f, -1.0f), //5 new Vector( 1.0f, -1.0f, -1.0f), //6 new Vector(-1.0f, -1.0f, -1.0f), //7 new Vector(-1.0f, 1.0f, -1.0f), //8 new Vector( 1.2f, 1.2f, 1.2f), //1 new Vector( 1.2f, -1.2f, 1.2f), //2 new Vector(-1.2f, -1.2f, 1.2f), //3 new Vector(-1.2f, 1.2f, 1.2f), //4 new Vector( 1.2f, 1.2f, -1.2f), //5 new Vector( 1.2f, -1.2f, -1.2f), //6 new Vector(-1.2f, -1.2f, -1.2f), //7 new Vector(-1.2f, 1.2f, -1.2f) //8 }; Color col; public Cube(Color c) { col = c; } public void Draw(Graphics g, List<Vector> vb) { Pen pen = new Pen(col, 3f); g.DrawLine(pen, vb[0].x, vb[0].y, vb[1].x, vb[1].y); //1 -> 2 g.DrawLine(pen, vb[1].x, vb[1].y, vb[2].x, vb[2].y); //2 -> 3 g.DrawLine(pen, vb[2].x, vb[2].y, vb[3].x, vb[3].y); //3 -> 4 g.DrawLine(pen, vb[3].x, vb[3].y, vb[0].x, vb[0].y); //4 -> 1 g.DrawLine(pen, vb[4].x, vb[4].y, vb[5].x, vb[5].y); //5 -> 6 g.DrawLine(pen, vb[5].x, vb[5].y, vb[6].x, vb[6].y); //6 -> 7 g.DrawLine(pen, vb[6].x, vb[6].y, vb[7].x, vb[7].y); //7 -> 8 g.DrawLine(pen, vb[7].x, vb[7].y, vb[4].x, vb[4].y); //8 -> 5 pen.DashStyle = DashStyle.DashDot; g.DrawLine(pen, vb[0].x, vb[0].y, vb[4].x, vb[4].y); //1 -> 5 g.DrawLine(pen, vb[1].x, vb[1].y, vb[5].x, vb[5].y); //2 -> 6 g.DrawLine(pen, vb[2].x, vb[2].y, vb[6].x, vb[6].y); //3 -> 7 g.DrawLine(pen, vb[3].x, vb[3].y, vb[7].x, vb[7].y); //4 -> 8 Font font = new Font("Arial", 12, FontStyle.Bold); for (int i = 0; i < 8; i++) { PointF p = new PointF(vb[i + 8].x, vb[i + 8].y); g.DrawString(i.ToString(), font, Brushes.Black, p); } } } }
37.75641
76
0.382003
[ "Apache-2.0" ]
M1sterPl0w/AI
CG/Lecture3 - 3D/Lecture3/Cube.cs
2,947
C#
using Microsoft.ML.Data; namespace SrCnnEntireDetection.DataStructures { public class PhoneCallsData { [LoadColumn(0)] public string timestamp; [LoadColumn(1)] public double value; } }
16.571429
45
0.637931
[ "MIT" ]
DPSYCHIAS/machinelearning-samples
samples/csharp/getting-started/AnomalyDetection_PhoneCalls/SrEntireDetection/SrEntireDetectionConsoleApp/DataStructures/PhoneCallsData.cs
234
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Реверси.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Реверси.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap WhiteCR50 { get { object obj = ResourceManager.GetObject("WhiteCR50", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
42.527027
173
0.601843
[ "Apache-2.0" ]
Anastasia-Rybak/oop-examples
GamesLabs/2015/IT-21/Reversi/Properties/Resources.Designer.cs
3,163
C#
using UnityEngine; public class ProgressBar : Bar { [SerializeField] private Spawner _spawner; private void OnEnable() { _spawner.EnemyCountChanged += OnSliderValueChanged; Slider.value = 0; } private void OnDisable() { _spawner.EnemyCountChanged -= OnSliderValueChanged; } }
18.444444
59
0.656627
[ "MIT" ]
wladweb/SwampAttack
Assets/Scripts/UI/ProgressBar.cs
334
C#
// Copyright (c) Jon Thysell <http://jonthysell.com> // Licensed under the MIT License. namespace Kolohe { public enum GameInput : byte { PlayerMoveUp, PlayerMoveUpRight, PlayerMoveRight, PlayerMoveDownRight, PlayerMoveDown, PlayerMoveDownLeft, PlayerMoveLeft, PlayerMoveUpLeft, PlayerWait, } }
20.052632
53
0.619423
[ "MIT" ]
jonthysell/Kolohe
src/Kolohe/GameInput.cs
383
C#
using System; class Program { static void Main() { while (true) { string z = Console.ReadLine(); if (z == "-1") { break; } uint y = 1; uint x = uint.Parse(z); uint x1 = x; for (int p = 0; p <= 31; p++) { uint mask = y << p; int v = ((x & (mask)) != 0 ? 1 : 0); if (v == 1) { x = x & (~(mask)); uint mask1 = y << (p + 1); int v1 = ((x1 & (mask1)) != 0 ? 1 : 0); if (v1 == 1) { x = x1; x = x & (~(mask1)); for (int q = p + 1; q <= 31 - p; q++) { uint mask2 = y << q; int v2 = ((x1 & (mask2)) != 0 ? 1 : 0); if (v2 == 0) { x = x1; x = x | (mask2); } //else //{ // x = x1; // x = x & (~(mask2)); //} } } //else //{ // x = x1; // x = x & (~(mask1)); //} for (int r = p + 1; r <= 31 - p; r++) { uint mask3 = y << r; int v3 = ((x1 & (mask3)) != 0 ? 1 : 0); if (v3 == 0) { //for (int k = r + 1; k <= 31 - r; k++) //{ // uint mask4 = y << k; // int v4 = ((x1 & (mask4)) != 0 ? 1 : 0); // x = x1; // x = x | (mask4); //} } //else //{ // x = x1; // x = x & (~(mask3)); //} } } } Console.WriteLine(x); } } }
30.72619
73
0.154979
[ "MIT" ]
kaizer04/Telerik-Academy-2013-2014
C#1/Prepare-For-Exam-Homework/testNeuronMapping/Program.cs
2,583
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the devicefarm-2015-06-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DeviceFarm.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DeviceFarm.Model.Internal.MarshallTransformations { /// <summary> /// ExecutionConfiguration Marshaller /// </summary> public class ExecutionConfigurationMarshaller : IRequestMarshaller<ExecutionConfiguration, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(ExecutionConfiguration requestObject, JsonMarshallerContext context) { if(requestObject.IsSetAccountsCleanup()) { context.Writer.WritePropertyName("accountsCleanup"); context.Writer.Write(requestObject.AccountsCleanup); } if(requestObject.IsSetAppPackagesCleanup()) { context.Writer.WritePropertyName("appPackagesCleanup"); context.Writer.Write(requestObject.AppPackagesCleanup); } if(requestObject.IsSetJobTimeoutMinutes()) { context.Writer.WritePropertyName("jobTimeoutMinutes"); context.Writer.Write(requestObject.JobTimeoutMinutes); } if(requestObject.IsSetSkipAppResign()) { context.Writer.WritePropertyName("skipAppResign"); context.Writer.Write(requestObject.SkipAppResign); } if(requestObject.IsSetVideoCapture()) { context.Writer.WritePropertyName("videoCapture"); context.Writer.Write(requestObject.VideoCapture); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static ExecutionConfigurationMarshaller Instance = new ExecutionConfigurationMarshaller(); } }
34.709302
118
0.658961
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/DeviceFarm/Generated/Model/Internal/MarshallTransformations/ExecutionConfigurationMarshaller.cs
2,985
C#
#region Using Directives using System; using System.Drawing; #endregion Using Directives namespace ScintillaNET.Configuration { public class MarkersConfig { #region Fields private int? _alpha; private Color _backColor; private Color _foreColor; private bool? _inherit; private string _name; private int? _number; private MarkerSymbol? _symbol; #endregion Fields #region Properties public int? Alpha { get { return _alpha; } set { _alpha = value; } } public Color BackColor { get { return _backColor; } set { _backColor = value; } } public Color ForeColor { get { return _foreColor; } set { _foreColor = value; } } public bool? Inherit { get { return _inherit; } set { _inherit = value; } } public string Name { get { return _name; } set { _name = value; } } public int? Number { get { return _number; } set { _number = value; } } public MarkerSymbol? Symbol { get { return _symbol; } set { _symbol = value; } } #endregion Properties } }
16.283333
38
0.350563
[ "Unlicense" ]
itlezy/ITLezyTools
ScintillaNET-2.6/Configuration/MarkersConfig.cs
1,954
C#
namespace YC.Core.DynamicApi { /// <summary> /// Specifies the dynamic webapi options for the assembly. /// </summary> public class AssemblyDynamicWebApiOptions { /// <summary> /// Routing prefix for all APIs /// <para></para> /// Default value is null. /// </summary> public string ApiPrefix { get; } /// <summary> /// API HTTP Verb. /// <para></para> /// Default value is null. /// </summary> public string HttpVerb { get; } /// <summary> /// /// </summary> /// <param name="apiPrefix">Routing prefix for all APIs</param> /// <param name="httpVerb">API HTTP Verb.</param> public AssemblyDynamicWebApiOptions(string apiPrefix = null, string httpVerb = null) { ApiPrefix = apiPrefix; HttpVerb = httpVerb; } } }
27.939394
92
0.523861
[ "Apache-2.0" ]
boozzh/yc.boilerplate
src/Backstage/Module/YC.Core.DynamicApi/AssemblyDynamicWebApiOptions.cs
924
C#
// Licensed under the MIT license. namespace System { using System; partial struct ArgIterator { private ArgIterator(IntPtr arglist) { throw new NotImplementedException(); } private unsafe ArgIterator(IntPtr arglist, void* ptr) { throw new NotImplementedException(); } // reference to TypedReference is banned, so have to pass result as void pointer private unsafe void FCallGetNextArg(void* result) { throw new NotImplementedException(); } // reference to TypedReference is banned, so have to pass result as void pointer private unsafe void InternalGetNextArg(void* result, RuntimeType rt) { throw new NotImplementedException(); } // How many arguments are left in the list public int GetRemainingCount() { throw new NotImplementedException(); } // Gets the type of the current arg, does NOT advance the iterator private unsafe void* _GetNextArgType() { throw new NotImplementedException(); } } }
27.209302
88
0.603419
[ "MIT" ]
1Crazymoney/cs2cpp
CoreLib/Impl/ArgIterator.cs
1,172
C#
using Kocsistem.RabbitMQ.Customers.Application.Interfaces; using Kocsistem.RabbitMQ.Customers.Application.Models; using Kocsistem.RabbitMQ.Customers.Domain.Entities; using Kocsistem.RabbitMQ.Customers.Domain.Interfaces; namespace Kocsistem.RabbitMQ.Customers.Application.Services { public class CustomerService : ICustomerService { private readonly ICustomersRepository _customersRepository; public CustomerService(ICustomersRepository customersRepository) { _customersRepository = customersRepository; } public async Task<bool> AddCustomer(CustomersTableModel model) { var entity = new CustomersTable { Email = model.Email, FullName = model.FullName, Id = model.Id }; await _customersRepository.Add(entity); return true; } public async Task<bool> DeleteCustomer(Guid customerId) { var entity = await _customersRepository.GetCustomerById(customerId); await _customersRepository.Delete(entity); return true; } public IEnumerable<CustomersTableModel> GetAllCustomers() { return _customersRepository.GetAllCustomers().Select(x => new CustomersTableModel { Email = x.Email, FullName = x.FullName, Id = x.Id }); } public async Task<CustomersTableModel> GetCustomerById(Guid customerId) { var customer = await _customersRepository.GetCustomerById(customerId); return new CustomersTableModel { Id = customer.Id, FullName = customer.FullName, Email = customer.Email }; } public bool UpdateCustomer(CustomersTableModel model) { var entity = new CustomersTable { Email = model.Email, FullName = model.FullName, Id = model.Id }; _customersRepository.Update(entity); return true; } } }
31.724638
93
0.587026
[ "MIT" ]
erdemkayagentr/Microservices.Sample
Kocsistem.RabbitMQ.Customers.Application/Services/CustomerService.cs
2,191
C#
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; using Magalu.Challenge.ApplicationServices; namespace Magalu.Challenge.Web.Api.Controllers { public abstract class DataController<TEntity, TGetModel, TSendModel> : ApplicationController where TEntity : class { protected readonly IDataService<TEntity, TGetModel, TSendModel> DataService; public DataController(IDataService<TEntity, TGetModel, TSendModel> dataService) { DataService = dataService ?? throw new ArgumentNullException(nameof(dataService)); } [HttpGet("{id}")] public virtual async Task<ActionResult<TGetModel>> Get(Guid id) { return GetResult(await DataService.GetAsync(id)); } [HttpGet] public virtual async Task<ActionResult<IEnumerable<TGetModel>>> GetPage(int? page) { return GetResult(await DataService.GetPageAsync(page)); } [HttpPost] public virtual async Task<ActionResult<TGetModel>> Post([FromBody] TSendModel model) { var result = await DataService.SaveAsync(model); return GetResult(result); } [HttpPut("{id}")] public virtual async Task<ActionResult<TGetModel>> Put(Guid id, [FromBody] TSendModel model) { return GetResult(await DataService.UpdateAsync(model, id)); } [HttpDelete("{id}")] public virtual async Task<ActionResult> Delete(Guid id) { return GetResult(await DataService.DeleteAsync(id)); } } }
32.117647
118
0.652625
[ "MIT" ]
ivelten/MagaluChallenge
Magalu.Challenge.Web.Api/Controllers/DataController.cs
1,640
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hinshlabs.CommandLineParser.DemoCSharp.Commands.Demo3Command { public class Demo3CommandLine : CommandLineBase { private string m_value1; private Value2Values m_value2 = Value2Values.Value1; [CommandLineSwitch("Value1", "[CommandLineSwitch.Description]"), CommandLineAlias("v1")] public string Value1 { get { return this.m_value1; } set { this.m_value1 = value; } } [CommandLineSwitch("Value2", "[CommandLineSwitch.Description]"), CommandLineAlias("v2")] public Value2Values Value2 { get { return this.m_value2; } set { this.m_value2 = value; } } public enum Value2Values { Value1, Value2, Value3 } } }
24.025641
96
0.608324
[ "Apache-2.0" ]
nkdAgility/CommandLineParser
Source/Hinshlabs.CommandLineParser.DemoCSharp/Commands/Demo3Command/Demo3CommandLine.cs
939
C#
using _6MKT.Identity.Domain.Enums; namespace _6MKT.Identity.Api.Models.Request { public class UserAddRequest { public string Email { get; set; } public string Password { get; set; } public UserEnum Type { get; set; } } }
23.454545
44
0.639535
[ "MIT" ]
mateusggeracino/6mkt
src/backend/microservices/sso/6MKT.Identity.Api/Models/Request/UserAddRequest.cs
260
C#
using Mono.Cecil; using Mono.Collections.Generic; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aspekt.Bootstrap { /// <summary> /// A class that defines traits about a method. /// </summary> internal static class MethodTraits { public static bool HasMethod(TypeDefinition td, string methodName, params Type[] types) { return td.Methods.Any((mth) => { return mth.Name == methodName && CompareParameters(mth.Parameters, types); }); } public static bool HasGenericMethod(TypeDefinition td, string methodName, int paramCount) { return td.Methods.Any((mth) => { return mth.Name == methodName && mth.Parameters.Count == paramCount; }); } private static bool CompareParameters(Collection<ParameterDefinition> pars, params Type[] types) { if (pars.Count != types.Length) return false; for (var i = 0; i < pars.Count; ++i) { if (pars[i].ParameterType.FullName != types[i].FullName) return false; } return true; } } }
30.625
123
0.601633
[ "MIT" ]
mvpete/aspekt
Aspekt.Bootstrap/MethodTraits.cs
1,225
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace ai4u.ext { public class AutoByStepReward : RewardFunc { private RLAgent agent; private float sumOfRewards = 0.0f; public bool ignoreX = false; public bool ignoreY = true; public bool ignoreZ = false; public int maxRewardByEpisode = 0; public float reward = -1; public float minimumDistance = 0.2f; private Vector3 prevPosition; private float fx, fy, fz; private Vector3 f; // Start is called before the first frame update void Start() { if (ignoreX) { fx = 0; } else { fx = 1; } if (ignoreY) { fy = 0; } else { fy = 1; } if (ignoreZ) { fz = 0; } else { fz = 1; } f = new Vector3(fx, fy, fz); prevPosition = transform.localPosition; agent = GetComponent<RLAgent>(); agent.AddResetListener(this); sumOfRewards = 0; } // Update is called once per frame void FixedUpdate() { if (agent != null) { if (maxRewardByEpisode <= 0 || sumOfRewards < maxRewardByEpisode) { Vector3 p = Vector3.Scale(transform.localPosition, f); Vector3 pp = Vector3.Scale(prevPosition, f); float dist = Vector3.Distance(p, pp); if (dist >= minimumDistance) { sumOfRewards += System.Math.Abs(reward); agent.AddReward(reward, this); } } } else { Debug.LogWarning("Warning: an agent was not specified or this game object is not an agent!!!"); } prevPosition = transform.localPosition; } public override void OnReset(Agent agent) { prevPosition = transform.localPosition; sumOfRewards = 0; } } }
30.226667
112
0.466255
[ "MIT" ]
gilcoder/AI4U
serverside/unityversion/baseline/ext/RewardShaping/AutoByStepReward.cs
2,269
C#
using System; using NSubstitute.Community.Diagnostics.Logging; using NSubstitute.Community.Diagnostics.Utils; using NSubstitute.Core; namespace NSubstitute.Community.Diagnostics.Decorators { internal class DiagnosticsProxyFactory : IProxyFactory { private readonly IProxyFactory _impl; private readonly DiagContextInternal _ctx; public DiagnosticsProxyFactory(IProxyFactory impl, DiagContextInternal ctx) { _impl = impl; _ctx = ctx; } public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, object[] constructorArguments) { var diagCallRouter = new DiagnosticsCallRouter(callRouter, _ctx); var result = _impl.GenerateProxy(diagCallRouter, typeToProxy, additionalInterfaces, constructorArguments); _ctx.RegisterPrimaryProxyType(result, typeToProxy); LogAndTrace( $"GenerateProxy(callRouter: {callRouter.DiagName(_ctx)}, " + $"typeToProxy: {typeToProxy.FullName}, " + $"additionalInterfaces: {additionalInterfaces.Print(x => x.FullName)}, " + $"constructorArguments: {constructorArguments.Print(a => a.GetObjectId(_ctx))}) " + $"=> {result.SubstituteId(_ctx)}"); _ctx.MapRouterToSubstitute(callRouter, result); _ctx.MapRouterToSubstitute(diagCallRouter, result); _ctx.MapRouterToDiagRouter(callRouter, diagCallRouter); return result; } public override int GetHashCode() => _impl.GetHashCode(); private void LogAndTrace(string message) => _ctx.Logger.WriteLine($"[ProxyFactory] {message}"); } }
38.822222
118
0.664568
[ "MIT" ]
zvirja/NSubstitute.Community.Diagnostics
Src/NSubstitute.Community.Diagnostics/Decorators/DiagnosticsProxyFactory.cs
1,747
C#
using UnityEngine; using System.Collections.Generic; namespace MistRidge { [CreateAssetMenu(menuName = "Items/Item Droplist")] public class ItemDroplist : ScriptableObject { [SerializeField] private List<ItemDrop> itemDrops; public List<ItemDrop> ItemDrops { get { return itemDrops; } } } }
19.095238
55
0.571072
[ "MIT" ]
hinshun/mist-ridge
Assets/Scripts/Game/Gameplay/Items/ItemDroplist.cs
401
C#
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using NSec.Cryptography; namespace NSec.Experimental.Text { // RFC 4648 public static class Base16 { public static byte[] Decode( string base16) { if (!TryGetDecodedLength(base16, out int length)) { throw Error.Format_BadBase16(); } byte[] result = new byte[length]; if (!TryDecode(base16, result)) { throw Error.Format_BadBase16(); } return result; } public static byte[] Decode( ReadOnlySpan<char> base16) { if (!TryGetDecodedLength(base16, out int length)) { throw Error.Format_BadBase16(); } byte[] result = new byte[length]; if (!TryDecode(base16, result)) { throw Error.Format_BadBase16(); } return result; } public static byte[] DecodeFromUtf8( ReadOnlySpan<byte> base16) { if (!TryGetDecodedLength(base16, out int length)) { throw Error.Format_BadBase16(); } byte[] result = new byte[length]; if (!TryDecodeFromUtf8(base16, result)) { throw Error.Format_BadBase16(); } return result; } public static string Encode( ReadOnlySpan<byte> bytes) { char[] chars = new char[GetEncodedLength(bytes.Length)]; Encode(bytes, chars); return new string(chars); } public static void Encode( ReadOnlySpan<byte> bytes, Span<char> base16) { if (base16.Length != GetEncodedLength(bytes.Length)) { throw Error.Argument_BadBase16Length(nameof(base16)); } int di = 0; int si = 0; int b0, b1; while (bytes.Length - si >= 1) { EncodeByte(bytes[si++], out b0, out b1); base16[di++] = (char)b0; base16[di++] = (char)b1; } Debug.Assert(si == bytes.Length); Debug.Assert(di == base16.Length); } public static void EncodeToUtf8( ReadOnlySpan<byte> bytes, Span<byte> base16) { if (base16.Length != GetEncodedLength(bytes.Length)) { throw Error.Argument_BadBase16Length(nameof(base16)); } int di = 0; int si = 0; int b0, b1; while (bytes.Length - si >= 1) { EncodeByte(bytes[si++], out b0, out b1); base16[di++] = (byte)b0; base16[di++] = (byte)b1; } Debug.Assert(si == bytes.Length); Debug.Assert(di == base16.Length); } public static int GetEncodedLength( int byteCount) { return byteCount * 2; } public static bool TryDecode( string base16, Span<byte> bytes) { if (base16 == null) { throw Error.ArgumentNull_String(nameof(base16)); } return TryDecode(base16.AsSpan(), bytes); } public static bool TryDecode( ReadOnlySpan<char> base16, Span<byte> bytes) { if (base16.Length != GetEncodedLength(bytes.Length)) { throw Error.Argument_BadBase16Length(nameof(base16)); } int err = 0; int di = 0; int si = 0; byte r0; while (bytes.Length - di >= 1) { err |= DecodeByte(base16[si++], base16[si++], out r0); bytes[di++] = r0; } Debug.Assert(si == base16.Length); Debug.Assert(di == bytes.Length); return err == 0; } public static bool TryDecodeFromUtf8( ReadOnlySpan<byte> base16, Span<byte> bytes) { if (base16.Length != GetEncodedLength(bytes.Length)) { throw Error.Argument_BadBase16Length(nameof(base16)); } int err = 0; int di = 0; int si = 0; byte r0; while (bytes.Length - di >= 1) { err |= DecodeByte(base16[si++], base16[si++], out r0); bytes[di++] = r0; } Debug.Assert(si == base16.Length); Debug.Assert(di == bytes.Length); return err == 0; } public static bool TryGetDecodedLength( string base16, out int decodedLength) { if (base16 == null) { throw Error.ArgumentNull_String(nameof(base16)); } return TryGetDecodedLength(base16.AsSpan(), out decodedLength); } public static bool TryGetDecodedLength( ReadOnlySpan<char> base16, out int decodedLength) { if ((base16.Length & 1) != 0) { decodedLength = 0; return false; } decodedLength = base16.Length / 2; return true; } public static bool TryGetDecodedLength( ReadOnlySpan<byte> base16, out int decodedLength) { if ((base16.Length & 1) != 0) { decodedLength = 0; return false; } decodedLength = base16.Length / 2; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Decode4Bits( int src) { unchecked { int ret = -1; ret += (((0x2f - src) & (src - 0x3a)) >> 31) & (src - 47); ret += (((0x40 - src) & (src - 0x47)) >> 31) & (src - 54); ret += (((0x60 - src) & (src - 0x67)) >> 31) & (src - 86); return ret; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int DecodeByte( int b0, int b1, out byte r0) { unchecked { int c0 = Decode4Bits(b0); int c1 = Decode4Bits(b1); r0 = (byte)((c0 << 4) | c1); return (c0 | c1) >> 31; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Encode4Bits( int src) { unchecked { // upper case int diff = 48; diff += ((9 - src) >> 31) & 7; return src + diff; // lower case ////int diff = 48; ////diff += ((9 - src) >> 31) & 39; ////return src + diff; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void EncodeByte( byte b0, out int r0, out int r1) { unchecked { r0 = Encode4Bits(b0 >> 4); r1 = Encode4Bits(b0 & 15); } } } }
26.65614
75
0.439779
[ "MIT" ]
Bobface/DotNetLightning
src/NSec/Experimental/Text/Base16.cs
7,597
C#