content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SmoothBoard { public partial class FileNotFound { } }
24.277778
81
0.411899
[ "MIT" ]
dakkafex/Smoothboard
SmoothBoard/FileNotFound.aspx.designer.cs
439
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Protocols.TestSuites.Rdp; using Microsoft.Protocols.TestSuites.Rdpbcgr; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr; using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpemt; using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpeudp; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; namespace Microsoft.Protocols.TestSuites.Rdpeudp { public enum SynAndAck_InvalidType { /// <summary> /// Valid Type. /// </summary> None, /// <summary> /// uUpStreamMtu is larger than 1232. /// </summary> LargerUpStreamMtu, /// <summary> /// uUpStreamMtu is smaller than 1132. /// </summary> SamllerUpStreamMtu, /// <summary> /// uDownStreamMtu is larger than 1232. /// </summary> LargerDownStreamMtu, /// <summary> /// uDownStreamMtu is smaller than 1132. /// </summary> SamllerDownStreamMtu, } public enum SourcePacket_InvalidType { /// <summary> /// Valid Type. /// </summary> None, /// <summary> /// The Source Payload of Source packet is larger than 1232. /// </summary> LargerSourcePayload, } [TestClass] public partial class RdpeudpTestSuite : RdpTestClassBase { #region Variables private RdpeudpServer rdpeudpServer; private RdpeudpServerSocket rdpeudpSocketR; private RdpeudpServerSocket rdpeudpSocketL; private RdpemtServer rdpemtServerR; private RdpemtServer rdpemtServerL; private uint multitransportRequestId = 0; private int DelayedACKTimer = 200; private int RetransmitTimer = 200; private uint? initSequenceNumber = null; private uUdpVer_Values? clientUUdpVer = null; private uSynExFlags_Values? clientRdpudpVerfionInfoValidFlag = null; #endregion #region Class Initialization And Cleanup [ClassInitialize] public static void ClassInitialize(TestContext context) { RdpTestClassBase.BaseInitialize(context); } [ClassCleanup] public static void ClassCleanup() { RdpTestClassBase.BaseCleanup(); } #endregion #region Test Cleanup protected override void TestCleanup() { base.TestCleanup(); //Reset the client status to avoid dirty data for the next test case. this.clientUUdpVer = null; this.clientRdpudpVerfionInfoValidFlag = null; this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger client to close all RDP connections for clean up."); TriggerClientDisconnectAll(); if (rdpemtServerL != null) rdpemtServerL.Dispose(); if (rdpemtServerR != null) rdpemtServerR.Dispose(); if (rdpeudpServer != null) rdpeudpServer.Stop(); if (rdpeudpSocketR != null && rdpeudpSocketR.Connected) rdpeudpSocketR.Close(); if (rdpeudpSocketL != null && rdpeudpSocketL.Connected) rdpeudpSocketL.Close(); this.TestSite.Log.Add(LogEntryKind.Comment, "Stop RDP listening."); this.rdpbcgrAdapter?.StopRDPListening(); } #endregion #region Private Methods /// <summary> /// Get the initial sequence number of the source packet /// </summary> /// <param name="udpTransportMode">The transport mode: reliable or lossy</param> /// <returns>The initial sequence number of the source packet</returns> private uint getSnInitialSequenceNumber(TransportMode udpTransportMode) { if (udpTransportMode == TransportMode.Reliable) { return rdpeudpSocketR.SnInitialSequenceNumber; } return rdpeudpSocketL.SnInitialSequenceNumber; } private uint getSourcePacketSequenceNumber(TransportMode udpTransportMode) { if (udpTransportMode == TransportMode.Reliable) { return rdpeudpSocketR.CurSnSource; } return rdpeudpSocketL.CurSnSource; } /// <summary> /// Start RDP connection. /// </summary> private void StartRDPConnection() { // Start RDP listening. this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening with transport protocol: {0}", transportProtocol.ToString()); this.rdpbcgrAdapter.StartRDPListening(transportProtocol); #region Trigger Client To Connect // Trigger client to connect. this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server."); triggerClientRDPConnect(transportProtocol); #endregion #region RDPBCGR Connection // Waiting for the transport level connection request. this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request."); this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal); // Waiting for the RDP connection sequence. this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection."); this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion, MULTITRANSPORT_TYPE_FLAGS.TRANSPORTTYPE_UDPFECL | MULTITRANSPORT_TYPE_FLAGS.TRANSPORTTYPE_UDPFECR); this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on."); this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER); #endregion } /// <summary> /// Send SYN and ACK packet. /// </summary> /// <param name="udpTransportMode">Transport mode: Reliable or Lossy</param> /// <param name="invalidType">invalid type</param> public void SendSynAndAckPacket(TransportMode udpTransportMode, SynAndAck_InvalidType invalidType, uint? initSequenceNumber = null, uUdpVer_Values? uUdpVer = null) { RdpeudpServerSocket rdpeudpSocket = rdpeudpSocketR; if (udpTransportMode == TransportMode.Lossy) { rdpeudpSocket = rdpeudpSocketL; } if (invalidType == SynAndAck_InvalidType.None) { // If invalid type is None, send the packet directly. rdpeudpSocket.SendSynAndAckPacket(initSequenceNumber, uUdpVer); return; } // Create the SYN and ACK packet first. RdpeudpPacket SynAndAckPacket = CreateInvalidSynAndACKPacket(udpTransportMode, invalidType, initSequenceNumber); rdpeudpSocket.SendPacket(SynAndAckPacket); } /// <summary> /// Establish a UDP connection. /// </summary> /// <param name="udpTransportMode">Transport mode: Reliable or Lossy.</param> /// <param name="timeout">Wait time.</param> /// <param name="verifyPacket">Whether verify the received packet.</param> /// <returns>The accepted socket.</returns> private RdpeudpSocket EstablishUDPConnection(TransportMode udpTransportMode, TimeSpan timeout, bool verifyPacket = false, bool autoHanlde = false, uUdpVer_Values? uUdpVer = null) { // Start UDP listening. if (rdpeudpServer == null) { rdpeudpServer = new RdpeudpServer((IPEndPoint)this.rdpbcgrAdapter.SessionContext.LocalIdentity, autoHanlde); rdpeudpServer.UnhandledExceptionReceived += (ex) => { Site.Log.Add(LogEntryKind.Debug, $"Unhandled exception from RdpeudpServer: {ex}"); }; } rdpeudpServer.Start(); // Send a Server Initiate Multitransport Request PDU. byte[] securityCookie = new byte[16]; Random rnd = new Random(); rnd.NextBytes(securityCookie); Multitransport_Protocol_value requestedProtocol = Multitransport_Protocol_value.INITITATE_REQUEST_PROTOCOL_UDPFECR; if (udpTransportMode == TransportMode.Lossy) { requestedProtocol = Multitransport_Protocol_value.INITITATE_REQUEST_PROTOCOL_UDPFECL; } this.rdpbcgrAdapter.SendServerInitiateMultitransportRequestPDU(++this.multitransportRequestId, requestedProtocol, securityCookie); // Create a UDP socket. RdpeudpServerSocket rdpudpSocket = rdpeudpServer.CreateSocket(((IPEndPoint)this.rdpbcgrAdapter.SessionContext.Identity).Address, udpTransportMode, timeout); if (rdpudpSocket == null) { this.Site.Assert.Fail("Failed to create a UDP socket for the Client : {0}", ((IPEndPoint)this.rdpbcgrAdapter.SessionContext.Identity).Address); } if (udpTransportMode == TransportMode.Reliable) { this.rdpeudpSocketR = rdpudpSocket; } else { this.rdpeudpSocketL = rdpudpSocket; } // Expect a SYN packet. RdpeudpPacket synPacket = rdpudpSocket.ExpectSynPacket(timeout); if (synPacket == null) { this.Site.Assert.Fail("Time out when waiting for the SYN packet"); } // Verify the SYN packet. if (verifyPacket) { VerifySYNPacket(synPacket, udpTransportMode); } // Send a SYN and ACK packet. if (this.clientRdpudpVerfionInfoValidFlag == uSynExFlags_Values.RDPUDP_VERSION_INFO_VALID) { //Section 3.1.5.1.3: The uUdpVer field MUST be set to the highest RDP-UDP protocol version supported by both endpoints. uUdpVer = uUdpVer > this.clientUUdpVer ? this.clientUUdpVer : uUdpVer; SendSynAndAckPacket(udpTransportMode, SynAndAck_InvalidType.None, initSequenceNumber, uUdpVer); } else if (this.clientRdpudpVerfionInfoValidFlag == uSynExFlags_Values.None) { //Section 3.1.5.1.3: The highest version supported by both endpoints, which is RDPUDP_PROTOCOL_VERSION_1 if either this packet or the SYN packet does not specify a version, is the version that MUST be used by both endpoints. SendSynAndAckPacket(udpTransportMode, SynAndAck_InvalidType.None, initSequenceNumber, uUdpVer_Values.RDPUDP_PROTOCOL_VERSION_1); } else { //Section 3.1.5.1.3: The RDPUDP_SYNEX_PAYLOAD structure (section 2.2.2.9) SHOULD only be present if it is also present in the received SYN packet. // When the SendSynAndAckPacket(udpTransportMode, SynAndAck_InvalidType.None, initSequenceNumber, null); } // Expect an ACK packet or ACK and Source Packet. RdpeudpPacket ackPacket = rdpudpSocket.ExpectACKPacket(timeout); if (ackPacket == null) { this.Site.Assert.Fail("Time out when waiting for the ACK packet to response the ACK and SYN packet"); } // Verify the ACK packet. if (verifyPacket) { VerifyACKPacket(ackPacket); } // If the packet is an ACK and Source Packet, add the source packet to the un-processed packet. if (ackPacket.fecHeader.uFlags.HasFlag(RDPUDP_FLAG.RDPUDP_FLAG_DATA)) { byte[] bytes = PduMarshaler.Marshal(ackPacket, false); RdpeudpBasePacket stackpacket = new RdpeudpBasePacket(bytes); rdpudpSocket.ReceivePacket(stackpacket); } rdpudpSocket.Connected = true; return rdpudpSocket; } /// <summary> /// Used to establish a RDPEMT connection. /// </summary> /// <param name="udpTransportMode">Transport Mode: Reliable or Lossy.</param> /// <param name="timeout">Wait time.</param> /// <returns>true,false.</returns> private bool EstablishRdpemtConnection(TransportMode udpTransportMode, TimeSpan timeout) { bool pass = true; RdpeudpServerSocket rdpeudpSocket = rdpeudpSocketR; if (udpTransportMode == TransportMode.Lossy) { rdpeudpSocket = rdpeudpSocketL; } if (!rdpeudpSocket.AutoHandle) { rdpeudpSocket.AutoHandle = true; } String certFile = this.Site.Properties["CertificatePath"]; String certPwd = this.Site.Properties["CertificatePassword"]; X509Certificate2 cert = new X509Certificate2(certFile, certPwd); RdpemtServer rdpemtServer = new RdpemtServer(rdpeudpSocket, cert); uint receivedRequestId; byte[] receivedSecurityCookie; if (!rdpemtServer.ExpectConnect(waitTime, out receivedRequestId, out receivedSecurityCookie)) { pass = false; } rdpeudpSocket.AutoHandle = false; if (udpTransportMode == TransportMode.Reliable) { rdpemtServerR = rdpemtServer; } else { rdpemtServerL = rdpemtServer; } if (!pass) { this.TestSite.Log.Add(LogEntryKind.Comment, "Create a {0} RDPEMT connection failed, stop rdpeudpServer and close socket connection and retry.", udpTransportMode); rdpeudpServer.Stop(); rdpeudpServer = null; if (udpTransportMode == TransportMode.Reliable) { rdpeudpSocketR.Close(); rdpeudpSocketR = null; } else { rdpeudpSocketL.Close(); rdpeudpSocketL = null; } } return pass; } private int GetMaxiumPayloadSizeForSourcePacket(int upStreamMtu) { // Create a fake empty RDPEUDP ACK+SOURCE packet. var packet = new RdpeudpPacket(); packet.fecHeader.snSourceAck = 0; packet.fecHeader.uReceiveWindowSize = 0; packet.fecHeader.uFlags = RDPUDP_FLAG.RDPUDP_FLAG_DATA | RDPUDP_FLAG.RDPUDP_FLAG_ACK; var ackVectorHeader = new RDPUDP_ACK_VECTOR_HEADER(); ackVectorHeader.uAckVectorSize = 0; ackVectorHeader.AckVectorElement = null; ackVectorHeader.Padding = null; packet.ackVectorHeader = ackVectorHeader; var sourceHeader = new RDPUDP_SOURCE_PAYLOAD_HEADER(); sourceHeader.snCoded = 0; sourceHeader.snSourceStart = 0; packet.sourceHeader = sourceHeader; var size = PduMarshaler.Marshal(packet).Length; // Maximum payload size = upstream MTU - empty ACK+SOURCE header size. return upStreamMtu - size; } /// <summary> /// Get the First valid UDP Source Packet. /// </summary> /// <param name="udpTransportMode"></param> /// <returns></returns> private RdpeudpPacket GetFirstValidUdpPacket(TransportMode udpTransportMode) { byte[] dataToSent = null; RdpeudpPacket firstPacket = null; String certFile = this.Site.Properties["CertificatePath"]; String certPwd = this.Site.Properties["CertificatePassword"]; X509Certificate2 cert = new X509Certificate2(certFile, certPwd); if (udpTransportMode == TransportMode.Reliable) { RdpeudpTLSChannel secChannel = new RdpeudpTLSChannel(rdpeudpSocketR); secChannel.AuthenticateAsServer(cert); RdpeudpPacket packet = rdpeudpSocketR.ExpectPacket(waitTime); if (packet.payload != null) { rdpeudpSocketR.ProcessSourceData(packet); // Process Source Data to make sure ACK Vector created next is correct secChannel.ReceiveBytes(packet.payload); } dataToSent = secChannel.GetDataToSent(waitTime); // Make sure this test packet does not exceed upstream MTU. int maxPayloadsize = GetMaxiumPayloadSizeForSourcePacket(rdpeudpSocketR.UUpStreamMtu); dataToSent = dataToSent.Take(maxPayloadsize).ToArray(); firstPacket = rdpeudpSocketR.CreateSourcePacket(dataToSent); } else { RdpeudpDTLSChannel secChannel = new RdpeudpDTLSChannel(rdpeudpSocketL); secChannel.AuthenticateAsServer(cert); RdpeudpPacket packet = rdpeudpSocketL.ExpectPacket(waitTime); if (packet.payload != null) { rdpeudpSocketL.ProcessSourceData(packet); // Process Source Data to make sure ACK Vector created next is correct secChannel.ReceiveBytes(packet.payload); } dataToSent = secChannel.GetDataToSent(waitTime); // Make sure this test packet does not exceed upstream MTU. int maxPayloadsize = GetMaxiumPayloadSizeForSourcePacket(rdpeudpSocketL.UUpStreamMtu); dataToSent = dataToSent.Take(maxPayloadsize).ToArray(); firstPacket = rdpeudpSocketL.CreateSourcePacket(dataToSent); } return firstPacket; } /// <summary> /// Get the next valid rdpeudp packet. /// </summary> /// <param name="udpTransportMode">Transport mode: reliable or Lossy.</param> /// <returns>The next valid rdpeudp packet.</returns> private RdpeudpPacket GetNextValidUdpPacket(TransportMode udpTransportMode, byte[] data = null) { /*This function is used to get a valid rdpeudp packet. * Using rdpeudpSocket.LossPacket flag to control whether the socket send the packet. * First set rdpeudpSocket.LossPacket to true and send a tunnal Data, the socket will store the next packet(RDPEUDP socket which contains the encrypted tunnel data) and doesn't send it. * Then get the stored packet and return it. */ RdpemtServer rdpemtServer = rdpemtServerR; RdpeudpSocket rdpeudpSocket = rdpeudpSocketR; if (udpTransportMode == TransportMode.Lossy) { rdpemtServer = rdpemtServerL; rdpeudpSocket = rdpeudpSocketL; } if (data == null) data = new byte[1000]; RDP_TUNNEL_DATA tunnelData = rdpemtServer.CreateTunnelDataPdu(data, null); byte[] unEncryptData = PduMarshaler.Marshal(tunnelData); byte[] encryptData = null; if (udpTransportMode == TransportMode.Reliable) { RdpeudpTLSChannel secChannel = rdpemtServer.SecureChannel as RdpeudpTLSChannel; encryptData = secChannel.Encrypt(unEncryptData); } else { RdpeudpDTLSChannel secChannel = rdpemtServer.SecureChannel as RdpeudpDTLSChannel; List<byte[]> encryptDataList = secChannel.Encrypt(unEncryptData); if (encryptDataList != null && encryptDataList.Count > 0) { encryptData = encryptDataList[0]; } } RdpeudpPacket packet = rdpeudpSocket.CreateSourcePacket(encryptData); return packet; } /// <summary> /// Send a udp packet. /// </summary> /// <param name="udpTransportMode">Transport mode: reliable or lossy.</param> /// <param name="packet">The packet to send.</param> private void SendPacket(TransportMode udpTransportMode, RdpeudpPacket packet) { RdpeudpSocket rdpeudpSocket = rdpeudpSocketR; if (udpTransportMode == TransportMode.Lossy) { rdpeudpSocket = rdpeudpSocketL; } rdpeudpSocket.SendPacket(packet); } /// <summary> /// Get a valid RDPEUDP packet and send it. /// </summary> /// <param name="udpTransportMode">Transport mode: reliable or lossy.</param> private void SendNextValidUdpPacket(TransportMode udpTransportMode, byte[] data = null) { RdpemtServer rdpemtServer = rdpemtServerR; if (udpTransportMode == TransportMode.Lossy) { rdpemtServer = rdpemtServerL; } if (data == null) data = new byte[1000]; RDP_TUNNEL_DATA tunnelData = rdpemtServer.CreateTunnelDataPdu(data, null); rdpemtServer.SendRdpemtPacket(tunnelData); } /// <summary> /// Send an invalid UDP source Packet. /// </summary> /// <param name="udpTransportMode"></param> /// <param name="invalidType"></param> private void SendInvalidUdpSourcePacket(TransportMode udpTransportMode, SourcePacket_InvalidType invalidType) { RdpeudpSocket rdpeudpSocket = rdpeudpSocketR; RdpemtServer rdpemtServer = rdpemtServerR; if (udpTransportMode == TransportMode.Lossy) { rdpeudpSocket = rdpeudpSocketL; rdpemtServer = rdpemtServerL; } if (invalidType == SourcePacket_InvalidType.LargerSourcePayload) { // Change UpStreamMtu of RDPEUDP Socket, so that large data can be sent ushort upstreamMtu = rdpeudpSocket.UUpStreamMtu; rdpeudpSocket.UUpStreamMtu = 2000; byte[] data = new byte[1600]; RDP_TUNNEL_DATA tunnelData = rdpemtServer.CreateTunnelDataPdu(data, null); rdpemtServer.SendRdpemtPacket(tunnelData); // Change UpStreamMtu to correct value rdpeudpSocket.UUpStreamMtu = upstreamMtu; } } /// <summary> /// Compare two AckVectors. /// </summary> /// <param name="vector1">Ack Vector 1.</param> /// <param name="vector2">Ack Vector 2.</param> /// <returns></returns> private bool CompareAckVectors(AckVector[] vector1, AckVector[] vector2) { int posForVector1 = 0; int posForVector2 = 0; int length1 = vector1[posForVector1].Length + 1; int length2 = vector2[posForVector2].Length + 1; while (posForVector1 < vector1.Length && posForVector2 < vector2.Length) { if (vector1[posForVector1].State != vector2[posForVector2].State) { return false; } if (length1 == length2) { posForVector1++; posForVector2++; if (!(posForVector1 < vector1.Length && posForVector2 < vector2.Length)) break; length1 = vector1[posForVector1].Length + 1; length2 = vector2[posForVector2].Length + 1; } else if (length1 > length2) { length1 -= length2; posForVector2++; if (!(posForVector1 < vector1.Length && posForVector2 < vector2.Length)) break; length2 = vector2[posForVector2].Length + 1; } else { length2 -= length1; posForVector1++; if (!(posForVector1 < vector1.Length && posForVector2 < vector2.Length)) break; length1 = vector1[posForVector1].Length + 1; } } if (posForVector1 < vector1.Length || posForVector2 < vector2.Length) { return false; } return true; } /// <summary> /// Expect for a Source Packet. /// </summary> /// <param name="udpTransportMode">Transport mode: reliable or lossy.</param> /// <param name="timeout">Wait time</param> /// <returns></returns> private RdpeudpPacket WaitForSourcePacket(TransportMode udpTransportMode, TimeSpan timeout, uint sequnceNumber = 0) { RdpeudpSocket rdpeudpSocket = rdpeudpSocketR; if (udpTransportMode == TransportMode.Lossy) { rdpeudpSocket = rdpeudpSocketL; } DateTime endTime = DateTime.Now + timeout; while (DateTime.Now < endTime) { RdpeudpPacket packet = rdpeudpSocket.ExpectPacket(endTime - DateTime.Now); if (packet != null && packet.fecHeader.uFlags.HasFlag(RDPUDP_FLAG.RDPUDP_FLAG_DATA)) { if (sequnceNumber == 0 || packet.sourceHeader.Value.snSourceStart == sequnceNumber) { return packet; } } } return null; } /// <summary> /// Wait for an ACK packet which meets certain conditions. /// </summary> /// <param name="udpTransportMode">Transport mode: reliable or lossy.</param> /// <param name="timeout">Wait time.</param> /// <param name="expectAckVectors">Expected ack vectors.</param> /// <param name="hasFlag">Flags, which the ACK packet must contain.</param> /// <param name="notHasFlag">Flags, which the ACK packet must no contain.</param> /// <returns></returns> private RdpeudpPacket WaitForACKPacket(TransportMode udpTransportMode, TimeSpan timeout, AckVector[] expectAckVectors = null, RDPUDP_FLAG hasFlag = 0, RDPUDP_FLAG notHasFlag = 0) { RdpeudpSocket rdpeudpSocket = rdpeudpSocketR; if (udpTransportMode == TransportMode.Lossy) { rdpeudpSocket = rdpeudpSocketL; } DateTime endTime = DateTime.Now + timeout; while (DateTime.Now < endTime) { RdpeudpPacket ackPacket = rdpeudpSocket.ExpectACKPacket(endTime - DateTime.Now); if (ackPacket != null) { if (expectAckVectors != null) { if (!(ackPacket.ackVectorHeader.HasValue && CompareAckVectors(ackPacket.ackVectorHeader.Value.AckVectorElement, expectAckVectors))) { continue; } } if (hasFlag != 0) { if ((ackPacket.fecHeader.uFlags & hasFlag) != hasFlag) { continue; } } if (notHasFlag != 0) { if ((ackPacket.fecHeader.uFlags & notHasFlag) != 0) { continue; } } return ackPacket; } } return null; } /// <summary> /// Create invalid SYN and ACK Packet /// </summary> /// <param name="udpTransportMode">Transport mode: reliable or lossy</param> /// <param name="invalidType">Invalid type</param> /// <param name="initSequenceNumber">init sequence</param> /// <returns></returns> private RdpeudpPacket CreateInvalidSynAndACKPacket(TransportMode udpTransportMode, SynAndAck_InvalidType invalidType, uint? initSequenceNumber = null) { RdpeudpServerSocket rdpeudpSocket = rdpeudpSocketR; if (udpTransportMode == TransportMode.Lossy) { rdpeudpSocket = rdpeudpSocketL; } // Create the SYN and ACK packet. RdpeudpPacket SynAndAckPacket = new RdpeudpPacket(); SynAndAckPacket.fecHeader.snSourceAck = rdpeudpSocket.SnSourceAck; SynAndAckPacket.fecHeader.uReceiveWindowSize = rdpeudpSocket.UReceiveWindowSize; SynAndAckPacket.fecHeader.uFlags = RDPUDP_FLAG.RDPUDP_FLAG_SYN | RDPUDP_FLAG.RDPUDP_FLAG_ACK; RDPUDP_SYNDATA_PAYLOAD SynPayload = rdpeudpSocket.CreateSynData(initSequenceNumber); switch (invalidType) { case SynAndAck_InvalidType.LargerUpStreamMtu: SynPayload.uUpStreamMtu = 1232 + 1; break; case SynAndAck_InvalidType.SamllerUpStreamMtu: SynPayload.uUpStreamMtu = 1132 - 1; break; case SynAndAck_InvalidType.LargerDownStreamMtu: SynPayload.uDownStreamMtu = 1232 + 1; break; case SynAndAck_InvalidType.SamllerDownStreamMtu: SynPayload.uDownStreamMtu = 1132 - 1; break; } SynAndAckPacket.SynData = SynPayload; return SynAndAckPacket; } #endregion #region Packet Verification /// <summary> /// Verify SYN packet. /// </summary> /// <param name="synPacket">The SYN packet.</param> /// <param name="udpTransportMode">Transport mode: reliable or lossy.</param> private void VerifySYNPacket(RdpeudpPacket synPacket, TransportMode udpTransportMode) { if (synPacket == null) { this.Site.Assert.Fail("The SYN Packet should not be null!"); } if (synPacket.fecHeader.snSourceAck != uint.MaxValue) { this.Site.Assert.Fail("The snSourceAck variable MUST be set to -1 (max value of uint)!"); } if ((synPacket.fecHeader.uFlags & RDPUDP_FLAG.RDPUDP_FLAG_SYN) == 0) { this.Site.Assert.Fail("The RDPUDP_FLAG_SYN flag MUST be set in SYN packet!"); } if (udpTransportMode == TransportMode.Reliable) { if ((synPacket.fecHeader.uFlags & RDPUDP_FLAG.RDPUDP_FLAG_SYNLOSSY) == RDPUDP_FLAG.RDPUDP_FLAG_SYNLOSSY) { this.Site.Assert.Fail("The RDPUDP_FLAG_SYNLOSSY flag MUST not be set when choose reliable UDP connection!"); } } else { if ((synPacket.fecHeader.uFlags & RDPUDP_FLAG.RDPUDP_FLAG_SYNLOSSY) == 0) { this.Site.Assert.Fail("The RDPUDP_FLAG_SYNLOSSY flag MUST be set When choose lossy UDP connection!"); } } if (synPacket.SynData == null) { this.Site.Assert.Fail("The SYN Packet should contain a RDPUDP_SYNDATA_PAYLOAD structure!"); } if (synPacket.SynData.Value.uUpStreamMtu > 1232 || synPacket.SynData.Value.uUpStreamMtu < 1132) { this.Site.Assert.Fail("The uUpStreamMtu field MUST be set to a value in the range of 1132 to 1232."); } if (synPacket.SynData.Value.uDownStreamMtu > 1232 || synPacket.SynData.Value.uDownStreamMtu < 1132) { this.Site.Assert.Fail("The uDownStreamMtu field MUST be set to a value in the range of 1132 to 1232."); } // The RDPUDP_FLAG_SYNEX flag and RDPUDP_SYNDATAEX_PAYLOAD structure should appear at the same time. if ((synPacket.SynDataEx == null) ^ ((synPacket.fecHeader.uFlags & RDPUDP_FLAG.RDPUDP_FLAG_SYNEX) == 0)) { this.Site.Assert.Fail("Section 3.1.5.1.1: The RDPUDP_FLAG_SYNEX flag MUST be set only when the RDPUDP_SYNDATAEX_PAYLOAD structure is included. Section 3.1.5.1.1: The RDPUDP_SYNEX_PAYLOAD structure MUST be appended to the UDP datagram if the RDPUDP_FLAG_SYNEX flag is set in uFlags."); } //Section 3.1.5.1.1: Not appending RDPUDP_SYNDATAEX_PAYLOAD structure implies that RDPUDP_PROTOCOL_VERSION_1 is the highest protocol version supported. if (synPacket.SynDataEx == null) { this.clientUUdpVer = uUdpVer_Values.RDPUDP_PROTOCOL_VERSION_1; this.clientRdpudpVerfionInfoValidFlag = null; } else { this.clientUUdpVer = synPacket.SynDataEx.Value.uUdpVer; this.clientRdpudpVerfionInfoValidFlag = synPacket.SynDataEx.Value.uSynExFlags; //Section 3.1.5.1.1: The RDPUDP_VERSION_INFO_VALID flag MUST be set only if the structure contains a valid RDP-UDP protocol version. if (synPacket.SynDataEx.Value.uSynExFlags.HasFlag(uSynExFlags_Values.RDPUDP_VERSION_INFO_VALID) && ((int)synPacket.SynDataEx.Value.uUdpVer & 0xfffc) != 0) { this.Site.Assert.Fail("Section 3.1.5.1.1: The RDPUDP_VERSION_INFO_VALID flag MUST be set only if the structure contains a valid RDP-UDP protocol version"); } } } /// <summary> /// Verify an ACK Packet. /// </summary> /// <param name="ackPacket">The ACK packet.</param> private void VerifyACKPacket(RdpeudpPacket ackPacket) { if (ackPacket == null) { this.Site.Assert.Fail("The ACK Packet should not be null!"); } if ((ackPacket.fecHeader.uFlags & RDPUDP_FLAG.RDPUDP_FLAG_ACK) == 0) { this.Site.Assert.Fail("The RDPUDP_FLAG_ACK flag MUST be set in ACK packet!"); } } #endregion private void CheckPlatformCompatibility(ref TransportMode[] transportModes) { var applicableTransportModes = transportModes.AsEnumerable(); // Check lossy transport mode, which is currently only supported on Windows. if (applicableTransportModes.Any(transportMode => transportMode == TransportMode.Lossy)) { if (!OperatingSystem.IsWindows()) { BaseTestSite.Log.Add(LogEntryKind.Comment, "The lossy transport mode is only supported on Windows."); applicableTransportModes = applicableTransportModes.Where(transportMode => transportMode != TransportMode.Lossy); } } if (applicableTransportModes.Count() == 0) { BaseTestSite.Assume.Inconclusive("No transport mode is applicable to the running operating system."); } transportModes = applicableTransportModes.ToArray(); } } }
40.267116
300
0.585122
[ "MIT" ]
hshavit-infinidat/WindowsProtocolTestSuites
TestSuites/RDP/Client/src/TestSuite/RDPEUDP/RdpeudpTestSuite.cs
35,878
C#
#region Copyright notice and license // Copyright 2019 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Threading.Tasks; using Grpc.Core; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace Grpc.AspNetCore.Server.Internal { internal class ServerStreamingServerCallHandler<TRequest, TResponse, TService> : ServerCallHandlerBase<TRequest, TResponse, TService> where TRequest : class where TResponse : class where TService : class { // We're using an open delegate (the first argument is the TService instance) to represent the call here since the instance is create per request. // This is the reason we're not using the delegates defined in Grpc.Core. This delegate maps to ServerStreamingServerMethod<TRequest, TResponse> // with an instance parameter. private delegate Task ServerStreamingServerMethod(TService service, TRequest request, IServerStreamWriter<TResponse> stream, ServerCallContext serverCallContext); private readonly ServerStreamingServerMethod _invoker; public ServerStreamingServerCallHandler(Method<TRequest, TResponse> method) : base(method) { var handlerMethod = typeof(TService).GetMethod(Method.Name); _invoker = (ServerStreamingServerMethod)Delegate.CreateDelegate(typeof(ServerStreamingServerMethod), handlerMethod); } public override async Task HandleCallAsync(HttpContext httpContext) { httpContext.Response.ContentType = "application/grpc"; httpContext.Response.Headers.Append("grpc-encoding", "identity"); var requestPayload = await httpContext.Request.BodyPipe.ReadSingleMessageAsync(); var request = Method.RequestMarshaller.Deserializer(requestPayload); // Activate the implementation type via DI. var activator = httpContext.RequestServices.GetRequiredService<IGrpcServiceActivator<TService>>(); var service = activator.Create(); var serverCallContext = new HttpContextServerCallContext(httpContext); var streamWriter = new HttpContextStreamWriter<TResponse>(serverCallContext, Method.ResponseMarshaller.Serializer); serverCallContext.Initialize(); using (serverCallContext) { await _invoker( service, request, streamWriter, serverCallContext); } httpContext.Response.ConsolidateTrailers(serverCallContext); // Flush any buffered content await httpContext.Response.BodyPipe.FlushAsync(); } } }
41.544304
170
0.703534
[ "Apache-2.0" ]
Kadajski/grpc-dotnet
src/Grpc.AspNetCore.Server/Internal/ServerStreamingServerCallHandler.cs
3,284
C#
// Copyright © 2018 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.IO.MemoryMappedFiles; using System.Windows; using System.Windows.Controls; using System.Windows.Interop; using System.Windows.Threading; using Rect = CefSharp.Structs.Rect; namespace CefSharp.Wpf.Rendering { /// <summary> /// InteropBitmapRenderHandler - creates/updates an InteropBitmap /// Uses a MemoryMappedFile for double buffering when the size matches /// or creates a new InteropBitmap when required /// </summary> /// <seealso cref="CefSharp.Wpf.IRenderHandler" /> public class InteropBitmapRenderHandler : AbstractRenderHandler { /// <summary> /// Initializes a new instance of the <see cref="InteropBitmapRenderHandler"/> class. /// </summary> /// <param name="dispatcherPriority">priority at which the bitmap will be updated on the UI thread</param> public InteropBitmapRenderHandler(DispatcherPriority dispatcherPriority = DispatcherPriority.Render) { this.dispatcherPriority = dispatcherPriority; } protected override void CreateOrUpdateBitmap(bool isPopup, Rect dirtyRect, IntPtr buffer, int width, int height, Image image, ref Size currentSize, ref MemoryMappedFile mappedFile, ref MemoryMappedViewAccessor viewAccessor) { var createNewBitmap = false; lock (lockObject) { int pixels = width * height; int numberOfBytes = pixels * BytesPerPixel; createNewBitmap = mappedFile == null || currentSize.Height != height || currentSize.Width != width; if (createNewBitmap) { //If the MemoryMappedFile is smaller than we need then create a larger one //If it's larger then we need then rather than going through the costly expense of //allocating a new one we'll just use the old one and only access the number of bytes we require. if (viewAccessor == null || viewAccessor.Capacity < numberOfBytes) { ReleaseMemoryMappedView(ref mappedFile, ref viewAccessor); mappedFile = MemoryMappedFile.CreateNew(null, numberOfBytes, MemoryMappedFileAccess.ReadWrite); viewAccessor = mappedFile.CreateViewAccessor(); } currentSize.Height = height; currentSize.Width = width; } NativeMethodWrapper.MemoryCopy(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, numberOfBytes); //Take a reference to the backBufferHandle, once we're on the UI thread we need to check if it's still valid var backBufferHandle = mappedFile.SafeMemoryMappedFileHandle; //Invoke on the WPF UI Thread image.Dispatcher.BeginInvoke((Action)(() => { lock (lockObject) { if (backBufferHandle.IsClosed || backBufferHandle.IsInvalid) { return; } if (createNewBitmap) { if (image.Source != null) { image.Source = null; //TODO: Is this still required in newer versions of .Net? GC.Collect(1); } var stride = width * BytesPerPixel; var bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(backBufferHandle.DangerousGetHandle(), width, height, PixelFormat, stride, 0); image.Source = bitmap; } else if (image.Source != null) { var bitmap = (InteropBitmap)image.Source; #if NET40 bitmap.Invalidate(); #else // We can optimise the invalidation in .NET >= 4.5 var sourceRect = new Int32Rect(dirtyRect.X, dirtyRect.Y, dirtyRect.Width, dirtyRect.Height); bitmap.Invalidate(sourceRect); #endif } } }), dispatcherPriority); } } } }
43.476636
231
0.55718
[ "BSD-3-Clause" ]
364988343/CefSharp.Net40
CefSharp.Wpf/Rendering/InteropBitmapRenderHandler.cs
4,653
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Kms.Model.V20160120; namespace Aliyun.Acs.Kms.Transform.V20160120 { public class EncryptResponseUnmarshaller { public static EncryptResponse Unmarshall(UnmarshallerContext context) { EncryptResponse encryptResponse = new EncryptResponse() { HttpResponse = context.HttpResponse, CiphertextBlob = context.StringValue("Encrypt.CiphertextBlob"), KeyId = context.StringValue("Encrypt.KeyId"), RequestId = context.StringValue("Encrypt.RequestId") }; return encryptResponse; } } }
39
79
0.699055
[ "Apache-2.0" ]
VAllens/aliyun-openapi-sdk-net-core
src/aliyun-net-sdk-kms/Transform/V20160120/EncryptResponseUnmarshaller.cs
1,482
C#
using FundAdministration.GlobalAccounting.Reference; using FundAdministration.GlobalAccounting.Reference.ExchangeRates; using FundAdministration.GlobalAccounting.Reference.ForwardExchangeRates; using FundAdministration.GlobalAccounting.Reference.ForwardInterestRates; using FundAdministration.GlobalAccounting.Reference.InterestRateTypes; using FundAdministration.GlobalAccounting.Reference.SecurityPrices; using FundAdministration.GlobalAccounting.Reference.SwapInterestRates; using FundAdministration.GlobalAccounting.Reference.SwapsPrices; namespace FundAdministration.GlobalAccounting; public class ReferenceClient : IReferenceClient { private readonly HttpClient _httpClient; public string BaseUrl { get; set; } = Shared.Data.DefaultConfig.BaseUrl; public bool ReadResponseAsString { get; set; } = Shared.Data.DefaultConfig.ReadResponseAsString; public ReferenceClient(HttpClient httpClient) { _httpClient = httpClient; } public IExchangeRateService ExchangeRateService => new ExchangeRateService(_httpClient) { BaseUrl = BaseUrl, ReadResponseAsString = ReadResponseAsString }; public IForwardExchangeRateService ForwardExchangeRateService => new ForwardExchangeRateService(_httpClient) { BaseUrl = BaseUrl, ReadResponseAsString = ReadResponseAsString }; public IForwardInterestRateService ForwardInterestRateService => new ForwardInterestRateService(_httpClient) { BaseUrl = BaseUrl, ReadResponseAsString = ReadResponseAsString }; public IInterestRateTypeService InterestRateTypeService => new InterestRateTypeService(_httpClient) { BaseUrl = BaseUrl, ReadResponseAsString = ReadResponseAsString }; public ISecurityPriceService SecurityPriceService => new SecurityPriceService(_httpClient) { BaseUrl = BaseUrl, ReadResponseAsString = ReadResponseAsString }; public ISwapInterestRateService SwapInterestRateService => new SwapInterestRateService(_httpClient) { BaseUrl = BaseUrl, ReadResponseAsString = ReadResponseAsString }; public ISwapsPriceService SwapsPriceService => new SwapsPriceService(_httpClient) { BaseUrl = BaseUrl, ReadResponseAsString = ReadResponseAsString }; }
71.6
180
0.837989
[ "MIT" ]
ElevateData/OpenTemenos
src/FundAdministration.GlobalAccounting/ReferenceClient.cs
2,150
C#
using Intellect.Core.Models.Authors; using Intellect.Core.Models.Authors.Dtos; using Intellect.Core.Models.Categories; using Intellect.Core.Models.Categories.Dtos; using Intellect.Core.Models.Helpers; using System; using System.Collections.Generic; using System.Text; namespace Intellect.Core.Models.GovtPublications.Dtos { public class GovtPublicationOutputDto { public int Id { get; set; } public int TotalPages { get; set; } public string Sector { get; set; } public string DisplayName { get; set; } public string Publisher { get; set; } public DateTime Year { get; set; } public int Price { get; set; } public SourceType SourceType { get; set; } public AuthorOutputDto Author { get; set; } public CategoryOutputDto Category { get; set; } } }
24.257143
55
0.677267
[ "MIT" ]
Lasanga/LibraryApplication
core/Intellect.Core/Models/GovtPublications/Dtos/GovtPublicationOutputDto.cs
851
C#
using UnityEngine; public class MBMusicOnOff : MonoBehaviour,MBAction { private Texture musicOn; public Texture musicOff; private bool active; private SoundController soundController; // Use this for initialization void Start () { active = true; musicOn = GetComponent<Renderer>().material.GetTexture("_MainTex"); this.InitSoundController(); if (PlayerPrefs.GetString("music", "True") == false.ToString()) { active = false; GetComponent<Renderer>().material.SetTexture("_MainTex", musicOff); } } private void InitSoundController() { GameObject soundControllerObject = GameObject.FindGameObjectWithTag("SoundController"); if (soundControllerObject != null) soundController = soundControllerObject.GetComponent<SoundController>(); else Debug.Log("Error: Sound Controller no encontrado."); } void MBAction.doAction() { active = !active; if (active) { GetComponent<Renderer>().material.SetTexture("_MainTex", musicOn); soundController.backgroundMusic.Play(); } else { GetComponent<Renderer>().material.SetTexture("_MainTex", musicOff); soundController.backgroundMusic.Stop(); } PlayerPrefs.SetString("music", active.ToString()); } }
27.269231
95
0.622708
[ "Unlicense" ]
Maximetinu/No-Mans-Flappy-Unity
Assets/Scripts/MenuButtons/MBMusicOnOff.cs
1,420
C#
using System; class Solution { static void Main(String[] args) { var numberOfTestCases = int.Parse(Console.ReadLine()); for (int a0 = 0; a0 < numberOfTestCases; a0++) { var n = Console.ReadLine(); var number = int.Parse(n); var digitCount = 0; foreach (var item in n) { if (item == '0') continue; if (number % (int)char.GetNumericValue(item) == 0) digitCount++; } Console.WriteLine(digitCount); } } }
24.12
66
0.456053
[ "MIT" ]
sahaavi/HackerRank
Algorithms/Implementation/Find Digits/Solution.cs
603
C#
namespace CombatModCollection.SendAllTroops { public class Item { public float Strength; public float Health; public Item Clone() { return new Item { Strength = this.Strength, Health = this.Health }; } } }
19.235294
44
0.477064
[ "MIT" ]
sgsdxzy/CombatModCollection
src/SendAllTroops/Item.cs
329
C#
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Game { class Time { // Stopwatch to start the time. static Stopwatch stopwatch = new Stopwatch(); // Gets the Delta-Time public static float deltaTime { get { return GetDeltaTime(); } set { GetDeltaTime(); } } // Stores the Current Time public static long currentTime = 0; // Stores the Last Time public static long lastTime = 0; // Starts the stopwatch public static void Start() { stopwatch.Start(); } // Resets the stopwatch public static void Reset() { stopwatch.Reset(); } // Gets the Delta-Time private static float GetDeltaTime() { currentTime = stopwatch.ElapsedMilliseconds; float dt = (currentTime - lastTime) / 1000.0f; lastTime = currentTime; return dt; } } }
26.410256
96
0.559223
[ "MIT" ]
TylerRPeterson/MathForGames
ConsoleApp1/Game/Utils/Time.cs
1,032
C#
// Copyright (c) 2022 AccelByte Inc. All Rights Reserved. // This is licensed software from AccelByte Inc, for limitations // and restrictions contact your company contract manager. // This code is generated by tool. DO NOT EDIT. using System.Text.Json.Serialization; using AccelByte.Sdk.Core; using AccelByte.Sdk.Core.Converters; namespace AccelByte.Sdk.Api.Platform.Model { public class ItemSnapshot : AccelByte.Sdk.Core.Model { [JsonPropertyName("appId")] public string? AppId { get; set; } [JsonPropertyName("appType")] [JsonStringEnum] public ItemSnapshotAppType? AppType { get; set; } [JsonPropertyName("baseAppId")] public string? BaseAppId { get; set; } [JsonPropertyName("boothName")] public string? BoothName { get; set; } [JsonPropertyName("createdAt")] public DateTime? CreatedAt { get; set; } [JsonPropertyName("description")] public string? Description { get; set; } [JsonPropertyName("entitlementType")] [JsonStringEnum] public ItemSnapshotEntitlementType? EntitlementType { get; set; } [JsonPropertyName("features")] public List<string>? Features { get; set; } [JsonPropertyName("itemId")] public string? ItemId { get; set; } [JsonPropertyName("itemIds")] public List<string>? ItemIds { get; set; } [JsonPropertyName("itemQty")] public Dictionary<string, int>? ItemQty { get; set; } [JsonPropertyName("itemType")] [JsonStringEnum] public ItemSnapshotItemType? ItemType { get; set; } [JsonPropertyName("language")] public string? Language { get; set; } [JsonPropertyName("listable")] public bool? Listable { get; set; } [JsonPropertyName("maxCount")] public int? MaxCount { get; set; } [JsonPropertyName("maxCountPerUser")] public int? MaxCountPerUser { get; set; } [JsonPropertyName("name")] public string? Name { get; set; } [JsonPropertyName("namespace")] public string? Namespace { get; set; } [JsonPropertyName("purchasable")] public bool? Purchasable { get; set; } [JsonPropertyName("recurring")] public Recurring? Recurring { get; set; } [JsonPropertyName("region")] public string? Region { get; set; } [JsonPropertyName("regionDataItem")] public RegionDataItem? RegionDataItem { get; set; } [JsonPropertyName("seasonType")] [JsonStringEnum] public ItemSnapshotSeasonType? SeasonType { get; set; } [JsonPropertyName("sku")] public string? Sku { get; set; } [JsonPropertyName("stackable")] public bool? Stackable { get; set; } [JsonPropertyName("targetCurrencyCode")] public string? TargetCurrencyCode { get; set; } [JsonPropertyName("targetItemId")] public string? TargetItemId { get; set; } [JsonPropertyName("targetNamespace")] public string? TargetNamespace { get; set; } [JsonPropertyName("thumbnailUrl")] public string? ThumbnailUrl { get; set; } [JsonPropertyName("title")] public string? Title { get; set; } [JsonPropertyName("updatedAt")] public DateTime? UpdatedAt { get; set; } [JsonPropertyName("useCount")] public int? UseCount { get; set; } } public class ItemSnapshotAppType : StringEnum<ItemSnapshotAppType> { public static readonly ItemSnapshotAppType GAME = new ItemSnapshotAppType("GAME"); public static readonly ItemSnapshotAppType SOFTWARE = new ItemSnapshotAppType("SOFTWARE"); public static readonly ItemSnapshotAppType DLC = new ItemSnapshotAppType("DLC"); public static readonly ItemSnapshotAppType DEMO = new ItemSnapshotAppType("DEMO"); public static implicit operator ItemSnapshotAppType(string value) { return Create(value); } public ItemSnapshotAppType(string enumValue) : base(enumValue) { } } public class ItemSnapshotEntitlementType : StringEnum<ItemSnapshotEntitlementType> { public static readonly ItemSnapshotEntitlementType DURABLE = new ItemSnapshotEntitlementType("DURABLE"); public static readonly ItemSnapshotEntitlementType CONSUMABLE = new ItemSnapshotEntitlementType("CONSUMABLE"); public static implicit operator ItemSnapshotEntitlementType(string value) { return Create(value); } public ItemSnapshotEntitlementType(string enumValue) : base(enumValue) { } } public class ItemSnapshotItemType : StringEnum<ItemSnapshotItemType> { public static readonly ItemSnapshotItemType APP = new ItemSnapshotItemType("APP"); public static readonly ItemSnapshotItemType COINS = new ItemSnapshotItemType("COINS"); public static readonly ItemSnapshotItemType INGAMEITEM = new ItemSnapshotItemType("INGAMEITEM"); public static readonly ItemSnapshotItemType BUNDLE = new ItemSnapshotItemType("BUNDLE"); public static readonly ItemSnapshotItemType CODE = new ItemSnapshotItemType("CODE"); public static readonly ItemSnapshotItemType SUBSCRIPTION = new ItemSnapshotItemType("SUBSCRIPTION"); public static readonly ItemSnapshotItemType SEASON = new ItemSnapshotItemType("SEASON"); public static readonly ItemSnapshotItemType MEDIA = new ItemSnapshotItemType("MEDIA"); public static implicit operator ItemSnapshotItemType(string value) { return Create(value); } public ItemSnapshotItemType(string enumValue) : base(enumValue) { } } public class ItemSnapshotSeasonType : StringEnum<ItemSnapshotSeasonType> { public static readonly ItemSnapshotSeasonType PASS = new ItemSnapshotSeasonType("PASS"); public static readonly ItemSnapshotSeasonType TIER = new ItemSnapshotSeasonType("TIER"); public static implicit operator ItemSnapshotSeasonType(string value) { return Create(value); } public ItemSnapshotSeasonType(string enumValue) : base(enumValue) { } } }
29.556054
86
0.63435
[ "MIT" ]
AccelByte/accelbyte-csharp-sdk
AccelByte.Sdk/Api/Platform/Model/ItemSnapshot.cs
6,591
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Charlotte.Common; using Charlotte.Tools; namespace Charlotte.Games { public static class MapTileManager { public static void INIT() { foreach (string file in DDResource.GetFiles()) { try { const string filePrefix = "Etoile\\G4YokoActTM\\MapTile\\"; const string fileSuffix = ".png"; if ( StringTools.StartsWithIgnoreCase(file, filePrefix) && StringTools.EndsWithIgnoreCase(file, fileSuffix) ) { string name = file.Substring(filePrefix.Length, file.Length - filePrefix.Length - fileSuffix.Length).Replace('\\', '/'); MapTile tile = new MapTile() { Name = name, Picture = DDPictureLoaders.Standard(file), }; Add(tile); } } catch (Exception e) { throw new AggregateException("file: " + file, e); } } } private static List<string> Names = new List<string>(); private static Dictionary<string, MapTile> Tiles = DictionaryTools.CreateIgnoreCase<MapTile>(); private static void Add(MapTile tile) { Names.Add(tile.Name); Tiles.Add(tile.Name, tile); } public static MapTile GetTile(string name) { if (Tiles.ContainsKey(name) == false) return null; return Tiles[name]; } public static List<string> GetNames() { return Names; } public static int GetCount() { return Names.Count; } } }
20.291667
126
0.647502
[ "MIT" ]
stackprobe/G4YokoActTM
G4YokoActTM/G4YokoActTM/Games/MapTileManager.cs
1,463
C#
//------------------------------------------------------------ // Game Framework v3.x // Copyright © 2013-2017 Jiang Yin. All rights reserved. // Homepage: http://gameframework.cn/ // Feedback: mailto:[email protected] //------------------------------------------------------------ using GameFramework.Event; using GameFramework.Network; namespace UnityGameFramework.Runtime { /// <summary> /// 网络连接成功事件。 /// </summary> public sealed class NetworkConnectedEventArgs : GameEventArgs { /// <summary> /// 初始化网络连接成功事件的新实例。 /// </summary> /// <param name="e">内部事件。</param> public NetworkConnectedEventArgs(GameFramework.Network.NetworkConnectedEventArgs e) { NetworkChannel = e.NetworkChannel; UserData = e.UserData; } /// <summary> /// 获取连接成功事件编号。 /// </summary> public override int Id { get { return (int)EventId.NetworkConnected; } } /// <summary> /// 获取网络频道。 /// </summary> public INetworkChannel NetworkChannel { get; private set; } /// <summary> /// 获取用户自定义数据。 /// </summary> public object UserData { get; private set; } } }
23.931034
91
0.471182
[ "MIT" ]
Echoflyer/ILGameFramework
Assets/Framework/Scripts/Runtime/Event/NetworkConnectedEventArgs.cs
1,507
C#
using System; using System.Reflection.Metadata.Ecma335; using System.Text.Json; using System.Xml; namespace Open_Lab_02._08 { public class Checker { public bool IsEmpty(string str) { if (String.IsNullOrEmpty(str)) { return true; } else { return false; } } } }
15.133333
42
0.431718
[ "MIT" ]
SimonKvasnovsky/Open-Lab-02.08
Open-Lab-02.08/Checker.cs
456
C#
namespace EA.Iws.RequestHandlers.StateOfImport { using System.Linq; using System.Threading.Tasks; using Core.Shared; using Core.StateOfExport; using Core.StateOfImport; using Core.TransitState; using DataAccess; using Domain; using Domain.TransportRoute; using EA.Iws.Domain.NotificationApplication; using EA.Iws.Requests.TransportRoute; using Prsd.Core.Mapper; using Prsd.Core.Mediator; using Requests.StateOfImport; internal class GetStateOfImportWithTransportRouteDataByNotificationIdHandler : IRequestHandler<GetStateOfImportWithTransportRouteDataByNotificationId, StateOfImportWithTransportRouteData> { private readonly IwsContext context; private readonly IMapper mapper; private readonly ITransportRouteRepository transportRouteRepository; private readonly ICompetentAuthorityRepository competentAuthorityRepository; private readonly ICountryRepository countryRepository; private readonly IIntraCountryExportAllowedRepository intraCountryExportAllowedRepository; private readonly INotificationApplicationRepository notificationApplicationRepository; private readonly IRequestHandler<GetCompetentAuthoritiesAndEntryPointsByCountryId, CompetentAuthorityAndEntryOrExitPointData> getCompetentAuthoritiesAndEntryPointsByCountryIdHandler; private readonly IUnitedKingdomCompetentAuthorityRepository unitedKingdomCompetentAuthorityRepository; public GetStateOfImportWithTransportRouteDataByNotificationIdHandler(IwsContext context, IMapper mapper, ITransportRouteRepository transportRouteRepository, ICompetentAuthorityRepository competentAuthorityRepository, ICountryRepository countryRepository, IIntraCountryExportAllowedRepository intraCountryExportAllowedRepository, INotificationApplicationRepository notificationApplicationRepository, IRequestHandler<GetCompetentAuthoritiesAndEntryPointsByCountryId, CompetentAuthorityAndEntryOrExitPointData> getCompetentAuthoritiesAndEntryPointsByCountryIdHandler, IUnitedKingdomCompetentAuthorityRepository unitedKingdomCompetentAuthorityRepository) { this.context = context; this.mapper = mapper; this.transportRouteRepository = transportRouteRepository; this.competentAuthorityRepository = competentAuthorityRepository; this.countryRepository = countryRepository; this.intraCountryExportAllowedRepository = intraCountryExportAllowedRepository; this.notificationApplicationRepository = notificationApplicationRepository; this.getCompetentAuthoritiesAndEntryPointsByCountryIdHandler = getCompetentAuthoritiesAndEntryPointsByCountryIdHandler; this.unitedKingdomCompetentAuthorityRepository = unitedKingdomCompetentAuthorityRepository; } public async Task<StateOfImportWithTransportRouteData> HandleAsync(GetStateOfImportWithTransportRouteDataByNotificationId message) { var transportRoute = await transportRouteRepository.GetByNotificationId(message.Id); var countries = await countryRepository.GetAllHavingCompetentAuthorities(); var notification = await notificationApplicationRepository.GetById(message.Id); var allowed = await intraCountryExportAllowedRepository.GetImportCompetentAuthorities(notification.CompetentAuthority); if (!allowed.Any()) { // Need to remove the UK from the list var unitedkingdomId = (await this.unitedKingdomCompetentAuthorityRepository.GetByCompetentAuthority(notification.CompetentAuthority)).CompetentAuthority.Country.Id; countries = countries.Where(c => c.Id != unitedkingdomId); } var data = new StateOfImportWithTransportRouteData(); if (transportRoute != null) { data.StateOfImport = mapper.Map<StateOfImportData>(transportRoute.StateOfImport); data.StateOfExport = mapper.Map<StateOfExportData>(transportRoute.StateOfExport); data.TransitStates = transportRoute.TransitStates.Select(t => mapper.Map<TransitStateData>(t)).ToList(); if (transportRoute.StateOfImport != null) { var selectedCountryModel = new GetCompetentAuthoritiesAndEntryPointsByCountryId(transportRoute.StateOfImport.Country.Id, notification.CompetentAuthority); var dataForSelectedCountry = await this.getCompetentAuthoritiesAndEntryPointsByCountryIdHandler.HandleAsync(selectedCountryModel); data.CompetentAuthorities = dataForSelectedCountry.CompetentAuthorities; data.EntryPoints = dataForSelectedCountry.EntryOrExitPoints; } data.IntraCountryExportAllowed = allowed.Select(a => mapper.Map<IntraCountryExportAllowedData>(a)).ToArray(); } data.Countries = countries.Select(c => mapper.Map<CountryData>(c)).ToArray(); return data; } } }
57.777778
191
0.7475
[ "Unlicense" ]
DEFRA/prsd-iws
src/EA.Iws.RequestHandlers/StateOfImport/GetStateOfImportWithTransportRouteDataByNotificationIdHandler.cs
5,202
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.GoogleNative.Container.V1Beta1.Inputs { /// <summary> /// LoggingConfig is cluster logging configuration. /// </summary> public sealed class LoggingConfigArgs : Pulumi.ResourceArgs { /// <summary> /// Logging components configuration /// </summary> [Input("componentConfig")] public Input<Inputs.LoggingComponentConfigArgs>? ComponentConfig { get; set; } public LoggingConfigArgs() { } } }
27.448276
86
0.669598
[ "Apache-2.0" ]
AaronFriel/pulumi-google-native
sdk/dotnet/Container/V1Beta1/Inputs/LoggingConfigArgs.cs
796
C#
using RWLayout.alpha2; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; using Verse; namespace PawnTableGrouped { public class CRowSegment : CListingRow { Verse.WeakReference<CPawnTableRow> row = null; public CPawnTableRow Row { get { return row?.Target; } set { row = new Verse.WeakReference<CPawnTableRow>(value); } } public virtual float xScrollOffset { get; set; } = 0; public virtual float visibleRectWidth { get; set; } = 0; } public class CPawnTableRow { public Verse.WeakReference<CPawnTable> owner = null; public CPawnTable Owner { get { return owner?.Target; } set { owner = new Verse.WeakReference<CPawnTable>(value); if (Fixed != null) { Fixed.Owner = value; } if (Row != null) { Row.Owner = value; } if (Background != null) { Background.Owner = value; } } } public CRowSegment fixed_; public CRowSegment Fixed { get => fixed_; set { fixed_ = value; if (value != null) { fixed_.Row = this; } } } public CRowSegment row_; public CRowSegment Row { get => row_; set { row_ = value; if (value != null) { row_.Row = this; } } } public CGuiRoot background_; public CGuiRoot Background { get => background_; set { background_ = value; /* if (value != null) { background_.Row = this; }*/ } } public virtual float xScrollOffset { get { return 0; } set { if (Fixed != null) { Fixed.xScrollOffset = value; } if (Row != null) { Row.xScrollOffset = value; } } } public virtual float visibleRectWidth { get { return 0; } set { if (Fixed != null) { Fixed.visibleRectWidth = value; } if (Row != null) { Row.visibleRectWidth = value; } } } } public class CPawnTable : CElement { Rect headerRowRect; Rect headerRowInnerRect; Rect vScrollViewOuterRect; Rect vScrollViewInnerRect; Rect hScrollClipRect; Rect hScrollInnerRect; /// <summary> /// Scroll Location /// </summary> public Vector2 OuterScrollPosition = Vector2.zero; public CPawnTableRow TableHeader = null; List<CPawnTableRow> rows = new List<CPawnTableRow>(); public IReadOnlyList<CPawnTableRow> Rows { get => rows; } public float FixedSegmentWidth { get; internal set; } public bool allowHScroll = false; public float InnerWidth; Rect hScrollRect; float hScrollPosition = 0; bool hScrollVisible = false; public override void PostLayoutUpdate() { base.PostLayoutUpdate(); var vBarWidth = GUI.skin.verticalScrollbar.fixedWidth + GUI.skin.verticalScrollbar.margin.left; var hBarHeight = GUI.skin.horizontalScrollbar.fixedHeight + GUI.skin.horizontalScrollbar.margin.top; if (TableHeader.Fixed != null) { TableHeader.Fixed.InRect = new Rect(Bounds.xMin, Bounds.yMin, FixedSegmentWidth, 0); TableHeader.Fixed.UpdateLayoutIfNeeded(); } if (TableHeader.Row != null) { if (allowHScroll) { TableHeader.Row.InRect = new Rect(0, 0, InnerWidth, 0); } else { TableHeader.Row.InRect = new Rect(Bounds.xMin, Bounds.yMin, InnerWidth, 0); } TableHeader.Row.UpdateLayoutIfNeeded(); } var headerHeight = Mathf.Max(TableHeader?.Fixed?.Bounds.height ?? 0, TableHeader?.Row?.Bounds.height ?? 0); headerRowRect = new Rect(Bounds.xMin + FixedSegmentWidth, Bounds.yMin, Bounds.width - FixedSegmentWidth - vBarWidth, headerHeight); headerRowInnerRect = new Rect(0, 0, InnerWidth, headerHeight); float y = 0; foreach (var row in rows) { if (row.Fixed != null) { row.Fixed.InRect = new Rect(0, y, FixedSegmentWidth, 0); row.Fixed.UpdateLayoutIfNeeded(); } if (row.Row != null) { row.Row.InRect = new Rect(0, y, InnerWidth - FixedSegmentWidth, 0); row.Row.UpdateLayoutIfNeeded(); } var rowHeight = Mathf.Max(row.Fixed?.Bounds.height ?? 0, row.Row?.Bounds.height ?? 0); if (row.Background != null) { row.Background.InRect = new Rect(0, y, InnerWidth, rowHeight); row.Background.UpdateLayoutIfNeeded(); } y += rowHeight; } hScrollVisible = InnerWidth > Bounds.width - vBarWidth; vScrollViewOuterRect = Rect.MinMaxRect(Bounds.xMin, Bounds.yMin + headerHeight, Bounds.xMax, Bounds.yMax - (hScrollVisible ? hBarHeight : 0)); vScrollViewInnerRect = new Rect(0, 0, Bounds.width - vBarWidth, y).GUIRoundedPreserveOrigin(); hScrollClipRect = new Rect(FixedSegmentWidth, 0, Bounds.width - vBarWidth - FixedSegmentWidth, y); hScrollInnerRect = new Rect(0, 0, InnerWidth - FixedSegmentWidth, y); hScrollRect = Rect.MinMaxRect(Bounds.xMin + FixedSegmentWidth, Bounds.yMax - hBarHeight, Bounds.xMax - vBarWidth, Bounds.yMax); } public override void DoContent() { base.DoContent(); if (hScrollVisible) { hScrollPosition = GUI.HorizontalScrollbar(hScrollRect, hScrollPosition, hScrollClipRect.width, 0, hScrollInnerRect.width); } else { hScrollPosition = 0; } if (TableHeader.Row != null) { float xScrollOffset; float visibleRectWidth; if (allowHScroll) { xScrollOffset = hScrollPosition + FixedSegmentWidth; visibleRectWidth = hScrollClipRect.width; GUI.BeginClip(headerRowRect); var innerRowRect = headerRowInnerRect; innerRowRect.x = headerRowInnerRect.x - xScrollOffset; GUI.BeginGroup(innerRowRect); } else { xScrollOffset = 0; visibleRectWidth = TableHeader.Row.BoundsRounded.width; } TableHeader.Row.xScrollOffset = xScrollOffset; TableHeader.Row.visibleRectWidth = visibleRectWidth; TableHeader.Row.DoElementContent(); if (allowHScroll) { GUI.EndGroup(); GUI.EndClip(); } } if (TableHeader.Fixed != null) { if (allowHScroll) { TableHeader.Fixed.xScrollOffset = 0; TableHeader.Fixed.visibleRectWidth = FixedSegmentWidth; TableHeader.Fixed.DoElementContent(); } } Widgets.BeginScrollView(vScrollViewOuterRect, ref OuterScrollPosition, vScrollViewInnerRect, true); var windowYMin = OuterScrollPosition.y; var windowYMax = OuterScrollPosition.y + this.BoundsRounded.height; foreach (var row in rows) { if (row.Background != null) { if ((row.Background.BoundsRounded.yMax > windowYMin) && (row.Background.BoundsRounded.yMin < windowYMax)) { row.xScrollOffset = hScrollPosition; row.visibleRectWidth = hScrollClipRect.width; row.Background.DoElementContent(); } } } GUI.BeginClip(hScrollClipRect); var rect = hScrollInnerRect; rect.x = rect.x - hScrollPosition; GUI.BeginGroup(rect); foreach (var row in rows) { if (row.Row != null) { if ((row.Row.BoundsRounded.yMax > windowYMin) && (row.Row.BoundsRounded.yMin < windowYMax)) { row.xScrollOffset = hScrollPosition; row.visibleRectWidth = hScrollClipRect.width; row.Row.DoElementContent(); } } } GUI.EndGroup(); GUI.EndClip(); foreach (var row in rows) { if (row.Fixed != null) { if ((row.Fixed.BoundsRounded.yMax > windowYMin) && (row.Fixed.BoundsRounded.yMin < windowYMax)) { row.xScrollOffset = 0; row.visibleRectWidth = FixedSegmentWidth; row.Fixed.DoElementContent(); } } } Widgets.EndScrollView(); } #region rows manipulations /// <summary> /// Append a row to CListView. /// </summary> /// <param name="row">the row</param> /// <returns>the row</returns> /// <remarks>Row must not be added in this or other CListView</remarks> public CPawnTableRow AppendRow(CPawnTableRow row) { if (row.Owner != null) { throw new InvalidOperationException($"{row} is already added to {row.Owner}"); } row.Owner = this; rows.Add(row); SetNeedsUpdateLayout(); return row; } /// <summary> /// Insert a row to CListView at index. /// </summary> /// <param name="index">index to insert the row at</param> /// <param name="row">the row</param> /// <returns>the row</returns> /// <remarks>Row must not be added in this or other CListView</remarks> public CPawnTableRow InsertRow(int index, CPawnTableRow row) { if (row.Owner != null) { throw new InvalidOperationException($"{row} is already added to {row.Owner}"); } row.Owner = this; rows.Insert(index, row); SetNeedsUpdateLayout(); return row; } /// <summary> /// Removes the row from CListView /// </summary> /// <param name="row">the row</param> /// <returns>true if row was successfully removed</returns> public bool RemoveRow(CPawnTableRow row) { bool result; if (result = rows.Remove(row)) { row.Owner = null; } SetNeedsUpdateLayout(); return result; } /// <summary> /// Removes the row at index from CListView /// </summary> /// <param name="row">index of row to remove</param> /// <returns>the removed row</returns> public CPawnTableRow RemoveRowAt(int index) { var row = rows[index]; rows.RemoveAt(index); row.Owner = null; SetNeedsUpdateLayout(); return row; } /// <summary> /// Moves row to index /// </summary> /// <param name="row">the row</param> /// <param name="index">new index</param> public void MoveRowTo(CPawnTableRow row, int index) { rows.Remove(row); rows.Insert(index, row); SetNeedsUpdateLayout(); } /// <summary> /// Returns index of the row /// </summary> /// <param name="row">the row</param> /// <returns>The zero-based index of the row, if found; otherwise, -1.</returns> public int IndexOfRow(CPawnTableRow row) { return rows.IndexOf(row); } /// <summary> /// Removes all rows /// </summary> public void ClearRows() { foreach (var row in rows) { row.Owner = null; } rows.Clear(); } #endregion } }
30.14693
154
0.473049
[ "MIT" ]
krypt-lynx/PawnTableGrouped
Source/PawnTableGrouped/PawnTableGrouped/Elements/CPawnTable.cs
13,749
C#
using System; using Gremlin.Net.Process.Traversal; namespace ExRam.Gremlinq.Core { public sealed class TailStep : Step { public static readonly TailStep TailLocal1 = new(1, Scope.Local); public static readonly TailStep TailGlobal1 = new(1, Scope.Global); public TailStep(long count, Scope scope) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); Count = count; Scope = scope; } public long Count { get; } public Scope Scope { get; } } }
24.291667
75
0.595197
[ "MIT" ]
fathym-it/ExRam.Gremlinq
src/ExRam.Gremlinq.Core/Queries/Steps/TailStep.cs
585
C#
using ARMeilleure.Memory; using ARMeilleure.State; using ARMeilleure.Translation; using System; using System.Runtime.InteropServices; using System.Threading; namespace ARMeilleure.Instructions { static class NativeInterface { private const int ErgSizeLog2 = 4; private class ThreadContext { public State.ExecutionContext Context { get; } public IMemoryManager Memory { get; } public Translator Translator { get; } public ulong ExclusiveAddress { get; set; } public ulong ExclusiveValueLow { get; set; } public ulong ExclusiveValueHigh { get; set; } public ThreadContext(State.ExecutionContext context, IMemoryManager memory, Translator translator) { Context = context; Memory = memory; Translator = translator; ExclusiveAddress = ulong.MaxValue; } } [ThreadStatic] private static ThreadContext _context; public static void RegisterThread(State.ExecutionContext context, IMemoryManager memory, Translator translator) { _context = new ThreadContext(context, memory, translator); } public static void UnregisterThread() { _context = null; } public static void Break(ulong address, int imm) { Statistics.PauseTimer(); GetContext().OnBreak(address, imm); Statistics.ResumeTimer(); } public static void SupervisorCall(ulong address, int imm) { Statistics.PauseTimer(); GetContext().OnSupervisorCall(address, imm); Statistics.ResumeTimer(); } public static void Undefined(ulong address, int opCode) { Statistics.PauseTimer(); GetContext().OnUndefined(address, opCode); Statistics.ResumeTimer(); } #region "System registers" public static ulong GetCtrEl0() { return (ulong)GetContext().CtrEl0; } public static ulong GetDczidEl0() { return (ulong)GetContext().DczidEl0; } public static ulong GetFpcr() { return (ulong)GetContext().Fpcr; } public static ulong GetFpsr() { return (ulong)GetContext().Fpsr; } public static uint GetFpscr() { var context = GetContext(); uint result = (uint)(context.Fpsr & FPSR.A32Mask) | (uint)(context.Fpcr & FPCR.A32Mask); result |= context.GetFPstateFlag(FPState.NFlag) ? (1u << 31) : 0; result |= context.GetFPstateFlag(FPState.ZFlag) ? (1u << 30) : 0; result |= context.GetFPstateFlag(FPState.CFlag) ? (1u << 29) : 0; result |= context.GetFPstateFlag(FPState.VFlag) ? (1u << 28) : 0; return result; } public static ulong GetTpidrEl0() { return (ulong)GetContext().TpidrEl0; } public static uint GetTpidrEl032() { return (uint)GetContext().TpidrEl0; } public static ulong GetTpidr() { return (ulong)GetContext().Tpidr; } public static uint GetTpidr32() { return (uint)GetContext().Tpidr; } public static ulong GetCntfrqEl0() { return GetContext().CntfrqEl0; } public static ulong GetCntpctEl0() { return GetContext().CntpctEl0; } public static ulong GetCntvctEl0() { return GetContext().CntvctEl0; } public static void SetFpcr(ulong value) { GetContext().Fpcr = (FPCR)value; } public static void SetFpsr(ulong value) { GetContext().Fpsr = (FPSR)value; } public static void SetFpscr(uint value) { var context = GetContext(); context.SetFPstateFlag(FPState.NFlag, (value & (1u << 31)) != 0); context.SetFPstateFlag(FPState.ZFlag, (value & (1u << 30)) != 0); context.SetFPstateFlag(FPState.CFlag, (value & (1u << 29)) != 0); context.SetFPstateFlag(FPState.VFlag, (value & (1u << 28)) != 0); context.Fpsr = FPSR.A32Mask & (FPSR)value; context.Fpcr = FPCR.A32Mask & (FPCR)value; } public static void SetTpidrEl0(ulong value) { GetContext().TpidrEl0 = (long)value; } public static void SetTpidrEl032(uint value) { GetContext().TpidrEl0 = (long)value; } #endregion #region "Read" public static byte ReadByte(ulong address) { return GetMemoryManager().Read<byte>(address); } public static ushort ReadUInt16(ulong address) { return GetMemoryManager().Read<ushort>(address); } public static uint ReadUInt32(ulong address) { return GetMemoryManager().Read<uint>(address); } public static ulong ReadUInt64(ulong address) { return GetMemoryManager().Read<ulong>(address); } public static V128 ReadVector128(ulong address) { return GetMemoryManager().Read<V128>(address); } #endregion #region "Read exclusive" public static byte ReadByteExclusive(ulong address) { byte value = _context.Memory.Read<byte>(address); _context.ExclusiveAddress = GetMaskedExclusiveAddress(address); _context.ExclusiveValueLow = value; _context.ExclusiveValueHigh = 0; return value; } public static ushort ReadUInt16Exclusive(ulong address) { ushort value = _context.Memory.Read<ushort>(address); _context.ExclusiveAddress = GetMaskedExclusiveAddress(address); _context.ExclusiveValueLow = value; _context.ExclusiveValueHigh = 0; return value; } public static uint ReadUInt32Exclusive(ulong address) { uint value = _context.Memory.Read<uint>(address); _context.ExclusiveAddress = GetMaskedExclusiveAddress(address); _context.ExclusiveValueLow = value; _context.ExclusiveValueHigh = 0; return value; } public static ulong ReadUInt64Exclusive(ulong address) { ulong value = _context.Memory.Read<ulong>(address); _context.ExclusiveAddress = GetMaskedExclusiveAddress(address); _context.ExclusiveValueLow = value; _context.ExclusiveValueHigh = 0; return value; } public static V128 ReadVector128Exclusive(ulong address) { V128 value = MemoryManagerPal.AtomicLoad128(ref _context.Memory.GetRef<V128>(address)); _context.ExclusiveAddress = GetMaskedExclusiveAddress(address); _context.ExclusiveValueLow = value.Extract<ulong>(0); _context.ExclusiveValueHigh = value.Extract<ulong>(1); return value; } #endregion #region "Write" public static void WriteByte(ulong address, byte value) { GetMemoryManager().Write(address, value); } public static void WriteUInt16(ulong address, ushort value) { GetMemoryManager().Write(address, value); } public static void WriteUInt32(ulong address, uint value) { GetMemoryManager().Write(address, value); } public static void WriteUInt64(ulong address, ulong value) { GetMemoryManager().Write(address, value); } public static void WriteVector128(ulong address, V128 value) { GetMemoryManager().Write(address, value); } #endregion #region "Write exclusive" public static int WriteByteExclusive(ulong address, byte value) { bool success = _context.ExclusiveAddress == GetMaskedExclusiveAddress(address); if (success) { ref int valueRef = ref _context.Memory.GetRefNoChecks<int>(address); int currentValue = valueRef; byte expected = (byte)_context.ExclusiveValueLow; int expected32 = (currentValue & ~byte.MaxValue) | expected; int desired32 = (currentValue & ~byte.MaxValue) | value; success = Interlocked.CompareExchange(ref valueRef, desired32, expected32) == expected32; if (success) { ClearExclusive(); } } return success ? 0 : 1; } public static int WriteUInt16Exclusive(ulong address, ushort value) { bool success = _context.ExclusiveAddress == GetMaskedExclusiveAddress(address); if (success) { ref int valueRef = ref _context.Memory.GetRefNoChecks<int>(address); int currentValue = valueRef; ushort expected = (ushort)_context.ExclusiveValueLow; int expected32 = (currentValue & ~ushort.MaxValue) | expected; int desired32 = (currentValue & ~ushort.MaxValue) | value; success = Interlocked.CompareExchange(ref valueRef, desired32, expected32) == expected32; if (success) { ClearExclusive(); } } return success ? 0 : 1; } public static int WriteUInt32Exclusive(ulong address, uint value) { bool success = _context.ExclusiveAddress == GetMaskedExclusiveAddress(address); if (success) { ref int valueRef = ref _context.Memory.GetRef<int>(address); success = Interlocked.CompareExchange(ref valueRef, (int)value, (int)_context.ExclusiveValueLow) == (int)_context.ExclusiveValueLow; if (success) { ClearExclusive(); } } return success ? 0 : 1; } public static int WriteUInt64Exclusive(ulong address, ulong value) { bool success = _context.ExclusiveAddress == GetMaskedExclusiveAddress(address); if (success) { ref long valueRef = ref _context.Memory.GetRef<long>(address); success = Interlocked.CompareExchange(ref valueRef, (long)value, (long)_context.ExclusiveValueLow) == (long)_context.ExclusiveValueLow; if (success) { ClearExclusive(); } } return success ? 0 : 1; } public static int WriteVector128Exclusive(ulong address, V128 value) { bool success = _context.ExclusiveAddress == GetMaskedExclusiveAddress(address); if (success) { V128 expected = new V128(_context.ExclusiveValueLow, _context.ExclusiveValueHigh); ref V128 location = ref _context.Memory.GetRef<V128>(address); success = MemoryManagerPal.CompareAndSwap128(ref location, expected, value) == expected; if (success) { ClearExclusive(); } } return success ? 0 : 1; } #endregion private static ulong GetMaskedExclusiveAddress(ulong address) { return address & ~((4UL << ErgSizeLog2) - 1); } public static ulong GetFunctionAddress(ulong address) { TranslatedFunction function = _context.Translator.GetOrTranslate(address, GetContext().ExecutionMode); return (ulong)function.GetPointer().ToInt64(); } public static ulong GetIndirectFunctionAddress(ulong address, ulong entryAddress) { TranslatedFunction function = _context.Translator.GetOrTranslate(address, GetContext().ExecutionMode); ulong ptr = (ulong)function.GetPointer().ToInt64(); if (function.HighCq) { // Rewrite the host function address in the table to point to the highCq function. Marshal.WriteInt64((IntPtr)entryAddress, 8, (long)ptr); } return ptr; } public static void ClearExclusive() { _context.ExclusiveAddress = ulong.MaxValue; } public static bool CheckSynchronization() { Statistics.PauseTimer(); var context = GetContext(); context.CheckInterrupt(); Statistics.ResumeTimer(); return context.Running; } public static State.ExecutionContext GetContext() { return _context.Context; } public static IMemoryManager GetMemoryManager() { return _context.Memory; } } }
29.346578
151
0.562284
[ "MIT" ]
Zeroksas/Ryujinx
ARMeilleure/Instructions/NativeInterface.cs
13,294
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// Prompt information related to a bot flow turn. /// </summary> [DataContract] public partial class TextBotModeOutputPrompts : IEquatable<TextBotModeOutputPrompts> { /// <summary> /// Initializes a new instance of the <see cref="TextBotModeOutputPrompts" /> class. /// </summary> [JsonConstructorAttribute] protected TextBotModeOutputPrompts() { } /// <summary> /// Initializes a new instance of the <see cref="TextBotModeOutputPrompts" /> class. /// </summary> /// <param name="Segments">The list of prompt segments. (required).</param> public TextBotModeOutputPrompts(List<TextBotPromptSegment> Segments = null) { this.Segments = Segments; } /// <summary> /// The list of prompt segments. /// </summary> /// <value>The list of prompt segments.</value> [DataMember(Name="segments", EmitDefaultValue=false)] public List<TextBotPromptSegment> Segments { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class TextBotModeOutputPrompts {\n"); sb.Append(" Segments: ").Append(Segments).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, Formatting = Formatting.Indented }); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as TextBotModeOutputPrompts); } /// <summary> /// Returns true if TextBotModeOutputPrompts instances are equal /// </summary> /// <param name="other">Instance of TextBotModeOutputPrompts to be compared</param> /// <returns>Boolean</returns> public bool Equals(TextBotModeOutputPrompts other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Segments == other.Segments || this.Segments != null && this.Segments.SequenceEqual(other.Segments) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Segments != null) hash = hash * 59 + this.Segments.GetHashCode(); return hash; } } } }
31.300752
92
0.54528
[ "MIT" ]
F-V-L/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/TextBotModeOutputPrompts.cs
4,163
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ShoppingBagShow : MonoBehaviour { public GameObject Panel; int counter; public void showhidePanel() { counter++; if (counter % 2 == 1) { Panel.gameObject.SetActive(true); } else { Panel.gameObject.SetActive(false); } } }
18.73913
46
0.596288
[ "MIT" ]
jaxee/perfit
src/Assets/Scripts/UI_Scripts/oldscripts/ShoppingBagShow.cs
433
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net.Http.Headers; using System.Web.Http.Description; using FileUploadAPI.Areas.HelpPage.ModelDescriptions; namespace FileUploadAPI.Areas.HelpPage.Models { /// <summary> /// The model that represents an API displayed on the help page. /// </summary> public class HelpPageApiModel { /// <summary> /// Initializes a new instance of the <see cref="HelpPageApiModel"/> class. /// </summary> public HelpPageApiModel() { UriParameters = new Collection<ParameterDescription>(); SampleRequests = new Dictionary<MediaTypeHeaderValue, object>(); SampleResponses = new Dictionary<MediaTypeHeaderValue, object>(); ErrorMessages = new Collection<string>(); } /// <summary> /// Gets or sets the <see cref="ApiDescription"/> that describes the API. /// </summary> public ApiDescription ApiDescription { get; set; } /// <summary> /// Gets or sets the <see cref="ParameterDescription"/> collection that describes the URI parameters for the API. /// </summary> public Collection<ParameterDescription> UriParameters { get; private set; } /// <summary> /// Gets or sets the documentation for the request. /// </summary> public string RequestDocumentation { get; set; } /// <summary> /// Gets or sets the <see cref="ModelDescription"/> that describes the request body. /// </summary> public ModelDescription RequestModelDescription { get; set; } /// <summary> /// Gets the request body parameter descriptions. /// </summary> public IList<ParameterDescription> RequestBodyParameters { get { return GetParameterDescriptions(RequestModelDescription); } } /// <summary> /// Gets or sets the <see cref="ModelDescription"/> that describes the resource. /// </summary> public ModelDescription ResourceDescription { get; set; } /// <summary> /// Gets the resource property descriptions. /// </summary> public IList<ParameterDescription> ResourceProperties { get { return GetParameterDescriptions(ResourceDescription); } } /// <summary> /// Gets the sample requests associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleRequests { get; private set; } /// <summary> /// Gets the sample responses associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleResponses { get; private set; } /// <summary> /// Gets the error messages associated with this model. /// </summary> public Collection<string> ErrorMessages { get; private set; } private static IList<ParameterDescription> GetParameterDescriptions(ModelDescription modelDescription) { ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription; if (complexTypeModelDescription != null) { return complexTypeModelDescription.Properties; } CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription; if (collectionModelDescription != null) { complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription; if (complexTypeModelDescription != null) { return complexTypeModelDescription.Properties; } } return null; } } }
36.62963
123
0.615268
[ "MIT" ]
prachibhandari15/sample-dot-net-web-api
FileUploadAPI/Areas/HelpPage/Models/HelpPageApiModel.cs
3,956
C#
namespace VISCA.NET.Enums { public enum ViscaDeltaState : byte { Reset = 0x00, Up = 0x02, Down = 0x03 } }
12.777778
35
0.643478
[ "MIT" ]
parzivail/VISCA.NET
VISCA.NET/Enums/ViscaDeltaState.cs
117
C#
// // DO NOT MODIFY. THIS IS AUTOMATICALLY GENERATED FILE. // #nullable enable #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. using System; using System.Collections.Generic; namespace CefNet.DevTools.Protocol.Emulation { public sealed class SetEmitTouchEventsForMouseRequest { /// <summary> /// Whether touch emulation based on mouse input should be enabled. /// </summary> public bool Enabled { get; set; } /// <summary> /// Touch/gesture events configuration. Default: current platform. /// </summary> public CefNet.DevTools.Protocol.Emulation.SetEmitTouchEventsForMouseRequestConfiguration? Configuration { get; set; } } }
33.25
140
0.703008
[ "MIT" ]
CefNet/CefNet.DevTools.Protocol
CefNet.DevTools.Protocol/Generated/Emulation/SetEmitTouchEventsForMouseRequest.g.cs
798
C#
namespace OkonkwoOandaV20.TradeLibrary.Transaction { /// <summary> /// A MarginCallExitTransaction is created when an Account leaves the margin call state /// </summary> public class MarginCallExitTransaction : Transaction { } }
24.8
90
0.725806
[ "MIT" ]
Petter-Hansson/OandaV20.2
OkonkwoOandaV20/OkonkwoOandaV20/TradeLibrary/Transaction/MarginCallExitTransaction.cs
250
C#
using AutoMapper; using FakeXiecheng.API.Dtos; using FakeXiecheng.API.Models; using FakeXiecheng.API.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FakeXiecheng.API.Controllers { [Route("api/touristRoutes/{touristRouteId}/pictures")] [ApiController] public class TouristRoutePictureController : ControllerBase { private ITouristRouteRepository _touristRouteRepository; private IMapper _mapper; public TouristRoutePictureController(ITouristRouteRepository touristRouteRepository, IMapper mapper) { _touristRouteRepository = touristRouteRepository ?? throw new ArgumentNullException(nameof(touristRouteRepository)); _mapper=mapper ?? throw new ArgumentNullException(nameof(mapper)); } [HttpGet] public async Task<IActionResult> GetPictureListForTouristRoute(Guid touristRouteId) { if(!(await _touristRouteRepository.TouristRouteExistsAsync(touristRouteId))) { return NotFound("旅游路线不存在"); } var picturesFromRepo = await _touristRouteRepository.GetPicturesByTouristRouteIdAsync(touristRouteId); if (picturesFromRepo == null || picturesFromRepo.Count()<=0) { return NotFound("照片不存在"); } return Ok(_mapper.Map<IEnumerable<TouristRoutePictureDto>>(picturesFromRepo)); } [HttpGet("{pictureId}",Name = "GetPicture")] public async Task<IActionResult> GetPicture(Guid touristRouteId,int pictureId) { if (!(await _touristRouteRepository.TouristRouteExistsAsync(touristRouteId))) { return NotFound("旅游路线不存在"); } var picturesFromRepo = await _touristRouteRepository.GetPictureAsync(pictureId); if(picturesFromRepo==null) { return NotFound("相片不存在!"); } return Ok(_mapper.Map<TouristRoutePictureDto>(picturesFromRepo)); } [HttpPost] public async Task<IActionResult> CreateTouristRoutePicture([FromRoute]Guid touristRouteId, [FromBody]TouristRoutePictureForCreationDto touristRoutePictureForCreationDto) { if (!(await _touristRouteRepository.TouristRouteExistsAsync(touristRouteId))) { return NotFound("旅游路线不存在"); } var pictureModel = _mapper.Map<TouristRoutePicture>(touristRoutePictureForCreationDto); _touristRouteRepository.AddTouristRoutePicture(touristRouteId, pictureModel); await _touristRouteRepository.SaveAsync(); var pictureToReturn = _mapper.Map<TouristRoutePictureDto>(pictureModel); return CreatedAtRoute( "GetPicture", new { touristRouteId = pictureModel.TouristRouteId, pictureId = pictureModel.Id }, pictureToReturn ); } [HttpDelete("{pictureId}")] public async Task<IActionResult> DeletePicture([FromRoute]Guid touristRouteId,[FromRoute]int pictureId) { if(!(await _touristRouteRepository.TouristRouteExistsAsync(touristRouteId))) { return NotFound("旅游路线不存在"); } var picture =await _touristRouteRepository.GetPictureAsync(pictureId); _touristRouteRepository.DeleteTouristRoutePicture(picture); await _touristRouteRepository.SaveAsync(); return NoContent(); } } }
39.547368
114
0.643066
[ "BSD-3-Clause" ]
LXQGH/.NetCore
FakeXiecheng.API/FakeXiecheng.API/Controllers/TouristRoutePictureController.cs
3,837
C#
using Xamarin.Forms; namespace ShallEmulation.Views { public partial class ViewA : ContentPage { public ViewA() { InitializeComponent(); } } }
14.846154
44
0.564767
[ "MIT" ]
runceel/Prism.Forms.ShellLike
ShallEmulation/ShallEmulation/Views/ViewA.xaml.cs
195
C#
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Screens.Menu; using osu.Game.Users; namespace osu.Game.Tests.Visual.Menus { public class TestSceneDisclaimer : ScreenTestScene { [BackgroundDependencyLoader] private void load() { AddStep("load disclaimer", () => LoadScreen(new Disclaimer())); AddStep("toggle support", () => { API.LocalUser.Value = new User { Username = API.LocalUser.Value.Username, Id = API.LocalUser.Value.Id + 1, IsSupporter = !API.LocalUser.Value.IsSupporter, }; }); } } }
30.103448
79
0.547537
[ "MIT" ]
AaqibAhamed/osu
osu.Game.Tests/Visual/Menus/TestSceneDisclaimer.cs
845
C#
using CuriositySoftware.PageObjects.Entities; using OpenQA.Selenium; using System; using System.Collections.Generic; namespace CuriositySoftware.PageObjects.ElementScanner { public class ElementExtractor { public ElementExtractor() { } public static Boolean updateParameter(PageObjectParameterEntity parameter, IWebElement element, IWebDriver driver) { // If the identifer no longer works -> We need to update it in the framework // Also need to assign a confidence value which gets tracked upwards String newIdentifier = null; if (parameter.paramType.Equals(VipAutomationSelectorEnum.ClassName)) { newIdentifier = element.GetAttribute("class"); } else if (parameter.paramType.Equals(VipAutomationSelectorEnum.Id)) { newIdentifier = element.GetAttribute("id"); } else if (parameter.paramType.Equals(VipAutomationSelectorEnum.LinkText)) { newIdentifier = element.Text; } else if (parameter.paramType.Equals(VipAutomationSelectorEnum.Name)) { newIdentifier = element.GetAttribute("name"); } else if (parameter.paramType.Equals(VipAutomationSelectorEnum.TagName)) { newIdentifier = element.TagName; } else if (parameter.paramType.Equals(VipAutomationSelectorEnum.XPath)) { newIdentifier = GetElementXPath(element, driver); } else { Console.WriteLine("Unsupported identifier reusing old value - " + parameter.paramType); newIdentifier = parameter.paramValue; } if (newIdentifier != null && newIdentifier.Length > 0) { parameter.paramValue = (newIdentifier); By identifer = GetElementIdentifierForParameter(parameter); if (identifer == null) { parameter.confidence = (0); return true; } try { List<IWebElement> elem = new List<IWebElement>(driver.FindElements(identifer)); if (elem.Count == 0) { parameter.confidence = (0); } else { parameter.confidence = (1.0f / elem.Count); } } catch (Exception e) { parameter.confidence = (0); } return true; } else { parameter.confidence = (0); return false; } } public static By GetElementIdentifierForParameter(PageObjectParameterEntity parameterEntity) { if (parameterEntity.paramType.Equals(VipAutomationSelectorEnum.ClassName)) { return By.ClassName(parameterEntity.paramValue); } else if (parameterEntity.paramType.Equals(VipAutomationSelectorEnum.CssSelector)) { return By.CssSelector(parameterEntity.paramValue); } else if (parameterEntity.paramType.Equals(VipAutomationSelectorEnum.Id)) { return By.Id(parameterEntity.paramValue); } else if (parameterEntity.paramType.Equals(VipAutomationSelectorEnum.LinkText)) { return By.LinkText(parameterEntity.paramValue); } else if (parameterEntity.paramType.Equals(VipAutomationSelectorEnum.Name)) { return By.Name(parameterEntity.paramValue); } else if (parameterEntity.paramType.Equals(VipAutomationSelectorEnum.PartialLinkText)) { return By.PartialLinkText(parameterEntity.paramValue); } else if (parameterEntity.paramType.Equals(VipAutomationSelectorEnum.TagName)) { return By.TagName(parameterEntity.paramValue); } else if (parameterEntity.paramType.Equals(VipAutomationSelectorEnum.XPath)) { return By.XPath(parameterEntity.paramValue); } else { return null; } } public static String GetElementXPath(IWebElement element, IWebDriver driver) { return (String)((IJavaScriptExecutor)driver).ExecuteScript( "getXPath=function(node)" + "{" + "if (node.id !== '')" + "{" + "return '//' + node.tagName.toLowerCase() + '[@id=\"' + node.id + '\"]'" + "}" + "if (node === document.body)" + "{" + "return node.tagName.toLowerCase()" + "}" + "var nodeCount = 0;" + "var childNodes = node.parentNode.childNodes;" + "for (var i=0; i<childNodes.length; i++)" + "{" + "var currentNode = childNodes[i];" + "if (currentNode === node)" + "{" + "return getXPath(node.parentNode) + '/' + node.tagName.toLowerCase() + '[' + (nodeCount+1) + ']'" + "}" + "if (currentNode.nodeType === 1 && " + "currentNode.tagName.toLowerCase() === node.tagName.toLowerCase())" + "{" + "nodeCount++" + "}" + "}" + "};" + "return getXPath(arguments[0]);", element); } } }
39.58042
127
0.525265
[ "MIT" ]
CuriositySoftwareIreland/TestModeller-CSharp
PageObjects/elementscanner/ElementExtractor.cs
5,660
C#
using System; using NUnit.Framework; namespace Tokens.Transformers { [TestFixture] public class ToDateTimeTransformerTests { private ToDateTimeTransformer @operator; [SetUp] public void SetUp() { @operator = new ToDateTimeTransformer(); } [Test] public void TestParseDate() { var result = @operator.CanTransform("2014-01-01", new [] { "yyyy-MM-dd" }, out var t); var dateTime = (DateTime) t; Assert.IsTrue(result); Assert.AreEqual(new DateTime(2014, 1, 1), dateTime); Assert.AreEqual(DateTimeKind.Unspecified, dateTime.Kind); } [Test] public void TestParseDateWithFormat() { var result = @operator.CanTransform("2 Mar 2012", new [] { "d MMM yyyy" }, out var t); var dateTime = (DateTime) t; Assert.IsTrue(result); Assert.AreEqual(new DateTime(2012, 3, 2), dateTime); } [Test] public void TestParseDateWithNoFormat() { var result = @operator.CanTransform("2012-05-06", null, out var t); var dateTime = (DateTime) t; Assert.IsTrue(result); Assert.AreEqual(new DateTime(2012, 5, 6), dateTime); } [Test] public void TestParseDateWithInvalidFormat() { var result = @operator.CanTransform("2012-05-06", new [] { "dd MMM yy" }, out var t); Assert.IsFalse(result); Assert.AreEqual("2012-05-06", t); } [Test] public void TestParseDateWithFormatList() { var result = @operator.CanTransform("2012-05-06", new [] { "dd MMM yy", "yyyy-MM-dd" }, out var t); var dateTime = (DateTime) t; Assert.IsTrue(result); Assert.AreEqual(new DateTime(2012, 5 ,6), dateTime); } [Test] public void TestParseDateWithEmptyValue() { var result = @operator.CanTransform(string.Empty, null, out var t); Assert.IsFalse(result); Assert.AreEqual(string.Empty, t); } [Test] public void TestParseDateWithNullValue() { var result = @operator.CanTransform(null, null, out var t); Assert.IsFalse(result); Assert.AreEqual(null, t); } [Test] public void TestParseDateWithUnixNewLine() { var result = @operator.CanTransform("2012-05-06\nHello", null, out var t); var dateTime = (DateTime) t; Assert.IsTrue(result); Assert.AreEqual(new DateTime(2012, 5, 6), t); } [Test] public void TestParseDateWithWindowsNewLine() { var result = @operator.CanTransform("2012-05-06\r\nHello", null, out var t); Assert.IsTrue(result); Assert.AreEqual(new DateTime(2012, 5, 6), t); } [Test] public void TestParseDateWithDayOrdinalAtStart() { var result = @operator.CanTransform("01st August 2001", new [] { "dd MMMM yyyy" }, out var t); var dateTime = (DateTime) t; Assert.IsTrue(result); Assert.AreEqual(new DateTime(2001, 8 , 1), dateTime); } [Test] public void TestParseDateWithDayOrdinalInMiddle() { var result = @operator.CanTransform("August 2nd 2001", new [] { "MMMM d yyyy" }, out var t); var dateTime = (DateTime) t; Assert.IsTrue(result); Assert.AreEqual(new DateTime(2001, 8 , 2), dateTime); } [Test] public void TestParseDateWithSpanishFullMonth() { var result = @operator.CanTransform("Agosto 2nd 2001", new [] { "MMMM d yyyy" }, out var t); var dateTime = (DateTime) t; Assert.IsTrue(result); Assert.AreEqual(new DateTime(2001, 8 , 2), dateTime); } [Test] public void TestParseDateWithSpanishMonthAbbreviation() { var result = @operator.CanTransform("16-abr-1997", new [] { "dd-MMM-yyyy" }, out var t); var dateTime = (DateTime) t; Assert.IsTrue(result); Assert.AreEqual(new DateTime(1997, 4 , 16), dateTime); } } }
30.22069
111
0.542903
[ "MIT" ]
AJH16/tokenizer
Tokenizer.Tests/Transformers/ToDateTimeTransformerTests.cs
4,384
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the auditmanager-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.AuditManager.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AuditManager.Model.Internal.MarshallTransformations { /// <summary> /// UpdateAssessmentStatus Request Marshaller /// </summary> public class UpdateAssessmentStatusRequestMarshaller : IMarshaller<IRequest, UpdateAssessmentStatusRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateAssessmentStatusRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateAssessmentStatusRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.AuditManager"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-07-25"; request.HttpMethod = "PUT"; if (!publicRequest.IsSetAssessmentId()) throw new AmazonAuditManagerException("Request object does not have required field AssessmentId set"); request.AddPathResource("{assessmentId}", StringUtils.FromString(publicRequest.AssessmentId)); request.ResourcePath = "/assessments/{assessmentId}/status"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetStatus()) { context.Writer.WritePropertyName("status"); context.Writer.Write(publicRequest.Status); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static UpdateAssessmentStatusRequestMarshaller _instance = new UpdateAssessmentStatusRequestMarshaller(); internal static UpdateAssessmentStatusRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateAssessmentStatusRequestMarshaller Instance { get { return _instance; } } } }
37.113208
159
0.644382
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/AuditManager/Generated/Model/Internal/MarshallTransformations/UpdateAssessmentStatusRequestMarshaller.cs
3,934
C#
using BenchmarkDotNet.Attributes; using System.Linq; using System.Collections.Generic; namespace MakingDotNETApplicationsFaster.Runners { [Config(typeof(CoreConfig))] public class SwitchVsIfOperatorsForIntRunner { [Params(1, 3, 5, 10, 15, 20)] public int Input; private readonly Dictionary<int, int> _keyValues; public SwitchVsIfOperatorsForIntRunner() { var values = Enumerable.Range(1, 51).ToList(); _keyValues = new Dictionary<int, int>(); for (var index = 0; index < values.Count; ++index) { if (index == values.Count - 1) { _keyValues.Add(values[index], 0); break; } _keyValues.Add(values[index], values[index]); } } [Benchmark] public int IfWithLongCycleOrOperator() { int result = 0; if (Input == 1 | Input == 2 | Input == 3 | Input == 4 | Input == 5 | Input == 6 | Input == 7 | Input == 8 | Input == 9 | Input == 10 | Input == 11 | Input == 12 | Input == 13 | Input == 14 | Input == 15 | Input == 16 | Input == 17 | Input == 18 | Input == 19 | Input == 20) { result = Input; } return result; } [Benchmark] public int IfWithShortCycleOrOperator() { int result = 0; if (Input == 1 || Input == 2 || Input == 3 || Input == 4 || Input == 5 || Input == 6 || Input == 7 || Input == 8 || Input == 9 || Input == 10 || Input == 11 || Input == 12 || Input == 13 || Input == 14 || Input == 15 || Input == 16 || Input == 17 || Input == 18 || Input == 19 || Input == 20) { result = Input; } return result; } [Benchmark] public int IfElseOperator() { int result; if (Input == 1) { result = Input; } else if (Input == 2) { result = Input; } else if (Input == 3) { result = Input; } else if (Input == 4) { result = Input; } else if (Input == 5) { result = Input; } else if (Input == 6) { result = Input; } else if (Input == 7) { result = Input; } else if (Input == 8) { result = Input; } else if (Input == 9) { result = Input; } else if (Input == 10) { result = Input; } else if (Input == 11) { result = Input; } else if (Input == 12) { result = Input; } else if (Input == 13) { result = Input; } else if (Input == 14) { result = Input; } else if (Input == 15) { result = Input; } else if (Input == 16) { result = Input; } else if (Input == 17) { result = Input; } else if (Input == 18) { result = Input; } else if (Input == 19) { result = Input; } else if (Input == 20) { result = Input; } else { result = 0; } return result; } [Benchmark] public int SwitchOperator() { int result; switch (Input) { case 1: result = Input; break; case 2: result = Input; break; case 3: result = Input; break; case 4: result = Input; break; case 5: result = Input; break; case 6: result = Input; break; case 7: result = Input; break; case 8: result = Input; break; case 9: result = Input; break; case 10: result = Input; break; case 11: result = Input; break; case 12: result = Input; break; case 13: result = Input; break; case 14: result = Input; break; case 15: result = Input; break; case 16: result = Input; break; case 17: result = Input; break; case 18: result = Input; break; case 19: result = Input; break; case 20: result = Input; break; default: result = 0; break; } return result; } [Benchmark] public int TryGetValueFromDictionary() { int result; return _keyValues.TryGetValue(Input, out result) ? result : 0; } } }
24.541818
74
0.301378
[ "MIT" ]
Ky7m/DemoCode
MakingDotNETApplicationsFaster/MakingDotNETApplicationsFaster/Runners/SwitchVsIfOperatorForIntRunner.cs
6,751
C#
 using System; namespace Sort3Numbers { class Program { static void Main() { int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); int c = int.Parse(Console.ReadLine()); if (a >= b) { if (b >= c) { Console.WriteLine(a + " " + b + " " + c); } else if (c > b && c <= a) { Console.WriteLine(a + " " + c + " " + b); } else { Console.WriteLine(c + " " + a + " " + b); } } else if (b > a) { if (a >= c) { Console.WriteLine(b + " " + a + " " + c); } else if (c > a && c < b) { Console.WriteLine(b + " " + c + " " + a); } else { Console.WriteLine(c + " " + b + " " + a); } } } } }
25.555556
61
0.261739
[ "MIT" ]
SimonaArsova/TelerikAcademy
C# Programming/C#Fundamentals/ConditionalStatements/Sort3Numbers/Program.cs
1,152
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.460/blob/master/LICENSE * */ #endregion using ComponentFactory.Krypton.Toolkit; using System; using System.ComponentModel; namespace ExtendedControls.ExtendedToolkit.Controls.Navigator.Controls { #region ... KryptonNavigatorButton ... [System.Drawing.ToolboxBitmap(typeof(System.Windows.Forms.Button)), ToolboxItem(false)] public class KryptonNavigatorButton : KryptonButton { private static IPalette _palette; private static PaletteRedirect _paletteRedirect; public KryptonNavigatorButton() { // add Palette Handler if (_palette != null) _palette.PalettePaint += new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint); KryptonManager.GlobalPaletteChanged += new EventHandler(GlobalPaletteChanged); _palette = KryptonManager.CurrentGlobalPalette; _paletteRedirect = new PaletteRedirect(_palette); this.AutoSize = false; this.Values.ExtraText = null; this.Values.Text = null; this.Values.Image = null; this.Values.ImageStates.ImageCheckedNormal = null; this.Values.ImageStates.ImageCheckedPressed = null; this.Values.ImageStates.ImageCheckedTracking = null; this.ButtonStyle = ButtonStyle.Standalone; this.StateNormal.Back.Color1 = _palette.ColorTable.ToolStripContentPanelGradientEnd; this.StateNormal.Back.Color2 = _palette.ColorTable.ToolStripContentPanelGradientEnd; this.StateNormal.Back.ColorStyle = PaletteColorStyle.Solid; this.StateNormal.Border.Color1 = _palette.ColorTable.ToolStripBorder; this.StateCommon.Border.Rounding = 0; this.Size = new System.Drawing.Size(23, 23); this.StateCommon.Content.ShortText.Color1 = _palette.ColorTable.StatusStripText; this.StateCommon.Content.ShortText.TextH = PaletteRelativeAlign.Center; this.StateCommon.Content.ShortText.TextV = PaletteRelativeAlign.Center; this.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Marlett", 11.00f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (byte)2); } #region ...Krypton... private void GlobalPaletteChanged(object sender, EventArgs e) { if (_palette != null) _palette.PalettePaint -= new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint); _palette = KryptonManager.CurrentGlobalPalette; _paletteRedirect.Target = _palette; if (_palette != null) { _palette.PalettePaint += new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint); //repaint with new values this.StateNormal.Back.Color1 = _palette.ColorTable.ToolStripContentPanelGradientEnd; this.StateNormal.Back.Color2 = _palette.ColorTable.ToolStripContentPanelGradientEnd; this.StateNormal.Border.Color1 = _palette.ColorTable.ToolStripBorder; this.StateCommon.Content.ShortText.Color1 = _palette.ColorTable.StatusStripText; } Invalidate(); } private void OnPalettePaint(object sender, PaletteLayoutEventArgs e) { Invalidate(); } protected override void Dispose(bool disposing) { if (disposing) { if (_palette != null) { _palette.PalettePaint -= new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint); _palette = null; } KryptonManager.GlobalPaletteChanged -= new EventHandler(OnGlobalPaletteChanged); } base.Dispose(disposing); } #endregion #endregion } }
38.065421
175
0.652345
[ "BSD-3-Clause" ]
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.460
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/ExtendedToolkit/Controls/Navigator/Controls/KryptonNavigatorButton.cs
4,075
C#
using MediatR; using SmartNote.Application.Configuration.Commands; namespace SmartNote.Application.Notes.Commands { public class PublishNoteCommand : ICommand<Unit> { public Guid NoteId { get; } public PublishNoteCommand(Guid noteId) { NoteId = noteId; } } }
21.133333
52
0.649842
[ "MIT" ]
linwenda/FunZone
src/SmartNote.Application/Notes/Commands/PublishNoteCommand.cs
319
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XBC.ViewModel { public class ResponseResult { public ResponseResult() { Success = true; } public bool Success { get; set; } public string ErrorMessage { get; set; } public object Entity { get; set; } } }
19.285714
48
0.614815
[ "MIT" ]
MRidoKurniawan/XBC
XBC/XBC.ViewModel/ResponseResult.cs
407
C#
using Microsoft.Graph; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Graph.Community { public class SiteUserRequest : BaseSharePointAPIRequest, ISiteUserRequest { public SiteUserRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base("SiteUser", requestUrl, client, options) { this.Headers.Add(new HeaderOption(SharePointAPIRequestConstants.Headers.AcceptHeaderName, SharePointAPIRequestConstants.Headers.AcceptHeaderValue)); this.Headers.Add(new HeaderOption(SharePointAPIRequestConstants.Headers.ODataVersionHeaderName, SharePointAPIRequestConstants.Headers.ODataVersionHeaderValue)); } public async Task<User> GetAsync() { return await this.GetAsync(CancellationToken.None); } public async Task<User> GetAsync(CancellationToken cancellationToken) { this.ContentType = "application/json"; var entity = await this.SendAsync<User>(null, cancellationToken).ConfigureAwait(false); return entity; } } }
32.878788
166
0.75576
[ "MIT" ]
microsoftgraph/msgraph-sdk-dotnet-contrib
src/Requests/SiteUsers/SiteUserRequest.cs
1,085
C#
using UnityEngine; using System.Collections; /// <summary> /// Example of control unit for drag and drop events handle /// </summary> public class DummyControlUnit : MonoBehaviour { void OnItemPlace(DragAndDropCell.DropDescriptor desc) { DummyControlUnit sourceSheet = desc.sourceCell.GetComponentInParent<DummyControlUnit>(); DummyControlUnit destinationSheet = desc.destinationCell.GetComponentInParent<DummyControlUnit>(); // If item dropped between different sheets if (destinationSheet != sourceSheet) { Debug.Log(desc.item.name + " is dropped from " + sourceSheet.name + " to " + destinationSheet.name); } } }
34.5
112
0.701449
[ "MIT" ]
irtezasyed007/CSC523-Game-Project
TheCircuitry/Assets/SimpleDragAndDrop/Scripts/DummyControlUnit.cs
692
C#
// ========================================================================== // JsonField.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== namespace Squidex.Domain.Apps.Core.Schemas { public sealed class JsonField : Field<JsonFieldProperties> { public JsonField(long id, string name, Partitioning partitioning) : base(id, name, partitioning, new JsonFieldProperties()) { } public JsonField(long id, string name, Partitioning partitioning, JsonFieldProperties properties) : base(id, name, partitioning, properties) { } public override T Accept<T>(IFieldVisitor<T> visitor) { return visitor.Visit(this); } } }
31.931034
105
0.469762
[ "MIT" ]
maooson/squidex
src/Squidex.Domain.Apps.Core.Model/Schemas/JsonField.cs
928
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Azure.Core; using Azure.Core.Pipeline; using Azure.Storage.Queues.Models; namespace Azure.Storage.Queues { internal partial class MessagesRestClient { private string url; private string version; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; /// <summary> Initializes a new instance of MessagesRestClient. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="url"> The URL of the service account, queue or message that is the targe of the desired operation. </param> /// <param name="version"> Specifies the version of the operation to use for this request. </param> /// <exception cref="ArgumentNullException"> <paramref name="url"/> or <paramref name="version"/> is null. </exception> public MessagesRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string url, string version = "2018-03-28") { if (url == null) { throw new ArgumentNullException(nameof(url)); } if (version == null) { throw new ArgumentNullException(nameof(version)); } this.url = url; this.version = version; _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; } internal HttpMessage CreateDequeueRequest(int? numberOfMessages, int? visibilitytimeout, int? timeout) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.AppendRaw(url, false); uri.AppendPath("/messages", false); if (numberOfMessages != null) { uri.AppendQuery("numofmessages", numberOfMessages.Value, true); } if (visibilitytimeout != null) { uri.AppendQuery("visibilitytimeout", visibilitytimeout.Value, true); } if (timeout != null) { uri.AppendQuery("timeout", timeout.Value, true); } request.Uri = uri; request.Headers.Add("x-ms-version", version); request.Headers.Add("Accept", "application/xml"); return message; } /// <summary> The Dequeue operation retrieves one or more messages from the front of the queue. </summary> /// <param name="numberOfMessages"> Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible messages are returned. By default, a single message is retrieved from the queue with this operation. </param> /// <param name="visibilitytimeout"> Optional. Specifies the new visibility timeout value, in seconds, relative to server time. The default value is 30 seconds. A specified value must be larger than or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value later than the expiry time. </param> /// <param name="timeout"> The The timeout parameter is expressed in seconds. For more information, see &lt;a href=&quot;https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations&gt;Setting Timeouts for Queue Service Operations.&lt;/a&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async Task<ResponseWithHeaders<IReadOnlyList<DequeuedMessageItem>, MessagesDequeueHeaders>> DequeueAsync(int? numberOfMessages = null, int? visibilitytimeout = null, int? timeout = null, CancellationToken cancellationToken = default) { using var message = CreateDequeueRequest(numberOfMessages, visibilitytimeout, timeout); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); var headers = new MessagesDequeueHeaders(message.Response); switch (message.Response.Status) { case 200: { IReadOnlyList<DequeuedMessageItem> value = default; var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace); if (document.Element("QueueMessagesList") is XElement queueMessagesListElement) { var array = new List<DequeuedMessageItem>(); foreach (var e in queueMessagesListElement.Elements("QueueMessage")) { array.Add(DequeuedMessageItem.DeserializeDequeuedMessageItem(e)); } value = array; } return ResponseWithHeaders.FromValue(value, headers, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> The Dequeue operation retrieves one or more messages from the front of the queue. </summary> /// <param name="numberOfMessages"> Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible messages are returned. By default, a single message is retrieved from the queue with this operation. </param> /// <param name="visibilitytimeout"> Optional. Specifies the new visibility timeout value, in seconds, relative to server time. The default value is 30 seconds. A specified value must be larger than or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value later than the expiry time. </param> /// <param name="timeout"> The The timeout parameter is expressed in seconds. For more information, see &lt;a href=&quot;https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations&gt;Setting Timeouts for Queue Service Operations.&lt;/a&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public ResponseWithHeaders<IReadOnlyList<DequeuedMessageItem>, MessagesDequeueHeaders> Dequeue(int? numberOfMessages = null, int? visibilitytimeout = null, int? timeout = null, CancellationToken cancellationToken = default) { using var message = CreateDequeueRequest(numberOfMessages, visibilitytimeout, timeout); _pipeline.Send(message, cancellationToken); var headers = new MessagesDequeueHeaders(message.Response); switch (message.Response.Status) { case 200: { IReadOnlyList<DequeuedMessageItem> value = default; var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace); if (document.Element("QueueMessagesList") is XElement queueMessagesListElement) { var array = new List<DequeuedMessageItem>(); foreach (var e in queueMessagesListElement.Elements("QueueMessage")) { array.Add(DequeuedMessageItem.DeserializeDequeuedMessageItem(e)); } value = array; } return ResponseWithHeaders.FromValue(value, headers, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateClearRequest(int? timeout) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.AppendRaw(url, false); uri.AppendPath("/messages", false); if (timeout != null) { uri.AppendQuery("timeout", timeout.Value, true); } request.Uri = uri; request.Headers.Add("x-ms-version", version); request.Headers.Add("Accept", "application/xml"); return message; } /// <summary> The Clear operation deletes all messages from the specified queue. </summary> /// <param name="timeout"> The The timeout parameter is expressed in seconds. For more information, see &lt;a href=&quot;https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations&gt;Setting Timeouts for Queue Service Operations.&lt;/a&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async Task<ResponseWithHeaders<MessagesClearHeaders>> ClearAsync(int? timeout = null, CancellationToken cancellationToken = default) { using var message = CreateClearRequest(timeout); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); var headers = new MessagesClearHeaders(message.Response); switch (message.Response.Status) { case 204: return ResponseWithHeaders.FromValue(headers, message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> The Clear operation deletes all messages from the specified queue. </summary> /// <param name="timeout"> The The timeout parameter is expressed in seconds. For more information, see &lt;a href=&quot;https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations&gt;Setting Timeouts for Queue Service Operations.&lt;/a&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public ResponseWithHeaders<MessagesClearHeaders> Clear(int? timeout = null, CancellationToken cancellationToken = default) { using var message = CreateClearRequest(timeout); _pipeline.Send(message, cancellationToken); var headers = new MessagesClearHeaders(message.Response); switch (message.Response.Status) { case 204: return ResponseWithHeaders.FromValue(headers, message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateEnqueueRequest(QueueMessage queueMessage, int? visibilitytimeout, int? messageTimeToLive, int? timeout) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.AppendRaw(url, false); uri.AppendPath("/messages", false); if (visibilitytimeout != null) { uri.AppendQuery("visibilitytimeout", visibilitytimeout.Value, true); } if (messageTimeToLive != null) { uri.AppendQuery("messagettl", messageTimeToLive.Value, true); } if (timeout != null) { uri.AppendQuery("timeout", timeout.Value, true); } request.Uri = uri; request.Headers.Add("x-ms-version", version); request.Headers.Add("Accept", "application/xml"); request.Headers.Add("Content-Type", "application/xml"); var content = new XmlWriterContent(); content.XmlWriter.WriteObjectValue(queueMessage, "QueueMessage"); request.Content = content; return message; } /// <summary> The Enqueue operation adds a new message to the back of the message queue. A visibility timeout can also be specified to make the message invisible until the visibility timeout expires. A message must be in a format that can be included in an XML request with UTF-8 encoding. The encoded message can be up to 64 KB in size for versions 2011-08-18 and newer, or 8 KB in size for previous versions. </summary> /// <param name="queueMessage"> A Message object which can be stored in a Queue. </param> /// <param name="visibilitytimeout"> Optional. If specified, the request must be made using an x-ms-version of 2011-08-18 or later. If not specified, the default value is 0. Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. visibilitytimeout should be set to a value smaller than the time-to-live value. </param> /// <param name="messageTimeToLive"> Optional. Specifies the time-to-live interval for the message, in seconds. Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For version 2017-07-29 or later, the maximum time-to-live can be any positive number, as well as -1 indicating that the message does not expire. If this parameter is omitted, the default time-to-live is 7 days. </param> /// <param name="timeout"> The The timeout parameter is expressed in seconds. For more information, see &lt;a href=&quot;https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations&gt;Setting Timeouts for Queue Service Operations.&lt;/a&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="queueMessage"/> is null. </exception> public async Task<ResponseWithHeaders<IReadOnlyList<SendReceipt>, MessagesEnqueueHeaders>> EnqueueAsync(QueueMessage queueMessage, int? visibilitytimeout = null, int? messageTimeToLive = null, int? timeout = null, CancellationToken cancellationToken = default) { if (queueMessage == null) { throw new ArgumentNullException(nameof(queueMessage)); } using var message = CreateEnqueueRequest(queueMessage, visibilitytimeout, messageTimeToLive, timeout); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); var headers = new MessagesEnqueueHeaders(message.Response); switch (message.Response.Status) { case 201: { IReadOnlyList<SendReceipt> value = default; var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace); if (document.Element("QueueMessagesList") is XElement queueMessagesListElement) { var array = new List<SendReceipt>(); foreach (var e in queueMessagesListElement.Elements("QueueMessage")) { array.Add(SendReceipt.DeserializeSendReceipt(e)); } value = array; } return ResponseWithHeaders.FromValue(value, headers, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> The Enqueue operation adds a new message to the back of the message queue. A visibility timeout can also be specified to make the message invisible until the visibility timeout expires. A message must be in a format that can be included in an XML request with UTF-8 encoding. The encoded message can be up to 64 KB in size for versions 2011-08-18 and newer, or 8 KB in size for previous versions. </summary> /// <param name="queueMessage"> A Message object which can be stored in a Queue. </param> /// <param name="visibilitytimeout"> Optional. If specified, the request must be made using an x-ms-version of 2011-08-18 or later. If not specified, the default value is 0. Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. visibilitytimeout should be set to a value smaller than the time-to-live value. </param> /// <param name="messageTimeToLive"> Optional. Specifies the time-to-live interval for the message, in seconds. Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For version 2017-07-29 or later, the maximum time-to-live can be any positive number, as well as -1 indicating that the message does not expire. If this parameter is omitted, the default time-to-live is 7 days. </param> /// <param name="timeout"> The The timeout parameter is expressed in seconds. For more information, see &lt;a href=&quot;https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations&gt;Setting Timeouts for Queue Service Operations.&lt;/a&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="queueMessage"/> is null. </exception> public ResponseWithHeaders<IReadOnlyList<SendReceipt>, MessagesEnqueueHeaders> Enqueue(QueueMessage queueMessage, int? visibilitytimeout = null, int? messageTimeToLive = null, int? timeout = null, CancellationToken cancellationToken = default) { if (queueMessage == null) { throw new ArgumentNullException(nameof(queueMessage)); } using var message = CreateEnqueueRequest(queueMessage, visibilitytimeout, messageTimeToLive, timeout); _pipeline.Send(message, cancellationToken); var headers = new MessagesEnqueueHeaders(message.Response); switch (message.Response.Status) { case 201: { IReadOnlyList<SendReceipt> value = default; var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace); if (document.Element("QueueMessagesList") is XElement queueMessagesListElement) { var array = new List<SendReceipt>(); foreach (var e in queueMessagesListElement.Elements("QueueMessage")) { array.Add(SendReceipt.DeserializeSendReceipt(e)); } value = array; } return ResponseWithHeaders.FromValue(value, headers, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreatePeekRequest(int? numberOfMessages, int? timeout) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.AppendRaw(url, false); uri.AppendPath("/messages", false); uri.AppendQuery("peekonly", "true", true); if (numberOfMessages != null) { uri.AppendQuery("numofmessages", numberOfMessages.Value, true); } if (timeout != null) { uri.AppendQuery("timeout", timeout.Value, true); } request.Uri = uri; request.Headers.Add("x-ms-version", version); request.Headers.Add("Accept", "application/xml"); return message; } /// <summary> The Peek operation retrieves one or more messages from the front of the queue, but does not alter the visibility of the message. </summary> /// <param name="numberOfMessages"> Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible messages are returned. By default, a single message is retrieved from the queue with this operation. </param> /// <param name="timeout"> The The timeout parameter is expressed in seconds. For more information, see &lt;a href=&quot;https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations&gt;Setting Timeouts for Queue Service Operations.&lt;/a&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async Task<ResponseWithHeaders<IReadOnlyList<PeekedMessageItem>, MessagesPeekHeaders>> PeekAsync(int? numberOfMessages = null, int? timeout = null, CancellationToken cancellationToken = default) { using var message = CreatePeekRequest(numberOfMessages, timeout); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); var headers = new MessagesPeekHeaders(message.Response); switch (message.Response.Status) { case 200: { IReadOnlyList<PeekedMessageItem> value = default; var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace); if (document.Element("QueueMessagesList") is XElement queueMessagesListElement) { var array = new List<PeekedMessageItem>(); foreach (var e in queueMessagesListElement.Elements("QueueMessage")) { array.Add(PeekedMessageItem.DeserializePeekedMessageItem(e)); } value = array; } return ResponseWithHeaders.FromValue(value, headers, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> The Peek operation retrieves one or more messages from the front of the queue, but does not alter the visibility of the message. </summary> /// <param name="numberOfMessages"> Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible messages are returned. By default, a single message is retrieved from the queue with this operation. </param> /// <param name="timeout"> The The timeout parameter is expressed in seconds. For more information, see &lt;a href=&quot;https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations&gt;Setting Timeouts for Queue Service Operations.&lt;/a&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public ResponseWithHeaders<IReadOnlyList<PeekedMessageItem>, MessagesPeekHeaders> Peek(int? numberOfMessages = null, int? timeout = null, CancellationToken cancellationToken = default) { using var message = CreatePeekRequest(numberOfMessages, timeout); _pipeline.Send(message, cancellationToken); var headers = new MessagesPeekHeaders(message.Response); switch (message.Response.Status) { case 200: { IReadOnlyList<PeekedMessageItem> value = default; var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace); if (document.Element("QueueMessagesList") is XElement queueMessagesListElement) { var array = new List<PeekedMessageItem>(); foreach (var e in queueMessagesListElement.Elements("QueueMessage")) { array.Add(PeekedMessageItem.DeserializePeekedMessageItem(e)); } value = array; } return ResponseWithHeaders.FromValue(value, headers, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
67.353247
523
0.631792
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/storage/Azure.Storage.Queues/src/Generated/MessagesRestClient.cs
25,931
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGame.Extended.Screens.Transitions { public class FadeTransition : Transition { private readonly GraphicsDevice _graphicsDevice; private readonly SpriteBatch _spriteBatch; public FadeTransition(GraphicsDevice graphicsDevice, Color color, float duration = 1.0f) : base(duration) { Color = color; _graphicsDevice = graphicsDevice; _spriteBatch = new SpriteBatch(graphicsDevice); } public override void Dispose() { _spriteBatch.Dispose(); } public Color Color { get; } public override void Draw(GameTime gameTime) { _spriteBatch.Begin(samplerState: SamplerState.PointClamp); _spriteBatch.FillRectangle(0, 0, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height, Color * Value); _spriteBatch.End(); } } }
28.742857
125
0.642147
[ "MIT" ]
Apostolique/MonoGame.Extended
src/dotnet/MonoGame.Extended/Screens/Transitions/FadeTransition.cs
1,006
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace sfShareLib { using System; using System.Collections.Generic; public partial class IoTHub { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public IoTHub() { this.IoTDevice = new HashSet<IoTDevice>(); } public string IoTHubAlias { get; set; } public string Description { get; set; } public int CompanyID { get; set; } public string P_IoTHubEndPoint { get; set; } public string P_IoTHubConnectionString { get; set; } public string P_EventConsumerGroup { get; set; } public string P_EventHubStorageConnectionString { get; set; } public string P_UploadContainer { get; set; } public string S_IoTHubEndPoint { get; set; } public string S_IoTHubConnectionString { get; set; } public string S_EventConsumerGroup { get; set; } public string S_EventHubStorageConnectionString { get; set; } public string S_UploadContainer { get; set; } public System.DateTime CreatedAt { get; set; } public Nullable<System.DateTime> UpdatedAt { get; set; } public bool DeletedFlag { get; set; } public virtual Company Company { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<IoTDevice> IoTDevice { get; set; } } }
42.977778
128
0.613754
[ "MIT" ]
KevinKao809/CDS10
sfShareLib/IoTHub.cs
1,934
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Xunit.Abstractions; namespace Microsoft.Coyote.SystematicTesting.Tests.Tasks { public class TaskRunConfigureAwaitFalseTests : Microsoft.Coyote.Production.Tests.Tasks.TaskRunConfigureAwaitFalseTests { public TaskRunConfigureAwaitFalseTests(ITestOutputHelper output) : base(output) { } public override bool SystematicTest => true; } }
26.333333
122
0.723629
[ "MIT" ]
p-org/coyote
Tests/SystematicTesting.Tests/Tasks/ConfigureAwait/TaskRunConfigureAwaitFalseTests.cs
476
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by the ClassGenerator.ttinclude code generation file. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Data.Common; using System.Collections.Generic; using Telerik.OpenAccess; using Telerik.OpenAccess.Metadata; using Telerik.OpenAccess.Data.Common; using Telerik.OpenAccess.Metadata.Fluent; using Telerik.OpenAccess.Metadata.Fluent.Advanced; using Construct.Server.Entities; namespace Construct.Server.Entities { public partial class PropertyType : PropertyParent { private Guid propertyDataTypeIDs; public virtual Guid PropertyDataTypeID { get { return this.propertyDataTypeIDs; } set { this.propertyDataTypeIDs = value; } } private DataType dataTypes; public override DataType DataType { get { return this.dataTypes; } set { this.dataTypes = value; } } } } #pragma warning restore 1591
23.017857
84
0.641583
[ "MIT" ]
dgerding/Construct
Construct3/Construct3/Construct.Server.Entities/Generated/PropertyType.generated.cs
1,289
C#
using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using PhoneBook.Authorization; using PhoneBook.Authorization.Roles; using PhoneBook.Authorization.Users; using PhoneBook.Editions; using PhoneBook.MultiTenancy; namespace PhoneBook.Identity { public static class IdentityRegistrar { public static IdentityBuilder Register(IServiceCollection services) { services.AddLogging(); return services.AddAbpIdentity<Tenant, User, Role>() .AddAbpTenantManager<TenantManager>() .AddAbpUserManager<UserManager>() .AddAbpRoleManager<RoleManager>() .AddAbpEditionManager<EditionManager>() .AddAbpUserStore<UserStore>() .AddAbpRoleStore<RoleStore>() .AddAbpLogInManager<LogInManager>() .AddAbpSignInManager<SignInManager>() .AddAbpSecurityStampValidator<SecurityStampValidator>() .AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>() .AddPermissionChecker<PermissionChecker>() .AddDefaultTokenProviders(); } } }
36.242424
79
0.665552
[ "MIT" ]
Mater813/PhoneBook
aspnet-core/src/PhoneBook.Core/Identity/IdentityRegistrar.cs
1,198
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Xml.Serialization; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Boku.Base; namespace Boku.Common.ParticleSystem { /// <summary> /// Provides a common entry point for the sources to add particles to the emitters. In the /// case of the smoke emitters this also allows there to be several so that we can bin the /// particles based on their life span. This prevents long lived particles from "locking in" /// short lived ones. We only have a sinlge distorted smoke emitter since these all tend /// to be short-lived. /// /// Note that the emitters managed here are not added to the normal particle system manager. /// Since we know more about them we can be a bit more efficient during rendering. /// </summary> public class SharedEmitterManager : BaseEmitter { #region Members // Smoke emitters. private const int kNumSmokes = 4; private static float[] smokeMaxLife = new float[kNumSmokes] { 1.0f, 4.0f, 8.0f, float.MaxValue }; private static SharedSmokeEmitter[] smoke = null; // Distorted smoke emitter. private static SharedSmokeEmitter distortedSmoke = null; private static BeamManager beam = null; private static BleepManager bleep = null; private static SharedSparkEmitter spark = null; private static SharedSplashEmitter splash = null; #endregion #region Accessors /// <summary> /// Provide access to the bleep manager, for firing off bleeps. /// </summary> public static BeamManager Beams { get { return beam; } } public static BleepManager Bleeps { get { return bleep; } } public static SharedSparkEmitter Sparks { get { return spark; } } public static SharedSplashEmitter Splashes { get { return splash; } } #endregion #region Public public SharedEmitterManager(ParticleSystemManager manager) : base(manager) { Persistent = true; // Tell ParticleSystemManager not to clear me. // // Create shared emitters. // // Smoke smoke = new SharedSmokeEmitter[kNumSmokes]; smoke[0] = new SharedSmokeEmitter(manager, 5000); smoke[1] = new SharedSmokeEmitter(manager, 8000); smoke[2] = new SharedSmokeEmitter(manager, 2000); smoke[3] = new SharedSmokeEmitter(manager, 2000); distortedSmoke = new SharedSmokeEmitter(manager, 1000); distortedSmoke.Usage = Use.Distort; beam = new BeamManager(manager); bleep = new BleepManager(manager); spark = new SharedSparkEmitter(manager, 1000); splash = new SharedSplashEmitter(manager, 1000); } // end of c'tor public static void AddSmokeParticle(ref SharedSmokeEmitter.SmokeParticle p) { // Get the index formn the lifetime. int i = 0; while (p.lifetime > smokeMaxLife[i]) { ++i; } Debug.Assert(i < kNumSmokes); smoke[i].AddParticle(ref p); } // end of AddSmokeParticle() public static void AddDistortedSmokeParticle(ref SharedSmokeEmitter.SmokeParticle p) { distortedSmoke.AddParticle(ref p); } // end of AddDistortedSmokeParticle() /// <summary> /// Removes all particles from all shared emitters. /// </summary> public override void FlushAllParticles() { for (int i = 0; i < kNumSmokes; i++) { smoke[i].FlushAllParticles(); } distortedSmoke.FlushAllParticles(); beam.FlushAllParticles(); bleep.FlushAllParticles(); spark.FlushAllParticles(); splash.FlushAllParticles(); } // end of SharedEmitterManager FlushAllParticles() public override void Update() { for (int i = 0; i < kNumSmokes; i++) { smoke[i].Update(); } distortedSmoke.Update(); beam.Update(); bleep.Update(); spark.Update(); splash.Update(); } // end of Update() public override void Render(Camera camera) { if (InGame.inGame.renderEffects == InGame.RenderEffect.DistortionPass) { distortedSmoke.PreRender(camera); distortedSmoke.Render(camera); distortedSmoke.PostRender(); } else { smoke[0].PreRender(camera); for (int i = 0; i < kNumSmokes; i++) { smoke[i].Render(camera); } smoke[0].PostRender(); beam.PreRender(camera); beam.Render(camera); beam.PostRender(); bleep.PreRender(camera); bleep.Render(camera); bleep.PostRender(); spark.PreRender(camera); spark.Render(camera); spark.PostRender(); splash.PreRender(camera); splash.Render(camera); splash.PostRender(); } } // end of Render() #endregion #region Internal public static void LoadContent(bool immediate) { for (int i = 0; i < kNumSmokes; i++) { BokuGame.Load(smoke[i], immediate); } BokuGame.Load(distortedSmoke, immediate); BokuGame.Load(beam, immediate); BokuGame.Load(bleep, immediate); BokuGame.Load(spark, immediate); BokuGame.Load(splash, immediate); } // end of LoadContent() public static void InitDeviceResources(GraphicsDevice device) { } public static void UnloadContent() { for (int i = 0; i < kNumSmokes; i++) { BokuGame.Unload(smoke[i]); } BokuGame.Unload(distortedSmoke); BokuGame.Unload(beam); BokuGame.Unload(bleep); BokuGame.Unload(spark); BokuGame.Unload(splash); } // end of UnloadContent() public static void DeviceReset(GraphicsDevice device) { } #endregion } // end of class SharedEmitterManager } // end of namespace Boku.Common.ParticleSystem
30.423077
105
0.558224
[ "MIT" ]
Yash-Codemaster/KoduGameLab
main/Boku/Common/ParticleSystem/SharedEmitterManager.cs
7,119
C#
using System; using NSaga; namespace Benchmarking.Sagas { public class FirstMessage : IInitiatingSagaMessage { public Guid CorrelationId { get; set; } public Guid MessageId { get; set; } public FirstMessage(Guid correlationId) { CorrelationId = correlationId; MessageId = Guid.NewGuid(); } } public class SecondMessage : ISagaMessage { public Guid CorrelationId { get; set; } public Guid MessageId { get; set; } public SecondMessage(Guid correlationId) { CorrelationId = correlationId; MessageId = Guid.NewGuid(); } } public class ThirdMessage : ISagaMessage { public Guid CorrelationId { get; set; } public Guid MessageId { get; set; } public ThirdMessage(Guid correlationId) { CorrelationId = correlationId; MessageId = Guid.NewGuid(); } } }
21.822222
54
0.57943
[ "MIT" ]
AMVSoftware/NSaga
src/Tests.Benchmarking/Sagas/BenchmarkSagaMessages.cs
984
C#
using Microsoft.Extensions.Logging; using Npgsql; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using watchtower.Code.ExtensionMethods; using watchtower.Models.PSB; namespace watchtower.Services.Db { public class PsbAccountNoteDbStore { private readonly ILogger<PsbAccountNoteDbStore> _Logger; private readonly IDbHelper _DbHelper; private readonly IDataReader<PsbAccountNote> _Reader; public PsbAccountNoteDbStore(ILogger<PsbAccountNoteDbStore> logger, IDbHelper helper, IDataReader<PsbAccountNote> reader) { _Logger = logger; _DbHelper = helper; _Reader = reader; } /// <summary> /// Get a <see cref="PsbAccountNote"/> by its ID /// </summary> /// <param name="ID">ID of the account to get</param> /// <param name="cancel">Cancellation token</param> /// <returns> /// The <see cref="PsbAccountNote"/> with <see cref="PsbAccountNote.ID"/> of <paramref name="ID"/>, /// or <c>null</c> if it does not exist /// </returns> public async Task<PsbAccountNote?> GetByID(long ID, CancellationToken cancel) { using NpgsqlConnection conn = _DbHelper.Connection(); using NpgsqlCommand cmd = await _DbHelper.Command(conn, @" SELECT * FROM psb_account_note WHERE id = @ID; "); cmd.AddParameter("ID", ID); return await cmd.ExecuteReadSingle(_Reader, cancel); } /// <summary> /// Get all notes of an account /// </summary> /// <param name="accountID">ID of the account</param> /// <param name="cancel">Cancellation token</param> /// <returns> /// All <see cref="PsbAccountNote"/>s with <see cref="PsbAccountNote.AccountID"/> of <paramref name="accountID"/> /// </returns> public async Task<List<PsbAccountNote>> GetByAccountID(long accountID, CancellationToken cancel) { using NpgsqlConnection conn = _DbHelper.Connection(); using NpgsqlCommand cmd = await _DbHelper.Command(conn, @" SELECT * FROM psb_account_note WHERE account_id = @AccountID; "); cmd.AddParameter("AccountID", accountID); return await cmd.ExecuteReadList(_Reader, cancel); } /// <summary> /// Insert a new note on an account /// </summary> /// <param name="accountID">ID of the account the note is for</param> /// <param name="note">Parameters used to insert the note</param> /// <param name="cancel">Cancellation token</param> public async Task<long> Insert(long accountID, PsbAccountNote note, CancellationToken cancel) { using NpgsqlConnection conn = _DbHelper.Connection(); using NpgsqlCommand cmd = await _DbHelper.Command(conn, @" INSERT INTO psb_account_note ( account_id, honu_id, timestamp, message ) VALUES ( @AccountID, @HonuID, NOW() AT TIME ZONE 'utc', @Message ) RETURNING id; "); cmd.AddParameter("AccountID", accountID); cmd.AddParameter("HonuID", note.HonuID); cmd.AddParameter("Message", note.Message); return await cmd.ExecuteInt64(cancel); } } }
38.021505
125
0.58767
[ "MIT" ]
Simacrus/honu
Services/Db/PsbAccountNoteDbStore.cs
3,538
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Gcp.Organizations { [GcpResourceType("gcp:organizations/iAMMember:IAMMember")] public partial class IAMMember : Pulumi.CustomResource { [Output("condition")] public Output<Outputs.IAMMemberCondition?> Condition { get; private set; } = null!; [Output("etag")] public Output<string> Etag { get; private set; } = null!; [Output("member")] public Output<string> Member { get; private set; } = null!; /// <summary> /// The numeric ID of the organization in which you want to manage the audit logging config. /// </summary> [Output("orgId")] public Output<string> OrgId { get; private set; } = null!; [Output("role")] public Output<string> Role { get; private set; } = null!; /// <summary> /// Create a IAMMember resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public IAMMember(string name, IAMMemberArgs args, CustomResourceOptions? options = null) : base("gcp:organizations/iAMMember:IAMMember", name, args ?? new IAMMemberArgs(), MakeResourceOptions(options, "")) { } private IAMMember(string name, Input<string> id, IAMMemberState? state = null, CustomResourceOptions? options = null) : base("gcp:organizations/iAMMember:IAMMember", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing IAMMember resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static IAMMember Get(string name, Input<string> id, IAMMemberState? state = null, CustomResourceOptions? options = null) { return new IAMMember(name, id, state, options); } } public sealed class IAMMemberArgs : Pulumi.ResourceArgs { [Input("condition")] public Input<Inputs.IAMMemberConditionArgs>? Condition { get; set; } [Input("member", required: true)] public Input<string> Member { get; set; } = null!; /// <summary> /// The numeric ID of the organization in which you want to manage the audit logging config. /// </summary> [Input("orgId", required: true)] public Input<string> OrgId { get; set; } = null!; [Input("role", required: true)] public Input<string> Role { get; set; } = null!; public IAMMemberArgs() { } } public sealed class IAMMemberState : Pulumi.ResourceArgs { [Input("condition")] public Input<Inputs.IAMMemberConditionGetArgs>? Condition { get; set; } [Input("etag")] public Input<string>? Etag { get; set; } [Input("member")] public Input<string>? Member { get; set; } /// <summary> /// The numeric ID of the organization in which you want to manage the audit logging config. /// </summary> [Input("orgId")] public Input<string>? OrgId { get; set; } [Input("role")] public Input<string>? Role { get; set; } public IAMMemberState() { } } }
37.830645
135
0.611597
[ "ECL-2.0", "Apache-2.0" ]
la3mmchen/pulumi-gcp
sdk/dotnet/Organizations/IAMMember.cs
4,691
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.ChangeFeed; using Microsoft.Azure.Cosmos.ChangeFeed.FeedProcessing; using Microsoft.Azure.Cosmos.CosmosElements; using Microsoft.Azure.Cosmos.Query; using Microsoft.Azure.Documents; /// <summary> /// Used to perform operations on items. There are two different types of operations. /// 1. The object operations where it serializes and deserializes the item on request/response /// 2. The stream response which takes a Stream containing a JSON serialized object and returns a response containing a Stream /// </summary> internal class CosmosItemsCore : CosmosItems { /// <summary> /// Cache the full URI segment without the last resource id. /// This allows only a single con-cat operation instead of building the full URI string each time. /// </summary> private string cachedUriSegmentWithoutId { get; } private readonly CosmosClientContext clientContext; private readonly CosmosQueryClient queryClient; internal CosmosItemsCore( CosmosClientContext clientContext, CosmosContainerCore container, CosmosQueryClient queryClient = null) { this.clientContext = clientContext; this.container = container; this.cachedUriSegmentWithoutId = this.GetResourceSegmentUriWithoutId(); this.queryClient = queryClient ?? new CosmosQueryClientCore(this.clientContext, container); } internal readonly CosmosContainerCore container; public override Task<CosmosResponseMessage> CreateItemStreamAsync( object partitionKey, Stream streamPayload, CosmosItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { return this.ProcessItemStreamAsync( partitionKey, null, streamPayload, OperationType.Create, requestOptions, cancellationToken); } public override Task<CosmosItemResponse<T>> CreateItemAsync<T>( object partitionKey, T item, CosmosItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { Task<CosmosResponseMessage> response = this.CreateItemStreamAsync( partitionKey: partitionKey, streamPayload: this.clientContext.JsonSerializer.ToStream<T>(item), requestOptions: requestOptions, cancellationToken: cancellationToken); return this.clientContext.ResponseFactory.CreateItemResponse<T>(response); } public override Task<CosmosResponseMessage> ReadItemStreamAsync( object partitionKey, string id, CosmosItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { return this.ProcessItemStreamAsync( partitionKey, id, null, OperationType.Read, requestOptions, cancellationToken); } public override Task<CosmosItemResponse<T>> ReadItemAsync<T>( object partitionKey, string id, CosmosItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { Task<CosmosResponseMessage> response = this.ReadItemStreamAsync( partitionKey: partitionKey, id: id, requestOptions: requestOptions, cancellationToken: cancellationToken); return this.clientContext.ResponseFactory.CreateItemResponse<T>(response); } public override Task<CosmosResponseMessage> UpsertItemStreamAsync( object partitionKey, Stream streamPayload, CosmosItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { return this.ProcessItemStreamAsync( partitionKey, null, streamPayload, OperationType.Upsert, requestOptions, cancellationToken); } public override Task<CosmosItemResponse<T>> UpsertItemAsync<T>( object partitionKey, T item, CosmosItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { Task<CosmosResponseMessage> response = this.UpsertItemStreamAsync( partitionKey: partitionKey, streamPayload: this.clientContext.JsonSerializer.ToStream<T>(item), requestOptions: requestOptions, cancellationToken: cancellationToken); return this.clientContext.ResponseFactory.CreateItemResponse<T>(response); } public override Task<CosmosResponseMessage> ReplaceItemStreamAsync( object partitionKey, string id, Stream streamPayload, CosmosItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { return this.ProcessItemStreamAsync( partitionKey, id, streamPayload, OperationType.Replace, requestOptions, cancellationToken); } public override Task<CosmosItemResponse<T>> ReplaceItemAsync<T>( object partitionKey, string id, T item, CosmosItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { Task<CosmosResponseMessage> response = this.ReplaceItemStreamAsync( partitionKey: partitionKey, id: id, streamPayload: this.clientContext.JsonSerializer.ToStream<T>(item), requestOptions: requestOptions, cancellationToken: cancellationToken); return this.clientContext.ResponseFactory.CreateItemResponse<T>(response); } public override Task<CosmosResponseMessage> DeleteItemStreamAsync( object partitionKey, string id, CosmosItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { return this.ProcessItemStreamAsync( partitionKey, id, null, OperationType.Delete, requestOptions, cancellationToken); } public override Task<CosmosItemResponse<T>> DeleteItemAsync<T>( object partitionKey, string id, CosmosItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { Task<CosmosResponseMessage> response = this.DeleteItemStreamAsync( partitionKey: partitionKey, id: id, requestOptions: requestOptions, cancellationToken: cancellationToken); return this.clientContext.ResponseFactory.CreateItemResponse<T>(response); } public override CosmosFeedIterator<T> GetItemIterator<T>( int? maxItemCount = null, string continuationToken = null) { return new CosmosDefaultResultSetIterator<T>( maxItemCount, continuationToken, null, this.ItemFeedRequestExecutor<T>); } public override CosmosFeedIterator GetItemStreamIterator( int? maxItemCount = null, string continuationToken = null, CosmosItemRequestOptions requestOptions = null) { return new CosmosResultSetIteratorCore(maxItemCount, continuationToken, requestOptions, this.ItemStreamFeedRequestExecutor); } public override CosmosFeedIterator CreateItemQueryAsStream( CosmosSqlQueryDefinition sqlQueryDefinition, int maxConcurrency, object partitionKey = null, int? maxItemCount = null, string continuationToken = null, CosmosQueryRequestOptions requestOptions = null) { requestOptions = requestOptions ?? new CosmosQueryRequestOptions(); requestOptions.MaxConcurrency = maxConcurrency; requestOptions.EnableCrossPartitionQuery = true; requestOptions.RequestContinuation = continuationToken; requestOptions.MaxItemCount = maxItemCount; requestOptions.PartitionKey = partitionKey; CosmosQueryExecutionContext cosmosQueryExecution = new CosmosQueryExecutionContextFactory( client: this.queryClient, resourceTypeEnum: ResourceType.Document, operationType: OperationType.Query, resourceType: typeof(CosmosQueryResponse), sqlQuerySpec: sqlQueryDefinition.ToSqlQuerySpec(), queryRequestOptions: requestOptions, resourceLink: this.container.LinkUri, isContinuationExpected: true, allowNonValueAggregateQuery: true, correlatedActivityId: Guid.NewGuid()); return new CosmosResultSetIteratorCore( maxItemCount, continuationToken, requestOptions, this.QueryRequestExecutor, cosmosQueryExecution); } public override CosmosFeedIterator CreateItemQueryAsStream( string sqlQueryText, int maxConcurrency, object partitionKey = null, int? maxItemCount = null, string continuationToken = null, CosmosQueryRequestOptions requestOptions = null) { return this.CreateItemQueryAsStream( new CosmosSqlQueryDefinition(sqlQueryText), maxConcurrency, partitionKey, maxItemCount, continuationToken, requestOptions); } public override CosmosFeedIterator<T> CreateItemQuery<T>( CosmosSqlQueryDefinition sqlQueryDefinition, object partitionKey, int? maxItemCount = null, string continuationToken = null, CosmosQueryRequestOptions requestOptions = null) { requestOptions = requestOptions ?? new CosmosQueryRequestOptions(); requestOptions.PartitionKey = partitionKey; requestOptions.EnableCrossPartitionQuery = false; requestOptions.RequestContinuation = continuationToken; requestOptions.MaxItemCount = maxItemCount; CosmosQueryExecutionContext cosmosQueryExecution = new CosmosQueryExecutionContextFactory( client: this.queryClient, resourceTypeEnum: ResourceType.Document, operationType: OperationType.Query, resourceType: typeof(T), sqlQuerySpec: sqlQueryDefinition.ToSqlQuerySpec(), queryRequestOptions: requestOptions, resourceLink: this.container.LinkUri, isContinuationExpected: true, allowNonValueAggregateQuery: true, correlatedActivityId: Guid.NewGuid()); return new CosmosDefaultResultSetIterator<T>( maxItemCount, continuationToken, requestOptions, this.NextResultSetAsync<T>, cosmosQueryExecution); } public override CosmosFeedIterator<T> CreateItemQuery<T>( string sqlQueryText, object partitionKey, int? maxItemCount = null, string continuationToken = null, CosmosQueryRequestOptions requestOptions = null) { return this.CreateItemQuery<T>( new CosmosSqlQueryDefinition(sqlQueryText), partitionKey, maxItemCount, continuationToken, requestOptions); } public override CosmosFeedIterator<T> CreateItemQuery<T>( CosmosSqlQueryDefinition sqlQueryDefinition, int maxConcurrency, int? maxItemCount = null, string continuationToken = null, CosmosQueryRequestOptions requestOptions = null) { requestOptions = requestOptions ?? new CosmosQueryRequestOptions(); requestOptions.EnableCrossPartitionQuery = true; requestOptions.RequestContinuation = continuationToken; requestOptions.MaxItemCount = maxItemCount; requestOptions.MaxConcurrency = maxConcurrency; CosmosQueryExecutionContext cosmosQueryExecution = new CosmosQueryExecutionContextFactory( client: this.queryClient, resourceTypeEnum: ResourceType.Document, operationType: OperationType.Query, resourceType: typeof(T), sqlQuerySpec: sqlQueryDefinition.ToSqlQuerySpec(), queryRequestOptions: requestOptions, resourceLink: this.container.LinkUri, isContinuationExpected: true, allowNonValueAggregateQuery: true, correlatedActivityId: Guid.NewGuid()); return new CosmosDefaultResultSetIterator<T>( maxItemCount, continuationToken, requestOptions, this.NextResultSetAsync<T>, cosmosQueryExecution); } public override CosmosFeedIterator<T> CreateItemQuery<T>( string sqlQueryText, int maxConcurrency, int? maxItemCount = null, string continuationToken = null, CosmosQueryRequestOptions requestOptions = null) { return this.CreateItemQuery<T>( new CosmosSqlQueryDefinition(sqlQueryText), maxConcurrency, maxItemCount, continuationToken, requestOptions); } public override ChangeFeedProcessorBuilder CreateChangeFeedProcessorBuilder<T>( string workflowName, Func<IReadOnlyCollection<T>, CancellationToken, Task> onChangesDelegate) { if (workflowName == null) { throw new ArgumentNullException(nameof(workflowName)); } if (onChangesDelegate == null) { throw new ArgumentNullException(nameof(onChangesDelegate)); } ChangeFeedObserverFactoryCore<T> observerFactory = new ChangeFeedObserverFactoryCore<T>(onChangesDelegate); ChangeFeedProcessorCore<T> changeFeedProcessor = new ChangeFeedProcessorCore<T>(observerFactory); return new ChangeFeedProcessorBuilder( workflowName: workflowName, cosmosContainer: this.container, changeFeedProcessor: changeFeedProcessor, applyBuilderConfiguration: changeFeedProcessor.ApplyBuildConfiguration); } public override ChangeFeedProcessorBuilder CreateChangeFeedProcessorBuilder( string workflowName, Func<long, CancellationToken, Task> estimationDelegate, TimeSpan? estimationPeriod = null) { if (workflowName == null) { throw new ArgumentNullException(nameof(workflowName)); } if (estimationDelegate == null) { throw new ArgumentNullException(nameof(estimationDelegate)); } ChangeFeedEstimatorCore changeFeedEstimatorCore = new ChangeFeedEstimatorCore(estimationDelegate, estimationPeriod); return new ChangeFeedProcessorBuilder( workflowName: workflowName, cosmosContainer: this.container, changeFeedProcessor: changeFeedEstimatorCore, applyBuilderConfiguration: changeFeedEstimatorCore.ApplyBuildConfiguration); } internal CosmosFeedIterator GetStandByFeedIterator( string continuationToken = null, int? maxItemCount = null, CosmosChangeFeedRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { CosmosChangeFeedRequestOptions cosmosQueryRequestOptions = requestOptions as CosmosChangeFeedRequestOptions ?? new CosmosChangeFeedRequestOptions(); return new CosmosChangeFeedResultSetIteratorCore( clientContext: this.clientContext, continuationToken: continuationToken, maxItemCount: maxItemCount, cosmosContainer: this.container, options: cosmosQueryRequestOptions); } internal async Task<CosmosFeedResponse<T>> NextResultSetAsync<T>( int? maxItemCount, string continuationToken, CosmosRequestOptions options, object state, CancellationToken cancellationToken) { CosmosQueryExecutionContext cosmosQueryExecution = (CosmosQueryExecutionContext)state; CosmosQueryResponse queryResponse = await cosmosQueryExecution.ExecuteNextAsync(cancellationToken); queryResponse.EnsureSuccessStatusCode(); return CosmosQueryResponse<T>.CreateResponse<T>( cosmosQueryResponse: queryResponse, jsonSerializer: this.clientContext.JsonSerializer, hasMoreResults: !cosmosQueryExecution.IsDone); } internal Task<CosmosResponseMessage> ProcessItemStreamAsync( object partitionKey, string itemId, Stream streamPayload, OperationType operationType, CosmosRequestOptions requestOptions, CancellationToken cancellationToken) { CosmosItemsCore.ValidatePartitionKey(partitionKey, requestOptions); Uri resourceUri = this.GetResourceUri(requestOptions, operationType, itemId); return this.clientContext.ProcessResourceOperationStreamAsync( resourceUri, ResourceType.Document, operationType, requestOptions, this.container, partitionKey, streamPayload, null, cancellationToken); } private Task<CosmosResponseMessage> ItemStreamFeedRequestExecutor( int? maxItemCount, string continuationToken, CosmosRequestOptions options, object state, CancellationToken cancellationToken) { Uri resourceUri = this.container.LinkUri; return this.clientContext.ProcessResourceOperationAsync<CosmosResponseMessage>( resourceUri: resourceUri, resourceType: ResourceType.Document, operationType: OperationType.ReadFeed, requestOptions: options, requestEnricher: request => { CosmosQueryRequestOptions.FillContinuationToken(request, continuationToken); CosmosQueryRequestOptions.FillMaxItemCount(request, maxItemCount); }, responseCreator: response => response, cosmosContainerCore: this.container, partitionKey: null, streamPayload: null, cancellationToken: cancellationToken); } private Task<CosmosFeedResponse<T>> ItemFeedRequestExecutor<T>( int? maxItemCount, string continuationToken, CosmosRequestOptions options, object state, CancellationToken cancellationToken) { Uri resourceUri = this.container.LinkUri; return this.clientContext.ProcessResourceOperationAsync<CosmosFeedResponse<T>>( resourceUri: resourceUri, resourceType: ResourceType.Document, operationType: OperationType.ReadFeed, requestOptions: options, requestEnricher: request => { CosmosQueryRequestOptions.FillContinuationToken(request, continuationToken); CosmosQueryRequestOptions.FillMaxItemCount(request, maxItemCount); }, responseCreator: response => this.clientContext.ResponseFactory.CreateResultSetQueryResponse<T>(response), cosmosContainerCore: this.container, partitionKey: null, streamPayload: null, cancellationToken: cancellationToken); } private async Task<CosmosResponseMessage> QueryRequestExecutor( int? maxItemCount, string continuationToken, CosmosRequestOptions options, object state, CancellationToken cancellationToken) { CosmosQueryExecutionContext cosmosQueryExecution = (CosmosQueryExecutionContext)state; return (CosmosResponseMessage)(await cosmosQueryExecution.ExecuteNextAsync(cancellationToken)); } internal Uri GetResourceUri(CosmosRequestOptions requestOptions, OperationType operationType, string itemId) { if (requestOptions != null && requestOptions.TryGetResourceUri(out Uri resourceUri)) { return resourceUri; } switch (operationType) { case OperationType.Create: case OperationType.Upsert: return this.container.LinkUri; default: return this.ContcatCachedUriWithId(itemId); } } /// <summary> /// Throw an exception if the partition key is null or empty string /// </summary> internal static void ValidatePartitionKey(object partitionKey, CosmosRequestOptions requestOptions) { if (partitionKey != null) { return; } if (requestOptions?.Properties != null && requestOptions.Properties.TryGetValue( WFConstants.BackendHeaders.EffectivePartitionKeyString, out object effectivePartitionKeyValue) && effectivePartitionKeyValue != null) { return; } throw new ArgumentNullException(nameof(partitionKey)); } /// <summary> /// Gets the full resource segment URI without the last id. /// </summary> /// <returns>Example: /dbs/*/colls/*/{this.pathSegment}/ </returns> private string GetResourceSegmentUriWithoutId() { // StringBuilder is roughly 2x faster than string.Format StringBuilder stringBuilder = new StringBuilder(this.container.LinkUri.OriginalString.Length + Paths.DocumentsPathSegment.Length + 2); stringBuilder.Append(this.container.LinkUri.OriginalString); stringBuilder.Append("/"); stringBuilder.Append(Paths.DocumentsPathSegment); stringBuilder.Append("/"); return stringBuilder.ToString(); } /// <summary> /// Gets the full resource URI using the cached resource URI segment /// </summary> /// <param name="resourceId">The resource id</param> /// <returns> /// A document link in the format of {CachedUriSegmentWithoutId}/{0}/ with {0} being a Uri escaped version of the <paramref name="resourceId"/> /// </returns> /// <remarks>Would be used when creating an <see cref="Attachment"/>, or when replacing or deleting a item in Azure Cosmos DB.</remarks> /// <seealso cref="Uri.EscapeUriString"/> private Uri ContcatCachedUriWithId(string resourceId) { return new Uri(this.cachedUriSegmentWithoutId + Uri.EscapeUriString(resourceId), UriKind.Relative); } } }
42.008306
160
0.610621
[ "MIT" ]
JohnLTaylor/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/Resource/Item/CosmosItemsCore.cs
25,291
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace DiceGirl.MainGame { public class Point : MonoBehaviour { public EventPoint pointEvent; private void Awake() { pointEvent = GetComponentInChildren<EventPoint>(); } //public void Init(PointEventInfo info) //{ // //if (info != null) // // pointEvent = Instantiate(Resources.Load<PointEvent>($"Prefabs/Events/{info.objName}"),transform); // //else // // pointEvent = null; //} public void DoEvent() { pointEvent?.doEvent?.Invoke(); } } }
20
117
0.545714
[ "Unlicense" ]
LinusMC/Dream-Date
Dream Date/Assets/Scripts/MainGame/Point.cs
702
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class CrosshairModule : HUDModule { [Ordinal(0)] [RED("activeCrosshairs")] public CArray<CHandle<Crosshair>> ActiveCrosshairs { get; set; } public CrosshairModule(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
25.875
107
0.717391
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/CrosshairModule.cs
399
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Commands.Test.Websites { using Commands.Utilities.Common; using Utilities.Common; using Utilities.Websites; using Commands.Utilities.Websites; using Commands.Websites; using Moq; using VisualStudio.TestTools.UnitTesting; [TestClass] public class StopAzureWebsiteTests : WebsitesTestBase { [TestMethod] public void ProcessStopWebsiteTest() { const string websiteName = "website1"; // Setup Mock<IWebsitesClient> websitesClientMock = new Mock<IWebsitesClient>(); websitesClientMock.Setup(f => f.StopWebsite(websiteName, null)); // Test StopAzureWebsiteCommand stopAzureWebsiteCommand = new StopAzureWebsiteCommand() { CommandRuntime = new MockCommandRuntime(), Name = websiteName, CurrentSubscription = new WindowsAzureSubscription { SubscriptionId = base.subscriptionId }, WebsitesClient = websitesClientMock.Object }; stopAzureWebsiteCommand.ExecuteCmdlet(); websitesClientMock.Verify(f => f.StopWebsite(websiteName, null), Times.Once()); } [TestMethod] public void StopsWebsiteSlot() { const string slot = "staging"; const string websiteName = "website1"; // Setup Mock<IWebsitesClient> websitesClientMock = new Mock<IWebsitesClient>(); websitesClientMock.Setup(f => f.StopWebsite(websiteName, slot)); // Test StopAzureWebsiteCommand stopAzureWebsiteCommand = new StopAzureWebsiteCommand() { CommandRuntime = new MockCommandRuntime(), Name = websiteName, CurrentSubscription = new WindowsAzureSubscription { SubscriptionId = base.subscriptionId }, WebsitesClient = websitesClientMock.Object, Slot = slot }; stopAzureWebsiteCommand.ExecuteCmdlet(); websitesClientMock.Verify(f => f.StopWebsite(websiteName, slot), Times.Once()); } } }
39.155844
109
0.595025
[ "MIT" ]
Milstein/azure-sdk-tools
WindowsAzurePowershell/src/Commands.Test/Websites/StopAzureWebSiteTests.cs
2,941
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DataFactory.Outputs { [OutputType] public sealed class RelationalSourceResponse { /// <summary> /// Specifies the additional columns to be added to source data. Type: array of objects (or Expression with resultType array of objects). /// </summary> public readonly ImmutableArray<Outputs.AdditionalColumnsResponse> AdditionalColumns; /// <summary> /// The maximum concurrent connection count for the source data store. Type: integer (or Expression with resultType integer). /// </summary> public readonly object? MaxConcurrentConnections; /// <summary> /// Database query. Type: string (or Expression with resultType string). /// </summary> public readonly object? Query; /// <summary> /// Source retry count. Type: integer (or Expression with resultType integer). /// </summary> public readonly object? SourceRetryCount; /// <summary> /// Source retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> public readonly object? SourceRetryWait; /// <summary> /// Copy source type. /// Expected value is 'RelationalSource'. /// </summary> public readonly string Type; [OutputConstructor] private RelationalSourceResponse( ImmutableArray<Outputs.AdditionalColumnsResponse> additionalColumns, object? maxConcurrentConnections, object? query, object? sourceRetryCount, object? sourceRetryWait, string type) { AdditionalColumns = additionalColumns; MaxConcurrentConnections = maxConcurrentConnections; Query = query; SourceRetryCount = sourceRetryCount; SourceRetryWait = sourceRetryWait; Type = type; } } }
35.630769
146
0.629965
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DataFactory/Outputs/RelationalSourceResponse.cs
2,316
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.AspNetCore.Mvc { public class HttpOkObjectResultTest { public static TheoryData<object> ValuesData { get { return new TheoryData<object> { null, "Test string", new Person { Id = 274, Name = "George", } }; } } [Theory] [MemberData(nameof(ValuesData))] public void HttpOkObjectResult_InitializesStatusCodeAndValue(object value) { // Arrange & Act var result = new OkObjectResult(value); // Assert Assert.Equal(StatusCodes.Status200OK, result.StatusCode); Assert.Same(value, result.Value); } [Theory] [MemberData(nameof(ValuesData))] public async Task HttpOkObjectResult_SetsStatusCode(object value) { // Arrange var result = new OkObjectResult(value); var httpContext = new DefaultHttpContext { RequestServices = CreateServices(), }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); // Act await result.ExecuteResultAsync(actionContext); // Assert Assert.Equal(StatusCodes.Status200OK, httpContext.Response.StatusCode); } private static IServiceProvider CreateServices() { var options = Options.Create(new MvcOptions()); options.Value.OutputFormatters.Add(new StringOutputFormatter()); options.Value.OutputFormatters.Add(new SystemTextJsonOutputFormatter(new JsonOptions())); var services = new ServiceCollection(); services.AddSingleton<IActionResultExecutor<ObjectResult>>(new ObjectResultExecutor( new DefaultOutputFormatterSelector(options, NullLoggerFactory.Instance), new TestHttpResponseStreamWriterFactory(), NullLoggerFactory.Instance, options)); return services.BuildServiceProvider(); } private class Person { public int Id { get; set; } public string Name { get; set; } } } }
32
111
0.59879
[ "Apache-2.0" ]
303248153/AspNetCore
src/Mvc/Mvc.Core/test/HttpOkObjectResultTest.cs
2,976
C#
using System.Linq; using System.Threading.Tasks; using EncompassApi.Loans; using EncompassApi.Loans.Enums; using EncompassApi.Loans.Milestones; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EncompassApi.Tests { [TestClass] public class LoanAssociateMilestoneTests : TestBaseClass { [TestMethod] [ApiTest] public async Task LoanAssociatesMilestones() { var client = await GetTestClientAsync(); var loanId = await client.Loans.CreateLoanAsync(new Loan(client)); try { var loanApis = client.Loans.GetLoanApis(loanId); var associates = await loanApis.Associates.GetAssociatesAsync(); foreach (var associate in associates) { AssertNoExtensionData(associate, "Associate", associate.Id, true); } var milestones = await loanApis.Milestones.GetMilestonesAsync(); foreach (var milestone in milestones) { AssertNoExtensionData(milestone, "Milestone", milestone.MilestoneName, true); var retrievedMilestone = await loanApis.Milestones.GetMilestoneAsync(milestone.Id); Assert.AreEqual(milestone.ToString(), retrievedMilestone.ToString()); } var milestoneFreeRoles = await loanApis.MilestoneFreeRoles.GetMilestoneFreeRolesAsync(); foreach (var milestoneFreeRole in milestoneFreeRoles) { AssertNoExtensionData(milestoneFreeRole, "MilestoneFreeRole", milestoneFreeRole.Id, true); var retrievedMilestoneFreeRole = await loanApis.MilestoneFreeRoles.GetMilestoneFreeRoleAsync(milestoneFreeRole.Id); Assert.AreEqual(milestoneFreeRole.ToString(), retrievedMilestoneFreeRole.ToString()); } } finally { try { await Task.Delay(5000); await client.Loans.DeleteLoanAsync(loanId); } catch { } } } // [TestMethod] // [ApiTest] // public async Task LoanMilestonesFinish() // { // var client = await GetTestClientAsync(); // if (client.AccessToken.Token == "Token") // { // var loanId = await client.Loans.CreateLoanAsync(new Loan(client)); // try // { // var loanApis = client.Loans.GetLoanApis(loanId); // var milestonesApi = loanApis.Milestones; // var milestones = await milestonesApi.GetMilestonesAsync(); // var milestone = milestones.First(ms => ms.DoneIndicator != true); // // Assign user to milestones // var userId = "officer"; // await loanApis.Associates.AssignAssociateAsync(milestone.Id, new LoanAssociate(userId, LoanAssociateType.User)); // milestones = await milestonesApi.GetMilestonesAsync(); // milestone = milestones.First(ms => ms.Id == milestone.Id); // Assert.AreEqual(milestone.LoanAssociate.Id, userId); // userId = "opener"; // var nextMilestone = milestones.Where(ms => ms.DoneIndicator != true).Skip(1).First(); // await loanApis.Associates.AssignAssociateAsync(nextMilestone.Id, new LoanAssociate(userId, LoanAssociateType.User)); // milestones = await milestonesApi.GetMilestonesAsync(); // nextMilestone = milestones.First(ms => ms.Id == nextMilestone.Id); // Assert.AreEqual(nextMilestone.LoanAssociate.Id, userId); // await milestonesApi.UpdateMilestoneAsync(milestone, MilestoneAction.Finish); // milestones = await milestonesApi.GetMilestonesAsync(); // milestone = milestones.First(ms => ms.Id == milestone.Id); // Assert.IsTrue(milestone.DoneIndicator == true); // await milestonesApi.UpdateMilestoneAsync(milestone, MilestoneAction.Unfinish); // milestones = await milestonesApi.GetMilestonesAsync(); // milestone = milestones.First(ms => ms.Id == milestone.Id); // Assert.IsFalse(milestone.DoneIndicator == true); // // Test unassigning user //#pragma warning disable CS0618 // Type or member is obsolete // await loanApis.Associates.UnassignAssociateAsync(nextMilestone.Id); //#pragma warning restore CS0618 // Type or member is obsolete // milestones = await milestonesApi.GetMilestonesAsync(); // nextMilestone = milestones.First(ms => ms.Id == nextMilestone.Id); // Assert.IsNull(nextMilestone.LoanAssociate.Id); // } // finally // { // try // { // await Task.Delay(5000); // await client.Loans.DeleteLoanAsync(loanId); // } // catch // { // } // } // } // } [TestMethod] [ApiTest] public async Task LoanMilestoneComments() { var client = await GetTestClientAsync(); var loanId = await client.Loans.CreateLoanAsync(new Loan(client)); try { var loanApis = client.Loans.GetLoanApis(loanId); var milestone = (await loanApis.Milestones.GetMilestonesAsync()).ElementAt(1); const string comments = "This is a test comment"; milestone.Comments = comments; await loanApis.Milestones.UpdateMilestoneAsync(milestone); var retrievedMilestone = await loanApis.Milestones.GetMilestoneAsync(milestone.Id); Assert.AreEqual(comments, retrievedMilestone.Comments); Assert.AreEqual(milestone.ToString(), retrievedMilestone.ToString()); } finally { try { await client.Loans.DeleteLoanAsync(loanId); } catch { } } } } }
43.417219
138
0.54637
[ "MIT" ]
fairwayindependentmc/EncompassApi
src/EncompassApi.Tests/LoanAssociateMilestoneTests.cs
6,558
C#
using System; using System.Text; namespace gcl2 { /// <summary> /// Represents both a production and a current read index. /// </summary> public class Element { public Production Production { get; private set; } public int ReadIndex { get; private set; } /// <summary> /// Returns the symbol being read by the read index. /// </summary> public Symbol ReadSymbol { get { return Production.Product[ReadIndex]; } } /// <summary> /// Returns true if the product reading is completed. /// </summary> public bool ReadCompleted { get { return ReadIndex == Production.Product.Count; } } /// <summary> /// Creates an element with the default read index of 0. /// </summary> /// <param name="production">Production to base this element on.</param> public Element(Production production) : this(production, 0) { } /// <summary> /// Returns true if the product reading is completed. /// </summary> /// <param name="production">Production to base this element on.</param> /// <param name="readIndex">Specific reading index.</param> public Element(Production production, int readIndex) { if (production == null) throw new ArgumentNullException(); Production = production; ReadIndex = readIndex; } /// <summary> /// /// </summary> /// <returns></returns> public Element Read() { if (ReadCompleted == false) return new Element(Production, ReadIndex + 1); return new Element(Production, 0); } public override int GetHashCode() { var code = ReadIndex; if (Production != null) code += Production.GetHashCode(); return code; } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (obj == null || (obj is Element) == false) return false; var otherElement = (obj as Element); if (Production == null || otherElement.Production == null) return false; return ReadIndex == otherElement.ReadIndex && Production == otherElement.Production; } public override string ToString() { var prod = Production.ToString(); var left = new StringBuilder(); var right = new StringBuilder(); for (var i = 0; i < Production.Product.Count; i++) { if (i < ReadIndex) left.Append(Production.Product[i]); else right.Append(Production.Product[i]); } return string.Format("{0} -> {1}●{2}", Production.Producer, left, right); ; } public static bool operator ==(Element e1, Element e2) { if ((object)e1 == null || (object)e2 == null) return false; return e1.Equals(e2); } public static bool operator !=(Element e1, Element e2) { return !(e1 == e2); } } }
29.401709
96
0.504651
[ "MIT" ]
Isracg/GCL
gcl2/Element.cs
3,444
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ordering.Application.Exceptions { public class NotFoundException : ApplicationException { public NotFoundException(string name, object Key) : base($"Entity \"{name}\" ({Key}) was not found.") { } } }
22.75
109
0.68956
[ "MIT" ]
SRICHARANSIRPA/Microservices
src/Services/Ordering/Ordering.Application/Exceptions/NotFoundException.cs
366
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Xml.Linq; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Protocol; using NuGet.Protocol.Core.Types; using NuGet.Versioning; namespace NuGet.Test.Utility { public class V3PackageSearchMetadataFixture : IDisposable { private bool _disposedValue = false; // To detect redundant calls public IPackageSearchMetadata TestData { get; private set; } public V3PackageSearchMetadataFixture() { TestData = new MockPackageSearchMetadata() { Vulnerabilities = new List<PackageVulnerabilityMetadata>() { new PackageVulnerabilityMetadata() { AdvisoryUrl = new Uri("https://example/advisory/ABCD-1234-5678-9012"), Severity = 2 }, new PackageVulnerabilityMetadata() { AdvisoryUrl = new Uri("https://example/advisory/ABCD-1234-5678-3535"), Severity = 3 } } }; } protected virtual void Dispose(bool disposing) { if (!_disposedValue) { TestData = null; _disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } public class MockPackageSearchMetadata : IPackageSearchMetadata { public MockPackageSearchMetadata() { Identity = new PackageIdentity("nuget.psm.test", new NuGetVersion(0, 0, 1)); } public string Authors => string.Empty; public IEnumerable<PackageDependencyGroup> DependencySets => null; public string Description => string.Empty; public long? DownloadCount => 100L; public Uri IconUrl => null; public PackageIdentity Identity { get; set; } public Uri ReadmeUrl => null; public Uri LicenseUrl => null; public Uri ProjectUrl => null; public Uri ReportAbuseUrl => null; public Uri PackageDetailsUrl => null; public string PackagePath => null; public DateTimeOffset? Published => DateTimeOffset.Now; public string Owners => string.Empty; public bool RequireLicenseAcceptance => false; public string Summary => string.Empty; public string Tags => null; public string Title => "title"; public bool IsListed => true; public bool PrefixReserved => false; public LicenseMetadata LicenseMetadata => null; public Task<PackageDeprecationMetadata> GetDeprecationMetadataAsync() => Task.FromResult<PackageDeprecationMetadata>(null); public Task<IEnumerable<VersionInfo>> GetVersionsAsync() { throw new NotImplementedException(); } public IEnumerable<PackageVulnerabilityMetadata> Vulnerabilities { get; set; } } } }
30.401709
135
0.57914
[ "Apache-2.0" ]
AntonC9018/NuGet.Client
test/TestUtilities/Test.Utility/Protocol/V3PackageSearchMetadataFixture.cs
3,557
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WebAssemblyDotNETTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebAssemblyDotNETTests")] [assembly: AssemblyCopyright("Copyright © Patrick Demian 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bd071f8d-c892-4fc2-9c4f-7cce77a895e4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.675676
84
0.750524
[ "MIT" ]
pdemian/WebAssemblyDotNET
WebAssemblyDotNETTests/Properties/AssemblyInfo.cs
1,434
C#
// // NWPath.cs: Bindings the Netowrk nw_path_t API. // // Authors: // Miguel de Icaza ([email protected]) // // Copyrigh 2018 Microsoft Inc // #nullable enable using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using ObjCRuntime; using Foundation; using CoreFoundation; namespace Network { [TV (12,0), Mac (10,14), iOS (12,0)] [Watch (6,0)] public class NWPath : NativeObject { public NWPath (IntPtr handle, bool owns) : base (handle, owns) {} [DllImport (Constants.NetworkLibrary)] extern static NWPathStatus nw_path_get_status (IntPtr handle); public NWPathStatus Status => nw_path_get_status (GetCheckedHandle ()); [DllImport (Constants.NetworkLibrary)] [return: MarshalAs(UnmanagedType.U1)] extern static bool nw_path_is_expensive (IntPtr handle); public bool IsExpensive => nw_path_is_expensive (GetCheckedHandle ()); [DllImport (Constants.NetworkLibrary)] [return: MarshalAs(UnmanagedType.U1)] extern static bool nw_path_has_ipv4 (IntPtr handle); public bool HasIPV4 => nw_path_has_ipv4 (GetCheckedHandle ()); [DllImport (Constants.NetworkLibrary)] [return: MarshalAs(UnmanagedType.U1)] extern static bool nw_path_has_ipv6 (IntPtr handle); public bool HasIPV6 => nw_path_has_ipv6 (GetCheckedHandle ()); [DllImport (Constants.NetworkLibrary)] [return: MarshalAs(UnmanagedType.U1)] extern static bool nw_path_has_dns (IntPtr handle); public bool HasDns => nw_path_has_dns (GetCheckedHandle ()); [DllImport (Constants.NetworkLibrary)] [return: MarshalAs(UnmanagedType.U1)] extern static bool nw_path_uses_interface_type (IntPtr handle, NWInterfaceType type); public bool UsesInterfaceType (NWInterfaceType type) => nw_path_uses_interface_type (GetCheckedHandle (), type); [DllImport (Constants.NetworkLibrary)] extern static IntPtr nw_path_copy_effective_local_endpoint (IntPtr handle); public NWEndpoint? EffectiveLocalEndpoint { get { var x = nw_path_copy_effective_local_endpoint (GetCheckedHandle ()); if (x == IntPtr.Zero) return null; return new NWEndpoint (x, owns: true); } } [DllImport (Constants.NetworkLibrary)] extern static IntPtr nw_path_copy_effective_remote_endpoint (IntPtr handle); public NWEndpoint? EffectiveRemoteEndpoint { get { var x = nw_path_copy_effective_remote_endpoint (GetCheckedHandle ()); if (x == IntPtr.Zero) return null; return new NWEndpoint (x, owns: true); } } [DllImport (Constants.NetworkLibrary)] [return: MarshalAs(UnmanagedType.U1)] extern static bool nw_path_is_equal (IntPtr p1, IntPtr p2); public bool EqualsTo (NWPath other) { if (other == null) return false; return nw_path_is_equal (GetCheckedHandle (), other.Handle); } delegate void nw_path_enumerate_interfaces_block_t (IntPtr block, IntPtr iface); static nw_path_enumerate_interfaces_block_t static_Enumerator = TrampolineEnumerator; [MonoPInvokeCallback (typeof (nw_path_enumerate_interfaces_block_t))] static void TrampolineEnumerator (IntPtr block, IntPtr iface) { var del = BlockLiteral.GetTarget<Action<NWInterface>> (block); if (del != null) del (new NWInterface (iface, owns: false)); } [DllImport (Constants.NetworkLibrary)] static extern void nw_path_enumerate_interfaces (IntPtr handle, ref BlockLiteral callback); [BindingImpl (BindingImplOptions.Optimizable)] public void EnumerateInterfaces (Action<NWInterface> callback) { if (callback == null) return; BlockLiteral block_handler = new BlockLiteral (); block_handler.SetupBlockUnsafe (static_Enumerator, callback); try { nw_path_enumerate_interfaces (GetCheckedHandle (), ref block_handler); } finally { block_handler.CleanupBlock (); } } [TV (13,0), Mac (10,15), iOS (13,0)] [DllImport (Constants.NetworkLibrary)] [return: MarshalAs (UnmanagedType.I1)] static extern bool nw_path_is_constrained (IntPtr path); [TV (13,0), Mac (10,15), iOS (13,0)] public bool IsConstrained => nw_path_is_constrained (GetCheckedHandle ()); [TV (13,0), Mac (10,15), iOS (13,0)] [DllImport (Constants.NetworkLibrary)] static extern void nw_path_enumerate_gateways (IntPtr path, ref BlockLiteral enumerate_block); delegate void nw_path_enumerate_gateways_t (IntPtr block, IntPtr endpoint); static nw_path_enumerate_gateways_t static_EnumerateGatewaysHandler = TrampolineGatewaysHandler; [MonoPInvokeCallback (typeof (nw_path_enumerate_gateways_t))] static void TrampolineGatewaysHandler (IntPtr block, IntPtr endpoint) { var del = BlockLiteral.GetTarget<Action<NWEndpoint>> (block); if (del != null) { var nwEndpoint = new NWEndpoint (endpoint, owns: false); del (nwEndpoint); } } [TV (13,0), Mac (10,15), iOS (13,0)] [BindingImpl (BindingImplOptions.Optimizable)] public void EnumerateGateways (Action<NWEndpoint> callback) { if (callback == null) throw new ArgumentNullException (nameof (callback)); BlockLiteral block_handler = new BlockLiteral (); block_handler.SetupBlockUnsafe (static_Enumerator, callback); try { nw_path_enumerate_gateways (GetCheckedHandle (), ref block_handler); } finally { block_handler.CleanupBlock (); } } [iOS (14,2)][TV (14,2)][Watch (7,1)][Mac (11,0)] [DllImport (Constants.NetworkLibrary)] static extern NWPathUnsatisfiedReason /* nw_path_unsatisfied_reason_t */ nw_path_get_unsatisfied_reason (IntPtr /* OS_nw_path */ path); [iOS (14,2)][TV (14,2)][Watch (7,1)][Mac (11,0)] public NWPathUnsatisfiedReason GetUnsatisfiedReason () { return nw_path_get_unsatisfied_reason (GetCheckedHandle ()); } } }
31.511111
137
0.740656
[ "BSD-3-Clause" ]
gameloft/xamarin-macios
src/Network/NWPath.cs
5,672
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201 { using static Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Extensions; /// <summary>Parameters allowed to update for a server.</summary> public partial class ServerUpdateParameters : Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParameters, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal { /// <summary>The password of the administrator login.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public string AdministratorLoginPassword { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).AdministratorLoginPassword; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).AdministratorLoginPassword = value ?? null; } /// <summary>Backing field for <see cref="Identity" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentity _identity; /// <summary>The Azure Active Directory identity of the server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Owned)] internal Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ResourceIdentity()); set => this._identity = value; } /// <summary>The Azure Active Directory principal id.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentityInternal)Identity).PrincipalId; } /// <summary>The Azure Active Directory tenant id.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentityInternal)Identity).TenantId; } /// <summary> /// The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory /// principal for the resource. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.IdentityType? IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentityInternal)Identity).Type = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.IdentityType)""); } /// <summary>Internal Acessors for Identity</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentity Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ResourceIdentity()); set { {_identity = value;} } } /// <summary>Internal Acessors for IdentityPrincipalId</summary> string Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentityInternal)Identity).PrincipalId = value; } /// <summary>Internal Acessors for IdentityTenantId</summary> string Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentityInternal)Identity).TenantId = value; } /// <summary>Internal Acessors for Property</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersProperties Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParametersProperties()); set { {_property = value;} } } /// <summary>Internal Acessors for Sku</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISku Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal.Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.Sku()); set { {_sku = value;} } } /// <summary>Internal Acessors for StorageProfile</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IStorageProfile Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal.StorageProfile { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).StorageProfile; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).StorageProfile = value; } /// <summary>Enforce a minimal Tls version for the server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum? MinimalTlsVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).MinimalTlsVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).MinimalTlsVersion = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum)""); } /// <summary>Backing field for <see cref="Property" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersProperties _property; /// <summary>The properties that can be updated for a server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Owned)] internal Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParametersProperties()); set => this._property = value; } /// <summary> /// Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' /// or 'Disabled' /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum? PublicNetworkAccess { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).PublicNetworkAccess; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).PublicNetworkAccess = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum)""); } /// <summary>The replication role of the server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public string ReplicationRole { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).ReplicationRole; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).ReplicationRole = value ?? null; } /// <summary>Backing field for <see cref="Sku" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISku _sku; /// <summary>The SKU (pricing tier) of the server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Owned)] internal Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISku Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.Sku()); set => this._sku = value; } /// <summary>The scale up/out capacity, representing server's compute units.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public int? SkuCapacity { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISkuInternal)Sku).Capacity; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISkuInternal)Sku).Capacity = value ?? default(int); } /// <summary>The family of hardware.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public string SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISkuInternal)Sku).Family; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISkuInternal)Sku).Family = value ?? null; } /// <summary> /// The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public string SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISkuInternal)Sku).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISkuInternal)Sku).Name = value ?? null; } /// <summary>The size code, to be interpreted by resource as appropriate.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public string SkuSize { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISkuInternal)Sku).Size; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISkuInternal)Sku).Size = value ?? null; } /// <summary>The tier of the particular SKU, e.g. Basic.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SkuTier? SkuTier { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISkuInternal)Sku).Tier; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISkuInternal)Sku).Tier = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SkuTier)""); } /// <summary>Enable ssl enforcement or not when connect to server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum? SslEnforcement { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).SslEnforcement; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).SslEnforcement = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum)""); } /// <summary>Backup retention days for the server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public int? StorageProfileBackupRetentionDay { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).StorageProfileBackupRetentionDay; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).StorageProfileBackupRetentionDay = value ?? default(int); } /// <summary>Enable Geo-redundant or not for server backup.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup? StorageProfileGeoRedundantBackup { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).StorageProfileGeoRedundantBackup; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).StorageProfileGeoRedundantBackup = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup)""); } /// <summary>Enable Storage Auto Grow.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow? StorageProfileStorageAutogrow { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).StorageProfileStorageAutogrow; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).StorageProfileStorageAutogrow = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow)""); } /// <summary>Max storage allowed for a server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public int? StorageProfileStorageMb { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).StorageProfileStorageMb; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).StorageProfileStorageMb = value ?? default(int); } /// <summary>Backing field for <see cref="Tag" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersTags _tag; /// <summary>Application-specific metadata in the form of key-value pairs.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Owned)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParametersTags()); set => this._tag = value; } /// <summary>The version of a server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion? Version { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).Version; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersPropertiesInternal)Property).Version = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion)""); } /// <summary>Creates an new <see cref="ServerUpdateParameters" /> instance.</summary> public ServerUpdateParameters() { } } /// Parameters allowed to update for a server. public partial interface IServerUpdateParameters : Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IJsonSerializable { /// <summary>The password of the administrator login.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"The password of the administrator login.", SerializedName = @"administratorLoginPassword", PossibleTypes = new [] { typeof(string) })] string AdministratorLoginPassword { get; set; } /// <summary>The Azure Active Directory principal id.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = true, Description = @"The Azure Active Directory principal id.", SerializedName = @"principalId", PossibleTypes = new [] { typeof(string) })] string IdentityPrincipalId { get; } /// <summary>The Azure Active Directory tenant id.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = true, Description = @"The Azure Active Directory tenant id.", SerializedName = @"tenantId", PossibleTypes = new [] { typeof(string) })] string IdentityTenantId { get; } /// <summary> /// The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory /// principal for the resource. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource.", SerializedName = @"type", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.IdentityType) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.IdentityType? IdentityType { get; set; } /// <summary>Enforce a minimal Tls version for the server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"Enforce a minimal Tls version for the server.", SerializedName = @"minimalTlsVersion", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum? MinimalTlsVersion { get; set; } /// <summary> /// Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' /// or 'Disabled' /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'", SerializedName = @"publicNetworkAccess", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum? PublicNetworkAccess { get; set; } /// <summary>The replication role of the server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"The replication role of the server.", SerializedName = @"replicationRole", PossibleTypes = new [] { typeof(string) })] string ReplicationRole { get; set; } /// <summary>The scale up/out capacity, representing server's compute units.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"The scale up/out capacity, representing server's compute units.", SerializedName = @"capacity", PossibleTypes = new [] { typeof(int) })] int? SkuCapacity { get; set; } /// <summary>The family of hardware.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"The family of hardware.", SerializedName = @"family", PossibleTypes = new [] { typeof(string) })] string SkuFamily { get; set; } /// <summary> /// The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8.", SerializedName = @"name", PossibleTypes = new [] { typeof(string) })] string SkuName { get; set; } /// <summary>The size code, to be interpreted by resource as appropriate.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"The size code, to be interpreted by resource as appropriate.", SerializedName = @"size", PossibleTypes = new [] { typeof(string) })] string SkuSize { get; set; } /// <summary>The tier of the particular SKU, e.g. Basic.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"The tier of the particular SKU, e.g. Basic.", SerializedName = @"tier", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SkuTier) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SkuTier? SkuTier { get; set; } /// <summary>Enable ssl enforcement or not when connect to server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"Enable ssl enforcement or not when connect to server.", SerializedName = @"sslEnforcement", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum? SslEnforcement { get; set; } /// <summary>Backup retention days for the server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"Backup retention days for the server.", SerializedName = @"backupRetentionDays", PossibleTypes = new [] { typeof(int) })] int? StorageProfileBackupRetentionDay { get; set; } /// <summary>Enable Geo-redundant or not for server backup.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"Enable Geo-redundant or not for server backup.", SerializedName = @"geoRedundantBackup", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup? StorageProfileGeoRedundantBackup { get; set; } /// <summary>Enable Storage Auto Grow.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"Enable Storage Auto Grow.", SerializedName = @"storageAutogrow", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow? StorageProfileStorageAutogrow { get; set; } /// <summary>Max storage allowed for a server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"Max storage allowed for a server.", SerializedName = @"storageMB", PossibleTypes = new [] { typeof(int) })] int? StorageProfileStorageMb { get; set; } /// <summary>Application-specific metadata in the form of key-value pairs.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"Application-specific metadata in the form of key-value pairs.", SerializedName = @"tags", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersTags) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersTags Tag { get; set; } /// <summary>The version of a server.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"The version of a server.", SerializedName = @"version", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion? Version { get; set; } } /// Parameters allowed to update for a server. internal partial interface IServerUpdateParametersInternal { /// <summary>The password of the administrator login.</summary> string AdministratorLoginPassword { get; set; } /// <summary>The Azure Active Directory identity of the server.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentity Identity { get; set; } /// <summary>The Azure Active Directory principal id.</summary> string IdentityPrincipalId { get; set; } /// <summary>The Azure Active Directory tenant id.</summary> string IdentityTenantId { get; set; } /// <summary> /// The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory /// principal for the resource. /// </summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.IdentityType? IdentityType { get; set; } /// <summary>Enforce a minimal Tls version for the server.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum? MinimalTlsVersion { get; set; } /// <summary>The properties that can be updated for a server.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersProperties Property { get; set; } /// <summary> /// Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' /// or 'Disabled' /// </summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum? PublicNetworkAccess { get; set; } /// <summary>The replication role of the server.</summary> string ReplicationRole { get; set; } /// <summary>The SKU (pricing tier) of the server.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISku Sku { get; set; } /// <summary>The scale up/out capacity, representing server's compute units.</summary> int? SkuCapacity { get; set; } /// <summary>The family of hardware.</summary> string SkuFamily { get; set; } /// <summary> /// The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8. /// </summary> string SkuName { get; set; } /// <summary>The size code, to be interpreted by resource as appropriate.</summary> string SkuSize { get; set; } /// <summary>The tier of the particular SKU, e.g. Basic.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SkuTier? SkuTier { get; set; } /// <summary>Enable ssl enforcement or not when connect to server.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum? SslEnforcement { get; set; } /// <summary>Storage profile of a server.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IStorageProfile StorageProfile { get; set; } /// <summary>Backup retention days for the server.</summary> int? StorageProfileBackupRetentionDay { get; set; } /// <summary>Enable Geo-redundant or not for server backup.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup? StorageProfileGeoRedundantBackup { get; set; } /// <summary>Enable Storage Auto Grow.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow? StorageProfileStorageAutogrow { get; set; } /// <summary>Max storage allowed for a server.</summary> int? StorageProfileStorageMb { get; set; } /// <summary>Application-specific metadata in the form of key-value pairs.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersTags Tag { get; set; } /// <summary>The version of a server.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion? Version { get; set; } } }
81.04878
516
0.718093
[ "MIT" ]
3quanfeng/azure-powershell
src/MySql/generated/api/Models/Api20171201/ServerUpdateParameters.cs
29,539
C#
//Author Maxim Kuzmin//makc// using Makc2020.Core.Base.Resources.Errors; using Makc2020.Host.Base.Parts.Auth.Jobs.CurrentUser.Get; using Makc2020.Host.Base.Parts.Auth.Jobs.Seed; using Makc2020.Host.Base.Parts.Auth.Jobs.UserEntity.Create; using Makc2020.Host.Base.Parts.Auth.Resources.Errors; using Makc2020.Host.Base.Parts.Auth.Resources.Successes; namespace Makc2020.Host.Base.Parts.Auth { /// <summary> /// Хост. Основа. Часть "Auth". Задания. /// </summary> public class HostBasePartAuthJobs { #region Properties /// <summary> /// Задание на получение текущего пользователя. /// </summary> public HostBasePartAuthJobCurrentUserGetService JobCurrentUserGet { get; private set; } /// <summary> /// Задание на посев. /// </summary> public HostBasePartAuthJobSeedService JobSeed { get; private set; } /// <summary> /// Задание на создание сущности пользователя. /// </summary> public HostBasePartAuthJobUserEntityCreateService JobUserEntityCreate { get; private set; } #endregion Properties #region Constructor /// <summary> /// Конструктор. /// </summary> /// <param name="coreBaseResourceErrors">Ядро. Основа. Ресурсы. Ошибки.</param> /// <param name="resourceSuccesses">Ресурсы. Успехи.</param> /// <param name="resourceErrors">Ресурсы. Ошибки.</param> /// <param name="service">Сервис.</param> public HostBasePartAuthJobs( CoreBaseResourceErrors coreBaseResourceErrors, HostBasePartAuthResourceSuccesses resourceSuccesses, HostBasePartAuthResourceErrors resourceErrors, HostBasePartAuthService service ) { JobCurrentUserGet = new HostBasePartAuthJobCurrentUserGetService( service.GetCurrentUser, coreBaseResourceErrors, resourceSuccesses, resourceErrors ); JobSeed = new HostBasePartAuthJobSeedService( service.Seed, coreBaseResourceErrors, resourceErrors ); JobUserEntityCreate = new HostBasePartAuthJobUserEntityCreateService( service.CreateUserEntity, coreBaseResourceErrors, resourceSuccesses, resourceErrors ); } #endregion Constructor } }
33.052632
99
0.619825
[ "MIT" ]
balkar20/SibTrain
net-core/Makc2020.Host.Base/Parts/Auth/HostBasePartAuthJobs.cs
2,691
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2020-05-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for NoSuchCloudFrontOriginAccessIdentityException operation /// </summary> public class NoSuchCloudFrontOriginAccessIdentityExceptionUnmarshaller : IErrorResponseUnmarshaller<NoSuchCloudFrontOriginAccessIdentityException, XmlUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public NoSuchCloudFrontOriginAccessIdentityException Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public NoSuchCloudFrontOriginAccessIdentityException Unmarshall(XmlUnmarshallerContext context, ErrorResponse errorResponse) { NoSuchCloudFrontOriginAccessIdentityException response = new NoSuchCloudFrontOriginAccessIdentityException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { } } return response; } private static NoSuchCloudFrontOriginAccessIdentityExceptionUnmarshaller _instance = new NoSuchCloudFrontOriginAccessIdentityExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static NoSuchCloudFrontOriginAccessIdentityExceptionUnmarshaller Instance { get { return _instance; } } } }
37.26506
174
0.685742
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/NoSuchCloudFrontOriginAccessIdentityExceptionUnmarshaller.cs
3,093
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Microsoft.EntityFrameworkCore.Query.Pipeline { public static class EntityQueryableExtensions { public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>( this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<TOuter, TInner, TResult>> resultSelector) { throw new NotImplementedException(); } } }
33.958333
111
0.694479
[ "Apache-2.0" ]
Wrank/EntityFrameworkCore
src/EFCore/Query/Pipeline/EntityQueryableExtensions.cs
817
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace WealthManager.Server.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [IgnoreAntiforgeryToken] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
25.787879
88
0.686251
[ "MIT" ]
ranjithvj/wealth-manager
WealthManager/Server/Pages/Error.cshtml.cs
853
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Francesco Crimi [email protected] using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Runtime.Serialization; namespace CiccioSoft.Collections.Generic { [Serializable] [DebuggerTypeProxy(typeof(CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class CiccioList<T> : Collection<T>, IBindingList, IRaiseItemChangedEvents, INotifyCollectionChanged, INotifyPropertyChanged, IReadOnlyList<T> { private SimpleMonitor _monitor; [NonSerialized] private int _blockReentrancyCount; private bool raiseItemChangedEvents; // Do not rename (binary serialization) [NonSerialized] private PropertyDescriptorCollection _itemTypeProperties; [NonSerialized] private PropertyChangedEventHandler _propertyChangedEventHandler; [NonSerialized] private ListChangedEventHandler _onListChanged; [NonSerialized] private int _lastChangeIndex = -1; #region Constructors public CiccioList() : base() { Initialize(); } //public CiccioList(IList<T> list) : base(list) { Initialize(); } public CiccioList(IEnumerable<T> collection) : base(new List<T>(collection)) { Initialize(); } public CiccioList(int capacity) : base(new List<T>(capacity)) { Initialize(); } private void Initialize() { if (typeof(INotifyPropertyChanged).IsAssignableFrom(typeof(T))) { raiseItemChangedEvents = true; foreach (T item in Items) { HookPropertyChanged(item); } } } #endregion #region Collection<T> overrides protected override void ClearItems() { CheckReentrancy(); if (raiseItemChangedEvents) { foreach (T item in Items) { UnhookPropertyChanged(item); } } base.ClearItems(); OnCountPropertyChanged(); OnIndexerPropertyChanged(); OnCollectionReset(); FireListChanged(ListChangedType.Reset, -1); } protected override void InsertItem(int index, T item) { CheckReentrancy(); base.InsertItem(index, item); if (raiseItemChangedEvents) { HookPropertyChanged(item); } OnCountPropertyChanged(); OnIndexerPropertyChanged(); OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index); FireListChanged(ListChangedType.ItemAdded, index); } protected override void RemoveItem(int index) { CheckReentrancy(); if (raiseItemChangedEvents) { UnhookPropertyChanged(this[index]); } T removedItem = this[index]; base.RemoveItem(index); OnCountPropertyChanged(); OnIndexerPropertyChanged(); OnCollectionChanged(NotifyCollectionChangedAction.Remove, removedItem, index); FireListChanged(ListChangedType.ItemDeleted, index); } protected override void SetItem(int index, T item) { CheckReentrancy(); if (raiseItemChangedEvents) { UnhookPropertyChanged(this[index]); } T originalItem = this[index]; base.SetItem(index, item); if (raiseItemChangedEvents) { HookPropertyChanged(item); } OnIndexerPropertyChanged(); OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index); FireListChanged(ListChangedType.ItemChanged, index); } #endregion Collection<T> overrides #region INotifyPropertyChanged [field: NonSerialized] protected virtual event PropertyChangedEventHandler PropertyChanged; event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add => PropertyChanged += value; remove => PropertyChanged -= value; } protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } private void OnCountPropertyChanged() => OnPropertyChanged(EventArgsCache.CountPropertyChanged); private void OnIndexerPropertyChanged() => OnPropertyChanged(EventArgsCache.IndexerPropertyChanged); #endregion #region INotifyCollectionChanged [field: NonSerialized] public virtual event NotifyCollectionChangedEventHandler CollectionChanged; protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { NotifyCollectionChangedEventHandler handler = CollectionChanged; if (handler != null) { // Not calling BlockReentrancy() here to avoid the SimpleMonitor allocation. _blockReentrancyCount++; try { handler(this, e); } finally { _blockReentrancyCount--; } } } protected IDisposable BlockReentrancy() { _blockReentrancyCount++; return EnsureMonitorInitialized(); } protected void CheckReentrancy() { if (_blockReentrancyCount > 0) { if (CollectionChanged?.GetInvocationList().Length > 1) throw new InvalidOperationException("ObservableCollection Reentrancy Not Allowed"); } } private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index)); } private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index)); } private void OnCollectionReset() => OnCollectionChanged(EventArgsCache.ResetCollectionChanged); private SimpleMonitor EnsureMonitorInitialized() { return _monitor ?? (_monitor = new SimpleMonitor(this)); } #endregion #region ListChanged event public event ListChangedEventHandler ListChanged { add => _onListChanged += value; remove => _onListChanged -= value; } protected virtual void OnListChanged(ListChangedEventArgs e) => _onListChanged?.Invoke(this, e); private void ResetBindings() => FireListChanged(ListChangedType.Reset, -1); private void FireListChanged(ListChangedType type, int index) { OnListChanged(new ListChangedEventArgs(type, index)); } #endregion #region Property Change Support private void HookPropertyChanged(T item) { if (item is INotifyPropertyChanged inpc) { if (_propertyChangedEventHandler == null) { _propertyChangedEventHandler = new PropertyChangedEventHandler(Child_PropertyChanged); } inpc.PropertyChanged += _propertyChangedEventHandler; } } private void UnhookPropertyChanged(T item) { if (item is INotifyPropertyChanged inpc && _propertyChangedEventHandler != null) { inpc.PropertyChanged -= _propertyChangedEventHandler; } } private void Child_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (sender == null || e == null || string.IsNullOrEmpty(e.PropertyName)) { ResetBindings(); } else { T item; try { item = (T)sender; } catch (InvalidCastException) { ResetBindings(); return; } int pos = _lastChangeIndex; if (pos < 0 || pos >= Count || !this[pos].Equals(item)) { pos = IndexOf(item); _lastChangeIndex = pos; } if (pos == -1) { UnhookPropertyChanged(item); ResetBindings(); } else { if (null == _itemTypeProperties) { _itemTypeProperties = TypeDescriptor.GetProperties(typeof(T)); Debug.Assert(_itemTypeProperties != null); } PropertyDescriptor pd = _itemTypeProperties.Find(e.PropertyName, true); ListChangedEventArgs args = new ListChangedEventArgs(ListChangedType.ItemChanged, pos, pd); OnListChanged(args); } } } #endregion #region IBindingList object IBindingList.AddNew() => throw new NotSupportedException(); bool IBindingList.AllowNew => false; bool IBindingList.AllowEdit => true; bool IBindingList.AllowRemove => true; bool IBindingList.SupportsChangeNotification => true; bool IBindingList.SupportsSearching => false; bool IBindingList.SupportsSorting => false; bool IBindingList.IsSorted => false; PropertyDescriptor IBindingList.SortProperty => null; ListSortDirection IBindingList.SortDirection => ListSortDirection.Ascending; void IBindingList.ApplySort(PropertyDescriptor prop, ListSortDirection direction) { throw new NotSupportedException(); } void IBindingList.RemoveSort() { throw new NotSupportedException(); } int IBindingList.Find(PropertyDescriptor prop, object key) { throw new NotSupportedException(); } void IBindingList.AddIndex(PropertyDescriptor prop) { // Not supported } void IBindingList.RemoveIndex(PropertyDescriptor prop) { // Not supported } #endregion #region IRaiseItemChangedEvents bool IRaiseItemChangedEvents.RaisesItemChangedEvents => raiseItemChangedEvents; #endregion [OnSerializing] private void OnSerializing(StreamingContext context) { EnsureMonitorInitialized(); _monitor._busyCount = _blockReentrancyCount; } [OnDeserialized] private void OnDeserialized(StreamingContext context) { if (_monitor != null) { _blockReentrancyCount = _monitor._busyCount; _monitor._collection = this; } } [Serializable] private sealed class SimpleMonitor : IDisposable { internal int _busyCount; // Only used during (de)serialization to maintain compatibility with desktop. Do not rename (binary serialization) [NonSerialized] internal CiccioList<T> _collection; public SimpleMonitor(CiccioList<T> collection) { Debug.Assert(collection != null); _collection = collection; } public void Dispose() => _collection._blockReentrancyCount--; } public bool IsReadOnly => Items.IsReadOnly; } }
31.167513
153
0.580863
[ "MIT" ]
FrancescoCrimi/CiccioSoft.Collections
CiccioSoft.Collections/CiccioList.cs
12,282
C#
namespace bai_7 { class ClassHinhVuong : ClassHinhChuNhat { public ClassHinhVuong() : base() {} public ClassHinhVuong(double canh) : base(canh, canh) {} public override double ChieuDai { get => base.ChieuDai; set => base.ChieuDai = value; } public override double ChieuRong { get => base.ChieuDai; set => base.ChieuDai = value; } public override KieuHinh kieuDoiTuong() { return KieuHinh.HinhVuong; } } }
22.590909
61
0.60161
[ "Unlicense" ]
thuanpham2311/thuc-hanh-lap-trinh-huong-doi-tuong
bai_7/ClassHinhVuong.cs
499
C#
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using Sce.Sled.Lua.Dom; using Sce.Sled.Lua.Resources; using Sce.Sled.Shared.Scmp; namespace Sce.Sled.Lua.Scmp { internal enum LuaTypeCodes { LuaMemoryTraceBegin = 200, LuaMemoryTrace = 201, LuaMemoryTraceEnd = 202, LuaMemoryTraceStreamBegin = 203, LuaMemoryTraceStream = 204, LuaMemoryTraceStreamEnd = 205, LuaProfileInfoBegin = 207, LuaProfileInfo = 208, LuaProfileInfoEnd = 209, LuaProfileInfoLookupPerform = 210, LuaProfileInfoLookupBegin = 211, LuaProfileInfoLookup = 212, LuaProfileInfoLookupEnd = 213, LuaVarFilterStateTypeBegin = 214, LuaVarFilterStateType = 215, LuaVarFilterStateTypeEnd = 216, LuaVarFilterStateNameBegin = 217, LuaVarFilterStateName = 218, LuaVarFilterStateNameEnd = 219, LuaVarGlobalBegin = 220, LuaVarGlobal = 221, LuaVarGlobalEnd = 222, LuaVarGlobalLookupBegin = 223, LuaVarGlobalLookupEnd = 224, LuaVarLocalBegin = 230, LuaVarLocal = 231, LuaVarLocalEnd = 232, LuaVarLocalLookupBegin = 233, LuaVarLocalLookupEnd = 234, LuaVarUpvalueBegin = 240, LuaVarUpvalue = 241, LuaVarUpvalueEnd = 242, LuaVarUpvalueLookupBegin = 243, LuaVarUpvalueLookupEnd = 244, LuaVarEnvVarBegin = 250, LuaVarEnvVar = 251, LuaVarEnvVarEnd = 252, LuaVarEnvVarLookupBegin = 253, LuaVarEnvVarLookupEnd = 254, LuaVarLookUp = 255, LuaVarUpdate = 256, LuaCallStackBegin = 260, LuaCallStack = 261, LuaCallStackEnd = 262, LuaCallStackLookupPerform = 263, LuaCallStackLookupBegin = 264, LuaCallStackLookup = 265, LuaCallStackLookupEnd = 266, LuaWatchLookupBegin = 270, LuaWatchLookupEnd = 271, LuaWatchLookupClear = 272, LuaWatchLookupProjectBegin = 280, LuaWatchLookupProjectEnd = 281, LuaWatchLookupCustomBegin = 282, LuaWatchLookupCustomEnd = 283, LuaStateBegin = 290, LuaStateAdd = 291, LuaStateRemove = 292, LuaStateEnd = 293, LuaStateToggle = 294, LuaMemoryTraceToggle = 300, LuaProfilerToggle = 301, LuaLimits = 310, } [ScmpReceive] internal class LuaMemoryTraceBegin : Base { public LuaMemoryTraceBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaMemoryTraceBegin; } public LuaMemoryTraceBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaMemoryTrace : Base { public LuaMemoryTrace() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaMemoryTrace; } public LuaMemoryTrace(UInt16 iPluginid, char chWhat, string szOldPtr, string szNewPtr, Int32 iOldSize, Int32 iNewSize) : this() { PluginId = iPluginid; What = (Byte)chWhat; OldPtr = szOldPtr; NewPtr = szNewPtr; OldSize = iOldSize; NewSize = iNewSize; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); What = reader.ReadByte(); OldPtr = reader.ReadString(); NewPtr = reader.ReadString(); OldSize = reader.ReadInt32(); NewSize = reader.ReadInt32(); } public Byte What; public string OldPtr; public string NewPtr; public Int32 OldSize; public Int32 NewSize; } [ScmpReceive] internal class LuaMemoryTraceEnd : Base { public LuaMemoryTraceEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaMemoryTraceEnd; } public LuaMemoryTraceEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaMemoryTraceStreamBegin : Base { public LuaMemoryTraceStreamBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaMemoryTraceStreamBegin; } public LuaMemoryTraceStreamBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaMemoryTraceStream : Base { public LuaMemoryTraceStream() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaMemoryTraceStream; } public LuaMemoryTraceStream(UInt16 iPluginid, char chWhat, string szOldPtr, string szNewPtr, Int32 iOldSize, Int32 iNewSize) : this() { PluginId = iPluginid; What = (Byte)chWhat; OldPtr = szOldPtr; NewPtr = szNewPtr; OldSize = iOldSize; NewSize = iNewSize; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); What = reader.ReadByte(); OldPtr = reader.ReadString(); NewPtr = reader.ReadString(); OldSize = reader.ReadInt32(); NewSize = reader.ReadInt32(); } public Byte What; public string OldPtr; public string NewPtr; public Int32 OldSize; public Int32 NewSize; } [ScmpReceive] internal class LuaMemoryTraceStreamEnd : Base { public LuaMemoryTraceStreamEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaMemoryTraceStreamEnd; } public LuaMemoryTraceStreamEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaProfileInfoBegin : Base { public LuaProfileInfoBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaProfileInfoBegin; } public LuaProfileInfoBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaProfileInfo : Base { public LuaProfileInfo() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaProfileInfo; } public LuaProfileInfo(UInt16 iPluginid, string szFuncName, string szRelScriptPath, float flFnTimeElapsed, float flFnTimeElapsedAvg, float flFnTimeElapsedShortest, float flFnTimeElapsedLongest, float flFnTimeInnerElapsed, float flFnTimeInnerElapsedAvg, float flFnTimeInnerElapsedShortest, float flFnTimeInnerElapsedLongest, UInt32 iFnCallCount, Int32 iFnLine, Int32 iFnCalls) : this() { PluginId = iPluginid; FunctionName = szFuncName; RelScriptPath = szRelScriptPath; FnTimeElapsed = flFnTimeElapsed; FnTimeElapsedAvg = flFnTimeElapsedAvg; FnTimeElapsedShortest = flFnTimeElapsedShortest; FnTimeElapsedLongest = flFnTimeElapsedLongest; FnTimeInnerElapsed = flFnTimeInnerElapsed; FnTimeInnerElapsedAvg = flFnTimeInnerElapsedAvg; FnTimeInnerElapsedShortest = flFnTimeInnerElapsedShortest; FnTimeInnerElapsedLongest = flFnTimeInnerElapsedLongest; FnCallCount = iFnCallCount; FnLine = iFnLine; FnCalls = iFnCalls; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); FunctionName = reader.ReadString(); RelScriptPath = reader.ReadString(); FnTimeElapsed = reader.ReadFloat(); FnTimeElapsedAvg = reader.ReadFloat(); FnTimeElapsedShortest = reader.ReadFloat(); FnTimeElapsedLongest = reader.ReadFloat(); FnTimeInnerElapsed = reader.ReadFloat(); FnTimeInnerElapsedAvg = reader.ReadFloat(); FnTimeInnerElapsedShortest = reader.ReadFloat(); FnTimeInnerElapsedLongest = reader.ReadFloat(); FnCallCount = reader.ReadUInt32(); FnLine = reader.ReadInt32(); FnCalls = reader.ReadInt32(); } public string FunctionName; public string RelScriptPath; public float FnTimeElapsed; public float FnTimeElapsedAvg; public float FnTimeElapsedShortest; public float FnTimeElapsedLongest; public float FnTimeInnerElapsed; public float FnTimeInnerElapsedAvg; public float FnTimeInnerElapsedShortest; public float FnTimeInnerElapsedLongest; public UInt32 FnCallCount; public Int32 FnLine; public Int32 FnCalls; } [ScmpReceive] internal class LuaProfileInfoEnd : Base { public LuaProfileInfoEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaProfileInfoEnd; } public LuaProfileInfoEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpSend] internal class LuaProfileInfoLookupPerform : Base { public LuaProfileInfoLookupPerform() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaProfileInfoLookupPerform; } public LuaProfileInfoLookupPerform(UInt16 iPluginid, string szLookup) : this() { PluginId = iPluginid; var split = szLookup.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); FunctionName = split[0].Remove(0, 11); // Remove "{pi_lookup:" What = (Byte)((split[1])[0]); Line = Int32.Parse(split[2]); RelScriptPath = split[3].Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); RelScriptPath = RelScriptPath.Remove(RelScriptPath.Length - 1, 1); } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + (2 + Encoding.UTF8.GetBytes(FunctionName).Length) + 1 + 4 + (2 + Encoding.UTF8.GetBytes(RelScriptPath).Length)]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackString(FunctionName); packer.PackByte(What); packer.PackInt32(Line); packer.PackString(RelScriptPath); return buffer; } public string FunctionName; public Byte What; public Int32 Line; public string RelScriptPath; } [ScmpReceive] internal class LuaProfileInfoLookupBegin : Base { public LuaProfileInfoLookupBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaProfileInfoLookupBegin; } public LuaProfileInfoLookupBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaProfileInfoLookup : Base { public LuaProfileInfoLookup() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaProfileInfoLookup; } public LuaProfileInfoLookup(UInt16 iPluginid, string szFuncName, string szRelScriptPath, float flFnTimeElapsed, float flFnTimeElapsedAvg, float flFnTimeElapsedShortest, float flFnTimeElapsedLongest, float flFnTimeInnerElapsed, float flFnTimeInnerElapsedAvg, float flFnTimeInnerElapsedShortest, float flFnTimeInnerElapsedLongest, UInt32 iFnCallCount, Int32 iFnLine, Int32 iFnCalls) : this() { PluginId = iPluginid; FunctionName = szFuncName; RelScriptPath = szRelScriptPath; FnTimeElapsed = flFnTimeElapsed; FnTimeElapsedAvg = flFnTimeElapsedAvg; FnTimeElapsedShortest = flFnTimeElapsedShortest; FnTimeElapsedLongest = flFnTimeElapsedLongest; FnTimeInnerElapsed = flFnTimeInnerElapsed; FnTimeInnerElapsedAvg = flFnTimeInnerElapsedAvg; FnTimeInnerElapsedShortest = flFnTimeInnerElapsedShortest; FnTimeInnerElapsedLongest = flFnTimeInnerElapsedLongest; FnCallCount = iFnCallCount; FnLine = iFnLine; FnCalls = iFnCalls; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); FunctionName = reader.ReadString(); RelScriptPath = reader.ReadString(); FnTimeElapsed = reader.ReadFloat(); FnTimeElapsedAvg = reader.ReadFloat(); FnTimeElapsedShortest = reader.ReadFloat(); FnTimeElapsedLongest = reader.ReadFloat(); FnTimeInnerElapsed = reader.ReadFloat(); FnTimeInnerElapsedAvg = reader.ReadFloat(); FnTimeInnerElapsedShortest = reader.ReadFloat(); FnTimeInnerElapsedLongest = reader.ReadFloat(); FnCallCount = reader.ReadUInt32(); FnLine = reader.ReadInt32(); FnCalls = reader.ReadInt32(); } public string FunctionName; public string RelScriptPath; public float FnTimeElapsed; public float FnTimeElapsedAvg; public float FnTimeElapsedShortest; public float FnTimeElapsedLongest; public float FnTimeInnerElapsed; public float FnTimeInnerElapsedAvg; public float FnTimeInnerElapsedShortest; public float FnTimeInnerElapsedLongest; public UInt32 FnCallCount; public Int32 FnLine; public Int32 FnCalls; } [ScmpReceive] internal class LuaProfileInfoLookupEnd : Base { public LuaProfileInfoLookupEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaProfileInfoLookupEnd; } public LuaProfileInfoLookupEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpSend] internal class LuaVarFilterStateTypeBegin : Base { public LuaVarFilterStateTypeBegin() { Length = SizeOf + 1; TypeCode = (UInt16)LuaTypeCodes.LuaVarFilterStateTypeBegin; } public LuaVarFilterStateTypeBegin(UInt16 iPluginid, char chWhat) : this() { PluginId = iPluginid; What = (Byte)chWhat; } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + 1]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackByte(What); return buffer; } public Byte What; } [ScmpSend] internal class LuaVarFilterStateType : Base { public LuaVarFilterStateType() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarFilterStateType; } public LuaVarFilterStateType(UInt16 iPluginid, char chWhat, bool[] filter) : this() { PluginId = iPluginid; What = (Byte)chWhat; for (var i = 0; i < filter.Length; i++) Filter[i] = (Byte)(filter[i] ? 1 : 0); } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + 1 + 2 + 9]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackByte(What); packer.PackByteArray(Filter); return buffer; } public Byte What; public Byte[] Filter = new Byte[9]; } [ScmpSend] internal class LuaVarFilterStateTypeEnd : Base { public LuaVarFilterStateTypeEnd() { Length = SizeOf + 1; TypeCode = (UInt16)LuaTypeCodes.LuaVarFilterStateTypeEnd; } public LuaVarFilterStateTypeEnd(UInt16 iPluginid, char chWhat) : this() { PluginId = iPluginid; What = (Byte)chWhat; } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + 1]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackByte(What); return buffer; } public Byte What; } [ScmpSend] internal class LuaVarFilterStateNameBegin : Base { public LuaVarFilterStateNameBegin() { Length = SizeOf + 1; TypeCode = (UInt16)LuaTypeCodes.LuaVarFilterStateNameBegin; } public LuaVarFilterStateNameBegin(UInt16 iPluginid, char chWhat) : this() { PluginId = iPluginid; What = (Byte)chWhat; } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + 1]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackByte(What); return buffer; } public Byte What; } [ScmpSend] internal class LuaVarFilterStateName : Base { public LuaVarFilterStateName() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarFilterStateName; } public LuaVarFilterStateName(UInt16 iPluginid, char chWhat, string filter) : this() { PluginId = iPluginid; What = (Byte)chWhat; Filter = filter; } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + 1 + (2 + Encoding.UTF8.GetBytes(Filter).Length)]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackByte(What); packer.PackString(Filter); return buffer; } public Byte What; public string Filter; } [ScmpSend] internal class LuaVarFilterStateNameEnd : Base { public LuaVarFilterStateNameEnd() { Length = SizeOf + 1; TypeCode = (UInt16)LuaTypeCodes.LuaVarFilterStateNameEnd; } public LuaVarFilterStateNameEnd(UInt16 iPluginid, char chWhat) : this() { PluginId = iPluginid; What = (Byte)chWhat; } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + 1]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackByte(What); return buffer; } public Byte What; } [ScmpReceive] internal class LuaVarGlobalBegin : Base { public LuaVarGlobalBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarGlobalBegin; } public LuaVarGlobalBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarGlobal : Base { public LuaVarGlobal() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarGlobal; Hierarchy = new List<KeyValuePair<string, int>>(); } public LuaVarGlobal(UInt16 iPluginid, string name, Int16 nameType, string value, Int16 valueType) : this() { PluginId = iPluginid; Name = name; KeyType = nameType; Value = value; What = valueType; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); Name = reader.ReadString(); KeyType = reader.ReadInt16(); Value = reader.ReadString(); What = reader.ReadInt16(); var count = reader.ReadUInt16(); for (UInt16 i = 0; i < count; ++i) { var name = reader.ReadString(); var type = reader.ReadInt16(); Hierarchy.Add(new KeyValuePair<string, int>(name, type)); } } public string Name; public Int16 KeyType; public string Value; public Int16 What; public List<KeyValuePair<string, int>> Hierarchy; } [ScmpReceive] internal class LuaVarGlobalEnd : Base { public LuaVarGlobalEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarGlobalEnd; } public LuaVarGlobalEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarGlobalLookupBegin : Base { public LuaVarGlobalLookupBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarGlobalLookupBegin; } public LuaVarGlobalLookupBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarGlobalLookupEnd : Base { public LuaVarGlobalLookupEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarGlobalLookupEnd; } public LuaVarGlobalLookupEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarLocalBegin : Base { public LuaVarLocalBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarLocalBegin; } public LuaVarLocalBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarLocal : Base { public LuaVarLocal() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarLocal; Hierarchy = new List<KeyValuePair<string, int>>(); } public LuaVarLocal(UInt16 iPluginid, string name, Int16 nameType, string value, Int16 valueType, Int16 stackLevel, Int32 index) : this() { PluginId = iPluginid; Name = name; KeyType = nameType; Value = value; What = valueType; StackLevel = stackLevel; Index = index; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); Name = reader.ReadString(); KeyType = reader.ReadInt16(); Value = reader.ReadString(); What = reader.ReadInt16(); StackLevel = reader.ReadInt16(); Index = reader.ReadInt32(); var count = reader.ReadUInt16(); for (UInt16 i = 0; i < count; ++i) { var name = reader.ReadString(); var type = reader.ReadInt16(); Hierarchy.Add(new KeyValuePair<string, int>(name, type)); } } public string Name; public Int16 KeyType; public string Value; public Int16 What; public Int16 StackLevel; public Int32 Index; public List<KeyValuePair<string, int>> Hierarchy; } [ScmpReceive] internal class LuaVarLocalEnd : Base { public LuaVarLocalEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarLocalEnd; } public LuaVarLocalEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarLocalLookupBegin : Base { public LuaVarLocalLookupBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarLocalLookupBegin; } public LuaVarLocalLookupBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarLocalLookupEnd : Base { public LuaVarLocalLookupEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarLocalLookupEnd; } public LuaVarLocalLookupEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarUpvalueBegin : Base { public LuaVarUpvalueBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarUpvalueBegin; } public LuaVarUpvalueBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarUpvalue : Base { public LuaVarUpvalue() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarUpvalue; Hierarchy = new List<KeyValuePair<string, int>>(); } public LuaVarUpvalue(UInt16 iPluginid, string name, Int16 nameType, string value, Int16 valueType, Int16 stackLevel, Int32 index) : this() { PluginId = iPluginid; Name = name; KeyType = nameType; Value = value; What = valueType; StackLevel = stackLevel; Index = index; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); Name = reader.ReadString(); KeyType = reader.ReadInt16(); Value = reader.ReadString(); What = reader.ReadInt16(); StackLevel = reader.ReadInt16(); Index = reader.ReadInt32(); var count = reader.ReadUInt16(); for (UInt16 i = 0; i < count; ++i) { var name = reader.ReadString(); var type = reader.ReadInt16(); Hierarchy.Add(new KeyValuePair<string, int>(name, type)); } } public string Name; public Int16 KeyType; public string Value; public Int16 What; public Int16 StackLevel; public Int32 Index; public List<KeyValuePair<string, int>> Hierarchy; } [ScmpReceive] internal class LuaVarUpvalueEnd : Base { public LuaVarUpvalueEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarUpvalueEnd; } public LuaVarUpvalueEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarUpvalueLookupBegin : Base { public LuaVarUpvalueLookupBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarUpvalueLookupBegin; } public LuaVarUpvalueLookupBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarUpvalueLookupEnd : Base { public LuaVarUpvalueLookupEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarUpvalueLookupEnd; } public LuaVarUpvalueLookupEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarEnvVarBegin : Base { public LuaVarEnvVarBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarEnvVarBegin; } public LuaVarEnvVarBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarEnvVar : Base { public LuaVarEnvVar() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarEnvVar; Hierarchy = new List<KeyValuePair<string, int>>(); } public LuaVarEnvVar(UInt16 iPluginid, string name, Int16 nameType, string value, Int16 valueType, Int16 stackLevel) : this() { PluginId = iPluginid; Name = name; KeyType = nameType; Value = value; What = valueType; StackLevel = stackLevel; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); Name = reader.ReadString(); KeyType = reader.ReadInt16(); Value = reader.ReadString(); What = reader.ReadInt16(); StackLevel = reader.ReadInt16(); var count = reader.ReadUInt16(); for (UInt16 i = 0; i < count; ++i) { var name = reader.ReadString(); var type = reader.ReadInt16(); Hierarchy.Add(new KeyValuePair<string, int>(name, type)); } } public string Name; public Int16 KeyType; public string Value; public Int16 What; public Int16 StackLevel; public List<KeyValuePair<string, int>> Hierarchy; } [ScmpReceive] internal class LuaVarEnvVarEnd : Base { public LuaVarEnvVarEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarEnvVarEnd; } public LuaVarEnvVarEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarEnvVarLookupBegin : Base { public LuaVarEnvVarLookupBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarEnvVarLookupBegin; } public LuaVarEnvVarLookupBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaVarEnvVarLookupEnd : Base { public LuaVarEnvVarLookupEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarEnvVarLookupEnd; } public LuaVarEnvVarLookupEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpSend] internal class LuaVarLookUp : Base { public LuaVarLookUp() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaVarLookUp; } public LuaVarLookUp(UInt16 iPluginId, SledLuaVarLookUpType lookUp) : this(iPluginId, lookUp, false) { } public LuaVarLookUp(UInt16 iPluginId, SledLuaVarLookUpType lookUp, bool bExtra) : this() { PluginId = iPluginId; LookUp = lookUp; Extra = (Byte)(bExtra ? 1 : 0); } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { int size = SizeOf // Base + 1 // Byte - what + 1 // Byte - context + 2 // UInt16 - key value pairs count + 2 // Int16 - stack level + 4 // Int32 - index + 1; // Byte - extra foreach (var kv in LookUp.NamesAndTypes) { var bytes = Encoding.UTF8.GetBytes(kv.Name); size += 2; // UInt16 - length of string that follows size += bytes.Length; // UInt16 - string size += 2; // UInt16 - name lua_t<type> } var buffer = new byte[size]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackByte((Byte)((int)LookUp.Scope)); packer.PackByte((Byte)((int)LookUp.Context)); packer.PackUInt16((UInt16)LookUp.NamesAndTypes.Count); packer.PackInt16((Int16)LookUp.StackLevel); packer.PackInt32(LookUp.Index); packer.PackByte(Extra); foreach (var kv in LookUp.NamesAndTypes) { packer.PackString(kv.Name); packer.PackUInt16((UInt16)kv.NameType); } return buffer; } public SledLuaVarLookUpType LookUp; public Byte Extra; } [ScmpSend] internal class LuaVarUpdate : Base { public LuaVarUpdate() { Length = SizeOf; TypeCode = (UInt16) LuaTypeCodes.LuaVarUpdate; } public LuaVarUpdate(UInt16 iPluginId, SledLuaVarLookUpType lookUp, string value, int valueType) : this() { PluginId = iPluginId; LookUp = lookUp; Value = value; ValueType = (Int16)valueType; } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { int size = SizeOf // Base + 1 // Byte - what + 1 // Byte - context + 2 // UInt16 - key value pairs count + 2 // Int16 - stack level + 4 // Int32 - index + 2 + Encoding.UTF32.GetBytes(Value).Length // string length + string + 2; // Int16 - value type foreach (var kv in LookUp.NamesAndTypes) { var bytes = Encoding.UTF8.GetBytes(kv.Name); size += 2; // UInt16 - length of string that follows size += bytes.Length; // UInt16 - string size += 2; // UInt16 - name lua_t<type> } var buffer = new byte[size]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackByte((Byte)(int)LookUp.Scope); packer.PackByte((Byte)(int)LookUp.Context); packer.PackUInt16((UInt16)LookUp.NamesAndTypes.Count); packer.PackInt16((Int16)LookUp.StackLevel); packer.PackInt32(LookUp.Index); packer.PackString(Value); packer.PackInt16(ValueType); foreach (var kv in LookUp.NamesAndTypes) { packer.PackString(kv.Name); packer.PackUInt16((UInt16)kv.NameType); } return buffer; } public SledLuaVarLookUpType LookUp; public string Value; public Int16 ValueType; } [ScmpReceive] internal class LuaCallStackBegin : Base { public LuaCallStackBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaCallStackBegin; } public LuaCallStackBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaCallStack : Base { public LuaCallStack() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaCallStack; } public LuaCallStack(UInt16 iPluginid, string szRelScriptPath, Int32 iCurrentLine, Int32 iLineDefined, Int32 iLastLineDefined, string szFunctionName, Int16 iStackLevel) : this() { PluginId = iPluginid; RelScriptPath = szRelScriptPath; CurrentLine = iCurrentLine; LineDefined = iLineDefined; LastLineDefined = iLastLineDefined; FunctionName = szFunctionName; StackLevel = iStackLevel; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); RelScriptPath = reader.ReadString(); CurrentLine = reader.ReadInt32(); LineDefined = reader.ReadInt32(); LastLineDefined = reader.ReadInt32(); FunctionName = reader.ReadString(); StackLevel = reader.ReadInt16(); } public string RelScriptPath; public Int32 CurrentLine; public Int32 LineDefined; public Int32 LastLineDefined; public string FunctionName; public Int16 StackLevel; } [ScmpReceive] internal class LuaCallStackEnd : Base { public LuaCallStackEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaCallStackEnd; } public LuaCallStackEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpSend] internal class LuaCallStackLookupPerform : Base { public LuaCallStackLookupPerform() { Length = SizeOf + 2; TypeCode = (UInt16)LuaTypeCodes.LuaCallStackLookupPerform; } public LuaCallStackLookupPerform(UInt16 iPluginid, Int16 iStackLevel) : this() { PluginId = iPluginid; StackLevel = iStackLevel; } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + 2]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackInt16(StackLevel); return buffer; } public Int16 StackLevel; } [ScmpReceive] internal class LuaCallStackLookupBegin : Base { public LuaCallStackLookupBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaCallStackLookupBegin; } public LuaCallStackLookupBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaCallStackLookup : Base { public LuaCallStackLookup() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaCallStackLookup; } public LuaCallStackLookup(UInt16 iPluginid, string szFunctionName, Int32 iLineDefined, Int16 iStackLevel) : this() { PluginId = iPluginid; LineDefined = iLineDefined; FunctionName = szFunctionName; StackLevel = iStackLevel; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); FunctionName = reader.ReadString(); LineDefined = reader.ReadInt32(); StackLevel = reader.ReadInt16(); } public string FunctionName; public Int32 LineDefined; public Int16 StackLevel; } [ScmpReceive] internal class LuaCallStackLookupEnd : Base { public LuaCallStackLookupEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaCallStackLookupEnd; } public LuaCallStackLookupEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpSend] [ScmpReceive] internal class LuaWatchLookupBegin : Base { public LuaWatchLookupBegin() { Length = SizeOf + 1; TypeCode = (UInt16)LuaTypeCodes.LuaWatchLookupBegin; } public LuaWatchLookupBegin(UInt16 iPluginid, SledLuaVarScopeType scope) : this() { PluginId = iPluginid; Scope = scope; } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + 1]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackByte((Byte)(int)Scope); return buffer; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); Scope = (SledLuaVarScopeType)reader.ReadByte(); } public SledLuaVarScopeType Scope; } [ScmpSend] [ScmpReceive] internal class LuaWatchLookupEnd : Base { public LuaWatchLookupEnd() { Length = SizeOf + 1; TypeCode = (UInt16)LuaTypeCodes.LuaWatchLookupEnd; } public LuaWatchLookupEnd(UInt16 iPluginid, SledLuaVarScopeType scope) : this() { PluginId = iPluginid; Scope = scope; } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + 1]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackByte((Byte)(int)Scope); return buffer; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); Scope = (SledLuaVarScopeType)reader.ReadByte(); } public SledLuaVarScopeType Scope; } [ScmpReceive] internal class LuaWatchLookupClear : Base { public LuaWatchLookupClear() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaWatchLookupClear; } public LuaWatchLookupClear(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaWatchLookupProjectBegin : Base { public LuaWatchLookupProjectBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaWatchLookupProjectBegin; } public LuaWatchLookupProjectBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaWatchLookupProjectEnd : Base { public LuaWatchLookupProjectEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaWatchLookupProjectEnd; } public LuaWatchLookupProjectEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaWatchLookupCustomBegin : Base { public LuaWatchLookupCustomBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaWatchLookupCustomBegin; } public LuaWatchLookupCustomBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaWatchLookupCustomEnd : Base { public LuaWatchLookupCustomEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaWatchLookupCustomEnd; } public LuaWatchLookupCustomEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaStateBegin : Base { public LuaStateBegin() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaStateBegin; } public LuaStateBegin(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaStateAdd : Base { public LuaStateAdd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaStateAdd; } public LuaStateAdd(UInt16 iPluginid, string szAddress, string szName, bool bDebugging) : this() { PluginId = iPluginid; Address = szAddress; Name = szName; Debugging = (Byte)(bDebugging ? 1 : 0); } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); Address = reader.ReadString(); Name = reader.ReadString(); Debugging = reader.ReadByte(); } public string Address; public string Name; public Byte Debugging; } [ScmpReceive] internal class LuaStateRemove : Base { public LuaStateRemove() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaStateRemove; } public LuaStateRemove(UInt16 iPluginid, string szAddress) : this() { PluginId = iPluginid; Address = szAddress; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); Address = reader.ReadString(); } public string Address; } [ScmpReceive] internal class LuaStateEnd : Base { public LuaStateEnd() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaStateEnd; } public LuaStateEnd(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpSend] internal class LuaStateToggle : Base { public LuaStateToggle() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaStateToggle; } public LuaStateToggle(UInt16 iPluginid, string address) : this() { PluginId = iPluginid; Address = address.Replace(Resource.HexAddress, string.Empty); } /// <summary> /// Wrap all contents into a byte array for sending /// </summary> public override byte[] Pack() { var buffer = new byte[SizeOf + (2 + Encoding.UTF8.GetBytes(Address).Length)]; base.Pack(ref buffer, buffer.Length); var packer = new SledNetworkBufferPacker(ref buffer, SizeOf); packer.PackString(Address); return buffer; } public string Address; } [ScmpSend] [ScmpReceive] internal class LuaMemoryTraceToggle : Base { public LuaMemoryTraceToggle() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaMemoryTraceToggle; } public LuaMemoryTraceToggle(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpSend] [ScmpReceive] internal class LuaProfilerToggle : Base { public LuaProfilerToggle() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaProfilerToggle; } public LuaProfilerToggle(UInt16 iPluginid) : this() { PluginId = iPluginid; } } [ScmpReceive] internal class LuaLimits : Base { public LuaLimits() { Length = SizeOf; TypeCode = (UInt16)LuaTypeCodes.LuaLimits; } public LuaLimits(UInt16 iPluginId, UInt16 iMaxBreakpoints, UInt16 iMaxVarFilters) : this() { PluginId = iPluginId; MaxBreakpoints = iMaxBreakpoints; MaxVarFilters = iMaxVarFilters; } /// <summary> /// Upon receiving data, unpack the byte array into the class members /// </summary> public override void Unpack(byte[] buffer) { // Read the Scmp.Base structure base.Unpack(buffer); // Create reader to easily unpack the network buffer var reader = new SledNetworkBufferReader(buffer, SizeOf); MaxBreakpoints = reader.ReadUInt16(); MaxVarFilters = reader.ReadUInt16(); ProfilerEnabled = (reader.ReadByte() == 1); MemoryTracerEnabled = (reader.ReadByte() == 1); } public UInt16 MaxBreakpoints; public UInt16 MaxVarFilters; public bool ProfilerEnabled; public bool MemoryTracerEnabled; } }
27.964657
175
0.552189
[ "Apache-2.0" ]
MasterScott/SLED
tool/SledLuaLanguagePlugin/SledControlMessageProtocol_Lua.cs
53,804
C#
#region Copyright // Copyright (c) Tobias Wilker and contributors // This file is licensed under MIT #endregion using System.Collections.Generic; using Agents.Net; namespace Agents.Net.Tests.Tools.Communities.TransactionManagerCommunity.Messages { public class TransactionSuccessful : Message { public TransactionSuccessful(Message predecessorMessage): base(predecessorMessage) { } public TransactionSuccessful(IEnumerable<Message> predecessorMessages): base(predecessorMessages) { } protected override string DataToString() { return string.Empty; } } }
25.296296
106
0.667643
[ "MIT" ]
agents-net/agents.net
src/Agents.Net.Tests/Tools/Communities/TransactionManagerCommunity/Messages/TransactionSuccessful.cs
685
C#
namespace Gu.Analyzers { using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MoveArgumentCodeFixProvider))] [Shared] internal class MoveArgumentCodeFixProvider : CodeFixProvider { /// <inheritdoc/> public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create( GU0002NamedArgumentPositionMatches.DiagnosticId, GU0005ExceptionArgumentsPositions.DiagnosticId); /// <inheritdoc/> public override FixAllProvider GetFixAllProvider() => DocumentEditorFixAllProvider.Default; /// <inheritdoc/> public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken) .ConfigureAwait(false); foreach (var diagnostic in context.Diagnostics) { var token = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.Start); if (string.IsNullOrEmpty(token.ValueText) || token.IsMissing) { continue; } if (diagnostic.Id == GU0002NamedArgumentPositionMatches.DiagnosticId) { var arguments = (ArgumentListSyntax)syntaxRoot.FindNode(diagnostic.Location.SourceSpan); if (!HasWhitespaceTriviaOnly(arguments)) { continue; } context.RegisterDocumentEditorFix( "Move arguments to match parameter positions.", (editor, cancellationToken) => ApplyFixGU0002(editor, arguments, cancellationToken), this.GetType(), diagnostic); } if (diagnostic.Id == GU0005ExceptionArgumentsPositions.DiagnosticId) { var argument = (ArgumentSyntax)syntaxRoot.FindNode(diagnostic.Location.SourceSpan); context.RegisterDocumentEditorFix( "Move name argument to match parameter positions.", (editor, cancellationToken) => ApplyFixGU0005(editor, argument, cancellationToken), this.GetType(), diagnostic); } } } private static void ApplyFixGU0002(DocumentEditor editor, ArgumentListSyntax argumentListSyntax, CancellationToken cancellationToken) { var arguments = new ArgumentSyntax[argumentListSyntax.Arguments.Count]; var method = editor.SemanticModel.GetSymbolSafe(argumentListSyntax.Parent, cancellationToken) as IMethodSymbol; foreach (var argument in argumentListSyntax.Arguments) { var index = ParameterIndex(method, argument); var oldArg = argumentListSyntax.Arguments[index]; arguments[index] = argument.WithLeadingTrivia(oldArg.GetLeadingTrivia()) .WithTrailingTrivia(oldArg.GetTrailingTrivia()); } var updated = argumentListSyntax.WithArguments(SyntaxFactory.SeparatedList(arguments, argumentListSyntax.Arguments.GetSeparators())); editor.ReplaceNode(argumentListSyntax, updated); } private static void ApplyFixGU0005(DocumentEditor editor, ArgumentSyntax nameArgument, CancellationToken cancellationToken) { var argumentListSyntax = nameArgument.FirstAncestorOrSelf<ArgumentListSyntax>(); var arguments = new ArgumentSyntax[argumentListSyntax.Arguments.Count]; var method = editor.SemanticModel.GetSymbolSafe(argumentListSyntax.Parent, cancellationToken) as IMethodSymbol; var messageIndex = ParameterIndex(method, "message"); var nameIndex = ParameterIndex(method, "paramName"); for (var i = 0; i < argumentListSyntax.Arguments.Count; i++) { if (i == messageIndex) { arguments[nameIndex] = argumentListSyntax.Arguments[i]; continue; } if (i == nameIndex) { arguments[messageIndex] = argumentListSyntax.Arguments[i]; continue; } arguments[i] = argumentListSyntax.Arguments[i]; } var updated = argumentListSyntax.WithArguments(SyntaxFactory.SeparatedList(arguments, argumentListSyntax.Arguments.GetSeparators())); editor.ReplaceNode(argumentListSyntax, updated); } private static int ParameterIndex(IMethodSymbol method, ArgumentSyntax argument) { return ParameterIndex(method, argument.NameColon.Name.Identifier.ValueText); } private static int ParameterIndex(IMethodSymbol method, string name) { for (int i = 0; i < method.Parameters.Length; i++) { if (method.Parameters[i].Name == name) { return i; } } return -1; } private static bool HasWhitespaceTriviaOnly(ArgumentListSyntax arguments) { foreach (var token in arguments.Arguments.GetWithSeparators()) { if (!IsWhiteSpace(token.GetLeadingTrivia()) || !IsWhiteSpace(token.GetTrailingTrivia())) { return false; } } return true; } private static bool IsWhiteSpace(SyntaxTriviaList trivia) { foreach (var syntaxTrivia in trivia) { if (!(syntaxTrivia.IsKind(SyntaxKind.WhitespaceTrivia) || syntaxTrivia.IsKind(SyntaxKind.EndOfLineTrivia))) { return false; } } return true; } } }
41.709677
145
0.583913
[ "MIT" ]
forki/Gu.Analyzers
Gu.Analyzers.CodeFixes/MoveArgumentCodeFixProvider.cs
6,467
C#
using System; using Prometheus.Client.MetricsWriter; namespace Prometheus.Client.Collectors.Abstractions { public interface ICollectorRegistry { void Add(ICollector collector); bool TryGet(string name, out ICollector collector); TCollector GetOrAdd<TCollector, TConfig>(TConfig config, Func<TConfig, TCollector> collectorFactory) where TCollector : class, ICollector where TConfig: ICollectorConfiguration; ICollector Remove(string name); bool Remove(ICollector collector); void CollectTo(IMetricsWriter writer); } }
26.391304
108
0.710049
[ "MIT" ]
ScottGuymer/Prometheus.Client
src/Prometheus.Client/Collectors/Abstractions/ICollectorRegistry.cs
607
C#
using System.Threading.Tasks; namespace Pars.Services.Contracts.Identity { public interface IEmailSender { #region BaseClass Task SendEmailAsync(string email, string subject, string message); #endregion #region CustomMethods Task SendEmailAsync<T>(string email, string subject, string viewNameOrPath, T model); #endregion } }
20.631579
93
0.678571
[ "Apache-2.0" ]
miladmazaheri/ASPNETCoreIdentitySampleWithMetronicTemplate
src/Pars.Services/Contracts/Identity/IEmailSender.cs
394
C#
// Copyright 2016, 2017, 2018 TRUMPF Werkzeugmaschinen GmbH + Co. KG. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Trumpf.Coparoo.Web.PageTests { using System; using System.Runtime.CompilerServices; /// <summary> /// Page test attribute used to mark page object tests. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = true)] public class PageTestAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="PageTestAttribute"/> class. /// Used to mark page tests inside a page test class /// The is used to sort tests from top to bottom. /// </summary> /// <param name="line">The method line.</param> public PageTestAttribute([CallerLineNumber] int line = 0) { Line = line; } /// <summary> /// Gets the line where the test method was define. /// </summary> public int Line { get; private set; } } }
35.488372
84
0.653997
[ "Apache-2.0" ]
NilsEngelbach/Trumpf.Coparoo.Web
Trumpf.Coparoo.Web/PageTests/PageTestAttribute.cs
1,528
C#
namespace Last_Army.Interfaces { public interface IGameController { void ProcessCommand(string input); void ProduceSummury(); } }
16
42
0.65625
[ "MIT" ]
alexandrateneva/CSharp-Fundamentals-SoftUni
CSharp OOP Advanced/CSharp OOP Advance Exam - Last Army/Last Army/Interfaces/IGameController.cs
162
C#
// Copyright (c) Get Real Health. All rights reserved. // MIT License // 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.Linq; using Hl7.Fhir.Model; using Microsoft.HealthVault.Fhir.Codes.HealthVault; using Microsoft.HealthVault.Fhir.Transformers; using Microsoft.HealthVault.ItemTypes; using Microsoft.VisualStudio.TestTools.UnitTesting; using NodaTime; using FhirMedication = Hl7.Fhir.Model.Medication; using HVMedication = Microsoft.HealthVault.ItemTypes.Medication; namespace Microsoft.HealthVault.Fhir.UnitTests.ToHealthVaultTests { [TestClass] [TestCategory(nameof(MedicationRequest))] public class MedicationRequestToHealthVaultTests { [TestMethod] public void WhenMedicationRequestTransformedToHealthVault_ThenPractitionerIsRequired() { var medicationRequest = new MedicationRequest { Medication = new CodeableConcept { Text = "Amoxicillin 250mg/5ml Suspension" }, }; Assert.ThrowsException<NotSupportedException>(() => medicationRequest.ToHealthVault()); } [TestMethod] public void WhenMedicationRequestTransformedToHealthVault_ThenPractitionerIsCopiedToPrescription() { MedicationRequest medicationRequest = GetSampleRequest(); var hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.IsNotNull(hvMedication.Prescription.PrescribedBy); } [TestMethod] public void WhenMedicationRequestTransformedToHealthVault_ThenAuthoredOnIsCopiedToDatePrescribed() { var prescribedOn = new LocalDate(2017, 08, 10); MedicationRequest medicationRequest = GetSampleRequest(); medicationRequest.AuthoredOnElement = new FhirDateTime(prescribedOn.ToDateTimeUnspecified()); var hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.IsTrue(hvMedication.Prescription?.DatePrescribed.ApproximateDate.CompareTo(prescribedOn) == 0); } [TestMethod] public void WhenMedicationRequestTransformedToHealthVault_ThenDispenseRequestQuantityIsCopiedToAmountPrescribed() { const int amountPrescribed = 15; MedicationRequest medicationRequest = GetSampleRequest(); medicationRequest.DispenseRequest = new MedicationRequest.DispenseRequestComponent { Quantity = new Quantity(amountPrescribed, "tablets").CopyTo(new SimpleQuantity()) as SimpleQuantity }; var hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.AreEqual(amountPrescribed, hvMedication.Prescription?.AmountPrescribed?.Structured.First()?.Value); } [TestMethod] public void WhenMedicationRequestTransformedToHealthVault_ThenSubstitutionIsCopiedToSubstitution() { MedicationRequest medicationRequest = GetSampleRequest(); medicationRequest.Substitution = new MedicationRequest.SubstitutionComponent { Allowed = true }; var hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.AreEqual(HealthVaultMedicationSubstitutionCodes.SubstitutionPermittedCode , hvMedication.Prescription?.Substitution.First().Value); } [TestMethod] public void WhenMedicationRequestTransformedToHealthVault_ThenNumberOfRepeatsAllowedIsCopiedToRefills() { MedicationRequest medicationRequest = GetSampleRequest(); medicationRequest.DispenseRequest = new MedicationRequest.DispenseRequestComponent(); var hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.IsNull(hvMedication.Prescription?.Refills); const int refillsAllowed = 3; medicationRequest.DispenseRequest = new MedicationRequest.DispenseRequestComponent { NumberOfRepeatsAllowed = refillsAllowed }; hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.AreEqual(refillsAllowed, hvMedication.Prescription.Refills); } [TestMethod] public void WhenMedicationRequestTransformedToHealthVault_ThenExpectedSupplyDurationIsCopiedToDaysSupply() { var daysSupply = 12; MedicationRequest medicationRequest = GetSampleRequest(); medicationRequest.DispenseRequest = new MedicationRequest.DispenseRequestComponent { ExpectedSupplyDuration = new Quantity(daysSupply, "day") .CopyTo(new Hl7.Fhir.Model.Duration()) as Hl7.Fhir.Model.Duration }; var hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.AreEqual(daysSupply, hvMedication.Prescription?.DaysSupply); medicationRequest.DispenseRequest.ExpectedSupplyDuration = new Quantity(1, "month") .CopyTo(new Hl7.Fhir.Model.Duration()) as Hl7.Fhir.Model.Duration; hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.AreEqual(30, hvMedication.Prescription?.DaysSupply); } [TestMethod] public void WhenMedicationRequestTransformedToHealthVault_ThenValidityPeriodEndIsCopiedToPrescriptionExpiration() { var expiration = new LocalDate(2017, 12, 12); MedicationRequest medicationRequest = GetSampleRequest(); medicationRequest.DispenseRequest = new MedicationRequest.DispenseRequestComponent { ValidityPeriod = new Hl7.Fhir.Model.Period { EndElement = new FhirDateTime(expiration.ToDateTimeUnspecified()) } }; var hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.IsTrue(hvMedication.Prescription?.PrescriptionExpiration.CompareTo(expiration) == 0); } [TestMethod] public void WhenMedicationRequestTransformedToHealthVault_ThenDosageInstructionIsCopiedToInstructions() { MedicationRequest medicationRequest = GetSampleRequest(); var dosage = new Dosage(); medicationRequest.DosageInstruction = new System.Collections.Generic.List<Dosage> { dosage }; var hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.IsNull(hvMedication.Prescription?.Instructions); var dosageInstructions = new CodeableConcept { Text = "3 tablets/day, have it after dinner." }; dosage.AdditionalInstruction = new System.Collections.Generic.List<CodeableConcept> { dosageInstructions }; hvMedication = medicationRequest.ToHealthVault() as HVMedication; Assert.IsNotNull(hvMedication.Prescription?.Instructions); } private static MedicationRequest GetSampleRequest() { return new MedicationRequest { Contained = new System.Collections.Generic.List<Resource> { new Practitioner { Id = "agent", Name = new System.Collections.Generic.List<HumanName> { new HumanName { Text = "John Sam" } } } }, Medication = new CodeableConcept { Text = "Amoxicillin 250mg/5ml Suspension" }, Requester = new MedicationRequest.RequesterComponent { Agent = new ResourceReference("#agent") } }; } } }
42.882629
463
0.65404
[ "MIT" ]
Bhaskers-Blu-Org2/healthvault-fhir-library
Microsoft.HealthVault.Fhir.UnitTests/ToHealthVaultTests/MedicationRequestToHealthVaultTests.cs
9,136
C#
namespace KeLi.FormMvp.IViews { public interface IUserLoginView { string UserName { get; set; } string Password { get; set; } void ShowMessage(string msg); bool ShowConfirm(string msg); void LoginSys(); } }
17.533333
37
0.589354
[ "MIT" ]
kelicto/FormMvp
KeLi.FormMvp/IViews/IUserLoginView.cs
265
C#
using System; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using DotNetty.Buffers; using DotNetty.Codecs; using DotNetty.Handlers.Logging; using DotNetty.Handlers.Tls; using DotNetty.Transport.Bootstrapping; using DotNetty.Transport.Channels; using DotNetty.Transport.Channels.Sockets; namespace TestClient { class Program { static async Task RunClientAsync() { var group = new MultithreadEventLoopGroup(); try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Channel<SocketDatagramChannel>() .Option(ChannelOption.SoBroadcast, true) .Handler(new ActionChannelInitializer<IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast("Logging", new LoggingClientHandler()); })); IChannel clientChannel = await bootstrap.BindAsync(IPEndPoint.MinPort); Console.WriteLine("Sending"); byte[] bytes = Encoding.UTF8.GetBytes("Hello"); IByteBuffer buffer = Unpooled.WrappedBuffer(bytes); var ipaddrList = await Dns.GetHostAddressesAsync("localhost"); var remoteIp = ipaddrList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork); if (remoteIp == null) { throw new Exception($"Can not resolve ip of "); } await clientChannel.WriteAndFlushAsync( new DatagramPacket( buffer, new IPEndPoint(remoteIp, 6253))); Console.WriteLine("Waiting for response."); await Task.Delay(5000); Console.WriteLine("Waiting for response time 5000 completed. Closing client channel."); await clientChannel.CloseAsync(); } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } } static void Main() => RunClientAsync().Wait(); } public class LoggingClientHandler : SimpleChannelInboundHandler<DatagramPacket> { protected override void ChannelRead0(IChannelHandlerContext ctx, DatagramPacket packet) { Console.WriteLine($"Client Received => {packet}"); if (!packet.Content.IsReadable()) { return; } string message = packet.Content.ToString(Encoding.UTF8); Console.WriteLine($"Client received: {message}"); ctx.CloseAsync(); } public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { Console.WriteLine("Exception: " + exception); context.CloseAsync(); } } }
33.104167
109
0.580868
[ "MIT" ]
kinglionsoft/K9Nano.Logging
test/TestClient/Program.cs
3,180
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Batch.Latest.Inputs { public sealed class WindowsConfigurationArgs : Pulumi.ResourceArgs { /// <summary> /// If omitted, the default value is true. /// </summary> [Input("enableAutomaticUpdates")] public Input<bool>? EnableAutomaticUpdates { get; set; } public WindowsConfigurationArgs() { } } }
27.038462
81
0.671408
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Batch/Latest/Inputs/WindowsConfigurationArgs.cs
703
C#
// // ExtensionNodeTypeCollection.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; namespace Mono.Addins.Description { /// <summary> /// A collection of node types. /// </summary> public class ExtensionNodeTypeCollection: ObjectDescriptionCollection { /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.Description.ExtensionNodeTypeCollection"/> class. /// </summary> public ExtensionNodeTypeCollection () { } internal ExtensionNodeTypeCollection (object owner): base (owner) { } /// <summary> /// Gets the <see cref="Mono.Addins.Description.ExtensionNodeType"/> at the specified index. /// </summary> /// <param name='n'> /// The index. /// </param> public ExtensionNodeType this [int n] { get { return (ExtensionNodeType) List [n]; } } /// <summary> /// Gets the <see cref="Mono.Addins.Description.ExtensionNodeType"/> with the specified id. /// </summary> /// <param name='id'> /// Identifier. /// </param> public ExtensionNodeType this [string id] { get { for (int n=0; n<List.Count; n++) if (((ExtensionNodeType) List [n]).Id == id) return (ExtensionNodeType) List [n]; return null; } } } }
31.064935
112
0.699415
[ "MIT" ]
directhex/mono-addins
Mono.Addins/Mono.Addins.Description/ExtensionNodeTypeCollection.cs
2,392
C#
/**************************************************************** Copyright 2021 Infosys Ltd. Use of this source code is governed by Apache License Version 2.0 that can be found in the LICENSE file or at http://www.apache.org/licenses/ ***************************************************************/ using System.Runtime.Serialization; using Infosys.WEM.SecurityAccess.Contracts.Data; using Infosys.WEM.Infrastructure.Common.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF; namespace Infosys.WEM.SecurityAccess.Contracts.Message { [DataContract] public class AddUserReqMsg { [DataMember] [ADValidator(MessageTemplate = "User not found in AD")] public User User { get; set; } } }
36.833333
110
0.659502
[ "Apache-2.0" ]
Infosys/Script-Control-Center
WEMServices/WEM.SecurityAccess.Contracts/Message/AddUserReqMsg.cs
886
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace OOPLab6.AppSettings { public class Theme { private List<string> themes = new List<string>(); public List<string> Themes { get => themes; } public Theme() { ThemeChanged += AppThemeChanged; themes.Add("classic"); themes.Add("darkblue"); themes.Add("bright"); Name = OOPLab6.Properties.Settings.Default.DefaultTheme; } public event EventHandler ThemeChanged; private string name; public string Name { get => name; set { if (value == null) throw new ArgumentNullException("value"); if (value == Name) return; name = value; Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(String.Format($"Themes/{value}.xaml"), UriKind.Relative) }); ThemeChanged(Application.Current, new EventArgs()); } } private void AppThemeChanged(Object sender, EventArgs e) { OOPLab6.Properties.Settings.Default.DefaultTheme = Name; OOPLab6.Properties.Settings.Default.Save(); } } }
26.509091
95
0.550754
[ "MIT" ]
dim-den/Hardware-store
OOPLab6/AppSettings/Theme.cs
1,460
C#
using Harmony; using QuantumTeleporter.Managers; namespace QuantumTeleporter.Patches { [HarmonyPatch(typeof(Player))] [HarmonyPatch("Update")] internal class Player_Patch { internal static void Postfix(ref Player __instance) { TeleportManager.Update(); } } }
19.8125
59
0.652997
[ "MIT" ]
ccgould/FCStudios_SubnauticaMods
QuantumTeleporter/Patches/Player_Patch.cs
319
C#
#nullable enable using System.Collections.Generic; using System.Linq; using Content.Server.Body.Mechanisms; using Content.Server.GameObjects.Components.Body; using Content.Shared.GameObjects.Components.Body; using Content.Shared.Interfaces; using JetBrains.Annotations; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Localization; namespace Content.Server.Body.Surgery { /// <summary> /// Data class representing the surgery state of a biological entity. /// </summary> [UsedImplicitly] public class BiologicalSurgeryData : SurgeryData { private readonly List<IMechanism> _disconnectedOrgans = new List<IMechanism>(); private bool _skinOpened; private bool _skinRetracted; private bool _vesselsClamped; public BiologicalSurgeryData(IBodyPart parent) : base(parent) { } protected override SurgeryAction? GetSurgeryStep(SurgeryType toolType) { if (toolType == SurgeryType.Amputation) { return RemoveBodyPartSurgery; } if (!_skinOpened) { // Case: skin is normal. if (toolType == SurgeryType.Incision) { return OpenSkinSurgery; } } else if (!_vesselsClamped) { // Case: skin is opened, but not clamped. switch (toolType) { case SurgeryType.VesselCompression: return ClampVesselsSurgery; case SurgeryType.Cauterization: return CauterizeIncisionSurgery; } } else if (!_skinRetracted) { // Case: skin is opened and clamped, but not retracted. switch (toolType) { case SurgeryType.Retraction: return RetractSkinSurgery; case SurgeryType.Cauterization: return CauterizeIncisionSurgery; } } else { // Case: skin is fully open. if (Parent.Mechanisms.Count > 0 && toolType == SurgeryType.VesselCompression) { if (_disconnectedOrgans.Except(Parent.Mechanisms).Count() != 0 || Parent.Mechanisms.Except(_disconnectedOrgans).Count() != 0) { return LoosenOrganSurgery; } } if (_disconnectedOrgans.Count > 0 && toolType == SurgeryType.Incision) { return RemoveOrganSurgery; } if (toolType == SurgeryType.Cauterization) { return CauterizeIncisionSurgery; } } return null; } public override string GetDescription(IEntity target) { var toReturn = ""; if (_skinOpened && !_vesselsClamped) { // Case: skin is opened, but not clamped. toReturn += Loc.GetString("The skin on {0:their} {1} has an incision, but it is prone to bleeding.\n", target, Parent.Name); } else if (_skinOpened && _vesselsClamped && !_skinRetracted) { // Case: skin is opened and clamped, but not retracted. toReturn += Loc.GetString("The skin on {0:their} {1} has an incision, but it is not retracted.\n", target, Parent.Name); } else if (_skinOpened && _vesselsClamped && _skinRetracted) { // Case: skin is fully open. toReturn += Loc.GetString("There is an incision on {0:their} {1}.\n", target, Parent.Name); foreach (var mechanism in _disconnectedOrgans) { toReturn += Loc.GetString("{0:their} {1} is loose.\n", target, mechanism.Name); } } return toReturn; } public override bool CanInstallMechanism(IMechanism mechanism) { return _skinOpened && _vesselsClamped && _skinRetracted; } public override bool CanAttachBodyPart(IBodyPart part) { return true; // TODO: if a bodypart is disconnected, you should have to do some surgery to allow another bodypart to be attached. } private void OpenSkinSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { performer.PopupMessage(Loc.GetString("Cut open the skin...")); // TODO do_after: Delay _skinOpened = true; } private void ClampVesselsSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { performer.PopupMessage(Loc.GetString("Clamp the vessels...")); // TODO do_after: Delay _vesselsClamped = true; } private void RetractSkinSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { performer.PopupMessage(Loc.GetString("Retract the skin...")); // TODO do_after: Delay _skinRetracted = true; } private void CauterizeIncisionSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { performer.PopupMessage(Loc.GetString("Cauterize the incision...")); // TODO do_after: Delay _skinOpened = false; _vesselsClamped = false; _skinRetracted = false; } private void LoosenOrganSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { if (Parent.Mechanisms.Count <= 0) { return; } var toSend = new List<IMechanism>(); foreach (var mechanism in Parent.Mechanisms) { if (!_disconnectedOrgans.Contains(mechanism)) { toSend.Add(mechanism); } } if (toSend.Count > 0) { surgeon.RequestMechanism(toSend, LoosenOrganSurgeryCallback); } } private void LoosenOrganSurgeryCallback(IMechanism target, IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { if (target == null || !Parent.Mechanisms.Contains(target)) { return; } performer.PopupMessage(Loc.GetString("Loosen the organ...")); // TODO do_after: Delay _disconnectedOrgans.Add(target); } private void RemoveOrganSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { if (_disconnectedOrgans.Count <= 0) { return; } if (_disconnectedOrgans.Count == 1) { RemoveOrganSurgeryCallback(_disconnectedOrgans[0], container, surgeon, performer); } else { surgeon.RequestMechanism(_disconnectedOrgans, RemoveOrganSurgeryCallback); } } private void RemoveOrganSurgeryCallback(IMechanism target, IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { if (target == null || !Parent.Mechanisms.Contains(target)) { return; } performer.PopupMessage(Loc.GetString("Remove the organ...")); // TODO do_after: Delay Parent.TryDropMechanism(performer, target, out _); _disconnectedOrgans.Remove(target); } private void RemoveBodyPartSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { // This surgery requires a DroppedBodyPartComponent. if (!(container is BodyManagerComponent)) { return; } var bmTarget = (BodyManagerComponent) container; performer.PopupMessage(Loc.GetString("Saw off the limb!")); // TODO do_after: Delay bmTarget.RemovePart(Parent, true); } } }
33.864
128
0.542169
[ "MIT" ]
AlphaQwerty/space-station-14
Content.Server/Body/Surgery/BiologicalSurgeryData.cs
8,468
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Globalization; using System.Linq; using Microsoft.Health.Dicom.Core.Features.Model; using Microsoft.Health.Dicom.Functions.Durable; using Microsoft.Health.Dicom.Functions.Indexing.Models; using Xunit; namespace Microsoft.Health.Dicom.Functions.UnitTests.Indexing.Models { public class ReindexInputTests { [Fact] public void GivenEmptyInput_WhenGettingProgress_ThenReturnDefaultStatus() { OperationProgress progress = new ReindexInput().GetProgress(); Assert.Equal(0, progress.PercentComplete); Assert.Null(progress.ResourceIds); } [Fact] public void GivenMinimumCompletion_WhenGettingProgress_ThenReturnCompletedProgress() { OperationProgress progress = new ReindexInput { Completed = new WatermarkRange(1, 1) }.GetProgress(); Assert.Equal(100, progress.PercentComplete); Assert.Null(progress.ResourceIds); } [Theory] [InlineData(4, 4, 25)] [InlineData(3, 4, 50)] [InlineData(2, 4, 75)] [InlineData(1, 4, 100)] public void GivenReindexInput_WhenGettingProgress_ThenReturnComputedProgress(int start, int end, int expected) { int[] expectedTagKeys = new int[] { 1, 3, 10 }; OperationProgress progress = new ReindexInput { Completed = new WatermarkRange(start, end), QueryTagKeys = expectedTagKeys, }.GetProgress(); Assert.Equal(expected, progress.PercentComplete); Assert.True(progress.ResourceIds.SequenceEqual(expectedTagKeys.Select(x => x.ToString(CultureInfo.InvariantCulture)))); } } }
38.833333
131
0.601335
[ "MIT" ]
ECGKit/dicom-server
src/Microsoft.Health.Dicom.Functions.UnitTests/Indexing/Models/ReindexInputTests.cs
2,099
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the glue-2017-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Glue.Model { /// <summary> /// A structure for a machine learning transform. /// </summary> public partial class MLTransform { private DateTime? _createdOn; private string _description; private EvaluationMetrics _evaluationMetrics; private List<GlueTable> _inputRecordTables = new List<GlueTable>(); private int? _labelCount; private DateTime? _lastModifiedOn; private double? _maxCapacity; private int? _maxRetries; private string _name; private int? _numberOfWorkers; private TransformParameters _parameters; private string _role; private List<SchemaColumn> _schema = new List<SchemaColumn>(); private TransformStatusType _status; private int? _timeout; private string _transformId; private WorkerType _workerType; /// <summary> /// Gets and sets the property CreatedOn. /// <para> /// A timestamp. The time and date that this machine learning transform was created. /// </para> /// </summary> public DateTime CreatedOn { get { return this._createdOn.GetValueOrDefault(); } set { this._createdOn = value; } } // Check to see if CreatedOn property is set internal bool IsSetCreatedOn() { return this._createdOn.HasValue; } /// <summary> /// Gets and sets the property Description. /// <para> /// A user-defined, long-form description text for the machine learning transform. Descriptions /// are not guaranteed to be unique and can be changed at any time. /// </para> /// </summary> [AWSProperty(Min=0, Max=2048)] public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property EvaluationMetrics. /// <para> /// An <code>EvaluationMetrics</code> object. Evaluation metrics provide an estimate of /// the quality of your machine learning transform. /// </para> /// </summary> public EvaluationMetrics EvaluationMetrics { get { return this._evaluationMetrics; } set { this._evaluationMetrics = value; } } // Check to see if EvaluationMetrics property is set internal bool IsSetEvaluationMetrics() { return this._evaluationMetrics != null; } /// <summary> /// Gets and sets the property InputRecordTables. /// <para> /// A list of AWS Glue table definitions used by the transform. /// </para> /// </summary> [AWSProperty(Min=0, Max=10)] public List<GlueTable> InputRecordTables { get { return this._inputRecordTables; } set { this._inputRecordTables = value; } } // Check to see if InputRecordTables property is set internal bool IsSetInputRecordTables() { return this._inputRecordTables != null && this._inputRecordTables.Count > 0; } /// <summary> /// Gets and sets the property LabelCount. /// <para> /// A count identifier for the labeling files generated by AWS Glue for this transform. /// As you create a better transform, you can iteratively download, label, and upload /// the labeling file. /// </para> /// </summary> public int LabelCount { get { return this._labelCount.GetValueOrDefault(); } set { this._labelCount = value; } } // Check to see if LabelCount property is set internal bool IsSetLabelCount() { return this._labelCount.HasValue; } /// <summary> /// Gets and sets the property LastModifiedOn. /// <para> /// A timestamp. The last point in time when this machine learning transform was modified. /// </para> /// </summary> public DateTime LastModifiedOn { get { return this._lastModifiedOn.GetValueOrDefault(); } set { this._lastModifiedOn = value; } } // Check to see if LastModifiedOn property is set internal bool IsSetLastModifiedOn() { return this._lastModifiedOn.HasValue; } /// <summary> /// Gets and sets the property MaxCapacity. /// <para> /// The number of AWS Glue data processing units (DPUs) that are allocated to task runs /// for this transform. You can allocate from 2 to 100 DPUs; the default is 10. A DPU /// is a relative measure of processing power that consists of 4 vCPUs of compute capacity /// and 16 GB of memory. For more information, see the <a href="https://aws.amazon.com/glue/pricing/">AWS /// Glue pricing page</a>. /// </para> /// /// <para> /// When the <code>WorkerType</code> field is set to a value other than <code>Standard</code>, /// the <code>MaxCapacity</code> field is set automatically and becomes read-only. /// </para> /// </summary> public double MaxCapacity { get { return this._maxCapacity.GetValueOrDefault(); } set { this._maxCapacity = value; } } // Check to see if MaxCapacity property is set internal bool IsSetMaxCapacity() { return this._maxCapacity.HasValue; } /// <summary> /// Gets and sets the property MaxRetries. /// <para> /// The maximum number of times to retry after an <code>MLTaskRun</code> of the machine /// learning transform fails. /// </para> /// </summary> public int MaxRetries { get { return this._maxRetries.GetValueOrDefault(); } set { this._maxRetries = value; } } // Check to see if MaxRetries property is set internal bool IsSetMaxRetries() { return this._maxRetries.HasValue; } /// <summary> /// Gets and sets the property Name. /// <para> /// A user-defined name for the machine learning transform. Names are not guaranteed unique /// and can be changed at any time. /// </para> /// </summary> [AWSProperty(Min=1, Max=255)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property NumberOfWorkers. /// <para> /// The number of workers of a defined <code>workerType</code> that are allocated when /// a task of the transform runs. /// </para> /// </summary> public int NumberOfWorkers { get { return this._numberOfWorkers.GetValueOrDefault(); } set { this._numberOfWorkers = value; } } // Check to see if NumberOfWorkers property is set internal bool IsSetNumberOfWorkers() { return this._numberOfWorkers.HasValue; } /// <summary> /// Gets and sets the property Parameters. /// <para> /// A <code>TransformParameters</code> object. You can use parameters to tune (customize) /// the behavior of the machine learning transform by specifying what data it learns from /// and your preference on various tradeoffs (such as precious vs. recall, or accuracy /// vs. cost). /// </para> /// </summary> public TransformParameters Parameters { get { return this._parameters; } set { this._parameters = value; } } // Check to see if Parameters property is set internal bool IsSetParameters() { return this._parameters != null; } /// <summary> /// Gets and sets the property Role. /// <para> /// The name or Amazon Resource Name (ARN) of the IAM role with the required permissions. /// This role needs permission to your Amazon Simple Storage Service (Amazon S3) sources, /// targets, temporary directory, scripts, and any libraries used by the task run for /// this transform. /// </para> /// </summary> public string Role { get { return this._role; } set { this._role = value; } } // Check to see if Role property is set internal bool IsSetRole() { return this._role != null; } /// <summary> /// Gets and sets the property Schema. /// <para> /// A map of key-value pairs representing the columns and data types that this transform /// can run against. Has an upper bound of 100 columns. /// </para> /// </summary> [AWSProperty(Max=100)] public List<SchemaColumn> Schema { get { return this._schema; } set { this._schema = value; } } // Check to see if Schema property is set internal bool IsSetSchema() { return this._schema != null && this._schema.Count > 0; } /// <summary> /// Gets and sets the property Status. /// <para> /// The current status of the machine learning transform. /// </para> /// </summary> public TransformStatusType Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property Timeout. /// <para> /// The timeout in minutes of the machine learning transform. /// </para> /// </summary> [AWSProperty(Min=1)] public int Timeout { get { return this._timeout.GetValueOrDefault(); } set { this._timeout = value; } } // Check to see if Timeout property is set internal bool IsSetTimeout() { return this._timeout.HasValue; } /// <summary> /// Gets and sets the property TransformId. /// <para> /// The unique transform ID that is generated for the machine learning transform. The /// ID is guaranteed to be unique and does not change. /// </para> /// </summary> [AWSProperty(Min=1, Max=255)] public string TransformId { get { return this._transformId; } set { this._transformId = value; } } // Check to see if TransformId property is set internal bool IsSetTransformId() { return this._transformId != null; } /// <summary> /// Gets and sets the property WorkerType. /// <para> /// The type of predefined worker that is allocated when a task of this transform runs. /// Accepts a value of Standard, G.1X, or G.2X. /// </para> /// <ul> <li> /// <para> /// For the <code>Standard</code> worker type, each worker provides 4 vCPU, 16 GB of memory /// and a 50GB disk, and 2 executors per worker. /// </para> /// </li> <li> /// <para> /// For the <code>G.1X</code> worker type, each worker provides 4 vCPU, 16 GB of memory /// and a 64GB disk, and 1 executor per worker. /// </para> /// </li> <li> /// <para> /// For the <code>G.2X</code> worker type, each worker provides 8 vCPU, 32 GB of memory /// and a 128GB disk, and 1 executor per worker. /// </para> /// </li> </ul> /// </summary> public WorkerType WorkerType { get { return this._workerType; } set { this._workerType = value; } } // Check to see if WorkerType property is set internal bool IsSetWorkerType() { return this._workerType != null; } } }
33.420147
113
0.561462
[ "Apache-2.0" ]
TallyUpTeam/aws-sdk-net
sdk/src/Services/Glue/Generated/Model/MLTransform.cs
13,602
C#
using System; using System.Text; using System.Windows.Forms; namespace DevExpress.XtraCharts.Wizard { public class AddRemoveChartNamedElementControl : UserControl { } }
19.222222
63
0.803468
[ "Unlicense" ]
broteam168/QuizContest-broteam
DoAn_thitracnghiem/bin/Debug/vi/Sources/DevExpress.XtraCharts.Wizard/AddRemoveChartNamedElementControl.cs
173
C#
using System; namespace Live.Caqui.Model { public class UserModel { public string Name { get; set; } public string Login { get; set; } public string Password { get; set; } public string HashUser { get; set; } public static string Hash { get; set; } } }
21.928571
47
0.583062
[ "MIT" ]
jhonatansantos61/LiveCodingEmployer2020
Live.Caqui.Model/UserModel.cs
309
C#
using System.Web.Mvc; using UEditor.Core; namespace Sample.Mvc.Controllers { public class UEditorController : Controller { public ContentResult Upload() { var response = UEditorService.Instance.UploadAndGetResponse(HttpContext.ApplicationInstance.Context); return Content(response.Result, response.ContentType); } } }
27.071429
113
0.688654
[ "MIT" ]
baiyunchen/UEditor.Core
Sample.Mvc/Controllers/UEditorController.cs
381
C#
using LuaInterface; using System; using UnityEngine; public class UnityEngine_SphereColliderWrap { public static void Register(LuaState L) { L.BeginClass(typeof(SphereCollider), typeof(Collider), null); L.RegFunction("New", new LuaCSFunction(UnityEngine_SphereColliderWrap._CreateUnityEngine_SphereCollider)); L.RegFunction("__eq", new LuaCSFunction(UnityEngine_SphereColliderWrap.op_Equality)); L.RegFunction("__tostring", new LuaCSFunction(UnityEngine_SphereColliderWrap.Lua_ToString)); L.RegVar("center", new LuaCSFunction(UnityEngine_SphereColliderWrap.get_center), new LuaCSFunction(UnityEngine_SphereColliderWrap.set_center)); L.RegVar("radius", new LuaCSFunction(UnityEngine_SphereColliderWrap.get_radius), new LuaCSFunction(UnityEngine_SphereColliderWrap.set_radius)); L.EndClass(); } [MonoPInvokeCallback(typeof(LuaCSFunction))] private static int _CreateUnityEngine_SphereCollider(IntPtr L) { int result; try { if (LuaDLL.lua_gettop(L) == 0) { SphereCollider obj = new SphereCollider(); ToLua.Push(L, obj); result = 1; } else { result = LuaDLL.luaL_throw(L, "invalid arguments to ctor method: UnityEngine.SphereCollider.New"); } } catch (Exception e) { result = LuaDLL.toluaL_exception(L, e, null); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] private static int op_Equality(IntPtr L) { int result; try { ToLua.CheckArgsCount(L, 2); Object @object = (Object)ToLua.ToObject(L, 1); Object object2 = (Object)ToLua.ToObject(L, 2); bool value = @object == object2; LuaDLL.lua_pushboolean(L, value); result = 1; } catch (Exception e) { result = LuaDLL.toluaL_exception(L, e, null); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] private static int Lua_ToString(IntPtr L) { object obj = ToLua.ToObject(L, 1); if (obj != null) { LuaDLL.lua_pushstring(L, obj.ToString()); } else { LuaDLL.lua_pushnil(L); } return 1; } [MonoPInvokeCallback(typeof(LuaCSFunction))] private static int get_center(IntPtr L) { object obj = null; int result; try { obj = ToLua.ToObject(L, 1); SphereCollider sphereCollider = (SphereCollider)obj; Vector3 center = sphereCollider.get_center(); ToLua.Push(L, center); result = 1; } catch (Exception ex) { result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.get_Message() : "attempt to index center on a nil value"); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] private static int get_radius(IntPtr L) { object obj = null; int result; try { obj = ToLua.ToObject(L, 1); SphereCollider sphereCollider = (SphereCollider)obj; float radius = sphereCollider.get_radius(); LuaDLL.lua_pushnumber(L, (double)radius); result = 1; } catch (Exception ex) { result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.get_Message() : "attempt to index radius on a nil value"); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] private static int set_center(IntPtr L) { object obj = null; int result; try { obj = ToLua.ToObject(L, 1); SphereCollider sphereCollider = (SphereCollider)obj; Vector3 center = ToLua.ToVector3(L, 2); sphereCollider.set_center(center); result = 0; } catch (Exception ex) { result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.get_Message() : "attempt to index center on a nil value"); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] private static int set_radius(IntPtr L) { object obj = null; int result; try { obj = ToLua.ToObject(L, 1); SphereCollider sphereCollider = (SphereCollider)obj; float radius = (float)LuaDLL.luaL_checknumber(L, 2); sphereCollider.set_radius(radius); result = 0; } catch (Exception ex) { result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.get_Message() : "attempt to index radius on a nil value"); } return result; } }
25.477707
145
0.70175
[ "MIT" ]
corefan/tianqi_src
src/UnityEngine_SphereColliderWrap.cs
4,000
C#
using System; using System.Linq; using System.Threading.Tasks; using Windows.UI.Input.Inking; using Windows.UI.Input.Inking.Analysis; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; namespace Param_RootNamespace.Services.Ink { public class InkNodeSelectionService { private const double BusyWaitingTime = 200; private const double TripleTapTime = 400; private readonly InkCanvas _inkCanvas; private readonly InkPresenter _inkPresenter; private readonly InkAsyncAnalyzer _analyzer; private readonly InkStrokesService _strokeService; private readonly InkSelectionRectangleService _selectionRectangleService; private readonly Canvas _selectionCanvas; private IInkAnalysisNode selectedNode; private DateTime lastDoubleTapTime; public InkNodeSelectionService( InkCanvas inkCanvas, Canvas selectionCanvas, InkAsyncAnalyzer analyzer, InkStrokesService strokeService, InkSelectionRectangleService selectionRectangleService) { _inkCanvas = inkCanvas; _selectionCanvas = selectionCanvas; _inkPresenter = _inkCanvas.InkPresenter; _analyzer = analyzer; _strokeService = strokeService; _selectionRectangleService = selectionRectangleService; _inkCanvas.Tapped += InkCanvas_Tapped; _inkCanvas.DoubleTapped += InkCanvas_DoubleTapped; _inkCanvas.PointerPressed += InkCanvas_PointerPressed; _inkPresenter.StrokesErased += InkPresenter_StrokesErased; } public void ClearSelection() { selectedNode = null; _strokeService.ClearStrokesSelection(); _selectionRectangleService.Clear(); } private void InkCanvas_Tapped(object sender, TappedRoutedEventArgs e) { var position = e.GetPosition(_inkCanvas); if (selectedNode != null && RectHelper.Contains(selectedNode.BoundingRect, position)) { if (DateTime.Now.Subtract(lastDoubleTapTime).TotalMilliseconds < TripleTapTime) { ExpandSelection(); } } else { selectedNode = _analyzer.FindHitNode(position); ShowOrHideSelection(selectedNode); } } private void InkCanvas_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e) { var position = e.GetPosition(_inkCanvas); if (selectedNode != null && RectHelper.Contains(selectedNode.BoundingRect, position)) { ExpandSelection(); lastDoubleTapTime = DateTime.Now; } } private async void InkCanvas_PointerPressed(object sender, PointerRoutedEventArgs e) { var position = e.GetCurrentPoint(_inkCanvas).Position; while (_analyzer.IsAnalyzing) { await Task.Delay(TimeSpan.FromMilliseconds(BusyWaitingTime)); } if (_selectionRectangleService.ContainsPosition(position)) { // Pressed on the selected rect, do nothing return; } selectedNode = _analyzer.FindHitNode(position); ShowOrHideSelection(selectedNode); } private void InkPresenter_StrokesErased(InkPresenter sender, InkStrokesErasedEventArgs e) { if (e.Strokes.Any(s => s.Selected)) { ClearSelection(); } } private void ExpandSelection() { if (selectedNode != null && selectedNode.Kind != InkAnalysisNodeKind.UnclassifiedInk && selectedNode.Kind != InkAnalysisNodeKind.InkDrawing && selectedNode.Kind != InkAnalysisNodeKind.WritingRegion) { selectedNode = selectedNode.Parent; if (selectedNode.Kind == InkAnalysisNodeKind.ListItem && selectedNode.Children.Count == 1) { // Hierarchy: WritingRegion->Paragraph->ListItem->Line->{Bullet, Word1, Word2...} // When a ListItem has only one Line, the bounding rect is same with its child Line, // in this case, we skip one level to avoid confusion. selectedNode = selectedNode.Parent; } ShowOrHideSelection(selectedNode); } } private void ShowOrHideSelection(IInkAnalysisNode node) { if (node != null) { var rect = _strokeService.SelectStrokesByNode(node); _selectionRectangleService.UpdateSelectionRect(rect); } else { ClearSelection(); } } } }
35.097902
106
0.595138
[ "MIT" ]
Acidburn0zzz/WindowsTemplateStudio
templates/Uwp/_composition/_shared/Page.Ink.AddNodeSelectionService/Services/Ink/InkNodeSelectionService.cs
5,021
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codecommit-2015-04-13.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CodeCommit.Model { /// <summary> /// Container for the parameters to the TestRepositoryTriggers operation. /// Tests the functionality of repository triggers by sending information to the trigger /// target. If real data is available in the repository, the test will send data from /// the last commit. If no data is available, sample data will be generated. /// </summary> public partial class TestRepositoryTriggersRequest : AmazonCodeCommitRequest { private string _repositoryName; private List<RepositoryTrigger> _triggers = new List<RepositoryTrigger>(); /// <summary> /// Gets and sets the property RepositoryName. /// <para> /// The name of the repository in which to test the triggers. /// </para> /// </summary> public string RepositoryName { get { return this._repositoryName; } set { this._repositoryName = value; } } // Check to see if RepositoryName property is set internal bool IsSetRepositoryName() { return this._repositoryName != null; } /// <summary> /// Gets and sets the property Triggers. /// <para> /// The list of triggers to test. /// </para> /// </summary> public List<RepositoryTrigger> Triggers { get { return this._triggers; } set { this._triggers = value; } } // Check to see if Triggers property is set internal bool IsSetTriggers() { return this._triggers != null && this._triggers.Count > 0; } } }
32.858974
108
0.643387
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/CodeCommit/Generated/Model/TestRepositoryTriggersRequest.cs
2,563
C#
using UnityEngine; public class FlyScript : MonoBehaviour { public GameObject FlyDeath; public Vector2 FlyPos; public float Speed = 500f; public float randY; public Vector2 SpawnPos; public int X; Rigidbody2D rb2d; Collider2D col2d; void Start() { SpawnPos = transform.position; if (SpawnPos.x > 1) { X = -1; transform.localScale = transform.localScale + (Vector3.left * 4); } if (SpawnPos.x < 1) { X = 1; } rb2d = GetComponent<Rigidbody2D>(); randY = Random.Range(-0.5f, 0.5f); Vector2 movement = new Vector2(X, randY); rb2d.AddForce(movement * Speed); } void FixedUpdate() { FlyPos = transform.position; } void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == "Tongue") { //Death after collide with tongue FlyDeath.transform.position = FlyPos; Instantiate(FlyDeath); Destroy(gameObject); } if (col.gameObject.tag == "FlySpawn") { Destroy(gameObject); } } }
21.403509
77
0.52541
[ "Apache-2.0" ]
Ruokin/TheMagicToad.android
Assets/Scripts/ZhabaSceneScripts/FlyScript.cs
1,222
C#
// System.Reflection/TypeDelegator.cs // // Paolo Molaro ([email protected]) // // (C) 2002 Ximian, Inc. // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Globalization; using System.Runtime.InteropServices; namespace System.Reflection { #if NET_2_0 [ComVisible (true)] #endif [Serializable] public class TypeDelegator : Type { protected Type typeImpl; protected TypeDelegator () { } public TypeDelegator( Type delegatingType) { if (delegatingType == null) throw new ArgumentNullException ("delegatingType must be non-null"); typeImpl = delegatingType; } public override Assembly Assembly { get { return typeImpl.Assembly; } } public override string AssemblyQualifiedName { get { return typeImpl.AssemblyQualifiedName; } } public override Type BaseType { get { return typeImpl.BaseType; } } public override string FullName { get { return typeImpl.FullName; } } public override Guid GUID { get { return typeImpl.GUID; } } public override Module Module { get { return typeImpl.Module; } } public override string Name { get { return typeImpl.Name; } } public override string Namespace { get { return typeImpl.Namespace; } } public override RuntimeTypeHandle TypeHandle { get { return typeImpl.TypeHandle; } } public override Type UnderlyingSystemType { get { return typeImpl.UnderlyingSystemType; } } protected override TypeAttributes GetAttributeFlagsImpl () { return typeImpl.Attributes; } protected override ConstructorInfo GetConstructorImpl ( BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return typeImpl.GetConstructor (bindingAttr, binder, callConvention, types, modifiers); } #if NET_2_0 [ComVisible (true)] #endif public override ConstructorInfo[] GetConstructors( BindingFlags bindingAttr) { return typeImpl.GetConstructors (bindingAttr); } public override object[] GetCustomAttributes (bool inherit) { return typeImpl.GetCustomAttributes (inherit); } public override object[] GetCustomAttributes (Type attributeType, bool inherit) { return typeImpl.GetCustomAttributes (attributeType, inherit); } public override Type GetElementType() { return typeImpl.GetElementType (); } public override EventInfo GetEvent( string name, BindingFlags bindingAttr) { return typeImpl.GetEvent (name, bindingAttr); } public override EventInfo[] GetEvents() { return GetEvents (BindingFlags.Public); } public override EventInfo[] GetEvents (BindingFlags bindingAttr) { return typeImpl.GetEvents (bindingAttr); } public override FieldInfo GetField (string name, BindingFlags bindingAttr) { return typeImpl.GetField (name, bindingAttr); } public override FieldInfo[] GetFields( BindingFlags bindingAttr) { return typeImpl.GetFields (bindingAttr); } public override Type GetInterface( string name, bool ignoreCase) { return typeImpl.GetInterface (name, ignoreCase); } #if NET_2_0 [ComVisible (true)] #endif public override InterfaceMapping GetInterfaceMap( Type interfaceType) { return typeImpl.GetInterfaceMap (interfaceType); } public override Type[] GetInterfaces () { return typeImpl.GetInterfaces (); } public override MemberInfo[] GetMember( string name, MemberTypes type, BindingFlags bindingAttr) { return typeImpl.GetMember (name, type, bindingAttr); } public override MemberInfo[] GetMembers( BindingFlags bindingAttr) { return typeImpl.GetMembers (bindingAttr); } protected override MethodInfo GetMethodImpl( string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { // Can't call GetMethod since it makes restrictive argument checks return typeImpl.GetMethodImplInternal (name, bindingAttr, binder, callConvention, types, modifiers); } public override MethodInfo[] GetMethods( BindingFlags bindingAttr) { return typeImpl.GetMethods (bindingAttr); } public override Type GetNestedType( string name, BindingFlags bindingAttr) { return typeImpl.GetNestedType (name, bindingAttr); } public override Type[] GetNestedTypes( BindingFlags bindingAttr) { return typeImpl.GetNestedTypes (bindingAttr); } public override PropertyInfo[] GetProperties( BindingFlags bindingAttr) { return typeImpl.GetProperties (bindingAttr); } protected override PropertyInfo GetPropertyImpl( string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { // Can't call GetProperty since it makes restrictive argument checks return typeImpl.GetPropertyImplInternal (name, bindingAttr, binder, returnType, types, modifiers); } protected override bool HasElementTypeImpl() { return typeImpl.HasElementType; } public override object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { return typeImpl.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } protected override bool IsArrayImpl() { return typeImpl.IsArray; } protected override bool IsByRefImpl() { return typeImpl.IsByRef; } protected override bool IsCOMObjectImpl() { return typeImpl.IsCOMObject; } public override bool IsDefined( Type attributeType, bool inherit) { return typeImpl.IsDefined (attributeType, inherit); } protected override bool IsPointerImpl() { return typeImpl.IsPointer; } protected override bool IsPrimitiveImpl() { return typeImpl.IsPrimitive; } protected override bool IsValueTypeImpl() { return typeImpl.IsValueType; } #if NET_2_0 || BOOTSTRAP_NET_2_0 public override int MetadataToken { get { return typeImpl.MetadataToken; } } #endif } }
27.846442
202
0.716611
[ "MIT" ]
GrapeCity/pagefx
mono/mcs/class/corlib/System.Reflection/TypeDelegator.cs
7,435
C#
using System.Collections.Generic; namespace InstagramConnection.Entity { public class FacebookAccountData { public FacebookAccountData() { Data = new List<FacebookAccount>(); } public List<FacebookAccount> Data { get; set; } } public class FacebookAccount { public FacebookAccount() { } public string Id { get; set; } public string Name { get; set; } public InstagramAccount Instagram_business_account { get; set; } } }
17.073171
58
0.46
[ "MIT" ]
Freezer-Games/Frozen-Out
FrozenOut/Assets/Plugins/InstagramService/Entity/FacebookAccount.cs
702
C#
namespace PragmaticSegmenterNet.Tests.Unit.Languages { using Xunit; public class SpanishLanguageTests { [Fact] public void QuestionMarkToEndSentence001() { var result = Segmenter.Segment("¿Cómo está hoy? Espero que muy bien.", Language.Spanish); Assert.Equal(new[] { "¿Cómo está hoy?", "Espero que muy bien." }, result); } [Fact] public void ExclamationPointToEndSentence002() { var result = Segmenter.Segment("¡Hola señorita! Espero que muy bien.", Language.Spanish); Assert.Equal(new[] { "¡Hola señorita!", "Espero que muy bien." }, result); } [Fact] public void Abbreviations003() { var result = Segmenter.Segment("Hola Srta. Ledesma. Buenos días, soy el Lic. Naser Pastoriza, y él es mi padre, el Dr. Naser.", Language.Spanish); Assert.Equal(new[] { "Hola Srta. Ledesma.", "Buenos días, soy el Lic. Naser Pastoriza, y él es mi padre, el Dr. Naser." }, result); } [Fact] public void Numbers004() { var result = Segmenter.Segment("¡La casa cuesta $170.500.000,00! ¡Muy costosa! Se prevé una disminución del 12.5% para el próximo año.", Language.Spanish); Assert.Equal(new[] { "¡La casa cuesta $170.500.000,00!", "¡Muy costosa!", "Se prevé una disminución del 12.5% para el próximo año." }, result); } [Fact] public void Quotations005() { var result = Segmenter.Segment("«Ninguna mente extraordinaria está exenta de un toque de demencia.», dijo Aristóteles.", Language.Spanish); Assert.Equal(new[] { "«Ninguna mente extraordinaria está exenta de un toque de demencia.», dijo Aristóteles." }, result); } [Fact] public void CorrectlySegmentsText001() { var result = Segmenter.Segment("«Ninguna mente extraordinaria está exenta de un toque de demencia», dijo Aristóteles. Pablo, ¿adónde vas? ¡¿Qué viste?!", Language.Spanish); Assert.Equal(new[] { "«Ninguna mente extraordinaria está exenta de un toque de demencia», dijo Aristóteles.", "Pablo, ¿adónde vas?", "¡¿Qué viste?!" }, result); } [Fact] public void CorrectlySegmentsText002() { var result = Segmenter.Segment("Admón. es administración o me equivoco.", Language.Spanish); Assert.Equal(new[] { "Admón. es administración o me equivoco." }, result); } [Fact] public void CorrectlySegmentsText003() { var result = Segmenter.Segment("• 1. Busca atención prenatal desde el principio \n• 2. Aliméntate bien \n• 3. Presta mucha atención a la higiene de los alimentos \n• 4. Toma suplementos de ácido fólico y come pescado \n• 5. Haz ejercicio regularmente \n• 6. Comienza a hacer ejercicios de Kegel \n• 7. Restringe el consumo de alcohol \n• 8. Disminuye el consumo de cafeína \n• 9. Deja de fumar \n• 10. Descansa", Language.Spanish); Assert.Equal(new[] { "• 1. Busca atención prenatal desde el principio", "• 2. Aliméntate bien", "• 3. Presta mucha atención a la higiene de los alimentos", "• 4. Toma suplementos de ácido fólico y come pescado", "• 5. Haz ejercicio regularmente", "• 6. Comienza a hacer ejercicios de Kegel", "• 7. Restringe el consumo de alcohol", "• 8. Disminuye el consumo de cafeína", "• 9. Deja de fumar", "• 10. Descansa" }, result); } [Fact] public void CorrectlySegmentsText004() { var result = Segmenter.Segment("• 1. Busca atención prenatal desde el principio \n• 2. Aliméntate bien \n• 3. Presta mucha atención a la higiene de los alimentos \n• 4. Toma suplementos de ácido fólico y come pescado \n• 5. Haz ejercicio regularmente \n• 6. Comienza a hacer ejercicios de Kegel \n• 7. Restringe el consumo de alcohol \n• 8. Disminuye el consumo de cafeína \n• 9. Deja de fumar \n• 10. Descansa \n• 11. Hola", Language.Spanish); Assert.Equal(new[] { "• 1. Busca atención prenatal desde el principio", "• 2. Aliméntate bien", "• 3. Presta mucha atención a la higiene de los alimentos", "• 4. Toma suplementos de ácido fólico y come pescado", "• 5. Haz ejercicio regularmente", "• 6. Comienza a hacer ejercicios de Kegel", "• 7. Restringe el consumo de alcohol", "• 8. Disminuye el consumo de cafeína", "• 9. Deja de fumar", "• 10. Descansa", "• 11. Hola" }, result); } [Fact] public void CorrectlySegmentsText005() { var result = Segmenter.Segment("¡Hola Srta. Ledesma! ¿Cómo está hoy? Espero que muy bien.", Language.Spanish); Assert.Equal(new[] { "¡Hola Srta. Ledesma!", "¿Cómo está hoy?", "Espero que muy bien." }, result); } [Fact] public void CorrectlySegmentsText006() { var result = Segmenter.Segment("Buenos días, soy el Lic. Naser Pastoriza, y él es mi padre, el Dr. Naser.", Language.Spanish); Assert.Equal(new[] { "Buenos días, soy el Lic. Naser Pastoriza, y él es mi padre, el Dr. Naser." }, result); } [Fact] public void CorrectlySegmentsText007() { var result = Segmenter.Segment("He apuntado una cita para la siguiente fecha: Mar. 23 de Nov. de 2014. Gracias.", Language.Spanish); Assert.Equal(new[] { "He apuntado una cita para la siguiente fecha: Mar. 23 de Nov. de 2014.", "Gracias." }, result); } [Fact] public void CorrectlySegmentsText008() { var result = Segmenter.Segment("Núm. de tel: 351.123.465.4. Envíe mis saludos a la Sra. Rescia.", Language.Spanish); Assert.Equal(new[] { "Núm. de tel: 351.123.465.4.", "Envíe mis saludos a la Sra. Rescia." }, result); } [Fact] public void CorrectlySegmentsText009() { var result = Segmenter.Segment( "Cero en la escala Celsius o de grados centígrados (0 °C) se define como el equivalente a 273.15 K, con una diferencia de temperatura de 1 °C equivalente a una diferencia de 1 Kelvin. Esto significa que 100 °C, definido como el punto de ebullición del agua, se define como el equivalente a 373.15 K."); Assert.Equal(new[] { "Cero en la escala Celsius o de grados centígrados (0 °C) se define como el equivalente a 273.15 K, con una diferencia de temperatura de 1 °C equivalente a una diferencia de 1 Kelvin.", "Esto significa que 100 °C, definido como el punto de ebullición del agua, se define como el equivalente a 373.15 K." }, result); } [Fact] public void CorrectlySegmentsText010() { var result = Segmenter.Segment("Durante la primera misión del Discovery (30 Ago. 1984 15:08.10) tuvo lugar el lanzamiento de dos satélites de comunicación, el nombre de esta misión fue STS-41-D.", Language.Spanish); Assert.Equal(new[] { "Durante la primera misión del Discovery (30 Ago. 1984 15:08.10) tuvo lugar el lanzamiento de dos satélites de comunicación, el nombre de esta misión fue STS-41-D." }, result); } [Fact] public void CorrectlySegmentsText011() { var result = Segmenter.Segment("Frase del gran José Hernández: \"Aquí me pongo a cantar / al compás de la vigüela, / que el hombre que lo desvela / una pena estrordinaria, / como la ave solitaria / con el cantar se consuela. / [...] \".", Language.Spanish); Assert.Equal(new[] { "Frase del gran José Hernández: \"Aquí me pongo a cantar / al compás de la vigüela, / que el hombre que lo desvela / una pena estrordinaria, / como la ave solitaria / con el cantar se consuela. / [...] \"."}, result); } [Fact] public void CorrectlySegmentsText012() { var result = Segmenter.Segment("Citando a Criss Jami «Prefiero ser un artista a ser un líder, irónicamente, un líder tiene que seguir las reglas.», lo cual parece muy acertado.", Language.Spanish); Assert.Equal(new[] { "Citando a Criss Jami «Prefiero ser un artista a ser un líder, irónicamente, un líder tiene que seguir las reglas.», lo cual parece muy acertado." }, result); } [Fact] public void CorrectlySegmentsText013() { var result = Segmenter.Segment("Cuando llegué, le estaba dando ejercicios a los niños, uno de los cuales era \"3 + (14/7).x = 5\". ¿Qué te parece?", Language.Spanish); Assert.Equal(new[] { "Cuando llegué, le estaba dando ejercicios a los niños, uno de los cuales era \"3 + (14/7).x = 5\".", "¿Qué te parece?" }, result); } [Fact] public void CorrectlySegmentsText014() { var result = Segmenter.Segment("Se le pidió a los niños que leyeran los párrf. 5 y 6 del art. 4 de la constitución de los EE. UU..", Language.Spanish); Assert.Equal(new[] { "Se le pidió a los niños que leyeran los párrf. 5 y 6 del art. 4 de la constitución de los EE. UU.." }, result); } [Fact] public void CorrectlySegmentsText015() { var result = Segmenter.Segment("Una de las preguntas realizadas en la evaluación del día Lun. 15 de Mar. fue la siguiente: \"Alumnos, ¿cuál es el resultado de la operación 1.1 + 4/5?\". Disponían de 1 min. para responder esa pregunta.", Language.Spanish); Assert.Equal(new[] { "Una de las preguntas realizadas en la evaluación del día Lun. 15 de Mar. fue la siguiente: \"Alumnos, ¿cuál es el resultado de la operación 1.1 + 4/5?\".", "Disponían de 1 min. para responder esa pregunta." }, result); } [Fact] public void CorrectlySegmentsText016() { var result = Segmenter.Segment("La temperatura del motor alcanzó los 120.5°C. Afortunadamente, pudo llegar al final de carrera.", Language.Spanish); Assert.Equal(new[] { "La temperatura del motor alcanzó los 120.5°C.", "Afortunadamente, pudo llegar al final de carrera." }, result); } [Fact] public void CorrectlySegmentsText017() { var result = Segmenter.Segment("El volumen del cuerpo es 3m³. ¿Cuál es la superficie de cada cara del prisma?", Language.Spanish); Assert.Equal(new[] { "El volumen del cuerpo es 3m³.", "¿Cuál es la superficie de cada cara del prisma?" }, result); } [Fact] public void CorrectlySegmentsText018() { var result = Segmenter.Segment("La habitación tiene 20.55m². El living tiene 50.0m².", Language.Spanish); Assert.Equal(new[] { "La habitación tiene 20.55m².", "El living tiene 50.0m²." }, result); } [Fact] public void CorrectlySegmentsText019() { var result = Segmenter.Segment("1°C corresponde a 33.8°F. ¿A cuánto corresponde 35°C?", Language.Spanish); Assert.Equal(new[] { "1°C corresponde a 33.8°F.", "¿A cuánto corresponde 35°C?" }, result); } [Fact] public void CorrectlySegmentsText020() { var result = Segmenter.Segment("Hamilton ganó el último gran premio de Fórmula 1, luego de 1:39:02.619 Hs. de carrera, segundo resultó Massa, a una diferencia de 2.5 segundos. De esta manera se consagró ¡Campeón mundial!", Language.Spanish); Assert.Equal(new[] { "Hamilton ganó el último gran premio de Fórmula 1, luego de 1:39:02.619 Hs. de carrera, segundo resultó Massa, a una diferencia de 2.5 segundos.", "De esta manera se consagró ¡Campeón mundial!" }, result); } [Fact] public void CorrectlySegmentsText021() { var result = Segmenter.Segment("¡La casa cuesta $170.500.000,00! ¡Muy costosa! Se prevé una disminución del 12.5% para el próximo año.", Language.Spanish); Assert.Equal(new[] { "¡La casa cuesta $170.500.000,00!", "¡Muy costosa!", "Se prevé una disminución del 12.5% para el próximo año." }, result); } [Fact] public void CorrectlySegmentsText022() { var result = Segmenter.Segment("El corredor No. 103 arrivó 4°.", Language.Spanish); Assert.Equal(new[] { "El corredor No. 103 arrivó 4°." }, result); } [Fact] public void CorrectlySegmentsText023() { var result = Segmenter.Segment("Hoy es 27/04/2014, y es mi cumpleaños. ¿Cuándo es el tuyo?", Language.Spanish); Assert.Equal(new[] { "Hoy es 27/04/2014, y es mi cumpleaños.", "¿Cuándo es el tuyo?" }, result); } [Fact] public void CorrectlySegmentsText024() { var result = Segmenter.Segment("Aquí está la lista de compras para el almuerzo: 1.Helado, 2.Carne, 3.Arroz. ¿Cuánto costará? Quizás $12.5.", Language.Spanish); Assert.Equal(new[] { "Aquí está la lista de compras para el almuerzo: 1. Helado, 2. Carne, 3. Arroz.", "¿Cuánto costará?", "Quizás $12.5." }, result); } [Fact] public void CorrectlySegmentsText025() { var result = Segmenter.Segment("1 + 1 es 2. 2 + 2 es 4. El auto es de color rojo.", Language.Spanish); Assert.Equal(new[] { "1 + 1 es 2.", "2 + 2 es 4.", "El auto es de color rojo." }, result); } [Fact] public void CorrectlySegmentsText026() { var result = Segmenter.Segment("La máquina viajaba a 100 km/h. ¿En cuánto tiempo recorrió los 153 Km.?", Language.Spanish); Assert.Equal(new[] { "La máquina viajaba a 100 km/h.", "¿En cuánto tiempo recorrió los 153 Km.?" }, result); } [Fact] public void CorrectlySegmentsText027() { var result = Segmenter.Segment( "\n \nCentro de Relaciones Interinstitucionales -CERI \n\nCra. 7 No. 40-53 Piso 10 Tel. (57-1) 3239300 Ext. 1010 Fax: (57-1) 3402973 Bogotá, D.C. - Colombia \n\nhttp://www.udistrital.edu.co - http://ceri.udistrital.edu.co - [email protected] \n\n \n\nCERI 0908 \n \nBogotá, D.C. 6 de noviembre de 2014. \n \nSeñores: \nEMBAJADA DE UNITED KINGDOM \n \n", Language.Spanish); Assert.Equal(new[] { "Centro de Relaciones Interinstitucionales -CERI", "Cra. 7 No. 40-53 Piso 10 Tel. (57-1) 3239300 Ext. 1010 Fax: (57-1) 3402973 Bogotá, D.C. - Colombia", "http://www.udistrital.edu.co - http://ceri.udistrital.edu.co - [email protected]", "CERI 0908", "Bogotá, D.C. 6 de noviembre de 2014.", "Señores:", "EMBAJADA DE UNITED KINGDOM" }, result); } [Fact] public void CorrectlySegmentsText028() { var result = Segmenter.Segment("N°. 1026.253.553", Language.Spanish); Assert.Equal(new[] { "N°. 1026.253.553" }, result); } [Fact] public void CorrectlySegmentsText029() { var result = Segmenter.Segment("\nA continuación me permito presentar a la Ingeniera LAURA MILENA LEÓN \nSANDOVAL, identificada con el documento N°. 1026.253.553 de Bogotá, \negresada del Programa Ingeniería Industrial en el año 2012, quien se desatacó por \nsu excelencia académica, actualmente cursa el programa de Maestría en \nIngeniería Industrial y se encuentra en un intercambio cultural en Bangalore – \nIndia.", Language.Spanish, documentType: DocumentType.Pdf); Assert.Equal(new[] { "A continuación me permito presentar a la Ingeniera LAURA MILENA LEÓN SANDOVAL, identificada con el documento N°. 1026.253.553 de Bogotá, egresada del Programa Ingeniería Industrial en el año 2012, quien se desatacó por su excelencia académica, actualmente cursa el programa de Maestría en Ingeniería Industrial y se encuentra en un intercambio cultural en Bangalore – India." }, result); } [Fact] public void CorrectlySegmentsText030() { var result = Segmenter.Segment("\n__________________________________________________________\nEl Board para Servicios Educativos de Putnam/Northern Westchester según el título IX, Sección 504 del “Rehabilitation Act” del 1973, del Título VII y del Acta “American with Disabilities” no discrimina para la admisión a programas educativos por sexo, creencia, nacionalidad, origen, edad o discapacidad.", Language.Spanish); Assert.Equal(new[] { "El Board para Servicios Educativos de Putnam/Northern Westchester según el título IX, Sección 504 del “Rehabilitation Act” del 1973, del Título VII y del Acta “American with Disabilities” no discrimina para la admisión a programas educativos por sexo, creencia, nacionalidad, origen, edad o discapacidad." }, result); } [Fact] public void CorrectlySegmentsText031() { var result = Segmenter.Segment("Explora oportunidades de carrera en el área de Salud en el Hospital de Northern en Mt. Kisco.", Language.Spanish); Assert.Equal(new[] { "Explora oportunidades de carrera en el área de Salud en el Hospital de Northern en Mt. Kisco." }, result); } } }
64.424242
483
0.642639
[ "MIT" ]
EliotJones/PragmaticSegmenterNet
PragmaticSegmenterNet.Tests.Unit/Languages/SpanishLanguageTests.cs
17,398
C#
using System.Threading; using System.Threading.Tasks; using Credfeto.Notification.Bot.Twitch.Actions; using Credfeto.Notification.Bot.Twitch.DataTypes; using Credfeto.Notification.Bot.Twitch.Models; using Credfeto.Notification.Bot.Twitch.Publishers; using FunFair.Test.Common; using MediatR; using NSubstitute; using Xunit; namespace Credfeto.Notification.Bot.Twitch.Tests.Publishers; public sealed class TwitchGiftSubSingleNotificationHandlerTests : TestBase { private static readonly Streamer Streamer = Streamer.FromString(nameof(Streamer)); private static readonly Viewer GiftedBy = Viewer.FromString(nameof(GiftedBy)); private readonly IContributionThanks _contributionThanks; private readonly INotificationHandler<TwitchGiftSubSingle> _notificationHandler; public TwitchGiftSubSingleNotificationHandlerTests() { this._contributionThanks = GetSubstitute<IContributionThanks>(); this._notificationHandler = new TwitchGiftSubSingleNotificationHandler(contributionThanks: this._contributionThanks, this.GetTypedLogger<TwitchGiftSubSingleNotificationHandler>()); } [Fact] public async Task HandleAsync() { await this._notificationHandler.Handle(new(streamer: Streamer, user: GiftedBy), cancellationToken: CancellationToken.None); await this.ThankForGiftingSubAsync(); } private Task ThankForGiftingSubAsync() { return this._contributionThanks.Received(1) .ThankForGiftingSubAsync(streamer: Streamer, giftedBy: GiftedBy, Arg.Any<CancellationToken>()); } }
38.463415
188
0.784401
[ "MIT" ]
credfeto/notification-bot
src/Credfeto.Notification.Bot.Twitch.Tests/Publishers/TwitchGiftSubSingleNotificationHandlerTests.cs
1,577
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace Cvl.VirtualMachine.Debugger { /// <summary> /// Logika interakcji dla klasy App.xaml /// </summary> public partial class App : Application { } }
19.277778
44
0.714697
[ "MIT" ]
cv-lang/virtual-machine
Cvl.VirtualMachine/Cvl.VirtualMachine.Debugger/App.xaml.cs
349
C#
using System; using System.Diagnostics; namespace ImageResizer.Configuration.Performance { /// <summary> /// 4 overlapping windows are used /// </summary> class PerIntervalSampling { readonly CircularTimeBuffer[] rings; readonly long[] offsets; const int RingCount = 4; readonly Action<long> resultCallback; readonly Func<long> getTimestampNow; public NamedInterval Interval { get; } readonly long intervalTicks; public PerIntervalSampling(NamedInterval interval, Action<long> resultCallback, Func<long> getTimestampNow) { this.Interval = interval; this.intervalTicks = interval.TicksDuration; this.getTimestampNow = getTimestampNow; offsets = new long[RingCount]; rings = new CircularTimeBuffer[RingCount]; this.resultCallback = resultCallback; // 3 seconds minimum to permit delayed reporting var buckets = (int)Math.Max(2, Stopwatch.Frequency * 3 / intervalTicks); for (var ix = 0; ix < RingCount; ix++) { var offset = (long)Math.Round(ix * 0.1 * intervalTicks); offsets[ix] = offset; rings[ix] = new CircularTimeBuffer(intervalTicks, buckets); } } public void FireCallbackEvents() { for (var ix = 0; ix < RingCount; ix++) { foreach(var result in rings[ix].DequeueValues()) { resultCallback(result); } } } public bool Record(long timestamp, long count) { if (timestamp - intervalTicks > this.getTimestampNow()) { return false; //Too far future, would break current values } var success = true; for (var ix = 0; ix < RingCount; ix++) { if (!rings[ix].Record(timestamp + offsets[ix], count)) { success = false; } } FireCallbackEvents(); return success; } } }
30.136986
115
0.532273
[ "MIT" ]
2sic/resizer
Core/Configuration/Performance/Support/RateTracking/PerIntervalSampling.cs
2,202
C#