content stringlengths 23 1.05M |
|---|
// 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.Threading;
using Microsoft.Build.BackEnd;
using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using LegacyThreadingData = Microsoft.Build.Execution.LegacyThreadingData;
using Xunit;
#nullable disable
namespace Microsoft.Build.UnitTests.BackEnd
{
public class NodeEndpointInProc_Tests
{
private delegate void EndpointOperationDelegate(NodeEndpointInProc endpoint);
private class MockHost : IBuildComponentHost, INodePacketFactory
{
private DataReceivedContext _dataReceivedContext;
private AutoResetEvent _dataReceivedEvent;
private BuildParameters _buildParameters;
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular component host
/// </summary>
private LegacyThreadingData _legacyThreadingData;
public MockHost()
{
_buildParameters = new BuildParameters();
_dataReceivedEvent = new AutoResetEvent(false);
_legacyThreadingData = new LegacyThreadingData();
}
public ILoggingService LoggingService
{
get
{
throw new NotImplementedException();
}
}
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular component host
/// </summary>
LegacyThreadingData IBuildComponentHost.LegacyThreadingData
{
get
{
return _legacyThreadingData;
}
}
public string Name
{
get
{
return "NodeEndpointInProc_Tests.MockHost";
}
}
public BuildParameters BuildParameters
{
get
{
return _buildParameters;
}
}
#region IBuildComponentHost Members
public IBuildComponent GetComponent(BuildComponentType type)
{
throw new NotImplementedException();
}
public void RegisterFactory(BuildComponentType type, BuildComponentFactoryDelegate factory)
{
}
#endregion
#region INodePacketFactory Members
public void RegisterPacketHandler(NodePacketType packetType, NodePacketFactoryMethod factory, INodePacketHandler handler)
{
throw new NotImplementedException();
}
public void UnregisterPacketHandler(NodePacketType packetType)
{
throw new NotImplementedException();
}
public void DeserializeAndRoutePacket(int nodeId, NodePacketType packetType, ITranslator translator)
{
throw new NotImplementedException();
}
public void RoutePacket(int nodeId, INodePacket packet)
{
_dataReceivedContext = new DataReceivedContext(Thread.CurrentThread, packet);
_dataReceivedEvent.Set();
}
public DataReceivedContext DataReceivedContext
{
get { return _dataReceivedContext; }
}
public WaitHandle DataReceivedEvent
{
get { return _dataReceivedEvent; }
}
#endregion
}
private class TestPacket : INodePacket
{
#region INodePacket Members
public NodePacketType Type
{
get { throw new NotImplementedException(); }
}
public void Translate(ITranslator translator)
{
throw new NotImplementedException();
}
#endregion
}
private struct LinkStatusContext
{
public readonly Thread thread;
public readonly LinkStatus status;
public LinkStatusContext(Thread thread, LinkStatus status)
{
this.thread = thread;
this.status = status;
}
}
private struct DataReceivedContext
{
public readonly Thread thread;
public readonly INodePacket packet;
public DataReceivedContext(Thread thread, INodePacket packet)
{
this.thread = thread;
this.packet = packet;
}
}
private Dictionary<INodeEndpoint, LinkStatusContext> _linkStatusTable;
private MockHost _host;
[Fact]
public void ConstructionWithValidHost()
{
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Synchronous, _host);
endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Asynchronous, _host);
}
[Fact]
public void ConstructionSynchronousWithInvalidHost()
{
Assert.Throws<ArgumentNullException>(() =>
{
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Synchronous, null);
}
);
}
[Fact]
public void ConstructionAsynchronousWithInvalidHost()
{
Assert.Throws<ArgumentNullException>(() =>
{
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Asynchronous, null);
}
);
}
/// <summary>
/// Verify that the links:
/// 1. are marked inactive
/// 2. and that attempting to send data while they are
/// inactive throws the expected exception.
/// </summary>
[Fact]
public void InactiveLinkTestSynchronous()
{
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Synchronous, _host);
CallOpOnEndpoints(endpoints, VerifyLinkInactive);
CallOpOnEndpoints(endpoints, VerifySendDataInvalidOperation);
CallOpOnEndpoints(endpoints, VerifyDisconnectInvalidOperation);
// The following should not throw
endpoints.ManagerEndpoint.Listen(_host);
endpoints.NodeEndpoint.Connect(_host);
}
/// <summary>
/// Verify that the links are marked inactive and that attempting to send data while they are
/// inactive throws the expected exception.
/// </summary>
[Fact]
public void InactiveLinkTestAsynchronous()
{
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Asynchronous, _host);
CallOpOnEndpoints(endpoints, VerifyLinkInactive);
CallOpOnEndpoints(endpoints, VerifySendDataInvalidOperation);
CallOpOnEndpoints(endpoints, VerifyDisconnectInvalidOperation);
// The following should not throw
endpoints.ManagerEndpoint.Listen(_host);
endpoints.NodeEndpoint.Connect(_host);
endpoints.ManagerEndpoint.Disconnect();
}
[Fact]
public void ConnectionTestSynchronous()
{
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Synchronous, _host);
endpoints.ManagerEndpoint.OnLinkStatusChanged += LinkStatusChanged;
endpoints.NodeEndpoint.OnLinkStatusChanged += LinkStatusChanged;
// Call listen. This shouldn't have any effect on the link statuses.
endpoints.ManagerEndpoint.Listen(_host);
CallOpOnEndpoints(endpoints, VerifyLinkInactive);
// No link status callback should have occurred.
Assert.False(_linkStatusTable.ContainsKey(endpoints.NodeEndpoint));
Assert.False(_linkStatusTable.ContainsKey(endpoints.ManagerEndpoint));
// Now call connect on the node side. This should activate the link on both ends.
endpoints.NodeEndpoint.Connect(_host);
CallOpOnEndpoints(endpoints, VerifyLinkActive);
// We should have received callbacks informing us of the link change.
Assert.Equal(LinkStatus.Active, _linkStatusTable[endpoints.NodeEndpoint].status);
Assert.Equal(LinkStatus.Active, _linkStatusTable[endpoints.ManagerEndpoint].status);
}
[Fact]
public void DisconnectionTestSynchronous()
{
DisconnectionTestHelper(NodeEndpointInProc.EndpointMode.Synchronous);
}
[Fact]
public void DisconnectionTestAsynchronous()
{
DisconnectionTestHelper(NodeEndpointInProc.EndpointMode.Asynchronous);
}
[Fact]
public void SynchronousData()
{
// Create the endpoints
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Synchronous, _host);
// Connect the endpoints
endpoints.ManagerEndpoint.Listen(_host);
endpoints.NodeEndpoint.Connect(_host);
// Create our test packets
INodePacket managerPacket = new TestPacket();
INodePacket nodePacket = new TestPacket();
// Send data from the manager. We expect to receive it from the node endpoint, and it should
// be on the same thread.
endpoints.ManagerEndpoint.SendData(managerPacket);
Assert.Equal(_host.DataReceivedContext.packet, managerPacket);
Assert.Equal(_host.DataReceivedContext.thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);
// Send data from the node. We expect to receive it from the manager endpoint, and it should
// be on the same thread.
endpoints.NodeEndpoint.SendData(nodePacket);
Assert.Equal(_host.DataReceivedContext.packet, nodePacket);
Assert.Equal(_host.DataReceivedContext.thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);
}
[Fact]
public void AsynchronousData()
{
// Create the endpoints
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Asynchronous, _host);
// Connect the endpoints
endpoints.ManagerEndpoint.Listen(_host);
endpoints.NodeEndpoint.Connect(_host);
// Create our test packets
INodePacket managerPacket = new TestPacket();
INodePacket nodePacket = new TestPacket();
// Send data from the manager. We expect to receive it from the node endpoint, and it should
// be on the same thread.
endpoints.ManagerEndpoint.SendData(managerPacket);
if (!_host.DataReceivedEvent.WaitOne(1000))
{
Assert.True(false, "Data not received before timeout expired.");
}
Assert.Equal(_host.DataReceivedContext.packet, managerPacket);
Assert.NotEqual(_host.DataReceivedContext.thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);
// Send data from the node. We expect to receive it from the manager endpoint, and it should
// be on the same thread.
endpoints.NodeEndpoint.SendData(nodePacket);
if (!_host.DataReceivedEvent.WaitOne(1000))
{
Assert.True(false, "Data not received before timeout expired.");
}
Assert.Equal(_host.DataReceivedContext.packet, nodePacket);
Assert.NotEqual(_host.DataReceivedContext.thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);
endpoints.ManagerEndpoint.Disconnect();
}
public NodeEndpointInProc_Tests()
{
_linkStatusTable = new Dictionary<INodeEndpoint, LinkStatusContext>();
_host = new MockHost();
}
private void CallOpOnEndpoints(NodeEndpointInProc.EndpointPair pair, EndpointOperationDelegate opDelegate)
{
opDelegate(pair.NodeEndpoint);
opDelegate(pair.ManagerEndpoint);
}
private void VerifyLinkInactive(NodeEndpointInProc endpoint)
{
Assert.Equal(LinkStatus.Inactive, endpoint.LinkStatus); // "Expected LinkStatus to be Inactive"
}
private void VerifyLinkActive(NodeEndpointInProc endpoint)
{
Assert.Equal(LinkStatus.Active, endpoint.LinkStatus); // "Expected LinkStatus to be Active"
}
private void VerifySendDataInvalidOperation(NodeEndpointInProc endpoint)
{
bool caught = false;
try
{
endpoint.SendData(new TestPacket());
}
catch (InternalErrorException)
{
caught = true;
}
Assert.True(caught); // "Did not receive InternalErrorException."
}
private void VerifyDisconnectInvalidOperation(NodeEndpointInProc endpoint)
{
bool caught = false;
try
{
endpoint.Disconnect();
}
catch (InternalErrorException)
{
caught = true;
}
Assert.True(caught); // "Did not receive InternalErrorException."
}
private void DisconnectionTestHelper(NodeEndpointInProc.EndpointMode mode)
{
NodeEndpointInProc.EndpointPair endpoints = SetupConnection(mode);
endpoints.ManagerEndpoint.Disconnect();
VerifyLinksAndCallbacksInactive(endpoints);
endpoints = SetupConnection(mode);
endpoints.NodeEndpoint.Disconnect();
VerifyLinksAndCallbacksInactive(endpoints);
}
private void VerifyLinksAndCallbacksInactive(NodeEndpointInProc.EndpointPair endpoints)
{
CallOpOnEndpoints(endpoints, VerifyLinkInactive);
Assert.Equal(LinkStatus.Inactive, _linkStatusTable[endpoints.NodeEndpoint].status);
Assert.Equal(LinkStatus.Inactive, _linkStatusTable[endpoints.ManagerEndpoint].status);
}
private NodeEndpointInProc.EndpointPair SetupConnection(NodeEndpointInProc.EndpointMode mode)
{
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(mode, _host);
endpoints.ManagerEndpoint.OnLinkStatusChanged += LinkStatusChanged;
endpoints.NodeEndpoint.OnLinkStatusChanged += LinkStatusChanged;
// Call listen. This shouldn't have any effect on the link statuses.
endpoints.ManagerEndpoint.Listen(_host);
endpoints.NodeEndpoint.Connect(_host);
return endpoints;
}
private void LinkStatusChanged(INodeEndpoint endpoint, LinkStatus status)
{
lock (_linkStatusTable)
{
_linkStatusTable[endpoint] = new LinkStatusContext(Thread.CurrentThread, status);
}
}
}
}
|
namespace UnitTest_sample
{
public class GamePlayer
{
private string Name { get; set; }
public uint TotalPlayTime { get; private set; }
public GamePlayer(string name)
{
this.Name = name;
this.TotalPlayTime = 0;
}
public void AddPlayTime(uint time)
{
this.TotalPlayTime += time;
}
public string GetPlayerStatus()
{
var status = $"name:{this.Name} playTime:${this.TotalPlayTime}";
return status;
}
}
public class Program
{
public static void Main(string[] args)
{
}
}
} |
using System;
using System.Linq;
using System.Reflection;
using Cs2Py.CSharp;
using Cs2Py.Source;
using Lang.Python;
namespace Cs2Py.NodeTranslators
{
public class DirectCallAttributeMethodTranslator : BaseCsharpMethodCallExpressionTranslator
{
public DirectCallAttributeMethodTranslator() : base(2)
{
}
public override IPyValue TranslateToPython(IExternalTranslationContext ctx, CsharpMethodCallExpression src)
{
string GetOperatorName()
{
if (!src.MethodInfo.IsSpecialName)
return null;
switch (src.MethodInfo.Name)
{
case "op_Addition": return "+";
case "op_Subtraction": return "-";
case "op_Multiply": return "*";
case "op_Division": return "/";
case "op_Equality": return "==";
case "op_Inequality ": return "!=";
case "op_Implicit": return "i";
}
return null;
}
var ats = src.MethodInfo.GetCustomAttribute<DirectCallAttribute>();
if (ats == null)
return null;
var name = ats.Name;
var opName = GetOperatorName();
if (string.IsNullOrEmpty(name)) name = src.MethodInfo.Name;
if (opName != null)
name = opName;
var cSharpParameters = src.MethodInfo.GetParameters();
var agrsIndexByName = Enumerable.Range(0, cSharpParameters.Length)
.ToDictionary(a => cSharpParameters[a].Name, a => a);
var argsValues = new Argument[cSharpParameters.Length];
var info = MapNamedParameters(src);
for (var index = 0; index < src.Arguments.Length; index++)
{
var i = src.Arguments[index];
var pythonArgName = cSharpParameters[index].Name;
if (!string.IsNullOrEmpty(i.ExplicitName))
pythonArgName = i.ExplicitName;
var b = ctx.TranslateValue(i.MyValue);
var pyIndex = agrsIndexByName[pythonArgName];
argsValues[pyIndex] = new Argument
{
Value = b,
Name = cSharpParameters[pyIndex].Name
};
}
if (opName != null)
{
if (opName == "i" && argsValues.Length == 1) return argsValues[0].Value;
switch (argsValues.Length)
{
case 2:
return new PyBinaryOperatorExpression(opName, argsValues[0].Value, argsValues[1].Value);
case 1:
return new PyUnaryOperatorExpression(argsValues[0].Value, opName);
}
throw new NotSupportedException("Unable to convert operator " + opName + " with " + argsValues.Length +
" arguments");
}
var result = new PyMethodCallExpression(name);
var setName = false;
foreach (var i in argsValues)
{
if (i == null)
{
setName = true;
continue;
}
var item = new PyMethodInvokeValue(i.Value);
if (setName)
item.Name = i.Name;
result.Arguments.Add(item);
}
result.TrySetTargetObjectFromModule(src.MethodInfo.DeclaringType);
return result;
}
private class Argument
{
public IPyValue Value { get; set; }
public string Name { get; set; }
}
}
} |
using Micser.Common.Settings;
namespace Micser.Common.Extensions
{
/// <summary>
/// Provides extension methods for services.
/// </summary>
public static class ServiceExtensions
{
/// <summary>
/// Gets the value for the specified setting converted to type <typeparamref name="T"/>.
/// </summary>
public static T GetSetting<T>(this ISettingsService settingsService, string key)
{
return settingsService.GetSetting(key).ToType<T>();
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace ModbusExaminer.helpers
{
public sealed class ModbusExaminerLogger
{
private static volatile ModbusExaminerLogger instance;
private static object syncRoot = new Object();
private static object listLock = new object();
private volatile ObservableCollection<string> logList = new ObservableCollection<string>();
private ModbusExaminerLogger(){}
public static ModbusExaminerLogger Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new ModbusExaminerLogger();
}
}
return instance;
}
}
public ObservableCollection<string> GetLogList()
{
return logList;
}
public Object GetLogListSyncObject()
{
return listLock;
}
public void AddLogLine(string log, params object[] args)
{
//Task.Run(() =>
//{
lock (listLock)
logList.Add(string.Format(log, args));
// });
}
}
}
|
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Extensions;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.OData;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Csdl;
namespace Stenn.AspNetCore.OData.Versioning
{
/// <summary>
/// Represents a controller for generating OData service and metadata ($metadata) documents.
/// </summary>
public abstract class MetadataControllerBase : ControllerBase
{
private readonly IOptions<ODataVersioningOptions> _options;
/// <inheritdoc />
protected MetadataControllerBase(IOptions<ODataVersioningOptions> options)
{
_options = options;
}
protected virtual ODataVersion ODataVersion => _options.Value.ODataVersion;
/// <summary>
/// Generates the OData $metadata document.
/// </summary>
/// <returns>The <see cref="IEdmModel" /> representing $metadata.</returns>
[HttpGet]
public virtual IEdmModel GetMetadata()
{
return GetModel();
}
/// <summary>
/// Generates the OData service document.
/// </summary>
/// <returns>The service document for the service.</returns>
[HttpGet]
public virtual ODataServiceDocument GetServiceDocument()
{
var model = GetModel();
return model.GenerateServiceDocument();
}
[HttpOptions]
public virtual IActionResult GetOptions()
{
var headers = Response.Headers;
headers.Add("Allow", new StringValues(new[] { "GET", "OPTIONS" }));
headers.Add(ODataConstants.ODataVersionHeader, GetODataVersionString());
return Ok();
}
protected virtual IEdmModel GetModel()
{
var model = Request.GetModel();
if (model == null)
{
throw new InvalidOperationException();
}
model.SetEdmxVersion(new Version(GetODataVersionString()));
return model;
}
protected virtual string GetODataVersionString()
{
return ODataUtils.ODataVersionToString(ODataVersion);
}
}
} |
namespace RIAppDemo.BLL.Utils
{
public interface IHostAddrService
{
string GetIPAddress();
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#if TELEMETRYEVENTSOURCE_USE_NUGET
using Microsoft.Diagnostics.Tracing;
#else
using System.Diagnostics.Tracing;
#endif
using System;
using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute;
#pragma warning disable 3021 // 'type' does not need a CLSCompliant attribute
namespace Microsoft.Diagnostics.Telemetry
{
/// <summary>
/// <para>
/// An EventSource with extra methods and constants commonly used in Microsoft's
/// TraceLogging-based ETW. This class inherits from EventSource, and is exactly
/// the same as EventSource except that it always enables
/// EtwSelfDescribingEventFormat and never uses traits. It also provides several
/// constants and helpers commonly used by Microsoft code.
/// </para>
/// <para>
/// Different versions of this class use different provider traits. The provider
/// traits in this class are empty. As a result, providers using this class will
/// not join any ETW Provider Groups and will not be given any special treatment
/// by group-sensitive ETW listeners.
/// </para>
/// <para>
/// When including this class in your project, you may define the following
/// conditional-compilation symbols to adjust the default behaviors:
/// </para>
/// <para>
/// TELEMETRYEVENTSOURCE_USE_NUGET - use Microsoft.Diagnostics.Tracing instead
/// of System.Diagnostics.Tracing.
/// </para>
/// <para>
/// TELEMETRYEVENTSOURCE_PUBLIC - define TelemetryEventSource as public instead
/// of internal.
/// </para>
/// </summary>
#if TELEMETRYEVENTSOURCE_PUBLIC
public
#else
internal
#endif
class TelemetryEventSource
: EventSource
{
/// <summary>
/// Keyword 0x0000100000000000 is reserved for future definition. Do
/// not use keyword 0x0000100000000000 in Microsoft-style ETW.
/// </summary>
public const EventKeywords Reserved44Keyword = (EventKeywords)0x0000100000000000;
/// <summary>
/// Add TelemetryKeyword to eventSourceOptions.Keywords to indicate that
/// an event is for general-purpose telemetry.
/// This keyword should not be combined with MeasuresKeyword or
/// CriticalDataKeyword.
/// </summary>
public const EventKeywords TelemetryKeyword = (EventKeywords)0x0000200000000000;
/// <summary>
/// Add MeasuresKeyword to eventSourceOptions.Keywords to indicate that
/// an event is for understanding measures and reporting scenarios.
/// This keyword should not be combined with TelemetryKeyword or
/// CriticalDataKeyword.
/// </summary>
public const EventKeywords MeasuresKeyword = (EventKeywords)0x0000400000000000;
/// <summary>
/// Add CriticalDataKeyword to eventSourceOptions.Keywords to indicate that
/// an event powers user experiences or is critical to business intelligence.
/// This keyword should not be combined with TelemetryKeyword or
/// MeasuresKeyword.
/// </summary>
public const EventKeywords CriticalDataKeyword = (EventKeywords)0x0000800000000000;
/// <summary>
/// Add CostDeferredLatency to eventSourceOptions.Tags to indicate that an event
/// should try to upload over free networks for a period of time before resorting
/// to upload over costed networks.
/// </summary>
public const EventTags CostDeferredLatency = (EventTags)0x040000;
/// <summary>
/// Add CoreData to eventSourceOptions.Tags to indicate that an event
/// contains high priority "core data".
/// </summary>
public const EventTags CoreData = (EventTags)0x00080000;
/// <summary>
/// Add InjectXToken to eventSourceOptions.Tags to indicate that an XBOX
/// identity token should be injected into the event before the event is
/// uploaded.
/// </summary>
public const EventTags InjectXToken = (EventTags)0x00100000;
/// <summary>
/// Add RealtimeLatency to eventSourceOptions.Tags to indicate that an event
/// should be transmitted in real time (via any available connection).
/// </summary>
public const EventTags RealtimeLatency = (EventTags)0x0200000;
/// <summary>
/// Add NormalLatency to eventSourceOptions.Tags to indicate that an event
/// should be transmitted via the preferred connection based on device policy.
/// </summary>
public const EventTags NormalLatency = (EventTags)0x0400000;
/// <summary>
/// Add CriticalPersistence to eventSourceOptions.Tags to indicate that an
/// event should be deleted last when low on spool space.
/// </summary>
public const EventTags CriticalPersistence = (EventTags)0x0800000;
/// <summary>
/// Add NormalPersistence to eventSourceOptions.Tags to indicate that an event
/// should be deleted first when low on spool space.
/// </summary>
public const EventTags NormalPersistence = (EventTags)0x1000000;
/// <summary>
/// Add DropPii to eventSourceOptions.Tags to indicate that an event contains
/// PII and should be anonymized by the telemetry client. If this tag is
/// present, PartA fields that might allow identification or cross-event
/// correlation will be removed from the event.
/// </summary>
public const EventTags DropPii = (EventTags)0x02000000;
/// <summary>
/// Add HashPii to eventSourceOptions.Tags to indicate that an event contains
/// PII and should be anonymized by the telemetry client. If this tag is
/// present, PartA fields that might allow identification or cross-event
/// correlation will be hashed (obfuscated).
/// </summary>
public const EventTags HashPii = (EventTags)0x04000000;
/// <summary>
/// Add MarkPii to eventSourceOptions.Tags to indicate that an event contains
/// PII but may be uploaded as-is. If this tag is present, the event will be
/// marked so that it will only appear on the private stream.
/// </summary>
public const EventTags MarkPii = (EventTags)0x08000000;
/// <summary>
/// Add DropPiiField to eventFieldAttribute.Tags to indicate that a field
/// contains PII and should be dropped by the telemetry client.
/// </summary>
public const EventFieldTags DropPiiField = (EventFieldTags)0x04000000;
/// <summary>
/// Add HashPiiField to eventFieldAttribute.Tags to indicate that a field
/// contains PII and should be hashed (obfuscated) prior to uploading.
/// </summary>
public const EventFieldTags HashPiiField = (EventFieldTags)0x08000000;
/// <summary>
/// Constructs a new instance of the TelemetryEventSource class with the
/// specified name. Sets the EtwSelfDescribingEventFormat option.
/// </summary>
/// <param name="eventSourceName">The name of the event source.</param>
[SuppressMessage("Microsoft.Performance", "CA1811", Justification = "Shared class with tiny helper methods - not all constructors/methods are used by all consumers")]
public TelemetryEventSource(
string eventSourceName)
: base(
eventSourceName,
EventSourceSettings.EtwSelfDescribingEventFormat)
{
return;
}
/// <summary>
/// For use by derived classes that set the eventSourceName via EventSourceAttribute.
/// Sets the EtwSelfDescribingEventFormat option.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811", Justification = "Shared class with tiny helper methods - not all constructors/methods are used by all consumers")]
protected TelemetryEventSource()
: base(
EventSourceSettings.EtwSelfDescribingEventFormat)
{
return;
}
/// <summary>
/// Constructs a new instance of the TelemetryEventSource class with the
/// specified name. Sets the EtwSelfDescribingEventFormat option.
/// </summary>
/// <param name="eventSourceName">The name of the event source.</param>
/// <param name="telemetryGroup">The parameter is not used.</param>
[SuppressMessage("Microsoft.Performance", "CA1811", Justification = "Shared class with tiny helper methods - not all constructors/methods are used by all consumers")]
[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "API compatibility")]
public TelemetryEventSource(
string eventSourceName,
TelemetryGroup telemetryGroup)
: base(
eventSourceName,
EventSourceSettings.EtwSelfDescribingEventFormat)
{
return;
}
/// <summary>
/// Returns an instance of EventSourceOptions with the TelemetryKeyword set.
/// </summary>
/// <returns>Returns an instance of EventSourceOptions with the TelemetryKeyword set.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811", Justification = "Shared class with tiny helper methods - not all constructors/methods are used by all consumers")]
public static EventSourceOptions TelemetryOptions()
{
return new EventSourceOptions { Keywords = TelemetryKeyword };
}
/// <summary>
/// Returns an instance of EventSourceOptions with the MeasuresKeyword set.
/// </summary>
/// <returns>Returns an instance of EventSourceOptions with the MeasuresKeyword set.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811", Justification = "Shared class with tiny helper methods - not all constructors/methods are used by all consumers")]
public static EventSourceOptions MeasuresOptions()
{
return new EventSourceOptions { Keywords = MeasuresKeyword };
}
}
/// <summary>
/// <para>
/// The PrivTags class defines privacy tags that can be used to specify the privacy
/// category of an event. Add a privacy tag as a field with name "PartA_PrivTags".
/// As a shortcut, you can use _1 as the field name, which will automatically be
/// expanded to "PartA_PrivTags" at runtime.
/// </para>
/// <para>
/// Multiple tags can be OR'ed together if necessary (rarely needed).
/// </para>
/// </summary>
/// <example>
/// Typical usage:
/// <code>
/// es.Write("UsageEvent", new
/// {
/// _1 = PrivTags.ProductAndServiceUsage,
/// field1 = fieldValue1,
/// field2 = fieldValue2
/// });
/// </code>
/// </example>
#if TELEMETRYEVENTSOURCE_PUBLIC
[CLSCompliant(false)]
public
#else
internal
#endif
static class PrivTags
{
/// <nodoc/>
public const Internal.PartA_PrivTags BrowsingHistory = Internal.PartA_PrivTags.BrowsingHistory;
/// <nodoc/>
public const Internal.PartA_PrivTags DeviceConnectivityAndConfiguration = Internal.PartA_PrivTags.DeviceConnectivityAndConfiguration;
/// <nodoc/>
public const Internal.PartA_PrivTags InkingTypingAndSpeechUtterance = Internal.PartA_PrivTags.InkingTypingAndSpeechUtterance;
/// <nodoc/>
public const Internal.PartA_PrivTags ProductAndServicePerformance = Internal.PartA_PrivTags.ProductAndServicePerformance;
/// <nodoc/>
public const Internal.PartA_PrivTags ProductAndServiceUsage = Internal.PartA_PrivTags.ProductAndServiceUsage;
/// <nodoc/>
public const Internal.PartA_PrivTags SoftwareSetupAndInventory = Internal.PartA_PrivTags.SoftwareSetupAndInventory;
}
/// <summary>
/// Pass a TelemetryGroup value to the constructor of TelemetryEventSource
/// to control which telemetry group should be joined.
/// Note: has no effect in this version of TelemetryEventSource.
/// </summary>
#if TELEMETRYEVENTSOURCE_PUBLIC
public
#else
internal
#endif
enum TelemetryGroup
{
/// <summary>
/// The default group. Join this group to log normal, non-critical, non-coredata
/// events.
/// </summary>
MicrosoftTelemetry,
/// <summary>
/// Join this group to log CriticalData, CoreData, or other specially approved
/// events.
/// </summary>
WindowsCoreTelemetry
}
#pragma warning disable SA1403 // File may only contain a single namespace
namespace Internal
#pragma warning restore SA1403 // File may only contain a single namespace
{
/// <summary>
/// The complete list of privacy tags supported for events.
/// Multiple tags can be OR'ed together if an event belongs in multiple
/// categories.
/// Note that the PartA_PrivTags enum should not be used directly.
/// Instead, use values from the PrivTags class.
/// </summary>
[Flags]
#if TELEMETRYEVENTSOURCE_PUBLIC
[CLSCompliant(false)]
public
#else
internal
#endif
enum PartA_PrivTags
: ulong
{
/// <nodoc/>
None = 0,
/// <nodoc/>
BrowsingHistory = 0x0000000000000002u,
/// <nodoc/>
DeviceConnectivityAndConfiguration = 0x0000000000000800u,
/// <nodoc/>
InkingTypingAndSpeechUtterance = 0x0000000000020000u,
/// <nodoc/>
ProductAndServicePerformance = 0x0000000001000000u,
/// <nodoc/>
ProductAndServiceUsage = 0x0000000002000000u,
/// <nodoc/>
SoftwareSetupAndInventory = 0x0000000080000000u,
}
}
}
|
namespace TemplateV2.Models
{
public class CheckboxItemSelection
{
public int Id { get; set; }
public bool Selected { get; set; }
}
}
|
public class C {
public void m() {
long l = 0L;
if (l == null) {
}
}
}
|
using System;
using CustomList;
using NUnit.Framework;
namespace CustomListTests
{
[TestFixture]
public class GetIndexerTests
{
private static void GetIndexer_WithValidIndex_ReturnsTheItemAtTheSpecifiedIndexInTheCollectionTestHelper<T>()
{
var collection = new CustomList<T>
{
default
};
T expected = default;
var actual = collection[^1];
Assert.AreEqual(expected, actual);
}
[Test]
public void GetIndexer_WithValidIndex_ReturnsTheItemAtTheSpecifiedIndexInTheCollection()
{
GetIndexer_WithValidIndex_ReturnsTheItemAtTheSpecifiedIndexInTheCollectionTestHelper<string>();
GetIndexer_WithValidIndex_ReturnsTheItemAtTheSpecifiedIndexInTheCollectionTestHelper<double>();
GetIndexer_WithValidIndex_ReturnsTheItemAtTheSpecifiedIndexInTheCollectionTestHelper<int>();
GetIndexer_WithValidIndex_ReturnsTheItemAtTheSpecifiedIndexInTheCollectionTestHelper<char>();
}
private static void GetIndexer_WithIndexLessThanZero_ThrowsIndexOutOfRangeExceptionTestHelper<T>()
{
var collection = new CustomList<T>();
Assert.Throws<IndexOutOfRangeException>((() =>
{
var index = collection[-1];
}));
}
[Test]
public void GetIndexer_WithIndexLessThanZero_ThrowsIndexOutOfRangeException()
{
GetIndexer_WithIndexLessThanZero_ThrowsIndexOutOfRangeExceptionTestHelper<string>();
GetIndexer_WithIndexLessThanZero_ThrowsIndexOutOfRangeExceptionTestHelper<double>();
GetIndexer_WithIndexLessThanZero_ThrowsIndexOutOfRangeExceptionTestHelper<int>();
GetIndexer_WithIndexLessThanZero_ThrowsIndexOutOfRangeExceptionTestHelper<char>();
}
private static void
GetIndexer_WithIndexGreaterThanTheCountOfTheItems_ThrowsIndexOutOfRangeExceptionTestHelper<T>()
{
var collection = new CustomList<T>();
var index = collection.Count + 1;
Assert.Throws<IndexOutOfRangeException>(() =>
{
var ind = collection[index];
});
}
[Test]
public void GetIndexer_WithIndexGreaterThanTheCountOfTheItems_ThrowsIndexOutOfRangeException()
{
GetIndexer_WithIndexGreaterThanTheCountOfTheItems_ThrowsIndexOutOfRangeExceptionTestHelper<string>();
GetIndexer_WithIndexGreaterThanTheCountOfTheItems_ThrowsIndexOutOfRangeExceptionTestHelper<double>();
GetIndexer_WithIndexGreaterThanTheCountOfTheItems_ThrowsIndexOutOfRangeExceptionTestHelper<int>();
GetIndexer_WithIndexGreaterThanTheCountOfTheItems_ThrowsIndexOutOfRangeExceptionTestHelper<char>();
}
private static void GetIndexer_WithIndexEqualToTheCountOfTheItems_ThrowsIndexOutOfRangeExceptionTestHelper<T>()
{
var collection = new CustomList<T>();
var i = collection.Count;
Assert.Throws<IndexOutOfRangeException>((() =>
{
var index = collection[i];
}));
}
[Test]
public void GetIndexer_WithIndexEqualToTheCountOfTheItems_ThrowsIndexOutOfRangeException()
{
GetIndexer_WithIndexEqualToTheCountOfTheItems_ThrowsIndexOutOfRangeExceptionTestHelper<string>();
GetIndexer_WithIndexEqualToTheCountOfTheItems_ThrowsIndexOutOfRangeExceptionTestHelper<double>();
GetIndexer_WithIndexEqualToTheCountOfTheItems_ThrowsIndexOutOfRangeExceptionTestHelper<int>();
GetIndexer_WithIndexEqualToTheCountOfTheItems_ThrowsIndexOutOfRangeExceptionTestHelper<char>();
}
private static void GetIndexer_WithValidIndex_DoesNotChangeTheCountOfTheItemsInTheCollectionTestHelper<T>()
{
var collection = new CustomList<T>()
{
default
};
var expected = collection.Count;
var item = collection[^1];
var actual = collection.Count;
Assert.AreEqual(expected, actual);
}
[Test]
public void GetIndexer_WithValidIndex_DoesNotChangeTheCountOfTheItemsInTheCollection()
{
GetIndexer_WithValidIndex_DoesNotChangeTheCountOfTheItemsInTheCollectionTestHelper<string>();
GetIndexer_WithValidIndex_DoesNotChangeTheCountOfTheItemsInTheCollectionTestHelper<double>();
GetIndexer_WithValidIndex_DoesNotChangeTheCountOfTheItemsInTheCollectionTestHelper<int>();
GetIndexer_WithValidIndex_DoesNotChangeTheCountOfTheItemsInTheCollectionTestHelper<char>();
}
private static void GetIndexer_WithValidIndex_DoesNotChangeTheCapacityOfTheCollectionTestHelper<T>()
{
var collection = new CustomList<T>()
{
default
};
var expected = collection.Capacity;
var item = collection[^1];
var actual = collection.Capacity;
Assert.AreEqual(expected, actual);
}
[Test]
public void GetIndexer_WithValidIndex_DoesNotChangeTheCapacityOfTheCollection()
{
GetIndexer_WithValidIndex_DoesNotChangeTheCapacityOfTheCollectionTestHelper<string>();
GetIndexer_WithValidIndex_DoesNotChangeTheCapacityOfTheCollectionTestHelper<double>();
GetIndexer_WithValidIndex_DoesNotChangeTheCapacityOfTheCollectionTestHelper<int>();
GetIndexer_WithValidIndex_DoesNotChangeTheCapacityOfTheCollectionTestHelper<char>();
}
}
} |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
// Copyright (c) 2020 Upendo Ventures, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Hotcakes.Commerce.Catalog;
using Hotcakes.Commerce.Membership;
using Hotcakes.Commerce.Utilities;
using Hotcakes.Common.Dnn;
using Hotcakes.Modules.Core.Admin.AppCode;
namespace Hotcakes.Modules.Core.Admin.Catalog
{
public partial class GiftCards : BaseAdminPage
{
#region Properties
private long? GiftCardId
{
get { return (long?) ViewState["GiftCardId"]; }
set { ViewState["GiftCardId"] = value; }
}
#endregion
#region Event handlers
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
PageTitle = Localization.GetString("GiftCards");
CurrentTab = AdminTabType.Catalog;
ValidateCurrentUserHasPermission(SystemPermissions.CatalogView);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
gvGiftCards.RowDeleting += gvGiftCards_RowDeleting;
gvGiftCards.RowEditing += gvGiftCards_RowEditing;
gvGiftCards.RowCommand += gvGiftCards_RowCommand;
lnkSave.Click += lnkSave_Click;
lnkCancel.Click += lnkCancel_Click;
btnFind.Click += (s, a) =>
{
ucPager.ResetPageNumber();
LoadGiftCards();
};
ucDateRangePicker.RangeTypeChanged += (s, a) =>
{
ucPager.ResetPageNumber();
LoadGiftCards();
};
ucPager.PageChanged += (s, a) => { LoadGiftCards(); };
lnkExportToExcel.Click += lnkExportToExcel_Click;
}
protected void gvGiftCards_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "GoToOrder")
{
var o = HccApp.OrderServices.Orders.FindByOrderNumber(e.CommandArgument.ToString());
Response.Redirect("../Orders/ViewOrder.aspx?id=" + o.bvin);
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
LoadGiftCards();
LocalizeView();
}
}
private void gvGiftCards_RowEditing(object sender, GridViewEditEventArgs e)
{
var id = (long) gvGiftCards.DataKeys[e.NewEditIndex].Value;
LoadGiftCardEditor(id);
e.Cancel = true;
}
private void gvGiftCards_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var id = (long) e.Keys[0];
HccApp.CatalogServices.GiftCards.Delete(id);
LoadGiftCards();
}
private void lnkSave_Click(object sender, EventArgs e)
{
var card = HccApp.CatalogServices.GiftCards.Find(GiftCardId.Value);
card.ExpirationDateUtc = DateHelper.ConvertStoreTimeToUtc(HccApp, DateTime.Parse(dpExpiration.Text.Trim()));
card.Amount = Convert.ToDecimal(txtAmount.Text);
card.Enabled = cbEnabled.Checked;
HccApp.CatalogServices.GiftCards.Update(card);
ShowEditor(false);
LoadGiftCards();
}
private void lnkCancel_Click(object sender, EventArgs e)
{
ShowEditor(false);
}
private void lnkExportToExcel_Click(object sender, EventArgs e)
{
var criteria = GetCriteria();
var rowCount = 0;
var items = HccApp.CatalogServices.GiftCards.FindAllWithFilter(criteria, 1, int.MaxValue, ref rowCount);
var giftCardExport = new GiftCardExport(HccApp);
giftCardExport.ExportToExcel(Response, "Hotcakes_GiftCards.xlsx", items);
}
protected void btnEdit_OnPreRender(object sender, EventArgs e)
{
var link = (LinkButton) sender;
link.Text = Localization.GetString("Edit");
}
protected void gvGiftCards_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = Localization.GetString("IssueDate");
e.Row.Cells[1].Text = Localization.GetString("Recipient");
e.Row.Cells[2].Text = Localization.GetString("CardNumber");
e.Row.Cells[3].Text = Localization.GetString("Amount");
e.Row.Cells[4].Text = Localization.GetString("Balance");
e.Row.Cells[5].Text = Localization.GetString("Enabled");
e.Row.Cells[6].Text = Localization.GetString("OrderNumber");
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
var chkBox = e.Row.Cells[5].Controls[0] as CheckBox;
chkBox.Enabled = true;
chkBox.Attributes.Add("onclick", "return false;");
}
}
#endregion
#region Implementation
private void LoadGiftCards()
{
var lineItemId = Request.QueryString["lineitem"].ConvertToNullable<long>();
List<GiftCard> items = null;
if (!lineItemId.HasValue)
{
var criteria = GetCriteria();
var rowCount = 0;
items = HccApp.CatalogServices.GiftCards.FindAllWithFilter(criteria, ucPager.PageNumber,
ucPager.PageSize, ref rowCount);
ucPager.SetRowCount(rowCount);
}
else
{
items = HccApp.CatalogServices.GiftCards.FindByLineItem(lineItemId.Value);
ucPager.SetRowCount(items.Count);
divFilterPanel.Visible = false;
pnlFilteredByLineItem.Visible = true;
}
foreach (var item in items)
{
item.IssueDateUtc = DateHelper.ConvertUtcToStoreTime(HccApp, item.IssueDateUtc);
item.ExpirationDateUtc = DateHelper.ConvertUtcToStoreTime(HccApp, item.ExpirationDateUtc);
item.UsedAmount = item.Amount - item.UsedAmount; // replace "used amount" to "balance"
}
gvGiftCards.DataSource = items;
gvGiftCards.DataBind();
lblNoGiftcards.Visible = items.Count == 0;
}
private GiftCardSearchCriteria GetCriteria()
{
var criteria = new GiftCardSearchCriteria
{
SearchText = txtSearchText.Text.Trim(),
ShowDisabled = cbShowDisabled.Checked,
ShowExpired = cbShowExpired.Checked,
StartDateUtc = ucDateRangePicker.GetStartDateUtc(HccApp),
EndDateUtc = ucDateRangePicker.GetEndDateUtc(HccApp),
CompareAmount = ucAmountComare.GetCompareCriteria(),
CompareBalance = ucBalanceComare.GetCompareCriteria()
};
return criteria;
}
private void ShowEditor(bool show)
{
pnlEditGiftCard.Visible = show;
if (show)
{
ClientScript.RegisterStartupScript(GetType(), "hcEditGiftCardDialog", "hcEditGiftCardDialog();", true);
}
}
private void LoadGiftCardEditor(long id)
{
var card = HccApp.CatalogServices.GiftCards.Find(id);
cbEnabled.Checked = card.Enabled;
lblCardNumber.Text = card.CardNumber;
lblIssueDate.Text = DateHelper.ConvertUtcToStoreTime(HccApp, card.IssueDateUtc).ToShortDateString();
lblRecipientEmail.Text = card.RecipientEmail + " ";
//NOTE: hack for jqueryui dialog, otherwise max-height calculates wrong
lblRecipientName.Text = card.RecipientName + " ";
dpExpiration.Text = DateHelper.ConvertUtcToStoreTime(HccApp, card.ExpirationDateUtc).ToString("MM/dd/yyyy");
txtAmount.Text = Money.FormatCurrency(card.Amount);
lblUsedAmount.Text = Money.FormatCurrency(card.UsedAmount);
lblOrderNumber.Text = card.OrderNumber;
GiftCardId = id;
ShowEditor(true);
}
private void LocalizeView()
{
rfvAmount.ErrorMessage = Localization.GetString("rfvAmount.ErrorMessage");
cvAmount.ErrorMessage = Localization.GetString("cvAmount.ErrorMessage");
}
#endregion
}
} |
using System;
namespace loopTask4_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("ohjelma tulostaa kertotaulun luvuille 1-9!");
Console.Write("Aloita painamalla mitä tahansa näppäintä:");
Console.ReadKey();
for (int i = 1; i <= 9; i++)
for (int j = 1; j <= 9; j++)
Console.WriteLine($"{i} x {j} = {i * j}");
}
}
}
|
using JetBrains.Annotations;
namespace MAS.Game.Core.Components
{
public abstract class SingletonComponentBase<T>
where T : SingletonComponentBase<T>, new()
{
[NotNull]
public static T Instance { get; } = new T();
public override string ToString() => GetType().Name.Replace("Component", "");
}
} |
using System.Collections.Generic;
using System;
namespace AddressBook.Models
{
public class Contact
{
private string _name;
private string _phone;
private int _id;
private Address _address;
private static List<Contact> _instances = new List<Contact> {};
private static int lastId = 1;
public Contact(string Name, string phoneNumber, Address addressDetails)
{
_name = Name;
_phone = phoneNumber;
_address = addressDetails;
_id = lastId++;
}
public string GetName()
{
return _name;
}
public string GetPhone()
{
return _phone;
}
public Address GetAddress()
{
return _address;
}
public int GetID()
{
return _id;
}
public static List<Contact> GetAll()
{
return _instances;
}
public void Save()
{
_instances.Add(this);
}
public static void ClearAll()
{
_instances.Clear();
}
public static void RemoveContact(int cntId)
{
Console.WriteLine("Deleting"+cntId);
var toDelete = -1;
for (var i=0; i<_instances.Count; i++) {
if (_instances[i].GetID() == cntId ) {
toDelete=i;
}
}
if (toDelete!=-1) {
_instances.RemoveAt(toDelete);
}
}
public static Contact Find(int searchId)
{
Console.WriteLine("Searching"+searchId);
for (var i=0; i<_instances.Count; i++) {
if (_instances[i].GetID() == searchId ) {
return _instances[i];
}
}
return null;
}
}
}
|
using comp_app.MVVM.ViewModel;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Grid.LookUp;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
namespace comp_app.MVVM.View
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class ItemListView : Page
{
public ItemListView()
{
InitializeComponent();
this.DataContext = new ItemListViewModel(ref Item_ListView);
}
}
}
|
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using System;
using System.Collections.Generic;
using System.Text;
namespace PHPUnit.TestAdapter
{
/// <summary>
/// Class to store information about the current test run to be used from <see cref="TestReporterExtension"/>.
/// </summary>
internal class TestRunContext
{
public string Source { get; }
public IFrameworkHandle FrameworkHandle { get; }
public TestRunContext(string source, IFrameworkHandle frameworkHandle)
{
this.Source = source;
this.FrameworkHandle = frameworkHandle;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading;
public class DbgView : IDisposable
{
public DbgView(TextWriter writer)
{
if (writer == null) throw new ArgumentNullException("writer");
this.writer = writer;
}
public void Start()
{
lock (this.lockObj)
{
if (this.listenerThread == null)
{
this.listenerThread = new Thread(ListenerThread) { IsBackground = true };
this.listenerThread.Start();
}
}
}
public void Stop()
{
lock (this.lockObj)
{
if (this.listenerThread != null)
{
this.listenerThread.Interrupt();
this.listenerThread.Join(10 * 1000);
this.listenerThread = null;
}
}
}
public void Dispose()
{
this.Stop();
}
private void ListenerThread(object state)
{
EventWaitHandle bufferReadyEvent = null;
EventWaitHandle dataReadyEvent = null;
MemoryMappedFile memoryMappedFile = null;
try
{
bool createdNew;
var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
var eventSecurity = new EventWaitHandleSecurity();
eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(everyone, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, AccessControlType.Allow));
bufferReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_BUFFER_READY", out createdNew, eventSecurity);
if (!createdNew) throw new Exception("Some DbgView already running");
dataReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_DATA_READY", out createdNew, eventSecurity);
if (!createdNew) throw new Exception("Some DbgView already running");
var memoryMapSecurity = new MemoryMappedFileSecurity();
memoryMapSecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>(everyone, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
memoryMappedFile = MemoryMappedFile.CreateNew("DBWIN_BUFFER", 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memoryMapSecurity, System.IO.HandleInheritability.None);
bufferReadyEvent.Set();
this.writer.WriteLine("[DbgView] Started.");
using (var accessor = memoryMappedFile.CreateViewAccessor())
{
byte[] buffer = new byte[4096];
while (dataReadyEvent.WaitOne())
{
accessor.ReadArray<byte>(0, buffer, 0, buffer.Length);
int processId = BitConverter.ToInt32(buffer, 0);
int terminator = Array.IndexOf<byte>(buffer, 0, 4);
string msg = Encoding.Default.GetString(buffer, 4, (terminator < 0 ? buffer.Length : terminator) - 4);
if (hashSet.Contains(processId))
{
if (msg == "CozyDebugOutput HideDebugPrint")
{
hashSet.Remove(processId);
}
writer.WriteLine("[{0:00000}] {1}", processId, msg);
}
else if (msg == "CozyDebugOutput ShowDebugPrint")
{
hashSet.Add(processId);
writer.WriteLine("[{0:00000}] {1}", processId, msg);
}
bufferReadyEvent.Set();
}
}
}
catch (ThreadInterruptedException)
{
this.writer.WriteLine("[DbgView] Stopped.");
}
catch (Exception e)
{
this.writer.WriteLine("[DbgView] Error: " + e.Message);
}
finally
{
foreach (var disposable in new IDisposable[] { bufferReadyEvent, dataReadyEvent, memoryMappedFile })
{
if (disposable != null) disposable.Dispose();
}
}
}
private Thread listenerThread;
private readonly object lockObj = new object();
private readonly TextWriter writer;
private HashSet<int> hashSet = new HashSet<int>();
}
|
using Microsoft.EntityFrameworkCore;
using System;
namespace BigCookieKit.AspCore.Apm
{
public abstract class ApmDbContext : DbContext
{
public ApmDbContext() { }
public ApmDbContext(DbContextOptions options)
: base(options)
{
}
public static Action<DbContextOptionsBuilder> _OnConfiguring { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
_OnConfiguring?.Invoke(optionsBuilder);
base.OnConfiguring(optionsBuilder);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace SimplifyingConditional
{
#region Other classes
public class Food
{
public string Name { get; set; }
}
public class Eating
{
public Dictionary<Food, double> Foods { get; }
public void Add(Food food, double weight)
{
var product = Foods.Keys.FirstOrDefault(f => f.Name.Equals(food.Name));
if (product == null)
{
Foods.Add(food, weight);
}
else
{
Foods[product] += weight;
}
}
}
public class DatabaseManager
{
public static void SaveFoods(IEnumerable<Food> foods)
{
//Perform save to database
}
public static void SaveEating(Eating eating)
{
//Perform save to database
}
}
#endregion
public class EatingController
{
public List<Food> Foods { get; }
public Eating Eating { get; }
public void Add(Food food, double weight)
{
var product = Foods.SingleOrDefault(p => p.Name == food.Name);
if (product == null)
{
Foods.Add(food);
Eating.Add(food, weight);
Save();
}
else
{
Eating.Add(product, weight);
Save();
}
}
private void Save()
{
DatabaseManager.SaveFoods(Foods);
DatabaseManager.SaveEating(Eating);
}
}
}
|
namespace NPOI.OpenXmlFormats.Spreadsheet
{
public enum ST_DataValidationType
{
none,
whole,
@decimal,
list,
date,
time,
textLength,
custom
}
}
|
using System.Collections.Generic;
public class FixedSizedQueue<T>
{
public int size
{
get; private set;
}
private readonly object m_privateLockObject = new object();
private readonly Queue<T> m_queue = new Queue<T>();
private T m_lastAdded;
public FixedSizedQueue(int size)
{
this.size = size;
}
public void Enqueue(T obj)
{
lock (m_privateLockObject)
{
m_lastAdded = obj;
m_queue.Enqueue(obj);
}
lock (m_privateLockObject)
{
while (m_queue.Count > size)
{
m_queue.Dequeue();
}
}
}
public T Peek()
{
lock (m_privateLockObject)
{
return m_lastAdded;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Actor : MonoBehaviour
{
private StateMachine stateMachine = new StateMachine();
public StateMachine StateMachine { get => stateMachine; private set => stateMachine = value; }
[SerializeField]
private CharacterScriptableObject actorData;
public virtual CharacterScriptableObject ActorData { get => actorData; private set => actorData = value; }
public bool windupFinished;
public bool attacking = false;
protected virtual void Update()
{
StateMachine.StateExecuteTick();
}
public virtual void ChooseBehaviour()
{
}
public virtual void FaceTarget()
{
}
public virtual bool CheckBeat(IState state)
{
return false;
}
public virtual void Death()
{
StateMachine.ChangeState(new Death(this, this.GetComponent<NavMeshAgent>()));
}
} |
using ContosoUniversity.Data;
using ContosoUniversity.Data.Abstract;
using ContosoUniversity.Data.Repositories;
using ContosoUniversity.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Scheduler.Data.Repositories
{
public class StudentsRepository : EntityBaseRepository<Student>, IStudentsRepository
{
private ContosoContext _context;
public StudentsRepository(ContosoContext context)
: base(context)
{
_context = context;
}
public async Task<Student> GetStudentAsync(int? id)
{
return await _context.Students
.Include(s => s.Enrollments)
.ThenInclude(e => e.Course)
.AsNoTracking()
.SingleOrDefaultAsync(m => m.ID == id);
}
}
} |
using nng.Native;
using System;
namespace nng
{
/// <summary>
/// Represents NNG options to get/set
/// </summary>
public interface IOptions : IGetOptions, ISetOptions
{
}
/// <summary>
/// Represents NNG options to get
/// </summary>
public interface IGetOptions
{
int GetOpt(string name, out bool data);
int GetOpt(string name, out int data);
int GetOpt(string name, out nng_duration data);
int GetOpt(string name, out IntPtr data);
int GetOpt(string name, out UIntPtr data);
int GetOpt(string name, out string data);
int GetOpt(string name, out UInt64 data);
}
/// <summary>
/// Represents NNG options to set
/// </summary>
public interface ISetOptions
{
int SetOpt(string name, byte[] data);
int SetOpt(string name, bool data);
int SetOpt(string name, int data);
int SetOpt(string name, nng_duration data);
int SetOpt(string name, IntPtr data);
int SetOpt(string name, UIntPtr data);
int SetOpt(string name, string data);
int SetOpt(string name, UInt64 data);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WastedgeApi
{
public class EntityCalculatedField : EntityTypedField
{
public override EntityMemberType Type => EntityMemberType.Calculated;
public EntityCalculatedField(string name, string comments, EntityDataType dataType, int? decimals)
: base(name, comments, dataType, decimals)
{
}
}
}
|
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Microsoft.Boogie;
using Symbooglix;
namespace SymbooglixLibTests
{
[TestFixture()]
public class Havoc : SymbooglixTest
{
[Test()]
public void simpleHavoc()
{
p = LoadProgramFrom(@"
procedure main()
{
var a:int;
a := 1;
assert {:symbooglix_bp ""a_is_concrete""} true;
havoc a;
assert {:symbooglix_bp ""a_is_symbolic""} true;
}
", "test.bpl");
e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
int counter = 0;
KeyValuePair<Variable,Expr>? aBefore = null;
e.BreakPointReached += delegate(object sender, Executor.BreakPointEventArgs eventArgs)
{
switch (eventArgs.Name)
{
case "a_is_concrete":
aBefore = e.CurrentState.GetInScopeVariableAndExprByName("a");
var asLit = ExprUtil.AsLiteral(aBefore.Value.Value);
Assert.IsNotNull(asLit);
Assert.IsTrue(asLit.isBigNum);
Assert.AreEqual(Microsoft.Basetypes.BigNum.FromInt(1), asLit.asBigNum);
break;
case "a_is_symbolic":
var aAfter = e.CurrentState.GetInScopeVariableAndExprByName("a");
Assert.IsTrue(aBefore != null && aBefore.HasValue);
Assert.AreNotSame(aBefore.Value, aAfter.Value);
var asId = ExprUtil.AsIdentifer(aAfter.Value);
Assert.IsNotNull(asId);
break;
default:
Assert.Fail("Unrecognised breakpoint");
break;
}
++counter;
};
e.Run(GetMain(p));
Assert.AreEqual(2, counter);
}
}
}
|
using UnityEngine;
using UniversalNetworkInput;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
public class PlayerChecker : MonoBehaviour
{
public MenuController menuController;
public Player[] players;
public bool blockCheck = false;
public static List<int> playersActivated = new List<int>();
private float horizontal, vertical;
private void Start()
{
foreach (Player player in players)
{
player.DesactivePlayer();
}
}
private void Update()
{
if (UNInput.GetButtonDown(ButtonCode.Start))
{
if (playersActivated.Count > 0)
{
SceneManager.LoadScene(1);
}
}
for (int id = 0; id < 4; id++)
{
if (playersActivated.Contains(id))
{
horizontal = UNInput.GetAxis(players[id].playerData.ID, AxisCode.LeftStickHorizontal);
vertical = UNInput.GetAxis(players[id].playerData.ID, AxisCode.LeftStickVertical);
if (Mathf.Abs(horizontal) > .55f)
{
if (horizontal > 0f)
players[id].IncrementModel();
else
players[id].DecrementModel();
}
if (Mathf.Abs(vertical) > .55f)
{
if (vertical > 0f)
players[id].IncrementSkin();
else
players[id].DecrementSkin();
}
continue;
}
blockCheck = false;
if (UNInput.GetButtonDown(id, ButtonCode.B))
{
for (int i = 0; i < 4; i++)
{
if (players[i].IsActive())
{
continue;
}
menuController.ChooseToMenu();
Invoke("Start",1f);
blockCheck = true;
break;
}
}
if (UNInput.GetButtonDown(id, ButtonCode.A))
{
for (int i = 0; i < 4; i++)
{
if (players[i].IsActive())
{
continue;
}
players[i].ActivePlayer(id, false);
playersActivated.Add(id);
blockCheck = true;
break;
}
}
if (blockCheck)
break;
}
}
}
|
using System;
using System.Collections.Generic;
namespace P01.Fibonacci
{
public class StartUp
{
private static Dictionary<long, long> calculatedFibonaccis;
public static void Main(string[] args)
{
calculatedFibonaccis = new Dictionary<long, long>();
var n = long.Parse(Console.ReadLine());
var result = GetFibbonaci(n);
Console.WriteLine(result);
}
private static long GetFibbonaci(long n)
{
if (n == 2 || n == 1)
{
return 1;
}
if (calculatedFibonaccis.ContainsKey(n))
{
return calculatedFibonaccis[n];
}
var currentFibNumber = GetFibbonaci(n - 1) + GetFibbonaci(n - 2);
calculatedFibonaccis.Add(n, currentFibNumber);
return currentFibNumber;
}
}
}
|
// --------------------------------------------------------------------------------
// <copyright file="https://github.com/ddur/DBCL/blob/master/LICENSE" company="DD">
// Copyright © 2013-2016 Dragan Duric. All Rights Reserved.
// </copyright>
// --------------------------------------------------------------------------------
using System;
using DD.Collections;
using NUnit.Framework;
namespace DD.Collections.ICodeSet.ICodeSetExtendedTest.Members {
[TestFixture]
public class IsEmpty {
[Test]
public void ICodeSet_Null_Throws () {
Assert.Throws<ArgumentNullException> (
delegate {
((BitSetArray)null).IsEmpty ();
}
);
}
[Test]
public void ICodeSet_Empty () {
Assert.True (CodeSetNone.Singleton.IsEmpty ());
}
[Test]
public void ICodeSet_NotEmpty () {
Assert.False (CodeSetMask.From (1).IsEmpty ());
Assert.False (CodeSetMask.From (10, 11, 20).IsEmpty ());
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
namespace Microsoft.ClearScript.JavaScript
{
/// <summary>
/// Defines properties and methods common to all
/// <see href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</see>
/// views.
/// </summary>
public interface IArrayBufferView
{
/// <summary>
/// Gets view's underlying <c>ArrayBuffer</c>.
/// </summary>
IArrayBuffer ArrayBuffer { get; }
/// <summary>
/// Gets the view's offset within the underlying <c>ArrayBuffer</c>.
/// </summary>
ulong Offset { get; }
/// <summary>
/// Gets the view's size in bytes.
/// </summary>
ulong Size { get; }
/// <summary>
/// Creates a byte array containing a copy of the view's contents.
/// </summary>
/// <returns>A new byte array containing a copy of the view's contents.</returns>
byte[] GetBytes();
/// <summary>
/// Copies bytes from the view into the specified byte array.
/// </summary>
/// <param name="offset">The offset within the view of the first byte to copy.</param>
/// <param name="count">The maximum number of bytes to copy.</param>
/// <param name="destination">The byte array into which to copy the bytes.</param>
/// <param name="destinationIndex">The index within <paramref name="destination"/> at which to store the first copied byte.</param>
/// <returns>The number of bytes copied.</returns>
ulong ReadBytes(ulong offset, ulong count, byte[] destination, ulong destinationIndex);
/// <summary>
/// Copies bytes from the specified byte array into the view.
/// </summary>
/// <param name="source">The byte array from which to copy the bytes.</param>
/// <param name="sourceIndex">The index within <paramref name="source"/> of the first byte to copy.</param>
/// <param name="count">The maximum number of bytes to copy.</param>
/// <param name="offset">The offset within the view at which to store the first copied byte.</param>
/// <returns>The number of bytes copied.</returns>
ulong WriteBytes(byte[] source, ulong sourceIndex, ulong count, ulong offset);
/// <summary>
/// Invokes a delegate that returns no value, giving it direct access to the view's contents.
/// </summary>
/// <param name="action">The delegate to invoke.</param>
/// <remarks>
/// This method invokes the specified delegate, passing in the memory address of the view's
/// contents. This memory address is valid only while the delegate is executing. The
/// delegate must not access memory outside the view's range.
/// </remarks>
void InvokeWithDirectAccess(Action<IntPtr> action);
/// <summary>
/// Invokes a delegate that returns a value, giving it direct access to the view's contents.
/// </summary>
/// <typeparam name="T">The delegate's return type.</typeparam>
/// <param name="func">The delegate to invoke.</param>
/// <returns>The delegate's return value.</returns>
/// <remarks>
/// This method invokes the specified delegate, passing in the memory address of the view's
/// contents. This memory address is valid only while the delegate is executing. The
/// delegate must not access memory outside the view's range.
/// </remarks>
T InvokeWithDirectAccess<T>(Func<IntPtr, T> func);
}
}
|
using Chaser.Game;
using Chaser.UI;
namespace Chaser.Adapters
{
public class UserInputProcessorAdapter : ILoopAdapter
{
private UserInputProcessor _inputProcessor;
public UserInputProcessorAdapter(UserInputProcessor inputProcessor)
{
_inputProcessor = inputProcessor;
}
public void PerformLoopAction()
{
if (GameStateSingleton.Instance.State.GameRunning)
{
_inputProcessor.Process();
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Class which manages a checkpoint
/// </summary>
public class Checkpoint : MonoBehaviour
{
[Header("Settings")]
[Tooltip("The location this checkpoint will respawn the player at")]
public Transform respawnLocation;
[Tooltip("The animator for this checkpoint")]
public Animator checkpointAnimator = null;
[Tooltip("The name of the parameter in the animator which determines if this checkpoint displays as active")]
public string animatorActiveParameter = "isActive";
[Tooltip("The effect to create when activating the checkpoint")]
public GameObject checkpointActivationEffect;
/// <summary>
/// Description:
/// Standard unity function called when a trigger is entered by another collider
/// Input:
/// Collider collision
/// Returns:
/// void (no return)
/// </summary>
/// <param name="collision">The collider that has entered the trigger</param>
private void OnTriggerEnter(Collider collision)
{
if (collision.tag == "Player" && collision.gameObject.GetComponent<Health>() != null)
{
Health playerHealth = collision.gameObject.GetComponent<Health>();
playerHealth.SetRespawnPoint(respawnLocation.position);
// Reset the last checkpoint if it exists
if (CheckpointTracker.currentCheckpoint != null)
{
CheckpointTracker.currentCheckpoint.checkpointAnimator.SetBool(animatorActiveParameter, false);
}
if (CheckpointTracker.currentCheckpoint != this && checkpointActivationEffect != null)
{
Instantiate(checkpointActivationEffect, transform.position, Quaternion.identity, null);
}
// Set current checkpoint to this and set up its animation
CheckpointTracker.currentCheckpoint = this;
checkpointAnimator.SetBool(animatorActiveParameter, true);
}
}
}
|
using System;
using System.Diagnostics;
namespace GenerationAttributes {
/// <summary>
/// Generates a Lambda implementation of the marked interface.
/// </summary>
///
/// <remarks>
/// <para>A Lambda implementation is a class where each function in the interface is converted to a delegate.</para>
///
/// <para>Thus an interface like this:</para>
/// <code><![CDATA[
/// public interface IExampleInterface {
/// int add(int a, int b);
/// int negate(int a);
/// }
/// ]]></code>
///
/// <para>Would be converted to:</para>
/// <code><![CDATA[
/// public record LambdaIExampleInterface(
/// LambdaIExampleInterface._add add_,
/// LambdaIExampleInterface._negate negate_
/// ) : IExampleInterface {
/// public delegate int _add(int a, int b);
/// public int add(int a, int b) => add_(a, b);
///
/// public delegate int _negate(int a);
/// public int negate(int a) => negate_(a);
/// }
/// ]]></code>
/// </remarks>
[AttributeUsage(AttributeTargets.Interface), Conditional(Consts.UNUSED_NAME)]
public sealed class LambdaInterfaceAttribute : Attribute {}
} |
using LLin.Game.Screens.Mvis.Plugins.Types;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osuTK.Graphics;
namespace LLin.Game.Screens.Mvis.Plugins.Internal.FallbackFunctionBar
{
public class ToggleableBarButton : SimpleBarButton
{
private Box indicator;
public BindableBool Value = new BindableBool();
public ToggleableBarButton(IToggleableFunctionProvider provider)
: base(provider)
{
Value.BindTo(provider.Bindable);
}
[BackgroundDependencyLoader]
private void load()
{
AddInternal(indicator = new Box
{
Height = 5,
RelativeSizeAxes = Axes.X
});
}
protected override void LoadComplete()
{
Value.BindValueChanged(onValueChanged, true);
Value.BindDisabledChanged(onDisableChanged, true);
}
private void onDisableChanged(bool value)
{
this.FadeColour(value ? Color4.Gray : Color4.White, 300, Easing.OutQuint);
}
private void onValueChanged(ValueChangedEvent<bool> v)
{
indicator.FadeColour(v.NewValue ? Color4.Green : Color4.Gold, 300, Easing.OutQuint);
}
protected override bool OnClick(ClickEvent e)
{
if (Value.Disabled)
{
this.FlashColour(Color4.Red, 1000, Easing.OutQuint);
return false;
}
return base.OnClick(e);
}
}
}
|
using NeoPixelController.Model;
using System;
using System.Collections.Generic;
using System.Text;
namespace NeoPixelController.Interface
{
public interface INeoPixelEffect
{
Guid Id { get; }
string Name { get; set; }
bool IsEnabled { get; set; }
float Intensity { get; set; }
void Enter(EffectTime time);
void Update(EffectTime time);
void Exit(EffectTime time);
}
}
|
using System;
using Blue.ECS;
namespace BlueSpace
{
[RequiresComponentData(typeof(TextComponentData))]
public class PlayerScoreHUDComponentData : ComponentData
{
public String id;
}
public class PlayerScoreHUDComponentSystem : ComponentSystem
{
protected override void Start( string gameObjectId, ComponentData data )
{
PlayerScoreHUDComponentData playerHudData = data as PlayerScoreHUDComponentData;
PlayerScoreComponentData playerScoreData = GetComponentData<PlayerScoreComponentData>( playerHudData.id );
GetComponentData<TextComponentData>( gameObjectId ).text = playerScoreData.score.ToString( "D6" );
playerScoreData.onScored +=
( int newScore ) =>
{
GetComponentData<TextComponentData>( gameObjectId ).text = newScore.ToString("D6");
};
}
}
}
|
using StepsInSpace.Core.Abstractions.Math;
using StepsInSpace.Core.Abstractions.Math.Extensions;
using Xunit;
namespace UnitTests.StepsInSpace.Core.Abstractions.Math.Extensions;
public class Vector2dExtensionsFacts
{
[Theory]
[InlineData(1F, 2F, 3F, 4F, 1F + 3F, 2F + 4F)]
[InlineData(2F, 3F, 4F, 5F, 2F + 4F, 3F + 5F)]
[InlineData(-1F, -2F, -3F, -4F, -1F + -3F, -2F + -4F)]
[InlineData(-2F, -3F, -4F, -5F, -2F + -4F, -3F + -5F)]
public void Adds_vectors(float x1, float y1, float x2, float y2, float expectedX, float expectedY)
{
// Given
var sut = new Vector2d(x1, y1);
var right = new Vector2d(x2, y2);
// When
var actual = sut.Add(right);
// Then
Assert.Equal(expectedX, actual.X);
Assert.Equal(expectedY, actual.Y);
}
[Theory]
[InlineData(1F, 2F, 3F, 4F, 1F - 3F, 2F - 4F)]
[InlineData(2F, 2F, 3F, 5F, 2F - 3F, 2F - 5F)]
[InlineData(-1F, -2F, -3F, -4F, -1F - -3F, -2F - -4F)]
[InlineData(-2F, -2F, -3F, -5F, -2F - -3F, -2F - -5F)]
public void Subtracts_vectors(float x1, float y1, float x2, float y2, float expectedX, float expectedY)
{
// Given
var sut = new Vector2d(x1, y1);
var right = new Vector2d(x2, y2);
// When
var actual = sut.Subtract(right);
// Then
Assert.Equal(expectedX, actual.X);
Assert.Equal(expectedY, actual.Y);
}
[Theory]
[InlineData(1F, 2F, 3F, 4F, 1F * 3F, 2F * 4F)]
[InlineData(2F, 2F, 3F, 5F, 2F * 3F, 2F * 5F)]
[InlineData(-1F, -2F, -3F, -4F, -1F * -3F, -2F * -4F)]
[InlineData(2F, 2F, -3F, -5F, 2F * -3F, 2F * -5F)]
public void Multiplies_vectors(float x1, float y1, float x2, float y2, float expectedX, float expectedY)
{
// Given
var sut = new Vector2d(x1, y1);
var right = new Vector2d(x2, y2);
// When
var actual = sut.Multiply(right);
// Then
Assert.Equal(expectedX, actual.X);
Assert.Equal(expectedY, actual.Y);
}
[Theory]
[InlineData(1F, 2F, 3F, 4F, 1F / 3F, 2F / 4F)]
[InlineData(2F, 2F, 3F, 5F, 2F / 3F, 2F / 5F)]
[InlineData(-1F, -2F, -3F, -4F, -1F / -3F, -2F / -4F)]
[InlineData(2F, 2F, -3F, -5F, 2F / -3F, 2F / -5F)]
public void Divides_vectors(float x1, float y1, float x2, float y2, float expectedX, float expectedY)
{
// Given
var sut = new Vector2d(x1, y1);
var right = new Vector2d(x2, y2);
// When
var actual = sut.Divide(right);
// Then
Assert.Equal(expectedX, actual.X);
Assert.Equal(expectedY, actual.Y);
}
[Theory]
[InlineData(1F, 2F, 3F, 4F, 1F * 3F + 2F * 4F)]
[InlineData(2F, 2F, 3F, 5F, 2F * 3F + 2F * 5F)]
[InlineData(-1F, -2F, -3F, -4F, -1F * -3F + -2F * -4F)]
[InlineData(2F, 2F, -3F, -5F, 2F * -3F + 2F * -5F)]
public void Dots_vectors(float x1, float y1, float x2, float y2, float expected)
{
// Given
var sut = new Vector2d(x1, y1);
var right = new Vector2d(x2, y2);
// When
var actual = sut.Dot(right);
// Then
Assert.Equal(expected, actual);
}
[Fact]
public void Normalizes_vector()
{
// Given
var sut = new Vector2d(5F, 7F);
// When
var actual = sut.Normalize();
// Then
Assert.Equal(sut.X / (float)System.Math.Pow(sut.X * sut.X + sut.Y * sut.Y, 0.5F), actual.X);
Assert.Equal(sut.Y / (float)System.Math.Pow(sut.X * sut.X + sut.Y * sut.Y, 0.5F), actual.Y);
}
[Fact]
public void Calculates_length_of_vector()
{
// Given
var sut = new Vector2d(5F, 7F);
// When
var actual = sut.Length();
// Then
Assert.Equal((float)System.Math.Pow(sut.X * sut.X + sut.Y * sut.Y, 0.5F), actual);
}
[Fact]
public void Calculates_squared_length_of_vector()
{
// Given
var sut = new Vector2d(5F, 7F);
// When
var actual = sut.SquaredLength();
// Then
Assert.Equal(sut.X * sut.X + sut.Y * sut.Y, actual);
}
[Theory]
[InlineData(2F, 3F, 4F)]
[InlineData(-2F, -3F, 4F)]
public void Adds_number(float x, float y, float value)
{
// Given
var sut = new Vector2d(x, y);
// When
var actual = sut.Add(value);
// Then
Assert.Equal(x + value, actual.X);
Assert.Equal(y + value, actual.Y);
}
[Theory]
[InlineData(2F, 3F, 4F)]
[InlineData(-2F, -3F, 4F)]
public void Subtracts_number(float x, float y, float value)
{
// Given
var sut = new Vector2d(x, y);
// When
var actual = sut.Subtract(value);
// Then
Assert.Equal(x - value, actual.X);
Assert.Equal(y - value, actual.Y);
}
[Theory]
[InlineData(2F, 3F, 4F)]
[InlineData(-2F, -3F, 4F)]
public void Multiplies_number(float x, float y, float value)
{
// Given
var sut = new Vector2d(x, y);
// When
var actual = sut.Multiply(value);
// Then
Assert.Equal(x * value, actual.X);
Assert.Equal(y * value, actual.Y);
}
[Theory]
[InlineData(2F, 3F, 4F)]
[InlineData(-2F, -3F, 4F)]
public void Divides_number(float x, float y, float value)
{
// Given
var sut = new Vector2d(x, y);
// When
var actual = sut.Divide(value);
// Then
Assert.Equal(x / value, actual.X);
Assert.Equal(y / value, actual.Y);
}
} |
using $ext_safeprojectname$.Business.Abstract;
using $ext_safeprojectname$.Business.ValidationRules.FluentValidation;
using $ext_safeprojectname$.Core.Aspect.Postsharp.ValidationAspects;
using $ext_safeprojectname$.DataAccess.Abstract;
using $ext_safeprojectname$.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace $safeprojectname$.Concrete
{
class EmployeeManager : IEmployeeService
{
private readonly IEmployeeDal _employeeDal;
public EmployeeManager(IEmployeeDal employeeDal)
{
_employeeDal = employeeDal;
}
public ICollection<Employee> GetAll(Expression<Func<Employee, bool>> filter = null) =>
_employeeDal.GetAll(filter);
public Employee GetById(int id) =>
_employeeDal.Get(x => x.Id == id);
[FluentValidationAspect(typeof(EmployeeValidator))]
public Employee Add(Employee employee) =>
_employeeDal.Add(employee);
[FluentValidationAspect(typeof(EmployeeValidator))]
public Employee Update(Employee employee) =>
_employeeDal.Update(employee);
public void DeleteById(int id) =>
_employeeDal.Delete(new Employee { Id = id });
}
}
|
using Sirenix.OdinInspector;
using System;
using UnityEngine;
namespace MissionGrammar
{
[Serializable]
[CreateAssetMenu]
public class MissionRuleScriptableObject : ScriptableObject
{
public bool isOriginalRule = true;
[Title("Condition")]
[HideLabel]
[InlineProperty]
public FlatMissionGraph condition;
[Title("Result")]
[HideLabel]
[InlineProperty]
public FlatMissionGraph result;
internal MissionRule GetPlainClass()
{
var rule = new MissionRule
{
condition = condition.GetPlainClass(),
result = result.GetPlainClass()
};
return rule;
}
}
}
|
@using Library.Models;
@{ Layout = "_Layout"; }
@Html.Partial("_Staff")
<table>
<th>Title</th>
<th>Authors</th>
<th>Year</th>
<th>Available</th>
<th>Stock</th>
@foreach(Book book in @Book.GetAll())
{
<tr>
<td><a href="/staff/books/@book.GetId()">@book.GetTitle()</a></td>
<td>@foreach (Author author in book.GetBookAuthors())
{
@author.GetFirst()<span> </span> @author.GetLast()<br>
}
</td>
<td>@book.GetYear()</td>
<td>@book.GetAvailable()</td>
<td>@book.GetStock()</td>
</tr>
}
</table> |
//
// Copyright (C) 2014 EllieWare
//
// All rights reserved
//
// www.EllieWare.com
//
using System.Collections.Generic;
using Quartz;
namespace RobotWare.Quartz.Extensions
{
public interface IJobInfo : IJob
{
/// <summary>
/// read-only list of <see cref="IJobDataInfo"/> so that clients
/// can provide an appropriate user interface for creating/editing
/// job parameters
/// </summary>
IEnumerable<IJobDataInfo> JobDataInfos { get; }
}
}
|
using pst.encodables.ndb;
using pst.encodables.ndb.btree;
using pst.interfaces;
using pst.interfaces.blockallocation.datatree;
using pst.utilities;
using System.Collections.Generic;
namespace pst.impl.blockallocation.datatree
{
class BlockBTreeEntryAllocator : IBlockBTreeEntryAllocator
{
private readonly IHeaderUsageProvider headerUsageProvider;
private readonly List<LBBTEntry> allocatedBlockBTreeEntries;
public BlockBTreeEntryAllocator(
IHeaderUsageProvider headerUsageProvider,
List<LBBTEntry> allocatedBlockBTreeEntries)
{
this.headerUsageProvider = headerUsageProvider;
this.allocatedBlockBTreeEntries = allocatedBlockBTreeEntries;
}
public BID Allocate(IB blockOffset, int rawDataSize, bool internalBlock)
{
var bidIndex = headerUsageProvider.GetHeader().NextBID;
headerUsageProvider.Use(header => header.IncrementBIDIndexForDataBlocks());
var blockId = internalBlock ? BID.ForInternalBlock(bidIndex) : BID.ForExternalBlock(bidIndex);
allocatedBlockBTreeEntries.Add(
new LBBTEntry(
BREF.OfValue(blockId, blockOffset),
rawDataSize,
numberOfReferencesToThisBlock: 2,
padding: BinaryData.OfSize(4)));
return blockId;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using webDiscussex.Models;
namespace webDiscussex.DAO
{
public class HivDAO
{
public IList<Hiv> Lista(ref IList<Imagem> imgs)
{
using (var contexto = new EducacaoSexualContext())
{
IList<Hiv> lista = contexto.PP2_HIV.ToList();
foreach (Hiv h in lista)
imgs.Add(contexto.PP2_Imagem.Where(p => p.Id == h.CodImagem).FirstOrDefault());
return lista;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Core.CodeType
{
/// <summary>
/// socket发送/接收消息类
/// </summary>
public class MessageInfo
{
public CmdType Type { get; set; }
public string Data { get; set; }
}
public enum CmdType
{
/// <summary>
/// socket首次连接
/// </summary>
Connect = 10000,
/// <summary>
/// 传输消息格式错误
/// </summary>
Error = 00000,
/// <summary>
/// 用户信息
/// </summary>
UserInfo = 10001,
/// <summary>
/// 设置是否中奖
/// </summary>
RedEnvInfo = 20001,
/// <summary>
/// 获取中奖人数
/// </summary>
GetRedInfo = 20002,
/// <summary>
/// 获取是否有抽奖资格
/// </summary>
IsJoined = 20003,
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace PLI.Models.Post
{
public class Break : Location
{
public int shipment_id { get; set; }
}
}
|
using DG.Tweening;
using SoftMasking;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using ZStart.Core;
using ZStart.RGraph.Common;
using ZStart.RGraph.Enum;
using ZStart.RGraph.Layout;
using ZStart.RGraph.Manager;
using ZStart.RGraph.Model;
using ZStart.RGraph.Util;
using ZStart.RGraph.View.Parts;
namespace ZStart.RGraph
{
[DisallowMultipleComponent]
public class RGSimulator: ZBehaviourBase
{
public enum TouchType
{
Empty,
Pinch,
Drag,
Node
}
public Camera renderCamera;
public ScrollRect scrollRect;
public Image image;
public Transform nodeBox;
public Transform edgeBox;
public TouchType touchType;
// 数据充足的情况下最多展开多少层
public int maxLevel = 2;
public int nowLevel = 0;
private BaseLayout layout = null;
private RGNode selectedNode = null;
private bool isSpawning = false;
private System.Action<string> callAction;
float radius = 230f;
TouchPinch pinchTool;
string cacheNode = "";
void Start()
{
Init();
ZLog.Warning("relation graph simulator start...center = " + cacheNode);
if (isStartEnd)
{
DataManager.Instance.GetGraphByNode(cacheNode);
}
}
private void OnEnable()
{
Init();
AddListeners();
ZLog.Warning("relation graph simulator enable...center = " + cacheNode);
if (isStartEnd)
{
DataManager.Instance.GetGraphByNode(cacheNode);
}
pinchTool.ResetData();
}
private void OnDisable()
{
isSpawning = false;
StopAllCoroutines();
RemoveListeners();
}
private void LateUpdate()
{
if (isStartEnd)
{
layout.Step();
if (selectedNode != null && selectedNode.viewer.highlight)
{
selectedNode.viewer.highlight.Rotate(Vector3.back, Time.deltaTime * 30);
}
}
}
private void Init()
{
if (isStartEnd)
{
return;
}
if (renderCamera == null)
renderCamera = Camera.main;
scrollRect = mTransform.GetComponent<ScrollRect>();
image = mTransform.GetComponent<Image>();
nodeBox = mTransform.Find("Viewport/Content/Nodes").GetComponent<Transform>();
edgeBox = mTransform.Find("Viewport/Content/Edges").GetComponent<Transform>();
layout = new ForceDirectLayout(5f, 1f, 0.1f, radius, scrollRect.content);
pinchTool = scrollRect.transform.parent.gameObject.AddComponent<TouchPinch>();
pinchTool.SetCamera(renderCamera, this);
var mask = scrollRect.viewport.gameObject.AddComponent<SoftMask>();
mask.defaultShader = Shader.Find("Hidden/UI Default (Soft Masked)");
isStartEnd = true;
}
private void ClearSelected()
{
if (selectedNode != null)
{
selectedNode.Data.VX = 0f;
selectedNode.Data.VY = 0f;
selectedNode.Data.X = selectedNode.Data.LastPosition.x;
selectedNode.Data.Y = selectedNode.Data.LastPosition.y;
selectedNode.Data.isDrag = false;
selectedNode.Selected = false;
selectedNode.ShowMenu = false;
selectedNode = null;
if (callAction != null)
callAction.Invoke("");
}
}
public void SetPinch(float min, float max, float speed)
{
pinchTool.SetRangeAndSpeed(min, max, speed);
}
public void ZoomIn(float speed)
{
float sc = scrollRect.content.localScale.x;
pinchTool.Zoom(sc + speed);
}
public void ZoomOut(float speed)
{
float sc = scrollRect.content.localScale.x;
pinchTool.Zoom(sc - speed);
}
public void OpenNode(string uid, System.Action<string> fun)
{
cacheNode = uid;
callAction = fun;
ZLog.Warning("try open graph node..."+uid + ";" + isStartEnd);
if (isStartEnd && isActiveAndEnabled)
{
DataManager.Instance.GetGraphByNode(uid);
}
}
public void SetExpendLevel(int num)
{
maxLevel = num;
}
public void Close()
{
nowLevel = 0;
ClearSelected();
if(null != layout)
layout.Dispose();
cacheNode = "";
}
public void SwitchTouch(TouchType kind)
{
if (touchType == kind)
return;
touchType = kind;
if (kind == TouchType.Empty)
{
scrollRect.enabled = true;
image.enabled = true;
pinchTool.ActiveRaycast(false);
}
else if (kind == TouchType.Node)
{
scrollRect.enabled = false;
image.enabled = false;
pinchTool.ActiveRaycast(false);
}
else if (kind == TouchType.Pinch)
{
scrollRect.enabled = false;
image.enabled = false;
pinchTool.ActiveRaycast(true);
}
else if (kind == TouchType.Drag)
{
scrollRect.enabled = true;
image.enabled = true;
pinchTool.ActiveRaycast(false);
}
}
#region Event Handle
private void AddListeners()
{
DFNotifyManager.AddListener(DFNotifyType.OnNodeExpend, gameObject, OnNodeExpend);
DFNotifyManager.AddListener(DFNotifyType.OnNodePin, gameObject, OnNodePinned);
DFNotifyManager.AddListener(DFNotifyType.OnNodeHighlight, gameObject, OnNodeHighlight);
DFNotifyManager.AddListener(DFNotifyType.OnGraphDataUpdate, gameObject, OnGraphDataUpdate);
}
private void RemoveListeners()
{
DFNotifyManager.RemoveListener(DFNotifyType.OnNodeExpend, gameObject);
DFNotifyManager.RemoveListener(DFNotifyType.OnNodePin, gameObject);
DFNotifyManager.RemoveListener(DFNotifyType.OnGraphDataUpdate, gameObject);
DFNotifyManager.RemoveListener(DFNotifyType.OnNodeHighlight, gameObject);
}
private void OnGraphDataUpdate(object data)
{
if (data == null)
return;
GraphModel graph = data as GraphModel;
ZLog.Warning("create graph node = " + cacheNode + ";center = " + graph.Center + "; spawn = " + isSpawning);
if (graph.Center != cacheNode || isSpawning)
{
return;
}
var success = DataManager.Instance.AddGraph(graph);
if (success)
{
nowLevel += 1;
layout.ExpendNode(graph.Center);
StartCoroutine(CreateGraphInspector(graph));
}
else
{
var node = layout.GetNode(graph.Center);
if (node != null)
{
node.Expend = ExpendStatus.Disable;
}
}
}
private void OnNodeExpend(object data)
{
if (isSpawning)
return;
var uid = data as string;
RGNode node = layout.GetNode(uid);
ExpendNode(node);
DFNotifyManager.SendNotify(DFNotifyType.OnUIRefresh, "");
}
private void OnNodePinned(object data)
{
var uid = data as string;
RGNode item = layout.GetNode(uid);
if (item != null)
{
item.Pinned = !item.Pinned;
}
DFNotifyManager.SendNotify(DFNotifyType.OnUIRefresh, "");
}
private void OnNodeHighlight(object data)
{
if (data == null)
return;
var pair = (PairInfo)data;
var item = layout.GetNode(pair.value);
if (item == null)
{
DataManager.Instance.CheckGraph(pair.value, pair.key);
}
else
{
item.IsHighlight = true;
}
}
/// <summary>
/// 选择一个节点
/// </summary>
/// <param name="gesture"></param>
private void OnSimpleTap(RGNode node)
{
var obj = node.viewer.gameObject;
if (obj == null)
{
layout.HighlightRelation("");
ClearSelected();
return;
}
if (obj.name.Contains("Menu"))
{
GMenuParts menu = obj.GetComponentInParent<GMenuParts>();
MenuType type = menu.SelectState(node.viewer.name);
CheckMenuType(type);
}
else
{
if (node == selectedNode)
return;
ClearSelected();
selectedNode = node;
//node.ShowMenu = true;
node.Selected = true;
layout.HighlightRelation(node.Data.UID);
if (node.Data.IsVirtual)
{
ExpendNode(node);
}
else
{
if (CheckNextGraph(node))
{
ExpendNode(node);
}
}
if (callAction != null)
callAction.Invoke(node.Data.UID);
}
}
private void OnTouchNode(RGNode node, TouchPhase phase)
{
if (phase == TouchPhase.Began)
{
SwitchTouch(TouchType.Empty);
}
else
{
SwitchTouch(TouchType.Node);
}
if (phase == TouchPhase.Ended)
{
if (node.Pinned)
{
node.Pinned = false;
}
else
{
node.Pinned = true;
}
}
}
private void OnDragStart(RGNode node)
{
if (node == null)
return;
ClearSelected();
node.ShowMenu = false;
node.Selected = true;
selectedNode = node;
node.Data.isDrag = true;
node.Pinned = true;
}
private void OnDragEnd(RGNode node)
{
ClearSelected();
}
#endregion
private void ExpendNode(RGNode node)
{
if (isSpawning || node == null || nowLevel > maxLevel)
return;
if (node.Data.IsVirtual)
{
layout.ExpendNode(node.Data.UID);
var graph = DataManager.Instance.GetGraph(node.Data.parent);
var nodes = graph.GetNodesByVLink(node.Data.vName, node.Data.UID);
var edges = graph.GetLinksByType(node.Data.vName);
StartCoroutine(CreateNodesInspector(node.Data, nodes, edges));
}
else
{
if (node.Expend == ExpendStatus.Disable)
return;
if (node.Expend == ExpendStatus.Closed)
{
DataManager.Instance.CheckGraph(node.Data.UID, "");
node.Expend = ExpendStatus.Opened;
}
else
{
layout.ShrinkNode(node);
}
}
}
IEnumerator CreateGraphInspector(GraphModel model)
{
isSpawning = true;
layout.Stop();
model.SortRelations();
var parent = layout.GetNode(model.Parent);
var center = layout.GetNode(model.Center);
if (center == null)
{
center = layout.CreateNode(model.CenterInfo(), parent?.mTransform, nodeBox, 0f, model.Center);
center.AddListeners(OnSimpleTap, OnTouchNode, OnDragStart, OnDragEnd);
}
yield return null;
center.Show();
List<NodeInfo> nodes = model.GetVirtualNodes();
List<RGNode> viewers = new List<RGNode>(model.Nodes.Count);
List<LinkInfo> edges = null;
if (nodes.Count > 0)
{
edges = model.GetVirtualLinks();
}
else
{
nodes = model.GetNodes();
edges = model.GetLinks();
}
for (int i = 0; i < nodes.Count; i += 1)
{
LinkInfo e = model.GetEdge(nodes[i].UID, model.Center);
if (e != null)
{
radius = e.InitLength;
}
var item = layout.CreateNode(nodes[i], center.mTransform, nodeBox, radius, model.Center);
item.AddListeners(OnSimpleTap, OnTouchNode, OnDragStart, OnDragEnd);
viewers.Add(item);
yield return null;
}
for (int i = 0; i < viewers.Count; i += 1)
{
viewers[i].Show();
}
yield return new WaitForSeconds(0.2f);
center.IsHighlight = true;
isSpawning = false;
for (int i = 0; i < edges.Count; i += 1)
{
layout.CreateEdge(edges[i], edgeBox, model.Center);
yield return null;
}
layout.Begin();
// DFNotifyManager.SendNotify(DFNotifyType.OnUIRefresh, "");
}
IEnumerator CreateNodesInspector(NodeInfo center, List<NodeInfo> nodes, List<LinkInfo> edges)
{
isSpawning = true;
layout.Stop();
var parentNode = layout.GetNode(center.parent);
var centerNode = layout.GetNode(center.UID);
if (centerNode == null)
{
centerNode = layout.CreateNode(center, parentNode?.mTransform, nodeBox, 0f, center.parent);
centerNode.AddListeners(OnSimpleTap, OnTouchNode, OnDragStart, OnDragEnd);
}
yield return null;
centerNode.Show();
List<RGNode> list = new List<RGNode>(nodes.Count);
for (int i = 0; i < nodes.Count; i += 1)
{
var item = layout.CreateNode(nodes[i], centerNode.mTransform, nodeBox, radius, center.UID);
item.AddListeners(OnSimpleTap, OnTouchNode, OnDragStart, OnDragEnd);
list.Add(item);
yield return null;
}
for (int i = 0; i < list.Count; i += 1)
{
list[i].Show();
}
yield return new WaitForSeconds(0.2f);
centerNode.IsHighlight = true;
isSpawning = false;
for (int i = 0; i < edges.Count; i += 1)
{
layout.CreateEdge(edges[i], edgeBox, center.UID);
yield return null;
}
layout.Begin();
}
private bool CheckNextGraph(RGNode node)
{
string root = MessageManager.Instance.RootPath;
var expend = layout.CheckExpend(root, node);
if(!expend)
{
return false;
}
if (node.Data.entity == null)
{
var file = Path.Combine(node.Data.fullPath);
if (File.Exists(file))
{
var json = File.ReadAllText(file);
var tmp = ParseUtil.ParseEntityJson(json, root);
if (tmp != null)
{
tmp.uid = node.Data.UID;
node.Data.entity = tmp;
}
else
{
node.Data.entity = new EntityInfo
{
uid = node.Data.UID,
name = node.Data.name
};
}
}
else
{
node.Data.entity = new EntityInfo
{
uid = node.Data.UID,
name = node.Data.name
};
}
}
node.Data.Screen = RectTransformUtility.WorldToScreenPoint(renderCamera, node.mTransform.position);
// DFNotifyManager.SendNotify(DFNotifyType.OnNodeSelected, node.Data);
return true;
}
private void CheckMenuType(MenuType menu)
{
if (menu == MenuType.Experience || menu == MenuType.Remark)
{
if (selectedNode == null)
{
return;
}
if (menu == MenuType.Experience && selectedNode.Data.entity.HadEvents)
{
DFNotifyManager.SendNotify(DFNotifyType.OnNodeMenuUpdate, (int)menu);
}
if (menu == MenuType.Remark && selectedNode.Data.entity.HadRecord)
{
DFNotifyManager.SendNotify(DFNotifyType.OnNodeMenuUpdate, (int)menu);
}
}
else if (menu == MenuType.Pin)
{
OnNodePinned(selectedNode.Data.UID);
}
else if (menu == MenuType.Expend)
{
OnNodeExpend(selectedNode.Data.UID);
}
else if (menu == MenuType.Hide)
{
layout.HideNode(selectedNode);
ClearSelected();
}
}
private RGNode GetNode(GameObject obj)
{
if (obj == null)
{
return null;
}
return layout.GetNode(obj);
}
}
}
|
namespace HuaweiARUnitySDK
{
using HuaweiARInternal;
using System;
using UnityEngine;
using System.Collections.Generic;
/**
* \if english
* @brief Camera metadata of a \link ARFrame \endlink
* \else
* @brief \link ARFrame \endlink 相关的相机元数据。
* \endif
*/
public class ARCameraMetadata
{
private IntPtr m_metadataPtr;
private NDKSession m_ndkSession;
internal ARCameraMetadata(IntPtr metadataPtr,NDKSession session)
{
m_metadataPtr = metadataPtr;
m_ndkSession = session;
}
/**
* \if english
* @brief Get all camera metadata tags.
* @return A list of camera metadata tags.
* \else
* @brief 获取所有的元数据的tag。
* @return 元数据tag的列表。
* \endif
*/
public List<ARCameraMetadataTag> GetAllCameraMetadataTags()
{
List<ARCameraMetadataTag> metadataTags = new List<ARCameraMetadataTag>();
m_ndkSession.CameraMetadataAdapter.GetAllCameraMetadataTags(m_metadataPtr, metadataTags);
return metadataTags;
}
/**
* \if english
* @brief Get a camera metadata of input tag.
* @param cameraMetadataTag A camera metadata tag.
* @return A list of camera metadata values.
* \else
* @brief 根据元数据的tag获取元数据值。
* @param cameraMetadataTag 元数据tag。
* @return 元数据tag对应的值。
* \endif
*/
public List<ARCameraMetadataValue> GetValue(ARCameraMetadataTag cameraMetadataTag)
{
List<ARCameraMetadataValue> metadataValues = new List<ARCameraMetadataValue>();
m_ndkSession.CameraMetadataAdapter.GetValues(m_metadataPtr, cameraMetadataTag, metadataValues);
return metadataValues;
}
~ARCameraMetadata()
{
m_ndkSession.CameraMetadataAdapter.Release(m_metadataPtr);
}
}
}
|
using System;
using System.Collections.Generic;
using Uno.Collections;
namespace Uno.Core.Collections
{
public static class ListExtensionsLegacy
{
/// <summary>
/// Adapts a list of type T into a list of type U
/// </summary>
/// <typeparam name="T">The type to adapt.</typeparam>
/// <typeparam name="U">The target type.</typeparam>
/// <param name="items">The list to adapt</param>
/// <param name="from">The function used to adapt a U into a T.</param>
/// <param name="to">The function used to adapt a T into a U.</param>
/// <returns>A adapted list of the target type.</returns>
public static IList<U> Adapt<T, U>(this IList<T> items, Func<U, T> from, Func<T, U> to)
{
return new ListAdapter<T, U>(items, from, to);
}
public static IList<U> Adapt<T, U>(this IList<T> items)
{
return Adapt(items, Funcs<U, T>.Convert, Funcs<T, U>.Convert);
}
}
}
|
using System;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
namespace Day22
{
[DebuggerDisplay("{Location.X},{Location.Y} {Tool}")]
internal struct StepState : IEquatable<StepState>
{
public StepState(Point location, Tool tool)
{
Location = location;
Tool = tool;
}
public Point Location { get; }
public Tool Tool { get; }
public bool Equals(StepState other)
{
return Location == other.Location
&& Tool == other.Tool;
}
public override bool Equals(object obj)
{
return obj is StepState step && Equals(step);
}
public override int GetHashCode()
{
var h1 = Location.GetHashCode();
var h2 = Tool.GetHashCode();
return (h1 << 5) + h1 ^ h2;
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0},{1} {2}", Location.X, Location.Y, Tool);
}
}
}
|
#region Copyright
/*
* Copyright (C) 2018 Larry Lopez
*
* 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;
namespace Keeg.Crypto.Common
{
internal static class BitConverterEndian
{
#region Get Bytes
public static unsafe byte[] GetBytesBE(short value)
{
byte[] bytes = new byte[2];
fixed (byte* pbyte = bytes)
{
*(pbyte + 0) = (byte)(value >> 8);
*(pbyte + 1) = (byte)(value >> 0);
}
return bytes;
}
public static unsafe byte[] GetBytesBE(int value)
{
byte[] bytes = new byte[4];
fixed (byte* pbyte = bytes)
{
*(pbyte + 0) = (byte)(value >> 24);
*(pbyte + 1) = (byte)(value >> 16);
*(pbyte + 2) = (byte)(value >> 8);
*(pbyte + 3) = (byte)(value >> 0);
}
return bytes;
}
public static unsafe byte[] GetBytesBE(long value)
{
byte[] bytes = new byte[8];
fixed (byte* pbyte = bytes)
{
*(pbyte + 0) = (byte)(value >> 56);
*(pbyte + 1) = (byte)(value >> 48);
*(pbyte + 2) = (byte)(value >> 40);
*(pbyte + 3) = (byte)(value >> 32);
*(pbyte + 3) = (byte)(value >> 24);
*(pbyte + 3) = (byte)(value >> 16);
*(pbyte + 3) = (byte)(value >> 8);
*(pbyte + 3) = (byte)(value >> 0);
}
return bytes;
}
public static unsafe byte[] GetBytesBE(ushort value)
{
return GetBytesBE((short)value);
}
public static unsafe byte[] GetBytesBE(uint value)
{
return GetBytesBE((int)value);
}
public static unsafe byte[] GetBytesBE(ulong value)
{
return GetBytesBE((long)value);
}
public static unsafe byte[] GetBytesLE(short value)
{
byte[] bytes = new byte[2];
fixed (byte* pbyte = bytes)
{
*(pbyte + 0) = (byte)(value >> 0);
*(pbyte + 1) = (byte)(value >> 8);
}
return bytes;
}
public static unsafe byte[] GetBytesLE(int value)
{
byte[] bytes = new byte[4];
fixed (byte* pbyte = bytes)
{
*(pbyte + 0) = (byte)(value >> 0);
*(pbyte + 1) = (byte)(value >> 8);
*(pbyte + 2) = (byte)(value >> 16);
*(pbyte + 3) = (byte)(value >> 24);
}
return bytes;
}
public static unsafe byte[] GetBytesLE(long value)
{
byte[] bytes = new byte[8];
fixed (byte* pbyte = bytes)
{
*(pbyte + 0) = (byte)(value >> 0);
*(pbyte + 1) = (byte)(value >> 8);
*(pbyte + 2) = (byte)(value >> 16);
*(pbyte + 3) = (byte)(value >> 24);
*(pbyte + 4) = (byte)(value >> 32);
*(pbyte + 5) = (byte)(value >> 40);
*(pbyte + 6) = (byte)(value >> 48);
*(pbyte + 7) = (byte)(value >> 56);
}
return bytes;
}
public static unsafe byte[] GetBytesLE(ushort value)
{
return GetBytesLE((short)value);
}
public static unsafe byte[] GetBytesLE(uint value)
{
return GetBytesLE((int)value);
}
public static unsafe byte[] GetBytesLE(ulong value)
{
return GetBytesLE((long)value);
}
#endregion
#region Set Bytes
public static unsafe void SetBytesBE(short value, byte[] array, int startIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(short) <= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &array[startIndex])
{
*(pbyte + 0) = (byte)(value >> 8);
*(pbyte + 1) = (byte)(value >> 0);
}
}
public static unsafe void SetBytesBE(int value, byte[] array, int startIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(int) <= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &array[startIndex])
{
*(pbyte + 0) = (byte)(value >> 24);
*(pbyte + 1) = (byte)(value >> 16);
*(pbyte + 2) = (byte)(value >> 8);
*(pbyte + 3) = (byte)(value >> 0);
}
}
public static unsafe void SetBytesBE(long value, byte[] array, int startIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(long) <= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &array[startIndex])
{
*(pbyte + 0) = (byte)(value >> 56);
*(pbyte + 1) = (byte)(value >> 48);
*(pbyte + 2) = (byte)(value >> 40);
*(pbyte + 3) = (byte)(value >> 32);
*(pbyte + 4) = (byte)(value >> 24);
*(pbyte + 5) = (byte)(value >> 16);
*(pbyte + 6) = (byte)(value >> 8);
*(pbyte + 7) = (byte)(value >> 0);
}
}
public static unsafe void SetBytesBE(ushort value, byte[] array, int startIndex)
{
SetBytesBE((short)value, array, startIndex);
}
public static unsafe void SetBytesBE(uint value, byte[] array, int startIndex)
{
SetBytesBE((int)value, array, startIndex);
}
public static unsafe void SetBytesBE(ulong value, byte[] array, int startIndex)
{
SetBytesBE((long)value, array, startIndex);
}
public static unsafe void SetBytesLE(short value, byte[] array, int startIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(short) <= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &array[startIndex])
{
*(pbyte + 0) = (byte)(value >> 0);
*(pbyte + 1) = (byte)(value >> 8);
}
}
public static unsafe void SetBytesLE(int value, byte[] array, int startIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(int) <= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &array[startIndex])
{
*(pbyte + 0) = (byte)(value >> 0);
*(pbyte + 1) = (byte)(value >> 8);
*(pbyte + 2) = (byte)(value >> 16);
*(pbyte + 3) = (byte)(value >> 24);
}
}
public static unsafe void SetBytesLE(long value, byte[] array, int startIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(long) <= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &array[startIndex])
{
*(pbyte + 0) = (byte)(value >> 0);
*(pbyte + 1) = (byte)(value >> 8);
*(pbyte + 2) = (byte)(value >> 16);
*(pbyte + 3) = (byte)(value >> 24);
*(pbyte + 4) = (byte)(value >> 32);
*(pbyte + 5) = (byte)(value >> 40);
*(pbyte + 6) = (byte)(value >> 48);
*(pbyte + 7) = (byte)(value >> 56);
}
}
public static unsafe void SetBytesLE(ushort value, byte[] array, int startIndex)
{
SetBytesLE((short)value, array, startIndex);
}
public static unsafe void SetBytesLE(uint value, byte[] array, int startIndex)
{
SetBytesLE((int)value, array, startIndex);
}
public static unsafe void SetBytesLE(ulong value, byte[] array, int startIndex)
{
SetBytesLE((long)value, array, startIndex);
}
#endregion
#region To Integer
public static unsafe short ToInt16BE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(short) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &value[startIndex])
{
return (short)
(
(*(pbyte + 0) << 8) |
(*(pbyte + 1))
);
}
}
public static unsafe int ToInt32BE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(int) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &value[startIndex])
{
return (int)
(
(*(pbyte + 0) << 24) |
(*(pbyte + 1) << 16) |
(*(pbyte + 2) << 8) |
(*(pbyte + 3))
);
}
}
public static unsafe long ToInt64BE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(long) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &value[startIndex])
{
return (long)
(
(*(pbyte + 0) << 56) |
(*(pbyte + 1) << 48) |
(*(pbyte + 2) << 40) |
(*(pbyte + 3) << 32) |
(*(pbyte + 4) << 24) |
(*(pbyte + 5) << 16) |
(*(pbyte + 6) << 8) |
(*(pbyte + 7))
);
}
}
public static unsafe ushort ToUInt16BE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(ushort) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
return (ushort)ToInt16BE(value, startIndex);
}
public static unsafe uint ToUInt32BE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(uint) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
return (uint)ToInt32BE(value, startIndex);
}
public static unsafe ulong ToUInt64BE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(ulong) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
return (ulong)ToInt64BE(value, startIndex);
}
public static unsafe short ToInt16LE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(short) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &value[startIndex])
{
return (short)
(
(*(pbyte + 0)) |
(*(pbyte + 1) << 8)
);
}
}
public static unsafe int ToInt32LE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(int) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &value[startIndex])
{
return (int)
(
(*(pbyte + 0)) |
(*(pbyte + 1) << 8) |
(*(pbyte + 2) << 16) |
(*(pbyte + 3) << 24)
);
}
}
public static unsafe long ToInt64LE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(long) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
fixed (byte* pbyte = &value[startIndex])
{
return (long)
(
(*(pbyte + 0)) |
(*(pbyte + 1) << 8) |
(*(pbyte + 2) << 16) |
(*(pbyte + 3) << 24) |
(*(pbyte + 4) << 32) |
(*(pbyte + 5) << 40) |
(*(pbyte + 6) << 48) |
(*(pbyte + 7) << 56)
);
}
}
public static unsafe ushort ToUInt16LE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(ushort) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
return (ushort)ToInt16LE(value, startIndex);
}
public static unsafe uint ToUInt32LE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(uint) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
return (uint)ToInt32LE(value, startIndex);
}
public static unsafe ulong ToUInt64LE(byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (startIndex + sizeof(ulong) <= value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
return (ulong)ToInt64LE(value, startIndex);
}
#endregion
}
}
|
using PhobiaX.SDL2.Wrappers;
using System;
using System.Collections.Generic;
using System.Text;
namespace PhobiaX.SDL2
{
public class SDLSurfaceFactory
{
private readonly ISDL2 sdl2;
public SDLSurfaceFactory(ISDL2 sdl2)
{
this.sdl2 = sdl2 ?? throw new ArgumentNullException(nameof(sdl2));
}
public SDLSurface CreateSurface(int width, int height)
{
return CreateSurface(width, height, 32, SDLColor.Black, 0);
}
public SDLSurface CreateSurface(int width, int height, int depth, SDLColor maskColor, uint maskAlpha)
{
return new SDLSurface(this.sdl2, width, height, depth, maskColor, maskAlpha);
}
public SDLSurface CreateResizedSurface(SDLSurface originalSurface, int newWidth)
{
var ratio = (float)originalSurface.Surface.w / originalSurface.Surface.h;
var resizedSurface = this.CreateSurface(newWidth, (int)(newWidth / ratio));
resizedSurface.SetColorKey(SDLColor.Black);
originalSurface.BlitScaled(resizedSurface);
return resizedSurface;
}
public SDLSurface LoadSurface(string filePath)
{
var surface = sdl2.LoadBMP(filePath);
return new SDLSurface(sdl2, surface);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Editor
{
[ExecuteInEditMode]
public class Tk2dEmu : MonoBehaviour
{
public Vector3[] vertices;
public Vector2[] uvs;
public int[] indices;
[SerializeField]
int instanceId = 0;
public void Awake()
{
if (Application.isPlaying)
return;
if (instanceId == 0)
{
instanceId = GetInstanceID();
MeshFilter meshFilter = GetComponent<MeshFilter>();
if (meshFilter != null && meshFilter.sharedMesh == null)
{
Mesh mesh = new Mesh();
mesh.vertices = vertices;
mesh.triangles = indices;
mesh.normals = new Vector3[4]
{
-Vector3.forward,
-Vector3.forward,
-Vector3.forward,
-Vector3.forward
};
mesh.uv = uvs;
meshFilter.sharedMesh = mesh;
}
return;
}
}
}
}
|
namespace WarOfEmpires.Models.Empires {
public sealed class ResearchViewModel {
public string ResearchType { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Level { get; set; }
public decimal LevelBonus { get; set; }
public decimal CurrentBonus { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Define;
public abstract class EnemyBase : MonoBehaviour {
//참조
protected GameObject die_effect = null;
protected SFXManager sfx_manager = null;
protected DataManager data_manager = null;
protected SystemManager system_manager = null;
//속성
protected int hp = 1;
protected int hp_max = 1;
protected float move_speed = 0.06f;
protected enum State
{
GoUp, Alive, GoBack, Die
}
protected State state = State.GoUp;
//스코어 / 플레이어 체력
protected float sub_hp = 10f;
protected float add_hp = 3f;
protected int add_score = 10;
//체크
protected bool attacked = false;
protected float hit_height = -0.2f;
protected float init_height = -1f;
protected float limit_height = 0f;
//시간 체크
protected Timer wait_timer = new Timer(0, 6f);
protected float limit_time_min = 2f;
//사운드
protected float spawn_volume = 1.0f;
protected float die_volume = 1.0f;
protected float hide_volume = 1.0f;
protected bool play_spawn_sound = false;
protected SFXManager.SFXList die_sound = SFXManager.SFXList.Hit;
//초기화
public void Init()
{
//속성 초기화
hp = hp_max;
attacked = false;
//위치 이동
Vector3 pos = transform.position;
pos.y = init_height;
transform.position = pos;
//타이머 초기화
wait_timer.time = 0f;
//스폰 사운드 초기화
play_spawn_sound = false;
//상태 초기화
state = State.GoUp;
OptionalInit();
}
//자식 초기화
protected abstract void ChildInit();
//외부 초기화(옵션)
protected abstract void OptionalInit();
//초기화
void Start()
{
//필수
sfx_manager = SFXManager.Instance;
data_manager = DataManager.Instance;
system_manager = SystemManager.Instance;
//기본 초기화
Init();
//자식 초기화
ChildInit();
}
//업데이트
void FixedUpdate()
{
//End면 두더지 다 들어가게
if (system_manager.game_state == SystemManager.GameState.End)
state = State.GoBack;
//상태 처리
switch (state)
{
//생성 시 / 피격 후
case State.GoUp:
GoUp();
break;
//보통
case State.Alive:
Alive();
break;
//되돌아가기
case State.GoBack:
GoBack();
break;
//죽으면
case State.Die:
Die();
break;
}
}
#region 상태 관련
protected virtual void GoUp()
{
//올라가기(다올라가면 살아있다 표시)
if (MoveUp())
state = State.Alive;
//누르고 기다리는거 방지
//시간 체크
if (!wait_timer.CheckTimer())
wait_timer.AddTimer();
//다되면 되돌아감
else
state = State.GoBack;
}
protected abstract void Alive();
protected virtual void GoBack()
{
//내려가기(다내려가면 false) + 플레이어 HP 감소
if (MoveDown())
{
data_manager.SubHP(sub_hp);
gameObject.SetActive(false);
}
}
protected virtual void Die()
{
//바로 false
gameObject.SetActive(false);
}
#endregion
#region 충돌 체크
protected void OnCollisionStay(Collision collision)
{
if (collision.collider.CompareTag("Player"))
attacked = true;
}
protected void OnCollisionExit(Collision collision)
{
if (collision.collider.CompareTag("Player"))
attacked = false;
}
protected void OnTriggerStay(Collider other)
{
if (other.CompareTag("Player"))
attacked = true;
}
protected void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
attacked = false;
}
#endregion
#region 움직임
//올라가기
protected bool MoveUp()
{
//다 올라갔나 체크
bool send_bool = false;
//위치값
Vector3 pos = transform.position;
//Offset
float offset = 0.01f;
//사운드
if (!play_spawn_sound)
{
sfx_manager.PlaySFX(SFXManager.SFXList.Spawn, spawn_volume);
play_spawn_sound = true;
}
//올라가기
if (pos.y < limit_height - offset)
transform.Translate(0, move_speed, 0, Space.World);
//다올라가면 limit_height로 설정
else
{
pos.y = limit_height;
transform.position = pos;
send_bool = true;
}
return send_bool;
}
//내려가기
protected bool MoveDown()
{
//다 내려갔나 체크
bool send_bool = false;
//위치값
Vector3 pos = transform.position;
//Offset
float offset = 0.01f;
//올라가기
if (pos.y > init_height + offset)
transform.Translate(0, -move_speed, 0, Space.World);
//다내려가면
else
{
send_bool = true;
//사운드
sfx_manager.PlaySFX(SFXManager.SFXList.Hide, hide_volume);
}
return send_bool;
}
#endregion
//체력--
protected virtual void SubHp()
{
if (state != State.Alive && state != State.GoUp)
return;
if (hp > 0)
hp--;
else
hp = 0;
//0이면 죽음
if (hp == 0)
{
//점수++
data_manager.AddScore(add_score);
//HP++
data_manager.AddHP(add_hp);
//이펙트
GameObject effect = Instantiate(die_effect);
Vector3 pos = transform.position;
pos.y = 0f;
effect.transform.position = pos;
//사운드
sfx_manager.PlaySFX(die_sound, die_volume);
//상태
state = State.Die;
}
}
//시간--
public void DecreaseWaitTime(float _sub_time)
{
//최소시간 보다 많으면 뺌
if (wait_timer.limit - _sub_time > limit_time_min)
wait_timer.limit -= _sub_time;
//아니면 최소시간으로
else
wait_timer.limit = limit_time_min;
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace GooglePinger
{
/// <summary>
/// Логика взаимодействия для Stuff.xaml
/// </summary>
public partial class Stuff : Window
{
public Stuff(NetworkInterface[] cabels)
{
InitializeComponent();
chooseIP(cabels);
}
private void chooseIP(NetworkInterface[] cabels)
{
//prepare for something I wouldnt do even in cpp
string lastIP = "";
int i = 0;
//checking all Gateways connected to PC
List<IpListingLabel> ipList = new List<IpListingLabel>();
foreach (NetworkInterface cabel in cabels)
{
ipList.Add(new IpListingLabel(i, cabel.Name + " -- " + cabel.Description, this.StuffMainGrid, false));
i++;
IPInterfaceProperties props = cabel.GetIPProperties();
GatewayIPAddressInformationCollection ipCol = props.GatewayAddresses;
foreach (GatewayIPAddressInformation ipOne in ipCol)
{
ipList.Add(new IpListingLabel(i, ipOne.Address.ToString(), this.StuffMainGrid, true));
ipList[i].MouseDown +=
delegate
{
this.Close();
};
ipList[i].hasActualIp = true;
i++;
lastIP = ipOne.Address.ToString();
}
}
}
//offering user to edit config manually
private void infoLabel_MouseDown(object sender, MouseButtonEventArgs e)
{
Process.Start("explorer.exe", System.IO.Directory.GetCurrentDirectory());
}
}
}
|
using UnityEngine;
using System.Collections;
namespace RVP
{
[RequireComponent(typeof(Suspension))]
[DisallowMultipleComponent]
[AddComponentMenu("RVP/Suspension/Suspension Property", 2)]
// Class for changing the properties of the suspension
public class SuspensionPropertyToggle : MonoBehaviour
{
public SuspensionToggledProperty[] properties;
Suspension sus;
void Start() {
sus = GetComponent<Suspension>();
}
// Toggle a property in the properties array at index
public void ToggleProperty(int index) {
if (properties.Length - 1 >= index) {
properties[index].toggled = !properties[index].toggled;
if (sus) {
sus.UpdateProperties();
}
}
}
// Set a property in the properties array at index to the value
public void SetProperty(int index, bool value) {
if (properties.Length - 1 >= index) {
properties[index].toggled = value;
if (sus) {
sus.UpdateProperties();
}
}
}
}
// Class for a single property
[System.Serializable]
public class SuspensionToggledProperty
{
public enum Properties { steerEnable, steerInvert, driveEnable, driveInvert, ebrakeEnable, skidSteerBrake } // The type of property
// steerEnable = enable steering
// steerInvert = invert steering
// driveEnable = enable driving
// driveInvert = invert drive
// ebrakeEnable = can ebrake
// skidSteerBrake = brake is specially adjusted for skid steering
public Properties property; // The property
public bool toggled; // Is it enabled?
}
} |
/*
MIT License
Copyright (c) 2019 Jose Ferreira (Bazoocaze)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using VulkanCpu.VulkanApi;
namespace VulkanCpu.Engines.SoftwareEngine
{
public class SoftwareDeviceMemory : VkDeviceMemory
{
public readonly VkMemoryAllocateInfo m_allocateInfo;
public readonly SoftwareDevice m_device;
public byte[] m_bytes;
public bool m_Mapped;
public byte[] m_MapSubBuffer;
public int m_MapSubOffset;
public int m_MapSubSize;
public SoftwareDeviceMemory(SoftwareDevice device, VkMemoryAllocateInfo allocateInfo)
{
this.m_device = device;
this.m_allocateInfo = allocateInfo;
this.m_bytes = new byte[m_allocateInfo.allocationSize];
}
public VkResult MapMemory(int offset, int size, int memoryMapFlags, out byte[] ppData)
{
if (m_Mapped)
{
ppData = null;
return VkResult.VK_ERROR_MEMORY_MAP_FAILED;
}
if (offset == 0)
{
ppData = m_bytes;
}
else
{
m_MapSubBuffer = new byte[size];
m_MapSubOffset = offset;
m_MapSubSize = size;
Buffer.BlockCopy(m_bytes, offset, m_MapSubBuffer, 0, size);
ppData = m_MapSubBuffer;
}
m_Mapped = true;
return VkResult.VK_SUCCESS;
}
public void UnmapMemory()
{
if (!m_Mapped)
{
return;
}
if (m_MapSubBuffer != null)
{
Array.Copy(m_MapSubBuffer, 0, m_bytes, m_MapSubOffset, m_MapSubSize);
m_MapSubBuffer = null;
}
m_Mapped = false;
}
public void Destroy()
{
}
}
} |
//
// System.Diagnostics.PerformanceCounter.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
// Andreas Nahr (ClassDevelopment@A-SoftTech.com)
//
// (C) 2002
// (C) 2003 Andreas Nahr
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
#if NET_2_0
using System.Runtime.ConstrainedExecution;
#endif
namespace System.Diagnostics {
// must be safe for multithreaded operations
#if !NET_2_0
[Designer ("Microsoft.VisualStudio.Install.PerformanceCounterDesigner, " + Consts.AssemblyMicrosoft_VisualStudio)]
#endif
[InstallerType (typeof (PerformanceCounterInstaller))]
public sealed class PerformanceCounter : Component, ISupportInitialize
{
private string categoryName;
private string counterName;
private string instanceName;
private string machineName;
IntPtr impl;
PerformanceCounterType type;
CounterSample old_sample;
private bool readOnly;
bool valid_old;
bool changed;
bool is_custom;
#if NET_2_0
private PerformanceCounterInstanceLifetime lifetime;
#endif
#if NET_2_0
[Obsolete]
#endif
public static int DefaultFileMappingSize = 524288;
// set catname, countname, instname to "", machname to "."
public PerformanceCounter ()
{
categoryName = counterName = instanceName = "";
machineName = ".";
}
// throws: InvalidOperationException (if catName or countName
// is ""); ArgumentNullException if either is null
// sets instName to "", machname to "."
public PerformanceCounter (String categoryName,
string counterName)
: this (categoryName, counterName, false)
{
}
public PerformanceCounter (string categoryName,
string counterName,
bool readOnly)
: this (categoryName, counterName, "", readOnly)
{
}
public PerformanceCounter (string categoryName,
string counterName,
string instanceName)
: this (categoryName, counterName, instanceName, false)
{
}
public PerformanceCounter (string categoryName,
string counterName,
string instanceName,
bool readOnly)
{
if (categoryName == null)
throw new ArgumentNullException ("categoryName");
if (counterName == null)
throw new ArgumentNullException ("counterName");
if (instanceName == null)
throw new ArgumentNullException ("instanceName");
CategoryName = categoryName;
CounterName = counterName;
if (categoryName == "" || counterName == "")
throw new InvalidOperationException ();
InstanceName = instanceName;
this.instanceName = instanceName;
this.machineName = ".";
this.readOnly = readOnly;
changed = true;
}
public PerformanceCounter (string categoryName,
string counterName,
string instanceName,
string machineName)
: this (categoryName, counterName, instanceName, false)
{
this.machineName = machineName;
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
static extern IntPtr GetImpl (string category, string counter,
string instance, string machine, out PerformanceCounterType ctype, out bool custom);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
static extern bool GetSample (IntPtr impl, bool only_value, out CounterSample sample);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
static extern long UpdateValue (IntPtr impl, bool do_incr, long value);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
static extern void FreeData (IntPtr impl);
/* the perf counter has changed, ensure it's valid and setup it to
* be able to collect/update data
*/
void UpdateInfo ()
{
// need to free the previous info
if (impl != IntPtr.Zero)
Close ();
impl = GetImpl (categoryName, counterName, instanceName, machineName, out type, out is_custom);
// system counters are always readonly
if (!is_custom)
readOnly = true;
// invalid counter, need to handle out of mem
// TODO: reenable this
//if (impl == IntPtr.Zero)
// throw new InvalidOperationException ();
changed = false;
}
// may throw ArgumentNullException
[DefaultValue (""), ReadOnly (true), RecommendedAsConfigurable (true)]
[TypeConverter ("System.Diagnostics.Design.CategoryValueConverter, " + Consts.AssemblySystem_Design)]
[SRDescription ("The category name for this performance counter.")]
public string CategoryName {
get {return categoryName;}
set {
if (value == null)
throw new ArgumentNullException ("categoryName");
categoryName = value;
changed = true;
}
}
// may throw InvalidOperationException
[MonoTODO]
[ReadOnly (true), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[MonitoringDescription ("A description describing the counter.")]
public string CounterHelp {
get {return "";}
}
// may throw ArgumentNullException
[DefaultValue (""), ReadOnly (true), RecommendedAsConfigurable (true)]
[TypeConverter ("System.Diagnostics.Design.CounterNameConverter, " + Consts.AssemblySystem_Design)]
[SRDescription ("The name of this performance counter.")]
public string CounterName
{
get {return counterName;}
set {
if (value == null)
throw new ArgumentNullException ("counterName");
counterName = value;
changed = true;
}
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[MonitoringDescription ("The type of the counter.")]
public PerformanceCounterType CounterType {
get {
if (changed)
UpdateInfo ();
return type;
}
}
#if NET_2_0
[MonoTODO]
[DefaultValue (PerformanceCounterInstanceLifetime.Global)]
public PerformanceCounterInstanceLifetime InstanceLifetime {
get { return lifetime; }
set { lifetime = value; }
}
#endif
[DefaultValue (""), ReadOnly (true), RecommendedAsConfigurable (true)]
[TypeConverter ("System.Diagnostics.Design.InstanceNameConverter, " + Consts.AssemblySystem_Design)]
[SRDescription ("The instance name for this performance counter.")]
public string InstanceName {
get {return instanceName;}
set {
if (value == null)
throw new ArgumentNullException ("value");
instanceName = value;
changed = true;
}
}
// may throw ArgumentException if machine name format is wrong
[MonoTODO("What's the machine name format?")]
[DefaultValue ("."), Browsable (false), RecommendedAsConfigurable (true)]
[SRDescription ("The machine where this performance counter resides.")]
public string MachineName {
get {return machineName;}
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value == "" || value == ".") {
machineName = ".";
changed = true;
return;
}
throw new PlatformNotSupportedException ();
}
}
// may throw InvalidOperationException, Win32Exception
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[MonitoringDescription ("The raw value of the counter.")]
public long RawValue {
get {
CounterSample sample;
if (changed)
UpdateInfo ();
GetSample (impl, true, out sample);
// should this update old_sample as well?
return sample.RawValue;
}
set {
if (changed)
UpdateInfo ();
if (readOnly)
throw new InvalidOperationException ();
UpdateValue (impl, false, value);
}
}
[Browsable (false), DefaultValue (true)]
[MonitoringDescription ("The accessability level of the counter.")]
public bool ReadOnly {
get {return readOnly;}
set {readOnly = value;}
}
public void BeginInit ()
{
// we likely don't need to do anything significant here
}
public void EndInit ()
{
// we likely don't need to do anything significant here
}
public void Close ()
{
IntPtr p = impl;
impl = IntPtr.Zero;
if (p != IntPtr.Zero)
FreeData (p);
}
public static void CloseSharedResources ()
{
// we likely don't need to do anything significant here
}
// may throw InvalidOperationException, Win32Exception
public long Decrement ()
{
return IncrementBy (-1);
}
protected override void Dispose (bool disposing)
{
Close ();
}
// may throw InvalidOperationException, Win32Exception
public long Increment ()
{
return IncrementBy (1);
}
// may throw InvalidOperationException, Win32Exception
#if NET_2_0
[ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public long IncrementBy (long value)
{
if (changed)
UpdateInfo ();
if (readOnly) {
// FIXME: This should really throw, but by now set this workaround in place.
//throw new InvalidOperationException ();
return 0;
}
return UpdateValue (impl, true, value);
}
// may throw InvalidOperationException, Win32Exception
public CounterSample NextSample ()
{
CounterSample sample;
if (changed)
UpdateInfo ();
GetSample (impl, false, out sample);
valid_old = true;
old_sample = sample;
return sample;
}
// may throw InvalidOperationException, Win32Exception
public float NextValue ()
{
CounterSample sample;
if (changed)
UpdateInfo ();
GetSample (impl, false, out sample);
float val;
if (valid_old)
val = CounterSampleCalculator.ComputeCounterValue (old_sample, sample);
else
val = CounterSampleCalculator.ComputeCounterValue (sample);
valid_old = true;
old_sample = sample;
return val;
}
// may throw InvalidOperationException, Win32Exception
[MonoTODO]
#if NET_2_0
[ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public void RemoveInstance ()
{
throw new NotImplementedException ();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GisSpatial
{
class Program
{
static void Main(string[] args)
{
string degrees = "5321.5802 N, 00630.3372 W";
Console.WriteLine("Coordinates: {0}", degrees);
GeoCoordinates coords = GeoCoordinates.FromNMEA0183(degrees);
Console.WriteLine("NMEA0183: {0}", coords.ToString(GeoCoordinates.NMEA0183));
Console.WriteLine("WGS84: {0}", coords.ToString(GeoCoordinates.WGS84));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using UniRx.Async;
using UnityEngine;
public class DOTweenList : CustomYieldInstruction
{
List<Tween> list;
public Func<bool> cond;
public DOTweenList(params Tween[] tweens)
{
list = tweens.ToList();
}
public DOTweenList(IEnumerable<Tween> tweens)
{
list = tweens.Where(x => x != null).ToList();
}
public override bool keepWaiting
{
get
{
if ((cond != null && cond()))
{
foreach (var tween in list)
{
if (tween.IsActive() && tween.IsPlaying())
{
if (tween.IsBackwards())
{
tween.Rewind();
}
else
{
tween.Complete();
}
}
}
return false;
}
return IsPlaying();
}
}
public DOTweenList PlayForward(bool rewind = false)
{
foreach (var tween in list)
{
if (rewind)
{
tween.Rewind();
}
tween.PlayForward();
}
return this;
}
public DOTweenList PlayForwardById(string id, bool rewind = false)
{
foreach (var tween in list)
{
if (tween.stringId == id)
{
if (rewind)
{
tween.Rewind();
}
tween.PlayForward();
}
}
return this;
}
public DOTweenList PlayBackwards(bool complete = false)
{
foreach (var tween in list)
{
if (complete)
{
tween.Complete();
}
tween.PlayBackwards();
}
return this;
}
public DOTweenList PlayBackwardsById(string id, bool complete = false)
{
foreach (var tween in list)
{
if (tween.stringId == id)
{
if (complete)
{
tween.Complete();
}
tween.PlayBackwards();
}
}
return this;
}
public void Rewind()
{
foreach (var tween in list)
{
tween.Rewind();
}
}
public void RewindById(string id)
{
foreach (var tween in list)
{
if (tween.stringId == id)
{
tween.Rewind();
}
}
}
public void Complete()
{
foreach (var tween in list)
{
tween.Complete();
}
}
public void CompleteById(string id)
{
foreach (var tween in list)
{
if (tween.stringId == id)
{
tween.Complete();
}
}
}
public void Kill()
{
foreach (var tween in list)
{
tween.Kill();
}
}
public void KillById(string id)
{
foreach (var tween in list)
{
if (tween.stringId == id)
{
tween.Kill();
}
}
}
public bool IsPlaying() => list.Any(x => x.IsActive() && x.IsPlaying());
public void Add(Tween tween) => list.Add(tween);
public void Clear() => list.Clear();
public float GetTotalTime() => list.Max(x => x.Duration() + x.Delay());
public float GetTotalTimeById(string id) =>
list.Where(x => x.stringId == id).Max(x => x.Duration() + x.Delay());
}
public static class DOTweenListExtensions
{
public static Tween AddTo(this Tween self, DOTweenList dotweenList)
{
if (self == null)
{
throw new ArgumentNullException("tween");
}
if (dotweenList == null)
{
throw new ArgumentNullException("dotweenList");
}
dotweenList.Add(self);
return self;
}
public static DOTweenList Skippable(this DOTweenList self, Func<bool> cond)
{
self.cond = cond;
return self;
}
public static async void Forget(this DOTweenList self)
{
await self;
}
}
|
using System.Threading.Tasks;
namespace NextGenSoftware.OASIS.API.Providers.CargoOASIS.Infrastructure.Interfaces
{
public interface ISingleHandler<T>
{
Task<T> Handle();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trees
{
public class Node
{
public int val;
public IList<Node> neighbors;
public Node()
{
val = 0;
neighbors = new List<Node>();
}
public Node(int _val)
{
val = _val;
neighbors = new List<Node>();
}
public Node(int _val, List<Node> _neighbors)
{
val = _val;
neighbors = _neighbors;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OKExSDK.Models.Futures
{
public class PositionCrossed : Position
{
/// <summary>
/// 预估爆仓价
/// </summary>
public decimal liquidation_price { get; set; }
/// <summary>
/// 杠杆倍数
/// </summary>
public int leverage { get; set; }
}
}
|
using System;
namespace Notus.Model.Models
{
public class Comment
{
public Comment()
{
CommentDate = DateTime.Now;
}
public int CommentId { get; set; }
public string CommentText { get; set; }
public int UpdateId { get; set; }
public DateTime CommentDate { get; set; }
public virtual Update Update { get; set; }
}
} |
using System;
namespace EmptyBox.Network
{
public interface IAccessPoint : IEquatable<IAccessPoint>, IFormattable
{
public AccessPointUniquenessType UniquenessType { get; }
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Glue.Services
{
public static class ApiService
{
static HttpClient client = new HttpClient();
public static async Task<IEnumerable<Model.Display>> GetAllDisplaysAsync()
{
return new List<Model.Display>()
{
new Model.Display(){Id="test1" },
new Model.Display(){Id="test2" },
new Model.Display(){Id="test3" },
new Model.Display(){Id="test4" }
};
HttpResponseMessage response = await client.GetAsync("api/display");
if (response.IsSuccessStatusCode)
{
var res = await response.Content.ReadAsStringAsync();
var displays = JsonConvert.DeserializeObject<IEnumerable<Model.Display>>(res);
return displays;
}
return new List<Model.Display>();
}
public static async Task<Model.Display> GetDisplayByIdAsync(string id)
{
HttpResponseMessage response = await client.GetAsync($"api/display/{id}");
if (response.IsSuccessStatusCode)
{
var res = await response.Content.ReadAsStringAsync();
var display = JsonConvert.DeserializeObject<Model.Display>(res);
return display;
}
return new Model.Display();
}
public static async Task<IEnumerable<Model.Volunteer>> GetAllVolunteersAsync()
{
return new List<Model.Volunteer>()
{
new Model.Volunteer(){Id="test1", FirstName="Tobias", Surname="Jetzen" },
new Model.Volunteer(){Id="test2", FirstName="Tinael", Surname="Devresse" },
new Model.Volunteer(){Id="test3", FirstName="Stephanie", Surname="Bemelmans" },
new Model.Volunteer(){Id="test4", FirstName="David", Surname="Servais"}
};
HttpResponseMessage response = await client.GetAsync("api/display");
if (response.IsSuccessStatusCode)
{
var res = await response.Content.ReadAsStringAsync();
var displays = JsonConvert.DeserializeObject<IEnumerable<Model.Volunteer>>(res);
return displays;
}
return new List<Model.Volunteer>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
namespace ColaFramework
{
/// <summary>
/// MD5码加密工具类
/// </summary>
public static class MD5Helper
{
/// <summary>
/// 对指定路径的文件加密,返回加密后的文本
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string MD5EncryptFile(string filePath)
{
byte[] retVal;
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
MD5 md5 = new MD5CryptoServiceProvider();
retVal = md5.ComputeHash(fs);
}
return retVal.ToHex("x2");
}
/// <summary>
/// 对指定的字符串加密,返回加密后的字符串
/// </summary>
/// <param name="originStr"></param>
/// <returns></returns>
public static string MD5EncryptString(string originStr)
{
byte[] retVal;
MD5 md5 = new MD5CryptoServiceProvider();
retVal = md5.ComputeHash(Encoding.UTF8.GetBytes(originStr));
return retVal.ToHex("x2");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using NHSD.GPIT.BuyingCatalogue.EntityFramework.Catalogue.Models;
using NHSD.GPIT.BuyingCatalogue.EntityFramework.Ordering.Models;
using NHSD.GPIT.BuyingCatalogue.Framework.Extensions;
using NHSD.GPIT.BuyingCatalogue.ServiceContracts.Solutions.Models;
using NHSD.GPIT.BuyingCatalogue.WebApp.Areas.Solutions.Controllers;
namespace NHSD.GPIT.BuyingCatalogue.WebApp.Areas.Solutions.Models
{
public abstract class SolutionDisplayBaseModel
{
private const string KeyDescription = "Description";
private static readonly string ControllerName = typeof(SolutionsController).ControllerName();
private IList<SectionModel> sections;
protected SolutionDisplayBaseModel()
{
}
protected SolutionDisplayBaseModel(
CatalogueItem catalogueItem,
CatalogueItemContentStatus contentStatus)
{
if (catalogueItem is null)
throw new ArgumentNullException(nameof(catalogueItem));
SolutionId = catalogueItem.Id;
SolutionName = catalogueItem.Name;
PublicationStatus = catalogueItem.PublishedStatus;
LastReviewed = catalogueItem.Solution.LastUpdated;
SetSections(contentStatus);
SetPaginationFooter();
}
public abstract int Index { get; }
public DateTime LastReviewed { get; set; }
public PaginationFooterModel PaginationFooter { get; set; } = new();
public virtual string Section => sections[Index].Name;
public CatalogueItemId SolutionId { get; set; }
public string SolutionName { get; set; }
public PublicationStatus PublicationStatus { get; }
public virtual IList<SectionModel> GetSections()
{
var sectionsToShow = new List<SectionModel>(sections.Where(s => s.Show));
sectionsToShow.ForEach(s => s.SolutionId = SolutionId.ToString());
if (sectionsToShow.FirstOrDefault(s => s.Name.EqualsIgnoreCase(Section)) is { } sectionModel)
sectionModel.Selected = true;
return sectionsToShow;
}
public bool NotFirstSection() => !Section.EqualsIgnoreCase(KeyDescription);
public void SetPaginationFooter()
{
var sectionsToShow = new List<SectionModel>(sections.Where(s => s.Show));
if (sectionsToShow.FirstOrDefault(s => s.Name.EqualsIgnoreCase(Section)) is not { } sectionModel)
return;
var index = sectionsToShow.IndexOf(sectionModel);
PaginationFooter.Previous = index > 0 ? sectionsToShow[index - 1] : null;
PaginationFooter.Next = index < (sectionsToShow.Count - 1) ? sectionsToShow[index + 1] : null;
}
public bool IsInRemediation() => PublicationStatus == PublicationStatus.InRemediation;
public bool IsSuspended() => PublicationStatus == PublicationStatus.Suspended;
private void SetSections(CatalogueItemContentStatus contentStatus)
{
sections = new List<SectionModel>
{
new()
{
Action = nameof(SolutionsController.Description),
Controller = ControllerName,
Name = KeyDescription,
Show = CatalogueItemContentStatus.ShowDescription,
},
new()
{
Action = nameof(SolutionsController.Features),
Controller = ControllerName,
Name = "Features",
Show = contentStatus.ShowFeatures,
},
new()
{
Action = nameof(SolutionsController.Capabilities),
Controller = ControllerName,
Name = "Capabilities and Epics",
Show = CatalogueItemContentStatus.ShowCapabilities,
},
new()
{
Action = nameof(SolutionsController.Standards),
Controller = ControllerName,
Name = "Standards",
Show = CatalogueItemContentStatus.ShowStandards,
},
new()
{
Action = nameof(SolutionsController.ListPrice),
Controller = ControllerName,
Name = "List price",
Show = CatalogueItemContentStatus.ShowListPrice,
},
new()
{
Action = nameof(SolutionsController.AdditionalServices),
Controller = ControllerName,
Name = "Additional Services",
Show = contentStatus.ShowAdditionalServices,
},
new()
{
Action = nameof(SolutionsController.AssociatedServices),
Controller = ControllerName,
Name = "Associated Services",
Show = contentStatus.ShowAssociatedServices,
},
new()
{
Action = nameof(SolutionsController.Interoperability),
Controller = ControllerName,
Name = nameof(SolutionsController.Interoperability),
Show = contentStatus.ShowInteroperability,
},
new()
{
Action = nameof(SolutionsController.Implementation),
Controller = ControllerName,
Name = "Implementation",
Show = contentStatus.ShowImplementation,
},
new()
{
Action = nameof(SolutionsController.ClientApplicationTypes),
Controller = ControllerName,
Name = "Client application type",
Show = CatalogueItemContentStatus.ShowClientApplications,
},
new()
{
Action = nameof(SolutionsController.HostingType),
Controller = ControllerName,
Name = "Hosting type",
Show = contentStatus.ShowHosting,
},
new()
{
Action = nameof(SolutionsController.ServiceLevelAgreement),
Controller = ControllerName,
Name = "Service Level Agreement",
Show = CatalogueItemContentStatus.ShowServiceLevelAgreements,
},
new()
{
Action = nameof(SolutionsController.DevelopmentPlans),
Controller = ControllerName,
Name = "Development plans",
Show = CatalogueItemContentStatus.ShowDevelopmentPlans,
},
new()
{
Action = nameof(SolutionsController.SupplierDetails),
Controller = ControllerName,
Name = "Supplier details",
Show = CatalogueItemContentStatus.ShowSupplierDetails,
},
};
}
}
}
|
namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests
{
public class FakeChangeMessageVisbilityRequest
{
public FakeChangeMessageVisbilityRequest(string queueUrl, string receiptHandle, int visibilityTimeoutInSeconds)
{
QueueUrl = queueUrl;
ReceiptHandle = receiptHandle;
VisibilityTimeoutInSeconds = visibilityTimeoutInSeconds;
}
public string QueueUrl { get; }
public string ReceiptHandle { get; }
public int VisibilityTimeoutInSeconds { get; }
}
}
|
using BlazorBoilerplate.Shared.Dto;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BlazorBoilerplate.Shared.DataInterfaces
{
public interface IApiLogStore
{
Task<List<ApiLogItemDto>> Get();
Task<List<ApiLogItemDto>> GetByUserId(Guid userId);
}
} |
//
// Copyright (c) 2009 Froduald Kabanza and the Université de Sherbrooke.
// Use of this software is permitted for non-commercial research purposes, and
// it may be copied or applied only for that use. All copies must include this
// copyright message.
//
// This is a research prototype and it has not gone through intensive tests and
// is delivered as is. It may still contain bugs. Froduald Kabanza and the
// Université de Sherbrooke disclaim any responsibility for damage that may be
// caused by using it.
//
// Please note that this file was inspired in part by the PDDL4J library:
// http://www.math-info.univ-paris5.fr/~pellier/software/software.php
//
// Implementation: Simon Chamberland
// Project Manager: Froduald Kabanza
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PDDLParser.Exp.Struct;
using PDDLParser.Exp.Term.Type;
using PDDLParser.World;
namespace PDDLParser.Exp.Term
{
/// <summary>
/// An object variable is a variable bound to an object (a constant from the domain).
/// </summary>
[TLPlan]
public abstract class ObjectVariable : Variable, ITerm
{
/// <summary>
/// The typeset of this object variable.
/// </summary>
private TypeSet m_typeSet;
/// <summary>
/// An handler for messages transmitted by object variables.
/// </summary>
/// <param name="sender">The object variable which sends the message.</param>
public delegate void VariableEventHandler(ObjectVariable sender);
/// <summary>
/// This event is raised whenever the domain of this object variable changes.
/// This mechanism has been implemented to allow formulas to update their arguments ID
/// if the domain of one of their argument is modified.
/// </summary>
public event VariableEventHandler TypeDomainChanged;
/// <summary>
/// Creates a new object variable with the specified name and typeset.
/// </summary>
/// <param name="name">The name of the object variable.</param>
/// <param name="typeSet">The typeset of the object variable.</param>
public ObjectVariable(string name, TypeSet typeSet)
: base(name)
{
System.Diagnostics.Debug.Assert(typeSet != null);
this.SetTypeSet(typeSet);
}
/// <summary>
/// Evaluates this term in the specified open world.
/// The bindings should not be modified by this call.
/// </summary>
/// <param name="world">The evaluation world.</param>
/// <param name="bindings">A set of variable bindings.</param>
/// <returns>Undefined, unknown, or the constant resulting from the evaluation.</returns>
/// <exception cref="PDDLParser.Exception.BindingException">A BindingException is thrown if this
/// variable is not bound.</exception>
public abstract FuzzyConstantExp Evaluate(IReadOnlyOpenWorld world, LocalBindings bindings);
/// <summary>
/// Simplifies this term by evaluating its known expression parts.
/// The bindings should not be modified by this call.
/// The resulting expression should not contain any unbound variables, since
/// they are substituted according to the bindings supplied.
/// </summary>
/// <param name="world">The evaluation world.</param>
/// <param name="bindings">A set of variable bindings.</param>
/// <returns>Undefined, or the term (possibly a constant) resulting from
/// the simplification.</returns>
/// <exception cref="PDDLParser.Exception.BindingException">A BindingException is thrown if this
/// variable is not bound.</exception>
public abstract TermValue Simplify(IReadOnlyOpenWorld world, LocalBindings bindings);
/// <summary>
/// Evaluates this term in the specified closed world.
/// The bindings should not be modified by this call.
/// </summary>
/// <param name="world">The evaluation world.</param>
/// <param name="bindings">A set of variable bindings.</param>
/// <returns>Undefined, or the constant resulting from the evaluation.</returns>
/// <exception cref="PDDLParser.Exception.BindingException">A BindingException is thrown if this
/// variable is not bound.</exception>
public abstract ConstantExp Evaluate(IReadOnlyClosedWorld world, LocalBindings bindings);
/// <summary>
/// Returns the typeset of this term.
/// </summary>
/// <returns>This term's typeset.</returns>
public TypeSet GetTypeSet()
{
return this.m_typeSet;
}
/// <summary>
/// Verifies whether the specified term can be assigned to this term,
/// i.e. if the other term's domain is a subset of this term's domain.
/// </summary>
/// <param name="term">The other term.</param>
/// <returns>True if the types are compatible, false otherwise.</returns>
public bool CanBeAssignedFrom(ITerm term)
{
return (this.GetTypeSet().CanBeAssignedFrom(term.GetTypeSet()));
}
/// <summary>
/// Verifies whether the specified term can be compared to this term,
/// i.e. if their domain overlap.
/// </summary>
/// <param name="term">The other term</param>
/// <returns>True if the types can be compared, false otherwise.</returns>
public bool IsComparableTo(ITerm term)
{
return (this.GetTypeSet().IsComparableTo(term.GetTypeSet()));
}
/// <summary>
/// Returns a clone of this expression.
/// </summary>
/// <returns>A clone of this expression.</returns>
public override object Clone()
{
ObjectParameterVariable var = (ObjectParameterVariable)base.Clone();
GetTypeSet().TypeDomainChanged += new TypeSet.TypeSetEventHandler(TypeSet_TypeDomainChanged);
return var;
}
/// <summary>
/// Sets the typset of this object variable. Registration must be done on the TypeDomainChanged
/// event of the typeset in the case where its domain changes.
/// </summary>
/// <param name="typeSet">The typeset of this object variable.</param>
internal void SetTypeSet(TypeSet typeSet)
{
if (this.m_typeSet != null)
{
this.m_typeSet.TypeDomainChanged -= new TypeSet.TypeSetEventHandler(TypeSet_TypeDomainChanged);
}
this.m_typeSet = typeSet;
this.m_typeSet.TypeDomainChanged += new TypeSet.TypeSetEventHandler(TypeSet_TypeDomainChanged);
}
/// <summary>
/// Handles typeset TypeDomainChanged events.
/// </summary>
/// <param name="sender">The typeset which sent the event.</param>
private void TypeSet_TypeDomainChanged(TypeSet sender)
{
FireTypeDomainChanged();
}
/// <summary>
/// Fires a TypeDomainChanged event.
/// </summary>
private void FireTypeDomainChanged()
{
if (TypeDomainChanged != null)
TypeDomainChanged(this);
}
/// <summary>
/// Returns a typed string representation of this expression.
/// </summary>
/// <returns>A typed string representation of this expression.</returns>
public override string ToTypedString()
{
return this.ToString() + " - " + this.GetTypeSet().ToString();
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Reflection;
using Microsoft.Identity.Client;
using Microsoft.Identity.Test.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Identity.Test.Unit.PublicApiTests
{
[TestClass]
public class AuthenticationResultTests
{
[TestInitialize]
public void TestInitialize()
{
TestCommon.ResetInternalStaticCaches();
}
[TestMethod]
public void PublicTestConstructorCoversAllProperties()
{
var ctorParameters = typeof(AuthenticationResult)
.GetConstructors()
.First(ctor => ctor.GetParameters().Length > 3)
.GetParameters();
var classProperties = typeof(AuthenticationResult)
.GetProperties()
.Where(p => p.GetCustomAttribute(typeof(ObsoleteAttribute)) == null);
Assert.AreEqual(ctorParameters.Length, classProperties.Count(), "The <for test> constructor should include all properties of AuthenticationObject"); ;
}
[TestMethod]
public void GetAuthorizationHeader()
{
var ar = new AuthenticationResult(
"at",
false,
"uid",
DateTime.UtcNow,
DateTime.UtcNow,
"tid",
new Account("aid", "user", "env"),
"idt", new[] { "scope" }, Guid.NewGuid(),
"SomeTokenType",
new AuthenticationResultMetadata(TokenSource.Cache));
Assert.AreEqual("SomeTokenType at", ar.CreateAuthorizationHeader());
}
[TestMethod]
public void GetHybridSpaAuthCode()
{
var ar = new AuthenticationResult(
"at",
false,
"uid",
DateTime.UtcNow,
DateTime.UtcNow,
"tid",
new Account("aid", "user", "env"),
"idt", new[] { "scope" }, Guid.NewGuid(),
"SomeTokenType",
new AuthenticationResultMetadata(TokenSource.Cache),
null,
"SpaAuthCatCode");
Assert.AreEqual("SpaAuthCatCode", ar.SpaAuthCode);
}
[TestMethod]
[Description(
"In MSAL 4.17 we made a mistake and added AuthenticationResultMetadata with no default value before tokenType param. " +
"To fix this breaking change, we added 2 constructors - " +
"one for backwards compat with 4.17+ and one for 4.16 and below")]
public void AuthenticationResult_PublicApi()
{
// old constructor, before 4.16
var ar1 = new AuthenticationResult(
"at",
false,
"uid",
DateTime.UtcNow,
DateTime.UtcNow,
"tid",
new Account("aid", "user", "env"),
"idt",
new[] { "scope" },
Guid.NewGuid());
Assert.IsNull(ar1.AuthenticationResultMetadata);
Assert.AreEqual("Bearer", ar1.TokenType);
// old constructor, before 4.16
var ar2 = new AuthenticationResult(
"at",
false,
"uid",
DateTime.UtcNow,
DateTime.UtcNow,
"tid",
new Account("aid", "user", "env"),
"idt",
new[] { "scope" },
Guid.NewGuid(),
"ProofOfBear");
Assert.IsNull(ar2.AuthenticationResultMetadata);
Assert.AreEqual("ProofOfBear", ar2.TokenType);
// new ctor, after 4.17
var ar3 = new AuthenticationResult(
"at",
false,
"uid",
DateTime.UtcNow,
DateTime.UtcNow,
"tid",
new Account("aid", "user", "env"),
"idt",
new[] { "scope" },
Guid.NewGuid(),
new AuthenticationResultMetadata(TokenSource.Broker));
Assert.AreEqual(TokenSource.Broker, ar3.AuthenticationResultMetadata.TokenSource);
Assert.AreEqual("Bearer", ar1.TokenType);
}
}
}
|
using ApiHorasDomain.Entities;
using System;
using System.Collections.Generic;
namespace ApiHorasDomain.Interfaces.Services
{
public interface ILancamentoService
{
Lancamento Insert(Lancamento lancamento);
Lancamento Update(Lancamento lancamento);
void Delete(Guid id);
Lancamento RecoverById(Guid id);
IList<Lancamento> Browse();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Bitter.Tools.NetCore.Validation
{
public class ValidateModel
{
}
}
|
using System.Collections.Generic;
using NJsonSchema;
namespace Saunter.Tests.Utils
{
public static class NJsonSchemaExtensions
{
public static IDictionary<string, JsonSchema> MergeAllProperties(this JsonSchema s)
{
var result = new Dictionary<string, JsonSchema>();
foreach (var property in s.ActualProperties)
{
result[property.Key] = property.Value;
}
foreach (var sub in s.AllInheritedSchemas)
{
foreach (var property in sub.Properties)
{
result[property.Key] = property.Value;
}
}
return result;
}
}
}
|
using System;
using BuildsAppReborn.Infrastructure;
using Newtonsoft.Json;
namespace BuildsAppReborn.Access.Models.Internal
{
internal class Repository
{
[JsonProperty("id")]
public String Id { get; set; }
[JsonConverter(typeof(TolerantEnumConverter))]
[JsonProperty("type")]
public RepositoryType RepositoryType { get; set; }
}
} |
/**
* Authors: David Bruck (dbruck1@@fau.edu) and Freguens Mildort (fmildort2015@@fau.edu)
* Original source: https://github.com/CDA6122/Project
* License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause)
**/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
namespace Project.Models
{
internal enum FieldError : byte
{
[Description("Number of nodes")] Nodes,
[Description("Simulation length")] SimulationLength,
[Description("Number of files per node")] FilesPerNode,
[Description("Mean file size")] MeanFileSize,
[Description("File size standard deviation")] FileSizeStandardDeviation,
[Description("Playback constant bitrate")] PlaybackBitrate,
[Description("Max storage capacity per node")] NodeCapacity,
[Description("1 hop max bandwidth")] MaxBandwidth,
[Description("File catalog size")] FileCatalogSize,
[Description("File popularity standard deviation")] FilePopularityStandardDeviation,
[Description("Max sampling attempts")] MaxSamplingAttempts,
[Description("File catalog size per node must not exceed storage capacity")] FileCatalogGigabyteSizePerNode,
[Description("How many times to run the simulation")] SimulationRuns
}
}
|
/*
SQLXEngine - Implementation of ANSI-SQL specification and
SQL-engine for executing the SELECT SQL command across the different data sources.
Copyright (C) 2008-2009 Semyon A. Chertkov (semyonc@gmail.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataEngine.CoreServices.Data
{
public class RowCache
{
private LinkedList<Row> _rows = new LinkedList<Row>();
private RowType _rowType;
internal RowCache(Resultset rs)
{
_rowType = rs._rtype;
}
public bool IsValid { get; private set; }
public RowType RowType { get { return _rowType; } }
public void Add(Row row)
{
if (_rowType != row._type)
throw new InvalidOperationException();
_rows.AddLast(row);
}
public void Fill(Resultset rs)
{
if (rs._rtype != _rowType)
throw new InvalidOperationException();
Row row = rs.Begin;
while (row != null)
{
_rows.AddLast(row);
row = rs.NextRow(row);
}
IsValid = true;
}
public Resultset GetResultset()
{
Resultset rs = new Resultset(_rowType, null);
foreach (Row row in _rows)
rs.Enqueue(row);
return rs;
}
public void SetValid()
{
IsValid = true;
}
public void Clear()
{
_rows.Clear();
}
}
public class ResultsetCache
{
private class Key
{
public QueryNode Node { get; private set; }
public Object[] Parameters { get; private set; }
public Key(QueryNode node, object[] parameters)
{
Node = node;
Parameters = parameters;
}
public override bool Equals(object obj)
{
if (obj is Key)
return Equals((Key)obj);
else
return false;
}
public override int GetHashCode()
{
int hashCode = Node.GetHashCode();
if (Parameters != null)
foreach (object p in Parameters)
if (p != null)
hashCode ^= p.GetHashCode();
return hashCode;
}
private bool Equals(Key k)
{
return Node == k.Node &&
ParametersEqual(k.Parameters);
}
private bool ParametersEqual(object[] p)
{
if (Parameters == p)
return true;
if (Parameters != null && p != null)
if (Parameters.Length == p.Length)
{
for (int k = 0; k < p.Length; k++)
if (! ParameterEqual(Parameters[k], p[k]))
return false;
return true;
}
return false;
}
private bool ParameterEqual(object p1, object p2)
{
if (p1 != null && p2 != null)
return p1.Equals(p2);
else
return p1 == null && p2 == null;
}
}
private Dictionary<Key, WeakReference> inner;
public ResultsetCache()
{
inner = new Dictionary<Key, WeakReference>();
}
public int CacheRequest = 0;
public int CacheHit = 0;
public int Count
{
get
{
CleanAbandonedItems();
return inner.Count;
}
}
public void Clear()
{
foreach (WeakReference wr in inner.Values)
{
RowCache curr = (RowCache)wr.Target;
if (curr != null)
curr.Clear();
}
inner.Clear();
}
private void CleanAbandonedItems()
{
List<Key> deadKeys = new List<Key>();
foreach (KeyValuePair<Key, WeakReference> kvp in inner)
if (kvp.Value.Target == null)
deadKeys.Add(kvp.Key);
foreach (Key key in deadKeys)
inner.Remove(key);
}
public RowCache Get(QueryNode node, Object[] parameters)
{
WeakReference wr;
Key key = new Key(node, parameters);
CacheRequest++;
if (inner.TryGetValue(key, out wr))
{
object result = wr.Target;
if (result == null)
inner.Remove(key);
else
{
RowCache rc = (RowCache)result;
if (rc.IsValid)
{
CacheHit++;
return rc;
}
else
inner.Remove(key);
}
}
return null;
}
public void Add(QueryNode node, Object[] parameters, Resultset rs)
{
if (rs._cache_wr != null)
throw new InvalidOperationException();
Key key = new Key(node, parameters);
RowCache rowCache = new RowCache(rs);
inner[key] =
rs._cache_wr = new WeakReference(rowCache);
if (rs._context == null)
rowCache.Fill(rs);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Xin.AQS
{
public class AirDayAQIData: AirDayData, IAQIResult
{
public int? AQI { get; set; }
public string PrimaryPollutant { get; set; }
public string Type { get; set; }
public string Effect { get; set; }
public string Measure { get; set; }
public void GetAQI()
{
DayAQIResult dar = DataConvert.ToDayAQIResult(this);
dar.GetAQI();
GetAQIResult(dar);
}
public void GetAQIResult(AQIResult src)
{
AQI = src.AQI;
PrimaryPollutant = src.PrimaryPollutant;
Type = src.Type;
Effect = src.Effect;
Measure = src.Measure;
}
}
}
|
using System.Collections.Generic;
namespace GSoft.Dynamite.Binding
{
/// <summary>
/// The default entity binder class.
/// </summary>
public class EntityBinder : IEntityBinder
{
#region Fields
private readonly IEntitySchemaBuilder _schemaBuilder;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="EntityBinder"/> class.
/// </summary>
public EntityBinder()
: this(new EntitySchemaBuilder<EntitySchema>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EntityBinder"/> class.
/// </summary>
/// <param name="schemaBuilder">The schema builder.</param>
public EntityBinder(IEntitySchemaBuilder schemaBuilder)
{
this._schemaBuilder = schemaBuilder;
}
#endregion
#region IEntityBinder Members
/// <summary>
/// Extracts the values from the entity to fill the values.
/// </summary>
/// <typeparam name="T">The type of the entity.</typeparam>
/// <param name="entity">The entity.</param>
/// <param name="values">The values.</param>
public void FromEntity<T>(T entity, IDictionary<string, object> values)
{
this._schemaBuilder.GetSchema(typeof(T)).FromEntity(entity, values);
}
/// <summary>
/// Gets the specified item.
/// </summary>
/// <typeparam name="T">The type of the entity.</typeparam>
/// <param name="values">The values.</param>
/// <returns>
/// The new entity.
/// </returns>
public T Get<T>(IDictionary<string, object> values) where T : new()
{
var entity = new T();
this.ToEntity(entity, values);
return entity;
}
/// <summary>
/// Fills the entity with values taken from the values collection.
/// </summary>
/// <typeparam name="T">The type of the entity.</typeparam>
/// <param name="entity">The entity.</param>
/// <param name="values">The values.</param>
public void ToEntity<T>(T entity, IDictionary<string, object> values)
{
this._schemaBuilder.GetSchema(typeof(T)).ToEntity(entity, values);
}
#endregion
}
} |
using Microsoft.EntityFrameworkCore;
using ProductsArchive.Domain.Common;
using ProductsArchive.Domain.Entities.ProductsSection;
namespace ProductsArchive.Application.Common.Interfaces;
public interface IApplicationDbContext
{
DbSet<LocalizedString> LocalizedStrings { get; }
DbSet<LocalizedStringValue> LocalizedStringValues { get; }
DbSet<ProductCategory> ProductCategories { get; }
DbSet<ProductGroup> ProductGroups { get; }
DbSet<Product> Products { get; }
DbSet<ProductSize> ProductSizes { get; }
void SetEntityState(AuditableEntity entity, EntityState entityState);
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Linq;
using Microsoft.Performance.SDK.Processing;
using NuGet.Versioning;
namespace Microsoft.Performance.SDK.PlugInConfiguration
{
internal static class SerializationExtensions
{
internal static ConfigurationOption ConfigurationOptionFromDTO(this ConfigurationOptionDTO sourceOption)
{
var result = new ConfigurationOption(sourceOption.Name, sourceOption.Description);
result.AddApplications(sourceOption.Applications);
result.AddRuntimes(sourceOption.Runtimes);
return result;
}
internal static ConfigurationOptionDTO ConfigurationOptionsToDTO(this ConfigurationOption sourceOption)
{
var result = new ConfigurationOptionDTO
{
Name = sourceOption.Name,
Description = sourceOption.Description,
Applications = sourceOption.Applications.ToArray(),
Runtimes = sourceOption.Runtimes.ToArray(),
};
return result;
}
internal static PlugInConfiguration ConfigurationFromDTO(this PlugInConfigurationDTO source, ILogger logger)
{
var options = new HashSet<ConfigurationOption>();
foreach (var configurationOption in source.Options)
{
options.Add(configurationOption.ConfigurationOptionFromDTO());
}
if (!SemanticVersion.TryParse(source.Version, out var version))
{
logger?.Error("Unable to parse PlugInConfiguration version: {0}", source.Version);
return null;
}
var result = new PlugInConfiguration(source.PlugInName, version, options);
return result;
}
internal static PlugInConfigurationDTO ConfigurationToDTO(this PlugInConfiguration source)
{
var options = new List<ConfigurationOptionDTO>();
foreach (var configurationOption in source.Options)
{
options.Add(configurationOption.ConfigurationOptionsToDTO());
}
var result = new PlugInConfigurationDTO
{
PlugInName = source.PlugInName,
Version = source.Version.ToString(),
Options = options.ToArray(),
};
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SmartAdminMvc.Models
{
public class AddressViewModel
{
public AddressViewModel()
{
ShowAddressTextBox = true;
ShowSaveInHistory = true;
PlaceholderText = "IP address, URL or host name";
}
public string PanelTitle { get; set; }
public string ButtonId { get; set; }
public string ButtonText { get; set; }
public string DefaultDestinationAddress { get; set; }
public bool ShowAddressTextBox { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public bool ShowSaveInHistory { get; set; }
public bool? OnlyWellknownPorts { get; set; }
public string PlaceholderText { get; set; }
}
} |
/* Juan Manuel (...), retoques por Nacho */
/*
Ejercicico 179.Crea un programa en C# que ordene el contenido de un fichero de
texto y lo vuelque a otro fichero, convirtiendo cada línea a mayúsculas.
Usa File.ReadAllLines y File.WriteAllLines. El nombre del fichero de texto de
entrada se debe preguntar al usuario. El nombre del fichero de salida será el
mismo que el de entrada, añadiéndole ".mays.txt". Debes comprobar los posibles
errores con try-catch.
*/
using System;
using System.IO;
class Ejercicio179
{
static void Main()
{
Console.WriteLine("Introduce el nombre del fichero a convertir a mayúsculas");
string nombreEntrada = Console.ReadLine();
string nombreSalida = nombreEntrada + ".mays.txt";
try
{
string[] lineas = File.ReadAllLines(nombreEntrada);
for (int i = 0; i < lineas.Length; i++)
{
lineas[i] = lineas[i].ToUpper();
}
File.WriteAllLines(nombreSalida, lineas);
}
catch (PathTooLongException)
{
Console.WriteLine("Nombre demasiado largo");
}
catch (FileNotFoundException)
{
Console.WriteLine("Ese fichero no existe");
}
catch (IOException e)
{
Console.WriteLine("Error de E/S: {0}", e.Message);
}
catch (Exception e)
{
Console.WriteLine("Error inesperado: {0}", e.Message);
}
Console.WriteLine("Conversión terminada");
}
}
|
namespace Kin
{
public enum AccountStatus
{
NotCreated = 0,
Created = 2
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xigadee
{
/// <summary>
/// This attribute can be set against a command method to register it for automatic registration as a remote command.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CommandContractAttribute:Attribute
{
public CommandContractAttribute(string messageType, string actionType, string channelId = null)
{
ChannelId = channelId;
MessageType = messageType;
ActionType = actionType;
Header = new Xigadee.ServiceMessageHeader(channelId, messageType, actionType);
}
public string ChannelId { get; protected set; }
public string MessageType { get; protected set; }
public string ActionType { get; protected set; }
/// <summary>
/// The converted header.
/// </summary>
public ServiceMessageHeader Header { get; protected set; }
}
}
|
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace JanHafner.DependencyModules
{
public abstract class DependencyModule
{
public abstract void Register(IServiceCollection services, IConfiguration configuration = null);
}
}
|
using Xadrez_OO.Exceptions;
namespace Xadrez_OO.Model {
class Board {
//Atributes
private int lines;
private int columns;
private Piece[,] pieces;
//Constructors
public Board () {
this.lines = 8;
this.lines = 8;
this.pieces = new Piece[lines, columns];
}
public Board (int lines, int columns) {
if (lines > 0 && columns > 0) {
this.lines = lines;
this.columns = columns;
}
else {
this.lines = 8;
this.columns = 8;
}
this.pieces = new Piece[lines, columns];
}
//Getter/Setter
public int GetLines () {
return this.lines;
}
public void SetLines (int lines) {
this.lines = lines;
}
public int GetColumns () {
return this.columns;
}
public void SetColumns (int columns) {
this.columns = columns;
}
public Piece GetPiece (int line, int column) {
if (line < this.lines && column < this.columns) {
return pieces[line, column];
}
else {
return null;
}
}
//Class Methods
public void PlacePiece (Piece p, Position pos) {
//Verifing if the coordinates are clear
if (HasPiece(pos)) throw new BoardException("There is a piece in this position already!");
//Recovering coordinates
int x = pos.GetLine();
int y = pos.GetColumn();
//Verifing if its a valid position
if (x >= 0 && x < this.lines && y >= 0 && y < this.columns) {
//Ok Proceding
p.SetPosition(pos);
this.pieces[x, y] = p;
}
}
public Piece RemovePiece (Position pos) {
if (GetPiece(pos.GetLine(), pos.GetColumn()) != null) {
//Recovering piece
Piece piece = GetPiece(pos.GetLine(), pos.GetColumn());
piece.SetPosition(null);
this.pieces[pos.GetLine(), pos.GetColumn()] = null;
//Returning found piece
return piece; ;
}
//Retornando null pois não há peça
return null;
}
public bool HasPiece (Position pos) {
//Verifing coordinates
ValidatePosition(pos);
//Verifing is it has a piece
return GetPiece(pos.GetLine(), pos.GetColumn()) != null;
}
public bool IsValidPos (Position pos) {
//Recovering coordinates
int x = pos.GetLine();
int y = pos.GetColumn();
if (x < 0 || x >= this.lines || y < 0 || y >= this.columns) return false;
return true;
}
public void ValidatePosition (Position pos) {
if (!IsValidPos(pos)) throw new BoardException("Invalid Move!");
}
}
}
|
using System;
using System.Collections;
using System.Text;
using SimpleJSON;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
public class UserProfileManager : MonoBehaviour
{
[SerializeField] private FirebaseManager firebaseManager;
public event Action userProfileChanged;
public event Action requestTextUpdate;
APIManager apiManager;
private void Awake()
{
if(firebaseManager!= null)
firebaseManager.authStateChanged += LoadUserProfile;
}
private void OnDestroy()
{
if (firebaseManager != null)
firebaseManager.authStateChanged -= LoadUserProfile;
}
public void Start()
{
apiManager = new APIManager();
}
public void LoadUserProfile()
{
StartCoroutine(GetUserProfile(StaticClass.UserID));
}
public IEnumerator GetUserProfile(string userid)
{
if (userid == null || userid.Length == 0)
{
StaticClass.diamond = "0";
StaticClass.gold = "0";
requestTextUpdate?.Invoke();
yield break;
}
yield return apiManager.GetUserProfile(userid);
requestTextUpdate?.Invoke();
}
// IAPShop buy button will call this function when purchase completed.
public void RewardSignUp()
{
RewardDiamond(30);
RewardGold(2000);
}
public void RewardDiamond(int diamond)
{
StartCoroutine(updateDiamond(diamond));
}
public IEnumerator updateDiamond(int diamond)
{
yield return apiManager.UpdateDiamond(StaticClass.UserID, diamond);
userProfileChanged?.Invoke();
}
public void RewardGold(int gold)
{
StartCoroutine(updateGold(gold));
}
IEnumerator updateGold(int gold)
{
yield return apiManager.UpdateGold(StaticClass.UserID, gold);
userProfileChanged?.Invoke();
}
}
|
using cor64;
using cor64.Mips.R4300I;
using NUnit.Framework;
using cor64.BareMetal;
using System;
using System.IO;
namespace Tests {
[TestFixture]
public class EndianessTests : BaseTest {
[Test]
public void BigEndianTest() {
var machine = MachineSpawner.CreateAndRun();
Assert.AreEqual("DEADBEEF", machine.Probe_ReadMem32(0x00000000).ToString("X8"));
}
// [Test]
// public void LittleEndianTest() {
// CoreConfig.Current.ByteSwap = false;
// var machine = MachineSpawner.CreateAndRun();
// Assert.AreEqual("DEADBEEF", machine.Probe_ReadMem32(0x00000000).ToString("X8"));
// }
}
} |
namespace TvShowReminder.TvMazeApi
{
public class TvMazeApiUrls
{
public const string ApiBaseUrl = "http://api.tvmaze.com";
public static string CreateSearchUrl(string query)
{
return string.Format("{0}/search/shows?q={1}", ApiBaseUrl, query);
}
public static string CreateEpisodeListUrl(int showId)
{
return string.Format("{0}/shows/{1}/episodes?specials=1", ApiBaseUrl, showId);
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using MixedRealityExtension.Behaviors;
using MixedRealityExtension.Behaviors.Contexts;
using MixedRealityExtension.PluginInterfaces.Behaviors;
namespace MixedRealityExtension.Core.Components
{
internal class BehaviorComponent : ActorComponentBase
{
private BehaviorContextBase _behaviorContext;
internal IBehavior Behavior => _behaviorContext?.Behavior;
internal BehaviorContextBase Context => _behaviorContext;
internal void SetBehaviorContext(BehaviorContextBase behaviorContext)
{
if (_behaviorContext != null && _behaviorContext.BehaviorType != behaviorContext.BehaviorType)
{
ClearBehaviorContext();
}
_behaviorContext = behaviorContext;
}
internal void ClearBehaviorContext()
{
if (_behaviorContext != null)
{
_behaviorContext.CleanUp();
_behaviorContext = null;
}
}
internal bool ContainsBehaviorContext()
{
return _behaviorContext != null;
}
internal override void CleanUp()
{
base.CleanUp();
ClearBehaviorContext();
}
internal override void SynchronizeComponent()
{
_behaviorContext?.SynchronizeBehavior();
}
private void FixedUpdate()
{
_behaviorContext?.FixedUpdate();
}
}
}
|
namespace NeoSharp.Application.Client
{
public interface IPromptController
{
}
} |
using System;
using Android.App;
using Android.OS;
using Android.Content;
using Android.Util;
using Java.Interop;
namespace StockService
{
[Service]
[IntentFilter(new String[]{"com.xamarin.DemoMessengerService"})]
public class DemoMessengerService : Service
{
Messenger demoMessenger;
public DemoMessengerService ()
{
demoMessenger = new Messenger (new DemoHandler ());
}
public override IBinder OnBind (Intent intent)
{
Log.Debug ("StockMessengerService", "client bound to service");
return demoMessenger.Binder;
}
class DemoHandler : Handler
{
public override void HandleMessage (Message msg)
{
Log.Debug ("DemoMessengerService", msg.What.ToString ());
string text = msg.Data.GetString ("InputText");
Log.Debug ("DemoMessengerService", "InputText = " + text);
}
}
}
}
|
namespace Sitecore.FakeDb.Serialization.Pipelines
{
using System.IO;
using Sitecore.Diagnostics;
using Sitecore.FakeDb.Pipelines;
public class DeserializeDescendants
{
public void Process(DsItemLoadingArgs args)
{
Assert.ArgumentNotNull(args, "args");
var dsDbItem = args.DsDbItem as DsDbItem;
if (dsDbItem == null)
{
return;
}
// Deserialize and link descendants, if needed
var file = args.DsDbItem.File;
if (!dsDbItem.IncludeDescendants || file.Directory == null)
{
return;
}
var childItemsFolder = new DirectoryInfo(file.Directory.FullName + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(file.Name));
if (!childItemsFolder.Exists)
{
return;
}
foreach (var itemFile in childItemsFolder.GetFiles("*.item", SearchOption.TopDirectoryOnly))
{
DbItem childItem;
var syncItem = itemFile.Deserialize();
if (syncItem.TemplateID == TemplateIDs.Template.ToString())
{
childItem = new DsDbTemplate(dsDbItem.SerializationFolderName, syncItem, itemFile);
}
else
{
childItem = new DsDbItem(dsDbItem.SerializationFolderName, syncItem, itemFile, true);
}
dsDbItem.Children.Add(childItem);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blatomic.Services.ColorScheme
{
public class ThemeService
{
private ITheme theme;
public ThemeService(ITheme theme)
{
this.theme = theme;
}
public Action<bool>? OnModeToggle { get; set; }
public Func<ITheme,Task>? OnSaveTheme { get; set; }
public bool IsDarkMode { get; set; } = true;
public void DarkMode()
{
if (IsDarkMode)
{
return;
}
IsDarkMode = true;
OnModeToggle?.Invoke(true);
}
public void LightMode()
{
if (!IsDarkMode)
{
return;
}
IsDarkMode = false;
OnModeToggle?.Invoke(false);
}
public void ToggleMode()
{
IsDarkMode = !IsDarkMode;
OnModeToggle?.Invoke(IsDarkMode);
}
public Task UpdateTheme(Action<ITheme> action)
{
action(theme);
return SaveThemeAsync(theme);
}
public Task SaveThemeAsync(ITheme theme)
{
if (OnSaveTheme is not null)
{
return OnSaveTheme.Invoke(theme);
}
return Task.CompletedTask;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for SysEvent
/// </summary>
public class SysEvent
{
public string Id { get; set; }
public DateTime EDate { get; set; }
public string EType { get; set; }
public string EHostID { get; set; }
public string ETitle { get; set; }
public string ECost { get; set; }
public string ETime { get; set; }
public DateTime EDeadline { get; set; }
public string ESpecialRule { get; set; }
public string EGuest { get; set; }
public int EPlayerLimit { get; set; }
public string EHostPhone { get; set; }
public DateTime EPostDate { get; set; }
public bool CanSignUp(DateTime lastDate)
{
return this.EType != "MISGA" && this.EDate <= lastDate;
}
} |
using CCXT.NET.Shared.Coin.Private;
namespace CCXT.NET.Anxpro.Private
{
/// <summary>
/// 거래소 회원 지갑 정보
/// </summary>
public class ABalanceItem : CCXT.NET.Shared.Coin.Private.BalanceItem, IBalanceItem
{
}
} |
using System;
using System.Linq;
using CompositeDesignPatternExampleCompany.Contracts;
namespace CompositeDesignPatternExampleCompany
{
public class Employee : EmployeeComponent
{
public Employee(string name)
: base(name)
{
}
public override bool GetDone(ITask task)
{
var result = task.IsFinished;
return result;
}
public override string Display()
{
var employeeToDisplay = $"Employee: {this.Name}";
return employeeToDisplay;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.