content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // // This file was generated, please do not edit it directly. // // Please see MilCodeGen.html for more information. // using MS.Internal; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Markup; using System.Windows.Media.Media3D.Converters; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Media3D { abstract partial class Transform3D : GeneralTransform3D, DUCE.IResource { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new Transform3D Clone() { return (Transform3D)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new Transform3D CloneCurrentValue() { return (Transform3D)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal abstract DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel); /// <summary> /// AddRefOnChannel /// </summary> DUCE.ResourceHandle DUCE.IResource.AddRefOnChannel(DUCE.Channel channel) { // Reconsider the need for this lock when removing the MultiChannelResource. using (CompositionEngineLock.Acquire()) { return AddRefOnChannelCore(channel); } } internal abstract void ReleaseOnChannelCore(DUCE.Channel channel); /// <summary> /// ReleaseOnChannel /// </summary> void DUCE.IResource.ReleaseOnChannel(DUCE.Channel channel) { // Reconsider the need for this lock when removing the MultiChannelResource. using (CompositionEngineLock.Acquire()) { ReleaseOnChannelCore(channel); } } internal abstract DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel); /// <summary> /// GetHandle /// </summary> DUCE.ResourceHandle DUCE.IResource.GetHandle(DUCE.Channel channel) { DUCE.ResourceHandle handle; using (CompositionEngineLock.Acquire()) { handle = GetHandleCore(channel); } return handle; } internal abstract int GetChannelCountCore(); /// <summary> /// GetChannelCount /// </summary> int DUCE.IResource.GetChannelCount() { // must already be in composition lock here return GetChannelCountCore(); } internal abstract DUCE.Channel GetChannelCore(int index); /// <summary> /// GetChannel /// </summary> DUCE.Channel DUCE.IResource.GetChannel(int index) { // must already be in composition lock here return GetChannelCore(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #endregion Constructors } }
25.189873
88
0.502848
[ "MIT" ]
KodamaSakuno/wpf
src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/Media3D/Generated/Transform3D.cs
5,970
C#
/* * Copyright 2020 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 cloudfront-2020-05-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for FieldLevelEncryptionProfileSizeExceededException operation /// </summary> public class FieldLevelEncryptionProfileSizeExceededExceptionUnmarshaller : IErrorResponseUnmarshaller<FieldLevelEncryptionProfileSizeExceededException, XmlUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public FieldLevelEncryptionProfileSizeExceededException Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public FieldLevelEncryptionProfileSizeExceededException Unmarshall(XmlUnmarshallerContext context, ErrorResponse errorResponse) { FieldLevelEncryptionProfileSizeExceededException response = new FieldLevelEncryptionProfileSizeExceededException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { } } return response; } private static FieldLevelEncryptionProfileSizeExceededExceptionUnmarshaller _instance = new FieldLevelEncryptionProfileSizeExceededExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static FieldLevelEncryptionProfileSizeExceededExceptionUnmarshaller Instance { get { return _instance; } } } }
37.686747
180
0.688939
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/FieldLevelEncryptionProfileSizeExceededExceptionUnmarshaller.cs
3,128
C#
using Akka.Actor; using AKDK.Actors; using AKDK.Messages; using Docker.DotNet.Models; using System; using DockerEvents = AKDK.Messages.DockerEvents; namespace AKDK.Examples.Orchestration.Actors { /// <summary> /// Actor that manages an instance of a Docker container. /// </summary> public partial class Process : ReceiveActorEx, IWithUnboundedStash { /// <summary> /// The actor that owns the <see cref="Process"/>. /// </summary> readonly IActorRef _owner; /// <summary> /// A reference to the <see cref="Client"/> actor for the Docker API. /// </summary> readonly IActorRef _client; /// <summary> /// The name or Id of the container managed by the <see cref="Process"/> actor. /// </summary> readonly string _containerId; /// <summary> /// The message correlation Id used for notifications from the <see cref="Process"/>. /// </summary> /// <remarks> /// Captured when the <see cref="Start"/> message is received. /// </remarks> string _correlationId; /// <summary> /// Create a new <see cref="Process"/> actor. /// </summary> /// <param name="owner"> /// The actor that owns the <see cref="Process"/>. /// </param> /// <param name="client"> /// A reference to the <see cref="Client"/> actor for the Docker API. /// </param> /// <param name="containerId"> /// The name or Id of the container managed by the <see cref="Process"/> actor. /// </param> public Process(IActorRef owner, IActorRef client, string containerId) { if (owner == null) throw new ArgumentNullException(nameof(owner)); if (client == null) throw new ArgumentNullException(nameof(client)); if (String.IsNullOrWhiteSpace(containerId)) throw new ArgumentException($"Argument cannot be null, empty, or entirely composed of whitespace: {nameof(containerId)}.", nameof(containerId)); _owner = owner; _client = client; _containerId = containerId; } /// <summary> /// The actor's message stash. /// </summary> public IStash Stash { get; set; } void Initializing() { Log.Debug("Process '{0}' initialising...", _containerId); Receive<EventBusActor.Subscribed>(subscribed => { Become(Created); }); Receive<Start>(start => { Stash.Stash(); }); Receive<Stop>(stop => { Stash.Stash(); }); Receive<Destroy>(destroy => { Stash.Stash(); }); ReceiveContainerEvent<DockerEvents.ContainerEvent>(containerEvent => { Stash.Stash(); }); } /// <summary> /// Called when the process is first created. /// </summary> void Created() { Log.Debug("Process '{0}' initialised.", _containerId); Stash.UnstashAll(); Receive<Start>(start => { _correlationId = start.CorrelationId; _client.Tell(new StartContainer(_containerId, correlationId: start.CorrelationId )); Become(Starting); }); Receive<Stop>(stop => { Sender.Tell(new OperationFailure(stop.CorrelationId, operationName: "Kill Process", reason: new InvalidOperationException("Process is not running.") )); }); ReceiveContainerEvent<DockerEvents.ContainerDestroyed>(containerDestroyed => { Log.Debug("Container '{0}' has been destroyed unexpectedly; management actor '{1}' will shut down.", _containerId, Self); Context.Stop(Self); }); } /// <summary> /// Called when the container is starting. /// </summary> void Starting() { Log.Debug("Process '{0}' starting...", _containerId); Receive<Start>(start => { Sender.Tell(new OperationFailure(start.CorrelationId, operationName: "Start Process", reason: new InvalidOperationException("Process is already running.") )); }); Receive<Destroy>(destroy => { _client.Tell(new RemoveContainer(_containerId, correlationId: destroy.CorrelationId )); Become(Destroying); }); Receive<Stop>(stop => { Log.Debug("Stopping container '{0}' for process '{1}'.", _containerId, Self ); _client.Tell(new StopContainer(_containerId, waitBeforeKillSeconds: 30, correlationId: stop.CorrelationId )); Become(Stopping); }); Receive<ContainerStarted>(containerStarted => { Log.Debug("Container '{0}' started for process '{1}'.", containerStarted.ContainerId, Self ); _owner.Tell(new Started(_correlationId, containerId: containerStarted.ContainerId )); Become(Running); }); Receive<ErrorResponse>(errorResponse => { Log.Error(errorResponse.Reason, "Failed to start container '{0}': {1}", _containerId, errorResponse.Reason.Message ); _owner.Forward(errorResponse); Context.Stop(Self); }); ReceiveContainerEvent<DockerEvents.ContainerDied>(containerDied => { Log.Debug("Container '{0}' has terminated unexpectedly with exit code {1}.", _containerId, containerDied.ExitCode); _owner.Tell(new Exited(_correlationId, containerId: containerDied.ContainerId, exitCode: containerDied.ExitCode )); Context.Stop(Self); }); ReceiveContainerEvent<DockerEvents.ContainerDestroyed>(containerDestroyed => { Log.Debug("Container '{0}' has been destroyed unexpectedly; management actor '{1}' will shut down.", _containerId, Self); Context.Stop(Self); }); } /// <summary> /// Called when the process is running. /// </summary> void Running() { Log.Debug("Process '{0}' running...", _containerId); Receive<Start>(start => { Sender.Tell(new OperationFailure(start.CorrelationId, operationName: "Start Process", reason: new InvalidOperationException("Process is already running.") )); }); Receive<Stop>(stop => { Log.Debug("Stopping container '{0}' for process '{1}'.", _containerId, Self ); _client.Tell(new StopContainer(_containerId, correlationId: stop.CorrelationId )); Become(Stopping); }); Receive<Destroy>(destroy => { Sender.Tell(new OperationFailure(destroy.CorrelationId, operationName: "Destroy Process", reason: new InvalidOperationException("Process is still running.") )); }); ReceiveContainerEvent<DockerEvents.ContainerDied>(containerDied => { Log.Debug("Container '{0}' has terminated with exit code {1}.", _containerId, containerDied.ExitCode); _owner.Tell(new Exited(_correlationId, containerId: containerDied.ContainerId, exitCode: containerDied.ExitCode )); Become(Completed); }); ReceiveContainerEvent<DockerEvents.ContainerDestroyed>(containerDestroyed => { Log.Debug("Container '{0}' has been destroyed unexpectedly; management actor '{1}' will shut down.", _containerId, Self); Context.Stop(Self); }); } /// <summary> /// Called when the process is stopping. /// </summary> void Stopping() { Receive<ContainerStopped>(containerStopped => { Log.Debug("Container '{0}' stopped for process '{1}'.", containerStopped.ContainerId, Self ); _owner.Tell(new Stopped(_correlationId, containerId: containerStopped.ContainerId )); }); Receive<ErrorResponse>(errorResponse => { Log.Error(errorResponse.Reason, "Failed to stop container '{0}': {1}", _containerId, errorResponse.Reason.Message ); _owner.Forward(errorResponse); Context.Stop(Self); }); ReceiveContainerEvent<DockerEvents.ContainerDied>(containerDied => { Log.Debug("Container '{0}' has terminated with exit code {1}.", _containerId, containerDied.ExitCode); _owner.Tell(new Exited(_correlationId, containerId: containerDied.ContainerId, exitCode: containerDied.ExitCode )); Become(Completed); }); Receive<Start>(start => { Sender.Tell(new OperationFailure(start.CorrelationId, operationName: "Start Process", reason: new InvalidOperationException("Process is still stopping.") )); }); Receive<Destroy>(destroy => { Sender.Tell(new OperationFailure(destroy.CorrelationId, operationName: "Destroy Process", reason: new InvalidOperationException("Process is still stopping.") )); }); } /// <summary> /// Called when the process has exited. /// </summary> void Completed() { Receive<Start>(start => { Sender.Tell(new OperationFailure(start.CorrelationId, operationName: "Start Process", reason: new InvalidOperationException("Process is already running.") )); }); Receive<Destroy>(destroy => { _client.Tell(new RemoveContainer(_containerId, correlationId: destroy.CorrelationId )); Become(Destroying); }); } /// <summary> /// Called when the process is being destroyed. /// </summary> void Destroying() { Log.Debug("Container '{0}' is being destroyed...", _containerId); Receive<ContainerRemoved>(containerRemoved => { Log.Debug("Container '{0}' has been destroyed; management actor '{1}' will shut down.", _containerId, Self); _owner.Tell(new Destroyed(containerRemoved.CorrelationId, containerId: _containerId )); Context.Stop(Self); }); Receive<Start>(start => { Sender.Tell(new OperationFailure(start.CorrelationId, operationName: "Start Process", reason: new InvalidOperationException("Process is already running.") )); }); Receive<Destroy>(destroy => { Sender.Tell(new OperationFailure(destroy.CorrelationId, operationName: "Destroy Process", reason: new InvalidOperationException("Process is still running.") )); }); } /// <summary> /// Called when the actor is started. /// </summary> protected override void PreStart() { base.PreStart(); Context.Watch(_client); _client.Tell( new EventBusActor.Subscribe(Self, eventTypes: new Type[] { typeof(DockerEvents.ContainerEvent) }) ); Context.Watch(_owner); Become(Created); } /// <summary> /// Register a handler for the specified container event type. /// </summary> /// <typeparam name="TContainerEvent"> /// The type of container event to handle. /// </typeparam> /// <param name="handler"> /// The handler. /// </param> void ReceiveContainerEvent<TContainerEvent>(Action<TContainerEvent> handler) where TContainerEvent : DockerEvents.ContainerEvent { if (handler == null) throw new ArgumentNullException(nameof(handler)); Receive<TContainerEvent>(containerEvent => { // Only interested in events for our own container. if (containerEvent.ContainerId != _containerId) return; handler(containerEvent); }); } /// <summary> /// Generate <see cref="Props"/> to create a new <see cref="Process"/> actor. /// </summary> /// <param name="owner"> /// The actor that owns the <see cref="Process"/>. /// </param> /// <param name="client"> /// A reference to the <see cref="Client"/> actor for the Docker API. /// </param> /// <param name="containerId"> /// The name or Id of the container managed by the <see cref="Process"/> actor. /// </param> /// <returns> /// The configured <see cref="Props"/>. /// </returns> public static Props Create(IActorRef owner, IActorRef client, string containerId) { if (owner == null) throw new ArgumentNullException(nameof(owner)); if (client == null) throw new ArgumentNullException(nameof(client)); if (String.IsNullOrWhiteSpace(containerId)) throw new ArgumentException($"Argument cannot be null, empty, or entirely composed of whitespace: {nameof(containerId)}.", nameof(containerId)); return Props.Create( () => new Process(owner, client, containerId) ); } } }
34.117257
160
0.498282
[ "MIT" ]
tintoy/akdk
examples/orchestration/Actors/Process.cs
15,423
C#
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using AutoQC; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using SharedBatch; using SharedBatchTest; namespace AutoQCTest { [TestClass] public class PanoramaTest: AbstractUnitTest { public const string SERVER_URL = "https://panoramaweb.org/"; public const string PANORAMA_PARENT_PATH = "SkylineTest"; public const string PANORAMA_FOLDER_PREFIX = "AutoQcTest"; public const string PANORAMA_USER_NAME = "skyline_tester@proteinms.net"; public const string PANORAMA_PASSWORD = "lclcmsms"; private const int WAIT_3SEC = 3000; private const int TIMEOUT_80SEC = 80000; private string _testPanoramaFolder; private WebPanoramaClient _panoramaClient; /// <summary> /// Called by the unit test framework when a test begins. /// </summary> [TestInitialize] public void TestInitialize() { // Create a Panorama folder for the test var panoramaServerUri = new Uri(SERVER_URL); _panoramaClient = new WebPanoramaClient(panoramaServerUri); var random = new Random(); FolderOperationStatus status; string uniqueFolderName; do { uniqueFolderName = PANORAMA_FOLDER_PREFIX + random.Next(1000, 9999); status = _panoramaClient.CreateFolder(PANORAMA_PARENT_PATH, uniqueFolderName, PANORAMA_USER_NAME, PANORAMA_PASSWORD); } while (FolderOperationStatus.alreadyexists == status); Assert.AreEqual(FolderOperationStatus.OK, status, "Expected folder to be successfully created"); _testPanoramaFolder = uniqueFolderName; } /// <summary> /// Called by the unit test framework when a test is finished. /// </summary> [TestCleanup] public void TestCleanup() { // Delete the Panorama test folder Assert.AreEqual(FolderOperationStatus.OK, _panoramaClient.DeleteFolder($"{PANORAMA_PARENT_PATH}/{_testPanoramaFolder}/", PANORAMA_USER_NAME, PANORAMA_PASSWORD)); } [TestMethod] [DeploymentItem(@"..\AutoQC\FileAcquisitionTime.skyr")] [DeploymentItem(@"..\AutoQC\SkylineRunner.exe")] [DeploymentItem(@"..\AutoQC\SkylineDailyRunner.exe")] public async Task TestPublishToPanorama() { var testFilesDir = new TestFilesDir(TestContext, TestUtils.GetTestFilePath("PanoramaPublishTest.zip")); var skyFileName = "QEP_2015_0424_RJ.sky"; var rawFileName = "CE_Vantage_15mTorr_0001_REP1_01.raw"; Assert.IsTrue(File.Exists(testFilesDir.GetTestPath(skyFileName)), "Could not find Skyline file, nothing to import data into."); Assert.IsTrue(File.Exists(testFilesDir.GetTestPath(rawFileName)), "Could not find data file, nothing to upload."); var skylineSettings = TestUtils.GetTestSkylineSettings(); Assert.IsNotNull(skylineSettings, "Test cannot run without an installation of Skyline or Skyline-daily."); var config = new AutoQcConfig("PanoramaTestConfig", false, DateTime.MinValue, DateTime.MinValue, TestUtils.GetTestMainSettings(testFilesDir.GetTestPath(skyFileName), "folderToWatch", testFilesDir.FullPath), new PanoramaSettings(true, SERVER_URL, PANORAMA_USER_NAME, PANORAMA_PASSWORD, $"{PANORAMA_PARENT_PATH}/{_testPanoramaFolder}"), skylineSettings); // Validate the configuration try { config.Validate(true); } catch (Exception e) { Assert.Fail($"Expected configuration to be valid. Validation failed with error '{e.Message}'"); } var runner = new ConfigRunner(config, TestUtils.GetTestLogger(config)); Assert.IsTrue(runner.CanStart()); runner.Start(); Assert.IsTrue(WaitForConfigRunning(runner), $"Expected configuration to be running. Status was {runner.GetStatus()}."); var success = await SuccessfulPanoramaUpload(_testPanoramaFolder); Assert.IsTrue(success, "File was not uploaded to panorama."); runner.Stop(); } private bool WaitForConfigRunning(ConfigRunner runner) { var start = DateTime.Now; while (!RunnerStatus.Running.Equals(runner.GetStatus())) { Thread.Sleep(1000); if (DateTime.Now > start.AddSeconds(60)) { return false; } } return true; } private async Task<bool> SuccessfulPanoramaUpload(string uniqueFolder) { var panoramaServerUri = new Uri(PanoramaUtil.ServerNameToUrl(SERVER_URL)); var labKeyQuery = PanoramaUtil.CallNewInterface(panoramaServerUri, "query", $"{PANORAMA_PARENT_PATH}/{uniqueFolder}", "selectRows", "schemaName=targetedms&queryName=runs", true); var webClient = new WebPanoramaClient(panoramaServerUri); var startTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; var x = startTime; while (x < startTime + TIMEOUT_80SEC) { var jsonAsString = webClient.DownloadString(labKeyQuery, PANORAMA_USER_NAME, PANORAMA_PASSWORD); var json = JsonConvert.DeserializeObject<PanoramaJsonObject>(jsonAsString); if (json.rowCount > 0) return true; await Task.Delay(WAIT_3SEC); x = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; } return false; } } }
42.110345
145
0.610383
[ "Apache-2.0" ]
vagisha/pwiz
pwiz_tools/Skyline/Executables/AutoQC/AutoQCTest/PanoramaTest.cs
6,108
C#
using JetBrains.Annotations; using Novell.Directory.Ldap.Controls; using System; using System.Collections.Generic; namespace Novell.Directory.Ldap { /// <summary> /// Provides extensions methods for <see cref="ILdapConnection"/> to do paged searches /// with <see cref="SimplePagedResultsControl"/> using <see cref="SimplePagedResultsControlHandler"/>. /// </summary> public static class SimplePagedResultsControlSearchExtensions { public static List<LdapEntry> SearchUsingSimplePaging([NotNull] this ILdapConnection ldapConnection, [NotNull] SearchOptions options, int pageSize) { if (ldapConnection == null) { throw new ArgumentNullException(nameof(ldapConnection)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (pageSize <= 0) { throw new ArgumentOutOfRangeException(nameof(pageSize)); } return new SimplePagedResultsControlHandler(ldapConnection) .SearchWithSimplePaging(options, pageSize); } public static List<T> SearchUsingSimplePaging<T>([NotNull] this ILdapConnection ldapConnection, [NotNull] Func<LdapEntry, T> converter, [NotNull] SearchOptions options, int pageSize) { if (ldapConnection == null) { throw new ArgumentNullException(nameof(ldapConnection)); } if (converter == null) { throw new ArgumentNullException(nameof(converter)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } return new SimplePagedResultsControlHandler(ldapConnection) .SearchWithSimplePaging(converter, options, pageSize); } } }
33.929825
190
0.609617
[ "MIT" ]
kbezuid/Novell.Directory.Ldap.NETStandard
src/Novell.Directory.Ldap.NETStandard/SearchExtensions/SimplePagedResultsControlSearchExtensions.cs
1,936
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02. Hornet Comm")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. Hornet Comm")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("66e1d757-89ed-4b0d-9e2f-6f00bd47fd31")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.783784
84
0.744635
[ "MIT" ]
vankatalp360/Programming-Fundamentals-2017
Exam Preparation V/02. Hornet Comm/Properties/AssemblyInfo.cs
1,401
C#
using System; using System.Collections.Generic; using System.Net.Http; using KeyPayV2.Nz.Models.Common; using KeyPayV2.Nz.Enums; namespace KeyPayV2.Nz.Models.RosterShift { public class FindMatchingClockOffRosterShiftQueryModel { public int KioskId { get; set; } public DateTime DateUtc { get; set; } } }
23.133333
59
0.697406
[ "MIT" ]
KeyPay/keypay-dotnet-v2
src/keypay-dotnet/Nz/Models/RosterShift/FindMatchingClockOffRosterShiftQueryModel.cs
347
C#
/* * 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 java = biz.ritter.javapi; namespace biz.ritter.javapi.lang { public class Thread : Runnable { private java.util.HashMap<ThreadLocal<Object>,Object> threadLocalStore = new java.util.HashMap<ThreadLocal<Object>,Object>(); private Runnable runnable; System.Threading.Thread delegateInstance; private ClassLoader contextClassLoader = null; /// <summary> /// Return the current thread /// </summary> /// <returns></returns> public static java.lang.Thread currentThread() { java.lang.Thread result = new java.lang.Thread(); result.delegateInstance = System.Threading.Thread.CurrentThread; return result; } /// <summary> /// Return the System ClassLoader /// </summary> /// <returns></returns> public ClassLoader getContextClassLoader() { if (null == contextClassLoader) { this.contextClassLoader = ClassLoader.getSystemClassLoader(); } return this.contextClassLoader; } /// <summary> /// Set the context class loader /// </summary> /// <param name="cl"></param> public void setContextClassLoader(ClassLoader cl) { if (null == cl) throw new NullPointerException("Classloader can not be null"); this.contextClassLoader = cl; } /// <summary> /// Set the name of Thread instance to newName /// </summary> /// <param name="newName"></param> public void setName(String newName) { delegateInstance.Name = newName; } /// <summary> /// Get the name of Thread instance /// </summary> /// <returns></returns> public String getName() { return delegateInstance.Name; } /// <summary> /// Set this Thread instance to background / daemon thread or not. /// </summary> /// <param name="onOrOff"></param> public void setDaemon(bool onOrOff) { delegateInstance.IsBackground = true; } /// <summary> /// Return Thread instance is background / deamon thread information /// </summary> /// <returns></returns> public bool isDaemon() { return delegateInstance.IsBackground; } /// <summary> /// Construct new Thread instance /// </summary> public Thread() { this.runnable = this; this.delegateInstance = new System.Threading.Thread(new System.Threading.ThreadStart(this.runnable.run)); } /// <summary> /// Construct new Thread instance for giving Runnable instance /// </summary> /// <param name="toRun"></param> public Thread(Runnable toRun) { this.runnable = toRun; this.delegateInstance = new System.Threading.Thread(new System.Threading.ThreadStart(this.runnable.run)); } /// <summary> /// Construct new named Thread instance /// </summary> public Thread(String name) : this() { this.runnable = this; this.setName(name); } /// <summary> /// Construct new named Thread instance for giving Runnable instance /// </summary> /// <param name="toRun"></param> /// <param name="name"></param> public Thread(Runnable toRun, String name) { this.runnable = toRun; this.delegateInstance = new System.Threading.Thread(new System.Threading.ThreadStart(this.runnable.run)); this.setName(name); } /// <summary> /// All todo is implemented in run method. /// </summary> public virtual void run () {} /// <summary> /// Start the Thread instance /// </summary> public void start() { try { this.delegateInstance.Start(); } catch (System.Threading.ThreadStateException tse) { throw new IllegalThreadStateException(tse.Message); } } /// <summary> /// Return the State of Thread instance /// </summary> /// <returns></returns> public Thread.State getState() { switch (this.delegateInstance.ThreadState) { case System.Threading.ThreadState.Running : return State.RUNNABLE; case System.Threading.ThreadState.Unstarted : return State.NEW; case System.Threading.ThreadState.WaitSleepJoin : return State.WAITING; case System.Threading.ThreadState.Stopped | System.Threading.ThreadState.Aborted : return State.TERMINATED; default: return State.RUNNABLE; } } /// <summary> /// Thread is started but not died. /// </summary> /// <returns>Thread running true / false</returns> public bool isAlive() { return State.RUNNABLE == this.getState(); } ///<summary> /// A representation of a thread's state. A given thread may only be in one state at a time. ///</summary> public enum State { /** * The thread has been created, but has never been started. */ NEW, /** * The thread may be run. */ RUNNABLE, /** * The thread is blocked and waiting for a lock. */ BLOCKED, /** * The thread is waiting. */ WAITING, /** * The thread is waiting for a specified amount of time. */ TIMED_WAITING, /** * The thread has been terminated. */ TERMINATED } /// <summary> /// Let the Thread instance sleeping /// </summary> /// <param name="millis"></param> public static void sleep(int millis) { if (millis < 0) throw new IllegalArgumentException("Sleep time need to be greater or equals zero"); System.Threading.Thread.Sleep(millis); } internal void setThreadLocal (ThreadLocal<Object> tl, Object obj) { this.threadLocalStore.put(tl, obj); } internal Object getThreadLocal (ThreadLocal<Object> tl) { return this.threadLocalStore.get(tl); } public void interrupt() { try { this.delegateInstance.Interrupt(); } catch (System.Security.SecurityException se) { throw new java.lang.SecurityException(se.Message); } } public void stop() { this.stop(new ThreadDeath()); } public void stop(java.lang.Throwable t) { try { this.delegateInstance.Abort(); } catch (System.Threading.ThreadAbortException) { } catch (System.Threading.ThreadStateException) { } throw t; } } }
32.023715
133
0.529005
[ "ECL-2.0", "Apache-2.0" ]
bastie/NetSpider
NetVampiro/java/lang/Thread.cs
8,104
C#
using System; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using System.Threading.Tasks; using System.Net.Http.Headers; using iCoreService.Models; using iCoreService.AzureServices; namespace iCoreService.Controllers { /// <summary> /// Provide data to the biography search (aka HistoryMakers) view. /// </summary> public class BiographySearchController : ApiController { private AzureSearch azureSearch = new AzureSearch(); /// <summary> /// Performs a full text search of the biography index. /// </summary> /// <param name="query">The query terms.</param> /// <param name="pageSize">Number of results to return.</param> /// <param name="currentPage">Retreive the nth page of results based on given page size.</param> /// <param name="searchFields">Comma-separated list of fields to be searched.</param> /// <param name="genderFacet">Filter results by the given gender.</param> /// <param name="yearFacet">Filter results by the given year.</param> /// <param name="makerFacet">Filter results by the given comma-separated list of maker categories.</param> /// <param name="jobFacet">Filter results by the given comma-separated list of job types.</param> /// <param name="lastInitialFacet">Filter results by first letter of last name, e.g., C is filtering to all last names starting with C.</param> /// <param name="sortField">Sort results by this field, e.g., lastName; default is empty (meaning query relevance ranking is used to sort)</param> /// <param name="sortInDescendingOrder">Sort results in descending order if true; default is false so default sort order is ascending.</param> /// <returns> /// A BiographyResultSet document containing the results of the search operation. /// </returns> /// <remarks> /// If searchFields is "all" or not specified, it will be taken to be descriptionShort, accession, lastName, preferredName. /// If query is "all" via "*" wildcard and sortField is not specified, query relevance ranking will be taken to be "lastName ascending". /// </remarks> [ResponseType(typeof(BiographyResultSet))] public async Task<HttpResponseMessage> GetBiographySearch(string query = "", int? pageSize = 20, int? currentPage = 1, string searchFields = "all", string genderFacet = "", string yearFacet = "", string makerFacet = "", string jobFacet = "", string lastInitialFacet = "", string sortField = "", bool? sortInDescendingOrder = false) { try { // NOTE: One override: to add in a sortField of "lastName" if the query is empty or just the wildcard * for all results, // and the sortField is also not originally specified, with sorting on last name to be in ascending order. var sortFieldOverride = sortField; var sortInDescendingOrderOverride = sortInDescendingOrder; if ((string.IsNullOrEmpty(query) || query.Trim() == "*") && string.IsNullOrEmpty(sortField)) { sortFieldOverride = "lastName"; sortInDescendingOrderOverride = false; } #if SCIENCEMAKERSONLY var results = await this.azureSearch.BiographySearch( (query == null) ? "" : query, (pageSize == null) ? 20 : (int)pageSize, (currentPage == null) ? 1 : (int)currentPage, (searchFields == null) ? "all" : searchFields, (genderFacet == null) ? "" : genderFacet, (yearFacet == null) ? "" : yearFacet, (makerFacet == null) ? WebApiApplication.SCIENCEMAKER_FLAG : WebApiApplication.SCIENCEMAKER_FLAG, (jobFacet == null) ? "" : jobFacet, (lastInitialFacet == null) ? "" : lastInitialFacet, (sortFieldOverride == null) ? "" : sortFieldOverride, (sortInDescendingOrderOverride == null) ? false : (bool)sortInDescendingOrderOverride ); #else var results = await this.azureSearch.BiographySearch( (query == null) ? "" : query, (pageSize == null) ? 20 : (int)pageSize, (currentPage == null) ? 1 : (int)currentPage, (searchFields == null) ? "all" : searchFields, (genderFacet == null) ? "" : genderFacet, (yearFacet == null) ? "" : yearFacet, (makerFacet == null) ? "" : makerFacet, (jobFacet == null) ? "" : jobFacet, (lastInitialFacet == null) ? "" : lastInitialFacet, (sortFieldOverride == null) ? "" : sortFieldOverride, (sortInDescendingOrderOverride == null) ? false : (bool)sortInDescendingOrderOverride ); #endif var toc = new BiographyResultSet { Facets = results.Facets, Biographies = results.Results, Count = results.Count }; var response = Request.CreateResponse(HttpStatusCode.OK, toc, Configuration.Formatters.JsonFormatter); #if !NO_CACHE_FOR_TESTING_API response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromDays(1), Public = true }; #endif return response; } catch (Exception ex) { return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(ex.Message) }; } } } }
55.193277
155
0.527253
[ "MIT" ]
mikechristel/iCoreService-Digital-Archive-API
iCoreService/Controllers/BiographySearchController.cs
6,570
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // using ApiManagement.Management.Tests; using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; namespace ApiManagement.Tests.ManagementApiTests { public class DiagnosticTests : TestBase { [Fact] [Trait("Owner", "vifedo")] public async Task CreateListUpdateDelete() { Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Record"); using (MockContext context = MockContext.Start(this.GetType())) { var testBase = new ApiManagementTestBase(context); testBase.TryCreateApiManagementService(); // list diagnostics: there should be none var diagnostics = testBase.client.Diagnostic.ListByService( testBase.rgName, testBase.serviceName, null); Assert.NotNull(diagnostics); Assert.Empty(diagnostics); // create new diagnostic, supported Ids are applicationinsights, azuremonitor string diagnosticId = "applicationinsights"; string loggerId = TestUtilities.GenerateName("appInsights"); try { // create a logger Guid applicationInsightsGuid = TestUtilities.GenerateGuid("appInsights"); var credentials = new Dictionary<string, string>(); credentials.Add("instrumentationKey", applicationInsightsGuid.ToString()); var loggerCreateParameters = new LoggerContract(LoggerType.ApplicationInsights, credentials); var loggerContract = await testBase.client.Logger.CreateOrUpdateAsync( testBase.rgName, testBase.serviceName, loggerId, loggerCreateParameters); Assert.NotNull(loggerContract); Assert.Equal(loggerId, loggerContract.Name); Assert.Equal(LoggerType.ApplicationInsights, loggerContract.LoggerType); Assert.NotNull(loggerContract.Credentials); Assert.Equal(1, loggerContract.Credentials.Keys.Count); // create a diagnostic entity with just loggerId var diagnosticContractParams = new DiagnosticContract() { LoggerId = loggerContract.Id }; var diagnosticContract = await testBase.client.Diagnostic.CreateOrUpdateAsync( testBase.rgName, testBase.serviceName, diagnosticId, diagnosticContractParams); Assert.NotNull(diagnosticContract); Assert.Equal(diagnosticId, diagnosticContract.Name); // check the diagnostic entity etag var diagnosticTag = await testBase.client.Diagnostic.GetEntityTagAsync( testBase.rgName, testBase.serviceName, diagnosticId); Assert.NotNull(diagnosticTag); Assert.NotNull(diagnosticTag.ETag); // now update the sampling and other settings of the diagnostic diagnosticContractParams.EnableHttpCorrelationHeaders = true; diagnosticContractParams.AlwaysLog = "allErrors"; diagnosticContractParams.Sampling = new SamplingSettings("fixed", 50); var listOfHeaders = new List<string> { "Content-type" }; var bodyDiagnostic = new BodyDiagnosticSettings(512); diagnosticContractParams.Frontend = new PipelineDiagnosticSettings { Request = new HttpMessageDiagnostic() { Body = bodyDiagnostic, Headers = listOfHeaders }, Response = new HttpMessageDiagnostic() { Body = bodyDiagnostic, Headers = listOfHeaders } }; diagnosticContractParams.Backend = new PipelineDiagnosticSettings { Request = new HttpMessageDiagnostic() { Body = bodyDiagnostic, Headers = listOfHeaders }, Response = new HttpMessageDiagnostic() { Body = bodyDiagnostic, Headers = listOfHeaders } }; var updatedDiagnostic = await testBase.client.Diagnostic.CreateOrUpdateWithHttpMessagesAsync( testBase.rgName, testBase.serviceName, diagnosticId, diagnosticContractParams, diagnosticTag.ETag); Assert.NotNull(updatedDiagnostic); Assert.True(updatedDiagnostic.Body.EnableHttpCorrelationHeaders.Value); Assert.Equal("allErrors", updatedDiagnostic.Body.AlwaysLog); Assert.NotNull(updatedDiagnostic.Body.Sampling); Assert.NotNull(updatedDiagnostic.Body.Frontend); Assert.NotNull(updatedDiagnostic.Body.Backend); // delete the diagnostic entity await testBase.client.Diagnostic.DeleteAsync( testBase.rgName, testBase.serviceName, diagnosticId, updatedDiagnostic.Headers.ETag); Assert.Throws<ErrorResponseException>(() => testBase.client.Diagnostic.GetEntityTag(testBase.rgName, testBase.serviceName, diagnosticId)); // check the logger entity etag var loggerTag = await testBase.client.Logger.GetEntityTagAsync( testBase.rgName, testBase.serviceName, loggerId); Assert.NotNull(loggerTag); Assert.NotNull(loggerTag.ETag); // delete the logger entity await testBase.client.Logger.DeleteAsync( testBase.rgName, testBase.serviceName, loggerId, loggerTag.ETag); Assert.Throws<ErrorResponseException>(() => testBase.client.Logger.GetEntityTag(testBase.rgName, testBase.serviceName, loggerId)); } finally { testBase.client.Diagnostic.Delete(testBase.rgName, testBase.serviceName, diagnosticId, "*"); testBase.client.Logger.Delete(testBase.rgName, testBase.serviceName, loggerId, "*"); } } } } }
46.457317
121
0.530122
[ "MIT" ]
jijohn14/azure-sdk-for-net
sdk/apimanagement/Microsoft.Azure.Management.ApiManagement/tests/ManagementApiTests/DiagnosticTests.cs
7,621
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Intellichess.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Intellichess.Core")] [assembly: AssemblyCopyright("Copyright © 2012 // m.sadegh.sh@gmail.com")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9e0f38ef-2e3f-4d8b-bef8-534394eedfd7")] // 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")]
35.769231
84
0.739785
[ "MIT" ]
m-sadegh-sh/Intellichess
src/Intellichess.Core/Properties/AssemblyInfo.cs
1,398
C#
using Assets.PatternDesigner.Scripts.PaintSystem.Player; using Assets.PatternDesigner.Scripts.PaintSystem.Stroke; using Assets.PatternDesigner.Scripts.Util; using Assets.PatternDesigner.Scripts.Values; using Assets.PatternDesigner.Scripts.Values.Resources; using UnityEngine; using UnityEngine.UI; namespace Assets.PatternDesigner.Scripts.UI.RadialMenu { /// <summary> /// Represents the secondary radial menu for controlling player and more. /// </summary> public class PlaybackRadialMenu : PatternRadialMenu { [SerializeField] public Button btnSpeed, btnTime; private ButtonHandler buttonHandler; [SerializeField] private ControllerUI controllerUI; private TactilePlayer player; [SerializeField] private VRSlider slider; private ToggleHandler toggleHandler; [SerializeField] public Toggle toggleLoop, togglePlay, toggleRecord; [SerializeField] public TextMesh trackpadDescText; #region Initialization protected override void Awake() { base.Awake(); paintMode.pattern.StrokeAdded += OnStrokeAdded; paintMode.pattern.StrokeRemoved += OnStrokeRemoved; player = paintMode.player; buttonHandler = new ButtonHandler( ButtonHandler.newKeyValuePair(btnSpeed, OnSpeedClicked), ButtonHandler.newKeyValuePair(btnTime, OnTimeClicked) ); toggleHandler = new ToggleHandler( ToggleHandler.newKeyValuePair(togglePlay, OnPlayClicked), ToggleHandler.newKeyValuePair(toggleLoop, OnLoopClicked), ToggleHandler.newKeyValuePair(toggleRecord, OnRecordClicked) ); } // initialization protected override void Start() { base.Start(); slider.OnSliderExit += OnSliderExit; player.PlayStarted += OnPatternPlay; player.PlayStopped += OnPatternStop; buttonHandler.RegisterActions(); toggleHandler.RegisterActions(); } protected override void OnEnable() { base.OnEnable(); UpdateToggleText(); EnableButtons(paintMode.pattern.strokes.Count); DisableButtons(paintMode.pattern.strokes.Count); } protected override void OnDisable() { base.OnDisable(); } protected override void OnDestroy() { base.OnDestroy(); slider.OnSliderExit -= OnSliderExit; player.PlayStarted -= OnPatternPlay; player.PlayStopped -= OnPatternStop; buttonHandler.UnregisterActions(); toggleHandler.UnregisterActions(); } #endregion #region buttonPressEvents /// <summary> /// Updates the text on the controller. /// </summary> public void UpdateToggleText() { var text = ResourcesManager.Get(Strings.PLAY); if (player.IsPlaying()) text = ResourcesManager.Get(Strings.STOP); togglePlay.GetComponentInChildren<Text>().text = text; var loopText = ResourcesManager.Get(Strings.ENABLE_LOOP); if (player.IsLooping()) { toggleLoop.isOn = true; loopText = ResourcesManager.Get(Strings.DISABLE_LOOP); } toggleLoop.GetComponentInChildren<Text>().text = loopText; } protected override void OnStrokeAdded(Stroke stroke) { EnableButtons(paintMode.pattern.strokes.Count); } protected override void OnStrokeRemoved(Stroke stroke) { DisableButtons(paintMode.pattern.strokes.Count); } private void EnableButtons(int strokeAmount) { if (strokeAmount > 0) EnableSelectable(btnTime, togglePlay); } private void DisableButtons(int strokeAmount) { if (strokeAmount <= 0) DisableSelectable(btnTime, togglePlay); } private void OnPlayClicked(bool isOn) { if (player.IsPlaying() && !isOn) player.Stop(); else if (isOn) player.Play(); UpdateToggleText(); } public void OnPatternPlay() { togglePlay.GetComponentInChildren<Text>().text = ResourcesManager.Get(Strings.STOP); } public void OnPatternStop() { togglePlay.GetComponentInChildren<Text>().text = ResourcesManager.Get(Strings.PLAY); togglePlay.isOn = false; } private void OnLoopClicked(bool isOn) { player.SetLooping(isOn); UpdateToggleText(); } private void OnSpeedClicked() { var sliderValue = calcSpeedSliderValue(player.GetSpeed()); slider.snapValue = calcSpeedSliderValue(1f); slider.OnValueChanged += OnSpeedSliderChanged; ShowSlider(sliderValue); } private float calcSpeedSliderValue(float speed) { return (speed - Constants.PLAYER_MIN_SPEED) / (Constants.PLAYER_MAX_SPEED - Constants.PLAYER_MIN_SPEED); } private void OnTimeClicked() { player.Stop(); var sliderValue = player.GetTime() / player.GetDuration(); slider.OnValueChanged += OnTimeSliderChanged; ShowSlider(sliderValue); } private void OnRecordClicked(bool isOn) { player.isRecording = isOn; } private void ShowSlider(float value) { inputHandler.UnregisterActions(); controllerUI.inputHandler.UnregisterActions(); slider.Show(value); } private void OnSpeedSliderChanged(float value) { var speed = value * (Constants.PLAYER_MAX_SPEED - Constants.PLAYER_MIN_SPEED) + Constants.PLAYER_MIN_SPEED; player.SetSpeed(speed); trackpadDescText.text = ResourcesManager.Get(Strings.SLIDER_SPEED, speed); } private void OnTimeSliderChanged(float value) { var time = value * player.GetDuration(); if (time < 0) time = 0f; player.SetTime(time); trackpadDescText.text = ResourcesManager.Get(Strings.SLIDER_TIME_DESC); } private void OnSliderExit(float value, bool shouldSave) { slider.snapValue = -1f; controllerUI.inputHandler.RegisterActions(); if (shouldSave) controllerUI.Show(); trackpadDescText.text = ResourcesManager.Get(Strings.SHOW_MENU); slider.OnValueChanged -= OnSpeedSliderChanged; slider.OnValueChanged -= OnTimeSliderChanged; } #endregion } }
31.165179
119
0.597909
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
obkaul/VRTactileDraw
Assets/PatternDesigner/Scripts/UI/RadialMenu/PlaybackRadialMenu.cs
6,983
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Printing; using System.Linq; using System.Threading; using System.Windows.Forms; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Core.Routing; using Microsoft.Msagl.Drawing; using Microsoft.Msagl.Layout.Incremental; using Microsoft.Msagl.Layout.Layered; using Microsoft.Msagl.Layout.MDS; using Microsoft.Msagl.Miscellaneous; using Microsoft.Msagl.Prototype.LayoutEditing; using Microsoft.Msagl.Prototype.Ranking; using Microsoft.Msagl.Routing; using DrawingEdge = Microsoft.Msagl.Drawing.Edge; using DrawingNode = Microsoft.Msagl.Drawing.Node; using Edge = Microsoft.Msagl.Core.Layout.Edge; using Label = Microsoft.Msagl.Drawing.Label; using MouseButtons = System.Windows.Forms.MouseButtons; using Node = Microsoft.Msagl.Core.Layout.Node; using Point = Microsoft.Msagl.Core.Geometry.Point; using Rectangle = System.Drawing.Rectangle; using Size = Microsoft.Msagl.Core.DataStructures.Size; namespace Microsoft.Msagl.GraphViewerGdi { /// <summary> /// Summary description for DOTViewer. /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public sealed partial class GViewer : UserControl { #region Support for layout editing double arrowheadLength = 10; LayoutEditor layoutEditor; ToolBarButton edgeInsertButton; bool insertingEdge; ToolBarButton layoutSettingsButton; ToolBarButton redoButton; ToolBarButton undoButton; internal ToolBarButton zoomin; internal ToolBarButton zoomout; internal ToolBarButton windowZoomButton; internal ToolBarButton panButton; private ToolBarButton homeZoomButton; /// <summary> /// gets or sets the drawing layout editor /// </summary> public LayoutEditor LayoutEditor { get { return layoutEditor; } set { layoutEditor = value; } } /// <summary> /// if is set to true then the mouse left click on a node and dragging the cursor to /// another node will create an edge and add it to the graph /// </summary> public bool InsertingEdge { get { return insertingEdge; } set { insertingEdge = value; if (LayoutEditor != null) { if (value) EntityFilterDelegate = EdgeFilter; else EntityFilterDelegate = null; } } } /// <summary> /// the length of arrowheads for newly inserted edges /// </summary> public double ArrowheadLength { get { if (Graph != null && Graph.LayoutAlgorithmSettings is SugiyamaLayoutSettings) return Math.Min(arrowheadLength, Graph.Attr.LayerSeparation/2); return arrowheadLength; } set { arrowheadLength = value; } } /// <summary> /// creates the port visual if it does not exist, and sets the port location /// </summary> /// <param name="portLocation"></param> public void SetSourcePortForEdgeRouting(Point portLocation) { var box = new Core.Geometry.Rectangle(portLocation); box.Pad(UnderlyingPolylineCircleRadius); if (SourcePortIsPresent) { var prevBox = new Core.Geometry.Rectangle(SourcePortLocation); prevBox.Pad(UnderlyingPolylineCircleRadius); box.Add(prevBox); } SourcePortIsPresent = true; SourcePortLocation = portLocation; panel.Invalidate(MapSourceRectangleToScreenRectangle(box)); } internal Point SourcePortLocation { get; private set; } internal bool SourcePortIsPresent { get; private set; } /// <summary> /// /// </summary> /// <param name="portLocation"></param> public void SetTargetPortForEdgeRouting(Point portLocation) { TargetPortIsPresent = true; TargetPortLocation = portLocation; } internal Point TargetPortLocation { get; private set; } internal bool TargetPortIsPresent { get; private set; } /// <summary> /// /// </summary> public void RemoveSourcePortEdgeRouting() { if (SourcePortIsPresent) { var prevBox = new Core.Geometry.Rectangle(SourcePortLocation); prevBox.Pad(UnderlyingPolylineCircleRadius); panel.Invalidate(MapSourceRectangleToScreenRectangle(prevBox)); SourcePortIsPresent = false; } } /// <summary> /// /// </summary> public void RemoveTargetPortEdgeRouting() { TargetPortIsPresent = false; } void ClearLayoutEditor() { if (LayoutEditor != null) DisableDrawingLayoutEditor(); InitDrawingLayoutEditor(); } #endregion bool asyncLayout; ToolBarButton backwardButton; BBNode bBNode; bool buildHitTree = true; IContainer components; DGraph dGraph; string fileName = ""; ToolBarButton forwardButton; EventHandler<MsaglMouseEventArgs> iEditViewerMouseDown; EventHandler<MsaglMouseEventArgs> iEditViewerMouseMove; EventHandler<MsaglMouseEventArgs> iEditViewerMouseUp; ImageList imageList; double looseOffsetForRouting = 1.0/8*2; double mouseHitDistance = 0.05; bool needToCalculateLayout = true; double offsetForRelaxingInRouting = 0.6; ToolBarButton openButton; Graph originalGraph; double paddingForEdgeRouting = 8; const string PanButtonDisabledToolTipText = "Pan, is disabled now"; ToolBarButton print; ToolBarButton saveButton; double tightOffsetForRouting = 1.0/8; ToolBar toolbar; ToolTip toolTip1; const double VisibleWidth = 0.05; //inches bool wasMinimized; const string WindowZoomButtonToolTipText = "Zoom in by dragging a rectangle"; double zoomWindowThreshold = 0.05; //inches #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GViewer)); this.imageList = new System.Windows.Forms.ImageList(this.components); this.toolbar = new System.Windows.Forms.ToolBar(); this.homeZoomButton = new System.Windows.Forms.ToolBarButton(); this.zoomin = new System.Windows.Forms.ToolBarButton(); this.zoomout = new System.Windows.Forms.ToolBarButton(); this.windowZoomButton = new System.Windows.Forms.ToolBarButton(); this.panButton = new System.Windows.Forms.ToolBarButton(); this.backwardButton = new System.Windows.Forms.ToolBarButton(); this.forwardButton = new System.Windows.Forms.ToolBarButton(); this.saveButton = new System.Windows.Forms.ToolBarButton(); this.undoButton = new System.Windows.Forms.ToolBarButton(); this.redoButton = new System.Windows.Forms.ToolBarButton(); this.openButton = new System.Windows.Forms.ToolBarButton(); this.print = new System.Windows.Forms.ToolBarButton(); this.layoutSettingsButton = new System.Windows.Forms.ToolBarButton(); this.edgeInsertButton = new System.Windows.Forms.ToolBarButton(); this.SuspendLayout(); // // imageList // this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream"))); this.imageList.TransparentColor = System.Drawing.Color.Transparent; this.imageList.Images.SetKeyName(0, ""); this.imageList.Images.SetKeyName(1, ""); this.imageList.Images.SetKeyName(2, "zoom.bmp"); this.imageList.Images.SetKeyName(3, ""); this.imageList.Images.SetKeyName(4, ""); this.imageList.Images.SetKeyName(5, ""); this.imageList.Images.SetKeyName(6, ""); this.imageList.Images.SetKeyName(7, ""); this.imageList.Images.SetKeyName(8, ""); this.imageList.Images.SetKeyName(9, "undo.bmp"); this.imageList.Images.SetKeyName(10, "redo.bmp"); this.imageList.Images.SetKeyName(11, ""); this.imageList.Images.SetKeyName(12, "openfolderHS.png"); this.imageList.Images.SetKeyName(13, "disabledUndo.bmp"); this.imageList.Images.SetKeyName(14, "disabledRedo.bmp"); this.imageList.Images.SetKeyName(15, "layoutMethodBlue.ico"); this.imageList.Images.SetKeyName(16, "edge.jpg"); this.imageList.Images.SetKeyName(17, "home.bmp"); // // toolbar // this.toolbar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.homeZoomButton, this.zoomin, this.zoomout, this.windowZoomButton, this.panButton, this.backwardButton, this.forwardButton, this.saveButton, this.undoButton, this.redoButton, this.openButton, this.print, this.layoutSettingsButton, this.edgeInsertButton}); this.toolbar.ButtonSize = new System.Drawing.Size(22, 23); this.toolbar.DropDownArrows = true; this.toolbar.ImageList = this.imageList; this.toolbar.Location = new System.Drawing.Point(0, 0); this.toolbar.Name = "toolbar"; this.toolbar.ShowToolTips = true; this.toolbar.Size = new System.Drawing.Size(624, 28); this.toolbar.TabIndex = 2; this.toolbar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.ToolBarButtonClick); // // homeZoomButton // this.homeZoomButton.ImageIndex = 17; this.homeZoomButton.Name = "homeZoomButton"; // // zoomin // this.zoomin.ImageIndex = 0; this.zoomin.Name = "zoomin"; this.zoomin.ToolTipText = "Zoom In"; // // zoomout // this.zoomout.ImageIndex = 1; this.zoomout.Name = "zoomout"; this.zoomout.ToolTipText = "Zoom Out"; // // windowZoomButton // this.windowZoomButton.ImageKey = "zoom.bmp"; this.windowZoomButton.Name = "windowZoomButton"; this.windowZoomButton.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton; this.windowZoomButton.ToolTipText = "Zoom in to the rectangle"; // // panButton // this.panButton.ImageIndex = 3; this.panButton.Name = "panButton"; this.panButton.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton; this.panButton.ToolTipText = "Pan"; // // backwardButton // this.backwardButton.ImageIndex = 6; this.backwardButton.Name = "backwardButton"; this.backwardButton.ToolTipText = "Backward"; // // forwardButton // this.forwardButton.ImageIndex = 4; this.forwardButton.Name = "forwardButton"; // // saveButton // this.saveButton.ImageIndex = 8; this.saveButton.Name = "saveButton"; this.saveButton.ToolTipText = "Save the graph or the drawing"; // // undoButton // this.undoButton.ImageIndex = 9; this.undoButton.Name = "undoButton"; // // redoButton // this.redoButton.ImageIndex = 10; this.redoButton.Name = "redoButton"; // // openButton // this.openButton.ImageIndex = 12; this.openButton.Name = "openButton"; this.openButton.ToolTipText = "Load a graph from a \".msagl\" file"; // // print // this.print.ImageIndex = 11; this.print.Name = "print"; this.print.ToolTipText = "Print the current view"; // // layoutSettingsButton // this.layoutSettingsButton.ImageIndex = 15; this.layoutSettingsButton.Name = "layoutSettingsButton"; // // edgeInsertButton // this.edgeInsertButton.ImageIndex = 16; this.edgeInsertButton.Name = "edgeInsertButton"; this.edgeInsertButton.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton; this.edgeInsertButton.ToolTipText = "Edge insertion"; // // GViewer // this.AutoScroll = true; this.Controls.Add(this.toolbar); this.Name = "GViewer"; this.Size = new System.Drawing.Size(624, 578); this.ResumeLayout(false); this.PerformLayout(); } #endregion internal EntityFilterDelegate EntityFilterDelegate { get; set; } /// <summary> /// /// </summary> public double CurrentScale { get { return Transform[0,0]; } } /// <summary> /// support for mouse selection /// </summary> public bool BuildHitTree { get { return buildHitTree; } set { buildHitTree = value; } } internal DGraph DGraph { get { return dGraph; } set { dGraph = value; } } internal Graph OriginalGraph { get { return originalGraph; } set { originalGraph = value; //this.nodeDragger = new DrawingNodeDragger(originalGraph); } } /// <summary> /// If set to false no layout is calculated. It is presumed that the layout is precalculated. /// </summary> public bool NeedToCalculateLayout { get { return needToCalculateLayout; } set { needToCalculateLayout = value; } } internal BBNode BbNode { get { if (bBNode == null) { DGraph.BuildBBHierarchy(); bBNode = DGraph.BbNode; } return bBNode; } set { bBNode = value; } } /// <summary> /// the last MSAGL file name used when saving-opening an MSAGL file /// </summary> public string FileName { get { return fileName; } set { fileName = value; } } /// <summary> /// Controls the pan button. /// </summary> public bool PanButtonPressed { get { return panButton.Pushed; } set { panButton.Pushed = value; } } /// <summary> /// Controls the window zoom button. /// </summary> public bool WindowZoomButtonPressed { get { return windowZoomButton.Pushed; } set { windowZoomButton.Pushed = value; } } /// <summary> /// If the mininal side of the zoom window is shorter than the threshold then zoom /// does not take place /// </summary> public double ZoomWindowThreshold { get { return zoomWindowThreshold; } set { zoomWindowThreshold = value; } } /// <summary> /// SelectedObject can be detected if the distance in inches between it and /// the cursor is less than MouseHitDistance /// </summary> public double MouseHitDistance { get { return mouseHitDistance; } set { mouseHitDistance = value; } } /// <summary> /// Returns layouted Microsoft.Msagl.Drawing.Graph /// </summary> public Graph GraphWithLayout { get { return DGraph.DrawingGraph; } } /// <summary> /// /// </summary> public double TightOffsetForRouting { get { return tightOffsetForRouting; } set { tightOffsetForRouting = value; } } /// <summary> /// /// </summary> public double LooseOffsetForRouting { get { return looseOffsetForRouting; } set { looseOffsetForRouting = value; } } /// <summary> /// /// </summary> public double OffsetForRelaxingInRouting { get { return offsetForRelaxingInRouting; } set { offsetForRelaxingInRouting = value; } } #region IViewer Members /// <summary> /// The event raised after changing the graph /// </summary> public event EventHandler GraphChanged; /// <summary> /// maps a point from the screen to the graph surface /// </summary> /// <param name="screenPoint"></param> /// <returns></returns> public Point ScreenToSource(Point screenPoint) { return Transform.Inverse*screenPoint; } /// <summary> /// Setting the Graph property shows the graph in the control /// </summary> /// public Graph Graph { get { return OriginalGraph; } set { DGraph = null; if (value != null) { if (!asyncLayout) { OriginalGraph = value; try { if (NeedToCalculateLayout) { OriginalGraph.GeometryGraph = null; LayoutAndCreateDGraph(); InitiateDrawing(); } else { InitiateDrawing(); DGraph = DGraph.CreateDGraphFromPrecalculatedDrawingGraph(OriginalGraph, this); } } catch (OperationCanceledException) { Graph = null; } } else SetGraphAsync(value); } else { OriginalGraph = null; DrawingPanel.Invalidate(); } if (InsertingEdge) layoutEditor.PrepareForEdgeDragging(); if (GraphChanged != null) GraphChanged(this, null); } } /// <summary> /// returns the object under the cursor /// </summary> public IViewerObject ObjectUnderMouseCursor { get { if (MousePositonWhenSetSelectedObject != MousePosition) UnconditionalHit(null, EntityFilterDelegate); return selectedDObject; } } //Microsoft.Msagl.Drawing.DrawingObject DObjectToDrawingObject(DObject drObj) { // return this.DGraph.drawingObjectsToDObjects[drObj as DrawingObject] as Microsoft.Msagl.Drawing.IDraggableObject; //} /// <summary> /// The radius of a circle around an underlying polyline corner /// </summary> public double UnderlyingPolylineCircleRadius { get { return UnderlyingPolylineRadiusWithNoScale/CurrentScale; } } internal static double UnderlyingPolylineRadiusWithNoScale { get { return dpix*0.05; } } /// <summary> /// Forces redraw of objectToInvalidate /// </summary> /// <param name="objectToInvalidate"></param> public void Invalidate(IViewerObject objectToInvalidate) { var dObject = (DObject) objectToInvalidate; dObject.Invalidate(); ClearBoundingBoxHierarchy(); Core.Geometry.Rectangle box = dObject.RenderedBox; //copying aside he previous rendering box dObject.UpdateRenderedBox(); box.Add(dObject.RenderedBox); //this is now the box to invalidate; to erase the old object and to render the new one panel.Invalidate(MapSourceRectangleToScreenRectangle(box)); } /// <summary> /// return ModifierKeys /// </summary> ModifierKeys IViewer.ModifierKeys { get { switch (ModifierKeys) { case Keys.Control: case Keys.ControlKey: return Drawing.ModifierKeys.Control; case Keys.Shift: case Keys.ShiftKey: return Drawing.ModifierKeys.Shift; case Keys.Alt: return Drawing.ModifierKeys.Alt; default: return Drawing.ModifierKeys.None; } } } /// <summary> /// Maps a screen point to the graph surface point /// </summary> /// <param name="e"></param> /// <returns></returns> public Point ScreenToSource(MsaglMouseEventArgs e) { if (e != null) return ScreenToSource(e.X, e.Y); return new Point(); } /// <summary> /// enumerates over all draggable entities /// </summary> public IEnumerable<IViewerObject> Entities { get { if (DGraph != null) { foreach (IViewerObject obj in DGraph.Entities) yield return obj; } } } /// <summary> /// number of dots per inch horizontally /// </summary> public double DpiX { get { return dpix; } } /// <summary> /// number of dots per inch vertically /// </summary> public double DpiY { get { return dpiy; } } /// <summary> /// /// </summary> event EventHandler<MsaglMouseEventArgs> IViewer.MouseDown { add { iEditViewerMouseDown += value; } remove { iEditViewerMouseDown -= value; } } /// <summary> /// /// </summary> event EventHandler<MsaglMouseEventArgs> IViewer.MouseMove { add { iEditViewerMouseMove += value; } remove { iEditViewerMouseMove -= value; } } event EventHandler<MsaglMouseEventArgs> IViewer.MouseUp { add { iEditViewerMouseUp += value; } remove { iEditViewerMouseUp -= value; } } /// <summary> /// A method of IEditViewer /// </summary> /// <param name="changedObjects"></param> public void OnDragEnd(IEnumerable<IViewerObject> changedObjects) { DGraph.UpdateBBoxHierarchy(changedObjects); } void IViewer.Invalidate() { panel.Invalidate(); } /// <summary> /// The scale dependent width of an edited curve that should be clearly visible. /// Used in the default entity editing. /// </summary> public double LineThicknessForEditing { get { return DpiX*VisibleWidth/CurrentScale; } } /// <summary> /// Pops up a pop up menu with a menu item for each couple, the string is the title and the delegate is the callback /// </summary> /// <param name="menuItems"></param> public void PopupMenus(params Tuple<string, VoidDelegate>[] menuItems) { var contextMenu = new ContextMenu(); foreach (var menuItem in menuItems) contextMenu.MenuItems.Add(CreateMenuItem(menuItem.Item1, menuItem.Item2)); contextMenu.Show(this, PointToClient(MousePosition)); } /// <summary> /// adding a node to the graph with the undo support /// The node boundary curve should have (0,0) as its internal point. /// The curve will be moved the the node center. /// </summary> /// <param name="node"></param> /// <param name="registerForUndo"></param> public void AddNode(IViewerNode node, bool registerForUndo) { var dNode = node as DNode; DrawingNode drawingNode = dNode.DrawingNode; var viewer = this as IViewer; DGraph.AddNode(dNode); Graph.AddNode(drawingNode); Graph.GeometryGraph.Nodes.Add(drawingNode.GeometryNode); foreach (DEdge e in dNode.outEdges) { e.Target.inEdges.Add(e); e.Target.DrawingNode.AddInEdge(e.DrawingEdge); e.Target.DrawingNode.GeometryNode.AddInEdge(e.DrawingEdge.GeometryEdge); } foreach (DEdge e in dNode.inEdges) { e.Source.outEdges.Add(e); e.Source.DrawingNode.AddOutEdge(e.DrawingEdge); e.Source.DrawingNode.GeometryNode.AddOutEdge(e.DrawingEdge.GeometryEdge); } viewer.Invalidate(node); foreach (DEdge e in Edges(dNode)) { DGraph.Edges.Add(e); Graph.AddPrecalculatedEdge(e.DrawingEdge); Graph.GeometryGraph.Edges.Add(e.DrawingEdge.GeometryEdge); viewer.Invalidate(e); } if (registerForUndo) { layoutEditor.RegisterNodeAdditionForUndo(node); Core.Geometry.Rectangle bounds = Graph.GeometryGraph.BoundingBox; bounds.Add(drawingNode.BoundingBox.LeftTop); bounds.Add(drawingNode.BoundingBox.RightBottom); Graph.GeometryGraph.BoundingBox = bounds; layoutEditor.CurrentUndoAction.GraphBoundingBoxAfter = Graph.BoundingBox; } BbNode = null; viewer.Invalidate(); } ///// <summary> ///// ///// </summary> ///// <param name="source"></param> ///// <param name="target"></param> ///// <param name="registerForUndo"></param> ///// <returns></returns> public Drawing.Edge AddEdge(Drawing.Node source, Drawing.Node target, bool registerForUndo) { Debug.Assert(Graph.FindNode(source.Id) == source); Debug.Assert(Graph.FindNode(target.Id) == target); Drawing.Edge drawingEdge = Graph.AddEdge(source.Id, target.Id); drawingEdge.Label = new Label(); var geometryEdge = drawingEdge.GeometryEdge = new Microsoft.Msagl.Core.Layout.Edge(); geometryEdge.GeometryParent = this.Graph.GeometryGraph; var a = source.GeometryNode.Center; var b = target.GeometryNode.Center; if (source == target) { Site start = new Site(a); Site end = new Site(b); var mid1 = source.GeometryNode.Center; mid1.X += (source.GeometryNode.BoundingBox.Width / 3 * 2); var mid2 = mid1; mid1.Y -= source.GeometryNode.BoundingBox.Height / 2; mid2.Y += source.GeometryNode.BoundingBox.Height / 2; Site mid1s = new Site(mid1); Site mid2s = new Site(mid2); start.Next = mid1s; mid1s.Previous = start; mid1s.Next = mid2s; mid2s.Previous = mid1s; mid2s.Next = end; end.Previous = mid2s; geometryEdge.UnderlyingPolyline = new SmoothedPolyline(start); geometryEdge.Curve = geometryEdge.UnderlyingPolyline.CreateCurve(); } else { Site start = new Site(a); Site end = new Site(b); Site mids = new Site(a * 0.5 + b * 0.5); start.Next = mids; mids.Previous = start; mids.Next = end; end.Previous = mids; geometryEdge.UnderlyingPolyline = new SmoothedPolyline(start); geometryEdge.Curve = geometryEdge.UnderlyingPolyline.CreateCurve(); } geometryEdge.Source = drawingEdge.SourceNode.GeometryNode; geometryEdge.Target = drawingEdge.TargetNode.GeometryNode; geometryEdge.EdgeGeometry.TargetArrowhead = new Arrowhead(){Length = drawingEdge.Attr.ArrowheadLength}; Arrowheads.TrimSplineAndCalculateArrowheads(geometryEdge, geometryEdge.Curve, true,true); IViewerEdge ve; AddEdge(ve=CreateEdgeWithGivenGeometry(drawingEdge), registerForUndo); layoutEditor.AttachLayoutChangeEvent(ve); return drawingEdge; } /// <summary> /// /// </summary> /// <param name="edge"></param> /// <param name="registerForUndo"></param> public void AddEdge(IViewerEdge edge, bool registerForUndo) { if (registerForUndo) layoutEditor.RegisterEdgeAdditionForUndo(edge); var dEdge = edge as DEdge; var drawingEdge = edge.DrawingObject as DrawingEdge; Edge geomEdge = drawingEdge.GeometryEdge; //the edge has to be disconnected from the graph Debug.Assert(DGraph.Edges.Contains(dEdge) == false); //Debug.Assert(Graph.Edges.Contains(drawingEdge) == false); Debug.Assert(Graph.GeometryGraph.Edges.Contains(geomEdge) == false); DGraph.Edges.Add(dEdge); Graph.AddPrecalculatedEdge(drawingEdge); Graph.GeometryGraph.Edges.Add(geomEdge); Core.Geometry.Rectangle bounds = Graph.GeometryGraph.BoundingBox; bounds.Add(drawingEdge.GeometryEdge.Curve.BoundingBox.LeftTop); bounds.Add(drawingEdge.GeometryEdge.Curve.BoundingBox.RightBottom); Graph.GeometryGraph.BoundingBox = bounds; if (registerForUndo) layoutEditor.CurrentUndoAction.GraphBoundingBoxAfter = Graph.BoundingBox; BbNode = null; var source = edge.Source as DNode; var target = edge.Target as DNode; //the edge has to be disconnected from the graph Debug.Assert(source.outEdges.Contains(dEdge) == false); Debug.Assert(target.inEdges.Contains(dEdge) == false); Debug.Assert(source.selfEdges.Contains(dEdge) == false); if (source != target) { source.AddOutEdge(dEdge); target.AddInEdge(dEdge); source.DrawingNode.AddOutEdge(drawingEdge); target.DrawingNode.AddInEdge(drawingEdge); source.DrawingNode.GeometryNode.AddOutEdge(geomEdge); target.DrawingNode.GeometryNode.AddInEdge(geomEdge); } else { source.AddSelfEdge(dEdge); source.DrawingNode.AddSelfEdge(drawingEdge); source.DrawingNode.GeometryNode.AddSelfEdge(geomEdge); } DGraph.BbNode = null; DGraph.BuildBBHierarchy(); Invalidate(); if (EdgeAdded != null) EdgeAdded(dEdge.DrawingEdge, new EventArgs()); } /// <summary> /// removes a node from the graph with the undo support /// </summary> /// <param name="node"></param> /// <param name="registerForUndo"></param> public void RemoveNode(IViewerNode node, bool registerForUndo) { if (registerForUndo) layoutEditor.RegisterNodeForRemoval(node); RemoveNodeFromAllGraphs(node); BbNode = null; DGraph.BbNode = null; DGraph.BuildBBHierarchy(); Invalidate(); } /// <summary> /// removes an edge from the graph with the undo support /// </summary> /// <param name="edge"></param> /// <param name="registerForUndo"></param> public void RemoveEdge(IViewerEdge edge, bool registerForUndo) { var de = edge as DEdge; if (registerForUndo) layoutEditor.RegisterEdgeRemovalForUndo(edge); Graph.RemoveEdge(de.DrawingEdge); DGraph.Edges.Remove(de); if (de.Source != de.Target) { de.Source.RemoveOutEdge(de); de.Target.RemoveInEdge(de); } else de.Source.RemoveSelfEdge(de); BbNode = null; DGraph.BbNode = null; DGraph.BuildBBHierarchy(); Invalidate(); if (EdgeRemoved != null) EdgeRemoved(de.DrawingEdge, EventArgs.Empty); } /// <summary> /// /// </summary> /// <param name="startingPoint"></param> public void StartDrawingRubberLine(Point startingPoint) { panel.MarkTheStartOfRubberLine(startingPoint); } /// <summary> /// /// </summary> /// <param name="args"></param> public void DrawRubberLine(MsaglMouseEventArgs args) { panel.DrawRubberLine(args); } /// <summary> /// /// </summary> /// <param name="point"></param> public void DrawRubberLine(Point point) { panel.DrawRubberLine(point); } /// <summary> /// /// </summary> public void StopDrawingRubberLine() { panel.StopDrawRubberLine(); } /// <summary> /// routes an edge and returns the corresponding edge of the viewer /// </summary> /// <returns></returns> public IViewerEdge RouteEdge(DrawingEdge drawingEdge) { drawingEdge.Label = new Label(); Edge geometryEdge = drawingEdge.GeometryEdge = new Edge(); if (drawingEdge.Attr.ArrowheadAtSource != ArrowStyle.NonSpecified && drawingEdge.Attr.ArrowheadAtSource != ArrowStyle.None) geometryEdge.EdgeGeometry.SourceArrowhead = new Arrowhead {Length = drawingEdge.Attr.ArrowheadLength}; if (drawingEdge.Attr.ArrowheadAtSource != ArrowStyle.None) geometryEdge.EdgeGeometry.TargetArrowhead = new Arrowhead {Length = drawingEdge.Attr.ArrowheadLength}; geometryEdge.GeometryParent = Graph.GeometryGraph; geometryEdge.Source = drawingEdge.SourceNode.GeometryNode; geometryEdge.Target = drawingEdge.TargetNode.GeometryNode; geometryEdge.SourcePort = drawingEdge.SourcePort; geometryEdge.TargetPort = drawingEdge.TargetPort; LayoutHelpers.RouteAndLabelEdges(this.Graph.GeometryGraph, Graph.LayoutAlgorithmSettings, new[] {geometryEdge}); var dEdge = new DEdge(DGraph.FindDNode(drawingEdge.SourceNode.Id), DGraph.FindDNode(drawingEdge.TargetNode.Id), drawingEdge, ConnectionToGraph.Disconnected, this); dEdge.Label = new DLabel(dEdge, new Label(), this); return dEdge; } /// <summary> /// gets the visual graph /// </summary> public IViewerGraph ViewerGraph { get { return DGraph; } } /// <summary> /// creates a viewer node /// </summary> /// <param name="drawingNode"></param> /// <returns></returns> public IViewerNode CreateIViewerNode(DrawingNode drawingNode) { return DGraph.CreateDNodeAndSetNodeBoundaryCurve(Graph, DGraph, drawingNode.GeometryNode, drawingNode, this); } /// <summary> /// /// </summary> /// <param name="drawingNode"></param> /// <param name="center"></param> /// <param name="visualElement">does not play any role here</param> /// <returns></returns> public IViewerNode CreateIViewerNode(DrawingNode drawingNode, Point center, object visualElement) { CreateNodeGeometry(drawingNode,center); return CreateIViewerNode(drawingNode); } void CreateNodeGeometry(DrawingNode node, Point center) { double width, height; StringMeasure.MeasureWithFont(node.Label.Text, new Font(node.Label.FontName, (float)node.Label.FontSize, (System.Drawing.FontStyle)(int)node.Label.FontStyle), out width, out height); if (node.Label != null) { width += 2 * node.Attr.LabelMargin; height += 2 * node.Attr.LabelMargin; } if (width < Graph.Attr.MinNodeWidth) width = Graph.Attr.MinNodeWidth; if (height < Graph.Attr.MinNodeHeight) height = Graph.Attr.MinNodeHeight; Node geomNode = node.GeometryNode = GeometryGraphCreator.CreateGeometryNode(Graph, Graph.GeometryGraph, node, ConnectionToGraph.Disconnected); geomNode.BoundaryCurve = NodeBoundaryCurves.GetNodeBoundaryCurve(node, width, height); geomNode.BoundaryCurve.Translate(center); geomNode.Center = center; } /// <summary> /// sets the edge label /// </summary> /// <param name="edge"></param> /// <param name="label"></param> public void SetEdgeLabel(DrawingEdge edge, Label label) { //find the edge first DEdge de = null; foreach (DEdge dEdge in DGraph.Edges) if (dEdge.DrawingEdge == edge) { de = dEdge; break; } Debug.Assert(de != null); edge.Label = label; double w, h; DGraph.CreateDLabel(de, label, out w, out h, this); edge.GeometryEdge.Label = label.GeometryLabel; ICurve curve = edge.GeometryEdge.Curve; label.GeometryLabel.Center = curve[(curve.ParStart + curve.ParEnd)/2]; label.GeometryLabel.GeometryParent = edge.GeometryEdge; BbNode = DGraph.BbNode = null; Invalidate(); } /// <summary> /// the event raised when the object under the mouse cursor changes /// </summary> public event EventHandler<ObjectUnderMouseCursorChangedEventArgs> ObjectUnderMouseCursorChanged; /// <summary> /// the padding used to route a new inserted edge around the nodes /// </summary> public double PaddingForEdgeRouting { get { return Graph == null ? paddingForEdgeRouting : Math.Min(paddingForEdgeRouting, Graph.Attr.NodeSeparation/6); } set { paddingForEdgeRouting = value; } } /// <summary> /// support for edge routing /// </summary> /// <param name="edgeGeometry"></param> public void DrawRubberEdge(EdgeGeometry edgeGeometry) { panel.DrawRubberEdge(edgeGeometry); } /// <summary> /// support for edge routing /// </summary> public void StopDrawingRubberEdge() { panel.StopDrawingRubberEdge(); } /// <summary> /// the current transform to the client viewport /// </summary> public PlaneTransformation Transform { get { if (transformation == null) InitTransform(); return transformation; } set { transformation = value; } } void InitTransform() { if (originalGraph == null) { transformation = PlaneTransformation.UnitTransformation; return; } var scale = GetFitScale(); var sourceCenter = originalGraph.BoundingBox.Center; SetTransformOnScaleAndCenter(scale, sourceCenter); } internal void SetTransformOnScaleAndCenter(double scale, Point sourceCenter) { if (!ScaleIsAcceptable(scale)) return; var dx = PanelWidth/2.0 - scale*sourceCenter.X; var dy = PanelHeight/2.0 + scale*sourceCenter.Y; transformation = new PlaneTransformation(scale, 0, dx, 0, -scale, dy); } /// <summary> /// drawing edge already has its geometry in place /// </summary> /// <param name="drawingEdge"></param> /// <returns></returns> public IViewerEdge CreateEdgeWithGivenGeometry(DrawingEdge drawingEdge) { drawingEdge.Label = new Label(); Edge geometryEdge = drawingEdge.GeometryEdge; Debug.Assert(geometryEdge != null); geometryEdge.GeometryParent = Graph.GeometryGraph; var dEdge = new DEdge(DGraph.FindDNode(drawingEdge.SourceNode.Id), DGraph.FindDNode(drawingEdge.TargetNode.Id), drawingEdge, ConnectionToGraph.Disconnected, this); dEdge.Label = new DLabel(dEdge, new Label(), this); return dEdge; } #endregion #region Asynchronous Layout // wrwg: added this for asynchronous layouting // The thread running the layout process Thread layoutThread; // A wait handle for ensuring layouting has started readonly EventWaitHandle layoutWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); PlaneTransformation transformation; /// <summary> /// Whether asynchronous layouting is enabled. Defaults to false. /// </summary> /// <remarks> /// If you set this property to true, setting the <see cref="Graph"/> property /// will work asynchronously by starting a thread which does the layout and /// displaying. The coarse progress of layouting can be observed with /// <see cref="AsyncLayoutProgress"/>, and layouting can be aborted with /// <see cref="AbortAsyncLayout"/>. /// </remarks> public bool AsyncLayout { get { return asyncLayout; } set { asyncLayout = value; } } double HugeDiagonal = 10e6; /// <summary> /// An event which can be subscribed to get notification of layout progress. /// </summary> public event EventHandler<LayoutProgressEventArgs> AsyncLayoutProgress; /// <summary> /// Abort an asynchronous layout activity. /// </summary> public void AbortAsyncLayout() { if (layoutThread != null) { layoutThread.Abort(); layoutThread = null; } } // Is called from Graph setter. void SetGraphAsync(Graph value) { if (layoutThread != null) { layoutThread.Abort(); layoutThread = null; } layoutThread = new Thread( (ThreadStart) delegate { var args = new LayoutProgressEventArgs(LayoutProgress.LayingOut, null); lock (value) { try { bool needToCalc = NeedToCalculateLayout; layoutWaitHandle.Set(); OriginalGraph = value; if (needToCalc) { if (AsyncLayoutProgress != null) AsyncLayoutProgress(this, args); LayoutAndCreateDGraph(); } else { DGraph = DGraph.CreateDGraphFromPrecalculatedDrawingGraph(OriginalGraph, this); } Invoke( (Invoker) delegate { if (AsyncLayoutProgress != null) { args.progress = LayoutProgress.Rendering; AsyncLayoutProgress(this, args); } InitiateDrawing(); if (AsyncLayoutProgress != null) { args.progress = LayoutProgress.Finished; AsyncLayoutProgress(this, args); } }); } catch (ThreadAbortException) { if (AsyncLayoutProgress != null) { args.progress = LayoutProgress.Aborted; AsyncLayoutProgress(this, args); } // rethrown automatically } //catch (Exception e) { // // must not leak through any exception, otherwise appl. terminates // if (AsyncLayoutProgress != null) { // args.progress = LayoutProgress.Aborted; // args.diagnostics = e.ToString(); // AsyncLayoutProgress(this, args); // } //} layoutThread = null; } }); // Before we start the thread, ensure the control is created. // Otherwise Invoke inside of the thread might fail. CreateControl(); layoutThread.Start(); // Wait until the layout thread has started. // If we don't do this, there is a chance that the thread is aborted // before we are in the try-context which catches the AbortException, // and we wouldn't get the abortion notification. layoutWaitHandle.WaitOne(); } delegate void Invoker(); #endregion /// <summary> /// returns false on filtered entities and only on them /// </summary> /// <param name="dObject"></param> /// <returns></returns> static bool EdgeFilter(DObject dObject) { return !(dObject is DEdge); } void UnconditionalHit(MouseEventArgs args, EntityFilterDelegate filter) { System.Drawing.Point point = args != null ? new System.Drawing.Point(args.X, args.Y) : DrawingPanel.PointToClient(MousePosition); object old = selectedDObject; if (bBNode == null && DGraph != null) bBNode = DGraph.BBNode; if (bBNode != null) { var subgraphs=new List<Geometry>(); Geometry geometry = bBNode.Hit(ScreenToSource(point), GetHitSlack(), filter, subgraphs) ?? PickSubgraph(subgraphs, ScreenToSource(point)); selectedDObject = geometry == null ? null : geometry.dObject; if (old == selectedDObject) return; SetSelectedObject(selectedDObject); if (ObjectUnderMouseCursorChanged != null) { var changedArgs = new ObjectUnderMouseCursorChangedEventArgs((IViewerObject) old, selectedDObject); ObjectUnderMouseCursorChanged(this, changedArgs); } } } Geometry PickSubgraph(List<Geometry> subgraphs, Point screenToSource) { if (subgraphs.Count == 0) return null; double area = subgraphs[0].dObject.DrawingObject.BoundingBox.Area; int ret = 0; for (int i = 1; i < subgraphs.Count; i++) { double a = subgraphs[i].dObject.DrawingObject.BoundingBox.Area; if (a < area) { area = a; ret = i; } } return subgraphs[ret]; } /// <summary> /// It should be physically on the screen by one tenth of an inch /// </summary> /// <returns></returns> double GetHitSlack() { double inchSlack = MouseHitDistance; double slackInPoints = Dpi*inchSlack; return slackInPoints/CurrentScale; } void DrawingPanelMouseClick(object sender, MouseEventArgs e) { OnMouseClick(e); } internal static bool ModifierKeyWasPressed() { return ModifierKeys == Keys.Control || ModifierKeys == Keys.Shift; } /// <summary> /// creates the corresponding rectangle on screen /// </summary> /// <param name="rect"></param> /// <returns></returns> public Rectangle MapSourceRectangleToScreenRectangle(Core.Geometry.Rectangle rect) { return CreateScreenRectFromTwoCornersInTheSource(rect.LeftTop, rect.RightBottom); } internal Rectangle CreateScreenRectFromTwoCornersInTheSource(Point leftTop, Point rightBottom) { var pts = new[] {Pf(leftTop), Pf(rightBottom)}; CurrentTransform().TransformPoints(pts); return Rectangle.FromLTRB( (int) Math.Floor(pts[0].X - 1), (int) Math.Floor(pts[0].Y) - 1, (int) Math.Ceiling(pts[1].X) + 1, (int) Math.Ceiling(pts[1].Y) + 1); } internal static PointF Pf(Point p2) { return new PointF((float) p2.X, (float) p2.Y); } /// <summary> /// Maps a point from the screen to the graph surface /// </summary> /// <param name="point"></param> /// <returns></returns> public Point ScreenToSource(System.Drawing.Point point) { Matrix m = CurrentTransform(); if (!m.IsInvertible) return new Point(0, 0); m.Invert(); var pf = new[] {new PointF(point.X, point.Y)}; m.TransformPoints(pf); return new Point(pf[0].X, pf[0].Y); } internal Point ScreenToSource(int x, int y) { return ScreenToSource(new System.Drawing.Point(x, y)); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } if (ToolTip != null) { ToolTip.RemoveAll(); ToolTip.Dispose(); ToolTip = null; } if (layoutWaitHandle != null) layoutWaitHandle.Close(); if (panGrabCursor != null) panGrabCursor.Dispose(); if (panOpenCursor != null) panOpenCursor.Dispose(); } base.Dispose(disposing); } ViewInfo CurrentViewInfo() { var viewInfo = new ViewInfo { Transformation = Transform.Clone(), leftMouseButtonWasPressed = MouseButtons == MouseButtons.Left, }; return viewInfo; } void HandleViewInfoList() { if (storeViewInfo) { ViewInfo currentViewInfo = CurrentViewInfo(); listOfViewInfos.AddNewViewInfo(currentViewInfo); } else storeViewInfo = true; BackwardEnabled = listOfViewInfos.BackwardAvailable; ForwardEnabled = listOfViewInfos.ForwardAvailable; } internal void ProcessOnPaint(Graphics g, PrintPageEventArgs printPageEvenArgs) { if (PanelHeight < minimalSizeToDraw || PanelWidth < minimalSizeToDraw || DGraph == null) return; if (wasMinimized) { wasMinimized = false; panel.Invalidate(); } if (OriginalGraph != null) { CalcRects(printPageEvenArgs); HandleViewInfoList(); if (printPageEvenArgs == null) { g.FillRectangle(outsideAreaBrush, ClientRectangle); g.FillRectangle(new SolidBrush(Draw.MsaglColorToDrawingColor(OriginalGraph.Attr.BackgroundColor)), destRect); } using (Matrix m = CurrentTransform()) { if (!m.IsInvertible) // just to make sure that the transform is legal return; g.Transform = m; g.Clip = new Region(SrcRect); if (DGraph == null) return; double scale = CurrentScale; foreach (IViewerObject viewerObject in Entities) ((DObject)viewerObject).UpdateRenderedBox(); DGraph.DrawGraph(g); //some info is known only after the first drawing if (bBNode == null && BuildHitTree #if TEST_MSAGL && ( dGraph.DrawingGraph.DebugICurves == null ) #endif ) { DGraph.BuildBBHierarchy(); bBNode = DGraph.BbNode; } } } else g.FillRectangle(Brushes.Gray, ClientRectangle); //g.Transform.Reset(); } internal Matrix CurrentTransform() { return new Matrix((float)Transform[0, 0], (float)Transform[0, 1], (float)Transform[1, 0], (float)Transform[1, 1], (float)Transform[0, 2], (float)Transform[1, 2]); } internal static Rectangle RectFromPoints(System.Drawing.Point p1, System.Drawing.Point p2) { return new Rectangle(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y), Math.Abs(p1.X - p2.X), Math.Abs(p1.Y - p2.Y)); } /// <summary> /// /// </summary> /// <param name="cx"></param> /// <param name="cy"></param> /// <param name="val"></param> [SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions"), SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.MessageBox.Show(System.String)")] internal void Zoom(double cx, double cy, double val) { ZoomF = val; panel.Invalidate(); } void InitiateDrawing() { transformation = null; CalcRects(null); bBNode = null; //to initiate new calculation panel.Invalidate(); } [SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")] void LayoutAndCreateDGraph() { switch (CurrentLayoutMethod) { case LayoutMethod.SugiyamaScheme: if (!(OriginalGraph.LayoutAlgorithmSettings is SugiyamaLayoutSettings)) OriginalGraph.LayoutAlgorithmSettings = sugiyamaSettings; break; case LayoutMethod.MDS: if (!(OriginalGraph.LayoutAlgorithmSettings is MdsLayoutSettings)) OriginalGraph.LayoutAlgorithmSettings = mdsLayoutSettings; break; case LayoutMethod.Ranking: if (!(OriginalGraph.LayoutAlgorithmSettings is RankingLayoutSettings)) OriginalGraph.LayoutAlgorithmSettings = rankingSettings; break; case LayoutMethod.IcrementalLayout: if (!(OriginalGraph.LayoutAlgorithmSettings is FastIncrementalLayoutSettings)) OriginalGraph.LayoutAlgorithmSettings = fastIncrementalLayoutSettings; break; } var localSugiyamaSettings = OriginalGraph.LayoutAlgorithmSettings as SugiyamaLayoutSettings; if (localSugiyamaSettings != null) { // Insert hard coded constraints for tests #if DEBUG TestSomeGraphs(); #endif } OriginalGraph.CreateGeometryGraph(); GeometryGraph geometryGraph = OriginalGraph.GeometryGraph; DGraph = DGraph.CreateDGraphAndGeometryInfo(OriginalGraph, geometryGraph, this); try { LayoutHelpers.CalculateLayout(geometryGraph, originalGraph.LayoutAlgorithmSettings, null); } catch (OperationCanceledException) { originalGraph = null; DGraph = null; } TransferGeometryFromMsaglGraphToGraph(geometryGraph); if (GraphChanged != null) { GraphChanged(this, null); } } #if DEBUG void TestSomeGraphs() { if (fileName.EndsWith("lovett.dot")) { OriginalGraph.LayerConstraints.AddUpDownVerticalConstraint(OriginalGraph.FindNode("Logica"), OriginalGraph.FindNode("IBM")); OriginalGraph.LayerConstraints.AddUpDownVerticalConstraint(OriginalGraph.FindNode("IBM"), OriginalGraph.FindNode("Taligent")); OriginalGraph.LayerConstraints.AddUpDownVerticalConstraint(OriginalGraph.FindNode("Taligent"), OriginalGraph.FindNode("Walkabout")); OriginalGraph.LayerConstraints.AddUpDownVerticalConstraint(OriginalGraph.FindNode("Walkabout"), OriginalGraph.FindNode("Microsoft")); OriginalGraph.LayerConstraints.AddSameLayerNeighbors(OriginalGraph.FindNode("MSXML"), OriginalGraph.FindNode("sysxml"), OriginalGraph.FindNode("xsharp"), OriginalGraph.FindNode("xmled"), OriginalGraph.FindNode("Progression")); } else if (fileName.EndsWith("dependenciesForTaskCrashTest.dot")) { OriginalGraph.LayerConstraints.PinNodesToSameLayer( OriginalGraph.FindNode("C1"), OriginalGraph.FindNode("C2"), OriginalGraph.FindNode("C3"), OriginalGraph.FindNode("C4"), OriginalGraph.FindNode("C5"), OriginalGraph.FindNode("C6"), OriginalGraph.FindNode("C7"), OriginalGraph.FindNode("C8"), OriginalGraph.FindNode("C9"), OriginalGraph.FindNode("C10")); OriginalGraph.LayerConstraints.PinNodesToSameLayer( OriginalGraph.FindNode("R1"), OriginalGraph.FindNode("R2"), OriginalGraph.FindNode("R3"), OriginalGraph.FindNode("R4"), OriginalGraph.FindNode("R5"), OriginalGraph.FindNode("R6"), OriginalGraph.FindNode("R7"), OriginalGraph.FindNode("R8"), OriginalGraph.FindNode("R9"), OriginalGraph.FindNode("R10")); } else if (fileName.EndsWith("andrei.dot")) { OriginalGraph.LayerConstraints.AddUpDownVerticalConstraint(OriginalGraph.FindNode("open"), OriginalGraph.FindNode("bezier")); OriginalGraph.LayerConstraints.AddUpDownVerticalConstraint(OriginalGraph.FindNode("closed"), OriginalGraph.FindNode("ellipse")); } } #endif /// <summary> /// /// </summary> public void ClearBoundingBoxHierarchy() { bBNode = null; } /// <summary> /// Brings in to the view the object of the group /// </summary> /// <param name="graphElements"></param> public void ShowGroup(object[] graphElements) { Core.Geometry.Rectangle bb = BBoxOfObjs(graphElements); ShowBBox(bb); } /// <summary> /// Changes the view in a way that the group is at the center /// </summary> /// <param name="graphElements"></param> public void CenterToGroup(params object[] graphElements) { Core.Geometry.Rectangle bb = BBoxOfObjs(graphElements); if (!bb.IsEmpty) { CenterToPoint(0.5f * (bb.LeftTop + bb.RightBottom)); } } static Core.Geometry.Rectangle BBoxOfObjs(IEnumerable<object> objs) { var bb = new Core.Geometry.Rectangle(0, 0, 0, 0); bool boxIsEmpty = true; foreach (object o in objs) { var node = o as DrawingNode; Core.Geometry.Rectangle objectBb; if (node != null) objectBb = node.BoundingBox; else { var edge = o as DrawingEdge; if (edge != null) objectBb = edge.BoundingBox; else continue; } if (boxIsEmpty) { bb = objectBb; boxIsEmpty = false; } else bb.Add(objectBb); } return bb; } /// <summary> /// Make the bounding rect fully visible /// </summary> /// <param name="bb"></param> public void ShowBBox(Core.Geometry.Rectangle bb) { if (bb.IsEmpty == false) { double sc = Math.Min(OriginalGraph.Width/bb.Width, OriginalGraph.Height/bb.Height); Point center = 0.5*(bb.LeftTop + bb.RightBottom); SetTransformOnScaleAndCenter(sc, center); panel.Invalidate(); } } /// <summary> /// Pans the view by vector (x,y) /// </summary> /// <param name="x"></param> /// <param name="y"></param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "y"), SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x")] public void Pan(double x, double y) { Transform[0, 2] += x; Transform[1, 2] += y; panel.Invalidate(); } /// <summary> /// Pans the view by vector point /// </summary> /// <param name="point"></param> public void Pan(Point point) { Pan(point.X, point.Y); } /// <summary> /// Centers the view to the point p /// </summary> /// <param name="point"></param> public void CenterToPoint(Point point) { SetTransformOnScaleAndCenter(CurrentScale, point); panel.Invalidate(); } /// <summary> /// Finds the object under point (x,y) where x,y are given in the window coordinates /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "y"), SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x")] public object GetObjectAt(int x, int y) { BBNode bn = BbNode; if (bn == null) return null; List<Geometry> subgraphs=new List<Geometry>(); Geometry g = bn.Hit(ScreenToSource(new System.Drawing.Point(x, y)), GetHitSlack(), EntityFilterDelegate, subgraphs) ?? PickSubgraph(subgraphs, ScreenToSource(new System.Drawing.Point(x, y))); return g == null ? null : g.dObject; } /// <summary> /// Finds the object under point p where p is given in the window coordinates /// </summary> /// <param name="point"></param> /// <returns></returns> public object GetObjectAt(System.Drawing.Point point) { return GetObjectAt(point.X, point.Y); } internal bool ScaleIsAcceptable(double scale) { var d = OriginalGraph != null ? OriginalGraph.BoundingBox.Diagonal : 0; return !(d * scale < 5) && !(d * scale > HugeDiagonal); } /// <summary> /// Zooms in /// </summary> public void ZoomInPressed() { double zoomFractionLocal = ZoomF * ZoomFactor(); if (!ScaleIsAcceptable(CurrentScale * zoomFractionLocal)) return; ZoomF *= ZoomFactor(); } /// <summary> /// Zooms out /// </summary> public void ZoomOutPressed() { ZoomF /= ZoomFactor(); } double ZoomFactor() { return 1.0f + zoomFraction; } void ToolBarButtonClick(object sender, ToolBarButtonClickEventArgs e) { if (e.Button == zoomin) ZoomInPressed(); else if (e.Button == zoomout) ZoomOutPressed(); else if (e.Button == backwardButton) BackwardButtonPressed(); else if (e.Button == forwardButton) ForwardButtonPressed(); else if (e.Button == saveButton) SaveButtonPressed(); else if (e.Button == print) PrintButtonPressed(); else if (e.Button == openButton) OpenButtonPressed(); else if (e.Button == undoButton) UndoButtonPressed(); else if (e.Button == redoButton) RedoButtonPressed(); else if (e.Button == windowZoomButton) WindowZoomButtonIsPressed(); else if (e.Button == panButton) PanButtonIsPressed(); else if (e.Button == layoutSettingsButton) LayoutSettingsIsClicked(); else if (e.Button == edgeInsertButton) { InsertingEdge = edgeInsertButton.Pushed; if (InsertingEdge) layoutEditor.PrepareForEdgeDragging(); else layoutEditor.ForgetEdgeDragging(); }else if (e.Button == homeZoomButton) { transformation = null; panel.Invalidate(); } } void LayoutSettingsIsClicked() { var layoutSettingsForm = new LayoutSettingsForm(); var wrapper = new LayoutSettingsWrapper {LayoutSettings = Graph != null ? Graph.LayoutAlgorithmSettings : null}; wrapper.LayoutTypeHasChanged += OnLayoutTypeChange; wrapper.LayoutMethod = CurrentLayoutMethod; switch (CurrentLayoutMethod) { case LayoutMethod.SugiyamaScheme: wrapper.LayoutSettings = sugiyamaSettings; break; case LayoutMethod.MDS: wrapper.LayoutSettings = mdsLayoutSettings; break; case LayoutMethod.Ranking: wrapper.LayoutSettings = rankingSettings; break; case LayoutMethod.IcrementalLayout: wrapper.LayoutSettings = fastIncrementalLayoutSettings; break; } layoutSettingsForm.PropertyGrid.SelectedObject = wrapper; LayoutAlgorithmSettings backup = Graph != null ? Graph.LayoutAlgorithmSettings.Clone() : null; if (layoutSettingsForm.ShowDialog() == DialogResult.OK) { if (Graph != null) { LayoutAlgorithmSettings settings = Graph.LayoutAlgorithmSettings; if (settings.EdgeRoutingSettings.EdgeRoutingMode == EdgeRoutingMode.SplineBundling) { if (settings.EdgeRoutingSettings.BundlingSettings == null) settings.EdgeRoutingSettings.BundlingSettings = new BundlingSettings(); } if (!(settings is SugiyamaLayoutSettings)) //fix wrong settings coming from the Sugiyama if (settings.EdgeRoutingSettings.EdgeRoutingMode == EdgeRoutingMode.SugiyamaSplines) settings.EdgeRoutingSettings.EdgeRoutingMode = EdgeRoutingMode.Spline; if (layoutSettingsForm.Wrapper.RerouteOnly == false) Graph = Graph; //recalculate the layout else { EdgeRoutingSettings ers = settings.EdgeRoutingSettings; if (ers.EdgeRoutingMode == EdgeRoutingMode.SplineBundling) { var br = new SplineRouter(Graph.GeometryGraph, ers.Padding, ers.PolylinePadding, ers.ConeAngle, ers.BundlingSettings); br.Run(); } else { var sp = new SplineRouter(Graph.GeometryGraph, ers.Padding, ers.PolylinePadding, ers.ConeAngle, ers.BundlingSettings); sp.Run(); } foreach (IViewerObject e in Entities.Where(e => e is IViewerEdge)) Invalidate(e); } } } else if (Graph != null) Graph.LayoutAlgorithmSettings = backup; } void OnLayoutTypeChange(object o, EventArgs args) { var wrapper = o as LayoutSettingsWrapper; switch (wrapper.LayoutMethod) { case LayoutMethod.SugiyamaScheme: wrapper.LayoutSettings = sugiyamaSettings; break; case LayoutMethod.MDS: wrapper.LayoutSettings = mdsLayoutSettings; break; case LayoutMethod.Ranking: wrapper.LayoutSettings = rankingSettings; break; case LayoutMethod.IcrementalLayout: wrapper.LayoutSettings = fastIncrementalLayoutSettings; break; case LayoutMethod.UseSettingsOfTheGraph: wrapper.LayoutSettings = Graph != null ? Graph.LayoutAlgorithmSettings : null; break; default: Debug.Assert(false); //cannot be here break; } CurrentLayoutMethod = wrapper.LayoutMethod; if (Graph != null) Graph.LayoutAlgorithmSettings = wrapper.LayoutSettings; } void PanButtonIsPressed() { if (panButton.Pushed) { panButton.ToolTipText = panButtonToolTipText; windowZoomButton.Pushed = false; windowZoomButton.ToolTipText = windowZoomButtonDisabledToolTipText; } else panButton.ToolTipText = panButtonToolTipText; } void WindowZoomButtonIsPressed() { if (windowZoomButton.Pushed) { windowZoomButton.ToolTipText = WindowZoomButtonToolTipText; panButton.Pushed = false; panButton.ToolTipText = PanButtonDisabledToolTipText; } else windowZoomButton.ToolTipText = WindowZoomButtonToolTipText; } void RedoButtonPressed() { if (LayoutEditor != null && LayoutEditor.CanRedo) LayoutEditor.Redo(); } void UndoButtonPressed() { if (LayoutEditor != null && LayoutEditor.CanUndo) LayoutEditor.Undo(); } /// <summary> /// an event raised on graph loading /// </summary> public event EventHandler GraphLoadingEnded; public event EventHandler<HandledEventArgs> CustomOpenButtonPressed; [SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")] void OpenButtonPressed() { HandledEventArgs args = new HandledEventArgs(); CustomOpenButtonPressed?.Invoke(this, args); if (args.Handled) return; var openFileDialog = new OpenFileDialog {RestoreDirectory = true, Filter = "MSAGL Files(*.msagl)|*.msagl"}; try { if (openFileDialog.ShowDialog() == DialogResult.OK) { FileName = openFileDialog.FileName; NeedToCalculateLayout = false; Graph = Graph.Read(openFileDialog.FileName); if (GraphLoadingEnded != null) GraphLoadingEnded(this, null); } } catch (Exception e) { MessageBox.Show(e.Message); } finally { NeedToCalculateLayout = true; } } /// <summary> /// Raises a dialog of saving the drawing image to a file /// </summary> public void SaveButtonPressed() { if (Graph == null) { return; } var contextMenu = new ContextMenu(CreateSaveMenuItems()); contextMenu.Show(this, new System.Drawing.Point(toolbar.Left + 100, toolbar.Bottom), LeftRightAlignment.Right); } [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.MenuItem.#ctor(System.String)")] MenuItem[] CreateSaveMenuItems() { var menuItems = new List<MenuItem>(); MenuItem menuItem; if (SaveAsMsaglEnabled) { menuItems.Add(menuItem = new MenuItem("Save graph")); menuItem.Click += SaveGraphClick; } if (SaveAsImageEnabled) { menuItems.Add(menuItem = new MenuItem("Save in bitmap format")); menuItem.Click += SaveImageClick; } if (SaveInVectorFormatEnabled) { menuItems.Add(menuItem = new MenuItem("Save in vector format")); menuItem.Click += SaveInVectorGraphicsFormatClick; } return menuItems.ToArray(); } void SaveInVectorGraphicsFormatClick(object sender, EventArgs e) { var saveForm = new SaveInVectorFormatForm(this); saveForm.ShowDialog(); } void SaveImageClick(object sender, EventArgs e) { var saveViewForm = new SaveViewAsImageForm(this); saveViewForm.ShowDialog(); } [SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")] void SaveGraphClick(object sender, EventArgs e) { var saveFileDialog = new SaveFileDialog {Filter = "MSAGL Files(*.msagl)|*.msagl"}; try { if (saveFileDialog.ShowDialog() == DialogResult.OK) { FileName = saveFileDialog.FileName; if (GraphSavingStarted != null) GraphSavingStarted(this, null); Graph.Write(saveFileDialog.FileName); if (GraphSavingEnded != null) GraphSavingEnded(this, null); } } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } /// <summary> /// Navigates forward in the view history /// </summary> public void ForwardButtonPressed() { if (listOfViewInfos.ForwardAvailable) if (listOfViewInfos.CurrentView.leftMouseButtonWasPressed) { while (listOfViewInfos.ForwardAvailable) { listOfViewInfos.Forward(); SetViewFromViewInfo(listOfViewInfos.CurrentView); if (listOfViewInfos.CurrentView.leftMouseButtonWasPressed == false) break; } } else { listOfViewInfos.Forward(); SetViewFromViewInfo(listOfViewInfos.CurrentView); /* if(listOfViewInfos.CurrentView.leftMouseButtonWasPressed) { while( listOfViewInfos.ForwardAvailable ) { listOfViewInfos.Forward(); this.SetViewFromViewInfo(listOfViewInfos.CurrentView); if(listOfViewInfos.CurrentView.leftMouseButtonWasPressed==false) break; } } */ } } /// <summary> /// Navigates backward in the view history /// </summary> public void BackwardButtonPressed() { if (listOfViewInfos.BackwardAvailable) if (listOfViewInfos.CurrentView.leftMouseButtonWasPressed) { while (listOfViewInfos.BackwardAvailable) { listOfViewInfos.Backward(); SetViewFromViewInfo(listOfViewInfos.CurrentView); if (listOfViewInfos.CurrentView.leftMouseButtonWasPressed == false) break; } } else { listOfViewInfos.Backward(); SetViewFromViewInfo(listOfViewInfos.CurrentView); } } /// <summary> /// Prints the graph. /// </summary> public void PrintButtonPressed() { var p = new GraphPrinting(this); var pd = new PrintDialog {Document = p}; if (pd.ShowDialog() == DialogResult.OK) p.Print(); } void PanelClick(object sender, EventArgs e) { OnClick(e); } /// <summary> /// Reacts on some pressed keys /// </summary> /// <param name="e"></param> public void OnKey(KeyEventArgs e) { if (e == null) return; if (e.KeyData == (Keys) 262181) { if (backwardButton.Enabled) { BackwardButtonPressed(); } } else if (e.KeyData == (Keys) 262183) //key==Keys.BrowserForward) { if (forwardButton.Enabled) ForwardButtonPressed(); } } void TransferGeometryFromMsaglGraphToGraph(GeometryGraph gleeGraph) { foreach (Edge gleeEdge in gleeGraph.Edges) { var drawingEdge = gleeEdge.UserData as DrawingEdge; drawingEdge.GeometryEdge = gleeEdge; } foreach (Node gleeNode in gleeGraph.Nodes) { DrawingNode drawingNode = (Drawing.Node) gleeNode.UserData; drawingNode.GeometryNode = gleeNode; } } /// <summary> /// calcualates the layout and returns the object ready to be drawn /// </summary> /// <param name="graph"></param> /// <returns></returns> public object CalculateLayout(Graph graph) { OriginalGraph = graph; LayoutAndCreateDGraph(); return DGraph; } /// <summary> /// sets a tool tip /// </summary> /// <param name="toolTip"></param> /// <param name="tip"></param> public void SetToolTip(ToolTip toolTip, string tip) { if (toolTip != null) toolTip.SetToolTip(DrawingPanel, tip); } /// <summary> /// Just uses the passed object to draw the graph. The method expects DGraph as the argument /// </summary> /// <param name="entityContainingLayout"></param> public void SetCalculatedLayout(object entityContainingLayout) { ClearLayoutEditor(); DGraph = entityContainingLayout as DGraph; if (DGraph != null) { OriginalGraph = DGraph.DrawingGraph; if (GraphChanged != null) GraphChanged(this, null); InitiateDrawing(); } } /// <summary> /// maps screen coordinates to viewer coordinates /// </summary> /// <param name="screenX"></param> /// <param name="screenY"></param> /// <param name="viewerX"></param> /// <param name="viewerY"></param> public void ScreenToSource(float screenX, float screenY, out float viewerX, out float viewerY) { Point p = ScreenToSource(new System.Drawing.Point((int) screenX, (int) screenY)); viewerX = (float) p.X; viewerY = (float) p.Y; } /// <summary> /// pans the drawing on deltaX, deltaY in the drawing coords /// </summary> /// <param name="deltaX"></param> /// <param name="deltaY"></param> public void Pan(float deltaX, float deltaY) { Pan(new Point(deltaX, deltaY)); } internal void RaiseMouseMoveEvent(MsaglMouseEventArgs iArgs) { if (iEditViewerMouseMove != null) iEditViewerMouseMove(this, iArgs); } internal void RaiseMouseDownEvent(MsaglMouseEventArgs iArgs) { if (iEditViewerMouseDown != null) iEditViewerMouseDown(this, iArgs); } internal void RaiseMouseUpEvent(MsaglMouseEventArgs iArgs) { if (iEditViewerMouseUp != null) iEditViewerMouseUp(this, iArgs); } /// <summary> /// This event is raised before the file saving /// </summary> public event EventHandler GraphSavingStarted; /// <summary> /// This even is raised after graph saving /// </summary> public event EventHandler GraphSavingEnded; /// <summary> /// Undoes the last edit action /// </summary> public void Undo() { if (LayoutEditor.CanUndo) LayoutEditor.Undo(); } /// <summary> /// redoes the last undo /// </summary> public void Redo() { if (LayoutEditor.CanRedo) LayoutEditor.Redo(); } /// <summary> /// returns true if an undo is available /// </summary> /// <returns></returns> public bool CanUndo() { return LayoutEditor.CanUndo; } /// <summary> /// returns true is a redo is available /// </summary> /// <returns></returns> public bool CanRedo() { return LayoutEditor.CanRedo; } static MenuItem CreateMenuItem(string title, VoidDelegate voidVoidDelegate) { var menuItem = new MenuItem {Text = title}; menuItem.Click += ((sender, e) => voidVoidDelegate()); return menuItem; } static IEnumerable<DEdge> Edges(DNode dNode) { foreach (DEdge de in dNode.OutEdges) yield return de; foreach (DEdge de in dNode.InEdges) yield return de; foreach (DEdge de in dNode.SelfEdges) yield return de; } /// <summary> /// makes the node unreachable /// </summary> /// <param name="node"></param> void RemoveNodeFromAllGraphs(IViewerNode node) { var drawingNode = node.DrawingObject as DrawingNode; DGraph.RemoveDNode(drawingNode.Id); Graph.NodeMap.Remove(drawingNode.Id); if (drawingNode.GeometryNode != null) { Graph.GeometryGraph.Nodes.Remove(drawingNode.GeometryNode); } foreach (DEdge de in Edges(node as DNode)) { DGraph.Edges.Remove(de); Graph.RemoveEdge(de.DrawingEdge); Graph.GeometryGraph.Edges.Remove(de.DrawingEdge.GeometryEdge); } foreach (DEdge de in node.OutEdges) { de.Target.inEdges.Remove(de); de.Target.DrawingNode.RemoveInEdge(de.DrawingEdge); de.Target.DrawingNode.GeometryNode.RemoveInEdge(de.DrawingEdge.GeometryEdge); } foreach (DEdge de in node.InEdges) { de.Source.outEdges.Remove(de); de.Source.DrawingNode.RemoveOutEdge(de.DrawingEdge); de.Source.DrawingNode.GeometryNode.RemoveOutEdge(de.DrawingEdge.GeometryEdge); } } /// <summary> /// Sets the size of the node to something appropriate to the label it has to display. /// </summary> /// <param name="node">The node to be resized</param> public void ResizeNodeToLabel(DrawingNode node) { double width = 0; double height = 0; string label = node.Label.Text; if (String.IsNullOrEmpty(label) == false) { var f = new Font(node.Label.FontName, (int)node.Label.FontSize, (System.Drawing.FontStyle)(int)node.Label.FontStyle); StringMeasure.MeasureWithFont(label, f, out width, out height); } node.Label.Size = new Size((float) width, (float) height); width += 2*node.Attr.LabelMargin; height += 2*node.Attr.LabelMargin; if (width < Graph.Attr.MinNodeWidth) width = Graph.Attr.MinNodeWidth; if (height < Graph.Attr.MinNodeHeight) height = Graph.Attr.MinNodeHeight; Point originalCenter = node.GeometryNode.Center; node.GeometryNode.BoundaryCurve = NodeBoundaryCurves.GetNodeBoundaryCurve(node, width, height).Clone(); node.GeometryNode.BoundaryCurve.Translate(originalCenter); LayoutHelpers.IncrementalLayout(Graph.GeometryGraph, node.GeometryNode, Graph.LayoutAlgorithmSettings as SugiyamaLayoutSettings); foreach (IViewerObject en in Entities) Invalidate(en); Invalidate(); } internal void RaisePaintEvent(PaintEventArgs e) { base.OnPaint(e); } /// <summary> /// an event raised when an edge is added /// </summary> public event EventHandler EdgeAdded; /// <summary> /// /// </summary> public event EventHandler EdgeRemoved; void RouteEdge(Edge geometryEdge) { var router = new RouterBetweenTwoNodes(Graph.GeometryGraph, Graph.Attr.NodeSeparation*tightOffsetForRouting, Graph.Attr.NodeSeparation*looseOffsetForRouting, Graph.Attr.NodeSeparation*offsetForRelaxingInRouting); router.RouteEdge(geometryEdge, true); } // ReSharper disable InconsistentNaming event MouseEventHandler mouseMove; // ReSharper restore InconsistentNaming /// <summary> /// /// </summary> public new event MouseEventHandler MouseMove { add { mouseMove += value; } remove { mouseMove -= value; } } internal void RaiseRegularMouseMove(MouseEventArgs args) { if (mouseMove != null) mouseMove(this, args); } double GetFitScale() { return OriginalGraph == null ? 1 : Math.Min(panel.Width/originalGraph.Width, panel.Height/originalGraph.Height); } } #if DEBUGLOG internal class Lo { static StreamWriter sw = null; static internal void W(string s) { if (sw == null) { sw = new StreamWriter("c:\\gdiviewerlog"); } sw.WriteLine(s); sw.Flush(); } static internal void W(object o) { if (sw == null) { sw = new StreamWriter("c:\\gdiviewerlog"); } sw.WriteLine(o.ToString()); sw.Flush(); } } #endif }
37.985768
181
0.536442
[ "MIT" ]
cgravill/automatic-graph-layout
GraphLayout/tools/GraphViewerGDI/GViewer.cs
90,748
C#
using Pulumi; using Kubernetes = Pulumi.Kubernetes; class MyStack : Stack { public MyStack() { var bar = new Kubernetes.Core.v1.Pod("bar", new Kubernetes.Core.v1.PodArgs { ApiVersion = "v1", Kind = "Pod", Metadata = new Kubernetes.Meta.Inputs.ObjectMetaArgs { Namespace = "foo", Name = "bar", }, Spec = new Kubernetes.Core.Inputs.PodSpecArgs { Containers = { new Kubernetes.Core.Inputs.ContainerArgs { Name = "nginx", Image = "nginx:1.14-alpine", Resources = new Kubernetes.Core.Inputs.ResourceRequirementsArgs { Limits = { { "memory", "20Mi" }, { "cpu", "0.2" }, }, }, }, }, }, }); } }
28.275
87
0.354553
[ "Apache-2.0" ]
marcusturewicz/pulumi
pkg/codegen/internal/test/testdata/kubernetes-pod.pp.cs
1,131
C#
using System; using System.Runtime.InteropServices; using LowLevelDesign.Win32.NUMA; using VsChromium.Core.Win32.Interop; namespace LowLevelDesign.Win32.Jobs { public enum JOBOBJECTINFOCLASS { JobObjectAssociateCompletionPortInformation = 7, JobObjectBasicLimitInformation = 2, JobObjectBasicUIRestrictions = 4, JobObjectEndOfJobTimeInformation = 6, JobObjectExtendedLimitInformation = 9, JobObjectGroupInformation = 11, JobObjectGroupInformationEx = 14, JobObjectCpuRateControlInformation = 15 } public class JobMsgInfoMessages { public const uint JOB_OBJECT_MSG_END_OF_JOB_TIME = 1; public const uint JOB_OBJECT_MSG_END_OF_PROCESS_TIME = 2; public const uint JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT = 3; public const uint JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO = 4; public const uint JOB_OBJECT_MSG_NEW_PROCESS = 6; public const uint JOB_OBJECT_MSG_EXIT_PROCESS = 7; public const uint JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS = 8; public const uint JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT = 9; public const uint JOB_OBJECT_MSG_JOB_MEMORY_LIMIT = 10; } [StructLayout(LayoutKind.Sequential)] public struct JOBOBJECT_ASSOCIATE_COMPLETION_PORT { public IntPtr CompletionKey; public IntPtr CompletionPort; } [Flags] public enum JobInformationLimitFlags { JOB_OBJECT_LIMIT_ACTIVE_PROCESS = 0x00000008, JOB_OBJECT_LIMIT_AFFINITY = 0x00000010, JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800, JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION = 0x00000400, JOB_OBJECT_LIMIT_JOB_MEMORY = 0x00000200, JOB_OBJECT_LIMIT_JOB_TIME = 0x00000004, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000, JOB_OBJECT_LIMIT_PRESERVE_JOB_TIME = 0x00000040, JOB_OBJECT_LIMIT_PRIORITY_CLASS = 0x00000020, JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x00000100, JOB_OBJECT_LIMIT_PROCESS_TIME = 0x00000002, JOB_OBJECT_LIMIT_SCHEDULING_CLASS = 0x00000080, JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK = 0x00001000, JOB_OBJECT_LIMIT_WORKINGSET = 0x00000001 } [StructLayout(LayoutKind.Sequential)] public struct JOBOBJECT_BASIC_LIMIT_INFORMATION { public Int64 PerProcessUserTimeLimit; public Int64 PerJobUserTimeLimit; public JobInformationLimitFlags LimitFlags; public UIntPtr MinimumWorkingSetSize; public UIntPtr MaximumWorkingSetSize; public UInt32 ActiveProcessLimit; public UInt64 Affinity; public UInt32 PriorityClass; public UInt32 SchedulingClass; } public struct IO_COUNTERS { public UInt64 ReadOperationCount; public UInt64 WriteOperationCount; public UInt64 OtherOperationCount; public UInt64 ReadTransferCount; public UInt64 WriteTransferCount; public UInt64 OtherTransferCount; } [StructLayout(LayoutKind.Sequential)] public struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION { public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; public IO_COUNTERS IoInfo; public UIntPtr ProcessMemoryLimit; public UIntPtr JobMemoryLimit; public UIntPtr PeakProcessMemoryUsed; public UIntPtr PeakJobMemoryUsed; } [Flags] public enum JOBOBJECT_CPU_RATE_CONTROL_FLAGS : uint { JOB_OBJECT_CPU_RATE_CONTROL_ENABLE = 0x1, JOB_OBJECT_CPU_RATE_CONTROL_WEIGHT_BASED = 0x2, JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP = 0x4, JOB_OBJECT_CPU_RATE_CONTROL_NOTIFY = 0x8, JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE = 0x10, } [StructLayout(LayoutKind.Explicit)] public struct JOBOBJECT_CPU_RATE_CONTROL_INFORMATION { [FieldOffset(0)] public JOBOBJECT_CPU_RATE_CONTROL_FLAGS ControlFlags; [FieldOffset(4)] public uint CpuRate; [FieldOffset(4)] public uint Weight; [FieldOffset(4)] public ushort MinRate; [FieldOffset(6)] public ushort MaxRate; } internal static class NativeMethods { [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr CreateJobObject([In]SecurityAttributes lpJobAttributes, string lpName); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool TerminateJobObject(IntPtr hJob, uint uExitCode); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetInformationJobObject(IntPtr hJob, JOBOBJECTINFOCLASS JobObjectInfoClass, ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION lpJobObjectInfo, uint cbJobObjectInfoLength); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetInformationJobObject(IntPtr hJob, JOBOBJECTINFOCLASS JobObjectInfoClass, ref JOBOBJECT_ASSOCIATE_COMPLETION_PORT lpJobObjectInfo, uint cbJobObjectInfoLength); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetInformationJobObject(IntPtr hJob, JOBOBJECTINFOCLASS JobObjectInfoClass, ref GROUP_AFFINITY lpJobObjectInfo, uint cbJobObjectInfoLength); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetInformationJobObject(IntPtr hJob, JOBOBJECTINFOCLASS JobObjectInfoClass, ref JOBOBJECT_CPU_RATE_CONTROL_INFORMATION lpJobObjectInfo, uint cbJobObjectInfoLength); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr CreateIoCompletionPort(IntPtr FileHandle, IntPtr ExistingCompletionPort, IntPtr CompletionKey, uint NumberOfConcurrentThreads); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool GetQueuedCompletionStatus(IntPtr CompletionPort, out uint lpNumberOfBytes, out IntPtr lpCompletionKey, out IntPtr lpOverlapped, uint dwMilliseconds); } }
39.839506
109
0.724357
[ "MIT" ]
rowandh/process-governor
ProcessGovernor/Win32/Jobs/NativeMethods.cs
6,454
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace EasyNetQ { /// <summary> /// Collection of precondition methods for qualifying method arguments. /// </summary> internal static class Preconditions { /// <summary> /// Ensures that <paramref name="value"/> is not null. /// </summary> /// <param name="value"> /// The value to check, must not be null. /// </param> /// <param name="name"> /// The name of the parameter the value is taken from, must not be /// blank. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="value"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="name"/> is blank. /// </exception> public static void CheckNotNull<T>(T value, string name) { CheckNotNull(value, name, string.Format("{0} must not be null", name)); } /// <summary> /// Ensures that <paramref name="value"/> is not null. /// </summary> /// <param name="value"> /// The value to check, must not be null. /// </param> /// <param name="name"> /// The name of the parameter the value is taken from, must not be /// blank. /// </param> /// <param name="message"> /// The message to provide to the exception if <paramref name="value"/> /// is null, must not be blank. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="value"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="name"/> or <paramref name="message"/> are /// blank. /// </exception> public static void CheckNotNull<T>(T value, string name, string message) { if (value == null) { CheckNotBlank(name, "name", "name must not be blank"); CheckNotBlank(message, "message", "message must not be blank"); throw new ArgumentNullException(name, message); } } /// <summary> /// Ensures that <paramref name="value"/> is not blank. /// </summary> /// <param name="value"> /// The value to check, must not be blank. /// </param> /// <param name="name"> /// The name of the parameter the value is taken from, must not be /// blank. /// </param> /// <param name="message"> /// The message to provide to the exception if <paramref name="value"/> /// is blank, must not be blank. /// </param> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="value"/>, <paramref name="name"/>, or /// <paramref name="message"/> are blank. /// </exception> public static void CheckNotBlank(string value, string name, string message) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException("name must not be blank", nameof(name)); } if (string.IsNullOrWhiteSpace(message)) { throw new ArgumentException("message must not be blank", nameof(message)); } if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException(message, name); } } /// <summary> /// Ensures that <paramref name="value"/> is not blank. /// </summary> /// <param name="value"> /// The value to check, must not be blank. /// </param> /// <param name="name"> /// The name of the parameter the value is taken from, must not be /// blank. /// </param> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="value"/> or <paramref name="name"/> are /// blank. /// </exception> public static void CheckNotBlank(string value, string name) { CheckNotBlank(value, name, string.Format("{0} must not be blank", name)); } /// <summary> /// Ensures that <paramref name="collection"/> contains at least one /// item. /// </summary> /// <param name="collection"> /// The collection to check, must not be null or empty. /// </param> /// <param name="name"> /// The name of the parameter the collection is taken from, must not be /// blank. /// </param> /// <param name="message"> /// The message to provide to the exception if <paramref name="collection"/> /// is empty, must not be blank. /// </param> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="collection"/> is empty, or if /// <paramref name="value"/> or <paramref name="name"/> are blank. /// </exception> public static void CheckAny<T>(IEnumerable<T> collection, string name, string message) { if (collection == null || !collection.Any()) { CheckNotBlank(name, "name", "name must not be blank"); CheckNotBlank(message, "message", "message must not be blank"); throw new ArgumentException(message, name); } } /// <summary> /// Ensures that <paramref name="value"/> is true. /// </summary> /// <param name="value"> /// The value to check, must be true. /// </param> /// <param name="name"> /// The name of the parameter the value is taken from, must not be /// blank. /// </param> /// <param name="message"> /// The message to provide to the exception if <paramref name="collection"/> /// is false, must not be blank. /// </param> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="value"/> is false, or if <paramref name="name"/> /// or <paramref name="message"/> are blank. /// </exception> public static void CheckTrue(bool value, string name, string message) { if (!value) { CheckNotBlank(name, "name", "name must not be blank"); CheckNotBlank(message, "message", "message must not be blank"); throw new ArgumentException(message, name); } } /// <summary> /// Ensures that <paramref name="value"/> is false. /// </summary> /// <param name="value"> /// The value to check, must be false. /// </param> /// <param name="name"> /// The name of the parameter the value is taken from, must not be /// blank. /// </param> /// <param name="message"> /// The message to provide to the exception if <paramref name="collection"/> /// is true, must not be blank. /// </param> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="value"/> is true, or if <paramref name="name"/> /// or <paramref name="message"/> are blank. /// </exception> public static void CheckFalse(bool value, string name, string message) { if (value) { CheckNotBlank(name, "name", "name must not be blank"); CheckNotBlank(message, "message", "message must not be blank"); throw new ArgumentException(message, name); } } public static void CheckShortString(string value, string name) { CheckNotNull(value, name); if (value.Length > 255) { throw new ArgumentException(string.Format("Argument '{0}' must be less than or equal to 255 characters.", name)); } } public static void CheckTypeMatches(Type expectedType, object value, string name, string message) { bool assignable = expectedType.IsAssignableFrom(value.GetType()); if (!assignable) { CheckNotBlank(name, "name", "name must not be blank"); CheckNotBlank(message, "message", "message must not be blank"); throw new ArgumentException(message, name); } } public static void CheckLess(TimeSpan value, TimeSpan maxValue, string name) { if (value < maxValue) return; throw new ArgumentOutOfRangeException(name, string.Format("Arguments {0} must be less than maxValue", name)); } public static void CheckNull<T>(T value, string name) { if (value == null) return; throw new ArgumentException(string.Format("{0} must not be null", name), name); } } }
37.04898
129
0.529911
[ "MIT" ]
IvanSorokin/EasyNetQ
Source/EasyNetQ/Preconditions.cs
9,077
C#
#region Copyright /////////////////////////////////////////////////////////////////////////////// // // Copyright (c) Phoenix Contact GmbH & Co KG // This software is licensed under Apache-2.0 // /////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using Agents.Net; using PlcNext.CppParser.CppRipper.CodeModel; namespace PlcNext.CppParser.CppRipper.Messages { internal class NoDeclarationFound : MessageDecorator { private NoDeclarationFound(Message decoratedMessage, IEnumerable<Message> additionalPredecessors = null) : base(decoratedMessage, additionalPredecessors) { } protected override string DataToString() { return string.Empty; } public static NoDeclarationFound Create(Message predecessor) { return new NoDeclarationFound(new TypeFieldsAggregated(predecessor, Array.Empty<CppField>()), new[] {predecessor}); } } }
30.972222
113
0.543498
[ "Apache-2.0" ]
PLCnext/PLCnext_CLI
src/PlcNext.CppParser/CppRipper/Messages/NoDeclarationFound.cs
1,117
C#
using System; using System.Collections.Generic; using System.Linq; using PKG1; namespace Edelstein.Provider.Reactors { public class ReactorStateTemplate { public int ID { get; set; } // TODO: timeOut public ICollection<ReactorEventTemplate> Events; public static ReactorStateTemplate Parse(WZProperty p) { return new ReactorStateTemplate { ID = Convert.ToInt32(p.Name), Events = p.Resolve("event")?.Children .Select(ReactorEventTemplate.Parse) .ToList() ?? new List<ReactorEventTemplate>() }; } } }
27.346154
64
0.547117
[ "MIT" ]
kaokaotw/Edelstein-archive
src/Edelstein.Provider/Reactors/ReactorStateTemplate.cs
711
C#
using System.Collections.Generic; namespace ProjectN.TicketManagement.Application.Responses { public class BaseResponse { public BaseResponse() { Success = true; } public BaseResponse(string message = null) { Success = true; Message = message; } public BaseResponse(string message, bool success) { Success = success; Message = message; } public bool Success { get; set; } public string Message { get; set; } public List<string> ValidationErrors { get; set; } } }
23.642857
59
0.528701
[ "MIT" ]
Naveenpatancheru/ProjectN
ProjectN.Application/Responses/BaseResponse.cs
664
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Bifrost.Concepts; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; namespace PowerBIDotNet { /// <summary> /// Represents an implementation of <see cref="IConfigurationForTenants"/> that is using Azure Table Storage for holding <see cref="TenantConfiguration"/> /// </summary> public class ConfigurationForTenants : IConfigurationForTenants { const string TableName = "TenantsConfiguration"; static PropertyInfo[] _properties = typeof(TenantConfiguration).GetProperties(); StorageConfiguration _storageConfiguration; CloudTable _table; /// <summary> /// Initializes a new instance of <see cref="ConfigurationForTenants"/> /// </summary> /// <param name="storageConfiguration"></param> public ConfigurationForTenants(StorageConfiguration storageConfiguration) { _storageConfiguration = storageConfiguration; SetupTable(); } #pragma warning disable 1591 // Xml Comments public TenantConfiguration GetFor(Tenant tenant) { var query = _table.CreateQuery<DynamicTableEntity>() .Where(e => e.PartitionKey == tenant && e.RowKey == tenant); var result = query.FirstOrDefault(); if (result != null) return Map(result); return null; } public void Save(TenantConfiguration configuration) { var entity = new DynamicTableEntity(configuration.Tenant, configuration.Tenant); foreach( var property in _properties ) { var value = property.GetValue(configuration); var valueAsString = string.Empty; if (value != null) { if (property.PropertyType.IsConcept()) value = value.GetConceptValue(); valueAsString = value.ToString(); } entity.Properties.Add(property.Name, new EntityProperty(valueAsString)); } var operation = TableOperation.InsertOrReplace(entity); _table.Execute(operation); } public IEnumerable<TenantConfiguration> GetAll() { var all = _table.CreateQuery<DynamicTableEntity>().Select(Map).ToArray(); return all; } #pragma warning restore 1591 // Xml Comments void SetupTable() { var connectionString = $"DefaultEndpointsProtocol=https;AccountName={_storageConfiguration.AccountName};AccountKey={_storageConfiguration.AccessKey}"; var storageAccount = CloudStorageAccount.Parse(connectionString); var tableClient = storageAccount.CreateCloudTableClient(); try { _table = tableClient.GetTableReference(TableName); _table.CreateIfNotExists(); } catch { } } TenantConfiguration Map(DynamicTableEntity entity) { var configuration = new TenantConfiguration(); foreach (var property in _properties ) { if (entity.Properties.ContainsKey(property.Name)) { var targetType = property.PropertyType; var value = entity.Properties[property.Name].StringValue; if (targetType.IsConcept()) property.SetValue(configuration, ConceptFactory.CreateConceptInstance(targetType, value)); else property.SetValue(configuration, Convert.ChangeType(value, targetType)); } } return configuration; } } }
35.078261
162
0.603123
[ "MIT" ]
msdevno/PowerBIDotNet
Source/PowerBIDotNet/ConfigurationForTenants.cs
4,036
C#
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org/?p=license&r=2.4 // **************************************************************** using System; using NUnit.Framework; namespace NUnit.Core.Tests { /// <summary> /// Summary description for ThreadedTestRunnerTests. /// </summary> [TestFixture] public class ThreadedTestRunnerTests : BasicRunnerTests { protected override TestRunner CreateRunner( int runnerID ) { return new ThreadedTestRunner( new SimpleTestRunner( runnerID ) ); } } }
28.08
70
0.571225
[ "Apache-2.0" ]
assessorgeneral/ConQAT
org.conqat.engine.dotnet/test-data/org.conqat.engine.dotnet.scope/NUnit_Folder/NUnitCore/tests/ThreadedTestRunnerTests.cs
702
C#
using System; //using JustDecompile.EngineInfrastructure; using Mono.Cecil; using System.IO; using Telerik.JustDecompiler.Languages.CSharp; using Telerik.JustDecompiler.Languages; using System.Collections.Generic; using JustDecompile.Tools.MSBuildProjectBuilder.FilePathsServices; using JustDecompile.Tools.MSBuildProjectBuilder.Contracts.FileManagers; namespace JustDecompile.Tools.MSBuildProjectBuilder.ProjectItemFileWriters { class ProjectItemWriterFactory { private readonly IProjectManager projectFileManager; private readonly string sourceExtension; private readonly string targetDirectory; private readonly AssemblyDefinition assembly; private object fileNamesCollisionsLock = new object(); private readonly IFilePathsService filePathsService; private readonly Dictionary<TypeDefinition, string> typeToPathMap; public ProjectItemWriterFactory(AssemblyDefinition thisAssembly, Mono.Collections.Generic.Collection<TypeDefinition> userDefinedTypes, IProjectManager projectFileManager, IFilePathsService filePathsService, string sourceExtension, string targetDirectory) { this.assembly = thisAssembly; this.projectFileManager = projectFileManager; this.filePathsService = filePathsService; this.typeToPathMap = filePathsService.GetTypesToFilePathsMap(); this.sourceExtension = sourceExtension; this.targetDirectory = targetDirectory; } public IProjectItemFileWriter GetProjectItemWriter(TypeDefinition type) { IMsBuildProjectManager msBuildProjectManager = this.projectFileManager as IMsBuildProjectManager; string relativeResourcePath; if(this.projectFileManager.ResourceDesignerMap.TryGetValue(type.FullName, out relativeResourcePath) || IsVBResourceType(type, out relativeResourcePath)) { if (type.BaseType != null && type.BaseType.Namespace == "System.Windows.Forms" && type.BaseType.Name == "Form") { return new WinFormsItemWriter(this.targetDirectory, relativeResourcePath, sourceExtension, msBuildProjectManager); } else { return new ResXDesignerWriter(this.targetDirectory, relativeResourcePath, this.projectFileManager, filePathsService); } } string relativeXamlPath; if(this.projectFileManager.XamlFullNameToRelativePathMap.TryGetValue(type.FullName, out relativeXamlPath)) { if(assembly.EntryPoint != null && assembly.EntryPoint.DeclaringType == type) { return new AppDefinitionItemWriter(this.targetDirectory, relativeXamlPath, sourceExtension, msBuildProjectManager); } else { return new XamlPageItemWriter(this.targetDirectory, relativeXamlPath, sourceExtension, msBuildProjectManager); } } string friendlyFilePath; if (type.FullName == "Properties.AssemblyInfo") { friendlyFilePath = filePathsService.GetAssemblyInfoRelativePath(); } else { lock (this.fileNamesCollisionsLock) { friendlyFilePath = this.typeToPathMap[type]; } } return new RegularProjectItemWriter(this.targetDirectory, friendlyFilePath, this.projectFileManager); } private bool IsVBResourceType(TypeDefinition type, out string relativeResourcePath) { relativeResourcePath = null; string resourceName; return Utilities.IsVBResourceType(type, out resourceName) && this.projectFileManager.ResourceDesignerMap.TryGetValue(resourceName, out relativeResourcePath); } } }
40.932692
169
0.630491
[ "ECL-2.0", "Apache-2.0" ]
Bebere/JustDecompileEngine
MSBuildProjectCreator/ProjectItemFileWriters/ProjectItemWriterFactory.cs
4,259
C#
/* * MIT License * * Copyright (c) 2019 plexdata.de * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ using Microsoft.AspNetCore.Http; namespace Plexdata.AspNetCore.Http.Abstraction { /// <summary> /// The interface of the HTTP context creator. /// </summary> /// <remarks> /// This interface is indeed a factory. But the naming extension <i>factory</i> would /// be in conflict with the interface name <see cref="IHttpContextFactory"/>. Therefore, /// this interface uses the naming extension <i>creator</i>. /// </remarks> public interface IHttpContextCreator { /// <summary> /// Creates an instance of type <see cref="IHttpContextFacade"/> by taking current /// <see cref="HttpContext"/>. /// </summary> /// <remarks> /// This method creates an instance of <see cref="IHttpContextFacade"/>. The internal instance of /// <see cref="HttpContext"/> is taken from injected instance of <see cref="IHttpContextAccessor"/>. /// </remarks> /// <returns> /// An instance of type <see cref="IHttpContextFacade"/>. /// </returns> IHttpContextFacade Create(); /// <summary> /// Creates an instance of type <see cref="IHttpContextFacade"/> using provided instance of /// <see cref="HttpContext"/>. /// </summary> /// <remarks> /// This method creates an instance of type <see cref="IHttpContextFacade"/> by using provided /// instance of <see cref="HttpContext"/>. /// </remarks> /// <param name="context"> /// The instance of type <see cref="HttpContext"/> to be wrapped. /// </param> /// <returns> /// An instance of type <see cref="IHttpContextFacade"/>. /// </returns> IHttpContextFacade Create(HttpContext context); } }
42.333333
108
0.657651
[ "MIT" ]
akesseler/Plexdata.Abstractions
code/src/Plexdata.AspNetCore.Http/Abstraction/IHttpContextCreator.cs
2,923
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; public class ButtonLogic : MonoBehaviour { private AudioManager audioManager; private void Start() { audioManager = FindObjectOfType<AudioManager>(); } public void WiggleButton() { transform.DOPunchScale(Vector3.one * 0.1f, 0.16f, 14).SetUpdate(true); audioManager.Play("Submit"); } public void IncreaseButton() { transform.DOScale(Vector3.one * 1.3f, 0.05f).SetUpdate(true); audioManager.Play("Tick"); } public void DecreaseButton() { transform.DOScale(Vector3.one, 0.05f).SetUpdate(true); } }
24.392857
78
0.670571
[ "MIT" ]
guigs10mil/EddieTheMole
Assets/Scripts/ButtonLogic.cs
685
C#
using System; using System.Collections.Generic; using System.Linq; using EK.CommonUtils.Extensions; using Xunit; namespace EK.CommonUtils.Tests.Extensions; public sealed class IEnumerableExtensionsTests { [Fact] public void ForEach_WithoutIndex() { var items = new int[] { 1, 2, 3, 4, 5 }; var result = new List<int>(); items.ForEach(result.Add); Assert.Equal(5, result.Count); Assert.Equal(1, result[0]); Assert.Equal(5, result[^1]); } [Fact] public void ForEach_WithIndex() { var items = new int[] { 1, 2, 3, 4, 5 }; var result = new List<int>(); items.ForEach((x, index) => result.Add(index)); Assert.Equal(5, result.Count); Assert.Equal(0, result[0]); Assert.Equal(4, result[^1]); } [Fact] public void Consume_NonEmptyEnumerable_IteratesThroughAllElements() { int consumed = 0; CreateEnumerable().Consume(); Assert.Equal(10, consumed); IEnumerable<object?> CreateEnumerable() { for (int i = 0; i < 10; i++) { consumed++; yield return null; } } } [Theory] [InlineData(new object[] { }, new object[] { })] [InlineData(new string[] { "x" }, new string[] { "x" })] [InlineData(new string?[] { "a", null, "b" }, new string[] { "a", "b" })] [InlineData(new string?[] { null, null, null }, new string[] { })] [InlineData(new string?[] { null, "x", null }, new string[] { "x" })] public void WhereNotNull(IEnumerable<object?> input, IEnumerable<object?> expected) { var actual = input.WhereNotNull().ToList(); Assert.True(expected.SequenceEqual(actual)); } [Theory] [MemberData(nameof(WhereNullableHasValueData))] public void WhereNullableHasValue(IEnumerable<int?> input, IEnumerable<int?> expected) { var actual = input.WhereNullableHasValue().ToList(); Assert.True(expected.SequenceEqual(actual)); } public static IEnumerable<object[]> WhereNullableHasValueData => new List<object[]> { new object[] { new int?[] { }, new int?[] { } }, new object[] { new int?[] { null }, new int?[] { } }, new object[] { new int?[] { null, null }, new int?[] { } }, new object[] { new int?[] { 1, null }, new int?[] { 1 } }, new object[] { new int?[] { 1, null, 3 }, new int?[] { 1, 3 } }, }; }
28.866667
90
0.535412
[ "MIT" ]
ekisielinski/CommonUtils
EK.CommonUtils.Tests/Code/Extensions/IEnumerableExtensionsTests.cs
2,600
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.1378 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace PositionSet_Connected_ViewerDemo.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.967742
151
0.573094
[ "MIT" ]
faizol/ai-algorithmplatform
AIAlgorithmPlatform/2007/algorithm/pathfinding/PositionSet_Connected_ViewerDemo/Properties/Settings.Designer.cs
1,117
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Publishing; namespace OfficeDevPnP.SPOnline.Core { public static class SPOWikiPage { public static void SetWikiPageContent(string pageUrl, string content, Web web, ClientContext clientContext) { //pageUrl = Utils.Urls.CombineUrl(web, pageUrl); File file = clientContext.Web.GetFileByServerRelativeUrl(pageUrl); clientContext.Load(file, f => f.ListItemAllFields); clientContext.ExecuteQuery(); ListItem item = file.ListItemAllFields; item["WikiField"] = content; item.Update(); clientContext.ExecuteQuery(); } public static string GetWikiPageContent(string serverRelativePageUrl, Web web, ClientContext clientContext) { serverRelativePageUrl = Utils.Urls.CombineUrl(web, serverRelativePageUrl); File file = clientContext.Web.GetFileByServerRelativeUrl(serverRelativePageUrl); clientContext.Load(file, f => f.ListItemAllFields); clientContext.ExecuteQuery(); ListItem item = file.ListItemAllFields; string content = item["WikiField"] as string; return content; } public static void AddWikiPage(string serverRelativePageUrl, Web web, ClientContext clientContext, string content = null) { //serverRelativePageUrl = Utils.Urls.CombineUrl(web, serverRelativePageUrl); string folderName = serverRelativePageUrl.Substring(0, serverRelativePageUrl.LastIndexOf("/")); Folder folder = web.GetFolderByServerRelativeUrl(folderName); File file = folder.Files.AddTemplateFile(serverRelativePageUrl, TemplateFileType.WikiPage); clientContext.ExecuteQuery(); if (content != null) { SetWikiPageContent(serverRelativePageUrl, content, web, clientContext); } } public static void RemoveWikiPage(string serverRelativePageUrl, Web web, ClientContext clientContext) { serverRelativePageUrl = Utils.Urls.CombineUrl(web, serverRelativePageUrl); File file = web.GetFileByServerRelativeUrl(serverRelativePageUrl); file.DeleteObject(); clientContext.ExecuteQuery(); } } }
34.666667
129
0.66867
[ "Apache-2.0" ]
HappySolutions/PnP
Solutions/OfficeDevPnP.SPOnline/Core/SPOWikiPage.cs
2,498
C#
class Ref {} class Def : Ref {} interface IFooRef { Ref Bar { get; } } interface IFooDef : IFooRef { new Def Bar { get; set; } } class FooProcessor<T> where T : IFooDef { public void Attach (T t, Def def) { t.Bar = def; } } class Program { public static void Main () { } }
12.72
41
0.553459
[ "Apache-2.0" ]
121468615/mono
mcs/tests/gtest-488.cs
318
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.cloudwf.Model.V20170328; namespace Aliyun.Acs.cloudwf.Transform.V20170328 { public class GetScanModeResponseUnmarshaller { public static GetScanModeResponse Unmarshall(UnmarshallerContext context) { GetScanModeResponse getScanModeResponse = new GetScanModeResponse(); getScanModeResponse.HttpResponse = context.HttpResponse; getScanModeResponse.RequestId = context.StringValue("GetScanMode.RequestId"); getScanModeResponse.Success = context.BooleanValue("GetScanMode.Success"); getScanModeResponse.Message = context.StringValue("GetScanMode.Message"); getScanModeResponse.Data = context.StringValue("GetScanMode.Data"); getScanModeResponse.ErrorCode = context.IntegerValue("GetScanMode.ErrorCode"); getScanModeResponse.ErrorMsg = context.StringValue("GetScanMode.ErrorMsg"); return getScanModeResponse; } } }
40.022222
82
0.762909
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-cloudwf/Cloudwf/Transform/V20170328/GetScanModeResponseUnmarshaller.cs
1,801
C#
using HelpMyStreet.Utils.Enums; using HelpMyStreet.Utils.Models; using HelpMyStreet.Utils.Utils; using RequestService.Core.Dto; using RequestService.Core.Interfaces.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using UserService.Core.Utils; namespace RequestService.Core.Services { public class JobService : IJobService { private readonly IRepository _repository; private readonly IDistanceCalculator _distanceCalculator; private readonly IGroupService _groupService; public JobService( IDistanceCalculator distanceCalculator, IRepository repository, IGroupService groupService) { _repository = repository; _distanceCalculator = distanceCalculator; _groupService = groupService; } public async Task<List<JobSummary>> AttachedDistanceToJobSummaries(string volunteerPostCode, List<JobSummary> jobSummaries, CancellationToken cancellationToken) { if (jobSummaries.Count == 0) { return null; } volunteerPostCode = PostcodeFormatter.FormatPostcode(volunteerPostCode); List<string> distinctPostCodes = jobSummaries.Select(d => d.PostCode).Distinct().Select(x => PostcodeFormatter.FormatPostcode(x)).ToList(); if (!distinctPostCodes.Contains(volunteerPostCode)) { distinctPostCodes.Add(volunteerPostCode); } var postcodeCoordinatesResponse = await _repository.GetLatitudeAndLongitudes(distinctPostCodes, cancellationToken); if (postcodeCoordinatesResponse == null) { return null; } var volunteerPostcodeCoordinates = postcodeCoordinatesResponse.Where(w => w.Postcode == volunteerPostCode).FirstOrDefault(); if (volunteerPostcodeCoordinates == null) { return null; } foreach (JobSummary jobSummary in jobSummaries) { var jobPostcodeCoordinates = postcodeCoordinatesResponse.Where(w => w.Postcode == jobSummary.PostCode).FirstOrDefault(); if (jobPostcodeCoordinates != null) { jobSummary.DistanceInMiles = _distanceCalculator.GetDistanceInMiles(volunteerPostcodeCoordinates.Latitude, volunteerPostcodeCoordinates.Longitude, jobPostcodeCoordinates.Latitude, jobPostcodeCoordinates.Longitude); } } return jobSummaries; } public async Task<List<JobHeader>> AttachedDistanceToJobHeaders(string volunteerPostCode, List<JobHeader> jobHeaders, CancellationToken cancellationToken) { if (jobHeaders.Count == 0) { return null; } volunteerPostCode = PostcodeFormatter.FormatPostcode(volunteerPostCode); List<string> distinctPostCodes = jobHeaders.Select(d => d.PostCode).Distinct().Select(x => PostcodeFormatter.FormatPostcode(x)).ToList(); if (!distinctPostCodes.Contains(volunteerPostCode)) { distinctPostCodes.Add(volunteerPostCode); } var postcodeCoordinatesResponse = await _repository.GetLatitudeAndLongitudes(distinctPostCodes, cancellationToken); if (postcodeCoordinatesResponse == null) { return null; } var volunteerPostcodeCoordinates = postcodeCoordinatesResponse.Where(w => w.Postcode == volunteerPostCode).FirstOrDefault(); if (volunteerPostcodeCoordinates == null) { return null; } foreach (JobHeader jobHeader in jobHeaders) { var jobPostcodeCoordinates = postcodeCoordinatesResponse.Where(w => w.Postcode == jobHeader.PostCode).FirstOrDefault(); if (jobPostcodeCoordinates != null) { jobHeader.DistanceInMiles = _distanceCalculator.GetDistanceInMiles(volunteerPostcodeCoordinates.Latitude, volunteerPostcodeCoordinates.Longitude, jobPostcodeCoordinates.Latitude, jobPostcodeCoordinates.Longitude); } } return jobHeaders; } public async Task<bool> HasPermissionToChangeStatusAsync(int jobID, int createdByUserID, CancellationToken cancellationToken) { var jobDetails = _repository.GetJobDetails(jobID); if (jobDetails == null) { throw new Exception($"Unable to retrieve job details for jobID:{jobID}"); } if (createdByUserID == jobDetails.JobSummary.VolunteerUserID) { return true; } int referringGroupId = await _repository.GetReferringGroupIDForJobAsync(jobID, cancellationToken); var userRoles = await _groupService.GetUserRoles(createdByUserID, cancellationToken); if (userRoles.UserGroupRoles[referringGroupId].Contains((int)GroupRoles.TaskAdmin)) { return true; } else { return false; } } } }
38.06383
234
0.634433
[ "MIT" ]
Magicianred/request-service
RequestService/RequestService.Core/Services/JobService.cs
5,369
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; namespace EfsTools.Items.Efs { [Serializable] [EfsFile("/nv/item_files/rfnv/00025286", true, 0xE1FF)] [Attributes(9)] public class LteB7C2LnaRangeRiseFall { [ElementsCount(32)] [ElementType("int16")] [Description("")] public short[] Value { get; set; } } }
21.809524
60
0.617904
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Efs/LteB7C2LnaRangeRiseFallI.cs
458
C#
namespace zControl.Math { /// <summary> /// A mathematical vector space over a <see cref="IField{T}"/> <typeparamref name="F"/>, which is an <see cref="IAbelian{T}"/> <typeparamref name="V"/> /// together with a scalar <see cref="Multiply(F)"/> operation (noted '*') that satisfies the following properties: /// <list type="bullet"> /// <item><description>Compatibility of scalar multiplication with field multiplication: <c>a * (bv) = (ab) * v</c></description></item> /// <item><description>Distributivity of scalar multiplication with respect to vector addition: <c>a * (u + v) = a * u + a * v</c></description></item> /// <item><description>Distributivity of scalar multiplication with respect to field addition: <c>(a + b) * v = a * v + b * v</c></description></item> /// </list> /// </summary> /// <typeparam name="V">the vector type</typeparam> /// <typeparam name="F">the scalar type</typeparam> public interface IVector<V, F> : IAbelian<V> where F : IField<F> { /// <summary> /// Returns the field identity element <see cref="IField{T}.One"/>. /// </summary> F One { get; } /// <summary> /// The scalar multiplication operation. /// </summary> /// <param name="a">the scalar</param> /// <returns>the result of the scalara product <code>this * a</code></returns> V Multiply (F a); } }
49.296296
153
0.646131
[ "MIT" ]
Helluys/zControl
Runtime/zControl/Math/IVector.cs
1,333
C#
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.1 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ namespace Vixen { using System; using System.Runtime.InteropServices; public class Model : Group { private HandleRef swigCPtr; internal Model(IntPtr cPtr, bool cMemoryOwn) : base(VixenLibPINVOKE.Model_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new HandleRef(this, cPtr); } internal static HandleRef getCPtr(Model obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } ~Model() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; VixenLibPINVOKE.delete_Model(swigCPtr); } swigCPtr = new HandleRef(null, IntPtr.Zero); } GC.SuppressFinalize(this); base.Dispose(); } } public new Model Parent() { IntPtr cPtr = VixenLibPINVOKE.Model_Parent(swigCPtr); return (Model) SharedObj.MakeObject(cPtr, true); } public new Model First() { IntPtr cPtr = VixenLibPINVOKE.Model_First(swigCPtr); return (Model) SharedObj.MakeObject(cPtr, true); } public new Model Last() { IntPtr cPtr = VixenLibPINVOKE.Model_Last(swigCPtr); return (Model) SharedObj.MakeObject(cPtr, true); } public new Model Next() { IntPtr cPtr = VixenLibPINVOKE.Model_Next(swigCPtr); return (Model) SharedObj.MakeObject(cPtr, true); } public new Model GetAt(int i) { IntPtr cPtr = VixenLibPINVOKE.Model_GetAt(swigCPtr, i); return (Model) SharedObj.MakeObject(cPtr, true); } public Model(Model arg0) : this(VixenLibPINVOKE.new_Model__SWIG_0(Model.getCPtr(arg0)), true) { if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } public Model() : this(VixenLibPINVOKE.new_Model__SWIG_1(), true) { } public Vec3 GetCenter(int transformtype) { Vec3 ret = new Vec3(VixenLibPINVOKE.Model_GetCenter__SWIG_0(swigCPtr, transformtype), true); return ret; } public virtual bool GetCenter(Vec3 OUTPUT, int transformtype) { bool ret = VixenLibPINVOKE.Model_GetCenter__SWIG_1(swigCPtr, Vec3.getCPtr(OUTPUT), transformtype); return ret; } public virtual bool GetCenter(Vec3 OUTPUT) { bool ret = VixenLibPINVOKE.Model_GetCenter__SWIG_2(swigCPtr, Vec3.getCPtr(OUTPUT)); return ret; } public virtual Vec3 GetDirection() { Vec3 ret = new Vec3(VixenLibPINVOKE.Model_GetDirection(swigCPtr), true); return ret; } public bool GetBound(Sphere OUTPUT, int transformtype) { bool ret = VixenLibPINVOKE.Model_GetBound__SWIG_0(swigCPtr, Sphere.getCPtr(OUTPUT), transformtype); return ret; } public bool GetBound(Sphere OUTPUT) { bool ret = VixenLibPINVOKE.Model_GetBound__SWIG_1(swigCPtr, Sphere.getCPtr(OUTPUT)); return ret; } public bool GetBound(Box3 OUTPUT, int transformtype) { bool ret = VixenLibPINVOKE.Model_GetBound__SWIG_2(swigCPtr, Box3.getCPtr(OUTPUT), transformtype); return ret; } public bool GetBound(Box3 OUTPUT) { bool ret = VixenLibPINVOKE.Model_GetBound__SWIG_3(swigCPtr, Box3.getCPtr(OUTPUT)); return ret; } public virtual void SetBound(Box3 INPUT) { VixenLibPINVOKE.Model_SetBound__SWIG_0(swigCPtr, Box3.getCPtr(INPUT)); } public virtual void SetBound(Sphere INPUT) { VixenLibPINVOKE.Model_SetBound__SWIG_1(swigCPtr, Sphere.getCPtr(INPUT)); } public virtual bool CalcSphere(Sphere arg0) { bool ret = VixenLibPINVOKE.Model_CalcSphere(swigCPtr, Sphere.getCPtr(arg0)); return ret; } public virtual bool CalcBound(Box3 arg0) { bool ret = VixenLibPINVOKE.Model_CalcBound(swigCPtr, Box3.getCPtr(arg0)); return ret; } public void Reset() { VixenLibPINVOKE.Model_Reset(swigCPtr); } public void Turn(Vec3 axis, float angle) { VixenLibPINVOKE.Model_Turn__SWIG_0(swigCPtr, Vec3.getCPtr(axis), angle); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } public void Turn(Quat INPUT) { VixenLibPINVOKE.Model_Turn__SWIG_1(swigCPtr, Quat.getCPtr(INPUT)); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } public void Rotate(Vec3 axis, float angle) { VixenLibPINVOKE.Model_Rotate__SWIG_0(swigCPtr, Vec3.getCPtr(axis), angle); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } public void Rotate(Quat INPUT) { VixenLibPINVOKE.Model_Rotate__SWIG_1(swigCPtr, Quat.getCPtr(INPUT)); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } public void LookAt(Vec3 INPUT, float twist) { VixenLibPINVOKE.Model_LookAt(swigCPtr, Vec3.getCPtr(INPUT), twist); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } public void Move(Vec3 arg0) { VixenLibPINVOKE.Model_Move__SWIG_0(swigCPtr, Vec3.getCPtr(arg0)); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } public void Move(float x, float y, float z) { VixenLibPINVOKE.Model_Move__SWIG_1(swigCPtr, x, y, z); } public void Translate(Vec3 INPUT) { VixenLibPINVOKE.Model_Translate__SWIG_0(swigCPtr, Vec3.getCPtr(INPUT)); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } public void Translate(float x, float y, float z) { VixenLibPINVOKE.Model_Translate__SWIG_1(swigCPtr, x, y, z); } public void Scale(Vec3 arg0) { VixenLibPINVOKE.Model_Scale__SWIG_0(swigCPtr, Vec3.getCPtr(arg0)); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } public void Scale(float x, float y, float z) { VixenLibPINVOKE.Model_Scale__SWIG_1(swigCPtr, x, y, z); } public void Size(Vec3 INPUT) { VixenLibPINVOKE.Model_Size__SWIG_0(swigCPtr, Vec3.getCPtr(INPUT)); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } public void Size(float x, float y, float z) { VixenLibPINVOKE.Model_Size__SWIG_1(swigCPtr, x, y, z); } public void TotalTransform(Matrix output) { VixenLibPINVOKE.Model_TotalTransform__SWIG_0(swigCPtr, Matrix.getCPtr(output)); } public void TotalTransform(Matrix output, Model parent) { VixenLibPINVOKE.Model_TotalTransform__SWIG_1(swigCPtr, Matrix.getCPtr(output), Model.getCPtr(parent)); } public long GetNumVtx() { long ret = VixenLibPINVOKE.Model_GetNumVtx(swigCPtr); return ret; } public static bool DoCulling { set { VixenLibPINVOKE.Model_DoCulling_set(value); } get { bool ret = VixenLibPINVOKE.Model_DoCulling_get(); return ret; } } public static Vec3 XAXIS { get { Vec3 ret = new Vec3(VixenLibPINVOKE.Model_XAXIS_get(), false); return ret; } } public static Vec3 YAXIS { get { Vec3 ret = new Vec3(VixenLibPINVOKE.Model_YAXIS_get(), false); return ret; } } public static Vec3 ZAXIS { get { Vec3 ret = new Vec3(VixenLibPINVOKE.Model_ZAXIS_get(), false); return ret; } } public virtual void Render(Scene arg0) { VixenLibPINVOKE.Model_Render(swigCPtr, Scene.getCPtr(arg0)); } public int Hints { set { VixenLibPINVOKE.Model_Hints_set(swigCPtr, value); } get { int ret = VixenLibPINVOKE.Model_Hints_get(swigCPtr); return ret; } } public Vec3 Translation { set { VixenLibPINVOKE.Model_Translation_set(swigCPtr, Vec3.getCPtr(value)); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } get { Vec3 ret = new Vec3(VixenLibPINVOKE.Model_Translation_get(swigCPtr), false); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); return ret; } } public Quat Rotation { set { VixenLibPINVOKE.Model_Rotation_set(swigCPtr, Quat.getCPtr(value)); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); } get { Quat ret = new Quat(VixenLibPINVOKE.Model_Rotation_get(swigCPtr), false); if (VixenLibPINVOKE.SWIGPendingException.Pending) throw VixenLibPINVOKE.SWIGPendingException.Retrieve(); return ret; } } public Vec3 Center { get { Vec3 ret = new Vec3(VixenLibPINVOKE.Model_Center_get(swigCPtr), false); return ret; } } public bool Culling { set { VixenLibPINVOKE.Model_Culling_set(swigCPtr, value); } get { bool ret = VixenLibPINVOKE.Model_Culling_get(swigCPtr); return ret; } } public Matrix Transform { set { VixenLibPINVOKE.Model_Transform_set(swigCPtr, Matrix.getCPtr(value)); } get { IntPtr cPtr = VixenLibPINVOKE.Model_Transform_get(swigCPtr); Matrix ret = (cPtr == IntPtr.Zero) ? null : new Matrix(cPtr, false); return ret; } } public static readonly int WORLD = VixenLibPINVOKE.Model_WORLD_get(); public static readonly int LOCAL = VixenLibPINVOKE.Model_LOCAL_get(); public static readonly int NONE = VixenLibPINVOKE.Model_NONE_get(); public static readonly int STATIC = VixenLibPINVOKE.Model_STATIC_get(); public static readonly int MORPH = VixenLibPINVOKE.Model_MORPH_get(); public static readonly int DISPLAY_NONE = VixenLibPINVOKE.Model_DISPLAY_NONE_get(); public static readonly int DISPLAY_ME = VixenLibPINVOKE.Model_DISPLAY_ME_get(); public static readonly int DISPLAY_ALL = VixenLibPINVOKE.Model_DISPLAY_ALL_get(); } }
30.433735
110
0.710808
[ "BSD-2-Clause" ]
Caprica666/vixen
build/swig/VixenCS/Sources/Model.cs
10,104
C#
#region License /* MIT License Copyright (c) 2020 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace InstallerBaseWixSharp.Files.Localization.TabDeliLocalization { /// <summary> /// A class for a simple localization using a text file embedded into a resource file. /// </summary> // ReSharper disable once UnusedMember.Global public class TabDeliLocalization { /// <summary> /// A class to store the localization text. /// </summary> internal class LocalizationTextContainer { /// <summary> /// Gets or sets the name of the localized message. /// </summary> /// <value>The name of the localized message.</value> internal string MessageName { get; set; } /// <summary> /// Gets or sets the message. /// </summary> /// <value>The message.</value> internal string Message { get; set; } /// <summary> /// Gets or sets the name of the culture of the localized message. /// </summary> /// <value>The name of the culture.</value> internal string CultureName { get; set; } } /// <summary> /// A list containing messages for localization. Please do fill at least the en-US localization. /// </summary> List<LocalizationTextContainer> LocalizationTexts { get; } = new List<LocalizationTextContainer>(); /// <summary> /// Gets a localized message and gets a string corresponding to that message. /// </summary> /// <param name="messageName">The name of the message to get.</param> /// <param name="defaultMessage">The default value for the message if none were found in the <see cref="LocalizationTexts"/> with the locale of <paramref name="locale"/>.</param> /// <param name="locale">A locale expressed as a string.</param> /// <returns>A localized message with the given parameters.</returns> // ReSharper disable once UnusedMember.Global public string GetMessage(string messageName, string defaultMessage, string locale) { var value = LocalizationTexts.FirstOrDefault(f => f.CultureName == locale && f.MessageName == messageName); if (value != null && value.Message == null && locale.Split('-').Length == 2) { value = LocalizationTexts.FirstOrDefault(f => f.CultureName == locale.Split('-')[0] && f.MessageName == messageName); } else if (value != null && value.Message == null) // fall back to a generic culture.. { value = LocalizationTexts.FirstOrDefault(f => f.CultureName.StartsWith(locale.Split('-')[0]) && f.MessageName == messageName); } return value?.Message ?? defaultMessage; } /// <summary> /// Gets a localized message and gets a string corresponding to that message with given arguments. /// </summary> /// <param name="messageName">The name of the message to get.</param> /// <param name="defaultMessage">The default value for the message if none were found in the <see cref="LocalizationTexts"/> with the locale of <paramref name="locale"/>.</param> /// <param name="locale">A locale expressed as a string.</param> /// <param name="args">An object array that contains zero or more objects to format the message.</param> /// <returns>A localized message with the given parameters.</returns> // ReSharper disable once UnusedMember.Global public string GetMessage(string messageName, string defaultMessage, string locale, params object[] args) { var value = LocalizationTexts.FirstOrDefault(f => f.CultureName == locale && f.MessageName == messageName); if (value != null && value.Message == null && locale.Split('-').Length == 2) { value = LocalizationTexts.FirstOrDefault(f => f.CultureName == locale.Split('-')[0] && f.MessageName == messageName); } else if (value != null && value.Message == null) // fall back to a generic culture.. { value = LocalizationTexts.FirstOrDefault(f => f.CultureName.StartsWith(locale.Split('-')[0]) && f.MessageName == messageName); } string msg = value?.Message ?? defaultMessage; try { return string.Format(msg, args); } catch { return msg; } } /// <summary> /// Fills the <see cref="LocalizationTexts"/> array with a given file contents as a list of strings. /// </summary> /// <param name="fileContents"></param> // ReSharper disable once UnusedMember.Global public void GetLocalizedTexts(string fileContents) { List<string> fileLines = new List<string>(); fileLines.AddRange(fileContents.Split(Environment.NewLine.ToArray())); string locale = string.Empty; foreach (var fileLine in fileLines) { if (fileLine.StartsWith("[")) { try { locale = fileLine.Trim('[', ']'); locale = new CultureInfo(locale).Name; } catch { locale = string.Empty; } continue; } if (locale == string.Empty) { continue; } string[] delimited = fileLine.Split('\t'); if (delimited.Length >= 2) { if (LocalizationTexts.Exists(f => f.CultureName == locale && f.MessageName == delimited[0])) { continue; } LocalizationTexts.Add(new LocalizationTextContainer { MessageName = delimited[0], Message = delimited[1], CultureName = locale}); } } } } }
43.056818
187
0.570599
[ "MIT" ]
VPKSoft/InstallerBaseWixSharp
InstallerBaseWixSharp/Files/Localization/TabDeliLocalization/TabDeliLocalization.cs
7,580
C#
namespace Zu.ChromeDevTools.Page { using Newtonsoft.Json; /// <summary> /// Deletes browser cookie with given name, domain and path. /// </summary> public sealed class DeleteCookieCommand : ICommand { private const string ChromeRemoteInterface_CommandName = "Page.deleteCookie"; [JsonIgnore] public string CommandName { get { return ChromeRemoteInterface_CommandName; } } /// <summary> /// Name of the cookie to remove. /// </summary> [JsonProperty("cookieName")] public string CookieName { get; set; } /// <summary> /// URL to match cooke domain and path. /// </summary> [JsonProperty("url")] public string Url { get; set; } } public sealed class DeleteCookieCommandResponse : ICommandResponse<DeleteCookieCommand> { } }
24.02439
91
0.546193
[ "Apache-2.0" ]
DoctorDump/AsyncChromeDriver
ChromeDevToolsClient/Page/DeleteCookieCommand.cs
985
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RadCBA.Core.ViewModels.UserViewModels { public class EditUserViewModel { public string Id { get; set; } [Required, MinLength(6)] [RegularExpression(@"^[ a-zA-Z0-9]+$", ErrorMessage = "Username should only contain characters and numbers"), MaxLength(40)] public string Username { get; set; } [Required(ErrorMessage = "Please enter your Full Name")] [RegularExpression(@"^[ a-zA-Z]+$", ErrorMessage = "Name should only contain characters and white spaces"), MaxLength(80)] [Display(Name = "Full name")] public string FullName { get; set; } [Required] [Display(Name = "Email Address")] [DataType(DataType.EmailAddress, ErrorMessage = "Please enter a valid email address"), MaxLength(100)] public string Email { get; set; } [Required] [Display(Name = "Phone Number")] [DataType(DataType.PhoneNumber, ErrorMessage = "Please enter a valid Phone Number")] [RegularExpression(@"^[0-9+]+$", ErrorMessage = "Please enter a valid phone number"), MinLength(11), MaxLength(16)] public string PhoneNumber { get; set; } [Required(ErrorMessage = "Please select a branch")] [Display(Name = "Branch")] public int BranchID { get; set; } [Required(ErrorMessage = "Please select a role")] [Display(Name = "Role")] public int RoleID { get; set; } } }
35.688889
132
0.64259
[ "MIT" ]
Sulzmido/Core-Banking-Application---RadCBA
RadCBA.Core/ViewModels/UserViewModels/EditUserViewModel.cs
1,608
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.Azure.WebJobs.Extensions.DurableTask; namespace WebJobs.Extensions.DurableTask.Tests.V2 { internal class TestCustomConnectionsStringResolver : IConnectionStringResolver { private readonly Dictionary<string, string> connectionStrings; public TestCustomConnectionsStringResolver(Dictionary<string, string> connectionStrings) { this.connectionStrings = connectionStrings; } public string Resolve(string connectionStringName) { if (this.connectionStrings.TryGetValue(connectionStringName, out string value)) { return value; } return null; } } }
29.709677
96
0.692725
[ "MIT" ]
Azure/azure-functions-durable-extension
test/FunctionsV2/TestCustomConnectionsStringResolver.cs
923
C#
using Factory.Models; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Linq; namespace Factory.Controllers { public class MachinesController : Controller { private readonly FactoryContext _db; public MachinesController(FactoryContext db) { _db = db; } public ViewResult Index(string sortOrder, string searchString) { ViewBag.MakeSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; var machines = from m in _db.Machines select m; if (!String.IsNullOrEmpty(searchString)) { machines = machines.Where(m => m.Name.Contains(searchString)); } machines = machines.OrderBy(m => m.Name); return View(machines.ToList()); } public ActionResult Create() { ViewBag.EngineerId = new SelectList(_db.Engineers, "EngineerId", "Name"); return View(); } [HttpPost] public ActionResult Create(Machine machine, int EngineerId) { machine.InstallationDate = DateTime.Now; _db.Machines.Add(machine); _db.SaveChanges(); if (EngineerId != 0) { _db.Repair.Add(new Repair() { EngineerId = EngineerId, MachineId = machine.MachineId }); } _db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Details(int id) { Machine thisMachine = _db.Machines .Include(machine => machine.JoinEntities) .ThenInclude(join => join.Engineer) .FirstOrDefault(machine => machine.MachineId == id); return View(thisMachine); } public ActionResult Edit(int id) { Machine thisMachine = _db.Machines.FirstOrDefault(machines => machines.MachineId == id); ViewBag.EngineerId = new SelectList(_db.Engineers, "EngineerId", "Name"); return View(thisMachine); } [HttpPost] public ActionResult Edit(Machine machine, int EngineerId, DateTime InstallationDate) { machine.InstallationDate = InstallationDate; bool duplicate = _db.Repair.Any(x => x.EngineerId == EngineerId && x.MachineId == machine.MachineId); if (EngineerId != 0 && !duplicate) { _db.Repair.Add(new Repair { EngineerId = EngineerId, MachineId = machine.MachineId }); } _db.Entry(machine).State = EntityState.Modified; _db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Delete(int id) { Machine thisMachine = _db.Machines.FirstOrDefault(machines => machines.MachineId == id); return View(thisMachine); } [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { Machine thisMachine = _db.Machines.FirstOrDefault(machines => machines.MachineId == id); _db.Machines.Remove(thisMachine); _db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult AddEngineer(int id) { Machine thisMachine = _db.Machines.FirstOrDefault(machine => machine.MachineId == id); ViewBag.EngineerId = new SelectList(_db.Engineers, "EngineerId", "Name"); return View(thisMachine); } [HttpPost] public ActionResult AddEngineer(Machine machine, int EngineerId) { bool duplicate = _db.Repair.Any(x => x.EngineerId == EngineerId && x.MachineId == machine.MachineId); if (EngineerId != 0 && !duplicate) { _db.Repair.Add(new Repair() { EngineerId = EngineerId, MachineId = machine.MachineId }); } _db.SaveChanges(); return RedirectToAction("Index"); } [HttpPost] public ActionResult DeleteEngineer(int joinId) { var joinEntry = _db.Repair.FirstOrDefault(entry => entry.RepairId == joinId); _db.Repair.Remove(joinEntry); _db.SaveChanges(); return RedirectToAction("Index"); } } }
31.064
107
0.657481
[ "MIT" ]
MorganJBradford/Factory.Solution
Factory/Controllers/MachinesController.cs
3,883
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.PlatformAbstractions; using Serilog; using Serilog.Core; using Serilog.Events; namespace Kmd.Logic.Logging.Sample.AspnetCore { public class Program { static string EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"; static readonly string ConsoleMinLevelKey = "Logging:ConsoleMinLevel"; public static IConfiguration Configuration { get; } = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{EnvironmentName}.json", optional: true) .AddEnvironmentVariables() .Build(); public static int Main(string[] args) { var config = Configuration; // When we are in local development mode, we want to be able to use the console to read the // logs, however in non-development environments, we don't want the console to cause performance // or IO issues, so we make sure only fatal events are recorded there. var consoleMinLevel = config.GetValue<LogEventLevel>(ConsoleMinLevelKey, LogEventLevel.Information); var seqServerUrl = config.GetValue<string>("Logging:Seq:ServerUrl", null); var seqApiKey = config.GetValue<string>("Logging:Seq:ApiKey", null); // Just like the regular output template, but includes {Properties} so that during development, // you can more easily become aware of the contextual correlation properties begin added to // all your log events. var consoleOutputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <props: {Properties}>{NewLine}{Exception}"; // Use a logging level switch so that Seq can report back a new logging level remotely // based on the API key. var seqLogLevelSwitch = new LoggingLevelSwitch(); Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.WithProperty(name: "App", value: PlatformServices.Default.Application.ApplicationName) .Enrich.WithProperty(name: "Version", value: typeof(Program).Assembly.GetName().Version.ToString()) .WriteTo.Console(outputTemplate: consoleOutputTemplate, restrictedToMinimumLevel: consoleMinLevel) .WriteTo.Seq(serverUrl: seqServerUrl, apiKey: seqApiKey, controlLevelSwitch: seqLogLevelSwitch, compact: true) // Focus on the logs from our application, not the aspnet core infrastructure .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System", LogEventLevel.Warning) .CreateLogger(); try { Log.Information("Getting the motors running..."); CreateWebHostBuilder(args).UseConfiguration(config).UseSerilog().Build().Run(); return 0; } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return 1; } finally { Log.Information("Flushing and shutting down"); Log.CloseAndFlush(); } } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
46.595238
132
0.63209
[ "MIT" ]
kmdlogic/kmd-logic-logging-sample-aspnetcore
src/Kmd.Logic.Logging.Sample.AspnetCore/Program.cs
3,916
C#
/* * Copyright 2018 JDCLOUD.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:#www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Video * 音视频管理相关接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using JDCloudSDK.Core.Client; using JDCloudSDK.Core.Http; using System; using System.Collections.Generic; using System.Text; namespace JDCloudSDK.Vod.Client { /// <summary> /// 批量修改视频信息 /// </summary> public class BatchUpdateVideosExecutor : JdcloudExecutor { /// <summary> /// 批量修改视频信息接口的Http 请求方法 /// </summary> public override string Method { get { return "POST"; } } /// <summary> /// 批量修改视频信息接口的Http资源请求路径 /// </summary> public override string Url { get { return "/videos:batchUpdate"; } } } }
24.083333
76
0.622837
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Vod/Client/BatchUpdateVideosExecutor.cs
1,543
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autodesk.DesignScript.Runtime; using Autodesk.DesignScript.Interfaces; using Autodesk.DesignScript.Geometry; using Machina; using MAction = Machina.Action; using MPoint = Machina.Point; using MVector = Machina.Vector; using MOrientation = Machina.Orientation; using MTool = Machina.Tool; using System.IO; namespace MachinaDynamo { // █████╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ███████║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ // /// <summary> /// All possible Actions. /// </summary> public partial class Actions { /// <summary> /// Make constructor internal so that it doesn't show up on the menu. /// </summary> internal Actions() { } } }
29.35
77
0.43356
[ "MIT" ]
RobotExMachina/Machina-Dynamo
src/MachinaDynamo/Actions/_base.cs
1,714
C#
using Lexical.Localization.Utils; using System.Collections.Generic; namespace Lexical.Localization { /// <summary> /// Extension functions for <see cref="ILineFormat"/>. /// </summary> public static partial class ILineFormatExtensions { /// <summary> /// Build name for key. /// </summary> /// <param name="lineFormat"></param> /// <param name="key"></param> /// <returns>full name string or null</returns> public static string Print(this ILineFormat lineFormat, ILine key) { if (lineFormat is ILineFormatPrinter provider) { string name = provider.Print(key); if (name != null) return name; } return null; } /// <summary> /// Parse string into key. /// </summary> /// <param name="lineFormat"></param> /// <param name="str">key as string</param> /// <param name="prevPart">(optional) previous part to append to</param> /// <param name="appender">(optional) line appender to append with. If null, uses appender from <paramref name="prevPart"/>. If null, uses default appender.</param> /// <returns>key result or null if contained no content</returns> /// <exception cref="LineException">If parse failed</exception> /// <exception cref="LineException">If <paramref name="lineFormat"/> doesn't implement <see cref="ILineFormatParser"/>.</exception> /// <exception cref="LineException">Error if appender is not available</exception> public static ILine Parse(this ILineFormat lineFormat, string str, ILine prevPart = default, ILineFactory appender = default) { if (lineFormat is ILineFormatAppendParser appendParser) { return appendParser.Parse(str, prevPart, appender); } if (lineFormat is ILineFormatParser parser) { if (appender == null) appender = prevPart.GetAppender(); foreach (ILineArgument arg in parser.ParseArgs(str)) prevPart = appender.Create(prevPart, arg); return prevPart; } else throw new LineException(prevPart, $"Cannot parse strings to {nameof(ILine)} with {lineFormat.GetType().FullName}. {lineFormat} doesn't implement {nameof(ILineFormatParser)}."); } /// <summary> /// Parse string into key. /// </summary> /// <param name="lineFormat"></param> /// <param name="str"></param> /// <param name="result">key result or null if contained no content</param> /// <param name="prevPart">(optional) previous part to append to</param> /// <param name="appender">(optional) line appender to append with. If null, uses appender from <paramref name="prevPart"/>. If null, uses default appender.</param> /// <returns>true if parse was successful (even through resulted key might be null)</returns> public static bool TryParse(this ILineFormat lineFormat, string str, out ILine result, ILine prevPart = default, ILineFactory appender = default) { if (lineFormat is ILineFormatAppendParser appendParser) { return appendParser.TryParse(str, out result, prevPart, appender); } // Try get appender if (appender == null && !prevPart.TryGetAppender(out appender)) { result = null; return false; } // Try parse IEnumerable<ILineArgument> args; if (lineFormat is ILineFormatParser parser && parser.TryParseArgs(str, out args)) { // Append arguments foreach (ILineArgument arg in parser.ParseArgs(str)) if (!appender.TryCreate(prevPart, arg, out prevPart)) { result = null; return false; } result = prevPart; return true; } else { result = null; return false; } } /// <summary> /// Get associated line appender. /// </summary> /// <param name="lineFactory"></param> /// <param name="lineFormat"></param> /// <returns></returns> public static bool TryGetLineFactory(this ILineFormat lineFormat, out ILineFactory lineFactory) { if (lineFormat is ILineFormatFactory lineFormat1 && lineFormat1.LineFactory != null) { lineFactory = lineFormat1.LineFactory; return true; } lineFactory = default; return false; } /// <summary> /// Get parameter infos. /// </summary> /// <param name="lineFormat"></param> /// <returns>infos or null</returns> public static IParameterInfos GetParameterInfos(this ILineFormat lineFormat) { ILineFactory lineFactory; IParameterInfos parameterInfos; if (lineFormat.TryGetLineFactory(out lineFactory) && lineFactory.TryGetParameterInfos(out parameterInfos)) return parameterInfos; return null; } /// <summary> /// Try get parameter infos. /// </summary> /// <param name="lineFormat"></param> /// <param name="parameterInfos"></param> /// <returns>true if returned infos</returns> public static bool TryGetParameterInfos(this ILineFormat lineFormat, out IParameterInfos parameterInfos) { ILineFactory lineFactory; if (lineFormat.TryGetLineFactory(out lineFactory) && lineFactory.TryGetParameterInfos(out parameterInfos)) return true; parameterInfos = default; return false; } /// <summary> /// Get parameter info. /// </summary> /// <param name="lineFormat"></param> /// <param name="parameterName"></param> /// <returns>info or null</returns> public static IParameterInfo GetParameterInfo(this ILineFormat lineFormat, string parameterName) { IParameterInfo info; ILineFactory lineFactory; IParameterInfos parameterInfos; if (lineFormat.TryGetLineFactory(out lineFactory) && lineFactory.TryGetParameterInfos(out parameterInfos) && parameterInfos.TryGetValue(parameterName, out info)) return info; return null; } /// <summary> /// Try get parameter info. /// </summary> /// <param name="lineFormat"></param> /// <param name="parameterName"></param> /// <param name="parameterInfo"></param> /// <returns>true if returned info</returns> public static bool TryGetParameterInfo(this ILineFormat lineFormat, string parameterName, out IParameterInfo parameterInfo) { ILineFactory lineFactory; IParameterInfos parameterInfos; if (lineFormat.TryGetLineFactory(out lineFactory) && lineFactory.TryGetParameterInfos(out parameterInfos) && parameterInfos.TryGetValue(parameterName, out parameterInfo)) return true; parameterInfo = null; return false; } } }
46.081761
196
0.590419
[ "MIT" ]
tagcode/Lexical.Localization
Lexical.Localization.Abstractions/Line/Format/ILineFormatExtensions.cs
7,329
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace project2_razors_coop.Models.ManageViewModels { public class TwoFactorAuthenticationViewModel { public bool HasAuthenticator { get; set; } public int RecoveryCodesLeft { get; set; } public bool Is2faEnabled { get; set; } } }
23.111111
54
0.735577
[ "MIT" ]
michailvarouchas/project2-razors-coop
Models/ManageViewModels/TwoFactorAuthenticationViewModel.cs
418
C#
using Blog.Core.DTOs; using Blog.Core.Models; using Sparrow.Core.DTOs.Responses; using Sparrow.Core.Services; using System.Collections.Generic; using System.Threading.Tasks; namespace Blog.Core.Services { public interface ICategoryService : IAppService<Category, int, CategoryCreateDTO, CategoryUpdateDTO, CategoryDTO> { /// <summary> /// 根据分类编号获取分类封面 /// </summary> /// <param name="id"></param> /// <returns></returns> Task<OpResponse<string>> GetCover(int id); /// <summary> /// 获取所有启用的分类 /// </summary> /// <returns></returns> OpResponse<List<CategoryDTO>> GetEnabledCategories(); } }
26.615385
117
0.631503
[ "MIT" ]
RajeshJs/Blog
src/Blog.Core/Services/ICategoryService.cs
736
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.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. internal class DecoderNLS : Decoder { // Remember our encoding private readonly Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _bytesUsed; private int _leftoverBytes; // leftover data from a previous invocation of GetChars (up to 4 bytes) private int _leftoverByteCount; // number of bytes of actual data in _leftoverBytes internal DecoderNLS(Encoding encoding) { _encoding = encoding; _fallback = this._encoding.DecoderFallback; this.Reset(); } public override void Reset() { ClearLeftoverData(); _fallbackBuffer?.Reset(); } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call pointer version fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) return GetCharCount(pBytes + index, count, flush); } public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember the flush _mustFlush = flush; _throwOnOverflow = true; // By default just call the encoding version, no flush by default Debug.Assert(_encoding != null); return _encoding.GetCharCount(bytes, count, this); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); int charCount = chars.Length - charIndex; // Just call pointer version fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember our flush _mustFlush = flush; _throwOnOverflow = true; // By default just call the encodings version Debug.Assert(_encoding != null); return _encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) { fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars public override unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // We don't want to throw _mustFlush = flush; _throwOnOverflow = false; _bytesUsed = 0; // Do conversion Debug.Assert(_encoding != null); charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = _bytesUsed; // Per MSDN, "The completed output parameter indicates whether all the data in the input // buffer was converted and stored in the output buffer." That means we've successfully // consumed all the input _and_ there's no pending state or fallback data remaining to be output. completed = (bytesUsed == byteCount) && !this.HasState && (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0); } public bool MustFlush => _mustFlush; // Anything left in our decoder? internal virtual bool HasState => _leftoverByteCount != 0; // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { _mustFlush = false; } internal ReadOnlySpan<byte> GetLeftoverData() => MemoryMarshal.AsBytes(new ReadOnlySpan<int>(ref _leftoverBytes, 1)).Slice(0, _leftoverByteCount); internal void SetLeftoverData(ReadOnlySpan<byte> bytes) { bytes.CopyTo(MemoryMarshal.AsBytes(new Span<int>(ref _leftoverBytes, 1))); _leftoverByteCount = bytes.Length; } internal bool HasLeftoverData => _leftoverByteCount != 0; internal void ClearLeftoverData() { _leftoverByteCount = 0; } internal int DrainLeftoverDataForGetCharCount(ReadOnlySpan<byte> bytes, out int bytesConsumed) { // Quick check: we _should not_ have leftover fallback data from a previous invocation, // as we'd end up consuming any such data and would corrupt whatever Convert call happens // to be in progress. Unlike EncoderNLS, this is simply a Debug.Assert. No exception is thrown. Debug.Assert(_fallbackBuffer is null || _fallbackBuffer.Remaining == 0, "Should have no data remaining in the fallback buffer."); Debug.Assert(HasLeftoverData, "Caller shouldn't invoke this routine unless there's leftover data in the decoder."); // Copy the existing leftover data plus as many bytes as possible of the new incoming data // into a temporary concated buffer, then get its char count by decoding it. Span<byte> combinedBuffer = stackalloc byte[4]; combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer)); int charCount = 0; Debug.Assert(_encoding != null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: charCount = value.Utf16SequenceLength; goto Finish; // successfully transcoded bytes -> chars case OperationStatus.NeedMoreData: if (MustFlush) { goto case OperationStatus.InvalidData; // treat as equivalent to bad data } else { goto Finish; // consumed some bytes, output 0 chars } case OperationStatus.InvalidData: break; default: Debug.Fail("Unexpected OperationStatus return value."); break; } // Couldn't decode the buffer. Fallback the buffer instead. See comment in DrainLeftoverDataForGetChars // for more information on why a negative index is provided. if (FallbackBuffer.Fallback(combinedBuffer.Slice(0, combinedBufferBytesConsumed).ToArray(), index: -_leftoverByteCount)) { charCount = _fallbackBuffer!.DrainRemainingDataForGetCharCount(); Debug.Assert(charCount >= 0, "Fallback buffer shouldn't have returned a negative char count."); } Finish: bytesConsumed = combinedBufferBytesConsumed - _leftoverByteCount; // amount of 'bytes' buffer consumed just now return charCount; } internal int DrainLeftoverDataForGetChars(ReadOnlySpan<byte> bytes, Span<char> chars, out int bytesConsumed) { // Quick check: we _should not_ have leftover fallback data from a previous invocation, // as we'd end up consuming any such data and would corrupt whatever Convert call happens // to be in progress. Unlike EncoderNLS, this is simply a Debug.Assert. No exception is thrown. Debug.Assert(_fallbackBuffer is null || _fallbackBuffer.Remaining == 0, "Should have no data remaining in the fallback buffer."); Debug.Assert(HasLeftoverData, "Caller shouldn't invoke this routine unless there's leftover data in the decoder."); // Copy the existing leftover data plus as many bytes as possible of the new incoming data // into a temporary concated buffer, then transcode it from bytes to chars. Span<byte> combinedBuffer = stackalloc byte[4]; combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer)); int charsWritten = 0; bool persistNewCombinedBuffer = false; Debug.Assert(_encoding != null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: if (value.TryEncodeToUtf16(chars, out charsWritten)) { goto Finish; // successfully transcoded bytes -> chars } else { goto DestinationTooSmall; } case OperationStatus.NeedMoreData: if (MustFlush) { goto case OperationStatus.InvalidData; // treat as equivalent to bad data } else { persistNewCombinedBuffer = true; goto Finish; // successfully consumed some bytes, output no chars } case OperationStatus.InvalidData: break; default: Debug.Fail("Unexpected OperationStatus return value."); break; } // Couldn't decode the buffer. Fallback the buffer instead. The fallback mechanism relies // on a negative index to convey "the start of the invalid sequence was some number of // bytes back before the current buffer." Since we know the invalid sequence must have // started at the beginning of our leftover byte buffer, we can signal to our caller that // they must backtrack that many bytes to find the real start of the invalid sequence. if (FallbackBuffer.Fallback(combinedBuffer.Slice(0, combinedBufferBytesConsumed).ToArray(), index: -_leftoverByteCount) && !_fallbackBuffer!.TryDrainRemainingDataForGetChars(chars, out charsWritten)) { goto DestinationTooSmall; } Finish: // Report back the number of bytes (from the new incoming span) we consumed just now. // This calculation is simple: it's the difference between the original leftover byte // count and the number of bytes from the combined buffer we needed to decode the first // scalar value. We need to report this before the call to SetLeftoverData / // ClearLeftoverData because those methods will overwrite the _leftoverByteCount field. bytesConsumed = combinedBufferBytesConsumed - _leftoverByteCount; if (persistNewCombinedBuffer) { Debug.Assert(combinedBufferBytesConsumed == combinedBuffer.Length, "We should be asked to persist the entire combined buffer."); SetLeftoverData(combinedBuffer); // the buffer still only contains partial data; a future call to Convert will need it } else { ClearLeftoverData(); // the buffer contains no partial data; we'll go down the normal paths } return charsWritten; DestinationTooSmall: // If we got to this point, we're trying to write chars to the output buffer, but we're unable to do // so. Unlike EncoderNLS, this type does not allow partial writes to the output buffer. Since we know // draining leftover data is the first operation performed by any DecoderNLS API, there was no // opportunity for any code before us to make forward progress, so we must fail immediately. _encoding.ThrowCharsOverflow(this, nothingDecoded: true); throw null!; // will never reach this point } /// <summary> /// Given a byte buffer <paramref name="dest"/>, concatenates as much of <paramref name="srcLeft"/> followed /// by <paramref name="srcRight"/> into it as will fit, then returns the total number of bytes copied. /// </summary> private static int ConcatInto(ReadOnlySpan<byte> srcLeft, ReadOnlySpan<byte> srcRight, Span<byte> dest) { int total = 0; for (int i = 0; i < srcLeft.Length; i++) { if ((uint)total >= (uint)dest.Length) { goto Finish; } else { dest[total++] = srcLeft[i]; } } for (int i = 0; i < srcRight.Length; i++) { if ((uint)total >= (uint)dest.Length) { goto Finish; } else { dest[total++] = srcRight[i]; } } Finish: return total; } } }
44.524138
144
0.585605
[ "MIT" ]
6opuc/coreclr
src/System.Private.CoreLib/shared/System/Text/DecoderNLS.cs
19,368
C#
using Com.Ctrip.Framework.Apollo.Enums; using Com.Ctrip.Framework.Apollo.Util; namespace Com.Ctrip.Framework.Apollo.Core { class MetaDomainConsts { public static string GetDomain(Env env) { return env switch { Env.Dev => GetAppSetting("DEV.Meta", GetAppSetting("Meta:DEV", ConfigConsts.DefaultMetaServerUrl)), Env.Fat => GetAppSetting("FAT.Meta", GetAppSetting("Meta:FAT", ConfigConsts.DefaultMetaServerUrl)), Env.Uat => GetAppSetting("UAT.Meta", GetAppSetting("Meta:UAT", ConfigConsts.DefaultMetaServerUrl)), Env.Pro => GetAppSetting("PRO.Meta", GetAppSetting("Meta:PRO", ConfigConsts.DefaultMetaServerUrl)), _ => ConfigConsts.DefaultMetaServerUrl, }; } private static string GetAppSetting(string key, string defaultValue) { var value = ConfigUtil.GetAppConfig(key); return !string.IsNullOrWhiteSpace(value) ? value! : defaultValue; } } }
37.285714
115
0.631226
[ "Apache-2.0" ]
nixiaodong/apollo.net
Apollo.ConfigurationManager/Core/MetaDomainConsts.cs
1,046
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Orders; using QuantConnect.Securities; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// This regression algorithm tests In The Money (ITM) future option expiry for puts. /// We expect 3 orders from the algorithm, which are: /// /// * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1) /// * Option exercise, receiving short ES future contracts (sell, qty -1) /// * Future contract liquidation, due to impending expiry (buy qty 1) /// /// Additionally, we test delistings for future options and assert that our /// portfolio holdings reflect the orders the algorithm has submitted. /// </summary> public class FutureOptionPutITMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private Symbol _es19m20; private Symbol _esOption; private Symbol _expectedContract; public override void Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 6, 30); _es19m20 = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)), Resolution.Minute).Symbol; // Select a future option expiring ITM, and adds it to the algorithm. _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time) .Where(x => x.ID.StrikePrice >= 3300m && x.ID.OptionRight == OptionRight.Put) .OrderBy(x => x.ID.StrikePrice) .Take(1) .Single(), Resolution.Minute).Symbol; _expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3300m, new DateTime(2020, 6, 19)); if (_esOption != _expectedContract) { throw new Exception($"Contract {_expectedContract} was not found in the chain"); } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () => { MarketOrder(_esOption, 1); }); } public override void OnData(Slice data) { // Assert delistings, so that we can make sure that we receive the delisting warnings at // the expected time. These assertions detect bug #4872 foreach (var delisting in data.Delistings.Values) { if (delisting.Type == DelistingType.Warning) { if (delisting.Time != new DateTime(2020, 6, 19)) { throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}"); } } if (delisting.Type == DelistingType.Delisted) { if (delisting.Time != new DateTime(2020, 6, 20)) { throw new Exception($"Delisting happened at unexpected date: {delisting.Time}"); } } } } public override void OnOrderEvent(OrderEvent orderEvent) { if (orderEvent.Status != OrderStatus.Filled) { // There's lots of noise with OnOrderEvent, but we're only interested in fills. return; } if (!Securities.ContainsKey(orderEvent.Symbol)) { throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}"); } var security = Securities[orderEvent.Symbol]; if (security.Symbol == _es19m20) { AssertFutureOptionOrderExercise(orderEvent, security, Securities[_expectedContract]); } else if (security.Symbol == _expectedContract) { AssertFutureOptionContractOrder(orderEvent, security); } else { throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}"); } Log($"{Time:yyyy-MM-dd HH:mm:ss} -- {orderEvent.Symbol} :: Price: {Securities[orderEvent.Symbol].Holdings.Price} Qty: {Securities[orderEvent.Symbol].Holdings.Quantity} Direction: {orderEvent.Direction} Msg: {orderEvent.Message}"); } private void AssertFutureOptionOrderExercise(OrderEvent orderEvent, Security future, Security optionContract) { var expectedLiquidationTimeUtc = new DateTime(2020, 6, 20, 4, 0, 0); if (orderEvent.Direction == OrderDirection.Buy && future.Holdings.Quantity != 0) { // We expect the contract to have been liquidated immediately throw new Exception($"Did not liquidate existing holdings for Symbol {future.Symbol}"); } if (orderEvent.Direction == OrderDirection.Buy && orderEvent.UtcTime != expectedLiquidationTimeUtc) { throw new Exception($"Liquidated future contract, but not at the expected time. Expected: {expectedLiquidationTimeUtc:yyyy-MM-dd HH:mm:ss} - found {orderEvent.UtcTime:yyyy-MM-dd HH:mm:ss}"); } // No way to detect option exercise orders or any other kind of special orders // other than matching strings, for now. if (orderEvent.Message.Contains("Option Exercise")) { if (orderEvent.FillPrice != 3300m) { throw new Exception("Option did not exercise at expected strike price (3300)"); } if (future.Holdings.Quantity != -1) { // Here, we expect to have some holdings in the underlying, but not in the future option anymore. throw new Exception($"Exercised option contract, but we have no holdings for Future {future.Symbol}"); } if (optionContract.Holdings.Quantity != 0) { throw new Exception($"Exercised option contract, but we have holdings for Option contract {optionContract.Symbol}"); } } } private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option) { if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1) { throw new Exception($"No holdings were created for option contract {option.Symbol}"); } if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0) { throw new Exception($"Holdings were found after a filled option exercise"); } if (orderEvent.Message.Contains("Exercise") && option.Holdings.Quantity != 0) { throw new Exception($"Holdings were found after exercising option contract {option.Symbol}"); } } /// <summary> /// Ran at the end of the algorithm to ensure the algorithm has no holdings /// </summary> /// <exception cref="Exception">The algorithm has holdings</exception> public override void OnEndOfAlgorithm() { if (Portfolio.Invested) { throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}"); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// Data Points count of all timeslices of algorithm /// </summary> public long DataPoints => 644315; /// </summary> /// Data Points count of the algorithm history /// </summary> public int AlgorithmHistoryDataPoints => 0; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "3"}, {"Average Win", "4.18%"}, {"Average Loss", "-8.26%"}, {"Compounding Annual Return", "-8.884%"}, {"Drawdown", "4.400%"}, {"Expectancy", "-0.247"}, {"Net Profit", "-4.427%"}, {"Sharpe Ratio", "-1.283"}, {"Probabilistic Sharpe Ratio", "0.001%"}, {"Loss Rate", "50%"}, {"Win Rate", "50%"}, {"Profit-Loss Ratio", "0.51"}, {"Alpha", "-0.061"}, {"Beta", "0.002"}, {"Annual Standard Deviation", "0.048"}, {"Annual Variance", "0.002"}, {"Information Ratio", "-0.221"}, {"Tracking Error", "0.376"}, {"Treynor Ratio", "-24.544"}, {"Total Fees", "$1.85"}, {"Estimated Strategy Capacity", "$330000000.00"}, {"Lowest Capacity Asset", "ES 31EL5FAOOQON8|ES XFH59UK0MYO1"}, {"Fitness Score", "0.008"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-0.225"}, {"Return Over Maximum Drawdown", "-2.009"}, {"Portfolio Turnover", "0.023"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "99f96f433bc76c31cb25bcd9117a6bf1"} }; } }
43.854962
242
0.575283
[ "Apache-2.0" ]
StefanWarringa/Lean
Algorithm.CSharp/FutureOptionPutITMExpiryRegressionAlgorithm.cs
11,490
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace QuantConnect.Indicators { /// <summary> /// Represents the traditional exponential moving average indicator (EMA) /// </summary> public class ExponentialMovingAverage : Indicator, IIndicatorWarmUpPeriodProvider { private readonly decimal _k; private readonly int _period; /// <summary> /// Required period, in data points, for the indicator to be ready and fully initialized. /// </summary> public int WarmUpPeriod => _period; /// <summary> /// Initializes a new instance of the ExponentialMovingAverage class with the specified name and period /// </summary> /// <param name="name">The name of this indicator</param> /// <param name="period">The period of the EMA</param> public ExponentialMovingAverage(string name, int period) : base(name) { _period = period; _k = SmoothingFactorDefault(period); } /// <summary> /// Initializes a new instance of the ExponentialMovingAverage class with the specified name and period /// </summary> /// <param name="name">The name of this indicator</param> /// <param name="period">The period of the EMA</param> /// <param name="smoothingFactor">The percentage of data from the previous value to be carried into the next value</param> public ExponentialMovingAverage(string name, int period, decimal smoothingFactor) : base(name) { _period = period; _k = smoothingFactor; } /// <summary> /// Initializes a new instance of the ExponentialMovingAverage class with the default name and period /// </summary> /// <param name="period">The period of the EMA</param> public ExponentialMovingAverage(int period) : this($"EMA({period})", period) { } /// <summary> /// Initializes a new instance of the ExponentialMovingAverage class with the default name and period /// </summary> /// <param name="period">The period of the EMA</param> /// <param name="smoothingFactor">The percentage of data from the previous value to be carried into the next value</param> public ExponentialMovingAverage(int period, decimal smoothingFactor) : this($"EMA({period},{smoothingFactor})", period, smoothingFactor) { } /// <summary> /// Calculates the default smoothing factor for an ExponentialMovingAverage indicator /// </summary> /// <param name="period">The period of the EMA</param> /// <returns>The default smoothing factor</returns> public static decimal SmoothingFactorDefault(int period) => 2.0m / (1 + period); /// <summary> /// Gets a flag indicating when this indicator is ready and fully initialized /// </summary> public override bool IsReady => Samples >= _period; /// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { // our first data point just return identity if (Samples == 1) { return input.Value; } return input.Value * _k + Current.Value * (1 - _k); } } }
42.04902
130
0.633015
[ "Apache-2.0" ]
3ai-co/Lean
Indicators/ExponentialMovingAverage.cs
4,291
C#
#if !NETSTANDARD13 /* * 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 route53-2013-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; namespace Amazon.Route53.Model { /// <summary> /// Base class for ListHostedZones paginators. /// </summary> internal sealed partial class ListHostedZonesPaginator : IPaginator<ListHostedZonesResponse>, IListHostedZonesPaginator { private readonly IAmazonRoute53 _client; private readonly ListHostedZonesRequest _request; private int _isPaginatorInUse = 0; /// <summary> /// Enumerable containing all full responses for the operation /// </summary> public IPaginatedEnumerable<ListHostedZonesResponse> Responses => new PaginatedResponse<ListHostedZonesResponse>(this); /// <summary> /// Enumerable containing all of the HostedZones /// </summary> public IPaginatedEnumerable<HostedZone> HostedZones => new PaginatedResultKeyResponse<ListHostedZonesResponse, HostedZone>(this, (i) => i.HostedZones); internal ListHostedZonesPaginator(IAmazonRoute53 client, ListHostedZonesRequest request) { this._client = client; this._request = request; } #if BCL IEnumerable<ListHostedZonesResponse> IPaginator<ListHostedZonesResponse>.Paginate() { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } var marker = _request.Marker; ListHostedZonesResponse response; do { _request.Marker = marker; response = _client.ListHostedZones(_request); marker = response.NextMarker; yield return response; } while (response.IsTruncated); } #endif #if AWS_ASYNC_ENUMERABLES_API async IAsyncEnumerable<ListHostedZonesResponse> IPaginator<ListHostedZonesResponse>.PaginateAsync(CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } var marker = _request.Marker; ListHostedZonesResponse response; do { _request.Marker = marker; response = await _client.ListHostedZonesAsync(_request, cancellationToken).ConfigureAwait(false); marker = response.NextMarker; cancellationToken.ThrowIfCancellationRequested(); yield return response; } while (response.IsTruncated); } #endif } } #endif
38.061856
152
0.658992
[ "Apache-2.0" ]
orinem/aws-sdk-net
sdk/src/Services/Route53/Generated/Model/_bcl45+netstandard/ListHostedZonesPaginator.cs
3,692
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Cpdp.V20190820.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DistributeAccreditTlinxResponse : AbstractModel { /// <summary> /// 业务系统返回消息 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("ErrMessage")] public string ErrMessage{ get; set; } /// <summary> /// 业务系统返回码 /// </summary> [JsonProperty("ErrCode")] public string ErrCode{ get; set; } /// <summary> /// 授权申请响应对象 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("Result")] public DistributeAccreditResult Result{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "ErrMessage", this.ErrMessage); this.SetParamSimple(map, prefix + "ErrCode", this.ErrCode); this.SetParamObj(map, prefix + "Result.", this.Result); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
31.149254
81
0.618112
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Cpdp/V20190820/Models/DistributeAccreditTlinxResponse.cs
2,271
C#
using Encodable; namespace Sample_Encodable { public class Sample3 { class Model : ICodable { private bool EncodableSomeProperty; public bool SomeProperty { get => EncodableSomeProperty; set => EncodableSomeProperty = value; } } public Sample3() { SaveSample().Wait(); LoadSample().Wait(); CodingProperties.Prefix = "_"; } private static async Task SaveSample() { Model model = new Model(); model.SomeProperty = true; // Change the prefix. CodingProperties.Prefix = "Encodable"; Uri uri = new Uri(Path.GetFullPath("file.binary")); await model.SaveAsync(uri); } private static async Task LoadSample() { Uri uri = new Uri(Path.GetFullPath("file.binary")); Model model = await uri.LoadAsync<Model>(); } } }
24.4
108
0.535861
[ "Unlicense" ]
HotariTobu/Encodable
Sample_Encodable/Sample3.cs
978
C#
using System; using System.Linq; using System.Collections.Generic; namespace MP_EF_HeberAndrade { class TvService { public Tv GetById(int itemId) { using (var context = new AssetsContext()) { return context.Tvs.Find(itemId); } } public List<Tv> GetAll() { using (var context = new AssetsContext()) { return context.Tvs.ToList(); } } public void Create(Tv Tv) { using (var context = new AssetsContext()) { context.Tvs.Add(Tv); context.SaveChanges(); } } public void Update(Tv Tv) { using (var context = new AssetsContext()) { var existingTv = context.Tvs.Find(Tv.Id); existingTv.Brand = Tv.Brand; existingTv.ModelName = Tv.ModelName; existingTv.PurchaseDate = Tv.PurchaseDate; existingTv.InicialCost = Tv.InicialCost; existingTv.ExpiredDate = Tv.ExpiredDate; existingTv.ExpiredCost = Tv.ExpiredCost; context.SaveChanges(); } } public void Delete(Tv Tv) { using (var context = new AssetsContext()) { context.Tvs.Remove(Tv); context.SaveChanges(); } } } }
25.338983
58
0.474247
[ "Apache-2.0" ]
IdesignerSe/MP_EF_HeberAndrade
MP_EF_HeberAndrade/Service/TvService.cs
1,497
C#
using System; using System.Threading.Tasks; using WebPerformanceMeter.Interfaces; using WebPerformanceMeter.PerformancePlans; namespace WebPerformanceMeter { public sealed class ActiveUsersBySteps<TData> : BasicActiveUsersBySteps where TData : class { private readonly IDataReader<TData> dataReader; private readonly bool reuseDataInLoop; public ActiveUsersBySteps( ITypedUser<TData> user, int fromActiveUsersCount, int toActiveUsersCount, int usersStep, IDataReader<TData> dataReader, TimeSpan? stepPeriodDuration = null, TimeSpan? performancePlanDuration = null, int userLoopCount = 1, bool reuseDataInLoop = true) : base(user, fromActiveUsersCount, toActiveUsersCount, usersStep, stepPeriodDuration, performancePlanDuration, userLoopCount) { this.dataReader = dataReader; this.reuseDataInLoop = reuseDataInLoop; } protected override Task InvokeUserAsync() { return ((ITypedUser<TData>)this.User).InvokeAsync(this.dataReader, this.reuseDataInLoop, this.userLoopCount); } } }
31.642857
121
0.612491
[ "MIT" ]
evgenynazarchuk/WebPerformanceMeter
WebPerformanceMeter/PerformancePlans/TypedActiveUsersBySteps.cs
1,331
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Vibrant.Tsdb.ConsoleApp.Entries { public enum Sampling { FiveMinutely, Hourly, Daily } }
15
41
0.702222
[ "MIT" ]
MikaelGRA/Tsdb
test/Vibrant.Tsdb.ConsoleApp/Entries/Sampling.cs
227
C#
using System; using System.Linq; namespace ExtendedDatabase { public class Database { private Person[] persons; private int count; public Database(params Person[] persons) { this.persons = new Person[16]; AddRange(persons); } public int Count { get { return count; } } private void AddRange(Person[] data) { if (data.Length > 16) { throw new ArgumentException("Provided data length should be in range [0..16]!"); } for (int i = 0; i < data.Length; i++) { this.Add(data[i]); } this.count = data.Length; } public void Add(Person person) { if (this.count == 16) { throw new InvalidOperationException("Array's capacity must be exactly 16 integers!"); } if (persons.Any(p => p?.UserName == person.UserName)) { throw new InvalidOperationException("There is already user with this username!"); } if (persons.Any(p => p?.Id == person.Id)) { throw new InvalidOperationException("There is already user with this Id!"); } this.persons[this.count] = person; this.count++; } public void Remove() { if (this.count == 0) { throw new InvalidOperationException(); } this.count--; this.persons[this.count] = null; } public Person FindByUsername(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("Username parameter is null!"); } if (this.persons.Any(p => p?.UserName == name) == false) { throw new InvalidOperationException("No user is present by this username!"); } Person person = this.persons.First(p => p.UserName == name); return person; } public Person FindById(long id) { if (id < 0) { throw new ArgumentOutOfRangeException("Id should be a positive number!"); } if (this.persons.Any(p => p?.Id == id) == false) { throw new InvalidOperationException("No user is present by this ID!"); } Person person = this.persons.First(p => p.Id == id); return person; } } }
27.635417
101
0.477573
[ "MIT" ]
hidden16/Softuni-Advanced
OOP/UnitTesting/Exercises/DatabaseExtended/Database.cs
2,655
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V23.Segment; using NHapi.Model.V23.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V23.Group { ///<summary> ///Represents the PPT_PCL_PATIENT Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: PID (Patient Identification) </li> ///<li>1: PPT_PCL_PATIENT_VISIT (a Group object) optional </li> ///<li>2: PPT_PCL_PATHWAY (a Group object) repeating</li> ///</ol> ///</summary> [Serializable] public class PPT_PCL_PATIENT : AbstractGroup { ///<summary> /// Creates a new PPT_PCL_PATIENT Group. ///</summary> public PPT_PCL_PATIENT(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(PID), true, false); this.add(typeof(PPT_PCL_PATIENT_VISIT), false, false); this.add(typeof(PPT_PCL_PATHWAY), true, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating PPT_PCL_PATIENT - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns PID (Patient Identification) - creates it if necessary ///</summary> public PID PID { get{ PID ret = null; try { ret = (PID)this.GetStructure("PID"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns PPT_PCL_PATIENT_VISIT (a Group object) - creates it if necessary ///</summary> public PPT_PCL_PATIENT_VISIT PATIENT_VISIT { get{ PPT_PCL_PATIENT_VISIT ret = null; try { ret = (PPT_PCL_PATIENT_VISIT)this.GetStructure("PATIENT_VISIT"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of PPT_PCL_PATHWAY (a Group object) - creates it if necessary ///</summary> public PPT_PCL_PATHWAY GetPATHWAY() { PPT_PCL_PATHWAY ret = null; try { ret = (PPT_PCL_PATHWAY)this.GetStructure("PATHWAY"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of PPT_PCL_PATHWAY /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public PPT_PCL_PATHWAY GetPATHWAY(int rep) { return (PPT_PCL_PATHWAY)this.GetStructure("PATHWAY", rep); } /** * Returns the number of existing repetitions of PPT_PCL_PATHWAY */ public int PATHWAYRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("PATHWAY").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the PPT_PCL_PATHWAY results */ public IEnumerable<PPT_PCL_PATHWAY> PATHWAYs { get { for (int rep = 0; rep < PATHWAYRepetitionsUsed; rep++) { yield return (PPT_PCL_PATHWAY)this.GetStructure("PATHWAY", rep); } } } ///<summary> ///Adds a new PPT_PCL_PATHWAY ///</summary> public PPT_PCL_PATHWAY AddPATHWAY() { return this.AddStructure("PATHWAY") as PPT_PCL_PATHWAY; } ///<summary> ///Removes the given PPT_PCL_PATHWAY ///</summary> public void RemovePATHWAY(PPT_PCL_PATHWAY toRemove) { this.RemoveStructure("PATHWAY", toRemove); } ///<summary> ///Removes the PPT_PCL_PATHWAY at the given index ///</summary> public void RemovePATHWAYAt(int index) { this.RemoveRepetition("PATHWAY", index); } } }
29.437086
153
0.687964
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V23/Group/PPT_PCL_PATIENT.cs
4,445
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ElusiveSoftware.net { public partial class MasterPage { /// <summary> /// head control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder head; /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// MasterLayout control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Telerik.Web.UI.RadPageLayout MasterLayout; /// <summary> /// LogoLayout control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Telerik.Web.UI.RadPageLayout LogoLayout; /// <summary> /// mainnavigation control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::ElusiveSoftware.net.controls.mainnavigation mainnavigation; /// <summary> /// ContentPlaceHolder1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder1; /// <summary> /// ContentPlaceHolder2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder2; /// <summary> /// mainfooter control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::ElusiveSoftware.net.controls.mainfooter mainfooter; } }
32.340909
88
0.587491
[ "MIT" ]
dlnuckolls/glorykidd-public
web/elusivesoftware/ElusiveSoftware.net/MasterPage.Master.designer.cs
2,848
C#
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CBTTaskStopBeingScaredDef : IBehTreeReactionTaskDefinition { public CBTTaskStopBeingScaredDef(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBTTaskStopBeingScaredDef(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
31.73913
137
0.754795
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/W3/RTTIConvert/CBTTaskStopBeingScaredDef.cs
708
C#
using Umbraco.Core.Persistence.Migrations.Syntax.Delete.Expressions; namespace Umbraco.Core.Persistence.Migrations.Syntax.Delete.Constraint { public class DeleteConstraintBuilder : ExpressionBuilderBase<DeleteConstraintExpression>, IDeleteConstraintOnTableSyntax { public DeleteConstraintBuilder(DeleteConstraintExpression expression) : base(expression) { } public void FromTable(string tableName) { Expression.Constraint.TableName = tableName; } } }
33.75
125
0.712963
[ "MIT" ]
Abhith/Umbraco-CMS
src/Umbraco.Core/Persistence/Migrations/Syntax/Delete/Constraint/DeleteConstraintBuilder.cs
542
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.MachineLearning")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Machine Learning. Amazon Machine Learning is a service that makes it easy for developers of all skill levels to use machine learning technology.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Machine Learning. Amazon Machine Learning is a service that makes it easy for developers of all skill levels to use machine learning technology.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - Amazon Machine Learning. Amazon Machine Learning is a service that makes it easy for developers of all skill levels to use machine learning technology.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon Machine Learning. Amazon Machine Learning is a service that makes it easy for developers of all skill levels to use machine learning technology.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon Machine Learning. Amazon Machine Learning is a service that makes it easy for developers of all skill levels to use machine learning technology.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.5.0.2")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
53
243
0.775009
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/MachineLearning/Properties/AssemblyInfo.cs
2,809
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace PropertyDependencyFramework { public static class PlatformSpecificSanityChecks { public static void TryVerifyLastPropertySetterEquals(string expectedPropertySetterName) { //Cannot easily validate in Windows Store App } public static void TryValidatePropertyHasSetter(Type type, string propertyName) { //Cannot easily validate in Windows Store App } } }
23.043478
89
0.796226
[ "MIT" ]
interknowlogy/pdfx
PropertyDependencyFramework/PropertyDependencyFramework_WindowsStore/PlatformSpecificSanityChecks.cs
532
C#
using AspNetCoreHero.Results; using AutoMapper; using CaraDotNetCore5V2.Application.Extensions; using CaraDotNetCore5V2.Application.Features.Face.Commands.Create; using CaraDotNetCore5V2.Application.Features.Face.Queries; using CaraDotNetCore5V2.Application.Interfaces.Repositories; using CaraDotNetCore5V2.Domain.Entities.Data; using MediatR; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CaraDotNetCore5V2.Application.Features.Scan.Queries.GetAllPaged { public class GetAllScansQuery : IRequest<PaginatedResult<GetAllScansResponse>> { public int PageNumber { get; set; } public int PageSize { get; set; } public GetAllScansQuery(int pageNumber, int pageSize) { PageNumber = pageNumber; PageSize = pageSize; } } public class GGetAllScansQueryHandler : IRequestHandler<GetAllScansQuery, PaginatedResult<GetAllScansResponse>> { private readonly IScanRepository _repository; private readonly IMapper _mapper; public GGetAllScansQueryHandler(IScanRepository repository, IMapper mapper) { _repository = repository; _mapper = mapper; } public async Task<PaginatedResult<GetAllScansResponse>> Handle(GetAllScansQuery request, CancellationToken cancellationToken) { Expression<Func<ScanLogs, GetAllScansResponse>> expression = e => new GetAllScansResponse { LogId = e.LogId, LoggedTime = e.LoggedTime, devid = e.devid, devname = e.devname, time = e.time, timelocal = e.timelocal //, //Faces = _mapper.Map<List<CreateFaceCommand>>(e.Faces) }; var paginatedList = await _repository.Scans .Select(expression) .ToPaginatedListAsync(request.PageNumber, request.PageSize); return paginatedList; } } }
32.815385
133
0.66526
[ "MIT" ]
rosdisulaiman/CaraDotNetCore5V2
CaraDotNetCore5V2.Application/Features/Scan/Queries/GetAllPaged/GetAllScansQuery.cs
2,135
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace Semp.WebHost.Migrations { public partial class InitialMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Cms_Menu", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), IsPublished = table.Column<bool>(nullable: false), IsSystem = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Cms_Menu", x => x.Id); }); migrationBuilder.CreateTable( name: "Core_AppSetting", columns: table => new { Id = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true), Module = table.Column<string>(nullable: true), IsVisibleInCommonSettingPage = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Core_AppSetting", x => x.Id); }); migrationBuilder.CreateTable( name: "Core_EntityType", columns: table => new { Id = table.Column<string>(nullable: false), IsMenuable = table.Column<bool>(nullable: false), RoutingController = table.Column<string>(nullable: true), RoutingAction = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Core_EntityType", x => x.Id); }); migrationBuilder.CreateTable( name: "Core_Media", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Caption = table.Column<string>(nullable: true), FileSize = table.Column<int>(nullable: false), FileName = table.Column<string>(nullable: true), MediaType = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Core_Media", x => x.Id); }); migrationBuilder.CreateTable( name: "Core_Role", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Core_Role", x => x.Id); }); migrationBuilder.CreateTable( name: "Core_User", columns: table => new { AccessFailedCount = table.Column<int>(nullable: false), EmailConfirmed = table.Column<bool>(nullable: false), Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), PasswordHash = table.Column<string>(nullable: true), SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), UserGuid = table.Column<Guid>(nullable: false), FullName = table.Column<string>(nullable: true), VendorId = table.Column<long>(nullable: true), IsDeleted = table.Column<bool>(nullable: false), CreatedOn = table.Column<DateTimeOffset>(nullable: false), UpdatedOn = table.Column<DateTimeOffset>(nullable: false), DefaultShippingAddressId = table.Column<long>(nullable: true), DefaultBillingAddressId = table.Column<long>(nullable: true), RefreshTokenHash = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Core_User", x => x.Id); }); migrationBuilder.CreateTable( name: "Core_Widget", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: true), ViewComponentName = table.Column<string>(nullable: true), CreateUrl = table.Column<string>(nullable: true), EditUrl = table.Column<string>(nullable: true), CreatedOn = table.Column<DateTimeOffset>(nullable: false), IsPublished = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Core_Widget", x => x.Id); }); migrationBuilder.CreateTable( name: "Core_WidgetZone", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Core_WidgetZone", x => x.Id); }); migrationBuilder.CreateTable( name: "Localization_Culture", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: true), IsDefault = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Localization_Culture", x => x.Id); }); migrationBuilder.CreateTable( name: "Core_Entity", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Slug = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true), EntityId = table.Column<long>(nullable: false), EntityTypeId = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Core_Entity", x => x.Id); table.ForeignKey( name: "FK_Core_Entity_Core_EntityType_EntityTypeId", column: x => x.EntityTypeId, principalTable: "Core_EntityType", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Core_RoleClaim", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), RoleId = table.Column<long>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Core_RoleClaim", x => x.Id); table.ForeignKey( name: "FK_Core_RoleClaim_Core_Role_RoleId", column: x => x.RoleId, principalTable: "Core_Role", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Cms_Page", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), Slug = table.Column<string>(nullable: true), MetaTitle = table.Column<string>(nullable: true), MetaKeywords = table.Column<string>(nullable: true), MetaDescription = table.Column<string>(nullable: true), IsPublished = table.Column<bool>(nullable: false), PublishedOn = table.Column<DateTimeOffset>(nullable: true), IsDeleted = table.Column<bool>(nullable: false), CreatedById = table.Column<long>(nullable: true), CreatedOn = table.Column<DateTimeOffset>(nullable: false), UpdatedOn = table.Column<DateTimeOffset>(nullable: false), UpdatedById = table.Column<long>(nullable: true), Body = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Cms_Page", x => x.Id); table.ForeignKey( name: "FK_Cms_Page_Core_User_CreatedById", column: x => x.CreatedById, principalTable: "Core_User", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Cms_Page_Core_User_UpdatedById", column: x => x.UpdatedById, principalTable: "Core_User", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Core_UserClaim", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), UserId = table.Column<long>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Core_UserClaim", x => x.Id); table.ForeignKey( name: "FK_Core_UserClaim_Core_User_UserId", column: x => x.UserId, principalTable: "Core_User", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Core_UserLogin", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<long>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Core_UserLogin", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_Core_UserLogin_Core_User_UserId", column: x => x.UserId, principalTable: "Core_User", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Core_UserRole", columns: table => new { UserId = table.Column<long>(nullable: false), RoleId = table.Column<long>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Core_UserRole", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_Core_UserRole_Core_Role_RoleId", column: x => x.RoleId, principalTable: "Core_Role", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Core_UserRole_Core_User_UserId", column: x => x.UserId, principalTable: "Core_User", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Core_UserToken", columns: table => new { UserId = table.Column<long>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Core_UserToken", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_Core_UserToken_Core_User_UserId", column: x => x.UserId, principalTable: "Core_User", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Core_WidgetInstance", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), CreatedOn = table.Column<DateTimeOffset>(nullable: false), UpdatedOn = table.Column<DateTimeOffset>(nullable: false), PublishStart = table.Column<DateTimeOffset>(nullable: true), PublishEnd = table.Column<DateTimeOffset>(nullable: true), WidgetId = table.Column<string>(nullable: true), WidgetZoneId = table.Column<long>(nullable: false), DisplayOrder = table.Column<int>(nullable: false), Data = table.Column<string>(nullable: true), HtmlData = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Core_WidgetInstance", x => x.Id); table.ForeignKey( name: "FK_Core_WidgetInstance_Core_Widget_WidgetId", column: x => x.WidgetId, principalTable: "Core_Widget", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Core_WidgetInstance_Core_WidgetZone_WidgetZoneId", column: x => x.WidgetZoneId, principalTable: "Core_WidgetZone", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Localization_Resource", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Key = table.Column<string>(nullable: true), Value = table.Column<string>(nullable: true), CultureId = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Localization_Resource", x => x.Id); table.ForeignKey( name: "FK_Localization_Resource_Localization_Culture_CultureId", column: x => x.CultureId, principalTable: "Localization_Culture", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Cms_MenuItem", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ParentId = table.Column<long>(nullable: true), MenuId = table.Column<long>(nullable: false), EntityId = table.Column<long>(nullable: true), CustomLink = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true), DisplayOrder = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Cms_MenuItem", x => x.Id); table.ForeignKey( name: "FK_Cms_MenuItem_Core_Entity_EntityId", column: x => x.EntityId, principalTable: "Core_Entity", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Cms_MenuItem_Cms_Menu_MenuId", column: x => x.MenuId, principalTable: "Cms_Menu", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Cms_MenuItem_Cms_MenuItem_ParentId", column: x => x.ParentId, principalTable: "Cms_MenuItem", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.InsertData( table: "Cms_Menu", columns: new[] { "Id", "IsPublished", "IsSystem", "Name" }, values: new object[,] { { 1L, true, true, "Customer Services" }, { 2L, true, true, "Information" } }); migrationBuilder.InsertData( table: "Core_AppSetting", columns: new[] { "Id", "IsVisibleInCommonSettingPage", "Module", "Value" }, values: new object[,] { { "Global.AssetVersion", true, "Core", "1.0" }, { "Theme", false, "Core", "Generic" } }); migrationBuilder.InsertData( table: "Core_EntityType", columns: new[] { "Id", "IsMenuable", "RoutingAction", "RoutingController" }, values: new object[,] { { "Page", true, "PageDetail", "Page" }, { "Vendor", false, "VendorDetail", "Vendor" } }); migrationBuilder.InsertData( table: "Core_Role", columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" }, values: new object[,] { { 3L, "d4754388-8355-4018-b728-218018836817", "guest", "GUEST" }, { 4L, "71f10604-8c4d-4a7d-ac4a-ffefb11cefeb", "vendor", "VENDOR" }, { 1L, "4776a1b2-dbe4-4056-82ec-8bed211d1454", "admin", "ADMIN" }, { 2L, "00d172be-03a0-4856-8b12-26d63fcf4374", "customer", "CUSTOMER" } }); migrationBuilder.InsertData( table: "Core_User", columns: new[] { "Id", "AccessFailedCount", "ConcurrencyStamp", "CreatedOn", "DefaultBillingAddressId", "DefaultShippingAddressId", "Email", "EmailConfirmed", "FullName", "IsDeleted", "LockoutEnabled", "LockoutEnd", "NormalizedEmail", "NormalizedUserName", "PasswordHash", "PhoneNumber", "PhoneNumberConfirmed", "RefreshTokenHash", "SecurityStamp", "TwoFactorEnabled", "UpdatedOn", "UserGuid", "UserName", "VendorId" }, values: new object[,] { { 2L, 0, "101cd6ae-a8ef-4a37-97fd-04ac2dd630e4", new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 189, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), null, null, "system@simplcommerce.com", false, "System User", true, false, null, "SYSTEM@SIMPLCOMMERCE.COM", "SYSTEM@SIMPLCOMMERCE.COM", "AQAAAAEAACcQAAAAEAEqSCV8Bpg69irmeg8N86U503jGEAYf75fBuzvL00/mr/FGEsiUqfR0rWBbBUwqtw==", null, false, null, "a9565acb-cee6-425f-9833-419a793f5fba", false, new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 189, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), new Guid("5f72f83b-7436-4221-869c-1b69b2e23aae"), "system@simplcommerce.com", null }, { 10L, 0, "c83afcbc-312c-4589-bad7-8686bd4754c0", new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 190, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), null, null, "admin@simplcommerce.com", false, "Shop Admin", false, false, null, "ADMIN@SIMPLCOMMERCE.COM", "ADMIN@SIMPLCOMMERCE.COM", "AQAAAAEAACcQAAAAEAEqSCV8Bpg69irmeg8N86U503jGEAYf75fBuzvL00/mr/FGEsiUqfR0rWBbBUwqtw==", null, false, null, "d6847450-47f0-4c7a-9fed-0c66234bf61f", false, new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 190, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), new Guid("ed8210c3-24b0-4823-a744-80078cf12eb4"), "admin@simplcommerce.com", null } }); migrationBuilder.InsertData( table: "Core_Widget", columns: new[] { "Id", "CreateUrl", "CreatedOn", "EditUrl", "IsPublished", "Name", "ViewComponentName" }, values: new object[,] { { "HtmlWidget", "widget-html-create", new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 164, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), "widget-html-edit", false, "Html Widget", "HtmlWidget" }, { "CarouselWidget", "widget-carousel-create", new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 164, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), "widget-carousel-edit", false, "Carousel Widget", "CarouselWidget" }, { "SpaceBarWidget", "widget-spacebar-create", new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 164, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), "widget-spacebar-edit", false, "SpaceBar Widget", "SpaceBarWidget" } }); migrationBuilder.InsertData( table: "Core_WidgetZone", columns: new[] { "Id", "Description", "Name" }, values: new object[,] { { 3L, null, "Home After Main Content" }, { 1L, null, "Home Featured" }, { 2L, null, "Home Main Content" } }); migrationBuilder.InsertData( table: "Localization_Culture", columns: new[] { "Id", "IsDefault", "Name" }, values: new object[] { "en-US", true, "English (US)" }); migrationBuilder.InsertData( table: "Core_UserRole", columns: new[] { "UserId", "RoleId" }, values: new object[] { 10L, 1L }); migrationBuilder.CreateIndex( name: "IX_Cms_MenuItem_EntityId", table: "Cms_MenuItem", column: "EntityId"); migrationBuilder.CreateIndex( name: "IX_Cms_MenuItem_MenuId", table: "Cms_MenuItem", column: "MenuId"); migrationBuilder.CreateIndex( name: "IX_Cms_MenuItem_ParentId", table: "Cms_MenuItem", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_Cms_Page_CreatedById", table: "Cms_Page", column: "CreatedById"); migrationBuilder.CreateIndex( name: "IX_Cms_Page_UpdatedById", table: "Cms_Page", column: "UpdatedById"); migrationBuilder.CreateIndex( name: "IX_Core_Entity_EntityTypeId", table: "Core_Entity", column: "EntityTypeId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "Core_Role", column: "NormalizedName", unique: true, filter: "[NormalizedName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_Core_RoleClaim_RoleId", table: "Core_RoleClaim", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "Core_User", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "Core_User", column: "NormalizedUserName", unique: true, filter: "[NormalizedUserName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_Core_UserClaim_UserId", table: "Core_UserClaim", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Core_UserLogin_UserId", table: "Core_UserLogin", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Core_UserRole_RoleId", table: "Core_UserRole", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_Core_WidgetInstance_WidgetId", table: "Core_WidgetInstance", column: "WidgetId"); migrationBuilder.CreateIndex( name: "IX_Core_WidgetInstance_WidgetZoneId", table: "Core_WidgetInstance", column: "WidgetZoneId"); migrationBuilder.CreateIndex( name: "IX_Localization_Resource_CultureId", table: "Localization_Resource", column: "CultureId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Cms_MenuItem"); migrationBuilder.DropTable( name: "Cms_Page"); migrationBuilder.DropTable( name: "Core_AppSetting"); migrationBuilder.DropTable( name: "Core_Media"); migrationBuilder.DropTable( name: "Core_RoleClaim"); migrationBuilder.DropTable( name: "Core_UserClaim"); migrationBuilder.DropTable( name: "Core_UserLogin"); migrationBuilder.DropTable( name: "Core_UserRole"); migrationBuilder.DropTable( name: "Core_UserToken"); migrationBuilder.DropTable( name: "Core_WidgetInstance"); migrationBuilder.DropTable( name: "Localization_Resource"); migrationBuilder.DropTable( name: "Core_Entity"); migrationBuilder.DropTable( name: "Cms_Menu"); migrationBuilder.DropTable( name: "Core_Role"); migrationBuilder.DropTable( name: "Core_User"); migrationBuilder.DropTable( name: "Core_Widget"); migrationBuilder.DropTable( name: "Core_WidgetZone"); migrationBuilder.DropTable( name: "Localization_Culture"); migrationBuilder.DropTable( name: "Core_EntityType"); } } }
47.824261
681
0.50717
[ "Apache-2.0" ]
afernandes/Projeto-Piloto
src/Semp.WebHost/Migrations/20180626144410_InitialMigration.cs
30,753
C#
namespace ZENBEAR.Services.Data { using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; using ZENBEAR.Data.Models; using ZENBEAR.Web.ViewModels.Projects; public interface IProjectsService { IDictionary<string, List<string>> GetProjectsItems(); string LoadProjectsItems(); Task CreateAsync(CreateProjectInputModel input); IEnumerable<SelectListItem> GetAllProjectsNames(); Project GetProjectById(int id); string GetProjectByDepartmentId(int id); Project GetProjectByName(string projectName); int GetCount(); List<Project> GetAllProjects(); } }
22.903226
61
0.695775
[ "Unlicense" ]
gready000/ZENBEAR-Digital
Services/ZENBEAR.Services.Data/IProjectsService.cs
712
C#
using UnityEngine; using System.Collections; // Warps the land to make it look like an iseland public class LandWarp : MonoBehaviour { public static float[,] CreateWarpedLand(int width, int height) { float[,] warpDepth = new float[width + 1, height + 1]; float[,] warpXVals = new float[width + 1, height + 1]; for (int y = 0; y <= width; y++) { for (int x = 0; x <= height; x++) { float tempX = (x / (float)width) * 2 - 1; // makes the x value of the terrain in the range [-1, 1] float tempY = (y / (float)width) * 2 - 1; float funcX = Mathf.Max(Mathf.Abs(tempX), Mathf.Abs(tempY)); warpXVals[x, y] = funcX; } } int size = Vars.size; int starter = 0; float depthValue; // An opimized algorithm which does only a single calculation per tier (read more at Game Design - Book 1 - page 24) // The warp amount is retrived from the created spline and applied to all the points from each tier for (int tier = 0; tier <= Vars.size / 2; tier++, size--, starter++) { depthValue = WarpFunction(warpXVals[tier, tier]); for (int x1 = starter, x2 = size, x3 = size, x4 = starter; x1 < size; x1++, x3--) { int y1 = x4, y2 = x1, y3 = x2, y4 = x3; warpDepth[x1, y1] = depthValue; warpDepth[x2, y2] = depthValue; warpDepth[x3, y3] = depthValue; warpDepth[x4, y4] = depthValue; } } warpDepth[Vars.size / 2 + 1, Vars.size / 2 + 1] = 0; return warpDepth; } // Checks which function we need for calculating warp amount and gets the warp value at the corresponding x value public static float WarpFunction(float x) { float m = Vars.warpFuncM; float n = Vars.warpFuncN; float valY; float S0; float S1; float d0 = (n - m) / (2 * Mathf.Pow(m, 2) * (m - 1)); float b0 = n / m - Mathf.Pow(m, 2) * d0; float a1 = n; float b1 = n / m + 2 * Mathf.Pow(m, 2) * d0; float c1 = 3 * m * d0; float d1 = m * d0 / (m - 1); // Use the S0 function when x value is in the range [0, m], and the S1 function when (m, 1] if (x <= m) { S0 = b0 * x + d0 * Mathf.Pow(x, 3); valY = S0; } else { S1 = a1 + b1 * (x - m) + c1 * Mathf.Pow(x - m, 2) + d1 * Mathf.Pow(x - m, 3); valY = S1; } return valY; } }
31.282353
124
0.495299
[ "MIT" ]
khorotyan/procedural-terrain-generation
Dwelland/Assets/Scripts/LandWarp.cs
2,661
C#
/* Copyright 2013-2017 MongoDB Inc. * * 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.Linq; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Operations.ElementNameValidators; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; namespace MongoDB.Driver.Core.Operations { /// <summary> /// Represents a find one and update operation. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> public class FindOneAndUpdateOperation<TResult> : FindAndModifyOperationBase<TResult> { // fields private IEnumerable<BsonDocument> _arrayFilters; private bool? _bypassDocumentValidation; private readonly BsonDocument _filter; private bool _isUpsert; private TimeSpan? _maxTime; private BsonDocument _projection; private ReturnDocument _returnDocument; private BsonDocument _sort; private readonly BsonDocument _update; // constructors /// <summary> /// Initializes a new instance of the <see cref="FindOneAndUpdateOperation{TResult}"/> class. /// </summary> /// <param name="collectionNamespace">The collection namespace.</param> /// <param name="filter">The filter.</param> /// <param name="update">The update.</param> /// <param name="resultSerializer">The result serializer.</param> /// <param name="messageEncoderSettings">The message encoder settings.</param> public FindOneAndUpdateOperation(CollectionNamespace collectionNamespace, BsonDocument filter, BsonDocument update, IBsonSerializer<TResult> resultSerializer, MessageEncoderSettings messageEncoderSettings) : base(collectionNamespace, resultSerializer, messageEncoderSettings) { _filter = Ensure.IsNotNull(filter, nameof(filter)); _update = Ensure.IsNotNull(update, nameof(update)); if (_update.ElementCount == 0) { throw new ArgumentException("Updates must have at least 1 update operator.", nameof(update)); } _returnDocument = ReturnDocument.Before; } // properties /// <summary> /// Gets or sets the array filters. /// </summary> /// <value> /// The array filters. /// </value> public IEnumerable<BsonDocument> ArrayFilters { get { return _arrayFilters; } set { _arrayFilters = value; } } /// <summary> /// Gets or sets a value indicating whether to bypass document validation. /// </summary> /// <value> /// A value indicating whether to bypass document validation. /// </value> public bool? BypassDocumentValidation { get { return _bypassDocumentValidation; } set { _bypassDocumentValidation = value; } } /// <summary> /// Gets the filter. /// </summary> /// <value> /// The filter. /// </value> public BsonDocument Filter { get { return _filter; } } /// <summary> /// Gets a value indicating whether a document should be inserted if no matching document is found. /// </summary> /// <value> /// <c>true</c> if a document should be inserted if no matching document is found; otherwise, <c>false</c>. /// </value> public bool IsUpsert { get { return _isUpsert; } set { _isUpsert = value; } } /// <summary> /// Gets or sets the maximum time the server should spend on this operation. /// </summary> /// <value> /// The maximum time the server should spend on this operation. /// </value> public TimeSpan? MaxTime { get { return _maxTime; } set { _maxTime = value; } } /// <summary> /// Gets or sets the projection. /// </summary> /// <value> /// The projection. /// </value> public BsonDocument Projection { get { return _projection; } set { _projection = value; } } /// <summary> /// Gets or sets which version of the modified document to return. /// </summary> /// <value> /// Which version of the modified document to return. /// </value> public ReturnDocument ReturnDocument { get { return _returnDocument; } set { _returnDocument = value; } } /// <summary> /// Gets or sets the sort specification. /// </summary> /// <value> /// The sort specification. /// </value> public BsonDocument Sort { get { return _sort; } set { _sort = value; } } /// <summary> /// Gets or sets the update specification. /// </summary> /// <value> /// The update specification. /// </value> public BsonDocument Update { get { return _update; } } // methods internal override BsonDocument CreateCommand(SemanticVersion serverVersion, long? transactionNumber) { Feature.Collation.ThrowIfNotSupported(serverVersion, Collation); return new BsonDocument { { "findAndModify", CollectionNamespace.CollectionName }, { "query", _filter }, { "update", _update }, { "new", true, _returnDocument == ReturnDocument.After }, { "sort", _sort, _sort != null }, { "fields", _projection, _projection != null }, { "upsert", true, _isUpsert }, { "maxTimeMS", () => _maxTime.Value.TotalMilliseconds, _maxTime.HasValue }, { "writeConcern", () => WriteConcern.ToBsonDocument(), WriteConcern != null && !WriteConcern.IsServerDefault && Feature.FindAndModifyWriteConcern.IsSupported(serverVersion) }, { "bypassDocumentValidation", () => _bypassDocumentValidation.Value, _bypassDocumentValidation.HasValue && Feature.BypassDocumentValidation.IsSupported(serverVersion) }, { "collation", () => Collation.ToBsonDocument(), Collation != null }, { "arrayFilters", () => new BsonArray(_arrayFilters), _arrayFilters != null }, { "txnNumber", () => transactionNumber, transactionNumber.HasValue } }; } /// <inheritdoc/> protected override IElementNameValidator GetCommandValidator() { return Validator.Instance; } private class Validator : IElementNameValidator { public readonly static Validator Instance = new Validator(); public IElementNameValidator GetValidatorForChildContent(string elementName) { if (elementName == "update") { return UpdateElementNameValidator.Instance; } return NoOpElementNameValidator.Instance; } public bool IsValidElementName(string elementName) { return true; } } } }
35.730088
213
0.586873
[ "Apache-2.0" ]
KermitCoder/mongo-csharp-driver
src/MongoDB.Driver.Core/Core/Operations/FindOneAndUpdateOperation.cs
8,075
C#
namespace LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample { [Microsoft.XLANGs.BaseTypes.SchemaReference(@"LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample.Families", typeof(global::LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample.Families))] [Microsoft.XLANGs.BaseTypes.SchemaReference(@"LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample.SchoolApplicationForm", typeof(global::LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample.SchoolApplicationForm))] public sealed class NestedFamiliesMapCorrect : global::Microsoft.XLANGs.BaseTypes.TransformBase { private const string _strMap = @"<?xml version=""1.0"" encoding=""UTF-16""?> <xsl:stylesheet xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:msxsl=""urn:schemas-microsoft-com:xslt"" xmlns:var=""http://schemas.microsoft.com/BizTalk/2003/var"" exclude-result-prefixes=""msxsl var s0 userCSharp"" version=""1.0"" xmlns:ns0=""http://LoopingPattern.SchoolApplicationForm"" xmlns:s0=""http://LoopingPattern.Families"" xmlns:userCSharp=""http://schemas.microsoft.com/BizTalk/2003/userCSharp""> <xsl:output omit-xml-declaration=""yes"" method=""xml"" version=""1.0"" /> <xsl:template match=""/""> <xsl:apply-templates select=""/s0:Families"" /> </xsl:template> <xsl:template match=""/s0:Families""> <ns0:ApplicationForm> <xsl:for-each select=""Family""> <xsl:variable name=""var:v1"" select=""position()"" /> <Form> <LineId> <xsl:value-of select=""$var:v1"" /> </LineId> <xsl:for-each select=""Parents""> <xsl:variable name=""var:v2"" select=""userCSharp:InitCumulativeSum(0)"" /> <xsl:for-each select=""Child""> <xsl:variable name=""var:v3"" select=""userCSharp:LogicalExistence(boolean(.))"" /> <xsl:if test=""string($var:v3)='true'""> <xsl:variable name=""var:v4"" select=""&quot;1&quot;"" /> <xsl:variable name=""var:v5"" select=""userCSharp:AddToCumulativeSum(0,string($var:v4),&quot;1&quot;)"" /> </xsl:if> </xsl:for-each> <xsl:variable name=""var:v6"" select=""userCSharp:GetCumulativeSum(0)"" /> <TotalOfChildren> <xsl:value-of select=""$var:v6"" /> </TotalOfChildren> </xsl:for-each> <Parents> <xsl:for-each select=""Parents/Name""> <xsl:variable name=""var:v7"" select=""userCSharp:LogicalEq(string(@Sex) , &quot;M&quot;)"" /> <xsl:variable name=""var:v9"" select=""userCSharp:LogicalNot(string($var:v7))"" /> <Parent> <Name> <xsl:value-of select=""./text()"" /> </Name> <xsl:if test=""string($var:v7)='true'""> <xsl:variable name=""var:v8"" select=""&quot;Father&quot;"" /> <Type> <xsl:value-of select=""$var:v8"" /> </Type> </xsl:if> <xsl:if test=""string($var:v9)='true'""> <xsl:variable name=""var:v10"" select=""&quot;Mother&quot;"" /> <Type> <xsl:value-of select=""$var:v10"" /> </Type> </xsl:if> </Parent> </xsl:for-each> </Parents> <Children> <xsl:for-each select=""Parents/Child""> <Child> <Name> <xsl:value-of select=""Name/text()"" /> </Name> <Age> <xsl:value-of select=""Age/text()"" /> </Age> <Sex> <xsl:value-of select=""Sex/text()"" /> </Sex> </Child> </xsl:for-each> </Children> </Form> </xsl:for-each> </ns0:ApplicationForm> </xsl:template> <msxsl:script language=""C#"" implements-prefix=""userCSharp""><![CDATA[ public bool LogicalExistence(bool val) { return val; } public string InitCumulativeSum(int index) { if (index >= 0) { if (index >= myCumulativeSumArray.Count) { int i = myCumulativeSumArray.Count; for (; i<=index; i++) { myCumulativeSumArray.Add(""""); } } else { myCumulativeSumArray[index] = """"; } } return """"; } public System.Collections.ArrayList myCumulativeSumArray = new System.Collections.ArrayList(); public string AddToCumulativeSum(int index, string val, string notused) { if (index < 0 || index >= myCumulativeSumArray.Count) { return """"; } double d = 0; if (IsNumeric(val, ref d)) { if (myCumulativeSumArray[index] == """") { myCumulativeSumArray[index] = d; } else { myCumulativeSumArray[index] = (double)(myCumulativeSumArray[index]) + d; } } return (myCumulativeSumArray[index] is double) ? ((double)myCumulativeSumArray[index]).ToString(System.Globalization.CultureInfo.InvariantCulture) : """"; } public string GetCumulativeSum(int index) { if (index < 0 || index >= myCumulativeSumArray.Count) { return """"; } return (myCumulativeSumArray[index] is double) ? ((double)myCumulativeSumArray[index]).ToString(System.Globalization.CultureInfo.InvariantCulture) : """"; } public bool LogicalEq(string val1, string val2) { bool ret = false; double d1 = 0; double d2 = 0; if (IsNumeric(val1, ref d1) && IsNumeric(val2, ref d2)) { ret = d1 == d2; } else { ret = String.Compare(val1, val2, StringComparison.Ordinal) == 0; } return ret; } public bool LogicalNot(string val) { return !ValToBool(val); } public bool IsNumeric(string val) { if (val == null) { return false; } double d = 0; return Double.TryParse(val, System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out d); } public bool IsNumeric(string val, ref double d) { if (val == null) { return false; } return Double.TryParse(val, System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out d); } public bool ValToBool(string val) { if (val != null) { if (string.Compare(val, bool.TrueString, StringComparison.OrdinalIgnoreCase) == 0) { return true; } if (string.Compare(val, bool.FalseString, StringComparison.OrdinalIgnoreCase) == 0) { return false; } val = val.Trim(); if (string.Compare(val, bool.TrueString, StringComparison.OrdinalIgnoreCase) == 0) { return true; } if (string.Compare(val, bool.FalseString, StringComparison.OrdinalIgnoreCase) == 0) { return false; } double d = 0; if (IsNumeric(val, ref d)) { return (d > 0); } } return false; } ]]></msxsl:script> </xsl:stylesheet>"; private const string _strArgList = @"<ExtensionObjects />"; private const string _strSrcSchemasList0 = @"LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample.Families"; private const global::LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample.Families _srcSchemaTypeReference0 = null; private const string _strTrgSchemasList0 = @"LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample.SchoolApplicationForm"; private const global::LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample.SchoolApplicationForm _trgSchemaTypeReference0 = null; public override string XmlContent { get { return _strMap; } } public override string XsltArgumentListContent { get { return _strArgList; } } public override string[] SourceSchemas { get { string[] _SrcSchemas = new string [1]; _SrcSchemas[0] = @"LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample.Families"; return _SrcSchemas; } } public override string[] TargetSchemas { get { string[] _TrgSchemas = new string [1]; _TrgSchemas[0] = @"LoopingPattern._01_LoppingTypes._06_NestedToNested.OtherExample.SchoolApplicationForm"; return _TrgSchemas; } } } }
33.472222
418
0.608417
[ "MIT" ]
sandroasp/BizTalk-Server-Learning-Path
Working-with-Maps/Looping-Pattern/LoopingPattern/01-LoppingTypes/06-NestedToNested/OtherExample/NestedFamiliesMapCorrect.btm.cs
8,435
C#
using GroupGenerator.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GroupGenerator.Data { public class GroupGeneratorDbContext : DbContext { public GroupGeneratorDbContext(DbContextOptions<GroupGeneratorDbContext> options) : base(options) { } public DbSet<Class> Class { get; set;} } }
21.95
105
0.731207
[ "MIT" ]
Kcils360/GroupGenerator
GroupGenerator/Data/GroupGeneratorDbContext.cs
441
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OlympicGames.Core.Commands.Abstracts; using OlympicGames.Core.Contracts; using OlympicGames.Utils; namespace OlympicGames.Core.Commands { public class ListOlympiansCommand : Command, ICommand { private string command; public ListOlympiansCommand(IList<string> commandParameters) : base(commandParameters) { if (Committee.Olympians.Count == 0) { Console.Write($"{GlobalConstants.NoOlympiansAdded}"); } this.command = string.Join(" ", commandParameters); } public override string Execute() { var commandTokens = command.Split(' ').ToArray(); var commandOutput = new StringBuilder(); var comittes = this.Committee.Olympians.ToList(); if (comittes.Count == 0) { } else if (commandTokens.Length == 0) { comittes = comittes.OrderBy(x => x.FirstName).ToList(); } else if (commandTokens.Length == 1) { if (commandTokens[0] == "firstname") { comittes = comittes.OrderBy(x => x.FirstName).ToList(); commandOutput.AppendLine($"Sorted by [key: firstname] in [order: asc]"); } else { comittes = comittes.OrderBy(x => x.LastName).ToList(); commandOutput.AppendLine("Sorted by [key: lastname] in [order: asc]"); } } else if (commandTokens.Length == 2) { if (commandTokens[0] == "firstname") { comittes = comittes.OrderByDescending(x => x.FirstName).ToList(); commandOutput.AppendLine("Sorted by [key: firstname] in [order: desc]"); } else { comittes = comittes.OrderByDescending(x => x.LastName).ToList(); commandOutput.AppendLine("Sorted by [key: lastname] in [order: desc]"); } } else { throw new ArgumentException(GlobalConstants.ParametersCountInvalid); } foreach (var olympian in comittes) { commandOutput.AppendLine(olympian.ToString()); } return commandOutput.ToString(); } } }
31.301205
92
0.506543
[ "MIT" ]
VProfirov/Telerik-Academy
Alpha/OOP-Ex-Alpha/OlympicGamesSkeleton v0.2/OlympicGames/Core/Commands/ListOlympiansCommand.cs
2,600
C#
#if false using UnityEngine; using UnityEngine.Experimental.UIElements; using UnityEditor; namespace UnityEngine.Experimental.UIElements { public class Element3D : VisualElement { Mesh m_Mesh; Material m_Material; Material m_LineMaterial; public Vector3 position { get; set; } public Quaternion rotation { get; set; } public Element3D() { GameObject go = GameObject.CreatePrimitive(PrimitiveType.Capsule); m_Mesh = go.GetComponent<MeshFilter>().sharedMesh; m_Material = go.GetComponent<MeshRenderer>().sharedMaterial; GameObject.DestroyImmediate(go); position = new Vector3(0, 0, -5); rotation = Quaternion.identity; m_LineMaterial = new Material(Shader.Find("Unlit/Element3DGridShader")); m_LineMaterial.color = Color.gray; } RenderTexture m_RenderTexture; #if ELEMENT3D_USE_BLIT_TEXTURE Texture2D m_BlitTexture; #endif public override void DoRepaint() { Rect panelRect = this.panel.visualTree.layout; Rect viewPort = this.parent.ChangeCoordinatesTo(this, layout); if (m_RenderTexture == null) { m_RenderTexture = new RenderTexture(Mathf.CeilToInt(viewPort.width), Mathf.CeilToInt(viewPort.height), 32, RenderTextureFormat.Default, RenderTextureReadWrite.sRGB); } if (m_RenderTexture.width != Mathf.CeilToInt(viewPort.width)) { m_RenderTexture.Release(); m_RenderTexture.width = Mathf.CeilToInt(viewPort.width); } if (m_RenderTexture.height != Mathf.CeilToInt(viewPort.height)) { m_RenderTexture.Release(); m_RenderTexture.height = Mathf.CeilToInt(viewPort.height); } #if ELEMENT3D_USE_BLIT_TEXTURE if (m_BlitTexture == null || m_BlitTexture.height != m_RenderTexture.height || m_BlitTexture.width != m_RenderTexture.width) { if (m_BlitTexture != null) m_BlitTexture.Resize(m_RenderTexture.width, m_BlitTexture.height); else { m_BlitTexture = new Texture2D(m_RenderTexture.width, m_RenderTexture.height, TextureFormat.ARGB32, false); style.backgroundImage = m_BlitTexture; } } #endif //EditorGUIUtility.SetRenderTextureNoViewport(m_RenderTexture); RenderTexture.active = m_RenderTexture; GL.PushMatrix(); //GL.Viewport(viewPort); GL.Clear(true, true, new Color(0.8f, 0.8f, 0.8f, 1)); #if true GL.LoadProjectionMatrix(Matrix4x4.Perspective(60, viewPort.width / viewPort.height, 0.01f, 100)); GL.modelview = Matrix4x4.Translate(position) * Matrix4x4.Rotate(rotation); m_LineMaterial.SetPass(0); float count = 20; GL.Begin(GL.LINES); for (float x = -count; x <= count; x++) { GL.Vertex3(x, 0, -count); GL.Vertex3(x, 0, count); } GL.End(); GL.Begin(GL.LINES); for (float x = -count; x <= count; x++) { GL.Vertex3(-count, 0, x); GL.Vertex3(count, 0, x); } GL.End(); GL.invertCulling = true; m_Material.SetPass(0); UnityEngine.Graphics.DrawMeshNow(m_Mesh, Matrix4x4.identity); GL.invertCulling = false; //Graphics.DrawMesh(m_Mesh, Matrix4x4.identity, m_Material, 1); #endif GL.PopMatrix(); #if ELEMENT3D_USE_BLIT_TEXTURE m_BlitTexture.ReadPixels(viewPort, 0, 0); RenderTexture.active = null; m_BlitTexture.Apply(); base.DoRepaint(); #else RenderTexture.active = null; var painter = elementPanel.stylePainter; var painterParams = painter.GetDefaultTextureParameters(this); painterParams.texture = m_RenderTexture; painter.DrawTexture(painterParams); #endif } } } #endif
30.385714
181
0.581805
[ "BSD-2-Clause" ]
1-10/VisualEffectGraphSample
GitHub/com.unity.visualeffectgraph/Editor/Controls/Element3D.cs
4,254
C#
namespace MuziqGrabber.Core.Models { public abstract class ModelBase : IModel {} }
29
47
0.747126
[ "MIT" ]
m-sadegh-sh/MuziqGrabber
src/MuziqGrabber.Core/Models/ModelBase.cs
89
C#
// Copyright 2010-2021 Google LLC // 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 Google.OrTools.Sat; public class BinPackingProblemSat { static void Main() { // Data. int bin_capacity = 100; int slack_capacity = 20; int num_bins = 5; int[,] items = new int[,] { { 20, 6 }, { 15, 6 }, { 30, 4 }, { 45, 3 } }; int num_items = items.GetLength(0); // Model. CpModel model = new CpModel(); // Main variables. IntVar[,] x = new IntVar[num_items, num_bins]; for (int i = 0; i < num_items; ++i) { int num_copies = items[i, 1]; for (int b = 0; b < num_bins; ++b) { x[i, b] = model.NewIntVar(0, num_copies, String.Format("x_{0}_{1}", i, b)); } } // Load variables. IntVar[] load = new IntVar[num_bins]; for (int b = 0; b < num_bins; ++b) { load[b] = model.NewIntVar(0, bin_capacity, String.Format("load_{0}", b)); } // Slack variables. IntVar[] slacks = new IntVar[num_bins]; for (int b = 0; b < num_bins; ++b) { slacks[b] = model.NewBoolVar(String.Format("slack_{0}", b)); } // Links load and x. int[] sizes = new int[num_items]; for (int i = 0; i < num_items; ++i) { sizes[i] = items[i, 0]; } for (int b = 0; b < num_bins; ++b) { IntVar[] tmp = new IntVar[num_items]; for (int i = 0; i < num_items; ++i) { tmp[i] = x[i, b]; } model.Add(load[b] == LinearExpr.ScalProd(tmp, sizes)); } // Place all items. for (int i = 0; i < num_items; ++i) { IntVar[] tmp = new IntVar[num_bins]; for (int b = 0; b < num_bins; ++b) { tmp[b] = x[i, b]; } model.Add(LinearExpr.Sum(tmp) == items[i, 1]); } // Links load and slack. int safe_capacity = bin_capacity - slack_capacity; for (int b = 0; b < num_bins; ++b) { // slack[b] => load[b] <= safe_capacity. model.Add(load[b] <= safe_capacity).OnlyEnforceIf(slacks[b]); // not(slack[b]) => load[b] > safe_capacity. model.Add(load[b] > safe_capacity).OnlyEnforceIf(slacks[b].Not()); } // Maximize sum of slacks. model.Maximize(LinearExpr.Sum(slacks)); // Solves and prints out the solution. CpSolver solver = new CpSolver(); CpSolverStatus status = solver.Solve(model); Console.WriteLine(String.Format("Solve status: {0}", status)); if (status == CpSolverStatus.Optimal) { Console.WriteLine(String.Format("Optimal objective value: {0}", solver.ObjectiveValue)); for (int b = 0; b < num_bins; ++b) { Console.WriteLine(String.Format("load_{0} = {1}", b, solver.Value(load[b]))); for (int i = 0; i < num_items; ++i) { Console.WriteLine(string.Format(" item_{0}_{1} = {2}", i, b, solver.Value(x[i, b]))); } } } Console.WriteLine("Statistics"); Console.WriteLine(String.Format(" - conflicts : {0}", solver.NumConflicts())); Console.WriteLine(String.Format(" - branches : {0}", solver.NumBranches())); Console.WriteLine(String.Format(" - wall time : {0} s", solver.WallTime())); } }
34.554622
106
0.521644
[ "Apache-2.0" ]
AlohaChina/or-tools
ortools/sat/samples/BinPackingProblemSat.cs
4,112
C#
using MatterHackers.VectorMath; // Copyright 2006 Herre Kuijpers - <herre@xs4all.nl> // // This source file(s) may be redistributed, altered and customized // by any means PROVIDING the authors name and all copyright // notices remain intact. // THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED. USE IT AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO // LIABILITY FOR ANY DATA DAMAGE/LOSS THAT THIS PRODUCT MAY CAUSE. //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; namespace MatterHackers.PolygonMesh.Processors { public class CompareCentersOnAxis : IComparer<IBvhItem> { private int whichAxis; public int WhichAxis { get { return whichAxis; } set { whichAxis = value % 3; } } public CompareCentersOnAxis(int whichAxis) { this.whichAxis = whichAxis % 3; } public int Compare(IBvhItem a, IBvhItem b) { if (a == null || b == null) { throw new Exception(); } double axisCenterA = a.GetAxisCenter(whichAxis); double axisCenterB = b.GetAxisCenter(whichAxis); if (axisCenterA > axisCenterB) { return 1; } else if (axisCenterA < axisCenterB) { return -1; } return 0; } } public interface IBvhItem { IEnumerable<IBvhItem> Children { get; } Matrix4X4 AxisToWorld { get; } /// <summary> /// The actual surface area of the surface that this bvh item is defining (a sphere, or a box, or a triangle, etc...) /// </summary> /// <returns></returns> double GetSurfaceArea(); /// <summary> /// Return the bounds of all of the elements of this bvh item /// </summary> /// <returns></returns> AxisAlignedBoundingBox GetAxisAlignedBoundingBox(); /// <summary> /// The center of the axis aligned bounds. Represented as a separate function /// for possible optimization depending on the underlying data. /// </summary> /// <returns></returns> Vector3 GetCenter(); double GetAxisCenter(int axis); /// <summary> /// Get all the items that cross the given plane /// </summary> /// <param name="plane"></param> /// <returns></returns> IEnumerable<IBvhItem> GetCrossing(Plane plane); /// <summary> /// return every Bvh item that touches this position /// </summary> /// <param name="position">The position to check</param> /// <param name="error">the amount to check around the position</param> /// <returns></returns> IEnumerable<IBvhItem> GetTouching(Vector3 position, double error); /// <summary> /// If this bvh item is a collection of other bvh items this will return the elements that are /// in the sub-region. If it is the actual element it will return itself (like a sphere or a box). /// </summary> /// <param name="results"></param> /// <param name="subRegion"></param> /// <returns></returns> bool GetContained(List<IBvhItem> results, AxisAlignedBoundingBox subRegion); /// <summary> /// Check if the give contains the item to check for as part of its collection or proxy /// </summary> /// <param name="itemToCheckFor"></param> /// <returns></returns> bool Contains(Vector3 position); } public static class ExtensionMethods { public static BvhIterator Filter(this IBvhItem item, Func<BvhIterator, bool> decentFilter = null) { return new BvhIterator(item, Matrix4X4.Identity, 0, decentFilter); } } }
27.07874
119
0.665019
[ "BSD-2-Clause" ]
595787816/agg-sharp
PolygonMesh/Processors/IBvhItem.cs
3,441
C#
//----------------------------------------------------------------------- // <copyright file="SerializedScriptableObject.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- namespace OdinSerializer { using UnityEngine; /// <summary> /// A Unity ScriptableObject which is serialized by the Sirenix serialization system. /// </summary> #if ODIN_INSPECTOR [Sirenix.OdinInspector.ShowOdinSerializedPropertiesInInspector] #endif public abstract class SerializedScriptableObject : ScriptableObject, ISerializationCallbackReceiver { [SerializeField, HideInInspector] private SerializationData serializationData; void ISerializationCallbackReceiver.OnAfterDeserialize() { UnitySerializationUtility.DeserializeUnityObject(this, ref this.serializationData); this.OnAfterDeserialize(); } void ISerializationCallbackReceiver.OnBeforeSerialize() { this.OnBeforeSerialize(); UnitySerializationUtility.SerializeUnityObject(this, ref this.serializationData); } /// <summary> /// Invoked after deserialization has taken place. /// </summary> protected virtual void OnAfterDeserialize() { } /// <summary> /// Invoked before serialization has taken place. /// </summary> protected virtual void OnBeforeSerialize() { } } }
35.1
103
0.639601
[ "Apache-2.0" ]
ImandaSyahrul/odin-serializer
OdinSerializer/Unity Integration/SerializedUnityObjects/SerializedScriptableObject.cs
2,108
C#
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kodestruct.Steel.AISC.Entities { public enum TransversePlateType { TConnection, XConnection } }
28.354839
75
0.745165
[ "Apache-2.0" ]
Kodestruct/Kodestruct.Design
Kodestruct.Steel/AISC/Entities/Enums/HssPlateConnection/TransversePlateType.cs
879
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Threading; using KdSoft.Lmdb.Interop; namespace KdSoft.Lmdb { //TODO Implement .NET 5.0 native interop improvements // see https://devblogs.microsoft.com/dotnet/improvements-in-native-code-interop-in-net-5-0/ public delegate void AssertFunction(LmdbEnvironment env, string msg); /// <summary>LMDB environment.</summary> /// <remarks> /// We make Environment the only <see cref="CriticalFinalizerObject"/> because it can /// clean up all resources it owns (databases, transactions, cursors) in its finalizer. /// </remarks> public class LmdbEnvironment: CriticalFinalizerObject, IDisposable { readonly bool autoReduceMapSizeIn32BitProcess; /// <summary>Constructor.</summary> /// <param name="config">Configuration to use.</param> public LmdbEnvironment(LmdbEnvironmentConfiguration config = null) { // so that we can refer back to the Environment instance instanceHandle = GCHandle.Alloc(this, GCHandleType.WeakTrackResurrection); DbRetCode ret = DbLib.mdb_env_create(out IntPtr envHandle); if (ret == DbRetCode.SUCCESS) { var ret2 = DbLib.mdb_env_set_userctx(envHandle, (IntPtr)instanceHandle); if (ret2 == DbRetCode.SUCCESS) this.env = envHandle; else { ret = ret2; DbLib.mdb_env_close(envHandle); } } ErrorUtil.CheckRetCode(ret); if (config != null) { this.autoReduceMapSizeIn32BitProcess = config.AutoReduceMapSizeIn32BitProcess; if (config.MapSize.HasValue) this.SetMapSize(config.MapSize.Value); if (config.MaxDatabases.HasValue) this.MaxDatabases = config.MaxDatabases.Value; if (config.MaxReaders.HasValue) this.MaxReaders = config.MaxReaders.Value; } } #region Helpers /// <summary> /// Helper method to run a native library function with disposed checking and exception processing. /// </summary> /// <param name="libFunc">Native function delegate that does not return a result.</param> [CLSCompliant(false)] protected void RunChecked(Func<IntPtr, DbRetCode> libFunc) { var handle = CheckDisposed(); var ret = libFunc(handle); ErrorUtil.CheckRetCode(ret); } /// <summary> /// Helper delegate for calling library functions with a common signature. /// </summary> /// <typeparam name="T">Result type.</typeparam> /// <typeparam name="R">Return code type.</typeparam> /// <param name="handle">Native handle to pass to the library function.</param> /// <param name="result">Result returned from the library function call.</param> /// <returns>Code returned by the native liv=brary function call.</returns> [CLSCompliant(false)] protected delegate R LibFunc<T, out R>(IntPtr handle, out T result); /// <summary> /// Helper method to run a native library function with disposed checking and exception processing. /// </summary> /// <typeparam name="T">Result type returned by native function.</typeparam> /// <param name="libFunc">Native function delegate that resturns a result.</param> /// <returns>Result returned from the native library function call.</returns> [CLSCompliant(false)] protected T GetChecked<T>(LibFunc<T, DbRetCode> libFunc) { var handle = CheckDisposed(); var ret = libFunc(handle, out T result); ErrorUtil.CheckRetCode(ret); return result; } #endregion #region Configuration and Stats /// <summary> /// Set the size of the memory map to use for this environment. /// The size should be a multiple of the OS page size. The default is 10485760 bytes. The size of the memory map /// is also the maximum size of the database. The value should be chosen as large as possible, to accommodate /// future growth of the database. This function should be called after mdb_env_create() and before mdb_env_open(). /// It may be called at later times if no transactions are active in this process. /// Note that the library does not check for this condition, the caller must ensure it explicitly. /// </summary> /// <remarks> /// The new size takes effect immediately for the current process but will not be persisted to any others /// until a write transaction has been committed by the current process. Also, only mapsize increases are persisted /// into the environment. /// If the mapsize is increased by another process, and data has grown beyond the range of the current mapsize, /// mdb_txn_begin() will return MDB_MAP_RESIZED. This function may be called with a size of zero to adopt the new size. /// Any attempt to set a size smaller than the space already consumed by the environment will be silently changed /// to the current size of the used space. /// Note: the current MapSize can be obtained by calling GetEnvInfo(). /// </remarks> /// <param name="newValue"></param> public void SetMapSize(long newValue) { if (autoReduceMapSizeIn32BitProcess && (IntPtr.Size == 4) && (newValue > int.MaxValue)) newValue = int.MaxValue; RunChecked((handle) => DbLib.mdb_env_set_mapsize(handle, (IntPtr)newValue)); } uint maxDatabases; /// <summary> /// Set/get the maximum number of named databases for the environment. /// This function is only needed if multiple databases will be used in the environment. /// Simpler applications that use the environment as a single unnamed database can ignore this option. /// This function may only be called after mdb_env_create() and before mdb_env_open(). /// Currently a moderate number of slots are cheap but a huge number gets expensive: 7-120 words per transaction, /// and every mdb_dbi_open() does a linear search of the opened slots. /// </summary> public int MaxDatabases { get { CheckDisposed(); return unchecked((int)maxDatabases); } set { RunChecked((handle) => DbLib.mdb_env_set_maxdbs(handle, unchecked((uint)value))); maxDatabases = unchecked((uint)value); } } /// <summary> /// This defines the number of slots in the lock table that is used to track readers in the the environment. /// The default is 126. Starting a read-only transaction normally ties a lock table slot to the current thread /// until the environment closes or the thread exits. If MDB_NOTLS is in use, mdb_txn_begin() instead /// ties the slot to the MDB_txn object until it or the MDB_env object is destroyed. /// This function may only be called after mdb_env_create() and before mdb_env_open(). /// </summary> public int MaxReaders { get => unchecked((int)GetChecked((IntPtr handle, out uint value) => DbLib.mdb_env_get_maxreaders(handle, out value))); set => RunChecked((handle) => DbLib.mdb_env_set_maxreaders(handle, unchecked((uint)value))); } /// <summary> /// Set environment flags. /// This may be used to set some flags in addition to those from mdb_env_open(), or to unset these flags. /// If several threads change the flags at the same time, the result is undefined. /// </summary> /// <param name="options">Option flags to set, bitwise OR'ed together.</param> /// <param name="onoff">A <c>true</c> value sets the flags, <c>false</c> clears them.</param> public void SetOptions(LmdbEnvironmentOptions options, bool onoff) { RunChecked((handle) => DbLib.mdb_env_set_flags(handle, options, onoff)); } /// <summary> /// Return information about the LMDB environment. /// </summary> public LmdbEnvironmentOptions GetOptions() { return GetChecked((IntPtr handle, out LmdbEnvironmentOptions value) => DbLib.mdb_env_get_flags(handle, out value)); } /// <summary> /// Return information about the LMDB environment. /// </summary> public LmdbEnvironmentInfo GetInfo() { return GetChecked((IntPtr handle, out LmdbEnvironmentInfo value) => DbLib.mdb_env_info(handle, out value)); } /// <summary> /// Return statistics about the LMDB environment. /// </summary> /// <returns></returns> public Statistics GetStats() { return GetChecked((IntPtr handle, out Statistics value) => DbLib.mdb_env_stat(handle, out value)); } /// <summary> /// Get the maximum size of keys and MDB_DUPSORT data we can write. /// Depends on the compile-time constant MDB_MAXKEYSIZE.Default 511. See MDB_val. /// </summary> public int GetMaxKeySize() { var handle = CheckDisposed(); return DbLib.mdb_env_get_maxkeysize(handle); } /// <summary> /// Return the path that was used in mdb_env_open(). /// </summary> public string GetPath() { return GetChecked((IntPtr handle, out string value) => DbLib.mdb_env_get_path(handle, out value)); } #endregion /// <summary> /// Open an environment handle. Do not open multiple times in the same process. /// If this function fails, mdb_env_close() must be called to discard the MDB_env handle. /// </summary> /// <param name="path">The directory in which the database files reside. This directory must already exist and be writable.</param> /// <param name="options">Special options for this environment. See <see cref="LmdbEnvironmentOptions"/>. /// This parameter must be set to 0 or by bitwise OR'ing together one or more of the values. /// Flags set by mdb_env_set_flags() are also used.</param> /// <param name="fileMode">The UNIX permissions to set on created files and semaphores. This parameter is ignored on Windows.</param> public void Open(string path, LmdbEnvironmentOptions options = LmdbEnvironmentOptions.None, UnixFileModes fileMode = UnixFileModes.Default) { RunChecked((handle) => DbLib.mdb_env_open(handle, path, options, fileMode)); } /// <summary> /// Close the environment and release the memory map. Same as Dispose(). /// Only a single thread may call this function. All transactions, databases, and cursors must already be closed /// before calling this function. Attempts to use any such handles after calling this function will cause a SIGSEGV. /// The environment handle will be freed and must not be used again after this call. /// </summary> public void Close() { Dispose(); } /// <summary> /// Flush the data buffers to disk. Data is always written to disk when mdb_txn_commit() is called, /// but the operating system may keep it buffered.LMDB always flushes the OS buffers upon commit as well, /// unless the environment was opened with MDB_NOSYNC or in part MDB_NOMETASYNC. /// This call is not valid if the environment was opened with MDB_RDONLY. /// </summary> /// <param name="force"> /// If <c>true</c>, force a synchronous flush. Otherwise if the environment has the MDB_NOSYNC flag set /// the flushes will be omitted, and with MDB_MAPASYNC they will be asynchronous. /// </param> public void Sync(bool force) { RunChecked((handle) => DbLib.mdb_env_sync(handle, force)); } //TODO expose mdb_reader_list() and mdb_reader_check() #region Databases and Transactions DatabaseTransaction activeDbTxn; readonly object dbTxnLock = new object(); readonly ConcurrentDictionary<IntPtr, Transaction> transactions = new ConcurrentDictionary<IntPtr, Transaction>(); readonly Dictionary<string, Database> databases = new Dictionary<string, Database>(StringComparer.OrdinalIgnoreCase); /// <summary>Returns database by name.</summary> public Database this[string name] { get { lock (dbTxnLock) { return databases[name]; } } } /// <summary>Enumerates databases in the environment.</summary> public IEnumerable<Database> Databases { get { lock (dbTxnLock) { return databases.Values; } } } void TransactionDisposed(IntPtr txnId) { transactions.TryRemove(txnId, out Transaction value); } void DatabaseTransactionClosed(IntPtr txnId) { lock (dbTxnLock) { activeDbTxn = null; } } void DatabaseDisposed(Database db) { lock (dbTxnLock) { databases.Remove(db.Name); } } (IntPtr txn, IntPtr txnId) BeginTransactionInternal(TransactionModes modes, Transaction parent) { var parentTxn = parent?.Handle ?? IntPtr.Zero; var txn = GetChecked((IntPtr handle, out IntPtr value) => DbLib.mdb_txn_begin(handle, parentTxn, modes, out value)); var txnId = DbLib.mdb_txn_id(txn); return (txn, txnId); } /// <summary> /// Create a transaction for use with the environment. /// The transaction handle may be discarded using mdb_txn_abort() or mdb_txn_commit(). /// Note: A transaction and its cursors must only be used by a single thread, and a thread may only have a single transaction at a time. /// If MDB_NOTLS is in use, this does not apply to read-only transactions. /// Cursors may not span transactions. /// </summary> /// <param name="modes">Special options for this transaction. This parameter must be set to 0 or by bitwise OR'ing together.</param> /// <param name="parent"> /// If this parameter is non-NULL, the new transaction will be a nested transaction, with the transaction /// indicated by parent as its parent. Transactions may be nested to any level. /// A parent transaction and its cursors may not issue any other operations than /// mdb_txn_commit and mdb_txn_abort while it has active child transactions. /// </param> /// <returns>New transaction instance.</returns> public Transaction BeginTransaction(TransactionModes modes = TransactionModes.None, Transaction parent = null) { var (txn, txnId) = BeginTransactionInternal(modes, parent); Transaction result; bool checkConcurrent = true; if ((modes & TransactionModes.ReadOnly) == 0) { result = new Transaction(txn, parent, TransactionDisposed); } else { result = new ReadOnlyTransaction(txn, parent, TransactionDisposed); var opts = GetOptions(); if (opts.HasFlag(LmdbEnvironmentOptions.NoThreadLocalStorage)) checkConcurrent = false; } if (!transactions.TryAdd(txnId, result) & checkConcurrent) { // no smart boolean evaluation! DbLib.mdb_txn_abort(txn); throw new LmdbException($"Transaction with same Id {txnId} exists already."); } return result; } /// <summary> /// Creates a <see cref="ReadOnlyTransaction"/>. The <see cref="TransactionModes.ReadOnly"/> flag will be set automatically. /// For details, see <see cref="BeginTransaction(TransactionModes, Transaction)"/>. /// </summary> public ReadOnlyTransaction BeginReadOnlyTransaction(TransactionModes modes = TransactionModes.None, Transaction parent = null) { modes = modes | TransactionModes.ReadOnly; return (ReadOnlyTransaction)BeginTransaction(modes, parent); } /// <summary> /// Create a transaction that allows opening databases in the environment. <see cref="BeginTransaction"/>. /// A newly opened database handle will be private to the transaction until the transaction is successfully committed. /// If the transaction is aborted the handle will be closed automatically. /// After a successful commit the handle will reside in the shared environment, and may be used by other transactions. /// The OpenDatabase function must not be called from multiple concurrent transactions in the same process. /// A transaction that uses that function must finish (either commit or abort) before any other transaction in the process /// may use the OpenDatabase function, therefore only one such transaction is allowed to be active in the environment at a time. /// </summary> /// <param name="modes">Special options for this transaction..</param> /// <param name="parent">If this parameter is non-NULL, the new transaction will be a nested transaction.</param> /// <returns>New transaction instance.</returns> public DatabaseTransaction BeginDatabaseTransaction(TransactionModes modes, Transaction parent = null) { if ((modes & TransactionModes.ReadOnly) != 0) throw new LmdbException("An OpenDbTransaction must not be read-only"); lock (dbTxnLock) { if (activeDbTxn != null) throw new LmdbException("Only one OpenDbTransaction can be active at a time."); var (txn, txnId) = BeginTransactionInternal(modes, parent); return new DatabaseTransaction(txn, parent, DatabaseTransactionClosed, databases, DatabaseDisposed); } } #endregion #region Unmanaged Resources // access to properly aligned types of size "native int" is atomic! IntPtr env; readonly GCHandle instanceHandle; internal IntPtr Handle => env; #endregion #region IDisposable Support void ThrowDisposed() { throw new ObjectDisposedException(this.GetType().Name); } /// <summary> /// Returns Environment handle. /// Throws if Environment handle is already closed/disposed of. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] protected IntPtr CheckDisposed() { // avoid multiple volatile memory access Interlocked.MemoryBarrier(); IntPtr result = this.env; Interlocked.MemoryBarrier(); if (result == IntPtr.Zero) ThrowDisposed(); return result; } /// <summary> /// Returns if Environment handle is closed/disposed. /// </summary> public bool IsDisposed { get { Interlocked.MemoryBarrier(); bool result = env == IntPtr.Zero; return result; } } /// <summary> /// Implementation of Dispose() pattern. See <see cref="Dispose()"/>. /// </summary> /// <param name="disposing"><c>true</c> if explicity disposing (finalizer not run), <c>false</c> if disposed from finalizer.</param> protected virtual void Dispose(bool disposing) { var handle = Interlocked.Exchange(ref env, IntPtr.Zero); // if the env handle was valid before we cleared it, lets close the handle if (handle != IntPtr.Zero) { if (disposing) { // dispose managed state (managed objects). foreach (var txEntry in transactions) { txEntry.Value.Dispose(); // this will also close the cursors owened by the transaction } lock (dbTxnLock) { activeDbTxn?.Dispose(); // It is very rarely necessary to close a database handle, and in general they should just be left open. // Therefore we just set the database handle to 0 when the environment is Disposed(), so that // using the Database instance will raise the appropriate exception foreach (var dbEntry in databases) { dbEntry.Value.ClearHandle(); } } } // free unmanaged resources DbLib.mdb_env_close(handle); } if (instanceHandle.IsAllocated) instanceHandle.Free(); // set large fields to null. transactions.Clear(); lock (dbTxnLock) { activeDbTxn = null; databases.Clear(); } } /// <summary> /// Finalizer. Releases unmanaged resources. /// </summary> ~LmdbEnvironment() { Dispose(false); } /// <summary> /// Close the environment and release the memory map. Same as Close(). /// Only a single thread may call this function. /// The environment handle will be freed and must not be used again after this call. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
47.846652
149
0.616666
[ "MIT" ]
kwaclaw/KdSoft.Lmdb
Lmdb/LmdbEnvironment.cs
22,155
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace MappingApplication { class PageNode { private int m_size; private MPoint m_position; private Page m_Page; private PageNode m_parent; private Font m_font; public int Index; public int Size { get {return m_size;}} public PageNode Parent { get { return m_parent; } } public bool Root { get { return m_parent == null; } } public MPoint Position { get { return m_position; } set { m_position = value; } } public PageNode(Page Page, PageNode Parent) { m_Page = Page; m_parent = Parent; m_size = 0; m_position = new MPoint(0, 0); m_font = new Font("Calibri", 12, FontStyle.Regular); } public PageNode[] GetPageLinks() { Page[] temp = m_Page.GetLinks(); PageNode[] newnodes = new PageNode[temp.Length]; int i = 0; foreach (Page p in temp) { newnodes[i] = new PageNode(p, this); i++; } m_size = temp.Length; return newnodes; } public override string ToString() { return m_Page.Title; } public SizeF StringSize(Graphics g) { return g.MeasureString(m_Page.Title, m_font); } public void SetDot(MPoint Origin, ref Bitmap bmp) { try { Graphics g = Graphics.FromImage(bmp); SizeF s = StringSize(g); MPoint pos = m_position + Origin - new MPoint(s.Width / 2, (s.Height) / 2); g.DrawRectangle(Pens.Black, pos.iX, pos.iY, s.Width + 2, s.Height + 1); pos += 1; g.FillRectangle(Brushes.White, pos.iX, pos.iY, s.Width, s.Height); pos -= 1; g.DrawString(m_Page.Title, m_font, Brushes.Black, pos.PointF()); } catch { } } } }
29.918919
92
0.494128
[ "Apache-2.0" ]
HaanstootZA/DotNet-Playground
MappingApplication/MappingApplication/Bck/PageNode.cs
2,216
C#
using System; using AGO.Core.Migration; using AGO.Tasks.Model.Dictionary; using AGO.Tasks.Model.Task; using FluentMigrator; namespace AGO.Tasks.Migrations { /// <summary> /// Первая миграция - основные таблицы и связи /// </summary> [MigrationVersion(2013, 09, 16, 01), Tags(MigrationTags.ProjectDb)] public class TasksBootstrapMigration: Migration { internal const string MODULE_SCHEMA = "Tasks"; public override void Up() { var provider = ApplicationContext as string; // ReSharper disable once InconsistentNaming var use_citext = provider != null && provider.StartsWith("postgres", StringComparison.InvariantCultureIgnoreCase); Create.SecureModelTable<TaskTypeModel>() .WithValueColumn<TaskTypeModel>(m => m.ProjectCode, use_citext) .WithValueColumn<TaskTypeModel>(m => m.Name, use_citext); Create.SecureModelTable<TaskModel>() .WithValueColumn<TaskModel>(m => m.ProjectCode, use_citext) .WithValueColumn<TaskModel>(m => m.SeqNumber, use_citext) .WithValueColumn<TaskModel>(m => m.InternalSeqNumber) .WithValueColumn<TaskModel>(m => m.Status) .WithValueColumn<TaskModel>(m => m.Priority) .WithRefColumn<TaskModel>(m => m.TaskType) .WithValueColumn<TaskModel>(m => m.Content, use_citext) .WithValueColumn<TaskModel>(m => m.Note, use_citext) .WithValueColumn<TaskModel>(m => m.DueDate) .WithValueColumn<TaskModel>(m => m.EstimatedTime); Create.SecureModelTable<TaskStatusHistoryModel>() .WithValueColumn<TaskStatusHistoryModel>(m => m.Start) .WithValueColumn<TaskStatusHistoryModel>(m => m.Finish) .WithRefColumn<TaskStatusHistoryModel>(m => m.Task) .WithValueColumn<TaskStatusHistoryModel>(m => m.Status); Create.SecureModelTable<TaskExecutorModel>() .WithRefColumn<TaskExecutorModel>(m => m.Task) .WithRefColumn<TaskExecutorModel>(m => m.Executor); Create.SecureModelTable<TaskAgreementModel>() .WithRefColumn<TaskAgreementModel>(m => m.Task) .WithRefColumn<TaskAgreementModel>(m => m.Agreemer) .WithValueColumn<TaskAgreementModel>(m => m.DueDate) .WithValueColumn<TaskAgreementModel>(m => m.AgreedAt) .WithValueColumn<TaskAgreementModel>(m => m.Done) .WithValueColumn<TaskAgreementModel>(m => m.Comment, use_citext); Create.SecureModelTable<TaskToTagModel>() .WithRefColumn<TaskToTagModel>(m => m.Task) .WithRefColumn<TaskToTagModel>(m => m.Tag); Alter.ModelTable<TaskCustomPropertyModel>() .AddRefColumn<TaskCustomPropertyModel>(m => m.Task); Create.SecureModelTable<TaskFileModel>() .WithValueColumn<TaskFileModel>(m => m.Name, use_citext) .WithValueColumn<TaskFileModel>(m => m.ContentType, use_citext) .WithValueColumn<TaskFileModel>(m => m.Size) .WithValueColumn<TaskFileModel>(m => m.Path) .WithValueColumn<TaskFileModel>(m => m.Uploaded) .WithRefColumn<TaskFileModel>(m => m.Owner); Create.SecureModelTable<TaskTimelogEntryModel>() .WithRefColumn<TaskTimelogEntryModel>(m => m.Task) .WithRefColumn<TaskTimelogEntryModel>(m => m.Member) .WithValueColumn<TaskTimelogEntryModel>(m => m.Time) .WithValueColumn<TaskTimelogEntryModel>(m => m.Comment, use_citext); Create.SecureModelTable<TaskCommentModel>() .WithRefColumn<TaskCommentModel>(m => m.Task) .WithValueColumn<TaskCommentModel>(m => m.Text); } public override void Down() { Delete.ModelTable<TaskCommentModel>(); Delete.ModelTable<TaskFileModel>(); Delete.ModelTable<TaskTimelogEntryModel>(); Delete.ModelTable<TaskToTagModel>(); Delete.ModelTable<TaskStatusHistoryModel>(); Delete.ModelTable<TaskExecutorModel>(); Delete.ModelTable<TaskAgreementModel>(); Delete.ModelTable<TaskModel>(); Delete.ModelTable<TaskTypeModel>(); Delete.Column<TaskCustomPropertyModel>(m => m.Task); } } }
42.520408
117
0.673146
[ "MIT" ]
olegsmetanin/apinet-server
AGO.Tasks/Migrations/TasksBootstrapMigration.cs
4,204
C#
namespace StardewMods.FuryCore.Models.GameObjects.Storages; using System; using System.Collections.Generic; using System.Linq; using StardewMods.FuryCore.Interfaces.GameObjects; using StardewValley; using StardewValley.Menus; /// <inheritdoc cref="StardewMods.FuryCore.Interfaces.GameObjects.IStorageContainer" /> public abstract class StorageContainer : GameObject, IStorageContainer { /// <summary> /// Initializes a new instance of the <see cref="StorageContainer" /> class. /// </summary> /// <param name="context">The source object.</param> /// <param name="getCapacity">A get method for the actual capacity of the storage.</param> /// <param name="getItems">A get method for the item in storage.</param> /// <param name="getModData">A get method for the mod data of the object.</param> protected StorageContainer(object context, Func<int> getCapacity, Func<IList<Item>> getItems, Func<ModDataDictionary> getModData) : base(context) { this.GetCapacity = getCapacity; this.GetItems = getItems; this.GetModData = getModData; } /// <summary> /// Initializes a new instance of the <see cref="StorageContainer" /> class. /// </summary> /// <param name="context">The source object.</param> /// <param name="getModData">A get method for the mod data of the object.</param> protected StorageContainer(object context, Func<ModDataDictionary> getModData) : base(context) { this.GetModData = getModData; } /// <inheritdoc /> public virtual int Capacity { get => this.GetCapacity.Invoke(); } /// <inheritdoc /> public virtual IList<Item> Items { get => this.GetItems.Invoke(); } /// <inheritdoc /> public override ModDataDictionary ModData { get => this.GetModData.Invoke(); } private Func<int> GetCapacity { get; } private Func<IList<Item>> GetItems { get; } private Func<ModDataDictionary> GetModData { get; } /// <inheritdoc /> public virtual Item AddItem(Item item) { item.resetState(); this.ClearNulls(); foreach (var existingItem in this.Items.Where(existingItem => existingItem.canStackWith(item))) { item.Stack = existingItem.addToStack(item); if (item.Stack <= 0) { return null; } } if (this.Items.Count < this.Capacity) { this.Items.Add(item); return null; } return item; } /// <inheritdoc /> public virtual void ClearNulls() { for (var index = this.Items.Count - 1; index >= 0; index--) { if (this.Items[index] is null) { this.Items.RemoveAt(index); } } } /// <inheritdoc /> public virtual void GrabInventoryItem(Item item, Farmer who) { if (item.Stack == 0) { item.Stack = 1; } var tmp = this.AddItem(item); if (tmp == null) { who.removeItemFromInventory(item); } else { tmp = who.addItemToInventory(tmp); } this.ClearNulls(); var oldId = Game1.activeClickableMenu.currentlySnappedComponent != null ? Game1.activeClickableMenu.currentlySnappedComponent.myID : -1; this.ShowMenu(); ((ItemGrabMenu)Game1.activeClickableMenu).heldItem = tmp; if (oldId != -1) { Game1.activeClickableMenu.currentlySnappedComponent = Game1.activeClickableMenu.getComponentWithID(oldId); Game1.activeClickableMenu.snapCursorToCurrentSnappedComponent(); } } /// <inheritdoc /> public virtual void GrabStorageItem(Item item, Farmer who) { if (who.couldInventoryAcceptThisItem(item)) { this.Items.Remove(item); this.ClearNulls(); this.ShowMenu(); } } /// <inheritdoc /> public virtual void ShowMenu() { Game1.activeClickableMenu = new ItemGrabMenu( this.Items, false, true, InventoryMenu.highlightAllItems, this.GrabInventoryItem, null, this.GrabStorageItem, false, true, true, true, true, 1, null, -1, this.Context); } }
28.320755
144
0.579614
[ "MIT" ]
KRISSzxc/StardewMods
FuryCore/Models/GameObjects/Storages/StorageContainer.cs
4,505
C#
using System; using System.Linq; using Newtonsoft.Json; using Sora.Enumeration; namespace Sora.Entities.Segment.DataModel; /// <summary> /// <para>自定义转发节点</para> /// <para>仅用于发送</para> /// </summary> public sealed record CustomNode { /// <summary> /// 转发消息Id /// </summary> [JsonProperty(PropertyName = "id", NullValueHandling = NullValueHandling.Ignore)] public string MessageId { get; internal set; } /// <summary> /// 发送者显示名字 /// </summary> [JsonProperty(PropertyName = "name", NullValueHandling = NullValueHandling.Ignore)] public string Name { get; internal set; } /// <summary> /// 发送者QQ号 /// </summary> [JsonProperty(PropertyName = "uin", NullValueHandling = NullValueHandling.Ignore)] public string UserId { get; internal set; } /// <summary> /// 具体消息 /// </summary> [JsonProperty(PropertyName = "content", NullValueHandling = NullValueHandling.Ignore)] internal dynamic Messages { get; set; } /// <summary> /// 转发时间 /// </summary> [JsonProperty(PropertyName = "time", NullValueHandling = NullValueHandling.Ignore)] internal string Time { get; set; } /// <summary> /// 构造自定义节点 /// </summary> /// <param name="messageId">消息ID</param> public CustomNode(int messageId) { MessageId = messageId.ToString(); Name = null; UserId = null; Messages = null; Time = null; } /// <summary> /// 构造自定义节点q /// </summary> /// <param name="name">发送者名</param> /// <param name="userId">发送者ID</param> /// <param name="customMessage">消息段</param> /// <param name="time">消息段转发时间</param> public CustomNode(string name, long userId, MessageBody customMessage, DateTimeOffset? time = null) { MessageId = null; Name = name; UserId = userId.ToString(); Messages = customMessage.Where(msg => msg.MessageType != SegmentType.Ignore) .Select(msg => msg.ToOnebotMessage()) .ToList(); Time = $"{time?.ToUnixTimeSeconds() ?? DateTimeOffset.Now.ToUnixTimeSeconds()}"; } /// <summary> /// 构造自定义节点 /// </summary> /// <param name="name">发送者名</param> /// <param name="userId">发送者ID</param> /// <param name="message">纯文本消息</param> /// <param name="time">消息段转发时间</param> public CustomNode(string name, long userId, string message, DateTimeOffset? time = null) { MessageId = null; Name = name; UserId = userId.ToString(); Messages = message; Time = $"{time?.ToUnixTimeSeconds() ?? DateTimeOffset.Now.ToUnixTimeSeconds()}"; } }
30.288889
103
0.588041
[ "Apache-2.0" ]
CBGan/Sora
Sora/Entities/Segment/DataModel/CustomNode.cs
2,914
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Threading; using System.Dynamic.Utils; using AstUtils = System.Linq.Expressions.Interpreter.Utils; namespace System.Linq.Expressions.Interpreter { internal sealed class LightLambdaCompileEventArgs : EventArgs { public Delegate Compiled { get; private set; } internal LightLambdaCompileEventArgs(Delegate compiled) { Compiled = compiled; } } public partial class LightLambda { private readonly IStrongBox[] _closure; private readonly Interpreter _interpreter; #if NO_FEATURE_STATIC_DELEGATE private static readonly CacheDict<Type, Func<LightLambda, Delegate>> _runCache = new CacheDict<Type, Func<LightLambda, Delegate>>(100); #endif // Adaptive compilation support private readonly LightDelegateCreator _delegateCreator; internal LightLambda(LightDelegateCreator delegateCreator, IStrongBox[] closure) { _delegateCreator = delegateCreator; _closure = closure; _interpreter = delegateCreator.Interpreter; } #if NO_FEATURE_STATIC_DELEGATE private static Func<LightLambda, Delegate> GetRunDelegateCtor(Type delegateType) { lock (_runCache) { Func<LightLambda, Delegate> fastCtor; if (_runCache.TryGetValue(delegateType, out fastCtor)) { return fastCtor; } return MakeRunDelegateCtor(delegateType); } } private static Func<LightLambda, Delegate> MakeRunDelegateCtor(Type delegateType) { var method = delegateType.GetMethod("Invoke"); var paramInfos = method.GetParameters(); Type[] paramTypes; string name = "Run"; if (paramInfos.Length >= MaxParameters) { return null; } if (method.ReturnType == typeof(void)) { name += "Void"; paramTypes = new Type[paramInfos.Length]; } else { paramTypes = new Type[paramInfos.Length + 1]; paramTypes[paramTypes.Length - 1] = method.ReturnType; } MethodInfo runMethod; if (method.ReturnType == typeof(void) && paramTypes.Length == 2 && paramInfos[0].ParameterType.IsByRef && paramInfos[1].ParameterType.IsByRef) { runMethod = typeof(LightLambda).GetMethod("RunVoidRef2", BindingFlags.NonPublic | BindingFlags.Instance); paramTypes[0] = paramInfos[0].ParameterType.GetElementType(); paramTypes[1] = paramInfos[1].ParameterType.GetElementType(); } else if (method.ReturnType == typeof(void) && paramTypes.Length == 0) { runMethod = typeof(LightLambda).GetMethod("RunVoid0", BindingFlags.NonPublic | BindingFlags.Instance); } else { for (int i = 0; i < paramInfos.Length; i++) { paramTypes[i] = paramInfos[i].ParameterType; if (paramTypes[i].IsByRef) { return null; } } #if FEATURE_MAKE_RUN_METHODS if (DelegateHelpers.MakeDelegate(paramTypes) == delegateType) { name = "Make" + name + paramInfos.Length; MethodInfo ctorMethod = typeof(LightLambda).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(paramTypes); return _runCache[delegateType] = (Func<LightLambda, Delegate>)ctorMethod.CreateDelegate(typeof(Func<LightLambda, Delegate>)); } #endif runMethod = typeof(LightLambda).GetMethod(name + paramInfos.Length, BindingFlags.NonPublic | BindingFlags.Instance); } /* try { DynamicMethod dm = new DynamicMethod("FastCtor", typeof(Delegate), new[] { typeof(LightLambda) }, typeof(LightLambda), true); var ilgen = dm.GetILGenerator(); ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldftn, runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod); ilgen.Emit(OpCodes.Newobj, delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) })); ilgen.Emit(OpCodes.Ret); return _runCache[delegateType] = (Func<LightLambda, Delegate>)dm.CreateDelegate(typeof(Func<LightLambda, Delegate>)); } catch (SecurityException) { }*/ // we don't have permission for restricted skip visibility dynamic methods, use the slower Delegate.CreateDelegate. var targetMethod = runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod; return _runCache[delegateType] = lambda => targetMethod.CreateDelegate(delegateType, lambda); } //TODO enable sharing of these custom delegates private Delegate CreateCustomDelegate(Type delegateType) { //PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Synchronously compiling a custom delegate"); var method = delegateType.GetMethod("Invoke"); var paramInfos = method.GetParameters(); var parameters = new ParameterExpression[paramInfos.Length]; var parametersAsObject = new Expression[paramInfos.Length]; bool hasByRef = false; for (int i = 0; i < paramInfos.Length; i++) { ParameterExpression parameter = Expression.Parameter(paramInfos[i].ParameterType, paramInfos[i].Name); hasByRef = hasByRef || paramInfos[i].ParameterType.IsByRef; parameters[i] = parameter; parametersAsObject[i] = Expression.Convert(parameter, typeof(object)); } var data = Expression.NewArrayInit(typeof(object), parametersAsObject); var dlg = new Func<object[], object>(Run); var dlgExpr = AstUtils.Constant(dlg); var argsParam = Expression.Parameter(typeof(object[]), "$args"); Expression body; if (method.ReturnType == typeof(void)) { body = Expression.Block(typeof(void), Expression.Invoke(dlgExpr, argsParam)); } else { body = Expression.Convert(Expression.Invoke(dlgExpr, argsParam), method.ReturnType); } if (hasByRef) { List<Expression> updates = new List<Expression>(); for (int i = 0; i < paramInfos.Length; i++) { if (paramInfos[i].ParameterType.IsByRef) { updates.Add( Expression.Assign( parameters[i], Expression.Convert( Expression.ArrayAccess(argsParam, Expression.Constant(i)), paramInfos[i].ParameterType.GetElementType() ) ) ); } } body = Expression.TryFinally(body, Expression.Block(typeof(void), updates)); } body = Expression.Block( method.ReturnType, new[] { argsParam }, Expression.Assign(argsParam, data), body ); var lambda = Expression.Lambda(delegateType, body, parameters); //return System.Linq.Expressions.Compiler.LambdaCompiler.Compile(lambda, null); throw new NotImplementedException("byref delegate"); } #endif internal Delegate MakeDelegate(Type delegateType) { #if !NO_FEATURE_STATIC_DELEGATE var method = delegateType.GetMethod("Invoke"); if (method.ReturnType == typeof(void)) { return System.Dynamic.Utils.DelegateHelpers.CreateObjectArrayDelegate(delegateType, RunVoid); } else { return System.Dynamic.Utils.DelegateHelpers.CreateObjectArrayDelegate(delegateType, Run); } #else Func<LightLambda, Delegate> fastCtor = GetRunDelegateCtor(delegateType); if (fastCtor != null) { return fastCtor(this); } else { return CreateCustomDelegate(delegateType); } #endif } private InterpretedFrame MakeFrame() { return new InterpretedFrame(_interpreter, _closure); } #if NO_FEATURE_STATIC_DELEGATE [EnableInvokeTesting] internal void RunVoidRef2<T0, T1>(ref T0 arg0, ref T1 arg1) { // copy in and copy out for today... var frame = MakeFrame(); frame.Data[0] = arg0; frame.Data[1] = arg1; var currentFrame = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(currentFrame); arg0 = (T0)frame.Data[0]; arg1 = (T1)frame.Data[1]; } } #endif public object Run(params object[] arguments) { var frame = MakeFrame(); for (int i = 0; i < arguments.Length; i++) { frame.Data[i] = arguments[i]; } var currentFrame = frame.Enter(); try { _interpreter.Run(frame); } finally { for (int i = 0; i < arguments.Length; i++) { arguments[i] = frame.Data[i]; } frame.Leave(currentFrame); } return frame.Pop(); } public object RunVoid(params object[] arguments) { var frame = MakeFrame(); for (int i = 0; i < arguments.Length; i++) { frame.Data[i] = arguments[i]; } var currentFrame = frame.Enter(); try { _interpreter.Run(frame); } finally { for (int i = 0; i < arguments.Length; i++) { arguments[i] = frame.Data[i]; } frame.Leave(currentFrame); } return null; } } }
35.859425
156
0.542944
[ "MIT" ]
bpschoch/corefx
src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs
11,224
C#
namespace Xamarin.Forms { public class WebNavigatingEventArgs : WebNavigationEventArgs { public WebNavigatingEventArgs(WebNavigationEvent navigationEvent, WebViewSource source, string url) : base(navigationEvent, source, url) { } public bool Cancel { get; set; } } }
25.272727
138
0.773381
[ "MIT" ]
07101994/Xamarin.Forms
Xamarin.Forms.Core/WebNavigatingEventArgs.cs
278
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using AdaptiveExpressions.Properties; using Newtonsoft.Json; using Microsoft.Bot.Builder.Dialogs; using Octokit; using System.ComponentModel.DataAnnotations; namespace GitHubClient.Enterprise.SearchIndexing { /// <summary> /// Action to call GitHubClient.Enterprise.SearchIndexing.Queue() API. /// </summary> public class Queue : GitHubAction { /// <summary> /// Class identifier. /// </summary> [JsonProperty("$kind")] public const string Kind = "GitHub.Enterprise.SearchIndexing.Queue"; /// <summary> /// Initializes a new instance of the <see cref="Queue"/> class. /// </summary> /// <param name="callerPath">Optional, source file full path.</param> /// <param name="callerLine">Optional, line number in source file.</param> public Queue([CallerFilePath] string callerPath = "", [CallerLineNumber] int callerLine = 0) { this.RegisterSourceLocation(callerPath, callerLine); } /// <summary> /// (REQUIRED) Gets or sets the expression for api argument owner. /// </summary> /// <value> /// The value or expression to bind to the value for the argument. /// </value> [Required()] [JsonProperty("owner")] public StringExpression Owner { get; set; } /// <summary> /// (OPTIONAL) Gets or sets the expression for api argument repository. /// </summary> /// <value> /// The value or expression to bind to the value for the argument. /// </value> [JsonProperty("repository")] public StringExpression Repository { get; set; } /// <inheritdoc/> protected override async Task<object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken)) { if (Owner != null && Repository != null) { var ownerValue = Owner.GetValue(dc.State); var repositoryValue = Repository.GetValue(dc.State); return await gitHubClient.Enterprise.SearchIndexing.Queue(ownerValue, repositoryValue).ConfigureAwait(false); } if (Owner != null) { var ownerValue = Owner.GetValue(dc.State); return await gitHubClient.Enterprise.SearchIndexing.Queue(ownerValue).ConfigureAwait(false); } throw new ArgumentNullException("Required [owner] arguments missing for GitHubClient.Enterprise.SearchIndexing.Queue"); } } }
37.621622
178
0.627874
[ "MIT" ]
coldplaying42/iciclecreek.bot
source/Libraries/Iciclecreek.Bot.Builder.Dialogs.Adaptive.GitHub/Actions/Enterprise/SearchIndexing/Queue.cs
2,784
C#
// Copyright 2018 by JCoder58. See License.txt for license // Auto-generated --- Do not modify. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UE4.Core; using UE4.CoreUObject; using UE4.CoreUObject.Native; using UE4.InputCore; using UE4.Native; #pragma warning disable CS0108 using UE4.UnrealEd.Native; using UE4.Engine; namespace UE4.UnrealEd { ///<summary>Configure settings for the 2D Level Editor</summary> public unsafe partial class LevelEditor2DSettings : DeveloperSettings { public bool bEnable2DWidget { get {return Main.GetGetBoolPropertyByName(this, "bEnable2DWidget"); } set {Main.SetGetBoolPropertyByName(this, "bEnable2DWidget", value); } } public bool bEnableSnapLayers { get {return Main.GetGetBoolPropertyByName(this, "bEnableSnapLayers"); } set {Main.SetGetBoolPropertyByName(this, "bEnableSnapLayers", value); } } //TODO: enum ELevelEditor2DAxis SnapAxis //TODO: array not UObject TArray SnapLayers static LevelEditor2DSettings() { StaticClass = Main.GetClass("LevelEditor2DSettings"); } internal unsafe LevelEditor2DSettings_fields* LevelEditor2DSettings_ptr => (LevelEditor2DSettings_fields*) ObjPointer.ToPointer(); ///<summary>Convert from IntPtr to UObject</summary> public static implicit operator LevelEditor2DSettings(IntPtr p) => UObject.Make<LevelEditor2DSettings>(p); ///<summary>Get UE4 Class</summary> public static Class StaticClass {get; private set;} ///<summary>Get UE4 Default Object for this Class</summary> public static LevelEditor2DSettings DefaultObject => Main.GetDefaultObject(StaticClass); ///<summary>Spawn an object of this class</summary> public static LevelEditor2DSettings New(UObject obj = null, Name name = new Name()) => Main.NewObject(StaticClass, obj, name); } }
44.954545
138
0.711325
[ "MIT" ]
UE4DotNet/Plugin
DotNet/DotNet/UE4/Generated/UnrealEd/LevelEditor2DSettings.cs
1,978
C#
using System; using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /tcb/getenvinfo 接口的响应。</para> /// </summary> public class TcbGetEnvironmentInfoResponse : WechatApiResponse { public static class Types { public class Environment { /// <summary> /// 获取或设置环境 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("env")] [System.Text.Json.Serialization.JsonPropertyName("env")] public string EnvironmentId { get; set; } = default!; /// <summary> /// 获取或设置环境别名。 /// </summary> [Newtonsoft.Json.JsonProperty("alias")] [System.Text.Json.Serialization.JsonPropertyName("alias")] public string Alias { get; set; } = default!; /// <summary> /// 获取或设置环境状态。 /// </summary> [Newtonsoft.Json.JsonProperty("status")] [System.Text.Json.Serialization.JsonPropertyName("status")] public string Status { get; set; } = default!; /// <summary> /// 获取或设置产品套餐 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("package_id")] [System.Text.Json.Serialization.JsonPropertyName("package_id")] public string? PackageId { get; set; } /// <summary> /// 获取或设置产品套餐名称。 /// </summary> [Newtonsoft.Json.JsonProperty("package_name")] [System.Text.Json.Serialization.JsonPropertyName("package_name")] public string? PackageName { get; set; } /// <summary> /// 获取或设置修改时间。 /// </summary> [Newtonsoft.Json.JsonProperty("update_time")] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.RFC3339DateTimeOffsetConverter))] [System.Text.Json.Serialization.JsonPropertyName("update_time")] [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Converters.RFC3339DateTimeOffsetConverter))] public DateTimeOffset UpdateTime { get; set; } = default!; /// <summary> /// 获取或设置创建时间。 /// </summary> [Newtonsoft.Json.JsonProperty("create_time")] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.RFC3339DateTimeOffsetConverter))] [System.Text.Json.Serialization.JsonPropertyName("create_time")] [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Converters.RFC3339DateTimeOffsetConverter))] public DateTimeOffset CreateTime { get; set; } = default!; } } /// <summary> /// 获取或设置环境列表。 /// </summary> [Newtonsoft.Json.JsonProperty("info_list")] [System.Text.Json.Serialization.JsonPropertyName("info_list")] public Types.Environment[] EnvironmentList { get; set; } = default!; } }
41.397436
130
0.547848
[ "MIT" ]
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/Tcb/ThirdPartyPlatforms/TcbGetEnvironmentInfoResponse.cs
3,407
C#
using System; using Medical; using System.Net.Http; using Anomalous.OSPlatform; using System.IO; using System.Runtime.InteropServices; using Anomalous.OSPlatform.Mac; using DentalSim; using Lecture; using AppKit; using ModernHttpClient; namespace AnomalousMedicalMac { class MainClass { static void Main(string[] args) { NSApplication.Init(); ServerConnection.HttpClientProvider = () => new HttpClient(new NativeMessageHandler()); MacRuntimePlatformInfo.Initialize(); OgrePlugin.OgreInterface.CompressedTextureSupport = OgrePlugin.CompressedTextureSupport.None; AnomalousController anomalous = null; try { anomalous = new AnomalousController() { PrimaryArchive = Path.Combine(FolderFinder.ExecutableFolder, "../Resources/AnomalousMedical.dat") }; anomalous.AddAdditionalPlugins += HandleAddAdditionalPlugins; anomalous.run(); } catch (Exception e) { Logging.Log.Default.printException(e); if (anomalous != null) { anomalous.saveCrashLog(); } MessageDialog.showErrorDialog(String.Format("{0} occured. Message: {1}.\nPlease see log file for more information", e.GetType().Name, e.Message), "Anomalous Medical Has Crashed"); MacRuntimePlatformInfo.AlertCrashing(); } finally { if (anomalous != null) { anomalous.Dispose(); } } } static void HandleAddAdditionalPlugins(AnomalousController anomalousController, StandaloneController controller) { controller.AtlasPluginManager.addPlugin(new PremiumBodyAtlasPlugin(controller) { AllowUninstall = false }); controller.AtlasPluginManager.addPlugin(new DentalSimPlugin() { AllowUninstall = false }); controller.AtlasPluginManager.addPlugin(new LecturePlugin() { AllowUninstall = false }); #if ALLOW_OVERRIDE controller.AtlasPluginManager.addPlugin(new Movement.MovementBodyAtlasPlugin() { AllowUninstall = false }); controller.AtlasPluginManager.addPlugin(new Developer.DeveloperAtlasPlugin(controller) { AllowUninstall = false }); controller.AtlasPluginManager.addPlugin(new EditorPlugin() { AllowUninstall = false }); #endif } } }
24.818182
183
0.729853
[ "MIT" ]
AnomalousMedical/Medical
AnomalousMedicalMac/Main.cs
2,186
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TextFileIO")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TextFileIO")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("13afd8b2-a029-4974-b3b9-071ccb354d2f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.513514
84
0.747118
[ "MIT" ]
VsIG-official/Study-Projects
Unity/Intermediate Object-Oriented Programming for Unity Games/1_week/TextFileIO/TextFileIO/Properties/AssemblyInfo.cs
1,391
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace OJS.Tools.OldDatabaseMigration { using System; using System.Collections.Generic; public partial class aspnet_Profile { public System.Guid UserId { get; set; } public string PropertyNames { get; set; } public string PropertyValuesString { get; set; } public byte[] PropertyValuesBinary { get; set; } public System.DateTime LastUpdatedDate { get; set; } public virtual aspnet_Users aspnet_Users { get; set; } } }
35.384615
84
0.557609
[ "MIT" ]
SveGeorgiev/OpenJudgeSystem
Open Judge System/Tools/OJS.Tools.OldDatabaseMigration/aspnet_Profile.cs
920
C#
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using mvc_minitwit.Data; using System; using System.Linq; namespace mvc_minitwit.Models { public static class SeedData { public static void Initialize(IServiceProvider serviceProvider) { using (var context = new MvcDbContext( serviceProvider.GetRequiredService<DbContextOptions<MvcDbContext>>())) { // Look for any messages. if (context.message.Any()) { Console.WriteLine("the db is not empty!") ; // DB has been seeded return; } else { Console.WriteLine("db it not found/or empty"); return; } //add something to db? } } } }
27.393939
87
0.52323
[ "Apache-2.0" ]
albertbethlowsky/DevOpsGroupH
mvc-minitwit/Models/SeedData.cs
904
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace FractalTree { /// <summary> /// A stationary branch. Forces cannot be applied to it. It is a line drawn onscreen by rotating and scaling a sprite between a start and end point. /// </summary> public class StationaryBranch : MonoBehaviour, Branch { /// <summary> /// Used by the default tree algorithm. Each branchings length is multiplied by this value. /// </summary> public static float LengthDegradation = 0.67f; /// <summary> /// Gets or sets the colonization direction. Used for space colonization tree generation. Defines the direction of the /// next branch in relation /// to nearby leaves. /// </summary> /// <value>The colonization dir.</value> public Vector2 colonizationDir { get; set; } /// <summary> /// Gets or sets the number of nearby colonizaion leaves. /// </summary> /// <value>The colonization leaf count.</value> public int colonizationLeafCount { get; set; } /// <summary> /// Gets the start position. /// </summary> /// <value>The start position.</value> public virtual Vector2 startPos { get; private set; } /// <summary> /// Gets the end position. /// </summary> /// <value>The end position.</value> public virtual Vector2 endPos { get; private set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="FractalTree.StationaryBranch"/> has branched. /// </summary> /// <value><c>true</c> if has branched; otherwise, <c>false</c>.</value> public bool hasBranched { get; set; } /// <summary> /// Sets the color of the branch sprite and updates the sprite renderer. /// </summary> /// <value>The color.</value> public Color color { set { UpdateColor (value); } } /// <summary> /// Pixels of line sprite / pixels per units. /// </summary> protected static readonly float SPRITE_SIZE = 100f / 100f; /// <summary> /// The width of the branch. /// </summary> protected float m_Width; /// <summary> /// The renderer associated with the branch. /// </summary> protected SpriteRenderer m_Renderer; protected virtual void Awake () { m_Renderer = GetComponent<SpriteRenderer> (); } /// <summary> /// Setup the specified owner, end, thickness and color. Used to create a branch that is attached to another branch. /// </summary> /// <param name="owner">The attached branch.</param> /// <param name="end">End.</param> /// <param name="thickness">Thickness.</param> /// <param name="color">Color.</param> public virtual void Setup (Branch owner, Vector2 end, float thickness, Color color) { Setup (owner.endPos, end, thickness, color, false); } /// <summary> /// Setup the specified owner, end, thickness and color. Used to create a branch that is attached to another branch /// that has its mass autogenerated based on line width. /// </summary> /// <param name="owner">Owner.</param> /// <param name="end">End.</param> /// <param name="thickness">Thickness.</param> /// <param name="color">Color.</param> /// <param name="autoMass">If set to <c>true</c> auto mass.</param> public virtual void Setup (Branch owner, Vector2 end, float thickness, Color color, bool autoMass) { Setup (owner.endPos, end, thickness, color, autoMass); } /// <summary> /// Setup the specified owner, end, thickness and color. Used to create a branch that is attached to another branch. /// </summary> /// <param name="owner">The attached branch.</param> /// <param name="end">End.</param> /// <param name="thickness">Thickness.</param> /// <param name="color">Color.</param> /// <param name="start">Start.</param> public virtual void Setup (Vector2 start, Vector2 end, float thickness, Color color) { Setup (start, end, thickness, color, false); } /// <summary> /// Setup the specified owner, end, thickness and color. Used to create a branch that is attached to another branch /// that has its mass autogenerated based on line width. /// </summary> /// <param name="owner">Owner.</param> /// <param name="end">End.</param> /// <param name="thickness">Thickness.</param> /// <param name="color">Color.</param> /// <param name="start">Start.</param> /// <param name="autoMass">If set to <c>true</c> auto mass.</param> public virtual void Setup (Vector2 start, Vector2 end, float thickness, Color color, bool autoMass) { this.m_Width = thickness; startPos = start; endPos = end; this.color = color; colonizationDir = end - start; colonizationLeafCount = 0; UpdateSprite (); UpdateColor (color); } /// <summary> /// Returns a new branch based on current branch angle plus parameter angle. /// </summary> /// <returns>The branching.</returns> /// <param name="angle">Angle.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public T DoBranching<T> (float angle) where T : Branch { var newBranch = ((GameObject)Instantiate (gameObject)).GetComponent<T> (); var dir = (endPos - startPos) * LengthDegradation; var dirRot = dir.Rotate (angle); var newEnd = endPos + dirRot; newBranch.Setup (this, newEnd, this.m_Width, m_Renderer.color); return newBranch; } /// <summary> /// Updates the sprite position, rotation, and scale in relation to the start and point. /// </summary> protected void UpdateSprite () { var heading = endPos - startPos; var distance = heading.magnitude; var direction = heading / distance; var centerPos = new Vector2 ( startPos.x + endPos.x, startPos.y + endPos.y) * 0.5f; m_Renderer.transform.position = centerPos; // angle float angle = Mathf.Atan2 (direction.y, direction.x) * Mathf.Rad2Deg; m_Renderer.transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward); //length m_Renderer.transform.localScale = new Vector3 (distance / SPRITE_SIZE + 0.0041f, m_Width, m_Renderer.transform.localScale.z); } /// <summary> /// Resets the colonization paramater. Used only for space colonization generation. /// </summary> public void DoColonizationReset() { colonizationDir = endPos - startPos; colonizationLeafCount = 0; } /// <summary> /// Updates the sprite renderer color. /// </summary> /// <param name="color">Color.</param> protected void UpdateColor (Color color) { m_Renderer.color = color; } } }
31.850242
149
0.650538
[ "MIT" ]
GandhiGames/fractal_trees_with_spring
fractal_tree/Assets/FT/Scripts/Branch/StationaryBranch.cs
6,595
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本: 4.0.30319.17929 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace WpfPagesApp.Properties { /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [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> /// 返回此类使用的、缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfPagesApp.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 为所有资源查找重写当前线程的 CurrentUICulture 属性, /// 方法是使用此强类型资源类。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
34.972222
178
0.559968
[ "MIT" ]
victoryckl/csharp
WpfPagesApp/Properties/Resources.Designer.cs
2,874
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BullsAndCows.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BullsAndCows.Tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("707360d5-dbf0-48d4-936f-8bc8e03fad11")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.081081
84
0.745919
[ "MIT" ]
TeamGotha/BullsAndCows
BullsAndCows.Tests/Properties/AssemblyInfo.cs
1,412
C#
using DotVVM.Framework.ViewModel; using System.Collections.Generic; namespace DotVVM.Samples.BasicSamples.ViewModels.ControlSamples.Literal { public class Literal_CollectionLengthViewModel : DotvvmViewModelBase { public List<string> MyCollection { get; set; } = new List<string>(); public string[] TestArray { get; set; } = new string[] { }; public void AddItemToCollection() { MyCollection.Add("Item"); TestArray = getTestArray(MyCollection.Count); } private string[] getTestArray(int length) { var a = new string[length]; return a; } } }
28.956522
76
0.623123
[ "Apache-2.0" ]
AMBULATUR/dotvvm
src/DotVVM.Samples.Common/ViewModels/ControlSamples/Literal/Literal_CollectionLenghtViewModel.cs
666
C#
using TONBRAINS.TONOPS.WebApp.Common; using System.Collections.Generic; namespace TONBRAINS.TONOPS.WebApp.Models.Nodes { /// <summary> /// View model for dropdowns node /// </summary> public class NodeDropdowns { /// <summary> /// Types node /// </summary> public IEnumerable<SelectListItem<int>> NodeTypes { get; set; } /// <summary> /// Deployment types node /// </summary> public IEnumerable<SelectListItem<int>> DeplymentTypes { get; set; } /// <summary> /// Credentials /// </summary> public IEnumerable<object> Credentials { get; set; } /// <summary> /// Operating Systems /// </summary> public IEnumerable<SelectListItem<string>> OperatingSystems { get; set; } /// <summary> /// Groups /// </summary> public IEnumerable<SelectListItem<string>> Groups { get; set; } public IEnumerable<SelectListItem<string>> Hosts { get; set; } public IEnumerable<object> ZabbixServers { get; set; } } }
25.860465
81
0.572842
[ "MIT" ]
mvkhokhlov/telegram_blockchain_devops
TONBRAINS.TONOPS.WebApp/Models/Nodes/NodeDropdowns.cs
1,114
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Bicep.Core.Diagnostics; using Bicep.Core.UnitTests.Assertions; using Bicep.Core.UnitTests.Utils; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Bicep.Core.IntegrationTests.Scenarios { [TestClass] public class ResourceListFunctionTests { [TestMethod] public void List_wildcard_function_on_resource_references() { var result = CompilationHelper.Compile(@" resource stg 'Microsoft.Storage/storageAccounts@2019-06-01' = { name: 'testacc' location: 'West US' kind: 'StorageV2' sku: { name: 'Standard_LRS' } } output pkStandard string = listKeys(stg.id, stg.apiVersion).keys[0].value output pkMethod string = stg.listKeys().keys[0].value output pkMethodVersionOverride string = stg.listKeys('2021-01-01').keys[0].value output pkMethodPayload string = stg.listKeys(stg.apiVersion, { key1: 'val1' }) "); result.Should().NotHaveAnyDiagnostics(); result.Template.Should().HaveValueAtPath("$.outputs['pkStandard'].value", "[listKeys(resourceId('Microsoft.Storage/storageAccounts', 'testacc'), '2019-06-01').keys[0].value]"); result.Template.Should().HaveValueAtPath("$.outputs['pkMethod'].value", "[listKeys(resourceId('Microsoft.Storage/storageAccounts', 'testacc'), '2019-06-01').keys[0].value]"); result.Template.Should().HaveValueAtPath("$.outputs['pkMethodVersionOverride'].value", "[listKeys(resourceId('Microsoft.Storage/storageAccounts', 'testacc'), '2021-01-01').keys[0].value]"); result.Template.Should().HaveValueAtPath("$.outputs['pkMethodPayload'].value", "[listKeys(resourceId('Microsoft.Storage/storageAccounts', 'testacc'), '2019-06-01', createObject('key1', 'val1'))]"); } [TestMethod] public void List_wildcard_function_on_cross_scope_resource_references() { var result = CompilationHelper.Compile(@" resource stg 'Microsoft.Storage/storageAccounts@2019-06-01' existing = { scope: resourceGroup('other') name: 'testacc' } output pkStandard string = listKeys(stg.id, stg.apiVersion).keys[0].value output pkMethod string = stg.listKeys().keys[0].value output pkMethodVersionOverride string = stg.listKeys('2021-01-01').keys[0].value output pkMethodPayload string = stg.listKeys(stg.apiVersion, { key1: 'val1' }) "); result.Should().NotHaveAnyDiagnostics(); result.Template.Should().HaveValueAtPath("$.outputs['pkStandard'].value", "[listKeys(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, 'other'), 'Microsoft.Storage/storageAccounts', 'testacc'), '2019-06-01').keys[0].value]"); result.Template.Should().HaveValueAtPath("$.outputs['pkMethod'].value", "[listKeys(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, 'other'), 'Microsoft.Storage/storageAccounts', 'testacc'), '2019-06-01').keys[0].value]"); result.Template.Should().HaveValueAtPath("$.outputs['pkMethodVersionOverride'].value", "[listKeys(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, 'other'), 'Microsoft.Storage/storageAccounts', 'testacc'), '2021-01-01').keys[0].value]"); result.Template.Should().HaveValueAtPath("$.outputs['pkMethodPayload'].value", "[listKeys(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, 'other'), 'Microsoft.Storage/storageAccounts', 'testacc'), '2019-06-01', createObject('key1', 'val1'))]"); } [TestMethod] public void Only_list_methods_are_permitted() { var result = CompilationHelper.Compile(@" resource stg 'Microsoft.Storage/storageAccounts@2019-06-01' existing = { name: 'testacc' } var allowed = { a: stg.list() b: stg.listA() c: stg.listTotallyMadeUpMethod() } var disallowed = { a: stg.lis() b: stg.lsit() c: stg.totallyMadeUpMethod() } "); result.Should().HaveDiagnostics(new[] { ("no-unused-vars", DiagnosticLevel.Warning, "Variable \"allowed\" is declared but never used."), ("no-unused-vars", DiagnosticLevel.Warning, "Variable \"disallowed\" is declared but never used."), ("BCP109", DiagnosticLevel.Error, "The type \"Microsoft.Storage/storageAccounts\" does not contain function \"lis\"."), ("BCP109", DiagnosticLevel.Error, "The type \"Microsoft.Storage/storageAccounts\" does not contain function \"lsit\"."), ("BCP109", DiagnosticLevel.Error, "The type \"Microsoft.Storage/storageAccounts\" does not contain function \"totallyMadeUpMethod\"."), }); } } }
49.885417
307
0.691167
[ "MIT" ]
AzureMentor/bicep
src/Bicep.Core.IntegrationTests/Scenarios/ResourceListFunctionTests.cs
4,789
C#
// <auto-generated> // 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 Gov.Lclb.Cllb.Interfaces { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Regardingobjectidadoxioapplicationlicenseechangesv10 operations. /// </summary> public partial class Regardingobjectidadoxioapplicationlicenseechangesv10 : IServiceOperations<DynamicsClient>, IRegardingobjectidadoxioapplicationlicenseechangesv10 { /// <summary> /// Initializes a new instance of the Regardingobjectidadoxioapplicationlicenseechangesv10 class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Regardingobjectidadoxioapplicationlicenseechangesv10(DynamicsClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DynamicsClient /// </summary> public DynamicsClient Client { get; private set; } /// <summary> /// Get regardingobjectid_adoxio_applicationlicenseechangesv10 from /// asyncoperations /// </summary> /// <param name='asyncoperationid'> /// key: asyncoperationid of asyncoperation /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>> GetWithHttpMessagesAsync(string asyncoperationid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (asyncoperationid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "asyncoperationid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("asyncoperationid", asyncoperationid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "asyncoperations({asyncoperationid})/regardingobjectid_adoxio_applicationlicenseechangesv10").ToString(); _url = _url.Replace("{asyncoperationid}", System.Uri.EscapeDataString(asyncoperationid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get regardingobjectid_adoxio_applicationlicenseechangesv10 from /// bulkdeletefailures /// </summary> /// <param name='bulkdeletefailureid'> /// key: bulkdeletefailureid of bulkdeletefailure /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>> Get1WithHttpMessagesAsync(string bulkdeletefailureid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (bulkdeletefailureid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "bulkdeletefailureid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("bulkdeletefailureid", bulkdeletefailureid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get1", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bulkdeletefailures({bulkdeletefailureid})/regardingobjectid_adoxio_applicationlicenseechangesv10").ToString(); _url = _url.Replace("{bulkdeletefailureid}", System.Uri.EscapeDataString(bulkdeletefailureid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get regardingobjectid_adoxio_applicationlicenseechangesv10 from /// mailboxtrackingfolders /// </summary> /// <param name='mailboxtrackingfolderid'> /// key: mailboxtrackingfolderid of mailboxtrackingfolder /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>> Get2WithHttpMessagesAsync(string mailboxtrackingfolderid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (mailboxtrackingfolderid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "mailboxtrackingfolderid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("mailboxtrackingfolderid", mailboxtrackingfolderid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get2", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "mailboxtrackingfolders({mailboxtrackingfolderid})/regardingobjectid_adoxio_applicationlicenseechangesv10").ToString(); _url = _url.Replace("{mailboxtrackingfolderid}", System.Uri.EscapeDataString(mailboxtrackingfolderid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get regardingobjectid_adoxio_applicationlicenseechangesv10 from /// processsessions /// </summary> /// <param name='processsessionid'> /// key: processsessionid of processsession /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>> Get3WithHttpMessagesAsync(string processsessionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (processsessionid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "processsessionid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("processsessionid", processsessionid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get3", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "processsessions({processsessionid})/regardingobjectid_adoxio_applicationlicenseechangesv10").ToString(); _url = _url.Replace("{processsessionid}", System.Uri.EscapeDataString(processsessionid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get regardingobjectid_adoxio_applicationlicenseechangesv10 from syncerrors /// </summary> /// <param name='syncerrorid'> /// key: syncerrorid of syncerror /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>> Get4WithHttpMessagesAsync(string syncerrorid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (syncerrorid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "syncerrorid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("syncerrorid", syncerrorid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get4", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "syncerrors({syncerrorid})/regardingobjectid_adoxio_applicationlicenseechangesv10").ToString(); _url = _url.Replace("{syncerrorid}", System.Uri.EscapeDataString(syncerrorid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioApplicationlicenseechangesv10>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
45.750289
378
0.572093
[ "Apache-2.0" ]
BrendanBeachBC/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/Regardingobjectidadoxioapplicationlicenseechangesv10.cs
39,574
C#
using UnityEngine; namespace Cryptoverse.Examples { public class ServiceExample : MonoBehaviour { public string ApiUrl = "http://api.cryptoverse.io"; ICache Cache; Service Service; void Awake() { // This GameObject will be used to run the coroutines required by the Service class, // so we make sure it doesn't get destroyed! Any GameObject that doesn't get destroyed // will work though. DontDestroyOnLoad(gameObject); // Create a cache, which is just a way to store data pulled from the server. Eventually // there should be a SqliteCache, since storing the blockchain in the memory will become // unfeasable. Cache = new MemoryCache(); // Create the Service, passing the API's URL, the cache, and turn on verbose logging, so // we can debug and see what's happening. This will create a lot of console spam though! Service = new Service(this, ApiUrl, Cache, true); // Initialize Service, this only needs to be done once and will automatically syncronize // the latest star logs. Since initialization is done asyncronously, you can provide an // event for it to call when it is done syncronizing. Service.Initialize(OnInitialized); } #region Events void OnInitialized(Status status) { // The status variable tells us whether initialization succeeded or failed. if (status != Status.Success) { Debug.LogError("Example initialize failed with result: "+status); return; } Debug.Log("Example initialize completed with result: "+status); // Now that the Service class has been initialized, we can make calls to the cache to // retrieve the information that was syncronized. All the calls are asyncronous so they // won't block Unity's main thread and cause crazy lag. Right now it's not an issue, but // it will be once we're using a Sqlite database and pulling megabytes of data at a time! Cache.ReadStarLogs(OnReadAllStarLogs); // No need to wait for the other task to finish, we can trigger another request to the // cache, and it will resolve it in whatever order is fastest. Cache.ReadStarLogsHighest(OnReadHighestStarLogs); // You can easily chain these commands together as well, using lambda statements or // regular methods. Enjoy! } void OnReadAllStarLogs(Status status, StarLog[] starLogs) { if (status != Status.Success) { Debug.LogError("Reading star logs from cache failed with result: "+status); return; } Debug.Log("There are " + starLogs.Length + " star logs in the cache"); } void OnReadHighestStarLogs(Status status, StarLog[] starLogs) { if (status != Status.Success) { Debug.LogError("Reading the highest star log from the cache failed with result: " + status); return; } if (starLogs.Length == 0) { Debug.Log("There are zero star logs in the cache"); } else { var first = starLogs[0]; if (starLogs.Length == 1) Debug.Log("There is one star log at height " + first.Height + " with a hash of " + first.Hash); else Debug.Log("There are multiple star logs at height " + first.Height + ", one of them has a hash of " + first.Hash); } } #endregion } }
38.349398
125
0.70311
[ "MIT" ]
Cryptoverse/cryptoverse-plugin-unity3d
Assets/Plugins/Cryptoverse/Examples/ServiceExample.cs
3,185
C#
namespace Gecko.WebIDL { using System; internal class DOMRect : WebIDLBase { public DOMRect(nsIDOMWindow globalWindow, nsISupports thisObject) : base(globalWindow, thisObject) { } public double X { get { return this.GetProperty<double>("x"); } set { this.SetProperty("x", value); } } public double Y { get { return this.GetProperty<double>("y"); } set { this.SetProperty("y", value); } } public double Width { get { return this.GetProperty<double>("width"); } set { this.SetProperty("width", value); } } public double Height { get { return this.GetProperty<double>("height"); } set { this.SetProperty("height", value); } } } }
19.857143
76
0.354916
[ "MIT" ]
haga-rak/Freezer
Freezer/GeckoFX/__Core/WebIDL/Generated/DOMRect.cs
1,251
C#
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using FSO.Client.UI.Controls; using FSO.Client.UI.Framework; using FSO.Client.UI.Model; using FSO.Client.Utils; using FSO.Common.Rendering.Framework.Model; using FSO.HIT; namespace FSO.Client.UI.Panels { /// <summary> /// A controller for messages. /// </summary> public class UIMessageController : UIContainer { public List<UIMessageGroup> MessageWindows; public List<EmailStore> PendingEmails; private bool soundAlt = true; /// <summary> /// Fired when an IM UIMessage element sends a message. Should be wired up to the server. /// If you need any more information than message and destination, feel free to edit in new functionality. /// </summary> public event MessageSendDelegate OnSendMessage; /// <summary> /// Fired when an Letter Compose UIMessage element sends a letter. Should be wired up to the server. /// If you need any more information than message and destination, feel free to edit in new functionality. /// </summary> public event LetterSendDelegate OnSendLetter; public UIMessageController() { MessageWindows = new List<UIMessageGroup>(); PendingEmails = new List<EmailStore>(); this.AddUpdateHook(new UpdateHookDelegate(MCUpdate)); } /// <summary> /// Fires OnSendMessage event with the passed message. /// </summary> public void SendMessage(string message, string GUID) { HITVM.Get().PlaySoundEvent(UISounds.CallSend); if (OnSendMessage != null) OnSendMessage(message, GUID); } /// <summary> /// Fires OnSendLetter event with the passed letter. /// </summary> public void SendLetter(string message, string subject, string destinationUser) { HITVM.Get().PlaySoundEvent(UISounds.LetterSend); if (OnSendLetter != null) OnSendLetter(message, subject, destinationUser); } /// <summary> /// Brings up a "You've got mail!" dialog and upon confirming that you want to see it, opens the message. /// If multiple messages are recieved while the dialog is open it will be updated. /// </summary> public void PassEmail(MessageAuthor sender, string subject, string message) { HITVM.Get().PlaySoundEvent(UISounds.LetterRecieve); //PendingEmails.Add(new EmailStore(sender, message)); OpenEmail(sender, subject, message); //will eventually show alert asking if you want to do this... } /// <summary> /// Opens mail without the confirmation dialog. Use when manually opening mail from the inbox. /// </summary> public void OpenEmail(MessageAuthor sender, string subject, string message) { bool GroupExisted = false; for (int i = 0; i < MessageWindows.Count; i++) { //Did conversation already exist? if (MessageWindows[i].name.Equals(sender.Author, StringComparison.InvariantCultureIgnoreCase)) { GroupExisted = true; //MessageWindows[i].AddMessage(message); break; } } if (!GroupExisted) { var group = new UIMessageGroup(UIMessageType.Read, sender, this); MessageWindows.Add(group); this.Add(group); group.SetEmail(subject, message); } ReorderIcons(); } /// <summary> /// Remove a UIMessageGroup from the Message UI. /// </summary> public void RemoveMessageGroup(UIMessageGroup grp) { MessageWindows.Remove(grp); this.Remove(grp); ReorderIcons(); } /// <summary> /// Get the first message group with the specified recipient name and type. /// </summary> private UIMessageGroup GetMessageGroup(string name, UIMessageType type) { for (int i = 0; i < MessageWindows.Count; i++) { var elem = MessageWindows.ElementAt(i); if (elem.name == name && elem.type == type) return elem; } return null; } /// <summary> /// Fix order of UIMessageGroup minimized icons. Called after every message minimize/restore/creation/deletion. /// </summary> public void ReorderIcons() { int pos = 0; for (int i = 0; i < MessageWindows.Count; i++) { var elem = MessageWindows.ElementAt(i); if (!elem.Shown) { elem.MoveIcon(pos++); } else { elem.MoveIcon(-1); } } } //WIP test stuff. needs Yes/No Alerts. public void MCUpdate(UpdateState update) { //Async(new AsyncHandler(hi)); } } public struct EmailStore { string name; string message; string subject; public EmailStore(string name, string subject, string message) { this.name = name; this.subject = subject; this.message = message; } } public delegate void MessageSendDelegate(string message, string GUID); public delegate void LetterSendDelegate(string message, string subject, string GUID); }
33.801136
119
0.576399
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Blayer98/FreeSO
TSOClient/tso.client/UI/Panels/UIMessageController.cs
5,951
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace AntMapGenerator { [System.Serializable] [CreateAssetMenu(fileName = "NewDataLayer", menuName = "Ant Map Generator/DataLayer", order = 362)] public class DataLayer : ScriptableObject { [SerializeField] MapDefinition definition; public MapDefinition Definition { get => definition; set => definition = value; } public int SizeX { get => definition.SizeX; } public int SizeY { get => definition.SizeY; } public BoundsInt Bounds { get => definition.Bounds; } int[,] data; public int this[int x, int y] { get { return data[x, y]; } set { data[x, y] = value; } } public int this[Vector2Int coord] { get { return this[coord.x, coord.y]; } set { this[coord.x, coord.y] = value; } } public bool Contains(int x, int y) { return definition.Contains(x, y); } public void ResetData() { data = new int[definition.SizeX,definition.SizeY]; } public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendLine(name); for (int y = SizeY-1; y > -1; y--) { sb.Append("[ "); for (int x = 0; x < SizeX; x++) { sb.Append(this[x, y]+" "); } sb.AppendLine("]"); } return sb.ToString(); } [ContextMenu("Debug Print")] public void DebugPrintToConsole() { Debug.Log(ToString()); } } }
25.239437
103
0.506696
[ "MIT" ]
daleran/ant-map-generator
AntMapGenerator/DataLayer.cs
1,794
C#